/*! 
  Ripple Mobile Environment Emulator v0.9.8 :: Built On Wed Oct 23 2013 20:24:42 GMT+0800 (CST)

                                Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   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.

-------------------------------------------------------
Copyright 2011 Research In Motion Limited.

Contributors:
        Brent Lintner (blintner@rim.com)
        Dan Silivestru (dsilivestru@rim.com)
        Gord Tanner (gtanner@rim.com)
        Nino D'Aversa (ndaversa@rim.com)
        Nukul Bhasin (nbhasin@rim.com)

-------------------------------------------------------
--> Kudos to third party awesomeness:

* browser-require *

https://github.com/rsms/browser-require

The MIT License
http://www.opensource.org/licenses/mit-license.php
Copyright (c) 2010 Rasmus Andersson http://hunch.se/

-------------------------------------------------------
* jWorkflow *

http://github.com/tinyhippos/jWorkflow/

The MIT License
http://www.opensource.org/licenses/mit-license.php
Copyright (c) 2010 all contributors:
Gord Tanner

-------------------------------------------------------
* jXHR.js (JSON-P XHR) *
 v0.1 (c) Kyle Simpson 
 MIT License

-------------------------------------------------------
* UI.Acceleromter Control (panel plugin) *

Licensed under the MIT license:
  Copyright Train Hack 2010
  Contributors: Wolfram Kriesing, Dan Silivestru, Brent Lintner
  http://www.opensource.org/licenses/mit-license.php

-------------------------------------------------------
* jQuery JavaScript Library *

http://jquery.com/

Copyright 2010, John Resig
Licensed under MIT
http://jquery.org/license

Includes Sizzle.js
http://sizzlejs.com/
Copyright 2010, The Dojo Foundation
Released under the MIT, BSD, and GPL Licenses.

-------------------------------------------------------
* jQuery UI *

Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
licensed under the MIT (MIT-LICENSE.txt)

http://docs.jquery.com/UI

-------------------------------------------------------
* jQuery Tooltip plugin *

http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
http://docs.jquery.com/Plugins/Tooltip

Copyright (c) 2006 - 2008 Jörn Zaefferer

Dual licensed under the MIT and GPL licenses:
  http://www.opensource.org/licenses/mit-license.php
  http://www.gnu.org/licenses/gpl.html

-------------------------------------------------------
* Math.uuid.js (v1.4) *

http://www.broofa.com
mailto:robert@broofa.com

Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.

-------------------------------------------------------
* Wii Opera SDK - 3D Math Class v2.7.22 2008-12-14 *
(c) 2007-2008 Daniel Gump. All Rights Reserved.                          
 http://wiioperasdk.com, http://hullbreachonline.com                      
 hullbreach@hullbreachonline.com                                          
                                                                          
* Wii Opera SDK - Drawing Class v2.6.16 2008-12-14 * 
(c) 2007-2008 Daniel Gump. All Rights Reserved
http://wiioperasdk.com, http://hullbreachonline.com
hullbreach@hullbreachonline.com

  Wii is a trademark of Nintendo Co., Ltd.                                
  Opera is a trademark of Opera, ASA.                                     
  This software package is not associated with either company             
  but was created to support users of both.  Its alternative name         
  when supporting other products is the HULLBREACH SDK.                   
                                                                          
  Redistribution and use in source and binary forms, with or without      
  modification, are permitted provided that the following conditions      
  are met:                                                                
    * Redistributions of source code must retain the above copyright      
      notice, this list of conditions and the following disclaimer.       
    * Redistributions in binary form must reproduce the above copyright   
      notice, this list of conditions and the following disclaimer in     
      the documentation and/or other materials provided with the          
      distribution.                                                       
    * Neither the names HULLBREACH ONLINE nor WII OPERA SDK nor the names 
      of its contributors may be used to endorse or promote products      
      derived from this software without specific prior written           
      permission.                                                         
    * If the explicit purpose of the software is not to support the       
      Nintendo Wii or the Opera Web browser, then the names of such must  
      not be used in any derived product. The name shall be the           
      HULLBREACH SDK with a reference link to http://hullbreachonline.    
                                                                          
  THIS SOFTWARE IS PROVIDED BY Daniel Gump ''AS IS'' AND ANY EXPRESS OR   
  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED          
  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE  
  DISCLAIMED. IN NO EVENT SHALL Daniel Gump BE LIABLE FOR ANY DIRECT,     
  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES      
  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR      
  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)      
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,     
  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING   
  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE      
  POSSIBILITY OF SUCH DAMAGE.                                             

-------------------------------------------------------
  OpenLayers.js -- OpenLayers Map Viewer Library

  Copyright 2005-2010 OpenLayers Contributors, released under the Clear BSD
  license. Full license text below taken from http://svn.openlayers.org/trunk/openlayers/license.txt

        Copyright 2005-2011 OpenLayers Contributors. All rights reserved. See
        authors.txt for full list.
         
        Redistribution and use in source and binary forms, with or without modification,
        are permitted provided that the following conditions are met:
         
        1. Redistributions of source code must retain the above copyright notice, this
        list of conditions and the following disclaimer.
         
        2. Redistributions in binary form must reproduce the above copyright notice,
        this list of conditions and the following disclaimer in the documentation and/or
        other materials provided with the distribution.
         
        THIS SOFTWARE IS PROVIDED BY OPENLAYERS CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
        OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
        MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
        SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
        INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
        PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
        LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
        OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
        ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
        The views and conclusions contained in the software and documentation are those
        of the authors and should not be interpreted as representing official policies,
        either expressed or implied, of OpenLayers Contributors.

  Includes compressed code under the following licenses:

  (For uncompressed versions of the code used please see the
  OpenLayers SVN repository: <http://openlayers.org/>)

-------------------------------------------------------
  Contains portions of Rico <http://openrico.org/>
 
  Copyright 2005 Sabre Airline Solutions  
  
  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 the top of this file or a the following
  link:
  
         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. 

-------------------------------------------------------
  Contains XMLHttpRequest.js <http://code.google.com/p/xmlhttprequest/>
  Copyright 2007 Sergey Ilinsky (http://www.ilinsky.com)
 
  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

-------------------------------------------------------
  Contains portions of Gears <http://code.google.com/apis/gears/>

  Copyright 2007, Google Inc.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
   3. Neither the name of Google Inc. nor the names of its contributors may be
      used to endorse or promote products derived from this software without
      specific prior written permission.
 
  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
  Sets up google.gears.*, which is *the only* supported way to access Gears.

  Circumvent this file at your own risk!
 
  In the future, Gears may automatically define google.gears.* without this
  file. Gears may use these objects to transparently fix bugs and compatibility
  issues. Applications that use the code below will continue to work seamlessly
  when that happens.
*/
window.require = null;window.define = null;/**
 * almond 0.0.3 Copyright (c) 2011, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/jrburke/almond for details
 */
/*jslint strict: false, plusplus: false */
/*global setTimeout: false */

var requirejs, require, define;
(function (undef) {

    var defined = {},
        waiting = {},
        aps = [].slice,
        main, req;

    if (typeof define === "function") {
        //If a define is already in play via another AMD loader,
        //do not overwrite.
        return;
    }

    /**
     * Given a relative module name, like ./something, normalize it to
     * a real name that can be mapped to a path.
     * @param {String} name the relative name
     * @param {String} baseName a real name that the name arg is relative
     * to.
     * @returns {String} normalized name
     */
    function normalize(name, baseName) {
        //Adjust any relative paths.
        if (name && name.charAt(0) === ".") {
            //If have a base name, try to normalize against it,
            //otherwise, assume it is a top-level require that will
            //be relative to baseUrl in the end.
            if (baseName) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that "directory" and not name of the baseName's
                //module. For instance, baseName of "one/two/three", maps to
                //"one/two/three.js", but we want the directory, "one/two" for
                //this normalization.
                baseName = baseName.split("/");
                baseName = baseName.slice(0, baseName.length - 1);

                name = baseName.concat(name.split("/"));

                //start trimDots
                var i, part;
                for (i = 0; (part = name[i]); i++) {
                    if (part === ".") {
                        name.splice(i, 1);
                        i -= 1;
                    } else if (part === "..") {
                        if (i === 1 && (name[2] === '..' || name[0] === '..')) {
                            //End of the line. Keep at least one non-dot
                            //path segment at the front so it can be mapped
                            //correctly to disk. Otherwise, there is likely
                            //no path mapping for a path starting with '..'.
                            //This can still fail, but catches the most reasonable
                            //uses of ..
                            break;
                        } else if (i > 0) {
                            name.splice(i - 1, 2);
                            i -= 2;
                        }
                    }
                }
                //end trimDots

                name = name.join("/");
            }
        }
        return name;
    }

    function makeRequire(relName, forceSync) {
        return function () {
            //A version of a require function that passes a moduleName
            //value for items that may need to
            //look up paths relative to the moduleName
            return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync]));
        };
    }

    function makeNormalize(relName) {
        return function (name) {
            return normalize(name, relName);
        };
    }

    function makeLoad(depName) {
        return function (value) {
            defined[depName] = value;
        };
    }

    function callDep(name) {
        if (waiting.hasOwnProperty(name)) {
            var args = waiting[name];
            delete waiting[name];
            main.apply(undef, args);
        }
        return defined[name];
    }

    /**
     * Makes a name map, normalizing the name, and using a plugin
     * for normalization if necessary. Grabs a ref to plugin
     * too, as an optimization.
     */
    function makeMap(name, relName) {
        var prefix, plugin,
            index = name.indexOf('!');

        if (index !== -1) {
            prefix = normalize(name.slice(0, index), relName);
            name = name.slice(index + 1);
            plugin = callDep(prefix);

            //Normalize according
            if (plugin && plugin.normalize) {
                name = plugin.normalize(name, makeNormalize(relName));
            } else {
                name = normalize(name, relName);
            }
        } else {
            name = normalize(name, relName);
        }

        //Using ridiculous property names for space reasons
        return {
            f: prefix ? prefix + '!' + name : name, //fullName
            n: name,
            p: plugin
        };
    }

    main = function (name, deps, callback, relName) {
        var args = [],
            usingExports,
            cjsModule, depName, i, ret, map;

        //Use name if no relName
        if (!relName) {
            relName = name;
        }

        //Call the callback to define the module, if necessary.
        if (typeof callback === 'function') {

            //Default to require, exports, module if no deps if
            //the factory arg has any arguments specified.
            if (!deps.length && callback.length) {
                deps = ['require', 'exports', 'module'];
            }

            //Pull out the defined dependencies and pass the ordered
            //values to the callback.
            for (i = 0; i < deps.length; i++) {
                map = makeMap(deps[i], relName);
                depName = map.f;

                //Fast path CommonJS standard dependencies.
                if (depName === "require") {
                    args[i] = makeRequire(name);
                } else if (depName === "exports") {
                    //CommonJS module spec 1.1
                    args[i] = defined[name] = {};
                    usingExports = true;
                } else if (depName === "module") {
                    //CommonJS module spec 1.1
                    cjsModule = args[i] = {
                        id: name,
                        uri: '',
                        exports: defined[name]
                    };
                } else if (defined.hasOwnProperty(depName) || waiting.hasOwnProperty(depName)) {
                    args[i] = callDep(depName);
                } else if (map.p) {
                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                    args[i] = defined[depName];
                } else {
                    throw name + ' missing ' + depName;
                }
            }

            ret = callback.apply(defined[name], args);

            if (name) {
                //If setting exports via "module" is in play,
                //favor that over return value and exports. After that,
                //favor a non-undefined return value over exports use.
                if (cjsModule && cjsModule.exports !== undef) {
                    defined[name] = cjsModule.exports;
                } else if (!usingExports) {
                    //Use the return value from the function.
                    defined[name] = ret;
                }
            }
        } else if (name) {
            //May just be an object definition for the module. Only
            //worry about defining if have a module name.
            defined[name] = callback;
        }
    };

    requirejs = req = function (deps, callback, relName, forceSync) {
        if (typeof deps === "string") {

            //Just return the module wanted. In this scenario, the
            //deps arg is the module name, and second arg (if passed)
            //is just the relName.
            //Normalize module name, if it contains . or ..
            return callDep(makeMap(deps, callback).f);
        } else if (!deps.splice) {
            //deps is a config object, not an array.
            //Drop the config stuff on the ground.
            if (callback.splice) {
                //callback is an array, which means it is a dependency list.
                //Adjust args if there are dependencies
                deps = callback;
                callback = arguments[2];
            } else {
                deps = [];
            }
        }

        //Simulate async callback;
        if (forceSync) {
            main(undef, deps, callback, relName);
        } else {
            setTimeout(function () {
                main(undef, deps, callback, relName);
            }, 15);
        }

        return req;
    };

    /**
     * Just drops the config on the floor, but returns req in case
     * the config return value is used.
     */
    req.config = function () {
        return req;
    };

    /**
     * Export require as a global, but only if it does not already exist.
     */
    if (!require) {
        require = req;
    }

    define = function (name, deps, callback) {

        //This module may not have dependencies
        if (!deps.splice) {
            //deps is not an array, so probably means
            //an object literal or factory function for
            //the value. Adjust args.
            callback = deps;
            deps = [];
        }

        if (define.unordered) {
            waiting[name] = [name, deps, callback];
        } else {
            main(name, deps, callback);
        }
    };

    define.amd = {
        jQuery: true
    };
}());
/*!
 * jQuery JavaScript Library v1.6
 * http://jquery.com/
 *
 * Copyright 2011, John Resig
 * licensed under the MIT 
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2011, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Mon May 2 13:50:00 2011 -0400
 */
(function( window, undefined ) {

// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
	navigator = window.navigator,
	location = window.location;
var jQuery = (function() {

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
		// The jQuery object is actually just the init constructor 'enhanced'
		return new jQuery.fn.init( selector, context, rootjQuery );
	},

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$,

	// A central reference to the root jQuery(document)
	rootjQuery,

	// A simple way to check for HTML strings or ID strings
	// (both of which we optimize for)
	quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,

	// Check if a string has a non-whitespace character in it
	rnotwhite = /\S/,

	// Used for trimming whitespace
	trimLeft = /^\s+/,
	trimRight = /\s+$/,

	// Check for digits
	rdigit = /\d/,

	// Match a standalone tag
	rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,

	// JSON RegExp
	rvalidchars = /^[\],:{}\s]*$/,
	rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
	rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
	rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,

	// Useragent RegExp
	rwebkit = /(webkit)[ \/]([\w.]+)/,
	ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
	rmsie = /(msie) ([\w.]+)/,
	rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,

	// Keep a UserAgent string for use with jQuery.browser
	userAgent = navigator.userAgent,

	// For matching the engine and version of the browser
	browserMatch,

	// The deferred used on DOM ready
	readyList,

	// The ready event handler
	DOMContentLoaded,

	// Save a reference to some core methods
	toString = Object.prototype.toString,
	hasOwn = Object.prototype.hasOwnProperty,
	push = Array.prototype.push,
	slice = Array.prototype.slice,
	trim = String.prototype.trim,
	indexOf = Array.prototype.indexOf,

	// [[Class]] -> type pairs
	class2type = {};

jQuery.fn = jQuery.prototype = {
	constructor: jQuery,
	init: function( selector, context, rootjQuery ) {
		var match, elem, ret, doc;

		// Handle $(""), $(null), or $(undefined)
		if ( !selector ) {
			return this;
		}

		// Handle $(DOMElement)
		if ( selector.nodeType ) {
			this.context = this[0] = selector;
			this.length = 1;
			return this;
		}

		// The body element only exists once, optimize finding it
		if ( selector === "body" && !context && document.body ) {
			this.context = document;
			this[0] = document.body;
			this.selector = selector;
			this.length = 1;
			return this;
		}

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			// Are we dealing with HTML string or an ID?
			if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = quickExpr.exec( selector );
			}

			// Verify a match, and that no context was specified for #id
			if ( match && (match[1] || !context) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[1] ) {
					context = context instanceof jQuery ? context[0] : context;
					doc = (context ? context.ownerDocument || context : document);

					// If a single string is passed in and it's a single tag
					// just do a createElement and skip the rest
					ret = rsingleTag.exec( selector );

					if ( ret ) {
						if ( jQuery.isPlainObject( context ) ) {
							selector = [ document.createElement( ret[1] ) ];
							jQuery.fn.attr.call( selector, context, true );

						} else {
							selector = [ doc.createElement( ret[1] ) ];
						}

					} else {
						ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
						selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes;
					}

					return jQuery.merge( this, selector );

				// HANDLE: $("#id")
				} else {
					elem = document.getElementById( match[2] );

					// Check parentNode to catch when Blackberry 4.6 returns
					// nodes that are no longer in the document #6963
					if ( elem && elem.parentNode ) {
						// Handle the case where IE and Opera return items
						// by name instead of ID
						if ( elem.id !== match[2] ) {
							return rootjQuery.find( selector );
						}

						// Otherwise, we inject the element directly into the jQuery object
						this.length = 1;
						this[0] = elem;
					}

					this.context = document;
					this.selector = selector;
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return (context || rootjQuery).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) ) {
			return rootjQuery.ready( selector );
		}

		if (selector.selector !== undefined) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

		return jQuery.makeArray( selector, this );
	},

	// Start with an empty selector
	selector: "",

	// The current version of jQuery being used
	jquery: "1.6",

	// The default length of a jQuery object is 0
	length: 0,

	// The number of elements contained in the matched element set
	size: function() {
		return this.length;
	},

	toArray: function() {
		return slice.call( this, 0 );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num == null ?

			// Return a 'clean' array
			this.toArray() :

			// Return just the object
			( num < 0 ? this[ this.length + num ] : this[ num ] );
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems, name, selector ) {
		// Build a new jQuery matched element set
		var ret = this.constructor();

		if ( jQuery.isArray( elems ) ) {
			push.apply( ret, elems );

		} else {
			jQuery.merge( ret, elems );
		}

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		ret.context = this.context;

		if ( name === "find" ) {
			ret.selector = this.selector + (this.selector ? " " : "") + selector;
		} else if ( name ) {
			ret.selector = this.selector + "." + name + "(" + selector + ")";
		}

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	// (You can seed the arguments with an array of args, but this is
	// only used internally.)
	each: function( callback, args ) {
		return jQuery.each( this, callback, args );
	},

	ready: function( fn ) {
		// Attach the listeners
		jQuery.bindReady();

		// Add the callback
		readyList.done( fn );

		return this;
	},

	eq: function( i ) {
		return i === -1 ?
			this.slice( i ) :
			this.slice( i, +i + 1 );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ),
			"slice", slice.call(arguments).join(",") );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map(this, function( elem, i ) {
			return callback.call( elem, i, elem );
		}));
	},

	end: function() {
		return this.prevObject || this.constructor(null);
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: [].sort,
	splice: [].splice
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[0] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;
		target = arguments[1] || {};
		// skip the boolean and the target
		i = 2;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
		target = {};
	}

	// extend jQuery itself if only one argument is passed
	if ( length === i ) {
		target = this;
		--i;
	}

	for ( ; i < length; i++ ) {
		// Only deal with non-null/undefined values
		if ( (options = arguments[ i ]) != null ) {
			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray(src) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject(src) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend({
	noConflict: function( deep ) {
		if ( window.$ === jQuery ) {
			window.$ = _$;
		}

		if ( deep && window.jQuery === jQuery ) {
			window.jQuery = _jQuery;
		}

		return jQuery;
	},

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,

	// Hold (or release) the ready event
	holdReady: function( hold ) {
		if ( hold ) {
			jQuery.readyWait++;
		} else {
			jQuery.ready( true );
		}
	},

	// Handle when the DOM is ready
	ready: function( wait ) {
		// Either a released hold or an DOMready/load event and not yet ready
		if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
			// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
			if ( !document.body ) {
				return setTimeout( jQuery.ready, 1 );
			}

			// Remember that the DOM is ready
			jQuery.isReady = true;

			// If a normal DOM Ready event fired, decrement, and wait if need be
			if ( wait !== true && --jQuery.readyWait > 0 ) {
				return;
			}

			// If there are functions bound, to execute
			readyList.resolveWith( document, [ jQuery ] );

			// Trigger any bound ready events
			if ( jQuery.fn.trigger ) {
				jQuery( document ).trigger( "ready" ).unbind( "ready" );
			}
		}
	},

	bindReady: function() {
		if ( readyList ) {
			return;
		}

		readyList = jQuery._Deferred();

		// Catch cases where $(document).ready() is called after the
		// browser event has already occurred.
		if ( document.readyState === "complete" ) {
			// Handle it asynchronously to allow scripts the opportunity to delay ready
			return setTimeout( jQuery.ready, 1 );
		}

		// Mozilla, Opera and webkit nightlies currently support this event
		if ( document.addEventListener ) {
			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

			// A fallback to window.onload, that will always work
			window.addEventListener( "load", jQuery.ready, false );

		// If IE event model is used
		} else if ( document.attachEvent ) {
			// ensure firing before onload,
			// maybe late but safe also for iframes
			document.attachEvent( "onreadystatechange", DOMContentLoaded );

			// A fallback to window.onload, that will always work
			window.attachEvent( "onload", jQuery.ready );

			// If IE and not a frame
			// continually check to see if the document is ready
			var toplevel = false;

			try {
				toplevel = window.frameElement == null;
			} catch(e) {}

			if ( document.documentElement.doScroll && toplevel ) {
				doScrollCheck();
			}
		}
	},

	// See test/unit/core.js for details concerning isFunction.
	// Since version 1.3, DOM methods and functions like alert
	// aren't supported. They return false on IE (#2968).
	isFunction: function( obj ) {
		return jQuery.type(obj) === "function";
	},

	isArray: Array.isArray || function( obj ) {
		return jQuery.type(obj) === "array";
	},

	// A crude way of determining if an object is a window
	isWindow: function( obj ) {
		return obj && typeof obj === "object" && "setInterval" in obj;
	},

	isNaN: function( obj ) {
		return obj == null || !rdigit.test( obj ) || isNaN( obj );
	},

	type: function( obj ) {
		return obj == null ?
			String( obj ) :
			class2type[ toString.call(obj) ] || "object";
	},

	isPlainObject: function( obj ) {
		// Must be an Object.
		// Because of IE, we also have to check the presence of the constructor property.
		// Make sure that DOM nodes and window objects don't pass through, as well
		if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}

		// Not own constructor property must be Object
		if ( obj.constructor &&
			!hasOwn.call(obj, "constructor") &&
			!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
			return false;
		}

		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own.

		var key;
		for ( key in obj ) {}

		return key === undefined || hasOwn.call( obj, key );
	},

	isEmptyObject: function( obj ) {
		for ( var name in obj ) {
			return false;
		}
		return true;
	},

	error: function( msg ) {
		throw msg;
	},

	parseJSON: function( data ) {
		if ( typeof data !== "string" || !data ) {
			return null;
		}

		// Make sure leading/trailing whitespace is removed (IE can't handle it)
		data = jQuery.trim( data );

		// Attempt to parse using the native JSON parser first
		if ( window.JSON && window.JSON.parse ) {
			return window.JSON.parse( data );
		}

		// Make sure the incoming data is actual JSON
		// Logic borrowed from http://json.org/json2.js
		if ( rvalidchars.test( data.replace( rvalidescape, "@" )
			.replace( rvalidtokens, "]" )
			.replace( rvalidbraces, "")) ) {

			return (new Function( "return " + data ))();

		}
		jQuery.error( "Invalid JSON: " + data );
	},

	// Cross-browser xml parsing
	// (xml & tmp used internally)
	parseXML: function( data , xml , tmp ) {

		if ( window.DOMParser ) { // Standard
			tmp = new DOMParser();
			xml = tmp.parseFromString( data , "text/xml" );
		} else { // IE
			xml = new ActiveXObject( "Microsoft.XMLDOM" );
			xml.async = "false";
			xml.loadXML( data );
		}

		tmp = xml.documentElement;

		if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) {
			jQuery.error( "Invalid XML: " + data );
		}

		return xml;
	},

	noop: function() {},

	// Evaluates a script in a global context
	// Workarounds based on findings by Jim Driscoll
	// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
	globalEval: function( data ) {
		if ( data && rnotwhite.test( data ) ) {
			// We use execScript on Internet Explorer
			// We use an anonymous function so that context is window
			// rather than jQuery in Firefox
			( window.execScript || function( data ) {
				window[ "eval" ].call( window, data );
			} )( data );
		}
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
	},

	// args is for internal usage only
	each: function( object, callback, args ) {
		var name, i = 0,
			length = object.length,
			isObj = length === undefined || jQuery.isFunction( object );

		if ( args ) {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.apply( object[ name ], args ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.apply( object[ i++ ], args ) === false ) {
						break;
					}
				}
			}

		// A special, fast, case for the most common use of each
		} else {
			if ( isObj ) {
				for ( name in object ) {
					if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
						break;
					}
				}
			} else {
				for ( ; i < length; ) {
					if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
						break;
					}
				}
			}
		}

		return object;
	},

	// Use native String.trim function wherever possible
	trim: trim ?
		function( text ) {
			return text == null ?
				"" :
				trim.call( text );
		} :

		// Otherwise use our own trimming functionality
		function( text ) {
			return text == null ?
				"" :
				text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
		},

	// results is for internal usage only
	makeArray: function( array, results ) {
		var ret = results || [];

		if ( array != null ) {
			// The window, strings (and functions) also have 'length'
			// The extra typeof function check is to prevent crashes
			// in Safari 2 (See: #3039)
			// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
			var type = jQuery.type( array );

			if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
				push.call( ret, array );
			} else {
				jQuery.merge( ret, array );
			}
		}

		return ret;
	},

	inArray: function( elem, array ) {

		if ( indexOf ) {
			return indexOf.call( array, elem );
		}

		for ( var i = 0, length = array.length; i < length; i++ ) {
			if ( array[ i ] === elem ) {
				return i;
			}
		}

		return -1;
	},

	merge: function( first, second ) {
		var i = first.length,
			j = 0;

		if ( typeof second.length === "number" ) {
			for ( var l = second.length; j < l; j++ ) {
				first[ i++ ] = second[ j ];
			}

		} else {
			while ( second[j] !== undefined ) {
				first[ i++ ] = second[ j++ ];
			}
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, inv ) {
		var ret = [], retVal;
		inv = !!inv;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( var i = 0, length = elems.length; i < length; i++ ) {
			retVal = !!callback( elems[ i ], i );
			if ( inv !== retVal ) {
				ret.push( elems[ i ] );
			}
		}

		return ret;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var value, key, ret = [],
			i = 0,
			length = elems.length,
			// jquery objects are treated as arrays
			isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;

		// Go through the array, translating each of the items to their
		if ( isArray ) {
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}

		// Go through every key on the object,
		} else {
			for ( key in elems ) {
				value = callback( elems[ key ], key, arg );

				if ( value != null ) {
					ret[ ret.length ] = value;
				}
			}
		}

		// Flatten any nested arrays
		return ret.concat.apply( [], ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// Bind a function to a context, optionally partially applying any
	// arguments.
	proxy: function( fn, context ) {
		if ( typeof context === "string" ) {
			var tmp = fn[ context ];
			context = fn;
			fn = tmp;
		}

		// Quick check to determine if target is callable, in the spec
		// this throws a TypeError, but we will just return undefined.
		if ( !jQuery.isFunction( fn ) ) {
			return undefined;
		}

		// Simulated bind
		var args = slice.call( arguments, 2 ),
			proxy = function() {
				return fn.apply( context, args.concat( slice.call( arguments ) ) );
			};

		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;

		return proxy;
	},

	// Mutifunctional method to get and set values to a collection
	// The value/s can be optionally by executed if its a function
	access: function( elems, key, value, exec, fn, pass ) {
		var length = elems.length;

		// Setting many attributes
		if ( typeof key === "object" ) {
			for ( var k in key ) {
				jQuery.access( elems, k, key[k], exec, fn, value );
			}
			return elems;
		}

		// Setting one attribute
		if ( value !== undefined ) {
			// Optionally, function values get executed if exec is true
			exec = !pass && exec && jQuery.isFunction(value);

			for ( var i = 0; i < length; i++ ) {
				fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
			}

			return elems;
		}

		// Getting an attribute
		return length ? fn( elems[0], key ) : undefined;
	},

	now: function() {
		return (new Date()).getTime();
	},

	// Use of jQuery.browser is frowned upon.
	// More details: http://docs.jquery.com/Utilities/jQuery.browser
	uaMatch: function( ua ) {
		ua = ua.toLowerCase();

		var match = rwebkit.exec( ua ) ||
			ropera.exec( ua ) ||
			rmsie.exec( ua ) ||
			ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
			[];

		return { browser: match[1] || "", version: match[2] || "0" };
	},

	sub: function() {
		function jQuerySub( selector, context ) {
			return new jQuerySub.fn.init( selector, context );
		}
		jQuery.extend( true, jQuerySub, this );
		jQuerySub.superclass = this;
		jQuerySub.fn = jQuerySub.prototype = this();
		jQuerySub.fn.constructor = jQuerySub;
		jQuerySub.sub = this.sub;
		jQuerySub.fn.init = function init( selector, context ) {
			if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
				context = jQuerySub( context );
			}

			return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
		};
		jQuerySub.fn.init.prototype = jQuerySub.fn;
		var rootjQuerySub = jQuerySub(document);
		return jQuerySub;
	},

	browser: {}
});

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
	jQuery.browser[ browserMatch.browser ] = true;
	jQuery.browser.version = browserMatch.version;
}

// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
	jQuery.browser.safari = true;
}

// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
	trimLeft = /^[\s\xA0]+/;
	trimRight = /[\s\xA0]+$/;
}

// All jQuery objects should point back to these
rootjQuery = jQuery(document);

// Cleanup functions for the document ready method
if ( document.addEventListener ) {
	DOMContentLoaded = function() {
		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
		jQuery.ready();
	};

} else if ( document.attachEvent ) {
	DOMContentLoaded = function() {
		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( document.readyState === "complete" ) {
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			jQuery.ready();
		}
	};
}

// The DOM ready check for Internet Explorer
function doScrollCheck() {
	if ( jQuery.isReady ) {
		return;
	}

	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch(e) {
		setTimeout( doScrollCheck, 1 );
		return;
	}

	// and execute any waiting functions
	jQuery.ready();
}

// Expose jQuery to the global object
return jQuery;

})();


var // Promise methods
	promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ),
	// Static reference to slice
	sliceDeferred = [].slice;

jQuery.extend({
	// Create a simple deferred (one callbacks list)
	_Deferred: function() {
		var // callbacks list
			callbacks = [],
			// stored [ context , args ]
			fired,
			// to avoid firing when already doing so
			firing,
			// flag to know if the deferred has been cancelled
			cancelled,
			// the deferred itself
			deferred  = {

				// done( f1, f2, ...)
				done: function() {
					if ( !cancelled ) {
						var args = arguments,
							i,
							length,
							elem,
							type,
							_fired;
						if ( fired ) {
							_fired = fired;
							fired = 0;
						}
						for ( i = 0, length = args.length; i < length; i++ ) {
							elem = args[ i ];
							type = jQuery.type( elem );
							if ( type === "array" ) {
								deferred.done.apply( deferred, elem );
							} else if ( type === "function" ) {
								callbacks.push( elem );
							}
						}
						if ( _fired ) {
							deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
						}
					}
					return this;
				},

				// resolve with given context and args
				resolveWith: function( context, args ) {
					if ( !cancelled && !fired && !firing ) {
						// make sure args are available (#8421)
						args = args || [];
						firing = 1;
						try {
							while( callbacks[ 0 ] ) {
								callbacks.shift().apply( context, args );
							}
						}
						finally {
							fired = [ context, args ];
							firing = 0;
						}
					}
					return this;
				},

				// resolve with this as context and given arguments
				resolve: function() {
					deferred.resolveWith( this, arguments );
					return this;
				},

				// Has this deferred been resolved?
				isResolved: function() {
					return !!( firing || fired );
				},

				// Cancel
				cancel: function() {
					cancelled = 1;
					callbacks = [];
					return this;
				}
			};

		return deferred;
	},

	// Full fledged deferred (two callbacks list)
	Deferred: function( func ) {
		var deferred = jQuery._Deferred(),
			failDeferred = jQuery._Deferred(),
			promise;
		// Add errorDeferred methods, then and promise
		jQuery.extend( deferred, {
			then: function( doneCallbacks, failCallbacks ) {
				deferred.done( doneCallbacks ).fail( failCallbacks );
				return this;
			},
			always: function() {
				return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments );
			},
			fail: failDeferred.done,
			rejectWith: failDeferred.resolveWith,
			reject: failDeferred.resolve,
			isRejected: failDeferred.isResolved,
			pipe: function( fnDone, fnFail ) {
				return jQuery.Deferred(function( newDefer ) {
					jQuery.each( {
						done: [ fnDone, "resolve" ],
						fail: [ fnFail, "reject" ]
					}, function( handler, data ) {
						var fn = data[ 0 ],
							action = data[ 1 ],
							returned;
						if ( jQuery.isFunction( fn ) ) {
							deferred[ handler ](function() {
								returned = fn.apply( this, arguments );
								if ( jQuery.isFunction( returned.promise ) ) {
									returned.promise().then( newDefer.resolve, newDefer.reject );
								} else {
									newDefer[ action ]( returned );
								}
							});
						} else {
							deferred[ handler ]( newDefer[ action ] );
						}
					});
				}).promise();
			},
			// Get a promise for this deferred
			// If obj is provided, the promise aspect is added to the object
			promise: function( obj ) {
				if ( obj == null ) {
					if ( promise ) {
						return promise;
					}
					promise = obj = {};
				}
				var i = promiseMethods.length;
				while( i-- ) {
					obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ];
				}
				return obj;
			}
		});
		// Make sure only one callback list will be used
		deferred.done( failDeferred.cancel ).fail( deferred.cancel );
		// Unexpose cancel
		delete deferred.cancel;
		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}
		return deferred;
	},

	// Deferred helper
	when: function( firstParam ) {
		var args = arguments,
			i = 0,
			length = args.length,
			count = length,
			deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
				firstParam :
				jQuery.Deferred();
		function resolveFunc( i ) {
			return function( value ) {
				args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
				if ( !( --count ) ) {
					// Strange bug in FF4:
					// Values changed onto the arguments object sometimes end up as undefined values
					// outside the $.when method. Cloning the object into a fresh array solves the issue
					deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) );
				}
			};
		}
		if ( length > 1 ) {
			for( ; i < length; i++ ) {
				if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) {
					args[ i ].promise().then( resolveFunc(i), deferred.reject );
				} else {
					--count;
				}
			}
			if ( !count ) {
				deferred.resolveWith( deferred, args );
			}
		} else if ( deferred !== firstParam ) {
			deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
		}
		return deferred.promise();
	}
});



jQuery.support = (function() {

	var div = document.createElement( "div" ),
		all,
		a,
		select,
		opt,
		input,
		marginDiv,
		support,
		fragment,
		body,
		bodyStyle,
		tds,
		events,
		eventName,
		i,
		isSupported;

	// Preliminary tests
	div.setAttribute("className", "t");
	div.innerHTML = "   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";

	all = div.getElementsByTagName( "*" );
	a = div.getElementsByTagName( "a" )[ 0 ];

	// Can't get basic test support
	if ( !all || !all.length || !a ) {
		return {};
	}

	// First batch of supports tests
	select = document.createElement( "select" );
	opt = select.appendChild( document.createElement("option") );
	input = div.getElementsByTagName( "input" )[ 0 ];

	support = {
		// IE strips leading whitespace when .innerHTML is used
		leadingWhitespace: ( div.firstChild.nodeType === 3 ),

		// Make sure that tbody elements aren't automatically inserted
		// IE will insert them into empty tables
		tbody: !div.getElementsByTagName( "tbody" ).length,

		// Make sure that link elements get serialized correctly by innerHTML
		// This requires a wrapper element in IE
		htmlSerialize: !!div.getElementsByTagName( "link" ).length,

		// Get the style information from getAttribute
		// (IE uses .cssText instead)
		style: /top/.test( a.getAttribute("style") ),

		// Make sure that URLs aren't manipulated
		// (IE normalizes it by default)
		hrefNormalized: ( a.getAttribute( "href" ) === "/a" ),

		// Make sure that element opacity exists
		// (IE uses filter instead)
		// Use a regex to work around a WebKit issue. See #5145
		opacity: /^0.55$/.test( a.style.opacity ),

		// Verify style float existence
		// (IE uses styleFloat instead of cssFloat)
		cssFloat: !!a.style.cssFloat,

		// Make sure that if no value is specified for a checkbox
		// that it defaults to "on".
		// (WebKit defaults to "" instead)
		checkOn: ( input.value === "on" ),

		// Make sure that a selected-by-default option has a working selected property.
		// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
		optSelected: opt.selected,

		// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
		getSetAttribute: div.className !== "t",

		// Will be defined later
		submitBubbles: true,
		changeBubbles: true,
		focusinBubbles: false,
		deleteExpando: true,
		noCloneEvent: true,
		inlineBlockNeedsLayout: false,
		shrinkWrapBlocks: false,
		reliableMarginRight: true
	};

	// Make sure checked status is properly cloned
	input.checked = true;
	support.noCloneChecked = input.cloneNode( true ).checked;

	// Make sure that the options inside disabled selects aren't marked as disabled
	// (WebKit marks them as disabled)
	select.disabled = true;
	support.optDisabled = !opt.disabled;

	// Test to see if it's possible to delete an expando from an element
	// Fails in Internet Explorer
	try {
		delete div.test;
	} catch( e ) {
		support.deleteExpando = false;
	}

	if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
		div.attachEvent( "onclick", function click() {
			// Cloning a node shouldn't copy over any
			// bound event handlers (IE does this)
			support.noCloneEvent = false;
			div.detachEvent( "onclick", click );
		});
		div.cloneNode( true ).fireEvent( "onclick" );
	}

	// Check if a radio maintains it's value
	// after being appended to the DOM
	input = document.createElement("input");
	input.value = "t";
	input.setAttribute("type", "radio");
	support.radioValue = input.value === "t";

	input.setAttribute("checked", "checked");
	div.appendChild( input );
	fragment = document.createDocumentFragment();
	fragment.appendChild( div.firstChild );

	// WebKit doesn't clone checked state correctly in fragments
	support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;

	div.innerHTML = "";

	// Figure out if the W3C box model works as expected
	div.style.width = div.style.paddingLeft = "1px";

	// We use our own, invisible, body
	body = document.createElement( "body" );
	bodyStyle = {
		visibility: "hidden",
		width: 0,
		height: 0,
		border: 0,
		margin: 0,
		// Set background to avoid IE crashes when removing (#9028)
		background: "none"
	};
	for ( i in bodyStyle ) {
		body.style[ i ] = bodyStyle[ i ];
	}
	body.appendChild( div );
	document.documentElement.appendChild( body );

	// Check if a disconnected checkbox will retain its checked
	// value of true after appended to the DOM (IE6/7)
	support.appendChecked = input.checked;

	support.boxModel = div.offsetWidth === 2;

	if ( "zoom" in div.style ) {
		// Check if natively block-level elements act like inline-block
		// elements when setting their display to 'inline' and giving
		// them layout
		// (IE < 8 does this)
		div.style.display = "inline";
		div.style.zoom = 1;
		support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );

		// Check if elements with layout shrink-wrap their children
		// (IE 6 does this)
		div.style.display = "";
		div.innerHTML = "<div style='width:4px;'></div>";
		support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
	}

	div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
	tds = div.getElementsByTagName( "td" );

	// Check if table cells still have offsetWidth/Height when they are set
	// to display:none and there are still other visible table cells in a
	// table row; if so, offsetWidth/Height are not reliable for use when
	// determining if an element has been hidden directly using
	// display:none (it is still safe to use offsets if a parent element is
	// hidden; don safety goggles and see bug #4512 for more information).
	// (only IE 8 fails this test)
	isSupported = ( tds[ 0 ].offsetHeight === 0 );

	tds[ 0 ].style.display = "";
	tds[ 1 ].style.display = "none";

	// Check if empty table cells still have offsetWidth/Height
	// (IE < 8 fail this test)
	support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
	div.innerHTML = "";

	// Check if div with explicit width and no margin-right incorrectly
	// gets computed margin-right based on width of container. For more
	// info see bug #3333
	// Fails in WebKit before Feb 2011 nightlies
	// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
	if ( document.defaultView && document.defaultView.getComputedStyle ) {
		marginDiv = document.createElement( "div" );
		marginDiv.style.width = "0";
		marginDiv.style.marginRight = "0";
		div.appendChild( marginDiv );
		support.reliableMarginRight =
			( parseInt( document.defaultView.getComputedStyle( marginDiv, null ).marginRight, 10 ) || 0 ) === 0;
	}

	// Remove the body element we added
	body.innerHTML = "";
	document.documentElement.removeChild( body );

	// Technique from Juriy Zaytsev
	// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
	// We only care about the case where non-standard event systems
	// are used, namely in IE. Short-circuiting here helps us to
	// avoid an eval call (in setAttribute) which can cause CSP
	// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
	if ( div.attachEvent ) {
		for( i in {
			submit: 1,
			change: 1,
			focusin: 1
		} ) {
			eventName = "on" + i;
			isSupported = ( eventName in div );
			if ( !isSupported ) {
				div.setAttribute( eventName, "return;" );
				isSupported = ( typeof div[ eventName ] === "function" );
			}
			support[ i + "Bubbles" ] = isSupported;
		}
	}

	return support;
})();

// Keep track of boxModel
jQuery.boxModel = jQuery.support.boxModel;




var rbrace = /^(?:\{.*\}|\[.*\])$/,
	rmultiDash = /([a-z])([A-Z])/g;

jQuery.extend({
	cache: {},

	// Please use with caution
	uuid: 0,

	// Unique for each copy of jQuery on the page
	// Non-digits removed to match rinlinejQuery
	expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),

	// The following elements throw uncatchable exceptions if you
	// attempt to add expando properties to them.
	noData: {
		"embed": true,
		// Ban all objects except for Flash (which handle expandos)
		"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
		"applet": true
	},

	hasData: function( elem ) {
		elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];

		return !!elem && !isEmptyDataObject( elem );
	},

	data: function( elem, name, data, pvt /* Internal Use Only */ ) {
		if ( !jQuery.acceptData( elem ) ) {
			return;
		}

		var internalKey = jQuery.expando, getByName = typeof name === "string", thisCache,

			// We have to handle DOM nodes and JS objects differently because IE6-7
			// can't GC object references properly across the DOM-JS boundary
			isNode = elem.nodeType,

			// Only DOM nodes need the global jQuery cache; JS object data is
			// attached directly to the object so GC can occur automatically
			cache = isNode ? jQuery.cache : elem,

			// Only defining an ID for JS objects if its cache already exists allows
			// the code to shortcut on the same path as a DOM node with no cache
			id = isNode ? elem[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando;

		// Avoid doing any more work than we need to when trying to get data on an
		// object that has no data at all
		if ( (!id || (pvt && id && !cache[ id ][ internalKey ])) && getByName && data === undefined ) {
			return;
		}

		if ( !id ) {
			// Only DOM nodes need a new unique ID for each element since their data
			// ends up in the global cache
			if ( isNode ) {
				elem[ jQuery.expando ] = id = ++jQuery.uuid;
			} else {
				id = jQuery.expando;
			}
		}

		if ( !cache[ id ] ) {
			cache[ id ] = {};

			// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
			// metadata on plain JS objects when the object is serialized using
			// JSON.stringify
			if ( !isNode ) {
				cache[ id ].toJSON = jQuery.noop;
			}
		}

		// An object can be passed to jQuery.data instead of a key/value pair; this gets
		// shallow copied over onto the existing cache
		if ( typeof name === "object" || typeof name === "function" ) {
			if ( pvt ) {
				cache[ id ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name);
			} else {
				cache[ id ] = jQuery.extend(cache[ id ], name);
			}
		}

		thisCache = cache[ id ];

		// Internal jQuery data is stored in a separate object inside the object's data
		// cache in order to avoid key collisions between internal data and user-defined
		// data
		if ( pvt ) {
			if ( !thisCache[ internalKey ] ) {
				thisCache[ internalKey ] = {};
			}

			thisCache = thisCache[ internalKey ];
		}

		if ( data !== undefined ) {
			thisCache[ name ] = data;
		}

		// TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should
		// not attempt to inspect the internal events object using jQuery.data, as this
		// internal data object is undocumented and subject to change.
		if ( name === "events" && !thisCache[name] ) {
			return thisCache[ internalKey ] && thisCache[ internalKey ].events;
		}

		return getByName ? thisCache[ name ] : thisCache;
	},

	removeData: function( elem, name, pvt /* Internal Use Only */ ) {
		if ( !jQuery.acceptData( elem ) ) {
			return;
		}

		var internalKey = jQuery.expando, isNode = elem.nodeType,

			// See jQuery.data for more information
			cache = isNode ? jQuery.cache : elem,

			// See jQuery.data for more information
			id = isNode ? elem[ jQuery.expando ] : jQuery.expando;

		// If there is already no cache entry for this object, there is no
		// purpose in continuing
		if ( !cache[ id ] ) {
			return;
		}

		if ( name ) {
			var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ];

			if ( thisCache ) {
				delete thisCache[ name ];

				// If there is no data left in the cache, we want to continue
				// and let the cache object itself get destroyed
				if ( !isEmptyDataObject(thisCache) ) {
					return;
				}
			}
		}

		// See jQuery.data for more information
		if ( pvt ) {
			delete cache[ id ][ internalKey ];

			// Don't destroy the parent cache unless the internal data object
			// had been the only thing left in it
			if ( !isEmptyDataObject(cache[ id ]) ) {
				return;
			}
		}

		var internalCache = cache[ id ][ internalKey ];

		// Browsers that fail expando deletion also refuse to delete expandos on
		// the window, but it will allow it on all other JS objects; other browsers
		// don't care
		if ( jQuery.support.deleteExpando || cache != window ) {
			delete cache[ id ];
		} else {
			cache[ id ] = null;
		}

		// We destroyed the entire user cache at once because it's faster than
		// iterating through each key, but we need to continue to persist internal
		// data if it existed
		if ( internalCache ) {
			cache[ id ] = {};
			// TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery
			// metadata on plain JS objects when the object is serialized using
			// JSON.stringify
			if ( !isNode ) {
				cache[ id ].toJSON = jQuery.noop;
			}

			cache[ id ][ internalKey ] = internalCache;

		// Otherwise, we need to eliminate the expando on the node to avoid
		// false lookups in the cache for entries that no longer exist
		} else if ( isNode ) {
			// IE does not allow us to delete expando properties from nodes,
			// nor does it have a removeAttribute function on Document nodes;
			// we must handle all of these cases
			if ( jQuery.support.deleteExpando ) {
				delete elem[ jQuery.expando ];
			} else if ( elem.removeAttribute ) {
				elem.removeAttribute( jQuery.expando );
			} else {
				elem[ jQuery.expando ] = null;
			}
		}
	},

	// For internal use only.
	_data: function( elem, name, data ) {
		return jQuery.data( elem, name, data, true );
	},

	// A method for determining if a DOM node can handle the data expando
	acceptData: function( elem ) {
		if ( elem.nodeName ) {
			var match = jQuery.noData[ elem.nodeName.toLowerCase() ];

			if ( match ) {
				return !(match === true || elem.getAttribute("classid") !== match);
			}
		}

		return true;
	}
});

jQuery.fn.extend({
	data: function( key, value ) {
		var data = null;

		if ( typeof key === "undefined" ) {
			if ( this.length ) {
				data = jQuery.data( this[0] );

				if ( this[0].nodeType === 1 ) {
			    var attr = this[0].attributes, name;
					for ( var i = 0, l = attr.length; i < l; i++ ) {
						name = attr[i].name;

						if ( name.indexOf( "data-" ) === 0 ) {
							name = jQuery.camelCase( name.substring(5) );

							dataAttr( this[0], name, data[ name ] );
						}
					}
				}
			}

			return data;

		} else if ( typeof key === "object" ) {
			return this.each(function() {
				jQuery.data( this, key );
			});
		}

		var parts = key.split(".");
		parts[1] = parts[1] ? "." + parts[1] : "";

		if ( value === undefined ) {
			data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

			// Try to fetch any internally stored data first
			if ( data === undefined && this.length ) {
				data = jQuery.data( this[0], key );
				data = dataAttr( this[0], key, data );
			}

			return data === undefined && parts[1] ?
				this.data( parts[0] ) :
				data;

		} else {
			return this.each(function() {
				var $this = jQuery( this ),
					args = [ parts[0], value ];

				$this.triggerHandler( "setData" + parts[1] + "!", args );
				jQuery.data( this, key, value );
				$this.triggerHandler( "changeData" + parts[1] + "!", args );
			});
		}
	},

	removeData: function( key ) {
		return this.each(function() {
			jQuery.removeData( this, key );
		});
	}
});

function dataAttr( elem, key, data ) {
	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {
		name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase();

		data = elem.getAttribute( name );

		if ( typeof data === "string" ) {
			try {
				data = data === "true" ? true :
				data === "false" ? false :
				data === "null" ? null :
				!jQuery.isNaN( data ) ? parseFloat( data ) :
					rbrace.test( data ) ? jQuery.parseJSON( data ) :
					data;
			} catch( e ) {}

			// Make sure we set the data so it isn't changed later
			jQuery.data( elem, key, data );

		} else {
			data = undefined;
		}
	}

	return data;
}

// TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON
// property to be considered empty objects; this property always exists in
// order to make sure JSON.stringify does not expose internal metadata
function isEmptyDataObject( obj ) {
	for ( var name in obj ) {
		if ( name !== "toJSON" ) {
			return false;
		}
	}

	return true;
}




function handleQueueMarkDefer( elem, type, src ) {
	var deferDataKey = type + "defer",
		queueDataKey = type + "queue",
		markDataKey = type + "mark",
		defer = jQuery.data( elem, deferDataKey, undefined, true );
	if ( defer &&
		( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) &&
		( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) {
		// Give room for hard-coded callbacks to fire first
		// and eventually mark/queue something else on the element
		setTimeout( function() {
			if ( !jQuery.data( elem, queueDataKey, undefined, true ) &&
				!jQuery.data( elem, markDataKey, undefined, true ) ) {
				jQuery.removeData( elem, deferDataKey, true );
				defer.resolve();
			}
		}, 0 );
	}
}

jQuery.extend({

	_mark: function( elem, type ) {
		if ( elem ) {
			type = (type || "fx") + "mark";
			jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true );
		}
	},

	_unmark: function( force, elem, type ) {
		if ( force !== true ) {
			type = elem;
			elem = force;
			force = false;
		}
		if ( elem ) {
			type = type || "fx";
			var key = type + "mark",
				count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 );
			if ( count ) {
				jQuery.data( elem, key, count, true );
			} else {
				jQuery.removeData( elem, key, true );
				handleQueueMarkDefer( elem, type, "mark" );
			}
		}
	},

	queue: function( elem, type, data ) {
		if ( elem ) {
			type = (type || "fx") + "queue";
			var q = jQuery.data( elem, type, undefined, true );
			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !q || jQuery.isArray(data) ) {
					q = jQuery.data( elem, type, jQuery.makeArray(data), true );
				} else {
					q.push( data );
				}
			}
			return q || [];
		}
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ),
			fn = queue.shift(),
			defer;

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
		}

		if ( fn ) {
			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift("inprogress");
			}

			fn.call(elem, function() {
				jQuery.dequeue(elem, type);
			});
		}

		if ( !queue.length ) {
			jQuery.removeData( elem, type + "queue", true );
			handleQueueMarkDefer( elem, type, "queue" );
		}
	}
});

jQuery.fn.extend({
	queue: function( type, data ) {
		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
		}

		if ( data === undefined ) {
			return jQuery.queue( this[0], type );
		}
		return this.each(function() {
			var queue = jQuery.queue( this, type, data );

			if ( type === "fx" && queue[0] !== "inprogress" ) {
				jQuery.dequeue( this, type );
			}
		});
	},
	dequeue: function( type ) {
		return this.each(function() {
			jQuery.dequeue( this, type );
		});
	},
	// Based off of the plugin by Clint Helfers, with permission.
	// http://blindsignals.com/index.php/2009/07/jquery-delay/
	delay: function( time, type ) {
		time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
		type = type || "fx";

		return this.queue( type, function() {
			var elem = this;
			setTimeout(function() {
				jQuery.dequeue( elem, type );
			}, time );
		});
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	},
	// Get a promise resolved when queues of a certain type
	// are emptied (fx is the type by default)
	promise: function( type, object ) {
		if ( typeof type !== "string" ) {
			object = type;
			type = undefined;
		}
		type = type || "fx";
		var defer = jQuery.Deferred(),
			elements = this,
			i = elements.length,
			count = 1,
			deferDataKey = type + "defer",
			queueDataKey = type + "queue",
			markDataKey = type + "mark";
		function resolve() {
			if ( !( --count ) ) {
				defer.resolveWith( elements, [ elements ] );
			}
		}
		while( i-- ) {
			if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
					( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
						jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
					jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) {
				count++;
				tmp.done( resolve );
			}
		}
		resolve();
		return defer.promise();
	}
});




var rclass = /[\n\t\r]/g,
	rspace = /\s+/,
	rreturn = /\r/g,
	rtype = /^(?:button|input)$/i,
	rfocusable = /^(?:button|input|object|select|textarea)$/i,
	rclickable = /^a(?:rea)?$/i,
	rspecial = /^(?:data-|aria-)/,
	rinvalidChar = /\:/,
	formHook;

jQuery.fn.extend({
	attr: function( name, value ) {
		return jQuery.access( this, name, value, true, jQuery.attr );
	},

	removeAttr: function( name ) {
		return this.each(function() {
			jQuery.removeAttr( this, name );
		});
	},
	
	prop: function( name, value ) {
		return jQuery.access( this, name, value, true, jQuery.prop );
	},
	
	removeProp: function( name ) {
		return this.each(function() {
			// try/catch handles cases where IE balks (such as removing a property on window)
			try {
				this[ name ] = undefined;
				delete this[ name ];
			} catch( e ) {}
		});
	},

	addClass: function( value ) {
		if ( jQuery.isFunction( value ) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.addClass( value.call(this, i, self.attr("class") || "") );
			});
		}

		if ( value && typeof value === "string" ) {
			var classNames = (value || "").split( rspace );

			for ( var i = 0, l = this.length; i < l; i++ ) {
				var elem = this[i];

				if ( elem.nodeType === 1 ) {
					if ( !elem.className ) {
						elem.className = value;

					} else {
						var className = " " + elem.className + " ",
							setClass = elem.className;

						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) {
								setClass += " " + classNames[c];
							}
						}
						elem.className = jQuery.trim( setClass );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.removeClass( value.call(this, i, self.attr("class")) );
			});
		}

		if ( (value && typeof value === "string") || value === undefined ) {
			var classNames = (value || "").split( rspace );

			for ( var i = 0, l = this.length; i < l; i++ ) {
				var elem = this[i];

				if ( elem.nodeType === 1 && elem.className ) {
					if ( value ) {
						var className = (" " + elem.className + " ").replace(rclass, " ");
						for ( var c = 0, cl = classNames.length; c < cl; c++ ) {
							className = className.replace(" " + classNames[c] + " ", " ");
						}
						elem.className = jQuery.trim( className );

					} else {
						elem.className = "";
					}
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value,
			isBool = typeof stateVal === "boolean";

		if ( jQuery.isFunction( value ) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				self.toggleClass( value.call(this, i, self.attr("class"), stateVal), stateVal );
			});
		}

		return this.each(function() {
			if ( type === "string" ) {
				// toggle individual class names
				var className,
					i = 0,
					self = jQuery( this ),
					state = stateVal,
					classNames = value.split( rspace );

				while ( (className = classNames[ i++ ]) ) {
					// check each className given, space seperated list
					state = isBool ? state : !self.hasClass( className );
					self[ state ? "addClass" : "removeClass" ]( className );
				}

			} else if ( type === "undefined" || type === "boolean" ) {
				if ( this.className ) {
					// store className if set
					jQuery._data( this, "__className__", this.className );
				}

				// toggle whole className
				this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
			}
		});
	},

	hasClass: function( selector ) {
		var className = " " + selector + " ";
		for ( var i = 0, l = this.length; i < l; i++ ) {
			if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
				return true;
			}
		}

		return false;
	},

	val: function( value ) {
		var hooks, ret,
			elem = this[0];
		
		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];

				if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
					return ret;
				}

				return (elem.value || "").replace(rreturn, "");
			}

			return undefined;
		}

		var isFunction = jQuery.isFunction( value );

		return this.each(function( i ) {
			var self = jQuery(this), val;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( isFunction ) {
				val = value.call( this, i, self.val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";
			} else if ( typeof val === "number" ) {
				val += "";
			} else if ( jQuery.isArray( val ) ) {
				val = jQuery.map(val, function ( value ) {
					return value == null ? "" : value + "";
				});
			}

			hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || ("set" in hooks && hooks.set( this, val, "value" ) === undefined) ) {
				this.value = val;
			}
		});
	}
});

jQuery.extend({
	valHooks: {
		option: {
			get: function( elem ) {
				// attributes.value is undefined in Blackberry 4.7 but
				// uses .value. See #6932
				var val = elem.attributes.value;
				return !val || val.specified ? elem.value : elem.text;
			}
		},
		select: {
			get: function( elem ) {
				var index = elem.selectedIndex,
					values = [],
					options = elem.options,
					one = elem.type === "select-one";

				// Nothing was selected
				if ( index < 0 ) {
					return null;
				}

				// Loop through all the selected options
				for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
					var option = options[ i ];

					// Don't return options that are disabled or in a disabled optgroup
					if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
							(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
				if ( one && !values.length && options.length ) {
					return jQuery( options[ index ] ).val();
				}

				return values;
			},

			set: function( elem, value ) {
				var values = jQuery.makeArray( value );

				jQuery(elem).find("option").each(function() {
					this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
				});

				if ( !values.length ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	},

	attrFn: {
		val: true,
		css: true,
		html: true,
		text: true,
		data: true,
		width: true,
		height: true,
		offset: true
	},
	
	attrFix: {
		// Always normalize to ensure hook usage
		tabindex: "tabIndex",
		readonly: "readOnly"
	},
	
	attr: function( elem, name, value, pass ) {
		var nType = elem.nodeType;
		
		// don't get/set attributes on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return undefined;
		}

		if ( pass && name in jQuery.attrFn ) {
			return jQuery( elem )[ name ]( value );
		}
		
		var ret, hooks,
			notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
		
		// Normalize the name if needed
		name = notxml && jQuery.attrFix[ name ] || name;

		// Get the appropriate hook, or the formHook
		// if getSetAttribute is not supported and we have form objects in IE6/7
		hooks = jQuery.attrHooks[ name ] ||
			( formHook && (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ?
				formHook :
				undefined );

		if ( value !== undefined ) {

			if ( value === null || (value === false && !rspecial.test( name )) ) {
				jQuery.removeAttr( elem, name );
				return undefined;

			} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;

			} else {

				// Set boolean attributes to the same name
				if ( value === true && !rspecial.test( name ) ) {
					value = name;
				}

				elem.setAttribute( name, "" + value );
				return value;
			}

		} else {

			if ( hooks && "get" in hooks && notxml ) {
				return hooks.get( elem, name );

			} else {

				ret = elem.getAttribute( name );

				// Non-existent attributes return null, we normalize to undefined
				return ret === null ?
					undefined :
					ret;
			}
		}
	},
	
	removeAttr: function( elem, name ) {
		if ( elem.nodeType === 1 ) {
			name = jQuery.attrFix[ name ] || name;
		
			if ( jQuery.support.getSetAttribute ) {
				// Use removeAttribute in browsers that support it
				elem.removeAttribute( name );
			} else {
				jQuery.attr( elem, name, "" );
				elem.removeAttributeNode( elem.getAttributeNode( name ) );
			}
		}
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				// We can't allow the type property to be changed (since it causes problems in IE)
				if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
					jQuery.error( "type property can't be changed" );
				} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
					// Setting the type on a radio button after the value resets the value in IE6-9
					// Reset value to it's default in case type is set after value
					// This is for element creation
					var val = elem.getAttribute("value");
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		},
		tabIndex: {
			get: function( elem ) {
				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				var attributeNode = elem.getAttributeNode("tabIndex");

				return attributeNode && attributeNode.specified ?
					parseInt( attributeNode.value, 10 ) :
					rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
						0 :
						undefined;
			}
		}
	},
	
	propFix: {},
	
	prop: function( elem, name, value ) {
		var nType = elem.nodeType;
		
		// don't get/set properties on text, comment and attribute nodes
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return undefined;
		}
		
		var ret, hooks,
			notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
		
		// Try to normalize/fix the name
		name = notxml && jQuery.propFix[ name ] || name;
		
		hooks = jQuery.propHooks[ name ];
		
		if ( value !== undefined ) {
			if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;
			
			} else {
				return (elem[ name ] = value);
			}
		
		} else {
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) {
				return ret;
				
			} else {
				return elem[ name ];
			}
		}
	},
	
	propHooks: {}
});

// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !jQuery.support.getSetAttribute ) {
	jQuery.attrFix = jQuery.extend( jQuery.attrFix, {
		"for": "htmlFor",
		"class": "className",
		maxlength: "maxLength",
		cellspacing: "cellSpacing",
		cellpadding: "cellPadding",
		rowspan: "rowSpan",
		colspan: "colSpan",
		usemap: "useMap",
		frameborder: "frameBorder"
	});
	
	// Use this for any attribute on a form in IE6/7
	formHook = jQuery.attrHooks.name = jQuery.attrHooks.value = jQuery.valHooks.button = {
		get: function( elem, name ) {
			var ret;
			if ( name === "value" && !jQuery.nodeName( elem, "button" ) ) {
				return elem.getAttribute( name );
			}
			ret = elem.getAttributeNode( name );
			// Return undefined if not specified instead of empty string
			return ret && ret.specified ?
				ret.nodeValue :
				undefined;
		},
		set: function( elem, value, name ) {
			// Check form objects in IE (multiple bugs related)
			// Only use nodeValue if the attribute node exists on the form
			var ret = elem.getAttributeNode( name );
			if ( ret ) {
				ret.nodeValue = value;
				return value;
			}
		}
	};

	// Set width and height to auto instead of 0 on empty string( Bug #8150 )
	// This is for removals
	jQuery.each([ "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
			set: function( elem, value ) {
				if ( value === "" ) {
					elem.setAttribute( name, "auto" );
					return value;
				}
			}
		});
	});
}


// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
	jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
		jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
			get: function( elem ) {
				var ret = elem.getAttribute( name, 2 );
				return ret === null ? undefined : ret;
			}
		});
	});
}

if ( !jQuery.support.style ) {
	jQuery.attrHooks.style = {
		get: function( elem ) {
			// Return undefined in the case of empty string
			// Normalize to lowercase since IE uppercases css property names
			return elem.style.cssText.toLowerCase() || undefined;
		},
		set: function( elem, value ) {
			return (elem.style.cssText = "" + value);
		}
	};
}

// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
	jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
		get: function( elem ) {
			var parent = elem.parentNode;

			if ( parent ) {
				parent.selectedIndex;

				// Make sure that it also works with optgroups, see #5701
				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
		}
	});
}

// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
	jQuery.each([ "radio", "checkbox" ], function() {
		jQuery.valHooks[ this ] = {
			get: function( elem ) {
				// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
				return elem.getAttribute("value") === null ? "on" : elem.value;
			}
		};
	});
}
jQuery.each([ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
		set: function( elem, value ) {
			if ( jQuery.isArray( value ) ) {
				return (elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0);
			}
		}
	});
});




var hasOwn = Object.prototype.hasOwnProperty,
	rnamespaces = /\.(.*)$/,
	rformElems = /^(?:textarea|input|select)$/i,
	rperiod = /\./g,
	rspaces = / /g,
	rescape = /[^\w\s.|`]/g,
	fcleanup = function( nm ) {
		return nm.replace(rescape, "\\$&");
	};

/*
 * A number of helper functions used for managing events.
 * Many of the ideas behind this code originated from
 * Dean Edwards' addEvent library.
 */
jQuery.event = {

	// Bind an event to an element
	// Original by Dean Edwards
	add: function( elem, types, handler, data ) {
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		if ( handler === false ) {
			handler = returnFalse;
		} else if ( !handler ) {
			// Fixes bug #7229. Fix recommended by jdalton
			return;
		}

		var handleObjIn, handleObj;

		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
		}

		// Make sure that the function being executed has a unique ID
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		// Init the element's event structure
		var elemData = jQuery._data( elem );

		// If no elemData is found then we must be trying to bind to one of the
		// banned noData elements
		if ( !elemData ) {
			return;
		}

		var events = elemData.events,
			eventHandle = elemData.handle;

		if ( !events ) {
			elemData.events = events = {};
		}

		if ( !eventHandle ) {
			elemData.handle = eventHandle = function( e ) {
				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
					jQuery.event.handle.apply( eventHandle.elem, arguments ) :
					undefined;
			};
		}

		// Add elem as a property of the handle function
		// This is to prevent a memory leak with non-native events in IE.
		eventHandle.elem = elem;

		// Handle multiple events separated by a space
		// jQuery(...).bind("mouseover mouseout", fn);
		types = types.split(" ");

		var type, i = 0, namespaces;

		while ( (type = types[ i++ ]) ) {
			handleObj = handleObjIn ?
				jQuery.extend({}, handleObjIn) :
				{ handler: handler, data: data };

			// Namespaced event handlers
			if ( type.indexOf(".") > -1 ) {
				namespaces = type.split(".");
				type = namespaces.shift();
				handleObj.namespace = namespaces.slice(0).sort().join(".");

			} else {
				namespaces = [];
				handleObj.namespace = "";
			}

			handleObj.type = type;
			if ( !handleObj.guid ) {
				handleObj.guid = handler.guid;
			}

			// Get the current list of functions bound to this event
			var handlers = events[ type ],
				special = jQuery.event.special[ type ] || {};

			// Init the event handler queue
			if ( !handlers ) {
				handlers = events[ type ] = [];

				// Check for a special event handler
				// Only use addEventListener/attachEvent if the special
				// events handler returns false
				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
					// Bind the global event handler to the element
					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle, false );

					} else if ( elem.attachEvent ) {
						elem.attachEvent( "on" + type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add the function to the element's handler list
			handlers.push( handleObj );

			// Keep track of which events have been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

		// Nullify elem to prevent memory leaks in IE
		elem = null;
	},

	global: {},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, pos ) {
		// don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		if ( handler === false ) {
			handler = returnFalse;
		}

		var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
			elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
			events = elemData && elemData.events;

		if ( !elemData || !events ) {
			return;
		}

		// types is actually an event object here
		if ( types && types.type ) {
			handler = types.handler;
			types = types.type;
		}

		// Unbind all events for the element
		if ( !types || typeof types === "string" && types.charAt(0) === "." ) {
			types = types || "";

			for ( type in events ) {
				jQuery.event.remove( elem, type + types );
			}

			return;
		}

		// Handle multiple events separated by a space
		// jQuery(...).unbind("mouseover mouseout", fn);
		types = types.split(" ");

		while ( (type = types[ i++ ]) ) {
			origType = type;
			handleObj = null;
			all = type.indexOf(".") < 0;
			namespaces = [];

			if ( !all ) {
				// Namespaced event handlers
				namespaces = type.split(".");
				type = namespaces.shift();

				namespace = new RegExp("(^|\\.)" +
					jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");
			}

			eventType = events[ type ];

			if ( !eventType ) {
				continue;
			}

			if ( !handler ) {
				for ( j = 0; j < eventType.length; j++ ) {
					handleObj = eventType[ j ];

					if ( all || namespace.test( handleObj.namespace ) ) {
						jQuery.event.remove( elem, origType, handleObj.handler, j );
						eventType.splice( j--, 1 );
					}
				}

				continue;
			}

			special = jQuery.event.special[ type ] || {};

			for ( j = pos || 0; j < eventType.length; j++ ) {
				handleObj = eventType[ j ];

				if ( handler.guid === handleObj.guid ) {
					// remove the given handler for the given type
					if ( all || namespace.test( handleObj.namespace ) ) {
						if ( pos == null ) {
							eventType.splice( j--, 1 );
						}

						if ( special.remove ) {
							special.remove.call( elem, handleObj );
						}
					}

					if ( pos != null ) {
						break;
					}
				}
			}

			// remove generic event handler if no more handlers exist
			if ( eventType.length === 0 || pos != null && eventType.length === 1 ) {
				if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
					jQuery.removeEvent( elem, type, elemData.handle );
				}

				ret = null;
				delete events[ type ];
			}
		}

		// Remove the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			var handle = elemData.handle;
			if ( handle ) {
				handle.elem = null;
			}

			delete elemData.events;
			delete elemData.handle;

			if ( jQuery.isEmptyObject( elemData ) ) {
				jQuery.removeData( elem, undefined, true );
			}
		}
	},
	
	// Events that are safe to short-circuit if no handlers are attached.
	// Native DOM events should not be added, they may have inline handlers.
	customEvent: {
		"getData": true,
		"setData": true,
		"changeData": true
	},

	trigger: function( event, data, elem, onlyHandlers ) {
		// Event object or event type
		var type = event.type || event,
			namespaces = [],
			exclusive;

		if ( type.indexOf("!") >= 0 ) {
			// Exclusive events trigger only for the exact event (no namespaces)
			type = type.slice(0, -1);
			exclusive = true;
		}

		if ( type.indexOf(".") >= 0 ) {
			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split(".");
			type = namespaces.shift();
			namespaces.sort();
		}

		if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
			// No jQuery handlers for this event type, and it can't have inline handlers
			return;
		}

		// Caller can pass in an Event, Object, or just an event type string
		event = typeof event === "object" ?
			// jQuery.Event object
			event[ jQuery.expando ] ? event :
			// Object literal
			new jQuery.Event( type, event ) :
			// Just the event type (string)
			new jQuery.Event( type );

		event.type = type;
		event.exclusive = exclusive;
		event.namespace = namespaces.join(".");
		event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
		
		// triggerHandler() and global events don't bubble or run the default action
		if ( onlyHandlers || !elem ) {
			event.preventDefault();
			event.stopPropagation();
		}

		// Handle a global trigger
		if ( !elem ) {
			// TODO: Stop taunting the data cache; remove global events and always attach to document
			jQuery.each( jQuery.cache, function() {
				// internalKey variable is just used to make it easier to find
				// and potentially change this stuff later; currently it just
				// points to jQuery.expando
				var internalKey = jQuery.expando,
					internalCache = this[ internalKey ];
				if ( internalCache && internalCache.events && internalCache.events[ type ] ) {
					jQuery.event.trigger( event, data, internalCache.handle.elem );
				}
			});
			return;
		}

		// Don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		// Clean up the event in case it is being reused
		event.result = undefined;
		event.target = elem;

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data ? jQuery.makeArray( data ) : [];
		data.unshift( event );

		var cur = elem,
			// IE doesn't like method names with a colon (#3533, #8272)
			ontype = type.indexOf(":") < 0 ? "on" + type : "";

		// Fire event on the current element, then bubble up the DOM tree
		do {
			var handle = jQuery._data( cur, "handle" );

			event.currentTarget = cur;
			if ( handle ) {
				handle.apply( cur, data );
			}

			// Trigger an inline bound script
			if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) {
				event.result = false;
				event.preventDefault();
			}

			// Bubble up to document, then to window
			cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window;
		} while ( cur && !event.isPropagationStopped() );

		// If nobody prevented the default action, do it now
		if ( !event.isDefaultPrevented() ) {
			var old,
				special = jQuery.event.special[ type ] || {};

			if ( (!special._default || special._default.call( elem.ownerDocument, event ) === false) &&
				!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name name as the event.
				// Can't use an .isFunction)() check here because IE6/7 fails that test.
				// IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch.
				try {
					if ( ontype && elem[ type ] ) {
						// Don't re-trigger an onFOO event when we call its FOO() method
						old = elem[ ontype ];

						if ( old ) {
							elem[ ontype ] = null;
						}

						jQuery.event.triggered = type;
						elem[ type ]();
					}
				} catch ( ieError ) {}

				if ( old ) {
					elem[ ontype ] = old;
				}

				jQuery.event.triggered = undefined;
			}
		}
		
		return event.result;
	},

	handle: function( event ) {
		event = jQuery.event.fix( event || window.event );
		// Snapshot the handlers list since a called handler may add/remove events.
		var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0),
			run_all = !event.exclusive && !event.namespace,
			args = Array.prototype.slice.call( arguments, 0 );

		// Use the fix-ed Event rather than the (read-only) native event
		args[0] = event;
		event.currentTarget = this;

		for ( var j = 0, l = handlers.length; j < l; j++ ) {
			var handleObj = handlers[ j ];

			// Triggered event must 1) be non-exclusive and have no namespace, or
			// 2) have namespace(s) a subset or equal to those in the bound event.
			if ( run_all || event.namespace_re.test( handleObj.namespace ) ) {
				// Pass in a reference to the handler function itself
				// So that we can later remove it
				event.handler = handleObj.handler;
				event.data = handleObj.data;
				event.handleObj = handleObj;

				var ret = handleObj.handler.apply( this, args );

				if ( ret !== undefined ) {
					event.result = ret;
					if ( ret === false ) {
						event.preventDefault();
						event.stopPropagation();
					}
				}

				if ( event.isImmediatePropagationStopped() ) {
					break;
				}
			}
		}
		return event.result;
	},

	props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),

	fix: function( event ) {
		if ( event[ jQuery.expando ] ) {
			return event;
		}

		// store a copy of the original event object
		// and "clone" to set read-only properties
		var originalEvent = event;
		event = jQuery.Event( originalEvent );

		for ( var i = this.props.length, prop; i; ) {
			prop = this.props[ --i ];
			event[ prop ] = originalEvent[ prop ];
		}

		// Fix target property, if necessary
		if ( !event.target ) {
			// Fixes #1925 where srcElement might not be defined either
			event.target = event.srcElement || document;
		}

		// check if target is a textnode (safari)
		if ( event.target.nodeType === 3 ) {
			event.target = event.target.parentNode;
		}

		// Add relatedTarget, if necessary
		if ( !event.relatedTarget && event.fromElement ) {
			event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
		}

		// Calculate pageX/Y if missing and clientX/Y available
		if ( event.pageX == null && event.clientX != null ) {
			var eventDocument = event.target.ownerDocument || document,
				doc = eventDocument.documentElement,
				body = eventDocument.body;

			event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
			event.pageY = event.clientY + (doc && doc.scrollTop  || body && body.scrollTop  || 0) - (doc && doc.clientTop  || body && body.clientTop  || 0);
		}

		// Add which for key events
		if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
			event.which = event.charCode != null ? event.charCode : event.keyCode;
		}

		// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
		if ( !event.metaKey && event.ctrlKey ) {
			event.metaKey = event.ctrlKey;
		}

		// Add which for click: 1 === left; 2 === middle; 3 === right
		// Note: button is not normalized, so don't use it
		if ( !event.which && event.button !== undefined ) {
			event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
		}

		return event;
	},

	// Deprecated, use jQuery.guid instead
	guid: 1E8,

	// Deprecated, use jQuery.proxy instead
	proxy: jQuery.proxy,

	special: {
		ready: {
			// Make sure the ready event is setup
			setup: jQuery.bindReady,
			teardown: jQuery.noop
		},

		live: {
			add: function( handleObj ) {
				jQuery.event.add( this,
					liveConvert( handleObj.origType, handleObj.selector ),
					jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) );
			},

			remove: function( handleObj ) {
				jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj );
			}
		},

		beforeunload: {
			setup: function( data, namespaces, eventHandle ) {
				// We only want to do this special case on windows
				if ( jQuery.isWindow( this ) ) {
					this.onbeforeunload = eventHandle;
				}
			},

			teardown: function( namespaces, eventHandle ) {
				if ( this.onbeforeunload === eventHandle ) {
					this.onbeforeunload = null;
				}
			}
		}
	}
};

jQuery.removeEvent = document.removeEventListener ?
	function( elem, type, handle ) {
		if ( elem.removeEventListener ) {
			elem.removeEventListener( type, handle, false );
		}
	} :
	function( elem, type, handle ) {
		if ( elem.detachEvent ) {
			elem.detachEvent( "on" + type, handle );
		}
	};

jQuery.Event = function( src, props ) {
	// Allow instantiation without the 'new' keyword
	if ( !this.preventDefault ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false ||
			src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// timeStamp is buggy for some events on Firefox(#3843)
	// So we won't rely on the native value
	this.timeStamp = jQuery.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

function returnFalse() {
	return false;
}
function returnTrue() {
	return true;
}

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	preventDefault: function() {
		this.isDefaultPrevented = returnTrue;

		var e = this.originalEvent;
		if ( !e ) {
			return;
		}

		// if preventDefault exists run it on the original event
		if ( e.preventDefault ) {
			e.preventDefault();

		// otherwise set the returnValue property of the original event to false (IE)
		} else {
			e.returnValue = false;
		}
	},
	stopPropagation: function() {
		this.isPropagationStopped = returnTrue;

		var e = this.originalEvent;
		if ( !e ) {
			return;
		}
		// if stopPropagation exists run it on the original event
		if ( e.stopPropagation ) {
			e.stopPropagation();
		}
		// otherwise set the cancelBubble property of the original event to true (IE)
		e.cancelBubble = true;
	},
	stopImmediatePropagation: function() {
		this.isImmediatePropagationStopped = returnTrue;
		this.stopPropagation();
	},
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse
};

// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
	// Check if mouse(over|out) are still within the same parent element
	var parent = event.relatedTarget;

	// Firefox sometimes assigns relatedTarget a XUL element
	// which we cannot access the parentNode property of
	try {

		// Chrome does something similar, the parentNode property
		// can be accessed but is null.
		if ( parent && parent !== document && !parent.parentNode ) {
			return;
		}
		// Traverse up the tree
		while ( parent && parent !== this ) {
			parent = parent.parentNode;
		}

		if ( parent !== this ) {
			// set the correct event type
			event.type = event.data;

			// handle event if we actually just moused on to a non sub-element
			jQuery.event.handle.apply( this, arguments );
		}

	// assuming we've left the element since we most likely mousedover a xul element
	} catch(e) { }
},

// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
	event.type = event.data;
	jQuery.event.handle.apply( this, arguments );
};

// Create mouseenter and mouseleave events
jQuery.each({
	mouseenter: "mouseover",
	mouseleave: "mouseout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		setup: function( data ) {
			jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
		},
		teardown: function( data ) {
			jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
		}
	};
});

// submit delegation
if ( !jQuery.support.submitBubbles ) {

	jQuery.event.special.submit = {
		setup: function( data, namespaces ) {
			if ( !jQuery.nodeName( this, "form" ) ) {
				jQuery.event.add(this, "click.specialSubmit", function( e ) {
					var elem = e.target,
						type = elem.type;

					if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
						trigger( "submit", this, arguments );
					}
				});

				jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
					var elem = e.target,
						type = elem.type;

					if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
						trigger( "submit", this, arguments );
					}
				});

			} else {
				return false;
			}
		},

		teardown: function( namespaces ) {
			jQuery.event.remove( this, ".specialSubmit" );
		}
	};

}

// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {

	var changeFilters,

	getVal = function( elem ) {
		var type = elem.type, val = elem.value;

		if ( type === "radio" || type === "checkbox" ) {
			val = elem.checked;

		} else if ( type === "select-multiple" ) {
			val = elem.selectedIndex > -1 ?
				jQuery.map( elem.options, function( elem ) {
					return elem.selected;
				}).join("-") :
				"";

		} else if ( jQuery.nodeName( elem, "select" ) ) {
			val = elem.selectedIndex;
		}

		return val;
	},

	testChange = function testChange( e ) {
		var elem = e.target, data, val;

		if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) {
			return;
		}

		data = jQuery._data( elem, "_change_data" );
		val = getVal(elem);

		// the current data will be also retrieved by beforeactivate
		if ( e.type !== "focusout" || elem.type !== "radio" ) {
			jQuery._data( elem, "_change_data", val );
		}

		if ( data === undefined || val === data ) {
			return;
		}

		if ( data != null || val ) {
			e.type = "change";
			e.liveFired = undefined;
			jQuery.event.trigger( e, arguments[1], elem );
		}
	};

	jQuery.event.special.change = {
		filters: {
			focusout: testChange,

			beforedeactivate: testChange,

			click: function( e ) {
				var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";

				if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) {
					testChange.call( this, e );
				}
			},

			// Change has to be called before submit
			// Keydown will be called before keypress, which is used in submit-event delegation
			keydown: function( e ) {
				var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : "";

				if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) ||
					(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
					type === "select-multiple" ) {
					testChange.call( this, e );
				}
			},

			// Beforeactivate happens also before the previous element is blurred
			// with this event you can't trigger a change event, but you can store
			// information
			beforeactivate: function( e ) {
				var elem = e.target;
				jQuery._data( elem, "_change_data", getVal(elem) );
			}
		},

		setup: function( data, namespaces ) {
			if ( this.type === "file" ) {
				return false;
			}

			for ( var type in changeFilters ) {
				jQuery.event.add( this, type + ".specialChange", changeFilters[type] );
			}

			return rformElems.test( this.nodeName );
		},

		teardown: function( namespaces ) {
			jQuery.event.remove( this, ".specialChange" );

			return rformElems.test( this.nodeName );
		}
	};

	changeFilters = jQuery.event.special.change.filters;

	// Handle when the input is .focus()'d
	changeFilters.focus = changeFilters.beforeactivate;
}

function trigger( type, elem, args ) {
	// Piggyback on a donor event to simulate a different one.
	// Fake originalEvent to avoid donor's stopPropagation, but if the
	// simulated event prevents default then we do the same on the donor.
	// Don't pass args or remember liveFired; they apply to the donor event.
	var event = jQuery.extend( {}, args[ 0 ] );
	event.type = type;
	event.originalEvent = {};
	event.liveFired = undefined;
	jQuery.event.handle.call( elem, event );
	if ( event.isDefaultPrevented() ) {
		args[ 0 ].preventDefault();
	}
}

// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler while someone wants focusin/focusout
		var attaches = 0;

		jQuery.event.special[ fix ] = {
			setup: function() {
				if ( attaches++ === 0 ) {
					document.addEventListener( orig, handler, true );
				}
			},
			teardown: function() {
				if ( --attaches === 0 ) {
					document.removeEventListener( orig, handler, true );
				}
			}
		};

		function handler( donor ) {
			// Donor event is always a native one; fix it and switch its type.
			// Let focusin/out handler cancel the donor focus/blur event.
			var e = jQuery.event.fix( donor );
			e.type = fix;
			e.originalEvent = {};
			jQuery.event.trigger( e, null, e.target );
			if ( e.isDefaultPrevented() ) {
				donor.preventDefault();
			}
		}
	});
}

jQuery.each(["bind", "one"], function( i, name ) {
	jQuery.fn[ name ] = function( type, data, fn ) {
		var handler;

		// Handle object literals
		if ( typeof type === "object" ) {
			for ( var key in type ) {
				this[ name ](key, data, type[key], fn);
			}
			return this;
		}

		if ( arguments.length === 2 || data === false ) {
			fn = data;
			data = undefined;
		}

		if ( name === "one" ) {
			handler = function( event ) {
				jQuery( this ).unbind( event, handler );
				return fn.apply( this, arguments );
			};
			handler.guid = fn.guid || jQuery.guid++;
		} else {
			handler = fn;
		}

		if ( type === "unload" && name !== "one" ) {
			this.one( type, data, fn );

		} else {
			for ( var i = 0, l = this.length; i < l; i++ ) {
				jQuery.event.add( this[i], type, handler, data );
			}
		}

		return this;
	};
});

jQuery.fn.extend({
	unbind: function( type, fn ) {
		// Handle object literals
		if ( typeof type === "object" && !type.preventDefault ) {
			for ( var key in type ) {
				this.unbind(key, type[key]);
			}

		} else {
			for ( var i = 0, l = this.length; i < l; i++ ) {
				jQuery.event.remove( this[i], type, fn );
			}
		}

		return this;
	},

	delegate: function( selector, types, data, fn ) {
		return this.live( types, data, fn, selector );
	},

	undelegate: function( selector, types, fn ) {
		if ( arguments.length === 0 ) {
			return this.unbind( "live" );

		} else {
			return this.die( types, null, fn, selector );
		}
	},

	trigger: function( type, data ) {
		return this.each(function() {
			jQuery.event.trigger( type, data, this );
		});
	},

	triggerHandler: function( type, data ) {
		if ( this[0] ) {
			return jQuery.event.trigger( type, data, this[0], true );
		}
	},

	toggle: function( fn ) {
		// Save reference to arguments for access in closure
		var args = arguments,
			guid = fn.guid || jQuery.guid++,
			i = 0,
			toggler = function( event ) {
				// Figure out which function to execute
				var lastToggle = ( jQuery.data( this, "lastToggle" + fn.guid ) || 0 ) % i;
				jQuery.data( this, "lastToggle" + fn.guid, lastToggle + 1 );

				// Make sure that clicks stop
				event.preventDefault();

				// and execute the function
				return args[ lastToggle ].apply( this, arguments ) || false;
			};

		// link all the functions, so any of them can unbind this click handler
		toggler.guid = guid;
		while ( i < args.length ) {
			args[ i++ ].guid = guid;
		}

		return this.click( toggler );
	},

	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
});

var liveMap = {
	focus: "focusin",
	blur: "focusout",
	mouseenter: "mouseover",
	mouseleave: "mouseout"
};

jQuery.each(["live", "die"], function( i, name ) {
	jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) {
		var type, i = 0, match, namespaces, preType,
			selector = origSelector || this.selector,
			context = origSelector ? this : jQuery( this.context );

		if ( typeof types === "object" && !types.preventDefault ) {
			for ( var key in types ) {
				context[ name ]( key, data, types[key], selector );
			}

			return this;
		}

		if ( name === "die" && !types &&
					origSelector && origSelector.charAt(0) === "." ) {

			context.unbind( origSelector );

			return this;
		}

		if ( data === false || jQuery.isFunction( data ) ) {
			fn = data || returnFalse;
			data = undefined;
		}

		types = (types || "").split(" ");

		while ( (type = types[ i++ ]) != null ) {
			match = rnamespaces.exec( type );
			namespaces = "";

			if ( match )  {
				namespaces = match[0];
				type = type.replace( rnamespaces, "" );
			}

			if ( type === "hover" ) {
				types.push( "mouseenter" + namespaces, "mouseleave" + namespaces );
				continue;
			}

			preType = type;

			if ( liveMap[ type ] ) {
				types.push( liveMap[ type ] + namespaces );
				type = type + namespaces;

			} else {
				type = (liveMap[ type ] || type) + namespaces;
			}

			if ( name === "live" ) {
				// bind live handler
				for ( var j = 0, l = context.length; j < l; j++ ) {
					jQuery.event.add( context[j], "live." + liveConvert( type, selector ),
						{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
				}

			} else {
				// unbind live handler
				context.unbind( "live." + liveConvert( type, selector ), fn );
			}
		}

		return this;
	};
});

function liveHandler( event ) {
	var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret,
		elems = [],
		selectors = [],
		events = jQuery._data( this, "events" );

	// Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911)
	if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) {
		return;
	}

	if ( event.namespace ) {
		namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)");
	}

	event.liveFired = this;

	var live = events.live.slice(0);

	for ( j = 0; j < live.length; j++ ) {
		handleObj = live[j];

		if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) {
			selectors.push( handleObj.selector );

		} else {
			live.splice( j--, 1 );
		}
	}

	match = jQuery( event.target ).closest( selectors, event.currentTarget );

	for ( i = 0, l = match.length; i < l; i++ ) {
		close = match[i];

		for ( j = 0; j < live.length; j++ ) {
			handleObj = live[j];

			if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) {
				elem = close.elem;
				related = null;

				// Those two events require additional checking
				if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
					event.type = handleObj.preType;
					related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];

					// Make sure not to accidentally match a child element with the same selector
					if ( related && jQuery.contains( elem, related ) ) {
						related = elem;
					}
				}

				if ( !related || related !== elem ) {
					elems.push({ elem: elem, handleObj: handleObj, level: close.level });
				}
			}
		}
	}

	for ( i = 0, l = elems.length; i < l; i++ ) {
		match = elems[i];

		if ( maxLevel && match.level > maxLevel ) {
			break;
		}

		event.currentTarget = match.elem;
		event.data = match.handleObj.data;
		event.handleObj = match.handleObj;

		ret = match.handleObj.origHandler.apply( match.elem, arguments );

		if ( ret === false || event.isPropagationStopped() ) {
			maxLevel = match.level;

			if ( ret === false ) {
				stop = false;
			}
			if ( event.isImmediatePropagationStopped() ) {
				break;
			}
		}
	}

	return stop;
}

function liveConvert( type, selector ) {
	return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&");
}

jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error").split(" "), function( i, name ) {

	// Handle event binding
	jQuery.fn[ name ] = function( data, fn ) {
		if ( fn == null ) {
			fn = data;
			data = null;
		}

		return arguments.length > 0 ?
			this.bind( name, data, fn ) :
			this.trigger( name );
	};

	if ( jQuery.attrFn ) {
		jQuery.attrFn[ name ] = true;
	}
});



/*!
 * Sizzle CSS Selector Engine
 *  Copyright 2011, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){

var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
	done = 0,
	toString = Object.prototype.toString,
	hasDuplicate = false,
	baseHasDuplicate = true,
	rBackslash = /\\/g,
	rNonWord = /\W/;

// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
//   Thus far that includes Google Chrome.
[0, 0].sort(function() {
	baseHasDuplicate = false;
	return 0;
});

var Sizzle = function( selector, context, results, seed ) {
	results = results || [];
	context = context || document;

	var origContext = context;

	if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
		return [];
	}
	
	if ( !selector || typeof selector !== "string" ) {
		return results;
	}

	var m, set, checkSet, extra, ret, cur, pop, i,
		prune = true,
		contextXML = Sizzle.isXML( context ),
		parts = [],
		soFar = selector;
	
	// Reset the position of the chunker regexp (start from head)
	do {
		chunker.exec( "" );
		m = chunker.exec( soFar );

		if ( m ) {
			soFar = m[3];
		
			parts.push( m[1] );
		
			if ( m[2] ) {
				extra = m[3];
				break;
			}
		}
	} while ( m );

	if ( parts.length > 1 && origPOS.exec( selector ) ) {

		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
			set = posProcess( parts[0] + parts[1], context );

		} else {
			set = Expr.relative[ parts[0] ] ?
				[ context ] :
				Sizzle( parts.shift(), context );

			while ( parts.length ) {
				selector = parts.shift();

				if ( Expr.relative[ selector ] ) {
					selector += parts.shift();
				}
				
				set = posProcess( selector, set );
			}
		}

	} else {
		// Take a shortcut and set the context if the root selector is an ID
		// (but not if it'll be faster if the inner selector is an ID)
		if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
				Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {

			ret = Sizzle.find( parts.shift(), context, contextXML );
			context = ret.expr ?
				Sizzle.filter( ret.expr, ret.set )[0] :
				ret.set[0];
		}

		if ( context ) {
			ret = seed ?
				{ expr: parts.pop(), set: makeArray(seed) } :
				Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );

			set = ret.expr ?
				Sizzle.filter( ret.expr, ret.set ) :
				ret.set;

			if ( parts.length > 0 ) {
				checkSet = makeArray( set );

			} else {
				prune = false;
			}

			while ( parts.length ) {
				cur = parts.pop();
				pop = cur;

				if ( !Expr.relative[ cur ] ) {
					cur = "";
				} else {
					pop = parts.pop();
				}

				if ( pop == null ) {
					pop = context;
				}

				Expr.relative[ cur ]( checkSet, pop, contextXML );
			}

		} else {
			checkSet = parts = [];
		}
	}

	if ( !checkSet ) {
		checkSet = set;
	}

	if ( !checkSet ) {
		Sizzle.error( cur || selector );
	}

	if ( toString.call(checkSet) === "[object Array]" ) {
		if ( !prune ) {
			results.push.apply( results, checkSet );

		} else if ( context && context.nodeType === 1 ) {
			for ( i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
					results.push( set[i] );
				}
			}

		} else {
			for ( i = 0; checkSet[i] != null; i++ ) {
				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
					results.push( set[i] );
				}
			}
		}

	} else {
		makeArray( checkSet, results );
	}

	if ( extra ) {
		Sizzle( extra, origContext, results, seed );
		Sizzle.uniqueSort( results );
	}

	return results;
};

Sizzle.uniqueSort = function( results ) {
	if ( sortOrder ) {
		hasDuplicate = baseHasDuplicate;
		results.sort( sortOrder );

		if ( hasDuplicate ) {
			for ( var i = 1; i < results.length; i++ ) {
				if ( results[i] === results[ i - 1 ] ) {
					results.splice( i--, 1 );
				}
			}
		}
	}

	return results;
};

Sizzle.matches = function( expr, set ) {
	return Sizzle( expr, null, null, set );
};

Sizzle.matchesSelector = function( node, expr ) {
	return Sizzle( expr, null, null, [node] ).length > 0;
};

Sizzle.find = function( expr, context, isXML ) {
	var set;

	if ( !expr ) {
		return [];
	}

	for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
		var match,
			type = Expr.order[i];
		
		if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
			var left = match[1];
			match.splice( 1, 1 );

			if ( left.substr( left.length - 1 ) !== "\\" ) {
				match[1] = (match[1] || "").replace( rBackslash, "" );
				set = Expr.find[ type ]( match, context, isXML );

				if ( set != null ) {
					expr = expr.replace( Expr.match[ type ], "" );
					break;
				}
			}
		}
	}

	if ( !set ) {
		set = typeof context.getElementsByTagName !== "undefined" ?
			context.getElementsByTagName( "*" ) :
			[];
	}

	return { set: set, expr: expr };
};

Sizzle.filter = function( expr, set, inplace, not ) {
	var match, anyFound,
		old = expr,
		result = [],
		curLoop = set,
		isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );

	while ( expr && set.length ) {
		for ( var type in Expr.filter ) {
			if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
				var found, item,
					filter = Expr.filter[ type ],
					left = match[1];

				anyFound = false;

				match.splice(1,1);

				if ( left.substr( left.length - 1 ) === "\\" ) {
					continue;
				}

				if ( curLoop === result ) {
					result = [];
				}

				if ( Expr.preFilter[ type ] ) {
					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );

					if ( !match ) {
						anyFound = found = true;

					} else if ( match === true ) {
						continue;
					}
				}

				if ( match ) {
					for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
						if ( item ) {
							found = filter( item, match, i, curLoop );
							var pass = not ^ !!found;

							if ( inplace && found != null ) {
								if ( pass ) {
									anyFound = true;

								} else {
									curLoop[i] = false;
								}

							} else if ( pass ) {
								result.push( item );
								anyFound = true;
							}
						}
					}
				}

				if ( found !== undefined ) {
					if ( !inplace ) {
						curLoop = result;
					}

					expr = expr.replace( Expr.match[ type ], "" );

					if ( !anyFound ) {
						return [];
					}

					break;
				}
			}
		}

		// Improper expression
		if ( expr === old ) {
			if ( anyFound == null ) {
				Sizzle.error( expr );

			} else {
				break;
			}
		}

		old = expr;
	}

	return curLoop;
};

Sizzle.error = function( msg ) {
	throw "Syntax error, unrecognized expression: " + msg;
};

var Expr = Sizzle.selectors = {
	order: [ "ID", "NAME", "TAG" ],

	match: {
		ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
		CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
		TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
		CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
		PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
	},

	leftMatch: {},

	attrMap: {
		"class": "className",
		"for": "htmlFor"
	},

	attrHandle: {
		href: function( elem ) {
			return elem.getAttribute( "href" );
		},
		type: function( elem ) {
			return elem.getAttribute( "type" );
		}
	},

	relative: {
		"+": function(checkSet, part){
			var isPartStr = typeof part === "string",
				isTag = isPartStr && !rNonWord.test( part ),
				isPartStrNotTag = isPartStr && !isTag;

			if ( isTag ) {
				part = part.toLowerCase();
			}

			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
				if ( (elem = checkSet[i]) ) {
					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}

					checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
						elem || false :
						elem === part;
				}
			}

			if ( isPartStrNotTag ) {
				Sizzle.filter( part, checkSet, true );
			}
		},

		">": function( checkSet, part ) {
			var elem,
				isPartStr = typeof part === "string",
				i = 0,
				l = checkSet.length;

			if ( isPartStr && !rNonWord.test( part ) ) {
				part = part.toLowerCase();

				for ( ; i < l; i++ ) {
					elem = checkSet[i];

					if ( elem ) {
						var parent = elem.parentNode;
						checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
					}
				}

			} else {
				for ( ; i < l; i++ ) {
					elem = checkSet[i];

					if ( elem ) {
						checkSet[i] = isPartStr ?
							elem.parentNode :
							elem.parentNode === part;
					}
				}

				if ( isPartStr ) {
					Sizzle.filter( part, checkSet, true );
				}
			}
		},

		"": function(checkSet, part, isXML){
			var nodeCheck,
				doneName = done++,
				checkFn = dirCheck;

			if ( typeof part === "string" && !rNonWord.test( part ) ) {
				part = part.toLowerCase();
				nodeCheck = part;
				checkFn = dirNodeCheck;
			}

			checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
		},

		"~": function( checkSet, part, isXML ) {
			var nodeCheck,
				doneName = done++,
				checkFn = dirCheck;

			if ( typeof part === "string" && !rNonWord.test( part ) ) {
				part = part.toLowerCase();
				nodeCheck = part;
				checkFn = dirNodeCheck;
			}

			checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
		}
	},

	find: {
		ID: function( match, context, isXML ) {
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);
				// Check parentNode to catch when Blackberry 4.6 returns
				// nodes that are no longer in the document #6963
				return m && m.parentNode ? [m] : [];
			}
		},

		NAME: function( match, context ) {
			if ( typeof context.getElementsByName !== "undefined" ) {
				var ret = [],
					results = context.getElementsByName( match[1] );

				for ( var i = 0, l = results.length; i < l; i++ ) {
					if ( results[i].getAttribute("name") === match[1] ) {
						ret.push( results[i] );
					}
				}

				return ret.length === 0 ? null : ret;
			}
		},

		TAG: function( match, context ) {
			if ( typeof context.getElementsByTagName !== "undefined" ) {
				return context.getElementsByTagName( match[1] );
			}
		}
	},
	preFilter: {
		CLASS: function( match, curLoop, inplace, result, not, isXML ) {
			match = " " + match[1].replace( rBackslash, "" ) + " ";

			if ( isXML ) {
				return match;
			}

			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
				if ( elem ) {
					if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
						if ( !inplace ) {
							result.push( elem );
						}

					} else if ( inplace ) {
						curLoop[i] = false;
					}
				}
			}

			return false;
		},

		ID: function( match ) {
			return match[1].replace( rBackslash, "" );
		},

		TAG: function( match, curLoop ) {
			return match[1].replace( rBackslash, "" ).toLowerCase();
		},

		CHILD: function( match ) {
			if ( match[1] === "nth" ) {
				if ( !match[2] ) {
					Sizzle.error( match[0] );
				}

				match[2] = match[2].replace(/^\+|\s*/g, '');

				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
				var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
					match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

				// calculate the numbers (first)n+(last) including if they are negative
				match[2] = (test[1] + (test[2] || 1)) - 0;
				match[3] = test[3] - 0;
			}
			else if ( match[2] ) {
				Sizzle.error( match[0] );
			}

			// TODO: Move to normal caching system
			match[0] = done++;

			return match;
		},

		ATTR: function( match, curLoop, inplace, result, not, isXML ) {
			var name = match[1] = match[1].replace( rBackslash, "" );
			
			if ( !isXML && Expr.attrMap[name] ) {
				match[1] = Expr.attrMap[name];
			}

			// Handle if an un-quoted value was used
			match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );

			if ( match[2] === "~=" ) {
				match[4] = " " + match[4] + " ";
			}

			return match;
		},

		PSEUDO: function( match, curLoop, inplace, result, not ) {
			if ( match[1] === "not" ) {
				// If we're dealing with a complex expression, or a simple one
				if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
					match[3] = Sizzle(match[3], null, null, curLoop);

				} else {
					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);

					if ( !inplace ) {
						result.push.apply( result, ret );
					}

					return false;
				}

			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
				return true;
			}
			
			return match;
		},

		POS: function( match ) {
			match.unshift( true );

			return match;
		}
	},
	
	filters: {
		enabled: function( elem ) {
			return elem.disabled === false && elem.type !== "hidden";
		},

		disabled: function( elem ) {
			return elem.disabled === true;
		},

		checked: function( elem ) {
			return elem.checked === true;
		},
		
		selected: function( elem ) {
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				elem.parentNode.selectedIndex;
			}
			
			return elem.selected === true;
		},

		parent: function( elem ) {
			return !!elem.firstChild;
		},

		empty: function( elem ) {
			return !elem.firstChild;
		},

		has: function( elem, i, match ) {
			return !!Sizzle( match[3], elem ).length;
		},

		header: function( elem ) {
			return (/h\d/i).test( elem.nodeName );
		},

		text: function( elem ) {
			var attr = elem.getAttribute( "type" ), type = elem.type;
			// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) 
			// use getAttribute instead to test this case
			return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
		},

		radio: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
		},

		checkbox: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
		},

		file: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
		},

		password: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
		},

		submit: function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return (name === "input" || name === "button") && "submit" === elem.type;
		},

		image: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
		},

		reset: function( elem ) {
			return elem.nodeName.toLowerCase() === "input" && "reset" === elem.type;
		},

		button: function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return name === "input" && "button" === elem.type || name === "button";
		},

		input: function( elem ) {
			return (/input|select|textarea|button/i).test( elem.nodeName );
		},

		focus: function( elem ) {
			return elem === elem.ownerDocument.activeElement;
		}
	},
	setFilters: {
		first: function( elem, i ) {
			return i === 0;
		},

		last: function( elem, i, match, array ) {
			return i === array.length - 1;
		},

		even: function( elem, i ) {
			return i % 2 === 0;
		},

		odd: function( elem, i ) {
			return i % 2 === 1;
		},

		lt: function( elem, i, match ) {
			return i < match[3] - 0;
		},

		gt: function( elem, i, match ) {
			return i > match[3] - 0;
		},

		nth: function( elem, i, match ) {
			return match[3] - 0 === i;
		},

		eq: function( elem, i, match ) {
			return match[3] - 0 === i;
		}
	},
	filter: {
		PSEUDO: function( elem, match, i, array ) {
			var name = match[1],
				filter = Expr.filters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );

			} else if ( name === "contains" ) {
				return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;

			} else if ( name === "not" ) {
				var not = match[3];

				for ( var j = 0, l = not.length; j < l; j++ ) {
					if ( not[j] === elem ) {
						return false;
					}
				}

				return true;

			} else {
				Sizzle.error( name );
			}
		},

		CHILD: function( elem, match ) {
			var type = match[1],
				node = elem;

			switch ( type ) {
				case "only":
				case "first":
					while ( (node = node.previousSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}

					if ( type === "first" ) { 
						return true; 
					}

					node = elem;

				case "last":
					while ( (node = node.nextSibling) )	 {
						if ( node.nodeType === 1 ) { 
							return false; 
						}
					}

					return true;

				case "nth":
					var first = match[2],
						last = match[3];

					if ( first === 1 && last === 0 ) {
						return true;
					}
					
					var doneName = match[0],
						parent = elem.parentNode;
	
					if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
						var count = 0;
						
						for ( node = parent.firstChild; node; node = node.nextSibling ) {
							if ( node.nodeType === 1 ) {
								node.nodeIndex = ++count;
							}
						} 

						parent.sizcache = doneName;
					}
					
					var diff = elem.nodeIndex - last;

					if ( first === 0 ) {
						return diff === 0;

					} else {
						return ( diff % first === 0 && diff / first >= 0 );
					}
			}
		},

		ID: function( elem, match ) {
			return elem.nodeType === 1 && elem.getAttribute("id") === match;
		},

		TAG: function( elem, match ) {
			return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
		},
		
		CLASS: function( elem, match ) {
			return (" " + (elem.className || elem.getAttribute("class")) + " ")
				.indexOf( match ) > -1;
		},

		ATTR: function( elem, match ) {
			var name = match[1],
				result = Expr.attrHandle[ name ] ?
					Expr.attrHandle[ name ]( elem ) :
					elem[ name ] != null ?
						elem[ name ] :
						elem.getAttribute( name ),
				value = result + "",
				type = match[2],
				check = match[4];

			return result == null ?
				type === "!=" :
				type === "=" ?
				value === check :
				type === "*=" ?
				value.indexOf(check) >= 0 :
				type === "~=" ?
				(" " + value + " ").indexOf(check) >= 0 :
				!check ?
				value && result !== false :
				type === "!=" ?
				value !== check :
				type === "^=" ?
				value.indexOf(check) === 0 :
				type === "$=" ?
				value.substr(value.length - check.length) === check :
				type === "|=" ?
				value === check || value.substr(0, check.length + 1) === check + "-" :
				false;
		},

		POS: function( elem, match, i, array ) {
			var name = match[2],
				filter = Expr.setFilters[ name ];

			if ( filter ) {
				return filter( elem, i, match, array );
			}
		}
	}
};

var origPOS = Expr.match.POS,
	fescape = function(all, num){
		return "\\" + (num - 0 + 1);
	};

for ( var type in Expr.match ) {
	Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
	Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}

var makeArray = function( array, results ) {
	array = Array.prototype.slice.call( array, 0 );

	if ( results ) {
		results.push.apply( results, array );
		return results;
	}
	
	return array;
};

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
	Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;

// Provide a fallback method if it does not work
} catch( e ) {
	makeArray = function( array, results ) {
		var i = 0,
			ret = results || [];

		if ( toString.call(array) === "[object Array]" ) {
			Array.prototype.push.apply( ret, array );

		} else {
			if ( typeof array.length === "number" ) {
				for ( var l = array.length; i < l; i++ ) {
					ret.push( array[i] );
				}

			} else {
				for ( ; array[i]; i++ ) {
					ret.push( array[i] );
				}
			}
		}

		return ret;
	};
}

var sortOrder, siblingCheck;

if ( document.documentElement.compareDocumentPosition ) {
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
			return a.compareDocumentPosition ? -1 : 1;
		}

		return a.compareDocumentPosition(b) & 4 ? -1 : 1;
	};

} else {
	sortOrder = function( a, b ) {
		var al, bl,
			ap = [],
			bp = [],
			aup = a.parentNode,
			bup = b.parentNode,
			cur = aup;

		// The nodes are identical, we can exit early
		if ( a === b ) {
			hasDuplicate = true;
			return 0;

		// If the nodes are siblings (or identical) we can do a quick check
		} else if ( aup === bup ) {
			return siblingCheck( a, b );

		// If no parents were found then the nodes are disconnected
		} else if ( !aup ) {
			return -1;

		} else if ( !bup ) {
			return 1;
		}

		// Otherwise they're somewhere else in the tree so we need
		// to build up a full list of the parentNodes for comparison
		while ( cur ) {
			ap.unshift( cur );
			cur = cur.parentNode;
		}

		cur = bup;

		while ( cur ) {
			bp.unshift( cur );
			cur = cur.parentNode;
		}

		al = ap.length;
		bl = bp.length;

		// Start walking down the tree looking for a discrepancy
		for ( var i = 0; i < al && i < bl; i++ ) {
			if ( ap[i] !== bp[i] ) {
				return siblingCheck( ap[i], bp[i] );
			}
		}

		// We ended someplace up the tree so do a sibling check
		return i === al ?
			siblingCheck( a, bp[i], -1 ) :
			siblingCheck( ap[i], b, 1 );
	};

	siblingCheck = function( a, b, ret ) {
		if ( a === b ) {
			return ret;
		}

		var cur = a.nextSibling;

		while ( cur ) {
			if ( cur === b ) {
				return -1;
			}

			cur = cur.nextSibling;
		}

		return 1;
	};
}

// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
	var ret = "", elem;

	for ( var i = 0; elems[i]; i++ ) {
		elem = elems[i];

		// Get the text from text nodes and CDATA nodes
		if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
			ret += elem.nodeValue;

		// Traverse everything else, except comment nodes
		} else if ( elem.nodeType !== 8 ) {
			ret += Sizzle.getText( elem.childNodes );
		}
	}

	return ret;
};

// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
	// We're going to inject a fake input element with a specified name
	var form = document.createElement("div"),
		id = "script" + (new Date()).getTime(),
		root = document.documentElement;

	form.innerHTML = "<a name='" + id + "'/>";

	// Inject it into the root element, check its status, and remove it quickly
	root.insertBefore( form, root.firstChild );

	// The workaround has to do additional checks after a getElementById
	// Which slows things down for other browsers (hence the branching)
	if ( document.getElementById( id ) ) {
		Expr.find.ID = function( match, context, isXML ) {
			if ( typeof context.getElementById !== "undefined" && !isXML ) {
				var m = context.getElementById(match[1]);

				return m ?
					m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
						[m] :
						undefined :
					[];
			}
		};

		Expr.filter.ID = function( elem, match ) {
			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");

			return elem.nodeType === 1 && node && node.nodeValue === match;
		};
	}

	root.removeChild( form );

	// release memory in IE
	root = form = null;
})();

(function(){
	// Check to see if the browser returns only elements
	// when doing getElementsByTagName("*")

	// Create a fake element
	var div = document.createElement("div");
	div.appendChild( document.createComment("") );

	// Make sure no comments are found
	if ( div.getElementsByTagName("*").length > 0 ) {
		Expr.find.TAG = function( match, context ) {
			var results = context.getElementsByTagName( match[1] );

			// Filter out possible comments
			if ( match[1] === "*" ) {
				var tmp = [];

				for ( var i = 0; results[i]; i++ ) {
					if ( results[i].nodeType === 1 ) {
						tmp.push( results[i] );
					}
				}

				results = tmp;
			}

			return results;
		};
	}

	// Check to see if an attribute returns normalized href attributes
	div.innerHTML = "<a href='#'></a>";

	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
			div.firstChild.getAttribute("href") !== "#" ) {

		Expr.attrHandle.href = function( elem ) {
			return elem.getAttribute( "href", 2 );
		};
	}

	// release memory in IE
	div = null;
})();

if ( document.querySelectorAll ) {
	(function(){
		var oldSizzle = Sizzle,
			div = document.createElement("div"),
			id = "__sizzle__";

		div.innerHTML = "<p class='TEST'></p>";

		// Safari can't handle uppercase or unicode characters when
		// in quirks mode.
		if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
			return;
		}
	
		Sizzle = function( query, context, extra, seed ) {
			context = context || document;

			// Only use querySelectorAll on non-XML documents
			// (ID selectors don't work in non-HTML documents)
			if ( !seed && !Sizzle.isXML(context) ) {
				// See if we find a selector to speed up
				var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
				
				if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
					// Speed-up: Sizzle("TAG")
					if ( match[1] ) {
						return makeArray( context.getElementsByTagName( query ), extra );
					
					// Speed-up: Sizzle(".CLASS")
					} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
						return makeArray( context.getElementsByClassName( match[2] ), extra );
					}
				}
				
				if ( context.nodeType === 9 ) {
					// Speed-up: Sizzle("body")
					// The body element only exists once, optimize finding it
					if ( query === "body" && context.body ) {
						return makeArray( [ context.body ], extra );
						
					// Speed-up: Sizzle("#ID")
					} else if ( match && match[3] ) {
						var elem = context.getElementById( match[3] );

						// Check parentNode to catch when Blackberry 4.6 returns
						// nodes that are no longer in the document #6963
						if ( elem && elem.parentNode ) {
							// Handle the case where IE and Opera return items
							// by name instead of ID
							if ( elem.id === match[3] ) {
								return makeArray( [ elem ], extra );
							}
							
						} else {
							return makeArray( [], extra );
						}
					}
					
					try {
						return makeArray( context.querySelectorAll(query), extra );
					} catch(qsaError) {}

				// qSA works strangely on Element-rooted queries
				// We can work around this by specifying an extra ID on the root
				// and working up from there (Thanks to Andrew Dupont for the technique)
				// IE 8 doesn't work on object elements
				} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
					var oldContext = context,
						old = context.getAttribute( "id" ),
						nid = old || id,
						hasParent = context.parentNode,
						relativeHierarchySelector = /^\s*[+~]/.test( query );

					if ( !old ) {
						context.setAttribute( "id", nid );
					} else {
						nid = nid.replace( /'/g, "\\$&" );
					}
					if ( relativeHierarchySelector && hasParent ) {
						context = context.parentNode;
					}

					try {
						if ( !relativeHierarchySelector || hasParent ) {
							return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
						}

					} catch(pseudoError) {
					} finally {
						if ( !old ) {
							oldContext.removeAttribute( "id" );
						}
					}
				}
			}
		
			return oldSizzle(query, context, extra, seed);
		};

		for ( var prop in oldSizzle ) {
			Sizzle[ prop ] = oldSizzle[ prop ];
		}

		// release memory in IE
		div = null;
	})();
}

(function(){
	var html = document.documentElement,
		matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;

	if ( matches ) {
		// Check to see if it's possible to do matchesSelector
		// on a disconnected node (IE 9 fails this)
		var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
			pseudoWorks = false;

		try {
			// This should fail with an exception
			// Gecko does not error, returns false instead
			matches.call( document.documentElement, "[test!='']:sizzle" );
	
		} catch( pseudoError ) {
			pseudoWorks = true;
		}

		Sizzle.matchesSelector = function( node, expr ) {
			// Make sure that attribute selectors are quoted
			expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");

			if ( !Sizzle.isXML( node ) ) {
				try { 
					if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
						var ret = matches.call( node, expr );

						// IE 9's matchesSelector returns false on disconnected nodes
						if ( ret || !disconnectedMatch ||
								// As well, disconnected nodes are said to be in a document
								// fragment in IE 9, so check for that
								node.document && node.document.nodeType !== 11 ) {
							return ret;
						}
					}
				} catch(e) {}
			}

			return Sizzle(expr, null, null, [node]).length > 0;
		};
	}
})();

(function(){
	var div = document.createElement("div");

	div.innerHTML = "<div class='test e'></div><div class='test'></div>";

	// Opera can't find a second classname (in 9.6)
	// Also, make sure that getElementsByClassName actually exists
	if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
		return;
	}

	// Safari caches class attributes, doesn't catch changes (in 3.2)
	div.lastChild.className = "e";

	if ( div.getElementsByClassName("e").length === 1 ) {
		return;
	}
	
	Expr.order.splice(1, 0, "CLASS");
	Expr.find.CLASS = function( match, context, isXML ) {
		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
			return context.getElementsByClassName(match[1]);
		}
	};

	// release memory in IE
	div = null;
})();

function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];

		if ( elem ) {
			var match = false;

			elem = elem[dir];

			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 && !isXML ){
					elem.sizcache = doneName;
					elem.sizset = i;
				}

				if ( elem.nodeName.toLowerCase() === cur ) {
					match = elem;
					break;
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
		var elem = checkSet[i];

		if ( elem ) {
			var match = false;
			
			elem = elem[dir];

			while ( elem ) {
				if ( elem.sizcache === doneName ) {
					match = checkSet[elem.sizset];
					break;
				}

				if ( elem.nodeType === 1 ) {
					if ( !isXML ) {
						elem.sizcache = doneName;
						elem.sizset = i;
					}

					if ( typeof cur !== "string" ) {
						if ( elem === cur ) {
							match = true;
							break;
						}

					} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
						match = elem;
						break;
					}
				}

				elem = elem[dir];
			}

			checkSet[i] = match;
		}
	}
}

if ( document.documentElement.contains ) {
	Sizzle.contains = function( a, b ) {
		return a !== b && (a.contains ? a.contains(b) : true);
	};

} else if ( document.documentElement.compareDocumentPosition ) {
	Sizzle.contains = function( a, b ) {
		return !!(a.compareDocumentPosition(b) & 16);
	};

} else {
	Sizzle.contains = function() {
		return false;
	};
}

Sizzle.isXML = function( elem ) {
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833) 
	var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;

	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

var posProcess = function( selector, context ) {
	var match,
		tmpSet = [],
		later = "",
		root = context.nodeType ? [context] : context;

	// Position selectors must be done after the filter
	// And so must :not(positional) so we move all PSEUDOs to the end
	while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
		later += match[0];
		selector = selector.replace( Expr.match.PSEUDO, "" );
	}

	selector = Expr.relative[selector] ? selector + "*" : selector;

	for ( var i = 0, l = root.length; i < l; i++ ) {
		Sizzle( selector, root[i], tmpSet );
	}

	return Sizzle.filter( later, tmpSet );
};

// EXPOSE
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;


})();


var runtil = /Until$/,
	rparentsprev = /^(?:parents|prevUntil|prevAll)/,
	// Note: This RegExp should be improved, or likely pulled from Sizzle
	rmultiselector = /,/,
	isSimple = /^.[^:#\[\.,]*$/,
	slice = Array.prototype.slice,
	POS = jQuery.expr.match.POS,
	// methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend({
	find: function( selector ) {
		var self = this,
			i, l;

		if ( typeof selector !== "string" ) {
			return jQuery( selector ).filter(function() {
				for ( i = 0, l = self.length; i < l; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			});
		}

		var ret = this.pushStack( "", "find", selector ),
			length, n, r;

		for ( i = 0, l = this.length; i < l; i++ ) {
			length = ret.length;
			jQuery.find( selector, this[i], ret );

			if ( i > 0 ) {
				// Make sure that the results are unique
				for ( n = length; n < ret.length; n++ ) {
					for ( r = 0; r < length; r++ ) {
						if ( ret[r] === ret[n] ) {
							ret.splice(n--, 1);
							break;
						}
					}
				}
			}
		}

		return ret;
	},

	has: function( target ) {
		var targets = jQuery( target );
		return this.filter(function() {
			for ( var i = 0, l = targets.length; i < l; i++ ) {
				if ( jQuery.contains( this, targets[i] ) ) {
					return true;
				}
			}
		});
	},

	not: function( selector ) {
		return this.pushStack( winnow(this, selector, false), "not", selector);
	},

	filter: function( selector ) {
		return this.pushStack( winnow(this, selector, true), "filter", selector );
	},

	is: function( selector ) {
		return !!selector && ( typeof selector === "string" ?
			jQuery.filter( selector, this ).length > 0 :
			this.filter( selector ).length > 0 );
	},

	closest: function( selectors, context ) {
		var ret = [], i, l, cur = this[0];
		
		// Array
		if ( jQuery.isArray( selectors ) ) {
			var match, selector,
				matches = {},
				level = 1;

			if ( cur && selectors.length ) {
				for ( i = 0, l = selectors.length; i < l; i++ ) {
					selector = selectors[i];

					if ( !matches[ selector ] ) {
						matches[ selector ] = POS.test( selector ) ?
							jQuery( selector, context || this.context ) :
							selector;
					}
				}

				while ( cur && cur.ownerDocument && cur !== context ) {
					for ( selector in matches ) {
						match = matches[ selector ];

						if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) {
							ret.push({ selector: selector, elem: cur, level: level });
						}
					}

					cur = cur.parentNode;
					level++;
				}
			}

			return ret;
		}

		// String
		var pos = POS.test( selectors ) || typeof selectors !== "string" ?
				jQuery( selectors, context || this.context ) :
				0;

		for ( i = 0, l = this.length; i < l; i++ ) {
			cur = this[i];

			while ( cur ) {
				if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
					ret.push( cur );
					break;

				} else {
					cur = cur.parentNode;
					if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
						break;
					}
				}
			}
		}

		ret = ret.length > 1 ? jQuery.unique( ret ) : ret;

		return this.pushStack( ret, "closest", selectors );
	},

	// Determine the position of an element within
	// the matched set of elements
	index: function( elem ) {
		if ( !elem || typeof elem === "string" ) {
			return jQuery.inArray( this[0],
				// If it receives a string, the selector is used
				// If it receives nothing, the siblings are used
				elem ? jQuery( elem ) : this.parent().children() );
		}
		// Locate the position of the desired element
		return jQuery.inArray(
			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[0] : elem, this );
	},

	add: function( selector, context ) {
		var set = typeof selector === "string" ?
				jQuery( selector, context ) :
				jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
			all = jQuery.merge( this.get(), set );

		return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
			all :
			jQuery.unique( all ) );
	},

	andSelf: function() {
		return this.add( this.prevObject );
	}
});

// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
	return !node || !node.parentNode || node.parentNode.nodeType === 11;
}

jQuery.each({
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return jQuery.dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return jQuery.nth( elem, 2, "nextSibling" );
	},
	prev: function( elem ) {
		return jQuery.nth( elem, 2, "previousSibling" );
	},
	nextAll: function( elem ) {
		return jQuery.dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return jQuery.dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return jQuery.dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return jQuery.sibling( elem.parentNode.firstChild, elem );
	},
	children: function( elem ) {
		return jQuery.sibling( elem.firstChild );
	},
	contents: function( elem ) {
		return jQuery.nodeName( elem, "iframe" ) ?
			elem.contentDocument || elem.contentWindow.document :
			jQuery.makeArray( elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var ret = jQuery.map( this, fn, until ),
			// The variable 'args' was introduced in
			// https://github.com/jquery/jquery/commit/52a0238
			// to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed.
			// http://code.google.com/p/v8/issues/detail?id=1050
			args = slice.call(arguments);

		if ( !runtil.test( name ) ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			ret = jQuery.filter( selector, ret );
		}

		ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;

		if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
			ret = ret.reverse();
		}

		return this.pushStack( ret, name, args.join(",") );
	};
});

jQuery.extend({
	filter: function( expr, elems, not ) {
		if ( not ) {
			expr = ":not(" + expr + ")";
		}

		return elems.length === 1 ?
			jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
			jQuery.find.matches(expr, elems);
	},

	dir: function( elem, dir, until ) {
		var matched = [],
			cur = elem[ dir ];

		while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
			if ( cur.nodeType === 1 ) {
				matched.push( cur );
			}
			cur = cur[dir];
		}
		return matched;
	},

	nth: function( cur, result, dir, elem ) {
		result = result || 1;
		var num = 0;

		for ( ; cur; cur = cur[dir] ) {
			if ( cur.nodeType === 1 && ++num === result ) {
				break;
			}
		}

		return cur;
	},

	sibling: function( n, elem ) {
		var r = [];

		for ( ; n; n = n.nextSibling ) {
			if ( n.nodeType === 1 && n !== elem ) {
				r.push( n );
			}
		}

		return r;
	}
});

// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {

	// Can't pass null or undefined to indexOf in Firefox 4
	// Set to 0 to skip string check
	qualifier = qualifier || 0;

	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep(elements, function( elem, i ) {
			var retVal = !!qualifier.call( elem, i, elem );
			return retVal === keep;
		});

	} else if ( qualifier.nodeType ) {
		return jQuery.grep(elements, function( elem, i ) {
			return (elem === qualifier) === keep;
		});

	} else if ( typeof qualifier === "string" ) {
		var filtered = jQuery.grep(elements, function( elem ) {
			return elem.nodeType === 1;
		});

		if ( isSimple.test( qualifier ) ) {
			return jQuery.filter(qualifier, filtered, !keep);
		} else {
			qualifier = jQuery.filter( qualifier, filtered );
		}
	}

	return jQuery.grep(elements, function( elem, i ) {
		return (jQuery.inArray( elem, qualifier ) >= 0) === keep;
	});
}




var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
	rleadingWhitespace = /^\s+/,
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
	rtagName = /<([\w:]+)/,
	rtbody = /<tbody/i,
	rhtml = /<|&#?\w+;/,
	rnocache = /<(?:script|object|embed|option|style)/i,
	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptType = /\/(java|ecma)script/i,
	wrapMap = {
		option: [ 1, "<select multiple='multiple'>", "</select>" ],
		legend: [ 1, "<fieldset>", "</fieldset>" ],
		thead: [ 1, "<table>", "</table>" ],
		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
		col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
		area: [ 1, "<map>", "</map>" ],
		_default: [ 0, "", "" ]
	};

wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;

// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
	wrapMap._default = [ 1, "div<div>", "</div>" ];
}

jQuery.fn.extend({
	text: function( text ) {
		if ( jQuery.isFunction(text) ) {
			return this.each(function(i) {
				var self = jQuery( this );

				self.text( text.call(this, i, self.text()) );
			});
		}

		if ( typeof text !== "object" && text !== undefined ) {
			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
		}

		return jQuery.text( this );
	},

	wrapAll: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapAll( html.call(this, i) );
			});
		}

		if ( this[0] ) {
			// The elements to wrap the target around
			var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);

			if ( this[0].parentNode ) {
				wrap.insertBefore( this[0] );
			}

			wrap.map(function() {
				var elem = this;

				while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
					elem = elem.firstChild;
				}

				return elem;
			}).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each(function(i) {
				jQuery(this).wrapInner( html.call(this, i) );
			});
		}

		return this.each(function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		});
	},

	wrap: function( html ) {
		return this.each(function() {
			jQuery( this ).wrapAll( html );
		});
	},

	unwrap: function() {
		return this.parent().each(function() {
			if ( !jQuery.nodeName( this, "body" ) ) {
				jQuery( this ).replaceWith( this.childNodes );
			}
		}).end();
	},

	append: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 ) {
				this.appendChild( elem );
			}
		});
	},

	prepend: function() {
		return this.domManip(arguments, true, function( elem ) {
			if ( this.nodeType === 1 ) {
				this.insertBefore( elem, this.firstChild );
			}
		});
	},

	before: function() {
		if ( this[0] && this[0].parentNode ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this );
			});
		} else if ( arguments.length ) {
			var set = jQuery(arguments[0]);
			set.push.apply( set, this.toArray() );
			return this.pushStack( set, "before", arguments );
		}
	},

	after: function() {
		if ( this[0] && this[0].parentNode ) {
			return this.domManip(arguments, false, function( elem ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			});
		} else if ( arguments.length ) {
			var set = this.pushStack( this, "after", arguments );
			set.push.apply( set, jQuery(arguments[0]).toArray() );
			return set;
		}
	},

	// keepData is for internal use only--do not document
	remove: function( selector, keepData ) {
		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
			if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
				if ( !keepData && elem.nodeType === 1 ) {
					jQuery.cleanData( elem.getElementsByTagName("*") );
					jQuery.cleanData( [ elem ] );
				}

				if ( elem.parentNode ) {
					elem.parentNode.removeChild( elem );
				}
			}
		}

		return this;
	},

	empty: function() {
		for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
			// Remove element nodes and prevent memory leaks
			if ( elem.nodeType === 1 ) {
				jQuery.cleanData( elem.getElementsByTagName("*") );
			}

			// Remove any remaining nodes
			while ( elem.firstChild ) {
				elem.removeChild( elem.firstChild );
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function () {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		});
	},

	html: function( value ) {
		if ( value === undefined ) {
			return this[0] && this[0].nodeType === 1 ?
				this[0].innerHTML.replace(rinlinejQuery, "") :
				null;

		// See if we can take a shortcut and just use innerHTML
		} else if ( typeof value === "string" && !rnocache.test( value ) &&
			(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
			!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {

			value = value.replace(rxhtmlTag, "<$1></$2>");

			try {
				for ( var i = 0, l = this.length; i < l; i++ ) {
					// Remove element nodes and prevent memory leaks
					if ( this[i].nodeType === 1 ) {
						jQuery.cleanData( this[i].getElementsByTagName("*") );
						this[i].innerHTML = value;
					}
				}

			// If using innerHTML throws an exception, use the fallback method
			} catch(e) {
				this.empty().append( value );
			}

		} else if ( jQuery.isFunction( value ) ) {
			this.each(function(i){
				var self = jQuery( this );

				self.html( value.call(this, i, self.html()) );
			});

		} else {
			this.empty().append( value );
		}

		return this;
	},

	replaceWith: function( value ) {
		if ( this[0] && this[0].parentNode ) {
			// Make sure that the elements are removed from the DOM before they are inserted
			// this can help fix replacing a parent with child elements
			if ( jQuery.isFunction( value ) ) {
				return this.each(function(i) {
					var self = jQuery(this), old = self.html();
					self.replaceWith( value.call( this, i, old ) );
				});
			}

			if ( typeof value !== "string" ) {
				value = jQuery( value ).detach();
			}

			return this.each(function() {
				var next = this.nextSibling,
					parent = this.parentNode;

				jQuery( this ).remove();

				if ( next ) {
					jQuery(next).before( value );
				} else {
					jQuery(parent).append( value );
				}
			});
		} else {
			return this.length ?
				this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
				this;
		}
	},

	detach: function( selector ) {
		return this.remove( selector, true );
	},

	domManip: function( args, table, callback ) {
		var results, first, fragment, parent,
			value = args[0],
			scripts = [];

		// We can't cloneNode fragments that contain checked, in WebKit
		if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
			return this.each(function() {
				jQuery(this).domManip( args, table, callback, true );
			});
		}

		if ( jQuery.isFunction(value) ) {
			return this.each(function(i) {
				var self = jQuery(this);
				args[0] = value.call(this, i, table ? self.html() : undefined);
				self.domManip( args, table, callback );
			});
		}

		if ( this[0] ) {
			parent = value && value.parentNode;

			// If we're in a fragment, just use that instead of building a new one
			if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
				results = { fragment: parent };

			} else {
				results = jQuery.buildFragment( args, this, scripts );
			}

			fragment = results.fragment;

			if ( fragment.childNodes.length === 1 ) {
				first = fragment = fragment.firstChild;
			} else {
				first = fragment.firstChild;
			}

			if ( first ) {
				table = table && jQuery.nodeName( first, "tr" );

				for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
					callback.call(
						table ?
							root(this[i], first) :
							this[i],
						// Make sure that we do not leak memory by inadvertently discarding
						// the original fragment (which might have attached data) instead of
						// using it; in addition, use the original fragment object for the last
						// item instead of first because it can end up being emptied incorrectly
						// in certain situations (Bug #8070).
						// Fragments from the fragment cache must always be cloned and never used
						// in place.
						results.cacheable || (l > 1 && i < lastIndex) ?
							jQuery.clone( fragment, true, true ) :
							fragment
					);
				}
			}

			if ( scripts.length ) {
				jQuery.each( scripts, evalScript );
			}
		}

		return this;
	}
});

function root( elem, cur ) {
	return jQuery.nodeName(elem, "table") ?
		(elem.getElementsByTagName("tbody")[0] ||
		elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
		elem;
}

function cloneCopyEvent( src, dest ) {

	if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
		return;
	}

	var internalKey = jQuery.expando,
		oldData = jQuery.data( src ),
		curData = jQuery.data( dest, oldData );

	// Switch to use the internal data object, if it exists, for the next
	// stage of data copying
	if ( (oldData = oldData[ internalKey ]) ) {
		var events = oldData.events;
				curData = curData[ internalKey ] = jQuery.extend({}, oldData);

		if ( events ) {
			delete curData.handle;
			curData.events = {};

			for ( var type in events ) {
				for ( var i = 0, l = events[ type ].length; i < l; i++ ) {
					jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
				}
			}
		}
	}
}

function cloneFixAttributes( src, dest ) {
	var nodeName;

	// We do not need to do anything for non-Elements
	if ( dest.nodeType !== 1 ) {
		return;
	}

	// clearAttributes removes the attributes, which we don't want,
	// but also removes the attachEvent events, which we *do* want
	if ( dest.clearAttributes ) {
		dest.clearAttributes();
	}

	// mergeAttributes, in contrast, only merges back on the
	// original attributes, not the events
	if ( dest.mergeAttributes ) {
		dest.mergeAttributes( src );
	}

	nodeName = dest.nodeName.toLowerCase();

	// IE6-8 fail to clone children inside object elements that use
	// the proprietary classid attribute value (rather than the type
	// attribute) to identify the type of content to display
	if ( nodeName === "object" ) {
		dest.outerHTML = src.outerHTML;

	} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
		// IE6-8 fails to persist the checked state of a cloned checkbox
		// or radio button. Worse, IE6-7 fail to give the cloned element
		// a checked appearance if the defaultChecked value isn't also set
		if ( src.checked ) {
			dest.defaultChecked = dest.checked = src.checked;
		}

		// IE6-7 get confused and end up setting the value of a cloned
		// checkbox/radio button to an empty string instead of "on"
		if ( dest.value !== src.value ) {
			dest.value = src.value;
		}

	// IE6-8 fails to return the selected option to the default selected
	// state when cloning options
	} else if ( nodeName === "option" ) {
		dest.selected = src.defaultSelected;

	// IE6-8 fails to set the defaultValue to the correct value when
	// cloning other types of input fields
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}

	// Event data gets referenced instead of copied if the expando
	// gets copied too
	dest.removeAttribute( jQuery.expando );
}

jQuery.buildFragment = function( args, nodes, scripts ) {
	var fragment, cacheable, cacheresults,
		doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);

	// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
	// Cloning options loses the selected state, so don't cache them
	// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
	// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
	if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
		args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {

		cacheable = true;

		cacheresults = jQuery.fragments[ args[0] ];
		if ( cacheresults && cacheresults !== 1 ) {
			fragment = cacheresults;
		}
	}

	if ( !fragment ) {
		fragment = doc.createDocumentFragment();
		jQuery.clean( args, doc, fragment, scripts );
	}

	if ( cacheable ) {
		jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
	}

	return { fragment: fragment, cacheable: cacheable };
};

jQuery.fragments = {};

jQuery.each({
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var ret = [],
			insert = jQuery( selector ),
			parent = this.length === 1 && this[0].parentNode;

		if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
			insert[ original ]( this[0] );
			return this;

		} else {
			for ( var i = 0, l = insert.length; i < l; i++ ) {
				var elems = (i > 0 ? this.clone(true) : this).get();
				jQuery( insert[i] )[ original ]( elems );
				ret = ret.concat( elems );
			}

			return this.pushStack( ret, name, insert.selector );
		}
	};
});

function getAll( elem ) {
	if ( "getElementsByTagName" in elem ) {
		return elem.getElementsByTagName( "*" );
	
	} else if ( "querySelectorAll" in elem ) {
		return elem.querySelectorAll( "*" );

	} else {
		return [];
	}
}

// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
	if ( elem.type === "checkbox" || elem.type === "radio" ) {
		elem.defaultChecked = elem.checked;
	}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
	if ( jQuery.nodeName( elem, "input" ) ) {
		fixDefaultChecked( elem );
	} else if ( elem.getElementsByTagName ) {
		jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
	}
}

jQuery.extend({
	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var clone = elem.cloneNode(true),
				srcElements,
				destElements,
				i;

		if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
				(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
			// IE copies events bound via attachEvent when using cloneNode.
			// Calling detachEvent on the clone will also remove the events
			// from the original. In order to get around this, we use some
			// proprietary methods to clear the events. Thanks to MooTools
			// guys for this hotness.

			cloneFixAttributes( elem, clone );

			// Using Sizzle here is crazy slow, so we use getElementsByTagName
			// instead
			srcElements = getAll( elem );
			destElements = getAll( clone );

			// Weird iteration because IE will replace the length property
			// with an element if you are cloning the body and one of the
			// elements on the page has a name or id of "length"
			for ( i = 0; srcElements[i]; ++i ) {
				cloneFixAttributes( srcElements[i], destElements[i] );
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			cloneCopyEvent( elem, clone );

			if ( deepDataAndEvents ) {
				srcElements = getAll( elem );
				destElements = getAll( clone );

				for ( i = 0; srcElements[i]; ++i ) {
					cloneCopyEvent( srcElements[i], destElements[i] );
				}
			}
		}

		// Return the cloned set
		return clone;
	},

	clean: function( elems, context, fragment, scripts ) {
		var checkScriptType;

		context = context || document;

		// !context.createElement fails in IE with an error but returns typeof 'object'
		if ( typeof context.createElement === "undefined" ) {
			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
		}

		var ret = [];

		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			if ( typeof elem === "number" ) {
				elem += "";
			}

			if ( !elem ) {
				continue;
			}

			// Convert html string into DOM nodes
			if ( typeof elem === "string" ) {
				if ( !rhtml.test( elem ) ) {
					elem = context.createTextNode( elem );
				} else {
					// Fix "XHTML"-style tags in all browsers
					elem = elem.replace(rxhtmlTag, "<$1></$2>");

					// Trim whitespace, otherwise indexOf won't work as expected
					var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(),
						wrap = wrapMap[ tag ] || wrapMap._default,
						depth = wrap[0],
						div = context.createElement("div");

					// Go to html and back, then peel off extra wrappers
					div.innerHTML = wrap[1] + elem + wrap[2];

					// Move to the right depth
					while ( depth-- ) {
						div = div.lastChild;
					}

					// Remove IE's autoinserted <tbody> from table fragments
					if ( !jQuery.support.tbody ) {

						// String was a <table>, *may* have spurious <tbody>
						var hasBody = rtbody.test(elem),
							tbody = tag === "table" && !hasBody ?
								div.firstChild && div.firstChild.childNodes :

								// String was a bare <thead> or <tfoot>
								wrap[1] === "<table>" && !hasBody ?
									div.childNodes :
									[];

						for ( var j = tbody.length - 1; j >= 0 ; --j ) {
							if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
								tbody[ j ].parentNode.removeChild( tbody[ j ] );
							}
						}
					}

					// IE completely kills leading whitespace when innerHTML is used
					if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
						div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
					}

					elem = div.childNodes;
				}
			}

			// Resets defaultChecked for any radios and checkboxes
			// about to be appended to the DOM in IE 6/7 (#8060)
			var len;
			if ( !jQuery.support.appendChecked ) {
				if ( elem[0] && typeof (len = elem.length) === "number" ) {
					for ( i = 0; i < len; i++ ) {
						findInputs( elem[i] );
					}
				} else {
					findInputs( elem );
				}
			}

			if ( elem.nodeType ) {
				ret.push( elem );
			} else {
				ret = jQuery.merge( ret, elem );
			}
		}

		if ( fragment ) {
			checkScriptType = function( elem ) {
				return !elem.type || rscriptType.test( elem.type );
			};
			for ( i = 0; ret[i]; i++ ) {
				if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
					scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );

				} else {
					if ( ret[i].nodeType === 1 ) {
						var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );

						ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
					}
					fragment.appendChild( ret[i] );
				}
			}
		}

		return ret;
	},

	cleanData: function( elems ) {
		var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special,
			deleteExpando = jQuery.support.deleteExpando;

		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
				continue;
			}

			id = elem[ jQuery.expando ];

			if ( id ) {
				data = cache[ id ] && cache[ id ][ internalKey ];

				if ( data && data.events ) {
					for ( var type in data.events ) {
						if ( special[ type ] ) {
							jQuery.event.remove( elem, type );

						// This is a shortcut to avoid jQuery.event.remove's overhead
						} else {
							jQuery.removeEvent( elem, type, data.handle );
						}
					}

					// Null the DOM reference to avoid IE6/7/8 leak (#7054)
					if ( data.handle ) {
						data.handle.elem = null;
					}
				}

				if ( deleteExpando ) {
					delete elem[ jQuery.expando ];

				} else if ( elem.removeAttribute ) {
					elem.removeAttribute( jQuery.expando );
				}

				delete cache[ id ];
			}
		}
	}
});

function evalScript( i, elem ) {
	if ( elem.src ) {
		jQuery.ajax({
			url: elem.src,
			async: false,
			dataType: "script"
		});
	} else {
		jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
	}

	if ( elem.parentNode ) {
		elem.parentNode.removeChild( elem );
	}
}




var ralpha = /alpha\([^)]*\)/i,
	ropacity = /opacity=([^)]*)/,
	rdashAlpha = /-([a-z])/ig,
	// fixed for IE9, see #8346
	rupper = /([A-Z]|^ms)/g,
	rnumpx = /^-?\d+(?:px)?$/i,
	rnum = /^-?\d/,
	rrelNum = /^[+\-]=/,
	rrelNumFilter = /[^+\-\.\de]+/g,

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssWidth = [ "Left", "Right" ],
	cssHeight = [ "Top", "Bottom" ],
	curCSS,

	getComputedStyle,
	currentStyle,

	fcamelCase = function( all, letter ) {
		return letter.toUpperCase();
	};

jQuery.fn.css = function( name, value ) {
	// Setting 'undefined' is a no-op
	if ( arguments.length === 2 && value === undefined ) {
		return this;
	}

	return jQuery.access( this, name, value, true, function( elem, name, value ) {
		return value !== undefined ?
			jQuery.style( elem, name, value ) :
			jQuery.css( elem, name );
	});
};

jQuery.extend({
	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {
					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity", "opacity" );
					return ret === "" ? "1" : ret;

				} else {
					return elem.style.opacity;
				}
			}
		}
	},

	// Exclude the following css properties to add px
	cssNumber: {
		"zIndex": true,
		"fontWeight": true,
		"opacity": true,
		"zoom": true,
		"lineHeight": true,
		"widows": true,
		"orphans": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {
		// normalize float css property
		"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
	},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {
		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, origName = jQuery.camelCase( name ),
			style = elem.style, hooks = jQuery.cssHooks[ origName ];

		name = jQuery.cssProps[ origName ] || origName;

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// Make sure that NaN and null values aren't set. See: #7116
			if ( type === "number" && isNaN( value ) || value == null ) {
				return;
			}

			// convert relative number strings (+= or -=) to relative numbers. #7345
			if ( type === "string" && rrelNum.test( value ) ) {
				value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) );
			}

			// If a number was passed in, add 'px' to the (except for certain CSS properties)
			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
				value += "px";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
				// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
				// Fixes bug #5509
				try {
					style[ name ] = value;
				} catch(e) {}
			}

		} else {
			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra ) {
		var ret, hooks;

		// Make sure that we're working with the right name
		name = jQuery.camelCase( name );
		hooks = jQuery.cssHooks[ name ];
		name = jQuery.cssProps[ name ] || name;

		// cssFloat needs a special treatment
		if ( name === "cssFloat" ) {
			name = "float";
		}

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
			return ret;

		// Otherwise, if a way to get the computed value exists, use that
		} else if ( curCSS ) {
			return curCSS( elem, name );
		}
	},

	// A method for quickly swapping in/out CSS properties to get correct calculations
	swap: function( elem, options, callback ) {
		var old = {};

		// Remember the old values, and insert the new ones
		for ( var name in options ) {
			old[ name ] = elem.style[ name ];
			elem.style[ name ] = options[ name ];
		}

		callback.call( elem );

		// Revert the old values
		for ( name in options ) {
			elem.style[ name ] = old[ name ];
		}
	},

	camelCase: function( string ) {
		return string.replace( rdashAlpha, fcamelCase );
	}
});

// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;

jQuery.each(["height", "width"], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			var val;

			if ( computed ) {
				if ( elem.offsetWidth !== 0 ) {
					val = getWH( elem, name, extra );

				} else {
					jQuery.swap( elem, cssShow, function() {
						val = getWH( elem, name, extra );
					});
				}

				if ( val <= 0 ) {
					val = curCSS( elem, name, name );

					if ( val === "0px" && currentStyle ) {
						val = currentStyle( elem, name, name );
					}

					if ( val != null ) {
						// Should return "auto" instead of 0, use 0 for
						// temporary backwards-compat
						return val === "" || val === "auto" ? "0px" : val;
					}
				}

				if ( val < 0 || val == null ) {
					val = elem.style[ name ];

					// Should return "auto" instead of 0, use 0 for
					// temporary backwards-compat
					return val === "" || val === "auto" ? "0px" : val;
				}

				return typeof val === "string" ? val : val + "px";
			}
		},

		set: function( elem, value ) {
			if ( rnumpx.test( value ) ) {
				// ignore negative width and height values #1599
				value = parseFloat(value);

				if ( value >= 0 ) {
					return value + "px";
				}

			} else {
				return value;
			}
		}
	};
});

if ( !jQuery.support.opacity ) {
	jQuery.cssHooks.opacity = {
		get: function( elem, computed ) {
			// IE uses filters for opacity
			return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
				( parseFloat( RegExp.$1 ) / 100 ) + "" :
				computed ? "1" : "";
		},

		set: function( elem, value ) {
			var style = elem.style,
				currentStyle = elem.currentStyle;

			// IE has trouble with opacity if it does not have layout
			// Force it by setting the zoom level
			style.zoom = 1;

			// Set the alpha filter to set the opacity
			var opacity = jQuery.isNaN( value ) ?
				"" :
				"alpha(opacity=" + value * 100 + ")",
				filter = currentStyle && currentStyle.filter || style.filter || "";

			style.filter = ralpha.test( filter ) ?
				filter.replace( ralpha, opacity ) :
				filter + " " + opacity;
		}
	};
}

jQuery(function() {
	// This hook cannot be added until DOM ready because the support test
	// for it is not run until after DOM ready
	if ( !jQuery.support.reliableMarginRight ) {
		jQuery.cssHooks.marginRight = {
			get: function( elem, computed ) {
				// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
				// Work around by temporarily setting element display to inline-block
				var ret;
				jQuery.swap( elem, { "display": "inline-block" }, function() {
					if ( computed ) {
						ret = curCSS( elem, "margin-right", "marginRight" );
					} else {
						ret = elem.style.marginRight;
					}
				});
				return ret;
			}
		};
	}
});

if ( document.defaultView && document.defaultView.getComputedStyle ) {
	getComputedStyle = function( elem, name ) {
		var ret, defaultView, computedStyle;

		name = name.replace( rupper, "-$1" ).toLowerCase();

		if ( !(defaultView = elem.ownerDocument.defaultView) ) {
			return undefined;
		}

		if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) {
			ret = computedStyle.getPropertyValue( name );
			if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
				ret = jQuery.style( elem, name );
			}
		}

		return ret;
	};
}

if ( document.documentElement.currentStyle ) {
	currentStyle = function( elem, name ) {
		var left,
			ret = elem.currentStyle && elem.currentStyle[ name ],
			rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ],
			style = elem.style;

		// From the awesome hack by Dean Edwards
		// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

		// If we're not dealing with a regular pixel number
		// but a number that has a weird ending, we need to convert it to pixels
		if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
			// Remember the original values
			left = style.left;

			// Put in the new values to get a computed value out
			if ( rsLeft ) {
				elem.runtimeStyle.left = elem.currentStyle.left;
			}
			style.left = name === "fontSize" ? "1em" : (ret || 0);
			ret = style.pixelLeft + "px";

			// Revert the changed values
			style.left = left;
			if ( rsLeft ) {
				elem.runtimeStyle.left = rsLeft;
			}
		}

		return ret === "" ? "auto" : ret;
	};
}

curCSS = getComputedStyle || currentStyle;

function getWH( elem, name, extra ) {
	var which = name === "width" ? cssWidth : cssHeight,
		val = name === "width" ? elem.offsetWidth : elem.offsetHeight;

	if ( extra === "border" ) {
		return val;
	}

	jQuery.each( which, function() {
		if ( !extra ) {
			val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0;
		}

		if ( extra === "margin" ) {
			val += parseFloat(jQuery.css( elem, "margin" + this )) || 0;

		} else {
			val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0;
		}
	});

	return val;
}

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.hidden = function( elem ) {
		var width = elem.offsetWidth,
			height = elem.offsetHeight;

		return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none");
	};

	jQuery.expr.filters.visible = function( elem ) {
		return !jQuery.expr.filters.hidden( elem );
	};
}




var r20 = /%20/g,
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rhash = /#.*$/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
	rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,
	rquery = /\?/,
	rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
	rselectTextarea = /^(?:select|textarea)/i,
	rspacesAjax = /\s+/,
	rts = /([?&])_=[^&]*/,
	rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,

	// Keep a copy of the old load method
	_load = jQuery.fn.load,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Document location
	ajaxLocation,

	// Document location segments
	ajaxLocParts;

// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
	ajaxLocation = location.href;
} catch( e ) {
	// Use the href attribute of an A element
	// since IE will modify it given document.location
	ajaxLocation = document.createElement( "a" );
	ajaxLocation.href = "";
	ajaxLocation = ajaxLocation.href;
}

// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		if ( jQuery.isFunction( func ) ) {
			var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
				i = 0,
				length = dataTypes.length,
				dataType,
				list,
				placeBefore;

			// For each dataType in the dataTypeExpression
			for(; i < length; i++ ) {
				dataType = dataTypes[ i ];
				// We control if we're asked to add before
				// any existing element
				placeBefore = /^\+/.test( dataType );
				if ( placeBefore ) {
					dataType = dataType.substr( 1 ) || "*";
				}
				list = structure[ dataType ] = structure[ dataType ] || [];
				// then we add to the structure accordingly
				list[ placeBefore ? "unshift" : "push" ]( func );
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
		dataType /* internal */, inspected /* internal */ ) {

	dataType = dataType || options.dataTypes[ 0 ];
	inspected = inspected || {};

	inspected[ dataType ] = true;

	var list = structure[ dataType ],
		i = 0,
		length = list ? list.length : 0,
		executeOnly = ( structure === prefilters ),
		selection;

	for(; i < length && ( executeOnly || !selection ); i++ ) {
		selection = list[ i ]( options, originalOptions, jqXHR );
		// If we got redirected to another dataType
		// we try there if executing only and not done already
		if ( typeof selection === "string" ) {
			if ( !executeOnly || inspected[ selection ] ) {
				selection = undefined;
			} else {
				options.dataTypes.unshift( selection );
				selection = inspectPrefiltersOrTransports(
						structure, options, originalOptions, jqXHR, selection, inspected );
			}
		}
	}
	// If we're only executing or nothing was selected
	// we try the catchall dataType if not done already
	if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
		selection = inspectPrefiltersOrTransports(
				structure, options, originalOptions, jqXHR, "*", inspected );
	}
	// unnecessary when only executing (prefilters)
	// but it'll be ignored by the caller in that case
	return selection;
}

jQuery.fn.extend({
	load: function( url, params, callback ) {
		if ( typeof url !== "string" && _load ) {
			return _load.apply( this, arguments );

		// Don't do a request if no elements are being requested
		} else if ( !this.length ) {
			return this;
		}

		var off = url.indexOf( " " );
		if ( off >= 0 ) {
			var selector = url.slice( off, url.length );
			url = url.slice( 0, off );
		}

		// Default to a GET request
		var type = "GET";

		// If the second parameter was provided
		if ( params ) {
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = undefined;

			// Otherwise, build a param string
			} else if ( typeof params === "object" ) {
				params = jQuery.param( params, jQuery.ajaxSettings.traditional );
				type = "POST";
			}
		}

		var self = this;

		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			dataType: "html",
			data: params,
			// Complete callback (responseText is used internally)
			complete: function( jqXHR, status, responseText ) {
				// Store the response as specified by the jqXHR object
				responseText = jqXHR.responseText;
				// If successful, inject the HTML into all the matched elements
				if ( jqXHR.isResolved() ) {
					// #4825: Get the actual response in case
					// a dataFilter is present in ajaxSettings
					jqXHR.done(function( r ) {
						responseText = r;
					});
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(responseText.replace(rscript, ""))

							// Locate the specified elements
							.find(selector) :

						// If not, just inject the full result
						responseText );
				}

				if ( callback ) {
					self.each( callback, [ responseText, status, jqXHR ] );
				}
			}
		});

		return this;
	},

	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},

	serializeArray: function() {
		return this.map(function(){
			return this.elements ? jQuery.makeArray( this.elements ) : this;
		})
		.filter(function(){
			return this.name && !this.disabled &&
				( this.checked || rselectTextarea.test( this.nodeName ) ||
					rinput.test( this.type ) );
		})
		.map(function( i, elem ){
			var val = jQuery( this ).val();

			return val == null ?
				null :
				jQuery.isArray( val ) ?
					jQuery.map( val, function( val, i ){
						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
					}) :
					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		}).get();
	}
});

// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
	jQuery.fn[ o ] = function( f ){
		return this.bind( o, f );
	};
});

jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {
		// shift arguments if data argument was omitted
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		return jQuery.ajax({
			type: method,
			url: url,
			data: data,
			success: callback,
			dataType: type
		});
	};
});

jQuery.extend({

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function ( target, settings ) {
		if ( !settings ) {
			// Only one parameter, we extend ajaxSettings
			settings = target;
			target = jQuery.extend( true, jQuery.ajaxSettings, settings );
		} else {
			// target was provided, we extend into it
			jQuery.extend( true, target, jQuery.ajaxSettings, settings );
		}
		// Flatten fields we don't want deep extended
		for( var field in { context: 1, url: 1 } ) {
			if ( field in settings ) {
				target[ field ] = settings[ field ];
			} else if( field in jQuery.ajaxSettings ) {
				target[ field ] = jQuery.ajaxSettings[ field ];
			}
		}
		return target;
	},

	ajaxSettings: {
		url: ajaxLocation,
		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
		global: true,
		type: "GET",
		contentType: "application/x-www-form-urlencoded",
		processData: true,
		async: true,
		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		traditional: false,
		headers: {},
		*/

		accepts: {
			xml: "application/xml, text/xml",
			html: "text/html",
			text: "text/plain",
			json: "application/json, text/javascript",
			"*": "*/*"
		},

		contents: {
			xml: /xml/,
			html: /html/,
			json: /json/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText"
		},

		// List of data converters
		// 1) key format is "source_type destination_type" (a single space in-between)
		// 2) the catchall symbol "*" can be used for source_type
		converters: {

			// Convert anything to text
			"* text": window.String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": jQuery.parseJSON,

			// Parse text as xml
			"text xml": jQuery.parseXML
		}
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var // Create the final options object
			s = jQuery.ajaxSetup( {}, options ),
			// Callbacks context
			callbackContext = s.context || s,
			// Context for global events
			// It's the callbackContext if one was provided in the options
			// and if it's a DOM node or a jQuery collection
			globalEventContext = callbackContext !== s &&
				( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
						jQuery( callbackContext ) : jQuery.event,
			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery._Deferred(),
			// Status-dependent callbacks
			statusCode = s.statusCode || {},
			// ifModified key
			ifModifiedKey,
			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},
			// Response headers
			responseHeadersString,
			responseHeaders,
			// transport
			transport,
			// timeout handle
			timeoutTimer,
			// Cross-domain detection vars
			parts,
			// The jqXHR state
			state = 0,
			// To know if global events are to be dispatched
			fireGlobals,
			// Loop variable
			i,
			// Fake xhr
			jqXHR = {

				readyState: 0,

				// Caches the header
				setRequestHeader: function( name, value ) {
					if ( !state ) {
						var lname = name.toLowerCase();
						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Raw string
				getAllResponseHeaders: function() {
					return state === 2 ? responseHeadersString : null;
				},

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( state === 2 ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
							}
						}
						match = responseHeaders[ key.toLowerCase() ];
					}
					return match === undefined ? null : match;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( !state ) {
						s.mimeType = type;
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					statusText = statusText || "abort";
					if ( transport ) {
						transport.abort( statusText );
					}
					done( 0, statusText );
					return this;
				}
			};

		// Callback for when everything is done
		// It is defined here because jslint complains if it is declared
		// at the end of the function (which would be more logical and readable)
		function done( status, statusText, responses, headers ) {

			// Called once
			if ( state === 2 ) {
				return;
			}

			// State is "done" now
			state = 2;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status ? 4 : 0;

			var isSuccess,
				success,
				error,
				response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
				lastModified,
				etag;

			// If successful, handle type chaining
			if ( status >= 200 && status < 300 || status === 304 ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {

					if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
						jQuery.lastModified[ ifModifiedKey ] = lastModified;
					}
					if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
						jQuery.etag[ ifModifiedKey ] = etag;
					}
				}

				// If not modified
				if ( status === 304 ) {

					statusText = "notmodified";
					isSuccess = true;

				// If we have data
				} else {

					try {
						success = ajaxConvert( s, response );
						statusText = "success";
						isSuccess = true;
					} catch(e) {
						// We have a parsererror
						statusText = "parsererror";
						error = e;
					}
				}
			} else {
				// We extract error from statusText
				// then normalize statusText and status for non-aborts
				error = statusText;
				if( !statusText || status ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = statusText;

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
						[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s] );
				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		// Attach deferreds
		deferred.promise( jqXHR );
		jqXHR.success = jqXHR.done;
		jqXHR.error = jqXHR.fail;
		jqXHR.complete = completeDeferred.done;

		// Status-dependent callbacks
		jqXHR.statusCode = function( map ) {
			if ( map ) {
				var tmp;
				if ( state < 2 ) {
					for( tmp in map ) {
						statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
					}
				} else {
					tmp = map[ jqXHR.status ];
					jqXHR.then( tmp, tmp );
				}
			}
			return this;
		};

		// Remove hash character (#7531: and string promotion)
		// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
		// We also use the url parameter if available
		s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );

		// Extract dataTypes list
		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );

		// Determine if a cross-domain request is in order
		if ( s.crossDomain == null ) {
			parts = rurl.exec( s.url.toLowerCase() );
			s.crossDomain = !!( parts &&
				( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
			);
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefiler, stop there
		if ( state === 2 ) {
			return false;
		}

		// We can fire global events as of now if asked to
		fireGlobals = s.global;

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// If data is available, append data to url
			if ( s.data ) {
				s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
			}

			// Get ifModifiedKey before adding the anti-cache parameter
			ifModifiedKey = s.url;

			// Add anti-cache in url if needed
			if ( s.cache === false ) {

				var ts = jQuery.now(),
					// try replacing _= if it is there
					ret = s.url.replace( rts, "$1_=" + ts );

				// if nothing was replaced, add timestamp to the end
				s.url = ret + ( (ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			ifModifiedKey = ifModifiedKey || s.url;
			if ( jQuery.lastModified[ ifModifiedKey ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
			}
			if ( jQuery.etag[ ifModifiedKey ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
			}
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
				s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
				// Abort if not done already
				jqXHR.abort();
				return false;

		}

		// Install callbacks on deferreds
		for ( i in { success: 1, error: 1, complete: 1 } ) {
			jqXHR[ i ]( s[ i ] );
		}

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;
			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}
			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = setTimeout( function(){
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				state = 1;
				transport.send( requestHeaders, done );
			} catch (e) {
				// Propagate exception as error if not done
				if ( status < 2 ) {
					done( -1, e );
				// Simply rethrow otherwise
				} else {
					jQuery.error( e );
				}
			}
		}

		return jqXHR;
	},

	// Serialize an array of form elements or a set of
	// key/values into a query string
	param: function( a, traditional ) {
		var s = [],
			add = function( key, value ) {
				// If value is a function, invoke it and return its value
				value = jQuery.isFunction( value ) ? value() : value;
				s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
			};

		// Set traditional to true for jQuery <= 1.3.2 behavior.
		if ( traditional === undefined ) {
			traditional = jQuery.ajaxSettings.traditional;
		}

		// If an array was passed in, assume that it is an array of form elements.
		if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
			// Serialize the form elements
			jQuery.each( a, function() {
				add( this.name, this.value );
			});

		} else {
			// If traditional, encode the "old" way (the way 1.3.2 or older
			// did it), otherwise encode params recursively.
			for ( var prefix in a ) {
				buildParams( prefix, a[ prefix ], traditional, add );
			}
		}

		// Return the resulting serialization
		return s.join( "&" ).replace( r20, "+" );
	}
});

function buildParams( prefix, obj, traditional, add ) {
	if ( jQuery.isArray( obj ) ) {
		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {
				// Treat each array item as a scalar.
				add( prefix, v );

			} else {
				// If array item is non-scalar (array or object), encode its
				// numeric index to resolve deserialization ambiguity issues.
				// Note that rack (as of 1.0.0) can't currently deserialize
				// nested arrays properly, and attempting to do so may cause
				// a server error. Possible fixes are to modify rack's
				// deserialization algorithm or to provide an option or flag
				// to force array serialization to be shallow.
				buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
			}
		});

	} else if ( !traditional && obj != null && typeof obj === "object" ) {
		// Serialize object item.
		for ( var name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {
		// Serialize scalar item.
		add( prefix, obj );
	}
}

// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {}

});

/* Handles responses to an ajax request:
 * - sets all responseXXX fields accordingly
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {

	var contents = s.contents,
		dataTypes = s.dataTypes,
		responseFields = s.responseFields,
		ct,
		type,
		finalDataType,
		firstDataType;

	// Fill responseXXX fields
	for( type in responseFields ) {
		if ( type in responses ) {
			jqXHR[ responseFields[type] ] = responses[ type ];
		}
	}

	// Remove auto dataType and get content-type in the process
	while( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {
		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}
		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {

	// Apply the dataFilter if provided
	if ( s.dataFilter ) {
		response = s.dataFilter( response, s.dataType );
	}

	var dataTypes = s.dataTypes,
		converters = {},
		i,
		key,
		length = dataTypes.length,
		tmp,
		// Current and previous dataTypes
		current = dataTypes[ 0 ],
		prev,
		// Conversion expression
		conversion,
		// Conversion function
		conv,
		// Conversion functions (transitive conversion)
		conv1,
		conv2;

	// For each dataType in the chain
	for( i = 1; i < length; i++ ) {

		// Create converters map
		// with lowercased keys
		if ( i === 1 ) {
			for( key in s.converters ) {
				if( typeof key === "string" ) {
					converters[ key.toLowerCase() ] = s.converters[ key ];
				}
			}
		}

		// Get the dataTypes
		prev = current;
		current = dataTypes[ i ];

		// If current is auto dataType, update it to prev
		if( current === "*" ) {
			current = prev;
		// If no auto and dataTypes are actually different
		} else if ( prev !== "*" && prev !== current ) {

			// Get the converter
			conversion = prev + " " + current;
			conv = converters[ conversion ] || converters[ "* " + current ];

			// If there is no direct converter, search transitively
			if ( !conv ) {
				conv2 = undefined;
				for( conv1 in converters ) {
					tmp = conv1.split( " " );
					if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
						conv2 = converters[ tmp[1] + " " + current ];
						if ( conv2 ) {
							conv1 = converters[ conv1 ];
							if ( conv1 === true ) {
								conv = conv2;
							} else if ( conv2 === true ) {
								conv = conv1;
							}
							break;
						}
					}
				}
			}
			// If we found no converter, dispatch an error
			if ( !( conv || conv2 ) ) {
				jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
			}
			// If found converter is not an equivalence
			if ( conv !== true ) {
				// Convert with 1 or 2 converters accordingly
				response = conv ? conv( response ) : conv2( conv1(response) );
			}
		}
	}
	return response;
}




var jsc = jQuery.now(),
	jsre = /(\=)\?(&|$)|\?\?/i;

// Default jsonp settings
jQuery.ajaxSetup({
	jsonp: "callback",
	jsonpCallback: function() {
		return jQuery.expando + "_" + ( jsc++ );
	}
});

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
		( typeof s.data === "string" );

	if ( s.dataTypes[ 0 ] === "jsonp" ||
		s.jsonp !== false && ( jsre.test( s.url ) ||
				inspectData && jsre.test( s.data ) ) ) {

		var responseContainer,
			jsonpCallback = s.jsonpCallback =
				jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
			previous = window[ jsonpCallback ],
			url = s.url,
			data = s.data,
			replace = "$1" + jsonpCallback + "$2";

		if ( s.jsonp !== false ) {
			url = url.replace( jsre, replace );
			if ( s.url === url ) {
				if ( inspectData ) {
					data = data.replace( jsre, replace );
				}
				if ( s.data === data ) {
					// Add callback manually
					url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
				}
			}
		}

		s.url = url;
		s.data = data;

		// Install callback
		window[ jsonpCallback ] = function( response ) {
			responseContainer = [ response ];
		};

		// Clean-up function
		jqXHR.always(function() {
			// Set callback back to previous value
			window[ jsonpCallback ] = previous;
			// Call if it was a function and we have a response
			if ( responseContainer && jQuery.isFunction( previous ) ) {
				window[ jsonpCallback ]( responseContainer[ 0 ] );
			}
		});

		// Use data converter to retrieve json after script execution
		s.converters["script json"] = function() {
			if ( !responseContainer ) {
				jQuery.error( jsonpCallback + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// force json dataType
		s.dataTypes[ 0 ] = "json";

		// Delegate to script
		return "script";
	}
});




// Install script dataType
jQuery.ajaxSetup({
	accepts: {
		script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /javascript|ecmascript/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
});

// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
		s.global = false;
	}
});

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {

	// This transport only deals with cross domain requests
	if ( s.crossDomain ) {

		var script,
			head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;

		return {

			send: function( _, callback ) {

				script = document.createElement( "script" );

				script.async = "async";

				if ( s.scriptCharset ) {
					script.charset = s.scriptCharset;
				}

				script.src = s.url;

				// Attach handlers for all browsers
				script.onload = script.onreadystatechange = function( _, isAbort ) {

					if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {

						// Handle memory leak in IE
						script.onload = script.onreadystatechange = null;

						// Remove the script
						if ( head && script.parentNode ) {
							head.removeChild( script );
						}

						// Dereference the script
						script = undefined;

						// Callback if not abort
						if ( !isAbort ) {
							callback( 200, "success" );
						}
					}
				};
				// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
				// This arises when a base node is used (#2709 and #4378).
				head.insertBefore( script, head.firstChild );
			},

			abort: function() {
				if ( script ) {
					script.onload( 0, 1 );
				}
			}
		};
	}
});




var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
	xhrOnUnloadAbort = window.ActiveXObject ? function() {
		// Abort all pending requests
		for ( var key in xhrCallbacks ) {
			xhrCallbacks[ key ]( 0, 1 );
		}
	} : false,
	xhrId = 0,
	xhrCallbacks;

// Functions to create xhrs
function createStandardXHR() {
	try {
		return new window.XMLHttpRequest();
	} catch( e ) {}
}

function createActiveXHR() {
	try {
		return new window.ActiveXObject( "Microsoft.XMLHTTP" );
	} catch( e ) {}
}

// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
	/* Microsoft failed to properly
	 * implement the XMLHttpRequest in IE7 (can't request local files),
	 * so we use the ActiveXObject when it is available
	 * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
	 * we need a fallback.
	 */
	function() {
		return !this.isLocal && createStandardXHR() || createActiveXHR();
	} :
	// For all other browsers, use the standard XMLHttpRequest object
	createStandardXHR;

// Determine support properties
(function( xhr ) {
	jQuery.extend( jQuery.support, {
		ajax: !!xhr,
		cors: !!xhr && ( "withCredentials" in xhr )
	});
})( jQuery.ajaxSettings.xhr() );

// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {

	jQuery.ajaxTransport(function( s ) {
		// Cross domain only allowed if supported through XMLHttpRequest
		if ( !s.crossDomain || jQuery.support.cors ) {

			var callback;

			return {
				send: function( headers, complete ) {

					// Get a new xhr
					var xhr = s.xhr(),
						handle,
						i;

					// Open the socket
					// Passing null username, generates a login popup on Opera (#2865)
					if ( s.username ) {
						xhr.open( s.type, s.url, s.async, s.username, s.password );
					} else {
						xhr.open( s.type, s.url, s.async );
					}

					// Apply custom fields if provided
					if ( s.xhrFields ) {
						for ( i in s.xhrFields ) {
							xhr[ i ] = s.xhrFields[ i ];
						}
					}

					// Override mime type if needed
					if ( s.mimeType && xhr.overrideMimeType ) {
						xhr.overrideMimeType( s.mimeType );
					}

					// X-Requested-With header
					// For cross-domain requests, seeing as conditions for a preflight are
					// akin to a jigsaw puzzle, we simply never set it to be sure.
					// (it can always be set on a per-request basis or even using ajaxSetup)
					// For same-domain requests, won't change header if already provided.
					if ( !s.crossDomain && !headers["X-Requested-With"] ) {
						headers[ "X-Requested-With" ] = "XMLHttpRequest";
					}

					// Need an extra try/catch for cross domain requests in Firefox 3
					try {
						for ( i in headers ) {
							xhr.setRequestHeader( i, headers[ i ] );
						}
					} catch( _ ) {}

					// Do send the request
					// This may raise an exception which is actually
					// handled in jQuery.ajax (so no try/catch here)
					xhr.send( ( s.hasContent && s.data ) || null );

					// Listener
					callback = function( _, isAbort ) {

						var status,
							statusText,
							responseHeaders,
							responses,
							xml;

						// Firefox throws exceptions when accessing properties
						// of an xhr when a network error occured
						// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
						try {

							// Was never called and is aborted or complete
							if ( callback && ( isAbort || xhr.readyState === 4 ) ) {

								// Only called once
								callback = undefined;

								// Do not keep as active anymore
								if ( handle ) {
									xhr.onreadystatechange = jQuery.noop;
									if ( xhrOnUnloadAbort ) {
										delete xhrCallbacks[ handle ];
									}
								}

								// If it's an abort
								if ( isAbort ) {
									// Abort it manually if needed
									if ( xhr.readyState !== 4 ) {
										xhr.abort();
									}
								} else {
									status = xhr.status;
									responseHeaders = xhr.getAllResponseHeaders();
									responses = {};
									xml = xhr.responseXML;

									// Construct response list
									if ( xml && xml.documentElement /* #4958 */ ) {
										responses.xml = xml;
									}
									responses.text = xhr.responseText;

									// Firefox throws an exception when accessing
									// statusText for faulty cross-domain requests
									try {
										statusText = xhr.statusText;
									} catch( e ) {
										// We normalize with Webkit giving an empty statusText
										statusText = "";
									}

									// Filter status for non standard behaviors

									// If the request is local and we have data: assume a success
									// (success with no data won't get notified, that's the best we
									// can do given current implementations)
									if ( !status && s.isLocal && !s.crossDomain ) {
										status = responses.text ? 200 : 404;
									// IE - #1450: sometimes returns 1223 when it should be 204
									} else if ( status === 1223 ) {
										status = 204;
									}
								}
							}
						} catch( firefoxAccessException ) {
							if ( !isAbort ) {
								complete( -1, firefoxAccessException );
							}
						}

						// Call complete if needed
						if ( responses ) {
							complete( status, statusText, responses, responseHeaders );
						}
					};

					// if we're in sync mode or it's in cache
					// and has been retrieved directly (IE6 & IE7)
					// we need to manually fire the callback
					if ( !s.async || xhr.readyState === 4 ) {
						callback();
					} else {
						handle = ++xhrId;
						if ( xhrOnUnloadAbort ) {
							// Create the active xhrs callbacks list if needed
							// and attach the unload handler
							if ( !xhrCallbacks ) {
								xhrCallbacks = {};
								jQuery( window ).unload( xhrOnUnloadAbort );
							}
							// Add to list of active xhrs callbacks
							xhrCallbacks[ handle ] = callback;
						}
						xhr.onreadystatechange = callback;
					}
				},

				abort: function() {
					if ( callback ) {
						callback(0,1);
					}
				}
			};
		}
	});
}




var elemdisplay = {},
	iframe, iframeDoc,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
	timerId,
	fxAttrs = [
		// height animations
		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
		// width animations
		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
		// opacity animations
		[ "opacity" ]
	],
	fxNow,
	requestAnimationFrame = window.webkitRequestAnimationFrame ||
	    window.mozRequestAnimationFrame ||
	    window.oRequestAnimationFrame;

jQuery.fn.extend({
	show: function( speed, easing, callback ) {
		var elem, display;

		if ( speed || speed === 0 ) {
			return this.animate( genFx("show", 3), speed, easing, callback);

		} else {
			for ( var i = 0, j = this.length; i < j; i++ ) {
				elem = this[i];

				if ( elem.style ) {
					display = elem.style.display;

					// Reset the inline display of this element to learn if it is
					// being hidden by cascaded rules or not
					if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
						display = elem.style.display = "";
					}

					// Set elements which have been overridden with display: none
					// in a stylesheet to whatever the default browser style is
					// for such an element
					if ( display === "" && jQuery.css( elem, "display" ) === "none" ) {
						jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName));
					}
				}
			}

			// Set the display of most of the elements in a second loop
			// to avoid the constant reflow
			for ( i = 0; i < j; i++ ) {
				elem = this[i];

				if ( elem.style ) {
					display = elem.style.display;

					if ( display === "" || display === "none" ) {
						elem.style.display = jQuery._data(elem, "olddisplay") || "";
					}
				}
			}

			return this;
		}
	},

	hide: function( speed, easing, callback ) {
		if ( speed || speed === 0 ) {
			return this.animate( genFx("hide", 3), speed, easing, callback);

		} else {
			for ( var i = 0, j = this.length; i < j; i++ ) {
				if ( this[i].style ) {
					var display = jQuery.css( this[i], "display" );

					if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) {
						jQuery._data( this[i], "olddisplay", display );
					}
				}
			}

			// Set the display of the elements in a second loop
			// to avoid the constant reflow
			for ( i = 0; i < j; i++ ) {
				if ( this[i].style ) {
					this[i].style.display = "none";
				}
			}

			return this;
		}
	},

	// Save the old toggle function
	_toggle: jQuery.fn.toggle,

	toggle: function( fn, fn2, callback ) {
		var bool = typeof fn === "boolean";

		if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
			this._toggle.apply( this, arguments );

		} else if ( fn == null || bool ) {
			this.each(function() {
				var state = bool ? fn : jQuery(this).is(":hidden");
				jQuery(this)[ state ? "show" : "hide" ]();
			});

		} else {
			this.animate(genFx("toggle", 3), fn, fn2, callback);
		}

		return this;
	},

	fadeTo: function( speed, to, easing, callback ) {
		return this.filter(":hidden").css("opacity", 0).show().end()
					.animate({opacity: to}, speed, easing, callback);
	},

	animate: function( prop, speed, easing, callback ) {
		var optall = jQuery.speed(speed, easing, callback);

		if ( jQuery.isEmptyObject( prop ) ) {
			return this.each( optall.complete, [ false ] );
		}

		return this[ optall.queue === false ? "each" : "queue" ](function() {
			// XXX 'this' does not always have a nodeName when running the
			// test suite

			if ( optall.queue === false ) {
				jQuery._mark( this );
			}

			var opt = jQuery.extend({}, optall),
				isElement = this.nodeType === 1,
				hidden = isElement && jQuery(this).is(":hidden"),
				name, val, p,
				display, e,
				parts, start, end, unit;

			// will store per property easing and be used to determine when an animation is complete
			opt.animatedProperties = {};

			for ( p in prop ) {

				// property name normalization
				name = jQuery.camelCase( p );
				if ( p !== name ) {
					prop[ name ] = prop[ p ];
					delete prop[ p ];
				}

				val = prop[name];

				if ( val === "hide" && hidden || val === "show" && !hidden ) {
					return opt.complete.call(this);
				}

				if ( isElement && ( name === "height" || name === "width" ) ) {
					// Make sure that nothing sneaks out
					// Record all 3 overflow attributes because IE does not
					// change the overflow attribute when overflowX and
					// overflowY are set to the same value
					opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];

					// Set display property to inline-block for height/width
					// animations on inline elements that are having width/height
					// animated
					if ( jQuery.css( this, "display" ) === "inline" &&
							jQuery.css( this, "float" ) === "none" ) {
						if ( !jQuery.support.inlineBlockNeedsLayout ) {
							this.style.display = "inline-block";

						} else {
							display = defaultDisplay(this.nodeName);

							// inline-level elements accept inline-block;
							// block-level elements need to be inline with layout
							if ( display === "inline" ) {
								this.style.display = "inline-block";

							} else {
								this.style.display = "inline";
								this.style.zoom = 1;
							}
						}
					}
				}

				// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
				opt.animatedProperties[name] = jQuery.isArray( val ) ?
					val[1]:
					opt.specialEasing && opt.specialEasing[name] || opt.easing || 'swing';
			}

			if ( opt.overflow != null ) {
				this.style.overflow = "hidden";
			}

			for ( p in prop ) {
				e = new jQuery.fx( this, opt, p );

				val = prop[p];

				if ( rfxtypes.test(val) ) {
					e[ val === "toggle" ? hidden ? "show" : "hide" : val ]();

				} else {
					parts = rfxnum.exec(val);
					start = e.cur();

					if ( parts ) {
						end = parseFloat( parts[2] );
						unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "px" );

						// We need to compute starting value
						if ( unit !== "px" ) {
							jQuery.style( this, p, (end || 1) + unit);
							start = ((end || 1) / e.cur()) * start;
							jQuery.style( this, p, start + unit);
						}

						// If a +=/-= token was provided, we're doing a relative animation
						if ( parts[1] ) {
							end = ((parts[1] === "-=" ? -1 : 1) * end) + start;
						}

						e.custom( start, end, unit );

					} else {
						e.custom( start, val, "" );
					}
				}
			}

			// For JS strict compliance
			return true;
		});
	},

	stop: function( clearQueue, gotoEnd ) {
		if ( clearQueue ) {
			this.queue([]);
		}

		this.each(function() {
			var timers = jQuery.timers,
				i = timers.length;
			// clear marker counters if we know they won't be
			if ( !gotoEnd ) {
				jQuery._unmark( true, this );
			}
			// go in reverse order so anything added to the queue during the loop is ignored
			while ( i-- ) {
				if ( timers[i].elem === this ) {
					if (gotoEnd) {
						// force the next step to be the last
						timers[i](true);
					}

					timers.splice(i, 1);
				}
			}
		});

		// start the next in the queue if the last step wasn't forced
		if ( !gotoEnd ) {
			this.dequeue();
		}

		return this;
	}

});

// Animations created synchronously will run synchronously
function createFxNow() {
	setTimeout( clearFxNow, 0 );
	return ( fxNow = jQuery.now() );
}

function clearFxNow() {
	fxNow = undefined;
}

// Generate parameters to create a standard animation
function genFx( type, num ) {
	var obj = {};

	jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
		obj[ this ] = type;
	});

	return obj;
}

// Generate shortcuts for custom animations
jQuery.each({
	slideDown: genFx("show", 1),
	slideUp: genFx("hide", 1),
	slideToggle: genFx("toggle", 1),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
});

jQuery.extend({
	speed: function( speed, easing, fn ) {
		var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
			complete: fn || !fn && easing ||
				jQuery.isFunction( speed ) && speed,
			duration: speed,
			easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
		};

		opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
			opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;

		// Queueing
		opt.old = opt.complete;
		opt.complete = function( noUnmark ) {
			if ( opt.queue !== false ) {
				jQuery.dequeue( this );
			} else if ( noUnmark !== false ) {
				jQuery._unmark( this );
			}

			if ( jQuery.isFunction( opt.old ) ) {
				opt.old.call( this );
			}
		};

		return opt;
	},

	easing: {
		linear: function( p, n, firstNum, diff ) {
			return firstNum + diff * p;
		},
		swing: function( p, n, firstNum, diff ) {
			return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
		}
	},

	timers: [],

	fx: function( elem, options, prop ) {
		this.options = options;
		this.elem = elem;
		this.prop = prop;

		options.orig = options.orig || {};
	}

});

jQuery.fx.prototype = {
	// Simple function for setting a style value
	update: function() {
		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
	},

	// Get the current size
	cur: function() {
		if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
			return this.elem[ this.prop ];
		}

		var parsed,
			r = jQuery.css( this.elem, this.prop );
		// Empty strings, null, undefined and "auto" are converted to 0,
		// complex values such as "rotate(1rad)" are returned as is,
		// simple values such as "10px" are parsed to Float.
		return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
	},

	// Start an animation from one number to another
	custom: function( from, to, unit ) {
		var self = this,
			fx = jQuery.fx,
			raf;

		this.startTime = fxNow || createFxNow();
		this.start = from;
		this.end = to;
		this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
		this.now = this.start;
		this.pos = this.state = 0;

		function t( gotoEnd ) {
			return self.step(gotoEnd);
		}

		t.elem = this.elem;

		if ( t() && jQuery.timers.push(t) && !timerId ) {
			// Use requestAnimationFrame instead of setInterval if available
			if ( requestAnimationFrame ) {
				timerId = 1;
				raf = function() {
					// When timerId gets set to null at any point, this stops
					if ( timerId ) {
						requestAnimationFrame( raf );
						fx.tick();
					}
				};
				requestAnimationFrame( raf );
			} else {
				timerId = setInterval( fx.tick, fx.interval );
			}
		}
	},

	// Simple 'show' function
	show: function() {
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
		this.options.show = true;

		// Begin the animation
		// Make sure that we start at a small width/height to avoid any
		// flash of content
		this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur());

		// Start by showing the element
		jQuery( this.elem ).show();
	},

	// Simple 'hide' function
	hide: function() {
		// Remember where we started, so that we can go back to it later
		this.options.orig[this.prop] = jQuery.style( this.elem, this.prop );
		this.options.hide = true;

		// Begin the animation
		this.custom(this.cur(), 0);
	},

	// Each step of an animation
	step: function( gotoEnd ) {
		var t = fxNow || createFxNow(),
			done = true,
			elem = this.elem,
			options = this.options,
			i, n;

		if ( gotoEnd || t >= options.duration + this.startTime ) {
			this.now = this.end;
			this.pos = this.state = 1;
			this.update();

			options.animatedProperties[ this.prop ] = true;

			for ( i in options.animatedProperties ) {
				if ( options.animatedProperties[i] !== true ) {
					done = false;
				}
			}

			if ( done ) {
				// Reset the overflow
				if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {

					jQuery.each( [ "", "X", "Y" ], function (index, value) {
						elem.style[ "overflow" + value ] = options.overflow[index];
					});
				}

				// Hide the element if the "hide" operation was done
				if ( options.hide ) {
					jQuery(elem).hide();
				}

				// Reset the properties, if the item has been hidden or shown
				if ( options.hide || options.show ) {
					for ( var p in options.animatedProperties ) {
						jQuery.style( elem, p, options.orig[p] );
					}
				}

				// Execute the complete function
				options.complete.call( elem );
			}

			return false;

		} else {
			// classical easing cannot be used with an Infinity duration
			if ( options.duration == Infinity ) {
				this.now = t;
			} else {
				n = t - this.startTime;

				this.state = n / options.duration;
				// Perform the easing function, defaults to swing
				this.pos = jQuery.easing[options.animatedProperties[this.prop]](this.state, n, 0, 1, options.duration);
				this.now = this.start + ((this.end - this.start) * this.pos);
			}
			// Perform the next step of the animation
			this.update();
		}

		return true;
	}
};

jQuery.extend( jQuery.fx, {
	tick: function() {
		var timers = jQuery.timers,
			i = timers.length;
		while ( i-- ) {
			if ( !timers[i]() ) {
				timers.splice(i, 1);
			}
		}

		if ( !timers.length ) {
			jQuery.fx.stop();
		}
	},

	interval: 13,

	stop: function() {
		clearInterval( timerId );
		timerId = null;
	},

	speeds: {
		slow: 600,
		fast: 200,
		// Default speed
		_default: 400
	},

	step: {
		opacity: function( fx ) {
			jQuery.style( fx.elem, "opacity", fx.now );
		},

		_default: function( fx ) {
			if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
				fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit;
			} else {
				fx.elem[ fx.prop ] = fx.now;
			}
		}
	}
});

if ( jQuery.expr && jQuery.expr.filters ) {
	jQuery.expr.filters.animated = function( elem ) {
		return jQuery.grep(jQuery.timers, function( fn ) {
			return elem === fn.elem;
		}).length;
	};
}

// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {

	if ( !elemdisplay[ nodeName ] ) {

		var elem = jQuery( "<" + nodeName + ">" ).appendTo( "body" ),
			display = elem.css( "display" );

		elem.remove();

		// If the simple way fails,
		// get element's real default display by attaching it to a temp iframe
		if ( display === "none" || display === "" ) {
			// No iframe to use yet, so create it
			if ( !iframe ) {
				iframe = document.createElement( "iframe" );
				iframe.frameBorder = iframe.width = iframe.height = 0;
			}

			document.body.appendChild( iframe );

			// Create a cacheable copy of the iframe document on first call.
			// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake html
			// document to it, Webkit & Firefox won't allow reusing the iframe document
			if ( !iframeDoc || !iframe.createElement ) {
				iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
				iframeDoc.write( "<!doctype><html><body></body></html>" );
			}

			elem = iframeDoc.createElement( nodeName );

			iframeDoc.body.appendChild( elem );

			display = jQuery.css( elem, "display" );

			document.body.removeChild( iframe );
		}

		// Store the correct default display
		elemdisplay[ nodeName ] = display;
	}

	return elemdisplay[ nodeName ];
}




var rtable = /^t(?:able|d|h)$/i,
	rroot = /^(?:body|html)$/i;

if ( "getBoundingClientRect" in document.documentElement ) {
	jQuery.fn.offset = function( options ) {
		var elem = this[0], box;

		if ( options ) {
			return this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
		}

		if ( !elem || !elem.ownerDocument ) {
			return null;
		}

		if ( elem === elem.ownerDocument.body ) {
			return jQuery.offset.bodyOffset( elem );
		}

		try {
			box = elem.getBoundingClientRect();
		} catch(e) {}

		var doc = elem.ownerDocument,
			docElem = doc.documentElement;

		// Make sure we're not dealing with a disconnected DOM node
		if ( !box || !jQuery.contains( docElem, elem ) ) {
			return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
		}

		var body = doc.body,
			win = getWindow(doc),
			clientTop  = docElem.clientTop  || body.clientTop  || 0,
			clientLeft = docElem.clientLeft || body.clientLeft || 0,
			scrollTop  = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop,
			scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
			top  = box.top  + scrollTop  - clientTop,
			left = box.left + scrollLeft - clientLeft;

		return { top: top, left: left };
	};

} else {
	jQuery.fn.offset = function( options ) {
		var elem = this[0];

		if ( options ) {
			return this.each(function( i ) {
				jQuery.offset.setOffset( this, options, i );
			});
		}

		if ( !elem || !elem.ownerDocument ) {
			return null;
		}

		if ( elem === elem.ownerDocument.body ) {
			return jQuery.offset.bodyOffset( elem );
		}

		jQuery.offset.initialize();

		var computedStyle,
			offsetParent = elem.offsetParent,
			prevOffsetParent = elem,
			doc = elem.ownerDocument,
			docElem = doc.documentElement,
			body = doc.body,
			defaultView = doc.defaultView,
			prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
			top = elem.offsetTop,
			left = elem.offsetLeft;

		while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
			if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
				break;
			}

			computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
			top  -= elem.scrollTop;
			left -= elem.scrollLeft;

			if ( elem === offsetParent ) {
				top  += elem.offsetTop;
				left += elem.offsetLeft;

				if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
					top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
					left += parseFloat( computedStyle.borderLeftWidth ) || 0;
				}

				prevOffsetParent = offsetParent;
				offsetParent = elem.offsetParent;
			}

			if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
				top  += parseFloat( computedStyle.borderTopWidth  ) || 0;
				left += parseFloat( computedStyle.borderLeftWidth ) || 0;
			}

			prevComputedStyle = computedStyle;
		}

		if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
			top  += body.offsetTop;
			left += body.offsetLeft;
		}

		if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) {
			top  += Math.max( docElem.scrollTop, body.scrollTop );
			left += Math.max( docElem.scrollLeft, body.scrollLeft );
		}

		return { top: top, left: left };
	};
}

jQuery.offset = {
	initialize: function() {
		var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0,
			html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";

		jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } );

		container.innerHTML = html;
		body.insertBefore( container, body.firstChild );
		innerDiv = container.firstChild;
		checkDiv = innerDiv.firstChild;
		td = innerDiv.nextSibling.firstChild.firstChild;

		this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
		this.doesAddBorderForTableAndCells = (td.offsetTop === 5);

		checkDiv.style.position = "fixed";
		checkDiv.style.top = "20px";

		// safari subtracts parent border width here which is 5px
		this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15);
		checkDiv.style.position = checkDiv.style.top = "";

		innerDiv.style.overflow = "hidden";
		innerDiv.style.position = "relative";

		this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

		this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop);

		body.removeChild( container );
		jQuery.offset.initialize = jQuery.noop;
	},

	bodyOffset: function( body ) {
		var top = body.offsetTop,
			left = body.offsetLeft;

		jQuery.offset.initialize();

		if ( jQuery.offset.doesNotIncludeMarginInBodyOffset ) {
			top  += parseFloat( jQuery.css(body, "marginTop") ) || 0;
			left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
		}

		return { top: top, left: left };
	},

	setOffset: function( elem, options, i ) {
		var position = jQuery.css( elem, "position" );

		// set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		var curElem = jQuery( elem ),
			curOffset = curElem.offset(),
			curCSSTop = jQuery.css( elem, "top" ),
			curCSSLeft = jQuery.css( elem, "left" ),
			calculatePosition = (position === "absolute" || position === "fixed") && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
			props = {}, curPosition = {}, curTop, curLeft;

		// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;
		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( jQuery.isFunction( options ) ) {
			options = options.call( elem, i, curOffset );
		}

		if (options.top != null) {
			props.top = (options.top - curOffset.top) + curTop;
		}
		if (options.left != null) {
			props.left = (options.left - curOffset.left) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );
		} else {
			curElem.css( props );
		}
	}
};


jQuery.fn.extend({
	position: function() {
		if ( !this[0] ) {
			return null;
		}

		var elem = this[0],

		// Get *real* offsetParent
		offsetParent = this.offsetParent(),

		// Get correct offsets
		offset       = this.offset(),
		parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();

		// Subtract element margins
		// note: when an element has margin: auto the offsetLeft and marginLeft
		// are the same in Safari causing offset.left to incorrectly be 0
		offset.top  -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
		offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;

		// Add offsetParent borders
		parentOffset.top  += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
		parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;

		// Subtract the two offsets
		return {
			top:  offset.top  - parentOffset.top,
			left: offset.left - parentOffset.left
		};
	},

	offsetParent: function() {
		return this.map(function() {
			var offsetParent = this.offsetParent || document.body;
			while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
				offsetParent = offsetParent.offsetParent;
			}
			return offsetParent;
		});
	}
});


// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
	var method = "scroll" + name;

	jQuery.fn[ method ] = function( val ) {
		var elem, win;

		if ( val === undefined ) {
			elem = this[ 0 ];

			if ( !elem ) {
				return null;
			}

			win = getWindow( elem );

			// Return the scroll offset
			return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
				jQuery.support.boxModel && win.document.documentElement[ method ] ||
					win.document.body[ method ] :
				elem[ method ];
		}

		// Set the scroll offset
		return this.each(function() {
			win = getWindow( this );

			if ( win ) {
				win.scrollTo(
					!i ? val : jQuery( win ).scrollLeft(),
					 i ? val : jQuery( win ).scrollTop()
				);

			} else {
				this[ method ] = val;
			}
		});
	};
});

function getWindow( elem ) {
	return jQuery.isWindow( elem ) ?
		elem :
		elem.nodeType === 9 ?
			elem.defaultView || elem.parentWindow :
			false;
}




// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {

	var type = name.toLowerCase();

	// innerHeight and innerWidth
	jQuery.fn["inner" + name] = function() {
		return this[0] ?
			parseFloat( jQuery.css( this[0], type, "padding" ) ) :
			null;
	};

	// outerHeight and outerWidth
	jQuery.fn["outer" + name] = function( margin ) {
		return this[0] ?
			parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) :
			null;
	};

	jQuery.fn[ type ] = function( size ) {
		// Get window width or height
		var elem = this[0];
		if ( !elem ) {
			return size == null ? null : this;
		}

		if ( jQuery.isFunction( size ) ) {
			return this.each(function( i ) {
				var self = jQuery( this );
				self[ type ]( size.call( this, i, self[ type ]() ) );
			});
		}

		if ( jQuery.isWindow( elem ) ) {
			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
			// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
			var docElemProp = elem.document.documentElement[ "client" + name ];
			return elem.document.compatMode === "CSS1Compat" && docElemProp ||
				elem.document.body[ "client" + name ] || docElemProp;

		// Get document width or height
		} else if ( elem.nodeType === 9 ) {
			// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
			return Math.max(
				elem.documentElement["client" + name],
				elem.body["scroll" + name], elem.documentElement["scroll" + name],
				elem.body["offset" + name], elem.documentElement["offset" + name]
			);

		// Get or set width or height on the element
		} else if ( size === undefined ) {
			var orig = jQuery.css( elem, type ),
				ret = parseFloat( orig );

			return jQuery.isNaN( ret ) ? orig : ret;

		// Set the width or height on the element (default to pixels if value is unitless)
		} else {
			return this.css( type, typeof size === "string" ? size : size + "px" );
		}
	};

});


window.jQuery = window.$ = jQuery;
})(window);
/*!
 * jQuery UI 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * licensed under MIT 
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function( $, undefined ) {

// prevent duplicate loading
// this is only a problem because we proxy existing functions
// and we don't want to double proxy them
$.ui = $.ui || {};
if ( $.ui.version ) {
	return;
}

$.extend( $.ui, {
	version: "1.8.12",

	keyCode: {
		ALT: 18,
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		COMMAND: 91,
		COMMAND_LEFT: 91, // COMMAND
		COMMAND_RIGHT: 93,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		MENU: 93, // COMMAND_RIGHT
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38,
		WINDOWS: 91 // COMMAND
	}
});

// plugins
$.fn.extend({
	_focus: $.fn.focus,
	focus: function( delay, fn ) {
		return typeof delay === "number" ?
			this.each(function() {
				var elem = this;
				setTimeout(function() {
					$( elem ).focus();
					if ( fn ) {
						fn.call( elem );
					}
				}, delay );
			}) :
			this._focus.apply( this, arguments );
	},

	scrollParent: function() {
		var scrollParent;
		if (($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	},

	disableSelection: function() {
		return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
			".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
	},

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	}
});

$.each( [ "Width", "Height" ], function( i, name ) {
	var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
		type = name.toLowerCase(),
		orig = {
			innerWidth: $.fn.innerWidth,
			innerHeight: $.fn.innerHeight,
			outerWidth: $.fn.outerWidth,
			outerHeight: $.fn.outerHeight
		};

	function reduce( elem, size, border, margin ) {
		$.each( side, function() {
			size -= parseFloat( $.curCSS( elem, "padding" + this, true) ) || 0;
			if ( border ) {
				size -= parseFloat( $.curCSS( elem, "border" + this + "Width", true) ) || 0;
			}
			if ( margin ) {
				size -= parseFloat( $.curCSS( elem, "margin" + this, true) ) || 0;
			}
		});
		return size;
	}

	$.fn[ "inner" + name ] = function( size ) {
		if ( size === undefined ) {
			return orig[ "inner" + name ].call( this );
		}

		return this.each(function() {
			$( this ).css( type, reduce( this, size ) + "px" );
		});
	};

	$.fn[ "outer" + name] = function( size, margin ) {
		if ( typeof size !== "number" ) {
			return orig[ "outer" + name ].call( this, size );
		}

		return this.each(function() {
			$( this).css( type, reduce( this, size, true, margin ) + "px" );
		});
	};
});

// selectors
function visible( element ) {
	return !$( element ).parents().andSelf().filter(function() {
		return $.curCSS( this, "visibility" ) === "hidden" ||
			$.expr.filters.hidden( this );
	}).length;
}

$.extend( $.expr[ ":" ], {
	data: function( elem, i, match ) {
		return !!$.data( elem, match[ 3 ] );
	},

	focusable: function( element ) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr( element, "tabindex" );
		if ( "area" === nodeName ) {
			var map = element.parentNode,
				mapName = map.name,
				img;
			if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
				return false;
			}
			img = $( "img[usemap=#" + mapName + "]" )[0];
			return !!img && visible( img );
		}
		return ( /input|select|textarea|button|object/.test( nodeName )
			? !element.disabled
			: "a" == nodeName
				? element.href || !isNaN( tabIndex )
				: !isNaN( tabIndex ))
			// the element and all of its ancestors must be visible
			&& visible( element );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" );
		return ( isNaN( tabIndex ) || tabIndex >= 0 ) && $( element ).is( ":focusable" );
	}
});

// support
$(function() {
	var body = document.body,
		div = body.appendChild( div = document.createElement( "div" ) );

	$.extend( div.style, {
		minHeight: "100px",
		height: "auto",
		padding: 0,
		borderWidth: 0
	});

	$.support.minHeight = div.offsetHeight === 100;
	$.support.selectstart = "onselectstart" in div;

	// set display to none to avoid a layout bug in IE
	// http://dev.jquery.com/ticket/4014
	body.removeChild( div ).style.display = "none";
});





// deprecated
$.extend( $.ui, {
	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function( module, option, set ) {
			var proto = $.ui[ module ].prototype;
			for ( var i in set ) {
				proto.plugins[ i ] = proto.plugins[ i ] || [];
				proto.plugins[ i ].push( [ option, set[ i ] ] );
			}
		},
		call: function( instance, name, args ) {
			var set = instance.plugins[ name ];
			if ( !set || !instance.element[ 0 ].parentNode ) {
				return;
			}
	
			for ( var i = 0; i < set.length; i++ ) {
				if ( instance.options[ set[ i ][ 0 ] ] ) {
					set[ i ][ 1 ].apply( instance.element, args );
				}
			}
		}
	},
	
	// will be deprecated when we switch to jQuery 1.4 - use jQuery.contains()
	contains: function( a, b ) {
		return document.compareDocumentPosition ?
			a.compareDocumentPosition( b ) & 16 :
			a !== b && a.contains( b );
	},
	
	// only used by resizable
	hasScroll: function( el, a ) {
	
		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}
	
		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;
	
		if ( el[ scroll ] > 0 ) {
			return true;
		}
	
		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},
	
	// these are odd functions, fix the API or move into individual plugins
	isOverAxis: function( x, reference, size ) {
		//Determines when x coordinate is over "b" element axis
		return ( x > reference ) && ( x < ( reference + size ) );
	},
	isOver: function( y, x, top, left, height, width ) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
	}
});

})( jQuery );
/*!
 * jQuery UI Widget 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function( $, undefined ) {

// jQuery 1.4+
if ( $.cleanData ) {
	var _cleanData = $.cleanData;
	$.cleanData = function( elems ) {
		for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
			$( elem ).triggerHandler( "remove" );
		}
		_cleanData( elems );
	};
} else {
	var _remove = $.fn.remove;
	$.fn.remove = function( selector, keepData ) {
		return this.each(function() {
			if ( !keepData ) {
				if ( !selector || $.filter( selector, [ this ] ).length ) {
					$( "*", this ).add( [ this ] ).each(function() {
						$( this ).triggerHandler( "remove" );
					});
				}
			}
			return _remove.call( $(this), selector, keepData );
		});
	};
}

$.widget = function( name, base, prototype ) {
	var namespace = name.split( "." )[ 0 ],
		fullName;
	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName ] = function( elem ) {
		return !!$.data( elem, name );
	};

	$[ namespace ] = $[ namespace ] || {};
	$[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without initializing for simple inheritance
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	var basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
//	$.each( basePrototype, function( key, val ) {
//		if ( $.isPlainObject(val) ) {
//			basePrototype[ key ] = $.extend( {}, val );
//		}
//	});
	basePrototype.options = $.extend( true, {}, basePrototype.options );
	$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
		namespace: namespace,
		widgetName: name,
		widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
		widgetBaseClass: fullName
	}, prototype );

	$.widget.bridge( name, $[ namespace ][ name ] );
};

$.widget.bridge = function( name, object ) {
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = Array.prototype.slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.extend.apply( null, [ true, options ].concat(args) ) :
			options;

		// prevent calls to internal methods
		if ( isMethodCall && options.charAt( 0 ) === "_" ) {
			return returnValue;
		}

		if ( isMethodCall ) {
			this.each(function() {
				var instance = $.data( this, name ),
					methodValue = instance && $.isFunction( instance[options] ) ?
						instance[ options ].apply( instance, args ) :
						instance;
				// TODO: add this back in 1.9 and use $.error() (see #5972)
//				if ( !instance ) {
//					throw "cannot call methods on " + name + " prior to initialization; " +
//						"attempted to call method '" + options + "'";
//				}
//				if ( !$.isFunction( instance[options] ) ) {
//					throw "no such method '" + options + "' for " + name + " widget instance";
//				}
//				var methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, name );
				if ( instance ) {
					instance.option( options || {} )._init();
				} else {
					$.data( this, name, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( options, element ) {
	// allow instantiation without initializing for simple inheritance
	if ( arguments.length ) {
		this._createWidget( options, element );
	}
};

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	options: {
		disabled: false
	},
	_createWidget: function( options, element ) {
		// $.widget.bridge stores the plugin instance, but we do it anyway
		// so that it's stored even before the _create function runs
		$.data( element, this.widgetName, this );
		this.element = $( element );
		this.options = $.extend( true, {},
			this.options,
			this._getCreateOptions(),
			options );

		var self = this;
		this.element.bind( "remove." + this.widgetName, function() {
			self.destroy();
		});

		this._create();
		this._trigger( "create" );
		this._init();
	},
	_getCreateOptions: function() {
		return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ];
	},
	_create: function() {},
	_init: function() {},

	destroy: function() {
		this.element
			.unbind( "." + this.widgetName )
			.removeData( this.widgetName );
		this.widget()
			.unbind( "." + this.widgetName )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetBaseClass + "-disabled " +
				"ui-state-disabled" );
	},

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.extend( {}, this.options );
		}

		if  (typeof key === "string" ) {
			if ( value === undefined ) {
				return this.options[ key ];
			}
			options = {};
			options[ key ] = value;
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var self = this;
		$.each( options, function( key, value ) {
			self._setOption( key, value );
		});

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				[ value ? "addClass" : "removeClass"](
					this.widgetBaseClass + "-disabled" + " " +
					"ui-state-disabled" )
				.attr( "aria-disabled", value );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_trigger: function( type, event, data ) {
		var callback = this.options[ type ];

		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		data = data || {};

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if ( event.originalEvent ) {
			for ( var i = $.event.props.length, prop; i; ) {
				prop = $.event.props[ --i ];
				event[ prop ] = event.originalEvent[ prop ];
			}
		}

		this.element.trigger( event, data );

		return !( $.isFunction(callback) &&
			callback.call( this.element[0], event, data ) === false ||
			event.isDefaultPrevented() );
	}
};

})( jQuery );
/*!
 * jQuery UI Mouse 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Mouse
 *
 * Depends:
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget("ui.mouse", {
	options: {
		cancel: ':input,option',
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if (true === $.data(event.target, self.widgetName + '.preventClickEvent')) {
				    $.removeData(event.target, self.widgetName + '.preventClickEvent');
					event.stopImmediatePropagation();
					return false;
				}
			});

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if (true === $.data(event.target, this.widgetName + '.preventClickEvent')) {
			$.removeData(event.target, this.widgetName + '.preventClickEvent');
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		event.preventDefault();
		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !(document.documentMode >= 9) && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;

			if (event.target == this._mouseDownEvent.target) {
			    $.data(event.target, this.widgetName + '.preventClickEvent', true);
			}

			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
});

})(jQuery);
/*
 * jQuery UI Draggable 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget("ui.draggable", $.ui.mouse, {
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false
	},
	_create: function() {

		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
			this.element[0].style.position = 'relative';

		(this.options.addClasses && this.element.addClass("ui-draggable"));
		(this.options.disabled && this.element.addClass("ui-draggable-disabled"));

		this._mouseInit();

	},

	destroy: function() {
		if(!this.element.data('draggable')) return;
		this.element
			.removeData("draggable")
			.unbind(".draggable")
			.removeClass("ui-draggable"
				+ " ui-draggable-dragging"
				+ " ui-draggable-disabled");
		this._mouseDestroy();

		return this;
	},

	_mouseCapture: function(event) {

		var o = this.options;

		// among others, prevent a drag on a resizable-handle
		if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
			return false;

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle)
			return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css("position");
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.positionAbs = this.element.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		//Trigger event + callbacks
		if(this._trigger("start", event) === false) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.helper.addClass("ui-draggable-dragging");
		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;
	},

	_mouseDrag: function(event, noPropagation) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if (!noPropagation) {
			var ui = this._uiHash();
			if(this._trigger('drag', event, ui) === false) {
				this._mouseUp({});
				return false;
			}
			this.position = ui.position;
		}

		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			dropped = $.ui.ddmanager.drop(this, event);

		//if a drop comes from outside (a sortable)
		if(this.dropped) {
			dropped = this.dropped;
			this.dropped = false;
		}
		
		//if the original element is removed, don't bother to continue if helper is set to "original"
		if((!this.element[0] || !this.element[0].parentNode) && this.options.helper == "original")
			return false;

		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			var self = this;
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				if(self._trigger("stop", event) !== false) {
					self._clear();
				}
			});
		} else {
			if(this._trigger("stop", event) !== false) {
				this._clear();
			}
		}

		return false;
	},
	
	cancel: function() {
		
		if(this.helper.is(".ui-draggable-dragging")) {
			this._mouseUp({});
		} else {
			this._clear();
		}
		
		return this;
		
	},

	_getHandle: function(event) {

		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
		$(this.options.handle, this.element)
			.find("*")
			.andSelf()
			.each(function() {
				if(this == event.target) handle = true;
			});

		return handle;

	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element);

		if(!helper.parents('body').length)
			helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

		if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
			helper.css("position", "absolute");

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj == 'string') {
			obj = obj.split(' ');
		}
		if ($.isArray(obj)) {
			obj = {left: +obj[0], top: +obj[1] || 0};
		}
		if ('left' in obj) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ('right' in obj) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ('top' in obj) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ('bottom' in obj) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.element.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"),10) || 0),
			top: (parseInt(this.element.css("marginTop"),10) || 0),
			right: (parseInt(this.element.css("marginRight"),10) || 0),
			bottom: (parseInt(this.element.css("marginBottom"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			(o.containment == 'document' ? 0 : $(window).scrollLeft()) - this.offset.relative.left - this.offset.parent.left,
			(o.containment == 'document' ? 0 : $(window).scrollTop()) - this.offset.relative.top - this.offset.parent.top,
			(o.containment == 'document' ? 0 : $(window).scrollLeft()) + $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
			(o.containment == 'document' ? 0 : $(window).scrollTop()) + ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
		];

		if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) {
			var ce = $(o.containment)[0]; if(!ce) return;
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0),
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0),
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top  - this.margins.bottom
			];
		} else if(o.containment.constructor == Array) {
			this.containment = o.containment;
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// The absolute mouse position
				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left																// The absolute mouse position
				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
		var pageX = event.pageX;
		var pageY = event.pageY;

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
			}

			if(o.grid) {
				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && $.browser.version < 526 && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
		this.helper = null;
		this.cancelHelperRemoval = false;
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function(type, event, ui) {
		ui = ui || this._uiHash();
		$.ui.plugin.call(this, type, [event, ui]);
		if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
		return $.Widget.prototype._trigger.call(this, type, event, ui);
	},

	plugins: {},

	_uiHash: function(event) {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

});

$.extend($.ui.draggable, {
	version: "1.8.12"
});

$.ui.plugin.add("draggable", "connectToSortable", {
	start: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options,
			uiSortable = $.extend({}, ui, { item: inst.element });
		inst.sortables = [];
		$(o.connectToSortable).each(function() {
			var sortable = $.data(this, 'sortable');
			if (sortable && !sortable.options.disabled) {
				inst.sortables.push({
					instance: sortable,
					shouldRevert: sortable.options.revert
				});
				sortable.refreshPositions();	// Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
				sortable._trigger("activate", event, uiSortable);
			}
		});

	},
	stop: function(event, ui) {

		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("draggable"),
			uiSortable = $.extend({}, ui, { item: inst.element });

		$.each(inst.sortables, function() {
			if(this.instance.isOver) {

				this.instance.isOver = 0;

				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)

				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
				if(this.shouldRevert) this.instance.options.revert = true;

				//Trigger the stop of the sortable
				this.instance._mouseStop(event);

				this.instance.options.helper = this.instance.options._helper;

				//If the helper has been the original item, restore properties in the sortable
				if(inst.options.helper == 'original')
					this.instance.currentItem.css({ top: 'auto', left: 'auto' });

			} else {
				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
				this.instance._trigger("deactivate", event, uiSortable);
			}

		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), self = this;

		var checkPos = function(o) {
			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
			var itemHeight = o.height, itemWidth = o.width;
			var itemTop = o.top, itemLeft = o.left;

			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
		};

		$.each(inst.sortables, function(i) {
			
			//Copy over some variables to allow calling the sortable's native _intersectsWith
			this.instance.positionAbs = inst.positionAbs;
			this.instance.helperProportions = inst.helperProportions;
			this.instance.offset.click = inst.offset.click;
			
			if(this.instance._intersectsWith(this.instance.containerCache)) {

				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {

					this.instance.isOver = 1;
					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };

					event.target = this.instance.currentItem[0];
					this.instance._mouseCapture(event, true);
					this.instance._mouseStart(event, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

					inst._trigger("toSortable", event);
					inst.dropped = this.instance.element; //draggable revert needs that
					//hack so receive/update callbacks work (mostly)
					inst.currentItem = inst.element;
					this.instance.fromOutside = inst;

				}

				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) this.instance._mouseDrag(event);

			} else {

				//If it doesn't intersect with the sortable, and it intersected before,
				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
				if(this.instance.isOver) {

					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;
					
					//Prevent reverting on this forced stop
					this.instance.options.revert = false;
					
					// The out event needs to be triggered independently
					this.instance._trigger('out', event, this.instance._uiHash(this.instance));
					
					this.instance._mouseStop(event, true);
					this.instance.options.helper = this.instance.options._helper;

					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) this.instance.placeholder.remove();

					inst._trigger("fromSortable", event);
					inst.dropped = false; //draggable revert needs that
				}

			};

		});

	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function(event, ui) {
		var t = $('body'), o = $(this).data('draggable').options;
		if (t.css("cursor")) o._cursor = t.css("cursor");
		t.css("cursor", o.cursor);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if (o._cursor) $('body').css("cursor", o._cursor);
	}
});

$.ui.plugin.add("draggable", "iframeFix", {
	start: function(event, ui) {
		var o = $(this).data('draggable').options;
		$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});
	},
	stop: function(event, ui) {
		$("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data('draggable').options;
		if(t.css("opacity")) o._opacity = t.css("opacity");
		t.css('opacity', o.opacity);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if(o._opacity) $(ui.helper).css('opacity', o._opacity);
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function(event, ui) {
		var i = $(this).data("draggable");
		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();
	},
	drag: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options, scrolled = false;

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {

			if(!o.axis || o.axis != 'x') {
				if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
				else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
			}

			if(!o.axis || o.axis != 'y') {
				if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
				else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
			}

		} else {

			if(!o.axis || o.axis != 'x') {
				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
			}

			if(!o.axis || o.axis != 'y') {
				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
			}

		}

		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(i, event);

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options;
		i.snapElements = [];

		$(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() {
			var $t = $(this); var $o = $t.offset();
			if(this != i.element[0]) i.snapElements.push({
				item: this,
				width: $t.outerWidth(), height: $t.outerHeight(),
				top: $o.top, left: $o.left
			});
		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options;
		var d = o.snapTolerance;

		var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for (var i = inst.snapElements.length - 1; i >= 0; i--){

			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;

			//Yes, I know, this is insane ;)
			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				inst.snapElements[i].snapping = false;
				continue;
			}

			if(o.snapMode != 'inner') {
				var ts = Math.abs(t - y2) <= d;
				var bs = Math.abs(b - y1) <= d;
				var ls = Math.abs(l - x2) <= d;
				var rs = Math.abs(r - x1) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
			}

			var first = (ts || bs || ls || rs);

			if(o.snapMode != 'outer') {
				var ts = Math.abs(t - y1) <= d;
				var bs = Math.abs(b - y2) <= d;
				var ls = Math.abs(l - x1) <= d;
				var rs = Math.abs(r - x2) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
			}

			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		};

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function(event, ui) {

		var o = $(this).data("draggable").options;

		var group = $.makeArray($(o.stack)).sort(function(a,b) {
			return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0);
		});
		if (!group.length) { return; }
		
		var min = parseInt(group[0].style.zIndex) || 0;
		$(group).each(function(i) {
			this.style.zIndex = min + i;
		});

		this[0].style.zIndex = min + group.length;

	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data("draggable").options;
		if(t.css("zIndex")) o._zIndex = t.css("zIndex");
		t.css('zIndex', o.zIndex);
	},
	stop: function(event, ui) {
		var o = $(this).data("draggable").options;
		if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex);
	}
});

})(jQuery);
/*
 * jQuery UI Droppable 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Droppables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.mouse.js
 *	jquery.ui.draggable.js
 */
(function( $, undefined ) {

$.widget("ui.droppable", {
	widgetEventPrefix: "drop",
	options: {
		accept: '*',
		activeClass: false,
		addClasses: true,
		greedy: false,
		hoverClass: false,
		scope: 'default',
		tolerance: 'intersect'
	},
	_create: function() {

		var o = this.options, accept = o.accept;
		this.isover = 0; this.isout = 1;

		this.accept = $.isFunction(accept) ? accept : function(d) {
			return d.is(accept);
		};

		//Store the droppable's proportions
		this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };

		// Add the reference and positions to the manager
		$.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
		$.ui.ddmanager.droppables[o.scope].push(this);

		(o.addClasses && this.element.addClass("ui-droppable"));

	},

	destroy: function() {
		var drop = $.ui.ddmanager.droppables[this.options.scope];
		for ( var i = 0; i < drop.length; i++ )
			if ( drop[i] == this )
				drop.splice(i, 1);

		this.element
			.removeClass("ui-droppable ui-droppable-disabled")
			.removeData("droppable")
			.unbind(".droppable");

		return this;
	},

	_setOption: function(key, value) {

		if(key == 'accept') {
			this.accept = $.isFunction(value) ? value : function(d) {
				return d.is(value);
			};
		}
		$.Widget.prototype._setOption.apply(this, arguments);
	},

	_activate: function(event) {
		var draggable = $.ui.ddmanager.current;
		if(this.options.activeClass) this.element.addClass(this.options.activeClass);
		(draggable && this._trigger('activate', event, this.ui(draggable)));
	},

	_deactivate: function(event) {
		var draggable = $.ui.ddmanager.current;
		if(this.options.activeClass) this.element.removeClass(this.options.activeClass);
		(draggable && this._trigger('deactivate', event, this.ui(draggable)));
	},

	_over: function(event) {

		var draggable = $.ui.ddmanager.current;
		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element

		if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
			if(this.options.hoverClass) this.element.addClass(this.options.hoverClass);
			this._trigger('over', event, this.ui(draggable));
		}

	},

	_out: function(event) {

		var draggable = $.ui.ddmanager.current;
		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element

		if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
			if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass);
			this._trigger('out', event, this.ui(draggable));
		}

	},

	_drop: function(event,custom) {

		var draggable = custom || $.ui.ddmanager.current;
		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element

		var childrenIntersection = false;
		this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() {
			var inst = $.data(this, 'droppable');
			if(
				inst.options.greedy
				&& !inst.options.disabled
				&& inst.options.scope == draggable.options.scope
				&& inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element))
				&& $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)
			) { childrenIntersection = true; return false; }
		});
		if(childrenIntersection) return false;

		if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
			if(this.options.activeClass) this.element.removeClass(this.options.activeClass);
			if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass);
			this._trigger('drop', event, this.ui(draggable));
			return this.element;
		}

		return false;

	},

	ui: function(c) {
		return {
			draggable: (c.currentItem || c.element),
			helper: c.helper,
			position: c.position,
			offset: c.positionAbs
		};
	}

});

$.extend($.ui.droppable, {
	version: "1.8.12"
});

$.ui.intersect = function(draggable, droppable, toleranceMode) {

	if (!droppable.offset) return false;

	var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
		y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height;
	var l = droppable.offset.left, r = l + droppable.proportions.width,
		t = droppable.offset.top, b = t + droppable.proportions.height;

	switch (toleranceMode) {
		case 'fit':
			return (l <= x1 && x2 <= r
				&& t <= y1 && y2 <= b);
			break;
		case 'intersect':
			return (l < x1 + (draggable.helperProportions.width / 2) // Right Half
				&& x2 - (draggable.helperProportions.width / 2) < r // Left Half
				&& t < y1 + (draggable.helperProportions.height / 2) // Bottom Half
				&& y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
			break;
		case 'pointer':
			var draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left),
				draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top),
				isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width);
			return isOver;
			break;
		case 'touch':
			return (
					(y1 >= t && y1 <= b) ||	// Top edge touching
					(y2 >= t && y2 <= b) ||	// Bottom edge touching
					(y1 < t && y2 > b)		// Surrounded vertically
				) && (
					(x1 >= l && x1 <= r) ||	// Left edge touching
					(x2 >= l && x2 <= r) ||	// Right edge touching
					(x1 < l && x2 > r)		// Surrounded horizontally
				);
			break;
		default:
			return false;
			break;
		}

};

/*
	This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
	current: null,
	droppables: { 'default': [] },
	prepareOffsets: function(t, event) {

		var m = $.ui.ddmanager.droppables[t.options.scope] || [];
		var type = event ? event.type : null; // workaround for #2317
		var list = (t.currentItem || t.element).find(":data(droppable)").andSelf();

		droppablesLoop: for (var i = 0; i < m.length; i++) {

			if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) continue;	//No disabled and non-accepted
			for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item
			m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; 									//If the element is not visible, continue

			if(type == "mousedown") m[i]._activate.call(m[i], event); //Activate the droppable if used directly from draggables

			m[i].offset = m[i].element.offset();
			m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight };

		}

	},
	drop: function(draggable, event) {

		var dropped = false;
		$.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {

			if(!this.options) return;
			if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance))
				dropped = dropped || this._drop.call(this, event);

			if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
				this.isout = 1; this.isover = 0;
				this._deactivate.call(this, event);
			}

		});
		return dropped;

	},
	drag: function(draggable, event) {

		//If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
		if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event);

		//Run through all droppables and check their positions based on specific tolerance options
		$.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {

			if(this.options.disabled || this.greedyChild || !this.visible) return;
			var intersects = $.ui.intersect(draggable, this, this.options.tolerance);

			var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null);
			if(!c) return;

			var parentInstance;
			if (this.options.greedy) {
				var parent = this.element.parents(':data(droppable):eq(0)');
				if (parent.length) {
					parentInstance = $.data(parent[0], 'droppable');
					parentInstance.greedyChild = (c == 'isover' ? 1 : 0);
				}
			}

			// we just moved into a greedy child
			if (parentInstance && c == 'isover') {
				parentInstance['isover'] = 0;
				parentInstance['isout'] = 1;
				parentInstance._out.call(parentInstance, event);
			}

			this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0;
			this[c == "isover" ? "_over" : "_out"].call(this, event);

			// we just moved out of a greedy child
			if (parentInstance && c == 'isout') {
				parentInstance['isout'] = 0;
				parentInstance['isover'] = 1;
				parentInstance._over.call(parentInstance, event);
			}
		});

	}
};

})(jQuery);
/*
 * jQuery UI Resizable 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Resizables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget("ui.resizable", $.ui.mouse, {
	widgetEventPrefix: "resize",
	options: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		containment: false,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,
		zIndex: 1000
	},
	_create: function() {

		var self = this, o = this.options;
		this.element.addClass("ui-resizable");

		$.extend(this, {
			_aspectRatio: !!(o.aspectRatio),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null
		});

		//Wrap the element if it cannot hold child nodes
		if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {

			//Opera fix for relative positioning
			if (/relative/.test(this.element.css('position')) && $.browser.opera)
				this.element.css({ position: 'relative', top: 'auto', left: 'auto' });

			//Create a wrapper element and set the wrapper to the new current internal element
			this.element.wrap(
				$('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({
					position: this.element.css('position'),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css('top'),
					left: this.element.css('left')
				})
			);

			//Overwrite the original this.element
			this.element = this.element.parent().data(
				"resizable", this.element.data('resizable')
			);

			this.elementIsWrapper = true;

			//Move margins to the wrapper
			this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
			this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});

			//Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css('resize');
			this.originalElement.css('resize', 'none');

			//Push the actual element to our proportionallyResize internal array
			this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' }));

			// avoid IE jump (hard set the margin)
			this.originalElement.css({ margin: this.originalElement.css('margin') });

			// fix handlers offset
			this._proportionallyResize();

		}

		this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' });
		if(this.handles.constructor == String) {

			if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw';
			var n = this.handles.split(","); this.handles = {};

			for(var i = 0; i < n.length; i++) {

				var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle;
				var axis = $('<div class="ui-resizable-handle ' + hname + '"></div>');

				// increase zIndex of sw, se, ne, nw axis
				//TODO : this modifies original option
				if(/sw|se|ne|nw/.test(handle)) axis.css({ zIndex: ++o.zIndex });

				//TODO : What's going on here?
				if ('se' == handle) {
					axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se');
				};

				//Insert into internal handles object and append to element
				this.handles[handle] = '.ui-resizable-'+handle;
				this.element.append(axis);
			}

		}

		this._renderAxis = function(target) {

			target = target || this.element;

			for(var i in this.handles) {

				if(this.handles[i].constructor == String)
					this.handles[i] = $(this.handles[i], this.element).show();

				//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
				if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {

					var axis = $(this.handles[i], this.element), padWrapper = 0;

					//Checking the correct pad and border
					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();

					//The padding type i have to apply...
					var padPos = [ 'padding',
						/ne|nw|n/.test(i) ? 'Top' :
						/se|sw|s/.test(i) ? 'Bottom' :
						/^e$/.test(i) ? 'Right' : 'Left' ].join("");

					target.css(padPos, padWrapper);

					this._proportionallyResize();

				}

				//TODO: What's that good for? There's not anything to be executed left
				if(!$(this.handles[i]).length)
					continue;

			}
		};

		//TODO: make renderAxis a prototype function
		this._renderAxis(this.element);

		this._handles = $('.ui-resizable-handle', this.element)
			.disableSelection();

		//Matching axis name
		this._handles.mouseover(function() {
			if (!self.resizing) {
				if (this.className)
					var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
				//Axis, default = se
				self.axis = axis && axis[1] ? axis[1] : 'se';
			}
		});

		//If we want to auto hide the elements
		if (o.autoHide) {
			this._handles.hide();
			$(this.element)
				.addClass("ui-resizable-autohide")
				.hover(function() {
					$(this).removeClass("ui-resizable-autohide");
					self._handles.show();
				},
				function(){
					if (!self.resizing) {
						$(this).addClass("ui-resizable-autohide");
						self._handles.hide();
					}
				});
		}

		//Initialize the mouse interaction
		this._mouseInit();

	},

	destroy: function() {

		this._mouseDestroy();

		var _destroy = function(exp) {
			$(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
				.removeData("resizable").unbind(".resizable").find('.ui-resizable-handle').remove();
		};

		//TODO: Unwrap at same DOM position
		if (this.elementIsWrapper) {
			_destroy(this.element);
			var wrapper = this.element;
			wrapper.after(
				this.originalElement.css({
					position: wrapper.css('position'),
					width: wrapper.outerWidth(),
					height: wrapper.outerHeight(),
					top: wrapper.css('top'),
					left: wrapper.css('left')
				})
			).remove();
		}

		this.originalElement.css('resize', this.originalResizeStyle);
		_destroy(this.originalElement);

		return this;
	},

	_mouseCapture: function(event) {
		var handle = false;
		for (var i in this.handles) {
			if ($(this.handles[i])[0] == event.target) {
				handle = true;
			}
		}

		return !this.options.disabled && handle;
	},

	_mouseStart: function(event) {

		var o = this.options, iniPos = this.element.position(), el = this.element;

		this.resizing = true;
		this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() };

		// bugfix for http://dev.jquery.com/ticket/1749
		if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) {
			el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left });
		}

		//Opera fixing relative position
		if ($.browser.opera && (/relative/).test(el.css('position')))
			el.css({ position: 'relative', top: 'auto', left: 'auto' });

		this._renderProxy();

		var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top'));

		if (o.containment) {
			curleft += $(o.containment).scrollLeft() || 0;
			curtop += $(o.containment).scrollTop() || 0;
		}

		//Store needed variables
		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };
		this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
		this.originalPosition = { left: curleft, top: curtop };
		this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		//Aspect Ratio
		this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);

	    var cursor = $('.ui-resizable-' + this.axis).css('cursor');
	    $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor);

		el.addClass("ui-resizable-resizing");
		this._propagate("start", event);
		return true;
	},

	_mouseDrag: function(event) {

		//Increase performance, avoid regex
		var el = this.helper, o = this.options, props = {},
			self = this, smp = this.originalMousePosition, a = this.axis;

		var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0;
		var trigger = this._change[a];
		if (!trigger) return false;

		// Calculate the attrs that will be change
		var data = trigger.apply(this, [event, dx, dy]), ie6 = $.browser.msie && $.browser.version < 7, csdif = this.sizeDiff;

		if (this._aspectRatio || event.shiftKey)
			data = this._updateRatio(data, event);

		data = this._respectSize(data, event);

		// plugins callbacks need to be called first
		this._propagate("resize", event);

		el.css({
			top: this.position.top + "px", left: this.position.left + "px",
			width: this.size.width + "px", height: this.size.height + "px"
		});

		if (!this._helper && this._proportionallyResizeElements.length)
			this._proportionallyResize();

		this._updateCache(data);

		// calling the user callback at the end
		this._trigger('resize', event, this.ui());

		return false;
	},

	_mouseStop: function(event) {

		this.resizing = false;
		var o = this.options, self = this;

		if(this._helper) {
			var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
				soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
				soffsetw = ista ? 0 : self.sizeDiff.width;

			var s = { width: (self.helper.width()  - soffsetw), height: (self.helper.height() - soffseth) },
				left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
				top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

			if (!o.animate)
				this.element.css($.extend(s, { top: top, left: left }));

			self.helper.height(self.size.height);
			self.helper.width(self.size.width);

			if (this._helper && !o.animate) this._proportionallyResize();
		}

		$('body').css('cursor', 'auto');

		this.element.removeClass("ui-resizable-resizing");

		this._propagate("stop", event);

		if (this._helper) this.helper.remove();
		return false;

	},

	_updateCache: function(data) {
		var o = this.options;
		this.offset = this.helper.offset();
		if (isNumber(data.left)) this.position.left = data.left;
		if (isNumber(data.top)) this.position.top = data.top;
		if (isNumber(data.height)) this.size.height = data.height;
		if (isNumber(data.width)) this.size.width = data.width;
	},

	_updateRatio: function(data, event) {

		var o = this.options, cpos = this.position, csize = this.size, a = this.axis;

		if (data.height) data.width = (csize.height * this.aspectRatio);
		else if (data.width) data.height = (csize.width / this.aspectRatio);

		if (a == 'sw') {
			data.left = cpos.left + (csize.width - data.width);
			data.top = null;
		}
		if (a == 'nw') {
			data.top = cpos.top + (csize.height - data.height);
			data.left = cpos.left + (csize.width - data.width);
		}

		return data;
	},

	_respectSize: function(data, event) {

		var el = this.helper, o = this.options, pRatio = this._aspectRatio || event.shiftKey, a = this.axis,
				ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
					isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height);

		if (isminw) data.width = o.minWidth;
		if (isminh) data.height = o.minHeight;
		if (ismaxw) data.width = o.maxWidth;
		if (ismaxh) data.height = o.maxHeight;

		var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height;
		var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);

		if (isminw && cw) data.left = dw - o.minWidth;
		if (ismaxw && cw) data.left = dw - o.maxWidth;
		if (isminh && ch)	data.top = dh - o.minHeight;
		if (ismaxh && ch)	data.top = dh - o.maxHeight;

		// fixing jump error on top/left - bug #2330
		var isNotwh = !data.width && !data.height;
		if (isNotwh && !data.left && data.top) data.top = null;
		else if (isNotwh && !data.top && data.left) data.left = null;

		return data;
	},

	_proportionallyResize: function() {

		var o = this.options;
		if (!this._proportionallyResizeElements.length) return;
		var element = this.helper || this.element;

		for (var i=0; i < this._proportionallyResizeElements.length; i++) {

			var prel = this._proportionallyResizeElements[i];

			if (!this.borderDif) {
				var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')],
					p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')];

				this.borderDif = $.map(b, function(v, i) {
					var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0;
					return border + padding;
				});
			}

			if ($.browser.msie && !(!($(element).is(':hidden') || $(element).parents(':hidden').length)))
				continue;

			prel.css({
				height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
				width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
			});

		};

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if(this._helper) {

			this.helper = this.helper || $('<div style="overflow:hidden;"></div>');

			// fix ie6 offset TODO: This seems broken
			var ie6 = $.browser.msie && $.browser.version < 7, ie6offset = (ie6 ? 1 : 0),
			pxyoffset = ( ie6 ? 2 : -1 );

			this.helper.addClass(this._helper).css({
				width: this.element.outerWidth() + pxyoffset,
				height: this.element.outerHeight() + pxyoffset,
				position: 'absolute',
				left: this.elementOffset.left - ie6offset +'px',
				top: this.elementOffset.top - ie6offset +'px',
				zIndex: ++o.zIndex //TODO: Don't modify option
			});

			this.helper
				.appendTo("body")
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function(event, dx, dy) {
			return { width: this.originalSize.width + dx };
		},
		w: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function(event, dx, dy) {
			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function(event, dx, dy) {
			return { height: this.originalSize.height + dy };
		},
		se: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		sw: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		},
		ne: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
		},
		nw: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
		}
	},

	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [event, this.ui()]);
		(n != "resize" && this._trigger(n, event, this.ui()));
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

});

$.extend($.ui.resizable, {
	version: "1.8.12"
});

/*
 * Resizable Extensions
 */

$.ui.plugin.add("resizable", "alsoResize", {

	start: function (event, ui) {
		var self = $(this).data("resizable"), o = self.options;

		var _store = function (exp) {
			$(exp).each(function() {
				var el = $(this);
				el.data("resizable-alsoresize", {
					width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
					left: parseInt(el.css('left'), 10), top: parseInt(el.css('top'), 10),
					position: el.css('position') // to reset Opera on stop()
				});
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) {
			if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); }
			else { $.each(o.alsoResize, function (exp) { _store(exp); }); }
		}else{
			_store(o.alsoResize);
		}
	},

	resize: function (event, ui) {
		var self = $(this).data("resizable"), o = self.options, os = self.originalSize, op = self.originalPosition;

		var delta = {
			height: (self.size.height - os.height) || 0, width: (self.size.width - os.width) || 0,
			top: (self.position.top - op.top) || 0, left: (self.position.left - op.left) || 0
		},

		_alsoResize = function (exp, c) {
			$(exp).each(function() {
				var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, 
					css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ['width', 'height'] : ['width', 'height', 'top', 'left'];

				$.each(css, function (i, prop) {
					var sum = (start[prop]||0) + (delta[prop]||0);
					if (sum && sum >= 0)
						style[prop] = sum || null;
				});

				// Opera fixing relative position
				if ($.browser.opera && /relative/.test(el.css('position'))) {
					self._revertToRelativePosition = true;
					el.css({ position: 'absolute', top: 'auto', left: 'auto' });
				}

				el.css(style);
			});
		};

		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) {
			$.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); });
		}else{
			_alsoResize(o.alsoResize);
		}
	},

	stop: function (event, ui) {
		var self = $(this).data("resizable"), o = self.options;

		var _reset = function (exp) {
			$(exp).each(function() {
				var el = $(this);
				// reset position for Opera - no need to verify it was changed
				el.css({ position: el.data("resizable-alsoresize").position });
			});
		};

		if (self._revertToRelativePosition) {
			self._revertToRelativePosition = false;
			if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) {
				$.each(o.alsoResize, function (exp) { _reset(exp); });
			}else{
				_reset(o.alsoResize);
			}
		}

		$(this).removeData("resizable-alsoresize");
	}
});

$.ui.plugin.add("resizable", "animate", {

	stop: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options;

		var pr = self._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
					soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : self.sizeDiff.height,
						soffsetw = ista ? 0 : self.sizeDiff.width;

		var style = { width: (self.size.width - soffsetw), height: (self.size.height - soffseth) },
					left = (parseInt(self.element.css('left'), 10) + (self.position.left - self.originalPosition.left)) || null,
						top = (parseInt(self.element.css('top'), 10) + (self.position.top - self.originalPosition.top)) || null;

		self.element.animate(
			$.extend(style, top && left ? { top: top, left: left } : {}), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseInt(self.element.css('width'), 10),
						height: parseInt(self.element.css('height'), 10),
						top: parseInt(self.element.css('top'), 10),
						left: parseInt(self.element.css('left'), 10)
					};

					if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height });

					// propagating resize, and updating values for each animation step
					self._updateCache(data);
					self._propagate("resize", event);

				}
			}
		);
	}

});

$.ui.plugin.add("resizable", "containment", {

	start: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options, el = self.element;
		var oc = o.containment,	ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
		if (!ce) return;

		self.containerElement = $(ce);

		if (/document/.test(oc) || oc == document) {
			self.containerOffset = { left: 0, top: 0 };
			self.containerPosition = { left: 0, top: 0 };

			self.parentData = {
				element: $(document), left: 0, top: 0,
				width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
			};
		}

		// i'm a node, so compute top, left, right, bottom
		else {
			var element = $(ce), p = [];
			$([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });

			self.containerOffset = element.offset();
			self.containerPosition = element.position();
			self.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };

			var co = self.containerOffset, ch = self.containerSize.height,	cw = self.containerSize.width,
						width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);

			self.parentData = {
				element: ce, left: co.left, top: co.top, width: width, height: height
			};
		}
	},

	resize: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options,
				ps = self.containerSize, co = self.containerOffset, cs = self.size, cp = self.position,
				pRatio = self._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = self.containerElement;

		if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co;

		if (cp.left < (self._helper ? co.left : 0)) {
			self.size.width = self.size.width + (self._helper ? (self.position.left - co.left) : (self.position.left - cop.left));
			if (pRatio) self.size.height = self.size.width / o.aspectRatio;
			self.position.left = o.helper ? co.left : 0;
		}

		if (cp.top < (self._helper ? co.top : 0)) {
			self.size.height = self.size.height + (self._helper ? (self.position.top - co.top) : self.position.top);
			if (pRatio) self.size.width = self.size.height * o.aspectRatio;
			self.position.top = self._helper ? co.top : 0;
		}

		self.offset.left = self.parentData.left+self.position.left;
		self.offset.top = self.parentData.top+self.position.top;

		var woset = Math.abs( (self._helper ? self.offset.left - cop.left : (self.offset.left - cop.left)) + self.sizeDiff.width ),
					hoset = Math.abs( (self._helper ? self.offset.top - cop.top : (self.offset.top - co.top)) + self.sizeDiff.height );

		var isParent = self.containerElement.get(0) == self.element.parent().get(0),
		    isOffsetRelative = /relative|absolute/.test(self.containerElement.css('position'));

		if(isParent && isOffsetRelative) woset -= self.parentData.left;

		if (woset + self.size.width >= self.parentData.width) {
			self.size.width = self.parentData.width - woset;
			if (pRatio) self.size.height = self.size.width / self.aspectRatio;
		}

		if (hoset + self.size.height >= self.parentData.height) {
			self.size.height = self.parentData.height - hoset;
			if (pRatio) self.size.width = self.size.height * self.aspectRatio;
		}
	},

	stop: function(event, ui){
		var self = $(this).data("resizable"), o = self.options, cp = self.position,
				co = self.containerOffset, cop = self.containerPosition, ce = self.containerElement;

		var helper = $(self.helper), ho = helper.offset(), w = helper.outerWidth() - self.sizeDiff.width, h = helper.outerHeight() - self.sizeDiff.height;

		if (self._helper && !o.animate && (/relative/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

		if (self._helper && !o.animate && (/static/).test(ce.css('position')))
			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });

	}
});

$.ui.plugin.add("resizable", "ghost", {

	start: function(event, ui) {

		var self = $(this).data("resizable"), o = self.options, cs = self.size;

		self.ghost = self.originalElement.clone();
		self.ghost
			.css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 })
			.addClass('ui-resizable-ghost')
			.addClass(typeof o.ghost == 'string' ? o.ghost : '');

		self.ghost.appendTo(self.helper);

	},

	resize: function(event, ui){
		var self = $(this).data("resizable"), o = self.options;
		if (self.ghost) self.ghost.css({ position: 'relative', height: self.size.height, width: self.size.width });
	},

	stop: function(event, ui){
		var self = $(this).data("resizable"), o = self.options;
		if (self.ghost && self.helper) self.helper.get(0).removeChild(self.ghost.get(0));
	}

});

$.ui.plugin.add("resizable", "grid", {

	resize: function(event, ui) {
		var self = $(this).data("resizable"), o = self.options, cs = self.size, os = self.originalSize, op = self.originalPosition, a = self.axis, ratio = o._aspectRatio || event.shiftKey;
		o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid;
		var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1);

		if (/^(se|s|e)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
		}
		else if (/^(ne)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
		}
		else if (/^(sw)$/.test(a)) {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.left = op.left - ox;
		}
		else {
			self.size.width = os.width + ox;
			self.size.height = os.height + oy;
			self.position.top = op.top - oy;
			self.position.left = op.left - ox;
		}
	}

});

var num = function(v) {
	return parseInt(v, 10) || 0;
};

var isNumber = function(value) {
	return !isNaN(parseInt(value, 10));
};

})(jQuery);
/*
 * jQuery UI Selectable 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Selectables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget("ui.selectable", $.ui.mouse, {
	options: {
		appendTo: 'body',
		autoRefresh: true,
		distance: 0,
		filter: '*',
		tolerance: 'touch'
	},
	_create: function() {
		var self = this;

		this.element.addClass("ui-selectable");

		this.dragged = false;

		// cache selectee children based on filter
		var selectees;
		this.refresh = function() {
			selectees = $(self.options.filter, self.element[0]);
			selectees.each(function() {
				var $this = $(this);
				var pos = $this.offset();
				$.data(this, "selectable-item", {
					element: this,
					$element: $this,
					left: pos.left,
					top: pos.top,
					right: pos.left + $this.outerWidth(),
					bottom: pos.top + $this.outerHeight(),
					startselected: false,
					selected: $this.hasClass('ui-selected'),
					selecting: $this.hasClass('ui-selecting'),
					unselecting: $this.hasClass('ui-unselecting')
				});
			});
		};
		this.refresh();

		this.selectees = selectees.addClass("ui-selectee");

		this._mouseInit();

		this.helper = $("<div class='ui-selectable-helper'></div>");
	},

	destroy: function() {
		this.selectees
			.removeClass("ui-selectee")
			.removeData("selectable-item");
		this.element
			.removeClass("ui-selectable ui-selectable-disabled")
			.removeData("selectable")
			.unbind(".selectable");
		this._mouseDestroy();

		return this;
	},

	_mouseStart: function(event) {
		var self = this;

		this.opos = [event.pageX, event.pageY];

		if (this.options.disabled)
			return;

		var options = this.options;

		this.selectees = $(options.filter, this.element[0]);

		this._trigger("start", event);

		$(options.appendTo).append(this.helper);
		// position helper (lasso)
		this.helper.css({
			"left": event.clientX,
			"top": event.clientY,
			"width": 0,
			"height": 0
		});

		if (options.autoRefresh) {
			this.refresh();
		}

		this.selectees.filter('.ui-selected').each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.startselected = true;
			if (!event.metaKey) {
				selectee.$element.removeClass('ui-selected');
				selectee.selected = false;
				selectee.$element.addClass('ui-unselecting');
				selectee.unselecting = true;
				// selectable UNSELECTING callback
				self._trigger("unselecting", event, {
					unselecting: selectee.element
				});
			}
		});

		$(event.target).parents().andSelf().each(function() {
			var selectee = $.data(this, "selectable-item");
			if (selectee) {
				var doSelect = !event.metaKey || !selectee.$element.hasClass('ui-selected');
				selectee.$element
					.removeClass(doSelect ? "ui-unselecting" : "ui-selected")
					.addClass(doSelect ? "ui-selecting" : "ui-unselecting");
				selectee.unselecting = !doSelect;
				selectee.selecting = doSelect;
				selectee.selected = doSelect;
				// selectable (UN)SELECTING callback
				if (doSelect) {
					self._trigger("selecting", event, {
						selecting: selectee.element
					});
				} else {
					self._trigger("unselecting", event, {
						unselecting: selectee.element
					});
				}
				return false;
			}
		});

	},

	_mouseDrag: function(event) {
		var self = this;
		this.dragged = true;

		if (this.options.disabled)
			return;

		var options = this.options;

		var x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY;
		if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; }
		if (y1 > y2) { var tmp = y2; y2 = y1; y1 = tmp; }
		this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1});

		this.selectees.each(function() {
			var selectee = $.data(this, "selectable-item");
			//prevent helper from being selected if appendTo: selectable
			if (!selectee || selectee.element == self.element[0])
				return;
			var hit = false;
			if (options.tolerance == 'touch') {
				hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
			} else if (options.tolerance == 'fit') {
				hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
			}

			if (hit) {
				// SELECT
				if (selectee.selected) {
					selectee.$element.removeClass('ui-selected');
					selectee.selected = false;
				}
				if (selectee.unselecting) {
					selectee.$element.removeClass('ui-unselecting');
					selectee.unselecting = false;
				}
				if (!selectee.selecting) {
					selectee.$element.addClass('ui-selecting');
					selectee.selecting = true;
					// selectable SELECTING callback
					self._trigger("selecting", event, {
						selecting: selectee.element
					});
				}
			} else {
				// UNSELECT
				if (selectee.selecting) {
					if (event.metaKey && selectee.startselected) {
						selectee.$element.removeClass('ui-selecting');
						selectee.selecting = false;
						selectee.$element.addClass('ui-selected');
						selectee.selected = true;
					} else {
						selectee.$element.removeClass('ui-selecting');
						selectee.selecting = false;
						if (selectee.startselected) {
							selectee.$element.addClass('ui-unselecting');
							selectee.unselecting = true;
						}
						// selectable UNSELECTING callback
						self._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
				if (selectee.selected) {
					if (!event.metaKey && !selectee.startselected) {
						selectee.$element.removeClass('ui-selected');
						selectee.selected = false;

						selectee.$element.addClass('ui-unselecting');
						selectee.unselecting = true;
						// selectable UNSELECTING callback
						self._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
			}
		});

		return false;
	},

	_mouseStop: function(event) {
		var self = this;

		this.dragged = false;

		var options = this.options;

		$('.ui-unselecting', this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass('ui-unselecting');
			selectee.unselecting = false;
			selectee.startselected = false;
			self._trigger("unselected", event, {
				unselected: selectee.element
			});
		});
		$('.ui-selecting', this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass('ui-selecting').addClass('ui-selected');
			selectee.selecting = false;
			selectee.selected = true;
			selectee.startselected = true;
			self._trigger("selected", event, {
				selected: selectee.element
			});
		});
		this._trigger("stop", event);

		this.helper.remove();

		return false;
	}

});

$.extend($.ui.selectable, {
	version: "1.8.12"
});

})(jQuery);
/*
 * jQuery UI Sortable 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget("ui.sortable", $.ui.mouse, {
	widgetEventPrefix: "sort",
	options: {
		appendTo: "parent",
		axis: false,
		connectWith: false,
		containment: false,
		cursor: 'auto',
		cursorAt: false,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		grid: false,
		handle: false,
		helper: "original",
		items: '> *',
		opacity: false,
		placeholder: false,
		revert: false,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		scope: "default",
		tolerance: "intersect",
		zIndex: 1000
	},
	_create: function() {

		var o = this.options;
		this.containerCache = {};
		this.element.addClass("ui-sortable");

		//Get the items
		this.refresh();

		//Let's determine if the items are being displayed horizontally
		this.floating = this.items.length ? (/left|right/).test(this.items[0].item.css('float')) || (/inline|table-cell/).test(this.items[0].item.css('display')) : false;

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

	},

	destroy: function() {
		this.element
			.removeClass("ui-sortable ui-sortable-disabled")
			.removeData("sortable")
			.unbind(".sortable");
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- )
			this.items[i].item.removeData("sortable-item");

		return this;
	},

	_setOption: function(key, value){
		if ( key === "disabled" ) {
			this.options[ key ] = value;
	
			this.widget()
				[ value ? "addClass" : "removeClass"]( "ui-sortable-disabled" );
		} else {
			// Don't call widget base _setOption for disable as it adds ui-state-disabled class
			$.Widget.prototype._setOption.apply(this, arguments);
		}
	},

	_mouseCapture: function(event, overrideHandle) {

		if (this.reverting) {
			return false;
		}

		if(this.options.disabled || this.options.type == 'static') return false;

		//We have to refresh the items data once first
		this._refreshItems(event);

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		var currentItem = null, self = this, nodes = $(event.target).parents().each(function() {
			if($.data(this, 'sortable-item') == self) {
				currentItem = $(this);
				return false;
			}
		});
		if($.data(event.target, 'sortable-item') == self) currentItem = $(event.target);

		if(!currentItem) return false;
		if(this.options.handle && !overrideHandle) {
			var validHandle = false;

			$(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
			if(!validHandle) return false;
		}

		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;

	},

	_mouseStart: function(event, overrideHandle, noActivation) {

		var o = this.options, self = this;
		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
		this.refreshPositions();

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Get the next scrolling parent
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.currentItem.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		// Only after we got the offset, we can change the helper's position to absolute
		// TODO: Still need to figure out a way to make relative sorting possible
		this.helper.css("position", "absolute");
		this.cssPosition = this.helper.css("position");

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

		//Cache the former DOM position
		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };

		//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
		if(this.helper[0] != this.currentItem[0]) {
			this.currentItem.hide();
		}

		//Create the placeholder
		this._createPlaceholder();

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		if(o.cursor) { // cursor option
			if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor");
			$('body').css("cursor", o.cursor);
		}

		if(o.opacity) { // opacity option
			if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity");
			this.helper.css("opacity", o.opacity);
		}

		if(o.zIndex) { // zIndex option
			if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex");
			this.helper.css("zIndex", o.zIndex);
		}

		//Prepare scrolling
		if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML')
			this.overflowOffset = this.scrollParent.offset();

		//Call callbacks
		this._trigger("start", event, this._uiHash());

		//Recache the helper size
		if(!this._preserveHelperProportions)
			this._cacheHelperProportions();


		//Post 'activate' events to possible containers
		if(!noActivation) {
			 for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, self._uiHash(this)); }
		}

		//Prepare possible droppables
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.dragging = true;

		this.helper.addClass("ui-sortable-helper");
		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;

	},

	_mouseDrag: function(event) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		if (!this.lastPositionAbs) {
			this.lastPositionAbs = this.positionAbs;
		}

		//Do scrolling
		if(this.options.scroll) {
			var o = this.options, scrolled = false;
			if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {

				if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
				else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity)
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;

				if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
				else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity)
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;

			} else {

				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);

				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);

			}

			if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
				$.ui.ddmanager.prepareOffsets(this, event);
		}

		//Regenerate the absolute position used for position checks
		this.positionAbs = this._convertPositionTo("absolute");

		//Set the helper position
		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';

		//Rearrange
		for (var i = this.items.length - 1; i >= 0; i--) {

			//Cache variables and intersection, continue if no intersection
			var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
			if (!intersection) continue;

			if(itemElement != this.currentItem[0] //cannot intersect with itself
				&&	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
				&&	!$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
				&& (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
				//&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container
			) {

				this.direction = intersection == 1 ? "down" : "up";

				if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
					this._rearrange(event, item);
				} else {
					break;
				}

				this._trigger("change", event, this._uiHash());
				break;
			}
		}

		//Post events to containers
		this._contactContainers(event);

		//Interconnect with droppables
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		//Call callbacks
		this._trigger('sort', event, this._uiHash());

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

	_mouseStop: function(event, noPropagation) {

		if(!event) return;

		//If we are using droppables, inform the manager about the drop
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			$.ui.ddmanager.drop(this, event);

		if(this.options.revert) {
			var self = this;
			var cur = self.placeholder.offset();

			self.reverting = true;

			$(this.helper).animate({
				left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
				top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
			}, parseInt(this.options.revert, 10) || 500, function() {
				self._clear(event);
			});
		} else {
			this._clear(event, noPropagation);
		}

		return false;

	},

	cancel: function() {

		var self = this;

		if(this.dragging) {

			this._mouseUp({ target: null });

			if(this.options.helper == "original")
				this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
			else
				this.currentItem.show();

			//Post deactivating events to containers
			for (var i = this.containers.length - 1; i >= 0; i--){
				this.containers[i]._trigger("deactivate", null, self._uiHash(this));
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", null, self._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		}

		if (this.placeholder) {
			//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
			if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
			if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove();

			$.extend(this, {
				helper: null,
				dragging: false,
				reverting: false,
				_noFinalSort: null
			});

			if(this.domPosition.prev) {
				$(this.domPosition.prev).after(this.currentItem);
			} else {
				$(this.domPosition.parent).prepend(this.currentItem);
			}
		}

		return this;

	},

	serialize: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected);
		var str = []; o = o || {};

		$(items).each(function() {
			var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
			if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
		});

		if(!str.length && o.key) {
			str.push(o.key + '=');
		}

		return str.join('&');

	},

	toArray: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected);
		var ret = []; o = o || {};

		items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
		return ret;

	},

	/* Be careful with the following core functions */
	_intersectsWith: function(item) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height;

		var l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height;

		var dyClick = this.offset.click.top,
			dxClick = this.offset.click.left;

		var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;

		if(	   this.options.tolerance == "pointer"
			|| this.options.forcePointerForContainers
			|| (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
		) {
			return isOverElement;
		} else {

			return (l < x1 + (this.helperProportions.width / 2) // Right Half
				&& x2 - (this.helperProportions.width / 2) < r // Left Half
				&& t < y1 + (this.helperProportions.height / 2) // Bottom Half
				&& y2 - (this.helperProportions.height / 2) < b ); // Top Half

		}
	},

	_intersectsWithPointer: function(item) {

		var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
			isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
			isOverElement = isOverElementHeight && isOverElementWidth,
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (!isOverElement)
			return false;

		return this.floating ?
			( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
			: ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );

	},

	_intersectsWithSides: function(item) {

		var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
			isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (this.floating && horizontalDirection) {
			return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
		} else {
			return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf));
		}

	},

	_getDragVerticalDirection: function() {
		var delta = this.positionAbs.top - this.lastPositionAbs.top;
		return delta != 0 && (delta > 0 ? "down" : "up");
	},

	_getDragHorizontalDirection: function() {
		var delta = this.positionAbs.left - this.lastPositionAbs.left;
		return delta != 0 && (delta > 0 ? "right" : "left");
	},

	refresh: function(event) {
		this._refreshItems(event);
		this.refreshPositions();
		return this;
	},

	_connectWith: function() {
		var options = this.options;
		return options.connectWith.constructor == String
			? [options.connectWith]
			: options.connectWith;
	},
	
	_getItemsAsjQuery: function(connected) {

		var self = this;
		var items = [];
		var queries = [];
		var connectWith = this._connectWith();

		if(connectWith && connected) {
			for (var i = connectWith.length - 1; i >= 0; i--){
				var cur = $(connectWith[i]);
				for (var j = cur.length - 1; j >= 0; j--){
					var inst = $.data(cur[j], 'sortable');
					if(inst && inst != this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), inst]);
					}
				};
			};
		}

		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), this]);

		for (var i = queries.length - 1; i >= 0; i--){
			queries[i][0].each(function() {
				items.push(this);
			});
		};

		return $(items);

	},

	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find(":data(sortable-item)");

		for (var i=0; i < this.items.length; i++) {

			for (var j=0; j < list.length; j++) {
				if(list[j] == this.items[i].item[0])
					this.items.splice(i,1);
			};

		};

	},

	_refreshItems: function(event) {

		this.items = [];
		this.containers = [this];
		var items = this.items;
		var self = this;
		var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];
		var connectWith = this._connectWith();

		if(connectWith) {
			for (var i = connectWith.length - 1; i >= 0; i--){
				var cur = $(connectWith[i]);
				for (var j = cur.length - 1; j >= 0; j--){
					var inst = $.data(cur[j], 'sortable');
					if(inst && inst != this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
						this.containers.push(inst);
					}
				};
			};
		}

		for (var i = queries.length - 1; i >= 0; i--) {
			var targetData = queries[i][1];
			var _queries = queries[i][0];

			for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
				var item = $(_queries[j]);

				item.data('sortable-item', targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				});
			};
		};

	},

	refreshPositions: function(fast) {

		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
		if(this.offsetParent && this.helper) {
			this.offset.parent = this._getParentOffset();
		}

		for (var i = this.items.length - 1; i >= 0; i--){
			var item = this.items[i];

			//We ignore calculating positions of all connected containers when we're not over them
			if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0])
				continue;

			var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;

			if (!fast) {
				item.width = t.outerWidth();
				item.height = t.outerHeight();
			}

			var p = t.offset();
			item.left = p.left;
			item.top = p.top;
		};

		if(this.options.custom && this.options.custom.refreshContainers) {
			this.options.custom.refreshContainers.call(this);
		} else {
			for (var i = this.containers.length - 1; i >= 0; i--){
				var p = this.containers[i].element.offset();
				this.containers[i].containerCache.left = p.left;
				this.containers[i].containerCache.top = p.top;
				this.containers[i].containerCache.width	= this.containers[i].element.outerWidth();
				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
			};
		}

		return this;
	},

	_createPlaceholder: function(that) {

		var self = that || this, o = self.options;

		if(!o.placeholder || o.placeholder.constructor == String) {
			var className = o.placeholder;
			o.placeholder = {
				element: function() {

					var el = $(document.createElement(self.currentItem[0].nodeName))
						.addClass(className || self.currentItem[0].className+" ui-sortable-placeholder")
						.removeClass("ui-sortable-helper")[0];

					if(!className)
						el.style.visibility = "hidden";

					return el;
				},
				update: function(container, p) {

					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
					if(className && !o.forcePlaceholderSize) return;

					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
					if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); };
					if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); };
				}
			};
		}

		//Create the placeholder
		self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem));

		//Append it after the actual current item
		self.currentItem.after(self.placeholder);

		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
		o.placeholder.update(self, self.placeholder);

	},

	_contactContainers: function(event) {
		
		// get innermost container that intersects with item 
		var innermostContainer = null, innermostIndex = null;		
		
		
		for (var i = this.containers.length - 1; i >= 0; i--){

			// never consider a container that's located within the item itself 
			if($.ui.contains(this.currentItem[0], this.containers[i].element[0]))
				continue;

			if(this._intersectsWith(this.containers[i].containerCache)) {

				// if we've already found a container and it's more "inner" than this, then continue 
				if(innermostContainer && $.ui.contains(this.containers[i].element[0], innermostContainer.element[0]))
					continue;

				innermostContainer = this.containers[i]; 
				innermostIndex = i;
					
			} else {
				// container doesn't intersect. trigger "out" event if necessary 
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", event, this._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		}
		
		// if no intersecting containers found, return 
		if(!innermostContainer) return; 

		// move the item into the container if it's not there already
		if(this.containers.length === 1) {
			this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
			this.containers[innermostIndex].containerCache.over = 1;
		} else if(this.currentContainer != this.containers[innermostIndex]) { 

			//When entering a new container, we will find the item with the least distance and append our item near it 
			var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[innermostIndex].floating ? 'left' : 'top']; 
			for (var j = this.items.length - 1; j >= 0; j--) { 
				if(!$.ui.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) continue; 
				var cur = this.items[j][this.containers[innermostIndex].floating ? 'left' : 'top']; 
				if(Math.abs(cur - base) < dist) { 
					dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; 
				} 
			} 

			if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled 
				return; 

			this.currentContainer = this.containers[innermostIndex]; 
			itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); 
			this._trigger("change", event, this._uiHash()); 
			this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); 

			//Update the placeholder 
			this.options.placeholder.update(this.currentContainer, this.placeholder); 
		
			this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); 
			this.containers[innermostIndex].containerCache.over = 1;
		} 
	
		
	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem);

		if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already
			$(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);

		if(helper[0] == this.currentItem[0])
			this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };

		if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width());
		if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height());

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj == 'string') {
			obj = obj.split(' ');
		}
		if ($.isArray(obj)) {
			obj = {left: +obj[0], top: +obj[1] || 0};
		}
		if ('left' in obj) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ('right' in obj) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ('top' in obj) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ('bottom' in obj) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_getParentOffset: function() {


		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.currentItem.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
		];

		if(!(/^(document|window|parent)$/).test(o.containment)) {
			var ce = $(o.containment)[0];
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// The absolute mouse position
				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left																// The absolute mouse position
				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
			this.offset.relative = this._getRelativeOffset();
		}

		var pageX = event.pageX;
		var pageY = event.pageY;

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
			}

			if(o.grid) {
				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_rearrange: function(event, i, a, hardRefresh) {

		a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));

		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var self = this, counter = this.counter;

		window.setTimeout(function() {
			if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
		},0);

	},

	_clear: function(event, noPropagation) {

		this.reverting = false;
		// We delay all events that have to be triggered to after the point where the placeholder has been removed and
		// everything else normalized again
		var delayedTriggers = [], self = this;

		// We first have to update the dom position of the actual currentItem
		// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
		if(!this._noFinalSort && this.currentItem[0].parentNode) this.placeholder.before(this.currentItem);
		this._noFinalSort = null;

		if(this.helper[0] == this.currentItem[0]) {
			for(var i in this._storedCSS) {
				if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = '';
			}
			this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
		} else {
			this.currentItem.show();
		}

		if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
		if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
		if(!$.ui.contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element
			if(!noPropagation) delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
			for (var i = this.containers.length - 1; i >= 0; i--){
				if($.ui.contains(this.containers[i].element[0], this.currentItem[0]) && !noPropagation) {
					delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
					delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.containers[i]));
				}
			};
		};

		//Post events to containers
		for (var i = this.containers.length - 1; i >= 0; i--){
			if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
			if(this.containers[i].containerCache.over) {
				delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
				this.containers[i].containerCache.over = 0;
			}
		}

		//Do what was originally in plugins
		if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor
		if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset opacity
		if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index

		this.dragging = false;
		if(this.cancelHelperRemoval) {
			if(!noPropagation) {
				this._trigger("beforeStop", event, this._uiHash());
				for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
				this._trigger("stop", event, this._uiHash());
			}
			return false;
		}

		if(!noPropagation) this._trigger("beforeStop", event, this._uiHash());

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
		this.placeholder[0].parentNode.removeChild(this.placeholder[0]);

		if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null;

		if(!noPropagation) {
			for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
			this._trigger("stop", event, this._uiHash());
		}

		this.fromOutside = false;
		return true;

	},

	_trigger: function() {
		if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
			this.cancel();
		}
	},

	_uiHash: function(inst) {
		var self = inst || this;
		return {
			helper: self.helper,
			placeholder: self.placeholder || $([]),
			position: self.position,
			originalPosition: self.originalPosition,
			offset: self.positionAbs,
			item: self.currentItem,
			sender: inst ? inst.element : null
		};
	}

});

$.extend($.ui.sortable, {
	version: "1.8.12"
});

})(jQuery);
/*
 * jQuery UI Effects 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/
 */
;jQuery.effects || (function($, undefined) {

$.effects = {};



/******************************************************************************/
/****************************** COLOR ANIMATIONS ******************************/
/******************************************************************************/

// override the animation for color styles
$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor',
	'borderRightColor', 'borderTopColor', 'borderColor', 'color', 'outlineColor'],
function(i, attr) {
	$.fx.step[attr] = function(fx) {
		if (!fx.colorInit) {
			fx.start = getColor(fx.elem, attr);
			fx.end = getRGB(fx.end);
			fx.colorInit = true;
		}

		fx.elem.style[attr] = 'rgb(' +
			Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0], 10), 255), 0) + ',' +
			Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1], 10), 255), 0) + ',' +
			Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2], 10), 255), 0) + ')';
	};
});

// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/

// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
				return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
				return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
				return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
				return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
				return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
		if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
				return colors['transparent'];

		// Otherwise, we're most likely dealing with a named color
		return colors[$.trim(color).toLowerCase()];
}

function getColor(elem, attr) {
		var color;

		do {
				color = $.curCSS(elem, attr);

				// Keep going until we find an element that has color, or we hit the body
				if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") )
						break;

				attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
};

// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/

var colors = {
	aqua:[0,255,255],
	azure:[240,255,255],
	beige:[245,245,220],
	black:[0,0,0],
	blue:[0,0,255],
	brown:[165,42,42],
	cyan:[0,255,255],
	darkblue:[0,0,139],
	darkcyan:[0,139,139],
	darkgrey:[169,169,169],
	darkgreen:[0,100,0],
	darkkhaki:[189,183,107],
	darkmagenta:[139,0,139],
	darkolivegreen:[85,107,47],
	darkorange:[255,140,0],
	darkorchid:[153,50,204],
	darkred:[139,0,0],
	darksalmon:[233,150,122],
	darkviolet:[148,0,211],
	fuchsia:[255,0,255],
	gold:[255,215,0],
	green:[0,128,0],
	indigo:[75,0,130],
	khaki:[240,230,140],
	lightblue:[173,216,230],
	lightcyan:[224,255,255],
	lightgreen:[144,238,144],
	lightgrey:[211,211,211],
	lightpink:[255,182,193],
	lightyellow:[255,255,224],
	lime:[0,255,0],
	magenta:[255,0,255],
	maroon:[128,0,0],
	navy:[0,0,128],
	olive:[128,128,0],
	orange:[255,165,0],
	pink:[255,192,203],
	purple:[128,0,128],
	violet:[128,0,128],
	red:[255,0,0],
	silver:[192,192,192],
	white:[255,255,255],
	yellow:[255,255,0],
	transparent: [255,255,255]
};



/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/

var classAnimationActions = ['add', 'remove', 'toggle'],
	shorthandStyles = {
		border: 1,
		borderBottom: 1,
		borderColor: 1,
		borderLeft: 1,
		borderRight: 1,
		borderTop: 1,
		borderWidth: 1,
		margin: 1,
		padding: 1
	};

function getElementStyles() {
	var style = document.defaultView
			? document.defaultView.getComputedStyle(this, null)
			: this.currentStyle,
		newStyle = {},
		key,
		camelCase;

	// webkit enumerates style porperties
	if (style && style.length && style[0] && style[style[0]]) {
		var len = style.length;
		while (len--) {
			key = style[len];
			if (typeof style[key] == 'string') {
				camelCase = key.replace(/\-(\w)/g, function(all, letter){
					return letter.toUpperCase();
				});
				newStyle[camelCase] = style[key];
			}
		}
	} else {
		for (key in style) {
			if (typeof style[key] === 'string') {
				newStyle[key] = style[key];
			}
		}
	}
	
	return newStyle;
}

function filterStyles(styles) {
	var name, value;
	for (name in styles) {
		value = styles[name];
		if (
			// ignore null and undefined values
			value == null ||
			// ignore functions (when does this occur?)
			$.isFunction(value) ||
			// shorthand styles that need to be expanded
			name in shorthandStyles ||
			// ignore scrollbars (break in IE)
			(/scrollbar/).test(name) ||

			// only colors or values that can be converted to numbers
			(!(/color/i).test(name) && isNaN(parseFloat(value)))
		) {
			delete styles[name];
		}
	}
	
	return styles;
}

function styleDifference(oldStyle, newStyle) {
	var diff = { _: 0 }, // http://dev.jquery.com/ticket/5459
		name;

	for (name in newStyle) {
		if (oldStyle[name] != newStyle[name]) {
			diff[name] = newStyle[name];
		}
	}

	return diff;
}

$.effects.animateClass = function(value, duration, easing, callback) {
	if ($.isFunction(easing)) {
		callback = easing;
		easing = null;
	}

	return this.queue('fx', function() {
		var that = $(this),
			originalStyleAttr = that.attr('style') || ' ',
			originalStyle = filterStyles(getElementStyles.call(this)),
			newStyle,
			className = that.attr('className');

		$.each(classAnimationActions, function(i, action) {
			if (value[action]) {
				that[action + 'Class'](value[action]);
			}
		});
		newStyle = filterStyles(getElementStyles.call(this));
		that.attr('className', className);

		that.animate(styleDifference(originalStyle, newStyle), duration, easing, function() {
			$.each(classAnimationActions, function(i, action) {
				if (value[action]) { that[action + 'Class'](value[action]); }
			});
			// work around bug in IE by clearing the cssText before setting it
			if (typeof that.attr('style') == 'object') {
				that.attr('style').cssText = '';
				that.attr('style').cssText = originalStyleAttr;
			} else {
				that.attr('style', originalStyleAttr);
			}
			if (callback) { callback.apply(this, arguments); }
		});

		// $.animate adds a function to the end of the queue
		// but we want it at the front
		var queue = $.queue(this),
			anim = queue.splice(queue.length - 1, 1)[0];
		queue.splice(1, 0, anim);
		$.dequeue(this);
	});
};

$.fn.extend({
	_addClass: $.fn.addClass,
	addClass: function(classNames, speed, easing, callback) {
		return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames);
	},

	_removeClass: $.fn.removeClass,
	removeClass: function(classNames,speed,easing,callback) {
		return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames);
	},

	_toggleClass: $.fn.toggleClass,
	toggleClass: function(classNames, force, speed, easing, callback) {
		if ( typeof force == "boolean" || force === undefined ) {
			if ( !speed ) {
				// without speed parameter;
				return this._toggleClass(classNames, force);
			} else {
				return $.effects.animateClass.apply(this, [(force?{add:classNames}:{remove:classNames}),speed,easing,callback]);
			}
		} else {
			// without switch parameter;
			return $.effects.animateClass.apply(this, [{ toggle: classNames },force,speed,easing]);
		}
	},

	switchClass: function(remove,add,speed,easing,callback) {
		return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]);
	}
});



/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/

$.extend($.effects, {
	version: "1.8.12",

	// Saves a set of properties in a data storage
	save: function(element, set) {
		for(var i=0; i < set.length; i++) {
			if(set[i] !== null) element.data("ec.storage."+set[i], element[0].style[set[i]]);
		}
	},

	// Restores a set of previously saved properties from a data storage
	restore: function(element, set) {
		for(var i=0; i < set.length; i++) {
			if(set[i] !== null) element.css(set[i], element.data("ec.storage."+set[i]));
		}
	},

	setMode: function(el, mode) {
		if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle
		return mode;
	},

	getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value
		// this should be a little more flexible in the future to handle a string & hash
		var y, x;
		switch (origin[0]) {
			case 'top': y = 0; break;
			case 'middle': y = 0.5; break;
			case 'bottom': y = 1; break;
			default: y = origin[0] / original.height;
		};
		switch (origin[1]) {
			case 'left': x = 0; break;
			case 'center': x = 0.5; break;
			case 'right': x = 1; break;
			default: x = origin[1] / original.width;
		};
		return {x: x, y: y};
	},

	// Wraps the element around a wrapper that copies position properties
	createWrapper: function(element) {

		// if the element is already wrapped, return it
		if (element.parent().is('.ui-effects-wrapper')) {
			return element.parent();
		}

		// wrap the element
		var props = {
				width: element.outerWidth(true),
				height: element.outerHeight(true),
				'float': element.css('float')
			},
			wrapper = $('<div></div>')
				.addClass('ui-effects-wrapper')
				.css({
					fontSize: '100%',
					background: 'transparent',
					border: 'none',
					margin: 0,
					padding: 0
				});

		element.wrap(wrapper);
		wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually loose the reference to the wrapped element

		// transfer positioning properties to the wrapper
		if (element.css('position') == 'static') {
			wrapper.css({ position: 'relative' });
			element.css({ position: 'relative' });
		} else {
			$.extend(props, {
				position: element.css('position'),
				zIndex: element.css('z-index')
			});
			$.each(['top', 'left', 'bottom', 'right'], function(i, pos) {
				props[pos] = element.css(pos);
				if (isNaN(parseInt(props[pos], 10))) {
					props[pos] = 'auto';
				}
			});
			element.css({position: 'relative', top: 0, left: 0, right: 'auto', bottom: 'auto' });
		}

		return wrapper.css(props).show();
	},

	removeWrapper: function(element) {
		if (element.parent().is('.ui-effects-wrapper'))
			return element.parent().replaceWith(element);
		return element;
	},

	setTransition: function(element, list, factor, value) {
		value = value || {};
		$.each(list, function(i, x){
			unit = element.cssUnit(x);
			if (unit[0] > 0) value[x] = unit[0] * factor + unit[1];
		});
		return value;
	}
});


function _normalizeArguments(effect, options, speed, callback) {
	// shift params for method overloading
	if (typeof effect == 'object') {
		callback = options;
		speed = null;
		options = effect;
		effect = options.effect;
	}
	if ($.isFunction(options)) {
		callback = options;
		speed = null;
		options = {};
	}
        if (typeof options == 'number' || $.fx.speeds[options]) {
		callback = speed;
		speed = options;
		options = {};
	}
	if ($.isFunction(speed)) {
		callback = speed;
		speed = null;
	}

	options = options || {};

	speed = speed || options.duration;
	speed = $.fx.off ? 0 : typeof speed == 'number'
		? speed : speed in $.fx.speeds ? $.fx.speeds[speed] : $.fx.speeds._default;

	callback = callback || options.complete;

	return [effect, options, speed, callback];
}

function standardSpeed( speed ) {
	// valid standard speeds
	if ( !speed || typeof speed === "number" || $.fx.speeds[ speed ] ) {
		return true;
	}
	
	// invalid strings - treat as "normal" speed
	if ( typeof speed === "string" && !$.effects[ speed ] ) {
		return true;
	}
	
	return false;
}

$.fn.extend({
	effect: function(effect, options, speed, callback) {
		var args = _normalizeArguments.apply(this, arguments),
			// TODO: make effects take actual parameters instead of a hash
			args2 = {
				options: args[1],
				duration: args[2],
				callback: args[3]
			},
			mode = args2.options.mode,
			effectMethod = $.effects[effect];
		
		if ( $.fx.off || !effectMethod ) {
			// delegate to the original method (e.g., .show()) if possible
			if ( mode ) {
				return this[ mode ]( args2.duration, args2.callback );
			} else {
				return this.each(function() {
					if ( args2.callback ) {
						args2.callback.call( this );
					}
				});
			}
		}
		
		return effectMethod.call(this, args2);
	},

	_show: $.fn.show,
	show: function(speed) {
		if ( standardSpeed( speed ) ) {
			return this._show.apply(this, arguments);
		} else {
			var args = _normalizeArguments.apply(this, arguments);
			args[1].mode = 'show';
			return this.effect.apply(this, args);
		}
	},

	_hide: $.fn.hide,
	hide: function(speed) {
		if ( standardSpeed( speed ) ) {
			return this._hide.apply(this, arguments);
		} else {
			var args = _normalizeArguments.apply(this, arguments);
			args[1].mode = 'hide';
			return this.effect.apply(this, args);
		}
	},

	// jQuery core overloads toggle and creates _toggle
	__toggle: $.fn.toggle,
	toggle: function(speed) {
		if ( standardSpeed( speed ) || typeof speed === "boolean" || $.isFunction( speed ) ) {
			return this.__toggle.apply(this, arguments);
		} else {
			var args = _normalizeArguments.apply(this, arguments);
			args[1].mode = 'toggle';
			return this.effect.apply(this, args);
		}
	},

	// helper functions
	cssUnit: function(key) {
		var style = this.css(key), val = [];
		$.each( ['em','px','%','pt'], function(i, unit){
			if(style.indexOf(unit) > 0)
				val = [parseFloat(style), unit];
		});
		return val;
	}
});



/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 *
 * Open source under the BSD License.
 *
 * Copyright 2008 George McGinley Smith
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
$.easing.jswing = $.easing.swing;

$.extend($.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert($.easing.default);
		return $.easing[$.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - $.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return $.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return $.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 *
 * Open source under the BSD License.
 *
 * Copyright 2001 Robert Penner
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

})(jQuery);
/*
 * jQuery UI Effects Blind 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Blind
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.blind = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','bottom','left','right'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'vertical'; // Default direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var ref = (direction == 'vertical') ? 'height' : 'width';
		var distance = (direction == 'vertical') ? wrapper.height() : wrapper.width();
		if(mode == 'show') wrapper.css(ref, 0); // Shift

		// Animation
		var animation = {};
		animation[ref] = mode == 'show' ? distance : 0;

		// Animate
		wrapper.animate(animation, o.duration, o.options.easing, function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Bounce 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Bounce
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.bounce = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','bottom','left','right'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var direction = o.options.direction || 'up'; // Default direction
		var distance = o.options.distance || 20; // Default distance
		var times = o.options.times || 5; // Default # of times
		var speed = o.duration || 250; // Default speed per bounce
		if (/show|hide/.test(mode)) props.push('opacity'); // Avoid touching opacity to prevent clearType and PNG issues in IE

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
		var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 3 : el.outerWidth({margin:true}) / 3);
		if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift
		if (mode == 'hide') distance = distance / (times * 2);
		if (mode != 'hide') times--;

		// Animate
		if (mode == 'show') { // Show Bounce
			var animation = {opacity: 1};
			animation[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
			el.animate(animation, speed / 2, o.options.easing);
			distance = distance / 2;
			times--;
		};
		for (var i = 0; i < times; i++) { // Bounces
			var animation1 = {}, animation2 = {};
			animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
			animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
			el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing);
			distance = (mode == 'hide') ? distance * 2 : distance / 2;
		};
		if (mode == 'hide') { // Last Bounce
			var animation = {opacity: 0};
			animation[ref] = (motion == 'pos' ? '-=' : '+=')  + distance;
			el.animate(animation, speed / 2, o.options.easing, function(){
				el.hide(); // Hide
				$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		} else {
			var animation1 = {}, animation2 = {};
			animation1[ref] = (motion == 'pos' ? '-=' : '+=') + distance;
			animation2[ref] = (motion == 'pos' ? '+=' : '-=') + distance;
			el.animate(animation1, speed / 2, o.options.easing).animate(animation2, speed / 2, o.options.easing, function(){
				$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		};
		el.queue('fx', function() { el.dequeue(); });
		el.dequeue();
	});

};

})(jQuery);
/*
 * jQuery UI Effects Clip 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Clip
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.clip = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','bottom','left','right','height','width'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'vertical'; // Default direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var animate = el[0].tagName == 'IMG' ? wrapper : el;
		var ref = {
			size: (direction == 'vertical') ? 'height' : 'width',
			position: (direction == 'vertical') ? 'top' : 'left'
		};
		var distance = (direction == 'vertical') ? animate.height() : animate.width();
		if(mode == 'show') { animate.css(ref.size, 0); animate.css(ref.position, distance / 2); } // Shift

		// Animation
		var animation = {};
		animation[ref.size] = mode == 'show' ? distance : 0;
		animation[ref.position] = mode == 'show' ? 0 : distance / 2;

		// Animate
		animate.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Drop 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Drop
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.drop = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','bottom','left','right','opacity'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'left'; // Default Direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
		var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 2 : el.outerWidth({margin:true}) / 2);
		if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift

		// Animation
		var animation = {opacity: mode == 'show' ? 1 : 0};
		animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance;

		// Animate
		el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Explode 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Explode
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.explode = function(o) {

	return this.queue(function() {

	var rows = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3;
	var cells = o.options.pieces ? Math.round(Math.sqrt(o.options.pieces)) : 3;

	o.options.mode = o.options.mode == 'toggle' ? ($(this).is(':visible') ? 'hide' : 'show') : o.options.mode;
	var el = $(this).show().css('visibility', 'hidden');
	var offset = el.offset();

	//Substract the margins - not fixing the problem yet.
	offset.top -= parseInt(el.css("marginTop"),10) || 0;
	offset.left -= parseInt(el.css("marginLeft"),10) || 0;

	var width = el.outerWidth(true);
	var height = el.outerHeight(true);

	for(var i=0;i<rows;i++) { // =
		for(var j=0;j<cells;j++) { // ||
			el
				.clone()
				.appendTo('body')
				.wrap('<div></div>')
				.css({
					position: 'absolute',
					visibility: 'visible',
					left: -j*(width/cells),
					top: -i*(height/rows)
				})
				.parent()
				.addClass('ui-effects-explode')
				.css({
					position: 'absolute',
					overflow: 'hidden',
					width: width/cells,
					height: height/rows,
					left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? (j-Math.floor(cells/2))*(width/cells) : 0),
					top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? (i-Math.floor(rows/2))*(height/rows) : 0),
					opacity: o.options.mode == 'show' ? 0 : 1
				}).animate({
					left: offset.left + j*(width/cells) + (o.options.mode == 'show' ? 0 : (j-Math.floor(cells/2))*(width/cells)),
					top: offset.top + i*(height/rows) + (o.options.mode == 'show' ? 0 : (i-Math.floor(rows/2))*(height/rows)),
					opacity: o.options.mode == 'show' ? 1 : 0
				}, o.duration || 500);
		}
	}

	// Set a timeout, to call the callback approx. when the other animations have finished
	setTimeout(function() {

		o.options.mode == 'show' ? el.css({ visibility: 'visible' }) : el.css({ visibility: 'visible' }).hide();
				if(o.callback) o.callback.apply(el[0]); // Callback
				el.dequeue();

				$('div.ui-effects-explode').remove();

	}, o.duration || 500);


	});

};

})(jQuery);
/*
 * jQuery UI Effects Fade 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Fade
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.fade = function(o) {
	return this.queue(function() {
		var elem = $(this),
			mode = $.effects.setMode(elem, o.options.mode || 'hide');

		elem.animate({ opacity: mode }, {
			queue: false,
			duration: o.duration,
			easing: o.options.easing,
			complete: function() {
				(o.callback && o.callback.apply(this, arguments));
				elem.dequeue();
			}
		});
	});
};

})(jQuery);
/*
 * jQuery UI Effects Fold 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Fold
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.fold = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','bottom','left','right'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var size = o.options.size || 15; // Default fold size
		var horizFirst = !(!o.options.horizFirst); // Ensure a boolean value
		var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2;

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var widthFirst = ((mode == 'show') != horizFirst);
		var ref = widthFirst ? ['width', 'height'] : ['height', 'width'];
		var distance = widthFirst ? [wrapper.width(), wrapper.height()] : [wrapper.height(), wrapper.width()];
		var percent = /([0-9]+)%/.exec(size);
		if(percent) size = parseInt(percent[1],10) / 100 * distance[mode == 'hide' ? 0 : 1];
		if(mode == 'show') wrapper.css(horizFirst ? {height: 0, width: size} : {height: size, width: 0}); // Shift

		// Animation
		var animation1 = {}, animation2 = {};
		animation1[ref[0]] = mode == 'show' ? distance[0] : size;
		animation2[ref[1]] = mode == 'show' ? distance[1] : 0;

		// Animate
		wrapper.animate(animation1, duration, o.options.easing)
		.animate(animation2, duration, o.options.easing, function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Highlight 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Highlight
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.highlight = function(o) {
	return this.queue(function() {
		var elem = $(this),
			props = ['backgroundImage', 'backgroundColor', 'opacity'],
			mode = $.effects.setMode(elem, o.options.mode || 'show'),
			animation = {
				backgroundColor: elem.css('backgroundColor')
			};

		if (mode == 'hide') {
			animation.opacity = 0;
		}

		$.effects.save(elem, props);
		elem
			.show()
			.css({
				backgroundImage: 'none',
				backgroundColor: o.options.color || '#ffff99'
			})
			.animate(animation, {
				queue: false,
				duration: o.duration,
				easing: o.options.easing,
				complete: function() {
					(mode == 'hide' && elem.hide());
					$.effects.restore(elem, props);
					(mode == 'show' && !$.support.opacity && this.style.removeAttribute('filter'));
					(o.callback && o.callback.apply(this, arguments));
					elem.dequeue();
				}
			});
	});
};

})(jQuery);
/*
 * jQuery UI Effects Pulsate 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Pulsate
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.pulsate = function(o) {
	return this.queue(function() {
		var elem = $(this),
			mode = $.effects.setMode(elem, o.options.mode || 'show');
			times = ((o.options.times || 5) * 2) - 1;
			duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2,
			isVisible = elem.is(':visible'),
			animateTo = 0;

		if (!isVisible) {
			elem.css('opacity', 0).show();
			animateTo = 1;
		}

		if ((mode == 'hide' && isVisible) || (mode == 'show' && !isVisible)) {
			times--;
		}

		for (var i = 0; i < times; i++) {
			elem.animate({ opacity: animateTo }, duration, o.options.easing);
			animateTo = (animateTo + 1) % 2;
		}

		elem.animate({ opacity: animateTo }, duration, o.options.easing, function() {
			if (animateTo == 0) {
				elem.hide();
			}
			(o.callback && o.callback.apply(this, arguments));
		});

		elem
			.queue('fx', function() { elem.dequeue(); })
			.dequeue();
	});
};

})(jQuery);
/*
 * jQuery UI Effects Scale 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Scale
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.puff = function(o) {
	return this.queue(function() {
		var elem = $(this),
			mode = $.effects.setMode(elem, o.options.mode || 'hide'),
			percent = parseInt(o.options.percent, 10) || 150,
			factor = percent / 100,
			original = { height: elem.height(), width: elem.width() };

		$.extend(o.options, {
			fade: true,
			mode: mode,
			percent: mode == 'hide' ? percent : 100,
			from: mode == 'hide'
				? original
				: {
					height: original.height * factor,
					width: original.width * factor
				}
		});

		elem.effect('scale', o.options, o.duration, o.callback);
		elem.dequeue();
	});
};

$.effects.scale = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);

		// Set options
		var options = $.extend(true, {}, o.options);
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var percent = parseInt(o.options.percent,10) || (parseInt(o.options.percent,10) == 0 ? 0 : (mode == 'hide' ? 0 : 100)); // Set default scaling percent
		var direction = o.options.direction || 'both'; // Set default axis
		var origin = o.options.origin; // The origin of the scaling
		if (mode != 'effect') { // Set default origin and restore for show/hide
			options.origin = origin || ['middle','center'];
			options.restore = true;
		}
		var original = {height: el.height(), width: el.width()}; // Save original
		el.from = o.options.from || (mode == 'show' ? {height: 0, width: 0} : original); // Default from state

		// Adjust
		var factor = { // Set scaling factor
			y: direction != 'horizontal' ? (percent / 100) : 1,
			x: direction != 'vertical' ? (percent / 100) : 1
		};
		el.to = {height: original.height * factor.y, width: original.width * factor.x}; // Set to state

		if (o.options.fade) { // Fade option to support puff
			if (mode == 'show') {el.from.opacity = 0; el.to.opacity = 1;};
			if (mode == 'hide') {el.from.opacity = 1; el.to.opacity = 0;};
		};

		// Animation
		options.from = el.from; options.to = el.to; options.mode = mode;

		// Animate
		el.effect('size', options, o.duration, o.callback);
		el.dequeue();
	});

};

$.effects.size = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','bottom','left','right','width','height','overflow','opacity'];
		var props1 = ['position','top','bottom','left','right','overflow','opacity']; // Always restore
		var props2 = ['width','height','overflow']; // Copy for children
		var cProps = ['fontSize'];
		var vProps = ['borderTopWidth', 'borderBottomWidth', 'paddingTop', 'paddingBottom'];
		var hProps = ['borderLeftWidth', 'borderRightWidth', 'paddingLeft', 'paddingRight'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var restore = o.options.restore || false; // Default restore
		var scale = o.options.scale || 'both'; // Default scale mode
		var origin = o.options.origin; // The origin of the sizing
		var original = {height: el.height(), width: el.width()}; // Save original
		el.from = o.options.from || original; // Default from state
		el.to = o.options.to || original; // Default to state
		// Adjust
		if (origin) { // Calculate baseline shifts
			var baseline = $.effects.getBaseline(origin, original);
			el.from.top = (original.height - el.from.height) * baseline.y;
			el.from.left = (original.width - el.from.width) * baseline.x;
			el.to.top = (original.height - el.to.height) * baseline.y;
			el.to.left = (original.width - el.to.width) * baseline.x;
		};
		var factor = { // Set scaling factor
			from: {y: el.from.height / original.height, x: el.from.width / original.width},
			to: {y: el.to.height / original.height, x: el.to.width / original.width}
		};
		if (scale == 'box' || scale == 'both') { // Scale the css box
			if (factor.from.y != factor.to.y) { // Vertical props scaling
				props = props.concat(vProps);
				el.from = $.effects.setTransition(el, vProps, factor.from.y, el.from);
				el.to = $.effects.setTransition(el, vProps, factor.to.y, el.to);
			};
			if (factor.from.x != factor.to.x) { // Horizontal props scaling
				props = props.concat(hProps);
				el.from = $.effects.setTransition(el, hProps, factor.from.x, el.from);
				el.to = $.effects.setTransition(el, hProps, factor.to.x, el.to);
			};
		};
		if (scale == 'content' || scale == 'both') { // Scale the content
			if (factor.from.y != factor.to.y) { // Vertical props scaling
				props = props.concat(cProps);
				el.from = $.effects.setTransition(el, cProps, factor.from.y, el.from);
				el.to = $.effects.setTransition(el, cProps, factor.to.y, el.to);
			};
		};
		$.effects.save(el, restore ? props : props1); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		el.css('overflow','hidden').css(el.from); // Shift

		// Animate
		if (scale == 'content' || scale == 'both') { // Scale the children
			vProps = vProps.concat(['marginTop','marginBottom']).concat(cProps); // Add margins/font-size
			hProps = hProps.concat(['marginLeft','marginRight']); // Add margins
			props2 = props.concat(vProps).concat(hProps); // Concat
			el.find("*[width]").each(function(){
				child = $(this);
				if (restore) $.effects.save(child, props2);
				var c_original = {height: child.height(), width: child.width()}; // Save original
				child.from = {height: c_original.height * factor.from.y, width: c_original.width * factor.from.x};
				child.to = {height: c_original.height * factor.to.y, width: c_original.width * factor.to.x};
				if (factor.from.y != factor.to.y) { // Vertical props scaling
					child.from = $.effects.setTransition(child, vProps, factor.from.y, child.from);
					child.to = $.effects.setTransition(child, vProps, factor.to.y, child.to);
				};
				if (factor.from.x != factor.to.x) { // Horizontal props scaling
					child.from = $.effects.setTransition(child, hProps, factor.from.x, child.from);
					child.to = $.effects.setTransition(child, hProps, factor.to.x, child.to);
				};
				child.css(child.from); // Shift children
				child.animate(child.to, o.duration, o.options.easing, function(){
					if (restore) $.effects.restore(child, props2); // Restore children
				}); // Animate children
			});
		};

		// Animate
		el.animate(el.to, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if (el.to.opacity === 0) {
				el.css('opacity', el.from.opacity);
			}
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, restore ? props : props1); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Shake 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Shake
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.shake = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','bottom','left','right'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode
		var direction = o.options.direction || 'left'; // Default direction
		var distance = o.options.distance || 20; // Default distance
		var times = o.options.times || 3; // Default # of times
		var speed = o.duration || o.options.duration || 140; // Default speed per shake

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';

		// Animation
		var animation = {}, animation1 = {}, animation2 = {};
		animation[ref] = (motion == 'pos' ? '-=' : '+=')  + distance;
		animation1[ref] = (motion == 'pos' ? '+=' : '-=')  + distance * 2;
		animation2[ref] = (motion == 'pos' ? '-=' : '+=')  + distance * 2;

		// Animate
		el.animate(animation, speed, o.options.easing);
		for (var i = 1; i < times; i++) { // Shakes
			el.animate(animation1, speed, o.options.easing).animate(animation2, speed, o.options.easing);
		};
		el.animate(animation1, speed, o.options.easing).
		animate(animation, speed / 2, o.options.easing, function(){ // Last shake
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
		});
		el.queue('fx', function() { el.dequeue(); });
		el.dequeue();
	});

};

})(jQuery);
/*
 * jQuery UI Effects Slide 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Slide
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.slide = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','bottom','left','right'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
		var direction = o.options.direction || 'left'; // Default Direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		$.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left';
		var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg';
		var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) : el.outerWidth({margin:true}));
		if (mode == 'show') el.css(ref, motion == 'pos' ? (isNaN(distance) ? "-" + distance : -distance) : distance); // Shift

		// Animation
		var animation = {};
		animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance;

		// Animate
		el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(this, arguments); // Callback
			el.dequeue();
		}});

	});

};

})(jQuery);
/*
 * jQuery UI Effects Transfer 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Effects/Transfer
 *
 * Depends:
 *	jquery.effects.core.js
 */
(function( $, undefined ) {

$.effects.transfer = function(o) {
	return this.queue(function() {
		var elem = $(this),
			target = $(o.options.to),
			endPosition = target.offset(),
			animation = {
				top: endPosition.top,
				left: endPosition.left,
				height: target.innerHeight(),
				width: target.innerWidth()
			},
			startPosition = elem.offset(),
			transfer = $('<div class="ui-effects-transfer"></div>')
				.appendTo(document.body)
				.addClass(o.options.className)
				.css({
					top: startPosition.top,
					left: startPosition.left,
					height: elem.innerHeight(),
					width: elem.innerWidth(),
					position: 'absolute'
				})
				.animate(animation, o.duration, o.options.easing, function() {
					transfer.remove();
					(o.callback && o.callback.apply(elem[0], arguments));
					elem.dequeue();
				});
	});
};

})(jQuery);
/*
 * jQuery UI Accordion 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Accordion
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget( "ui.accordion", {
	options: {
		active: 0,
		animated: "slide",
		autoHeight: true,
		clearStyle: false,
		collapsible: false,
		event: "click",
		fillSpace: false,
		header: "> li > :first-child,> :not(li):even",
		icons: {
			header: "ui-icon-triangle-1-e",
			headerSelected: "ui-icon-triangle-1-s"
		},
		navigation: false,
		navigationFilter: function() {
			return this.href.toLowerCase() === location.href.toLowerCase();
		}
	},

	_create: function() {
		var self = this,
			options = self.options;

		self.running = 0;

		self.element
			.addClass( "ui-accordion ui-widget ui-helper-reset" )
			// in lack of child-selectors in CSS
			// we need to mark top-LIs in a UL-accordion for some IE-fix
			.children( "li" )
				.addClass( "ui-accordion-li-fix" );

		self.headers = self.element.find( options.header )
			.addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" )
			.bind( "mouseenter.accordion", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).addClass( "ui-state-hover" );
			})
			.bind( "mouseleave.accordion", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).removeClass( "ui-state-hover" );
			})
			.bind( "focus.accordion", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).addClass( "ui-state-focus" );
			})
			.bind( "blur.accordion", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).removeClass( "ui-state-focus" );
			});

		self.headers.next()
			.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" );

		if ( options.navigation ) {
			var current = self.element.find( "a" ).filter( options.navigationFilter ).eq( 0 );
			if ( current.length ) {
				var header = current.closest( ".ui-accordion-header" );
				if ( header.length ) {
					// anchor within header
					self.active = header;
				} else {
					// anchor within content
					self.active = current.closest( ".ui-accordion-content" ).prev();
				}
			}
		}

		self.active = self._findActive( self.active || options.active )
			.addClass( "ui-state-default ui-state-active" )
			.toggleClass( "ui-corner-all" )
			.toggleClass( "ui-corner-top" );
		self.active.next().addClass( "ui-accordion-content-active" );

		self._createIcons();
		self.resize();
		
		// ARIA
		self.element.attr( "role", "tablist" );

		self.headers
			.attr( "role", "tab" )
			.bind( "keydown.accordion", function( event ) {
				return self._keydown( event );
			})
			.next()
				.attr( "role", "tabpanel" );

		self.headers
			.not( self.active || "" )
			.attr({
				"aria-expanded": "false",
				"aria-selected": "false",
				tabIndex: -1
			})
			.next()
				.hide();

		// make sure at least one header is in the tab order
		if ( !self.active.length ) {
			self.headers.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			self.active
				.attr({
					"aria-expanded": "true",
					"aria-selected": "true",
					tabIndex: 0
				});
		}

		// only need links in tab order for Safari
		if ( !$.browser.safari ) {
			self.headers.find( "a" ).attr( "tabIndex", -1 );
		}

		if ( options.event ) {
			self.headers.bind( options.event.split(" ").join(".accordion ") + ".accordion", function(event) {
				self._clickHandler.call( self, event, this );
				event.preventDefault();
			});
		}
	},

	_createIcons: function() {
		var options = this.options;
		if ( options.icons ) {
			$( "<span></span>" )
				.addClass( "ui-icon " + options.icons.header )
				.prependTo( this.headers );
			this.active.children( ".ui-icon" )
				.toggleClass(options.icons.header)
				.toggleClass(options.icons.headerSelected);
			this.element.addClass( "ui-accordion-icons" );
		}
	},

	_destroyIcons: function() {
		this.headers.children( ".ui-icon" ).remove();
		this.element.removeClass( "ui-accordion-icons" );
	},

	destroy: function() {
		var options = this.options;

		this.element
			.removeClass( "ui-accordion ui-widget ui-helper-reset" )
			.removeAttr( "role" );

		this.headers
			.unbind( ".accordion" )
			.removeClass( "ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
			.removeAttr( "role" )
			.removeAttr( "aria-expanded" )
			.removeAttr( "aria-selected" )
			.removeAttr( "tabIndex" );

		this.headers.find( "a" ).removeAttr( "tabIndex" );
		this._destroyIcons();
		var contents = this.headers.next()
			.css( "display", "" )
			.removeAttr( "role" )
			.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled" );
		if ( options.autoHeight || options.fillHeight ) {
			contents.css( "height", "" );
		}

		return $.Widget.prototype.destroy.call( this );
	},

	_setOption: function( key, value ) {
		$.Widget.prototype._setOption.apply( this, arguments );
			
		if ( key == "active" ) {
			this.activate( value );
		}
		if ( key == "icons" ) {
			this._destroyIcons();
			if ( value ) {
				this._createIcons();
			}
		}
		// #5332 - opacity doesn't cascade to positioned elements in IE
		// so we need to add the disabled class to the headers and panels
		if ( key == "disabled" ) {
			this.headers.add(this.headers.next())
				[ value ? "addClass" : "removeClass" ](
					"ui-accordion-disabled ui-state-disabled" );
		}
	},

	_keydown: function( event ) {
		if ( this.options.disabled || event.altKey || event.ctrlKey ) {
			return;
		}

		var keyCode = $.ui.keyCode,
			length = this.headers.length,
			currentIndex = this.headers.index( event.target ),
			toFocus = false;

		switch ( event.keyCode ) {
			case keyCode.RIGHT:
			case keyCode.DOWN:
				toFocus = this.headers[ ( currentIndex + 1 ) % length ];
				break;
			case keyCode.LEFT:
			case keyCode.UP:
				toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
				break;
			case keyCode.SPACE:
			case keyCode.ENTER:
				this._clickHandler( { target: event.target }, event.target );
				event.preventDefault();
		}

		if ( toFocus ) {
			$( event.target ).attr( "tabIndex", -1 );
			$( toFocus ).attr( "tabIndex", 0 );
			toFocus.focus();
			return false;
		}

		return true;
	},

	resize: function() {
		var options = this.options,
			maxHeight;

		if ( options.fillSpace ) {
			if ( $.browser.msie ) {
				var defOverflow = this.element.parent().css( "overflow" );
				this.element.parent().css( "overflow", "hidden");
			}
			maxHeight = this.element.parent().height();
			if ($.browser.msie) {
				this.element.parent().css( "overflow", defOverflow );
			}

			this.headers.each(function() {
				maxHeight -= $( this ).outerHeight( true );
			});

			this.headers.next()
				.each(function() {
					$( this ).height( Math.max( 0, maxHeight -
						$( this ).innerHeight() + $( this ).height() ) );
				})
				.css( "overflow", "auto" );
		} else if ( options.autoHeight ) {
			maxHeight = 0;
			this.headers.next()
				.each(function() {
					maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
				})
				.height( maxHeight );
		}

		return this;
	},

	activate: function( index ) {
		// TODO this gets called on init, changing the option without an explicit call for that
		this.options.active = index;
		// call clickHandler with custom event
		var active = this._findActive( index )[ 0 ];
		this._clickHandler( { target: active }, active );

		return this;
	},

	_findActive: function( selector ) {
		return selector
			? typeof selector === "number"
				? this.headers.filter( ":eq(" + selector + ")" )
				: this.headers.not( this.headers.not( selector ) )
			: selector === false
				? $( [] )
				: this.headers.filter( ":eq(0)" );
	},

	// TODO isn't event.target enough? why the separate target argument?
	_clickHandler: function( event, target ) {
		var options = this.options;
		if ( options.disabled ) {
			return;
		}

		// called only when using activate(false) to close all parts programmatically
		if ( !event.target ) {
			if ( !options.collapsible ) {
				return;
			}
			this.active
				.removeClass( "ui-state-active ui-corner-top" )
				.addClass( "ui-state-default ui-corner-all" )
				.children( ".ui-icon" )
					.removeClass( options.icons.headerSelected )
					.addClass( options.icons.header );
			this.active.next().addClass( "ui-accordion-content-active" );
			var toHide = this.active.next(),
				data = {
					options: options,
					newHeader: $( [] ),
					oldHeader: options.active,
					newContent: $( [] ),
					oldContent: toHide
				},
				toShow = ( this.active = $( [] ) );
			this._toggle( toShow, toHide, data );
			return;
		}

		// get the click target
		var clicked = $( event.currentTarget || target ),
			clickedIsActive = clicked[0] === this.active[0];

		// TODO the option is changed, is that correct?
		// TODO if it is correct, shouldn't that happen after determining that the click is valid?
		options.active = options.collapsible && clickedIsActive ?
			false :
			this.headers.index( clicked );

		// if animations are still active, or the active header is the target, ignore click
		if ( this.running || ( !options.collapsible && clickedIsActive ) ) {
			return;
		}

		// find elements to show and hide
		var active = this.active,
			toShow = clicked.next(),
			toHide = this.active.next(),
			data = {
				options: options,
				newHeader: clickedIsActive && options.collapsible ? $([]) : clicked,
				oldHeader: this.active,
				newContent: clickedIsActive && options.collapsible ? $([]) : toShow,
				oldContent: toHide
			},
			down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] );

		// when the call to ._toggle() comes after the class changes
		// it causes a very odd bug in IE 8 (see #6720)
		this.active = clickedIsActive ? $([]) : clicked;
		this._toggle( toShow, toHide, data, clickedIsActive, down );

		// switch classes
		active
			.removeClass( "ui-state-active ui-corner-top" )
			.addClass( "ui-state-default ui-corner-all" )
			.children( ".ui-icon" )
				.removeClass( options.icons.headerSelected )
				.addClass( options.icons.header );
		if ( !clickedIsActive ) {
			clicked
				.removeClass( "ui-state-default ui-corner-all" )
				.addClass( "ui-state-active ui-corner-top" )
				.children( ".ui-icon" )
					.removeClass( options.icons.header )
					.addClass( options.icons.headerSelected );
			clicked
				.next()
				.addClass( "ui-accordion-content-active" );
		}

		return;
	},

	_toggle: function( toShow, toHide, data, clickedIsActive, down ) {
		var self = this,
			options = self.options;

		self.toShow = toShow;
		self.toHide = toHide;
		self.data = data;

		var complete = function() {
			if ( !self ) {
				return;
			}
			return self._completed.apply( self, arguments );
		};

		// trigger changestart event
		self._trigger( "changestart", null, self.data );

		// count elements to animate
		self.running = toHide.size() === 0 ? toShow.size() : toHide.size();

		if ( options.animated ) {
			var animOptions = {};

			if ( options.collapsible && clickedIsActive ) {
				animOptions = {
					toShow: $( [] ),
					toHide: toHide,
					complete: complete,
					down: down,
					autoHeight: options.autoHeight || options.fillSpace
				};
			} else {
				animOptions = {
					toShow: toShow,
					toHide: toHide,
					complete: complete,
					down: down,
					autoHeight: options.autoHeight || options.fillSpace
				};
			}

			if ( !options.proxied ) {
				options.proxied = options.animated;
			}

			if ( !options.proxiedDuration ) {
				options.proxiedDuration = options.duration;
			}

			options.animated = $.isFunction( options.proxied ) ?
				options.proxied( animOptions ) :
				options.proxied;

			options.duration = $.isFunction( options.proxiedDuration ) ?
				options.proxiedDuration( animOptions ) :
				options.proxiedDuration;

			var animations = $.ui.accordion.animations,
				duration = options.duration,
				easing = options.animated;

			if ( easing && !animations[ easing ] && !$.easing[ easing ] ) {
				easing = "slide";
			}
			if ( !animations[ easing ] ) {
				animations[ easing ] = function( options ) {
					this.slide( options, {
						easing: easing,
						duration: duration || 700
					});
				};
			}

			animations[ easing ]( animOptions );
		} else {
			if ( options.collapsible && clickedIsActive ) {
				toShow.toggle();
			} else {
				toHide.hide();
				toShow.show();
			}

			complete( true );
		}

		// TODO assert that the blur and focus triggers are really necessary, remove otherwise
		toHide.prev()
			.attr({
				"aria-expanded": "false",
				"aria-selected": "false",
				tabIndex: -1
			})
			.blur();
		toShow.prev()
			.attr({
				"aria-expanded": "true",
				"aria-selected": "true",
				tabIndex: 0
			})
			.focus();
	},

	_completed: function( cancel ) {
		this.running = cancel ? 0 : --this.running;
		if ( this.running ) {
			return;
		}

		if ( this.options.clearStyle ) {
			this.toShow.add( this.toHide ).css({
				height: "",
				overflow: ""
			});
		}

		// other classes are removed before the animation; this one needs to stay until completed
		this.toHide.removeClass( "ui-accordion-content-active" );
		// Work around for rendering bug in IE (#5421)
		if ( this.toHide.length ) {
			this.toHide.parent()[0].className = this.toHide.parent()[0].className;
		}

		this._trigger( "change", null, this.data );
	}
});

$.extend( $.ui.accordion, {
	version: "1.8.12",
	animations: {
		slide: function( options, additions ) {
			options = $.extend({
				easing: "swing",
				duration: 300
			}, options, additions );
			if ( !options.toHide.size() ) {
				options.toShow.animate({
					height: "show",
					paddingTop: "show",
					paddingBottom: "show"
				}, options );
				return;
			}
			if ( !options.toShow.size() ) {
				options.toHide.animate({
					height: "hide",
					paddingTop: "hide",
					paddingBottom: "hide"
				}, options );
				return;
			}
			var overflow = options.toShow.css( "overflow" ),
				percentDone = 0,
				showProps = {},
				hideProps = {},
				fxAttrs = [ "height", "paddingTop", "paddingBottom" ],
				originalWidth;
			// fix width before calculating height of hidden element
			var s = options.toShow;
			originalWidth = s[0].style.width;
			s.width( parseInt( s.parent().width(), 10 )
				- parseInt( s.css( "paddingLeft" ), 10 )
				- parseInt( s.css( "paddingRight" ), 10 )
				- ( parseInt( s.css( "borderLeftWidth" ), 10 ) || 0 )
				- ( parseInt( s.css( "borderRightWidth" ), 10) || 0 ) );

			$.each( fxAttrs, function( i, prop ) {
				hideProps[ prop ] = "hide";

				var parts = ( "" + $.css( options.toShow[0], prop ) ).match( /^([\d+-.]+)(.*)$/ );
				showProps[ prop ] = {
					value: parts[ 1 ],
					unit: parts[ 2 ] || "px"
				};
			});
			options.toShow.css({ height: 0, overflow: "hidden" }).show();
			options.toHide
				.filter( ":hidden" )
					.each( options.complete )
				.end()
				.filter( ":visible" )
				.animate( hideProps, {
				step: function( now, settings ) {
					// only calculate the percent when animating height
					// IE gets very inconsistent results when animating elements
					// with small values, which is common for padding
					if ( settings.prop == "height" ) {
						percentDone = ( settings.end - settings.start === 0 ) ? 0 :
							( settings.now - settings.start ) / ( settings.end - settings.start );
					}

					options.toShow[ 0 ].style[ settings.prop ] =
						( percentDone * showProps[ settings.prop ].value )
						+ showProps[ settings.prop ].unit;
				},
				duration: options.duration,
				easing: options.easing,
				complete: function() {
					if ( !options.autoHeight ) {
						options.toShow.css( "height", "" );
					}
					options.toShow.css({
						width: originalWidth,
						overflow: overflow
					});
					options.complete();
				}
			});
		},
		bounceslide: function( options ) {
			this.slide( options, {
				easing: options.down ? "easeOutBounce" : "swing",
				duration: options.down ? 1000 : 200
			});
		}
	}
});

})( jQuery );
/*
 * jQuery UI Autocomplete 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Autocomplete
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 */
(function( $, undefined ) {

// used to prevent race conditions with remote data sources
var requestIndex = 0;

$.widget( "ui.autocomplete", {
	options: {
		appendTo: "body",
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null
	},

	pending: 0,

	_create: function() {
		var self = this,
			doc = this.element[ 0 ].ownerDocument,
			suppressKeyPress;

		this.element
			.addClass( "ui-autocomplete-input" )
			.attr( "autocomplete", "off" )
			// TODO verify these actually work as intended
			.attr({
				role: "textbox",
				"aria-autocomplete": "list",
				"aria-haspopup": "true"
			})
			.bind( "keydown.autocomplete", function( event ) {
				if ( self.options.disabled || self.element.attr( "readonly" ) ) {
					return;
				}

				suppressKeyPress = false;
				var keyCode = $.ui.keyCode;
				switch( event.keyCode ) {
				case keyCode.PAGE_UP:
					self._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					self._move( "nextPage", event );
					break;
				case keyCode.UP:
					self._move( "previous", event );
					// prevent moving cursor to beginning of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.DOWN:
					self._move( "next", event );
					// prevent moving cursor to end of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.ENTER:
				case keyCode.NUMPAD_ENTER:
					// when menu is open and has focus
					if ( self.menu.active ) {
						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
					}
					//passthrough - ENTER and TAB both select the current element
				case keyCode.TAB:
					if ( !self.menu.active ) {
						return;
					}
					self.menu.select( event );
					break;
				case keyCode.ESCAPE:
					self.element.val( self.term );
					self.close( event );
					break;
				default:
					// keypress is triggered before the input value is changed
					clearTimeout( self.searching );
					self.searching = setTimeout(function() {
						// only search if the value has changed
						if ( self.term != self.element.val() ) {
							self.selectedItem = null;
							self.search( null, event );
						}
					}, self.options.delay );
					break;
				}
			})
			.bind( "keypress.autocomplete", function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					event.preventDefault();
				}
			})
			.bind( "focus.autocomplete", function() {
				if ( self.options.disabled ) {
					return;
				}

				self.selectedItem = null;
				self.previous = self.element.val();
			})
			.bind( "blur.autocomplete", function( event ) {
				if ( self.options.disabled ) {
					return;
				}

				clearTimeout( self.searching );
				// clicks on the menu (or a button to trigger a search) will cause a blur event
				self.closing = setTimeout(function() {
					self.close( event );
					self._change( event );
				}, 150 );
			});
		this._initSource();
		this.response = function() {
			return self._response.apply( self, arguments );
		};
		this.menu = $( "<ul></ul>" )
			.addClass( "ui-autocomplete" )
			.appendTo( $( this.options.appendTo || "body", doc )[0] )
			// prevent the close-on-blur in case of a "slow" click on the menu (long mousedown)
			.mousedown(function( event ) {
				// clicking on the scrollbar causes focus to shift to the body
				// but we can't detect a mouseup or a click immediately afterward
				// so we have to track the next mousedown and close the menu if
				// the user clicks somewhere outside of the autocomplete
				var menuElement = self.menu.element[ 0 ];
				if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
					setTimeout(function() {
						$( document ).one( 'mousedown', function( event ) {
							if ( event.target !== self.element[ 0 ] &&
								event.target !== menuElement &&
								!$.ui.contains( menuElement, event.target ) ) {
								self.close();
							}
						});
					}, 1 );
				}

				// use another timeout to make sure the blur-event-handler on the input was already triggered
				setTimeout(function() {
					clearTimeout( self.closing );
				}, 13);
			})
			.menu({
				focus: function( event, ui ) {
					var item = ui.item.data( "item.autocomplete" );
					if ( false !== self._trigger( "focus", event, { item: item } ) ) {
						// use value to match what will end up in the input, if it was a key event
						if ( /^key/.test(event.originalEvent.type) ) {
							self.element.val( item.value );
						}
					}
				},
				selected: function( event, ui ) {
					var item = ui.item.data( "item.autocomplete" ),
						previous = self.previous;

					// only trigger when focus was lost (click on menu)
					if ( self.element[0] !== doc.activeElement ) {
						self.element.focus();
						self.previous = previous;
						// #6109 - IE triggers two focus events and the second
						// is asynchronous, so we need to reset the previous
						// term synchronously and asynchronously :-(
						setTimeout(function() {
							self.previous = previous;
							self.selectedItem = item;
						}, 1);
					}

					if ( false !== self._trigger( "select", event, { item: item } ) ) {
						self.element.val( item.value );
					}
					// reset the term after the select event
					// this allows custom select handling to work properly
					self.term = self.element.val();

					self.close( event );
					self.selectedItem = item;
				},
				blur: function( event, ui ) {
					// don't set the value of the text field if it's already correct
					// this prevents moving the cursor unnecessarily
					if ( self.menu.element.is(":visible") &&
						( self.element.val() !== self.term ) ) {
						self.element.val( self.term );
					}
				}
			})
			.zIndex( this.element.zIndex() + 1 )
			// workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781
			.css({ top: 0, left: 0 })
			.hide()
			.data( "menu" );
		if ( $.fn.bgiframe ) {
			 this.menu.element.bgiframe();
		}
	},

	destroy: function() {
		this.element
			.removeClass( "ui-autocomplete-input" )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-autocomplete" )
			.removeAttr( "aria-haspopup" );
		this.menu.element.remove();
		$.Widget.prototype.destroy.call( this );
	},

	_setOption: function( key, value ) {
		$.Widget.prototype._setOption.apply( this, arguments );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( $( value || "body", this.element[0].ownerDocument )[0] )
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_initSource: function() {
		var self = this,
			array,
			url;
		if ( $.isArray(this.options.source) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter(array, request.term) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( self.xhr ) {
					self.xhr.abort();
				}
				self.xhr = $.ajax({
					url: url,
					data: request,
					dataType: "json",
					autocompleteRequest: ++requestIndex,
					success: function( data, status ) {
						if ( this.autocompleteRequest === requestIndex ) {
							response( data );
						}
					},
					error: function() {
						if ( this.autocompleteRequest === requestIndex ) {
							response( [] );
						}
					}
				});
			};
		} else {
			this.source = this.options.source;
		}
	},

	search: function( value, event ) {
		value = value != null ? value : this.element.val();

		// always save the actual value, not the one passed as an argument
		this.term = this.element.val();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		clearTimeout( this.closing );
		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this.element.addClass( "ui-autocomplete-loading" );

		this.source( { term: value }, this.response );
	},

	_response: function( content ) {
		if ( !this.options.disabled && content && content.length ) {
			content = this._normalize( content );
			this._suggest( content );
			this._trigger( "open" );
		} else {
			this.close();
		}
		this.pending--;
		if ( !this.pending ) {
			this.element.removeClass( "ui-autocomplete-loading" );
		}
	},

	close: function( event ) {
		clearTimeout( this.closing );
		if ( this.menu.element.is(":visible") ) {
			this.menu.element.hide();
			this.menu.deactivate();
			this._trigger( "close", event );
		}
	},
	
	_change: function( event ) {
		if ( this.previous !== this.element.val() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {
		// assume all items have the right format when the first item is complete
		if ( items.length && items[0].label && items[0].value ) {
			return items;
		}
		return $.map( items, function(item) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend({
				label: item.label || item.value,
				value: item.value || item.label
			}, item );
		});
	},

	_suggest: function( items ) {
		var ul = this.menu.element
			.empty()
			.zIndex( this.element.zIndex() + 1 );
		this._renderMenu( ul, items );
		// TODO refresh should check if the active item is still in the dom, removing the need for a manual deactivate
		this.menu.deactivate();
		this.menu.refresh();

		// size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend({
			of: this.element
		}, this.options.position ));

		if ( this.options.autoFocus ) {
			this.menu.next( new $.Event("mouseover") );
		}
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(
			ul.width( "" ).outerWidth(),
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var self = this;
		$.each( items, function( index, item ) {
			self._renderItem( ul, item );
		});
	},

	_renderItem: function( ul, item) {
		return $( "<li></li>" )
			.data( "item.autocomplete", item )
			.append( $( "<a></a>" ).text( item.label ) )
			.appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is(":visible") ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.first() && /^previous/.test(direction) ||
				this.menu.last() && /^next/.test(direction) ) {
			this.element.val( this.term );
			this.menu.deactivate();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	}
});

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
	},
	filter: function(array, term) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
		return $.grep( array, function(value) {
			return matcher.test( value.label || value.value || value );
		});
	}
});

}( jQuery ));

/*
 * jQuery UI Menu (not officially released)
 * 
 * This widget isn't yet finished and the API is subject to change. We plan to finish
 * it for the next release. You're welcome to give it a try anyway and give us feedback,
 * as long as you're okay with migrating your code later on. We can help with that, too.
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Menu
 *
 * Depends:
 *	jquery.ui.core.js
 *  jquery.ui.widget.js
 */
(function($) {

$.widget("ui.menu", {
	_create: function() {
		var self = this;
		this.element
			.addClass("ui-menu ui-widget ui-widget-content ui-corner-all")
			.attr({
				role: "listbox",
				"aria-activedescendant": "ui-active-menuitem"
			})
			.click(function( event ) {
				if ( !$( event.target ).closest( ".ui-menu-item a" ).length ) {
					return;
				}
				// temporary
				event.preventDefault();
				self.select( event );
			});
		this.refresh();
	},
	
	refresh: function() {
		var self = this;

		// don't refresh list items that are already adapted
		var items = this.element.children("li:not(.ui-menu-item):has(a)")
			.addClass("ui-menu-item")
			.attr("role", "menuitem");
		
		items.children("a")
			.addClass("ui-corner-all")
			.attr("tabindex", -1)
			// mouseenter doesn't work with event delegation
			.mouseenter(function( event ) {
				self.activate( event, $(this).parent() );
			})
			.mouseleave(function() {
				self.deactivate();
			});
	},

	activate: function( event, item ) {
		this.deactivate();
		if (this.hasScroll()) {
			var offset = item.offset().top - this.element.offset().top,
				scroll = this.element.attr("scrollTop"),
				elementHeight = this.element.height();
			if (offset < 0) {
				this.element.attr("scrollTop", scroll + offset);
			} else if (offset >= elementHeight) {
				this.element.attr("scrollTop", scroll + offset - elementHeight + item.height());
			}
		}
		this.active = item.eq(0)
			.children("a")
				.addClass("ui-state-hover")
				.attr("id", "ui-active-menuitem")
			.end();
		this._trigger("focus", event, { item: item });
	},

	deactivate: function() {
		if (!this.active) { return; }

		this.active.children("a")
			.removeClass("ui-state-hover")
			.removeAttr("id");
		this._trigger("blur");
		this.active = null;
	},

	next: function(event) {
		this.move("next", ".ui-menu-item:first", event);
	},

	previous: function(event) {
		this.move("prev", ".ui-menu-item:last", event);
	},

	first: function() {
		return this.active && !this.active.prevAll(".ui-menu-item").length;
	},

	last: function() {
		return this.active && !this.active.nextAll(".ui-menu-item").length;
	},

	move: function(direction, edge, event) {
		if (!this.active) {
			this.activate(event, this.element.children(edge));
			return;
		}
		var next = this.active[direction + "All"](".ui-menu-item").eq(0);
		if (next.length) {
			this.activate(event, next);
		} else {
			this.activate(event, this.element.children(edge));
		}
	},

	// TODO merge with previousPage
	nextPage: function(event) {
		if (this.hasScroll()) {
			// TODO merge with no-scroll-else
			if (!this.active || this.last()) {
				this.activate(event, this.element.children(".ui-menu-item:first"));
				return;
			}
			var base = this.active.offset().top,
				height = this.element.height(),
				result = this.element.children(".ui-menu-item").filter(function() {
					var close = $(this).offset().top - base - height + $(this).height();
					// TODO improve approximation
					return close < 10 && close > -10;
				});

			// TODO try to catch this earlier when scrollTop indicates the last page anyway
			if (!result.length) {
				result = this.element.children(".ui-menu-item:last");
			}
			this.activate(event, result);
		} else {
			this.activate(event, this.element.children(".ui-menu-item")
				.filter(!this.active || this.last() ? ":first" : ":last"));
		}
	},

	// TODO merge with nextPage
	previousPage: function(event) {
		if (this.hasScroll()) {
			// TODO merge with no-scroll-else
			if (!this.active || this.first()) {
				this.activate(event, this.element.children(".ui-menu-item:last"));
				return;
			}

			var base = this.active.offset().top,
				height = this.element.height();
				result = this.element.children(".ui-menu-item").filter(function() {
					var close = $(this).offset().top - base + height - $(this).height();
					// TODO improve approximation
					return close < 10 && close > -10;
				});

			// TODO try to catch this earlier when scrollTop indicates the last page anyway
			if (!result.length) {
				result = this.element.children(".ui-menu-item:first");
			}
			this.activate(event, result);
		} else {
			this.activate(event, this.element.children(".ui-menu-item")
				.filter(!this.active || this.first() ? ":last" : ":first"));
		}
	},

	hasScroll: function() {
		return this.element.height() < this.element.attr("scrollHeight");
	},

	select: function( event ) {
		this._trigger("selected", event, { item: this.active });
	}
});

}(jQuery));
/*
 * jQuery UI Button 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Button
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

var lastActive,
	baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
	stateClasses = "ui-state-hover ui-state-active ",
	typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
	formResetHandler = function( event ) {
		$( ":ui-button", event.target.form ).each(function() {
			var inst = $( this ).data( "button" );
			setTimeout(function() {
				inst.refresh();
			}, 1 );
		});
	},
	radioGroup = function( radio ) {
		var name = radio.name,
			form = radio.form,
			radios = $( [] );
		if ( name ) {
			if ( form ) {
				radios = $( form ).find( "[name='" + name + "']" );
			} else {
				radios = $( "[name='" + name + "']", radio.ownerDocument )
					.filter(function() {
						return !this.form;
					});
			}
		}
		return radios;
	};

$.widget( "ui.button", {
	options: {
		disabled: null,
		text: true,
		label: null,
		icons: {
			primary: null,
			secondary: null
		}
	},
	_create: function() {
		this.element.closest( "form" )
			.unbind( "reset.button" )
			.bind( "reset.button", formResetHandler );

		if ( typeof this.options.disabled !== "boolean" ) {
			this.options.disabled = this.element.attr( "disabled" );
		}

		this._determineButtonType();
		this.hasTitle = !!this.buttonElement.attr( "title" );

		var self = this,
			options = this.options,
			toggleButton = this.type === "checkbox" || this.type === "radio",
			hoverClass = "ui-state-hover" + ( !toggleButton ? " ui-state-active" : "" ),
			focusClass = "ui-state-focus";

		if ( options.label === null ) {
			options.label = this.buttonElement.html();
		}

		if ( this.element.is( ":disabled" ) ) {
			options.disabled = true;
		}

		this.buttonElement
			.addClass( baseClasses )
			.attr( "role", "button" )
			.bind( "mouseenter.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).addClass( "ui-state-hover" );
				if ( this === lastActive ) {
					$( this ).addClass( "ui-state-active" );
				}
			})
			.bind( "mouseleave.button", function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).removeClass( hoverClass );
			})
			.bind( "focus.button", function() {
				// no need to check disabled, focus won't be triggered anyway
				$( this ).addClass( focusClass );
			})
			.bind( "blur.button", function() {
				$( this ).removeClass( focusClass );
			});

		if ( toggleButton ) {
			this.element.bind( "change.button", function() {
				self.refresh();
			});
		}

		if ( this.type === "checkbox" ) {
			this.buttonElement.bind( "click.button", function() {
				if ( options.disabled ) {
					return false;
				}
				$( this ).toggleClass( "ui-state-active" );
				self.buttonElement.attr( "aria-pressed", self.element[0].checked );
			});
		} else if ( this.type === "radio" ) {
			this.buttonElement.bind( "click.button", function() {
				if ( options.disabled ) {
					return false;
				}
				$( this ).addClass( "ui-state-active" );
				self.buttonElement.attr( "aria-pressed", true );

				var radio = self.element[ 0 ];
				radioGroup( radio )
					.not( radio )
					.map(function() {
						return $( this ).button( "widget" )[ 0 ];
					})
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", false );
			});
		} else {
			this.buttonElement
				.bind( "mousedown.button", function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).addClass( "ui-state-active" );
					lastActive = this;
					$( document ).one( "mouseup", function() {
						lastActive = null;
					});
				})
				.bind( "mouseup.button", function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).removeClass( "ui-state-active" );
				})
				.bind( "keydown.button", function(event) {
					if ( options.disabled ) {
						return false;
					}
					if ( event.keyCode == $.ui.keyCode.SPACE || event.keyCode == $.ui.keyCode.ENTER ) {
						$( this ).addClass( "ui-state-active" );
					}
				})
				.bind( "keyup.button", function() {
					$( this ).removeClass( "ui-state-active" );
				});

			if ( this.buttonElement.is("a") ) {
				this.buttonElement.keyup(function(event) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						// TODO pass through original event correctly (just as 2nd argument doesn't work)
						$( this ).click();
					}
				});
			}
		}

		// TODO: pull out $.Widget's handling for the disabled option into
		// $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
		// be overridden by individual plugins
		this._setOption( "disabled", options.disabled );
	},

	_determineButtonType: function() {

		if ( this.element.is(":checkbox") ) {
			this.type = "checkbox";
		} else if ( this.element.is(":radio") ) {
			this.type = "radio";
		} else if ( this.element.is("input") ) {
			this.type = "input";
		} else {
			this.type = "button";
		}

		if ( this.type === "checkbox" || this.type === "radio" ) {
			// we don't search against the document in case the element
			// is disconnected from the DOM
			var ancestor = this.element.parents().filter(":last"),
				labelSelector = "label[for=" + this.element.attr("id") + "]";
			this.buttonElement = ancestor.find( labelSelector );
			if ( !this.buttonElement.length ) {
				ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
				this.buttonElement = ancestor.filter( labelSelector );
				if ( !this.buttonElement.length ) {
					this.buttonElement = ancestor.find( labelSelector );
				}
			}
			this.element.addClass( "ui-helper-hidden-accessible" );

			var checked = this.element.is( ":checked" );
			if ( checked ) {
				this.buttonElement.addClass( "ui-state-active" );
			}
			this.buttonElement.attr( "aria-pressed", checked );
		} else {
			this.buttonElement = this.element;
		}
	},

	widget: function() {
		return this.buttonElement;
	},

	destroy: function() {
		this.element
			.removeClass( "ui-helper-hidden-accessible" );
		this.buttonElement
			.removeClass( baseClasses + " " + stateClasses + " " + typeClasses )
			.removeAttr( "role" )
			.removeAttr( "aria-pressed" )
			.html( this.buttonElement.find(".ui-button-text").html() );

		if ( !this.hasTitle ) {
			this.buttonElement.removeAttr( "title" );
		}

		$.Widget.prototype.destroy.call( this );
	},

	_setOption: function( key, value ) {
		$.Widget.prototype._setOption.apply( this, arguments );
		if ( key === "disabled" ) {
			if ( value ) {
				this.element.attr( "disabled", true );
			} else {
				this.element.removeAttr( "disabled" );
			}
		}
		this._resetButton();
	},

	refresh: function() {
		var isDisabled = this.element.is( ":disabled" );
		if ( isDisabled !== this.options.disabled ) {
			this._setOption( "disabled", isDisabled );
		}
		if ( this.type === "radio" ) {
			radioGroup( this.element[0] ).each(function() {
				if ( $( this ).is( ":checked" ) ) {
					$( this ).button( "widget" )
						.addClass( "ui-state-active" )
						.attr( "aria-pressed", true );
				} else {
					$( this ).button( "widget" )
						.removeClass( "ui-state-active" )
						.attr( "aria-pressed", false );
				}
			});
		} else if ( this.type === "checkbox" ) {
			if ( this.element.is( ":checked" ) ) {
				this.buttonElement
					.addClass( "ui-state-active" )
					.attr( "aria-pressed", true );
			} else {
				this.buttonElement
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", false );
			}
		}
	},

	_resetButton: function() {
		if ( this.type === "input" ) {
			if ( this.options.label ) {
				this.element.val( this.options.label );
			}
			return;
		}
		var buttonElement = this.buttonElement.removeClass( typeClasses ),
			buttonText = $( "<span></span>" )
				.addClass( "ui-button-text" )
				.html( this.options.label )
				.appendTo( buttonElement.empty() )
				.text(),
			icons = this.options.icons,
			multipleIcons = icons.primary && icons.secondary,
			buttonClasses = [];  

		if ( icons.primary || icons.secondary ) {
			if ( this.options.text ) {
				buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
			}

			if ( icons.primary ) {
				buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
			}

			if ( icons.secondary ) {
				buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
			}

			if ( !this.options.text ) {
				buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );

				if ( !this.hasTitle ) {
					buttonElement.attr( "title", buttonText );
				}
			}
		} else {
			buttonClasses.push( "ui-button-text-only" );
		}
		buttonElement.addClass( buttonClasses.join( " " ) );
	}
});

$.widget( "ui.buttonset", {
	options: {
		items: ":button, :submit, :reset, :checkbox, :radio, a, :data(button)"
	},

	_create: function() {
		this.element.addClass( "ui-buttonset" );
	},
	
	_init: function() {
		this.refresh();
	},

	_setOption: function( key, value ) {
		if ( key === "disabled" ) {
			this.buttons.button( "option", key, value );
		}

		$.Widget.prototype._setOption.apply( this, arguments );
	},
	
	refresh: function() {
		this.buttons = this.element.find( this.options.items )
			.filter( ":ui-button" )
				.button( "refresh" )
			.end()
			.not( ":ui-button" )
				.button()
			.end()
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
				.filter( ":first" )
					.addClass( "ui-corner-left" )
				.end()
				.filter( ":last" )
					.addClass( "ui-corner-right" )
				.end()
			.end();
	},

	destroy: function() {
		this.element.removeClass( "ui-buttonset" );
		this.buttons
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-left ui-corner-right" )
			.end()
			.button( "destroy" );

		$.Widget.prototype.destroy.call( this );
	}
});

}( jQuery ) );
/*
 * jQuery UI Datepicker 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	jquery.ui.core.js
 */
(function( $, undefined ) {

$.extend($.ui, { datepicker: { version: "1.8.12" } });

var PROP_NAME = 'datepicker';
var dpuuid = new Date().getTime();

/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this.debug = false; // Change this to true to start debugging
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
	this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
	this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
	this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
	this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
	this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
	this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
	this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
	this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[''] = { // Default regional settings
		closeText: 'Done', // Display text for close link
		prevText: 'Prev', // Display text for previous month link
		nextText: 'Next', // Display text for next month link
		currentText: 'Today', // Display text for current month link
		monthNames: ['January','February','March','April','May','June',
			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
		weekHeader: 'Wk', // Column header for week of the year
		dateFormat: 'mm/dd/yy', // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false, // True if right-to-left language, false if left-to-right
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearSuffix: '' // Additional text to append to the year in the month headers
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: 'focus', // 'focus' for popup on focus,
			// 'button' for trigger button, or 'both' for either
		showAnim: 'fadeIn', // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: '', // Display text following the input box, e.g. showing the format
		buttonText: '...', // Text for trigger button
		buttonImage: '', // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		yearRange: 'c-10:c+10', // Range of years to display in drop-down,
			// either relative to today's year (-nn:+nn), relative to currently displayed year
			// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
		showWeek: false, // True to show week of the year, false to not show it
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: '+10', // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with '+' for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: 'fast', // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: '', // Selector for an alternate field to store selected dates into
		altFormat: '', // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false, // True to show button panel, false to not show it
		autoSize: false // True to size the input for the date format, false to leave as is
	};
	$.extend(this._defaults, this.regional['']);
	this.dpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>');
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: 'hasDatepicker',

	/* Debug logging (if enabled). */
	log: function () {
		if (this.debug)
			console.log.apply('', arguments);
	},
	
	// TODO rename to "widget" when switching to widget factory
	_widgetDatepicker: function() {
		return this.dpDiv;
	},

	/* Override the default settings for all instances of the date picker.
	   @param  settings  object - the new settings to use as defaults (anonymous object)
	   @return the manager object */
	setDefaults: function(settings) {
		extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span
	   @param  settings  object - the new settings to use for this date picker instance (anonymous) */
	_attachDatepicker: function(target, settings) {
		// check for settings on the control itself - in namespace 'date:'
		var inlineSettings = null;
		for (var attrName in this._defaults) {
			var attrValue = target.getAttribute('date:' + attrName);
			if (attrValue) {
				inlineSettings = inlineSettings || {};
				try {
					inlineSettings[attrName] = eval(attrValue);
				} catch (err) {
					inlineSettings[attrName] = attrValue;
				}
			}
		}
		var nodeName = target.nodeName.toLowerCase();
		var inline = (nodeName == 'div' || nodeName == 'span');
		if (!target.id) {
			this.uuid += 1;
			target.id = 'dp' + this.uuid;
		}
		var inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {}, inlineSettings || {});
		if (nodeName == 'input') {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			$('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		inst.append = $([]);
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName))
			return;
		this._attachments(input, inst);
		input.addClass(this.markerClassName).keydown(this._doKeyDown).
			keypress(this._doKeyPress).keyup(this._doKeyUp).
			bind("setData.datepicker", function(event, key, value) {
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key) {
				return this._get(inst, key);
			});
		this._autoSize(inst);
		$.data(target, PROP_NAME, inst);
	},

	/* Make attachments based on settings. */
	_attachments: function(input, inst) {
		var appendText = this._get(inst, 'appendText');
		var isRTL = this._get(inst, 'isRTL');
		if (inst.append)
			inst.append.remove();
		if (appendText) {
			inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
			input[isRTL ? 'before' : 'after'](inst.append);
		}
		input.unbind('focus', this._showDatepicker);
		if (inst.trigger)
			inst.trigger.remove();
		var showOn = this._get(inst, 'showOn');
		if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
			var buttonText = this._get(inst, 'buttonText');
			var buttonImage = this._get(inst, 'buttonImage');
			inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
				$('<img/>').addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$('<button type="button"></button>').addClass(this._triggerClass).
					html(buttonImage == '' ? buttonText : $('<img/>').attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? 'before' : 'after'](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0])
					$.datepicker._hideDatepicker();
				else
					$.datepicker._showDatepicker(input[0]);
				return false;
			});
		}
	},

	/* Apply the maximum length for the date format. */
	_autoSize: function(inst) {
		if (this._get(inst, 'autoSize') && !inst.inline) {
			var date = new Date(2009, 12 - 1, 20); // Ensure double digits
			var dateFormat = this._get(inst, 'dateFormat');
			if (dateFormat.match(/[DM]/)) {
				var findMax = function(names) {
					var max = 0;
					var maxI = 0;
					for (var i = 0; i < names.length; i++) {
						if (names[i].length > max) {
							max = names[i].length;
							maxI = i;
						}
					}
					return maxI;
				};
				date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
					'monthNames' : 'monthNamesShort'))));
				date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
					'dayNames' : 'dayNamesShort'))) + 20 - date.getDay());
			}
			inst.input.attr('size', this._formatDate(inst, date).length);
		}
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName))
			return;
		divSpan.addClass(this.markerClassName).append(inst.dpDiv).
			bind("setData.datepicker", function(event, key, value){
				inst.settings[key] = value;
			}).bind("getData.datepicker", function(event, key){
				return this._get(inst, key);
			});
		$.data(target, PROP_NAME, inst);
		this._setDate(inst, this._getDefaultDate(inst), true);
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
		inst.dpDiv.show();
	},

	/* Pop-up the date picker in a "dialog" box.
	   @param  input     element - ignored
	   @param  date      string or Date - the initial date to display
	   @param  onSelect  function - the function to call when a date is selected
	   @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	   @param  pos       int[2] - coordinates for the dialog's position within the screen or
	                     event - with x/y coordinates or
	                     leave empty for default (screen centre)
	   @return the manager object */
	_dialogDatepicker: function(input, date, onSelect, settings, pos) {
		var inst = this._dialogInst; // internal instance
		if (!inst) {
			this.uuid += 1;
			var id = 'dp' + this.uuid;
			this._dialogInput = $('<input type="text" id="' + id +
				'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>');
			this._dialogInput.keydown(this._doKeyDown);
			$('body').append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], PROP_NAME, inst);
		}
		extendRemove(inst.settings, settings || {});
		date = (date && date.constructor == Date ? this._formatDate(inst, date) : date);
		this._dialogInput.val(date);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			var browserWidth = document.documentElement.clientWidth;
			var browserHeight = document.documentElement.clientHeight;
			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px');
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI)
			$.blockUI(this.dpDiv);
		$.data(this._dialogInput[0], PROP_NAME, inst);
		return this;
	},

	/* Detach a datepicker from its control.
	   @param  target    element - the target input field or division or span */
	_destroyDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		$.removeData(target, PROP_NAME);
		if (nodeName == 'input') {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass(this.markerClassName).
				unbind('focus', this._showDatepicker).
				unbind('keydown', this._doKeyDown).
				unbind('keypress', this._doKeyPress).
				unbind('keyup', this._doKeyUp);
		} else if (nodeName == 'div' || nodeName == 'span')
			$target.removeClass(this.markerClassName).empty();
	},

	/* Enable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_enableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
			target.disabled = false;
			inst.trigger.filter('button').
				each(function() { this.disabled = false; }).end().
				filter('img').css({opacity: '1.0', cursor: ''});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().removeClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	   @param  target    element - the target input field or division or span */
	_disableDatepicker: function(target) {
		var $target = $(target);
		var inst = $.data(target, PROP_NAME);
		if (!$target.hasClass(this.markerClassName)) {
			return;
		}
		var nodeName = target.nodeName.toLowerCase();
		if (nodeName == 'input') {
			target.disabled = true;
			inst.trigger.filter('button').
				each(function() { this.disabled = true; }).end().
				filter('img').css({opacity: '0.5', cursor: 'default'});
		}
		else if (nodeName == 'div' || nodeName == 'span') {
			var inline = $target.children('.' + this._inlineClass);
			inline.children().addClass('ui-state-disabled');
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value == target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	   @param  target    element - the target input field or division or span
	   @return boolean - true if disabled, false if enabled */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] == target)
				return true;
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	   @param  target  element - the target input field or division or span
	   @return  object - the associated instance data
	   @throws  error if a jQuery problem getting data */
	_getInst: function(target) {
		try {
			return $.data(target, PROP_NAME);
		}
		catch (err) {
			throw 'Missing instance data for this datepicker';
		}
	},

	/* Update or retrieve the settings for a date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span
	   @param  name    object - the new settings to update or
	                   string - the name of the setting to change or retrieve,
	                   when retrieving also 'all' for all instance settings or
	                   'defaults' for all global defaults
	   @param  value   any - the new value for the setting
	                   (omit if above is an object or to retrieve a value) */
	_optionDatepicker: function(target, name, value) {
		var inst = this._getInst(target);
		if (arguments.length == 2 && typeof name == 'string') {
			return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) :
				(inst ? (name == 'all' ? $.extend({}, inst.settings) :
				this._get(inst, name)) : null));
		}
		var settings = name || {};
		if (typeof name == 'string') {
			settings = {};
			settings[name] = value;
		}
		if (inst) {
			if (this._curInst == inst) {
				this._hideDatepicker();
			}
			var date = this._getDateDatepicker(target, true);
			var minDate = this._getMinMaxDate(inst, 'min');
			var maxDate = this._getMinMaxDate(inst, 'max');
			extendRemove(inst.settings, settings);
			// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
			if (minDate !== null && settings['dateFormat'] !== undefined && settings['minDate'] === undefined)
				inst.settings.minDate = this._formatDate(inst, minDate);
			if (maxDate !== null && settings['dateFormat'] !== undefined && settings['maxDate'] === undefined)
				inst.settings.maxDate = this._formatDate(inst, maxDate);
			this._attachments($(target), inst);
			this._autoSize(inst);
			this._setDateDatepicker(target, date);
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	   @param  target  element - the target input field or division or span */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	   @param  target   element - the target input field or division or span
	   @param  date     Date - the new date */
	_setDateDatepicker: function(target, date) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	   @param  target     element - the target input field or division or span
	   @param  noDefault  boolean - true if no default date is to be used
	   @return Date - the current date */
	_getDateDatepicker: function(target, noDefault) {
		var inst = this._getInst(target);
		if (inst && !inst.inline)
			this._setDateFromField(inst, noDefault);
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var inst = $.datepicker._getInst(event.target);
		var handled = true;
		var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing)
			switch (event.keyCode) {
				case 9: $.datepicker._hideDatepicker();
						handled = false;
						break; // hide on tab out
				case 13: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' + 
									$.datepicker._currentClass + ')', inst.dpDiv);
						if (sel[0])
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						else
							$.datepicker._hideDatepicker();
						return false; // don't submit the form
						break; // select the value on enter
				case 27: $.datepicker._hideDatepicker();
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, 'stepBigMonths') :
							-$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, 'stepBigMonths') :
							+$.datepicker._get(inst, 'stepMonths')), 'M');
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									-$.datepicker._get(inst, 'stepBigMonths') :
									-$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
									+$.datepicker._get(inst, 'stepBigMonths') :
									+$.datepicker._get(inst, 'stepMonths')), 'M');
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		else {
			handled = false;
		}
		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var inst = $.datepicker._getInst(event.target);
		if ($.datepicker._get(inst, 'constrainInput')) {
			var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
			var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
			return event.ctrlKey || event.metaKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Synchronise manual entry and field/alternate field. */
	_doKeyUp: function(event) {
		var inst = $.datepicker._getInst(event.target);
		if (inst.input.val() != inst.lastVal) {
			try {
				var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
					(inst.input ? inst.input.val() : null),
					$.datepicker._getFormatConfig(inst));
				if (date) { // only if valid
					$.datepicker._setDateFromField(inst);
					$.datepicker._updateAlternate(inst);
					$.datepicker._updateDatepicker(inst);
				}
			}
			catch (event) {
				$.datepicker.log(event);
			}
		}
		return true;
	},

	/* Pop-up the date picker for a given input field.
	   @param  input  element - the input field attached to the date picker or
	                  event - if triggered by focus */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
			input = $('input', input.parentNode)[0];
		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
			return;
		var inst = $.datepicker._getInst(input);
		if ($.datepicker._curInst && $.datepicker._curInst != inst) {
			$.datepicker._curInst.dpDiv.stop(true, true);
		}
		var beforeShow = $.datepicker._get(inst, 'beforeShow');
		extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
		inst.lastVal = null;
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);
		if ($.datepicker._inDialog) // hide cursor
			input.value = '';
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}
		var isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css('position') == 'fixed';
			return !isFixed;
		});
		if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
			$.datepicker._pos[0] -= document.documentElement.scrollLeft;
			$.datepicker._pos[1] -= document.documentElement.scrollTop;
		}
		var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		//to avoid flashes on Firefox
		inst.dpDiv.empty();
		// determine sizing offscreen
		inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
			left: offset.left + 'px', top: offset.top + 'px'});
		if (!inst.inline) {
			var showAnim = $.datepicker._get(inst, 'showAnim');
			var duration = $.datepicker._get(inst, 'duration');
			var postProcess = function() {
				$.datepicker._datepickerShowing = true;
				var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only
				if( !! cover.length ){
					var borders = $.datepicker._getBorders(inst.dpDiv);
					cover.css({left: -borders[0], top: -borders[1],
						width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()});
				}
			};
			inst.dpDiv.zIndex($(input).zIndex()+1);
			if ($.effects && $.effects[showAnim])
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
			else
				inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess);
			if (!showAnim || !duration)
				postProcess();
			if (inst.input.is(':visible') && !inst.input.is(':disabled'))
				inst.input.focus();
			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		var self = this;
		var borders = $.datepicker._getBorders(inst.dpDiv);
		inst.dpDiv.empty().append(this._generateHTML(inst));
		var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only
		if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6
			cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()})
		}
		inst.dpDiv.find('button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a')
				.bind('mouseout', function(){
					$(this).removeClass('ui-state-hover');
					if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
					if(this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
				})
				.bind('mouseover', function(){
					if (!self._isDisabledDatepicker( inst.inline ? inst.dpDiv.parent()[0] : inst.input[0])) {
						$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
						$(this).addClass('ui-state-hover');
						if(this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
						if(this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
					}
				})
			.end()
			.find('.' + this._dayOverClass + ' a')
				.trigger('mouseover')
			.end();
		var numMonths = this._getNumberOfMonths(inst);
		var cols = numMonths[1];
		var width = 17;
		if (cols > 1)
			inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
		else
			inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
		inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
			'Class']('ui-datepicker-multi');
		inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
			'Class']('ui-datepicker-rtl');
		if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input &&
				// #6694 - don't focus the input if it's already focused
				// this breaks the change event in IE
				inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement)
			inst.input.focus();
		// deffered render of the years select (to avoid flashes on Firefox) 
		if( inst.yearshtml ){
			var origyearshtml = inst.yearshtml;
			setTimeout(function(){
				//assure that inst.yearshtml didn't change.
				if( origyearshtml === inst.yearshtml ){
					inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml);
				}
				origyearshtml = inst.yearshtml = null;
			}, 0);
		}
	},

	/* Retrieve the size of left and top borders for an element.
	   @param  elem  (jQuery object) the element of interest
	   @return  (number[2]) the left and top borders */
	_getBorders: function(elem) {
		var convert = function(value) {
			return {thin: 1, medium: 2, thick: 3}[value] || value;
		};
		return [parseFloat(convert(elem.css('border-left-width'))),
			parseFloat(convert(elem.css('border-top-width')))];
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth();
		var dpHeight = inst.dpDiv.outerHeight();
		var inputWidth = inst.input ? inst.input.outerWidth() : 0;
		var inputHeight = inst.input ? inst.input.outerHeight() : 0;
		var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft();
		var viewHeight = document.documentElement.clientHeight + $(document).scrollTop();

		offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
			Math.abs(offset.left + dpWidth - viewWidth) : 0);
		offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
			Math.abs(dpHeight + inputHeight) : 0);

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
		var inst = this._getInst(obj);
		var isRTL = this._get(inst, 'isRTL');
        while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) {
            obj = obj[isRTL ? 'previousSibling' : 'nextSibling'];
        }
        var position = $(obj).offset();
	    return [position.left, position.top];
	},

	/* Hide the date picker from view.
	   @param  input  element - the input field attached to the date picker */
	_hideDatepicker: function(input) {
		var inst = this._curInst;
		if (!inst || (input && inst != $.data(input, PROP_NAME)))
			return;
		if (this._datepickerShowing) {
			var showAnim = this._get(inst, 'showAnim');
			var duration = this._get(inst, 'duration');
			var postProcess = function() {
				$.datepicker._tidyDialog(inst);
				this._curInst = null;
			};
			if ($.effects && $.effects[showAnim])
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
			else
				inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' :
					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
			if (!showAnim)
				postProcess();
			var onClose = this._get(inst, 'onClose');
			if (onClose)
				onClose.apply((inst.input ? inst.input[0] : null),
					[(inst.input ? inst.input.val() : ''), inst]);  // trigger custom callback
			this._datepickerShowing = false;
			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
				if ($.blockUI) {
					$.unblockUI();
					$('body').append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst)
			return;
		var $target = $(event.target);
		if ($target[0].id != $.datepicker._mainDivId &&
				$target.parents('#' + $.datepicker._mainDivId).length == 0 &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.hasClass($.datepicker._triggerClass) &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI))
			$.datepicker._hideDatepicker();
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		}
		else {
			var date = new Date();
			inst.selectedDay = date.getDate();
			inst.drawMonth = inst.selectedMonth = date.getMonth();
			inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		inst._selectingMonthYear = false;
		inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
		inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
			parseInt(select.options[select.selectedIndex].value,10);
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Restore input focus after not changing month/year. */
	_clickMonthYear: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		if (inst.input && inst._selectingMonthYear) {
			setTimeout(function() {
				inst.input.focus();
			}, 0);
		}
		inst._selectingMonthYear = !inst._selectingMonthYear;
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var target = $(id);
		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}
		var inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $('a', td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		this._selectDate(target, '');
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var target = $(id);
		var inst = this._getInst(target[0]);
		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input)
			inst.input.val(dateStr);
		this._updateAlternate(inst);
		var onSelect = this._get(inst, 'onSelect');
		if (onSelect)
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		else if (inst.input)
			inst.input.trigger('change'); // fire the change event
		if (inst.inline)
			this._updateDatepicker(inst);
		else {
			this._hideDatepicker();
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) != 'object')
				inst.input.focus(); // restore focus
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altField = this._get(inst, 'altField');
		if (altField) { // update alternate field too
			var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
			var date = this._getDate(inst);
			var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	   @param  date  Date - the date to customise
	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ''];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	   @param  date  Date - the date to get the week for
	   @return  number - the number of the week within the year that contains this date */
	iso8601Week: function(date) {
		var checkDate = new Date(date.getTime());
		// Find Thursday of this week starting on Monday
		checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
		var time = checkDate.getTime();
		checkDate.setMonth(0); // Compare with Jan 1
		checkDate.setDate(1);
		return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
	},

	/* Parse a string value into a date object.
	   See formatDate below for the possible formats.

	   @param  format    string - the expected format of the date
	   @param  value     string - the date in the above format
	   @param  settings  Object - attributes include:
	                     shortYearCutoff  number - the cutoff year for determining the century (optional)
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  Date - the extracted date value or null if value is blank */
	parseDate: function (format, value, settings) {
		if (format == null || value == null)
			throw 'Invalid arguments';
		value = (typeof value == 'object' ? value.toString() : value + '');
		if (value == '')
			return null;
		var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
				new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		var year = -1;
		var month = -1;
		var day = -1;
		var doy = -1;
		var literal = false;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Extract a number from the string value
		var getNumber = function(match) {
			var isDoubled = lookAhead(match);
			var size = (match == '@' ? 14 : (match == '!' ? 20 :
				(match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2))));
			var digits = new RegExp('^\\d{1,' + size + '}');
			var num = value.substring(iValue).match(digits);
			if (!num)
				throw 'Missing number at position ' + iValue;
			iValue += num[0].length;
			return parseInt(num[0], 10);
		};
		// Extract a name from the string value and convert to an index
		var getName = function(match, shortNames, longNames) {
			var names = (lookAhead(match) ? longNames : shortNames);
			for (var i = 0; i < names.length; i++) {
				if (value.substr(iValue, names[i].length).toLowerCase() == names[i].toLowerCase()) {
					iValue += names[i].length;
					return i + 1;
				}
			}
			throw 'Unknown name at position ' + iValue;
		};
		// Confirm that a literal character matches the string value
		var checkLiteral = function() {
			if (value.charAt(iValue) != format.charAt(iFormat))
				throw 'Unexpected literal at position ' + iValue;
			iValue++;
		};
		var iValue = 0;
		for (var iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					checkLiteral();
			else
				switch (format.charAt(iFormat)) {
					case 'd':
						day = getNumber('d');
						break;
					case 'D':
						getName('D', dayNamesShort, dayNames);
						break;
					case 'o':
						doy = getNumber('o');
						break;
					case 'm':
						month = getNumber('m');
						break;
					case 'M':
						month = getName('M', monthNamesShort, monthNames);
						break;
					case 'y':
						year = getNumber('y');
						break;
					case '@':
						var date = new Date(getNumber('@'));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case '!':
						var date = new Date((getNumber('!') - this._ticksTo1970) / 10000);
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'"))
							checkLiteral();
						else
							literal = true;
						break;
					default:
						checkLiteral();
				}
		}
		if (year == -1)
			year = new Date().getFullYear();
		else if (year < 100)
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				var dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim)
					break;
				month++;
				day -= dim;
			} while (true);
		}
		var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
			throw 'Invalid date'; // E.g. 31/02/00
		return date;
	},

	/* Standard date formats. */
	ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
	COOKIE: 'D, dd M yy',
	ISO_8601: 'yy-mm-dd',
	RFC_822: 'D, d M y',
	RFC_850: 'DD, dd-M-y',
	RFC_1036: 'D, d M y',
	RFC_1123: 'D, d M yy',
	RFC_2822: 'D, d M yy',
	RSS: 'D, d M y', // RFC 822
	TICKS: '!',
	TIMESTAMP: '@',
	W3C: 'yy-mm-dd', // ISO 8601

	_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
		Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),

	/* Format a date object into a string value.
	   The format can be combinations of the following:
	   d  - day of month (no leading zero)
	   dd - day of month (two digit)
	   o  - day of year (no leading zeros)
	   oo - day of year (three digit)
	   D  - day name short
	   DD - day name long
	   m  - month of year (no leading zero)
	   mm - month of year (two digit)
	   M  - month name short
	   MM - month name long
	   y  - year (two digit)
	   yy - year (four digit)
	   @ - Unix timestamp (ms since 01/01/1970)
	   ! - Windows ticks (100ns since 01/01/0001)
	   '...' - literal text
	   '' - single quote

	   @param  format    string - the desired format of the date
	   @param  date      Date - the date value to format
	   @param  settings  Object - attributes include:
	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
	                     dayNames         string[7] - names of the days from Sunday (optional)
	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
	                     monthNames       string[12] - names of the months (optional)
	   @return  string - the date in the above format */
	formatDate: function (format, date, settings) {
		if (!date)
			return '';
		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		// Format a number, with leading zero if necessary
		var formatNumber = function(match, value, len) {
			var num = '' + value;
			if (lookAhead(match))
				while (num.length < len)
					num = '0' + num;
			return num;
		};
		// Format a name, short or long as requested
		var formatName = function(match, value, shortNames, longNames) {
			return (lookAhead(match) ? longNames[value] : shortNames[value]);
		};
		var output = '';
		var literal = false;
		if (date)
			for (var iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal)
					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
						literal = false;
					else
						output += format.charAt(iFormat);
				else
					switch (format.charAt(iFormat)) {
						case 'd':
							output += formatNumber('d', date.getDate(), 2);
							break;
						case 'D':
							output += formatName('D', date.getDay(), dayNamesShort, dayNames);
							break;
						case 'o':
							output += formatNumber('o',
								(date.getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000, 3);
							break;
						case 'm':
							output += formatNumber('m', date.getMonth() + 1, 2);
							break;
						case 'M':
							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
							break;
						case 'y':
							output += (lookAhead('y') ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
							break;
						case '@':
							output += date.getTime();
							break;
						case '!':
							output += date.getTime() * 10000 + this._ticksTo1970;
							break;
						case "'":
							if (lookAhead("'"))
								output += "'";
							else
								literal = true;
							break;
						default:
							output += format.charAt(iFormat);
					}
			}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var chars = '';
		var literal = false;
		// Check whether a format character is doubled
		var lookAhead = function(match) {
			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
			if (matches)
				iFormat++;
			return matches;
		};
		for (var iFormat = 0; iFormat < format.length; iFormat++)
			if (literal)
				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
					literal = false;
				else
					chars += format.charAt(iFormat);
			else
				switch (format.charAt(iFormat)) {
					case 'd': case 'm': case 'y': case '@':
						chars += '0123456789';
						break;
					case 'D': case 'M':
						return null; // Accept anything
					case "'":
						if (lookAhead("'"))
							chars += "'";
						else
							literal = true;
						break;
					default:
						chars += format.charAt(iFormat);
				}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst, noDefault) {
		if (inst.input.val() == inst.lastVal) {
			return;
		}
		var dateFormat = this._get(inst, 'dateFormat');
		var dates = inst.lastVal = inst.input ? inst.input.val() : null;
		var date, defaultDate;
		date = defaultDate = this._getDefaultDate(inst);
		var settings = this._getFormatConfig(inst);
		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			this.log(event);
			dates = (noDefault ? '' : dates);
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		return this._restrictMinMax(inst,
			this._determineDate(inst, this._get(inst, 'defaultDate'), new Date()));
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(inst, date, defaultDate) {
		var offsetNumeric = function(offset) {
			var date = new Date();
			date.setDate(date.getDate() + offset);
			return date;
		};
		var offsetString = function(offset) {
			try {
				return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
					offset, $.datepicker._getFormatConfig(inst));
			}
			catch (e) {
				// Ignore
			}
			var date = (offset.toLowerCase().match(/^c/) ?
				$.datepicker._getDate(inst) : null) || new Date();
			var year = date.getFullYear();
			var month = date.getMonth();
			var day = date.getDate();
			var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
			var matches = pattern.exec(offset);
			while (matches) {
				switch (matches[2] || 'd') {
					case 'd' : case 'D' :
						day += parseInt(matches[1],10); break;
					case 'w' : case 'W' :
						day += parseInt(matches[1],10) * 7; break;
					case 'm' : case 'M' :
						month += parseInt(matches[1],10);
						day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
						break;
					case 'y': case 'Y' :
						year += parseInt(matches[1],10);
						day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
						break;
				}
				matches = pattern.exec(offset);
			}
			return new Date(year, month, day);
		};
		var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) :
			(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
		newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate);
		if (newDate) {
			newDate.setHours(0);
			newDate.setMinutes(0);
			newDate.setSeconds(0);
			newDate.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(newDate);
	},

	/* Handle switch to/from daylight saving.
	   Hours may be non-zero on daylight saving cut-over:
	   > 12 when midnight changeover, but then cannot generate
	   midnight datetime, so jump to 1AM, otherwise reset.
	   @param  date  (Date) the date to check
	   @return  (Date) the corrected date */
	_daylightSavingAdjust: function(date) {
		if (!date) return null;
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, noChange) {
		var clear = !date;
		var origMonth = inst.selectedMonth;
		var origYear = inst.selectedYear;
		var newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
		inst.selectedDay = inst.currentDay = newDate.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
		if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange)
			this._notifyChange(inst);
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? '' : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var today = new Date();
		today = this._daylightSavingAdjust(
			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
		var isRTL = this._get(inst, 'isRTL');
		var showButtonPanel = this._get(inst, 'showButtonPanel');
		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
		var numMonths = this._getNumberOfMonths(inst);
		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
		var stepMonths = this._get(inst, 'stepMonths');
		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		var minDate = this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		var drawMonth = inst.drawMonth - showCurrentAtPos;
		var drawYear = inst.drawYear;
		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;
		var prevText = this._get(inst, 'prevText');
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));
		var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_' + dpuuid +
			'.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
			' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
		var nextText = this._get(inst, 'nextText');
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));
		var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_' + dpuuid +
			'.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
			' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
		var currentText = this._get(inst, 'currentText');
		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
		var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
			'.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
		var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
			(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
			'.datepicker._gotoToday(\'#' + inst.id + '\');"' +
			'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
		var firstDay = parseInt(this._get(inst, 'firstDay'),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);
		var showWeek = this._get(inst, 'showWeek');
		var dayNames = this._get(inst, 'dayNames');
		var dayNamesShort = this._get(inst, 'dayNamesShort');
		var dayNamesMin = this._get(inst, 'dayNamesMin');
		var monthNames = this._get(inst, 'monthNames');
		var monthNamesShort = this._get(inst, 'monthNamesShort');
		var beforeShowDay = this._get(inst, 'beforeShowDay');
		var showOtherMonths = this._get(inst, 'showOtherMonths');
		var selectOtherMonths = this._get(inst, 'selectOtherMonths');
		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
		var defaultDate = this._getDefaultDate(inst);
		var html = '';
		for (var row = 0; row < numMonths[0]; row++) {
			var group = '';
			for (var col = 0; col < numMonths[1]; col++) {
				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				var cornerClass = ' ui-corner-all';
				var calender = '';
				if (isMultiMonth) {
					calender += '<div class="ui-datepicker-group';
					if (numMonths[1] > 1)
						switch (col) {
							case 0: calender += ' ui-datepicker-group-first';
								cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
							case numMonths[1]-1: calender += ' ui-datepicker-group-last';
								cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
							default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break;
						}
					calender += '">';
				}
				calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
					(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
					(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					'</div><table class="ui-datepicker-calendar"><thead>' +
					'<tr>';
				var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : '');
				for (var dow = 0; dow < 7; dow++) { // days of the week
					var day = (dow + firstDay) % 7;
					thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
						'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
				}
				calender += thead + '</tr></thead><tbody>';
				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				var numRows = (isMultiMonth ? 6 : Math.ceil((leadDays + daysInMonth) / 7)); // calculate the number of rows to generate
				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += '<tr>';
					var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' +
						this._get(inst, 'calculateWeek')(printDate) + '</td>');
					for (var dow = 0; dow < 7; dow++) { // create date picker days
						var daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
						var otherMonth = (printDate.getMonth() != drawMonth);
						var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += '<td class="' +
							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							' ' + this._dayOverClass : '') + // highlight selected day
							(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
							(printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day
							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
							(unselectable ? '' : ' onclick="DP_jQuery_' + dpuuid + '.datepicker._selectDay(\'#' +
							inst.id + '\',' + printDate.getMonth() + ',' + printDate.getFullYear() + ', this);return false;"') + '>' + // actions
							(otherMonth && !showOtherMonths ? '&#xa0;' : // display for other months
							(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
							(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
							(printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day
							(otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months
							'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + '</tr>';
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += '</tbody></table>' + (isMultiMonth ? '</div>' + 
							((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
				group += calender;
			}
			html += group;
		}
		html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
			'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			secondary, monthNames, monthNamesShort) {
		var changeMonth = this._get(inst, 'changeMonth');
		var changeYear = this._get(inst, 'changeYear');
		var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
		var html = '<div class="ui-datepicker-title">';
		var monthHtml = '';
		// month selection
		if (secondary || !changeMonth)
			monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>';
		else {
			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
			monthHtml += '<select class="ui-datepicker-month" ' +
				'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
				'onclick="DP_jQuery_' + dpuuid + '.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
			 	'>';
			for (var month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) &&
						(!inMaxYear || month <= maxDate.getMonth()))
					monthHtml += '<option value="' + month + '"' +
						(month == drawMonth ? ' selected="selected"' : '') +
						'>' + monthNamesShort[month] + '</option>';
			}
			monthHtml += '</select>';
		}
		if (!showMonthAfterYear)
			html += monthHtml + (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '');
		// year selection
		if ( !inst.yearshtml ) {
			inst.yearshtml = '';
			if (secondary || !changeYear)
				html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
			else {
				// determine range of years to display
				var years = this._get(inst, 'yearRange').split(':');
				var thisYear = new Date().getFullYear();
				var determineYear = function(value) {
					var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) :
						(value.match(/[+-].*/) ? thisYear + parseInt(value, 10) :
						parseInt(value, 10)));
					return (isNaN(year) ? thisYear : year);
				};
				var year = determineYear(years[0]);
				var endYear = Math.max(year, determineYear(years[1] || ''));
				year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
				endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
				inst.yearshtml += '<select class="ui-datepicker-year" ' +
					'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
					'onclick="DP_jQuery_' + dpuuid + '.datepicker._clickMonthYear(\'#' + inst.id + '\');"' +
					'>';
				for (; year <= endYear; year++) {
					inst.yearshtml += '<option value="' + year + '"' +
						(year == drawYear ? ' selected="selected"' : '') +
						'>' + year + '</option>';
				}
				inst.yearshtml += '</select>';
				//when showing there is no need for later update
				if( ! $.browser.mozilla ){
					html += inst.yearshtml;
					inst.yearshtml = null;
				} else {
					// will be replaced later with inst.yearshtml
					html += '<select class="ui-datepicker-year"><option value="' + drawYear + '" selected="selected">' + drawYear + '</option></select>';
				}
			}
		}
		html += this._get(inst, 'yearSuffix');
		if (showMonthAfterYear)
			html += (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '') + monthHtml;
		html += '</div>'; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period == 'Y' ? offset : 0);
		var month = inst.drawMonth + (period == 'M' ? offset : 0);
		var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
			(period == 'D' ? offset : 0);
		var date = this._restrictMinMax(inst,
			this._daylightSavingAdjust(new Date(year, month, day)));
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period == 'M' || period == 'Y')
			this._notifyChange(inst);
	},

	/* Ensure a date is within any min/max bounds. */
	_restrictMinMax: function(inst, date) {
		var minDate = this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		var newDate = (minDate && date < minDate ? minDate : date);
		newDate = (maxDate && newDate > maxDate ? maxDate : newDate);
		return newDate;
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, 'onChangeMonthYear');
		if (onChange)
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, 'numberOfMonths');
		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set. */
	_getMinMaxDate: function(inst, minMax) {
		return this._determineDate(inst, this._get(inst, minMax + 'Date'), null);
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst);
		var date = this._daylightSavingAdjust(new Date(curYear,
			curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
		if (offset < 0)
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		var minDate = this._getMinMaxDate(inst, 'min');
		var maxDate = this._getMinMaxDate(inst, 'max');
		return ((!minDate || date.getTime() >= minDate.getTime()) &&
			(!maxDate || date.getTime() <= maxDate.getTime()));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, 'shortYearCutoff');
		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
			monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day == 'object' ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
	}
});

/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props)
		if (props[name] == null || props[name] == undefined)
			target[name] = props[name];
	return target;
};

/* Determine whether an object is an array. */
function isArray(a) {
	return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
		(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
                    Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){
	
	/* Verify an empty collection wasn't passed - Fixes #6976 */
	if ( !this.length ) {
		return this;
	}
	
	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick).
			find('body').append($.datepicker.dpDiv);
		$.datepicker.initialized = true;
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget'))
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
		return $.datepicker['_' + options + 'Datepicker'].
			apply($.datepicker, [this[0]].concat(otherArgs));
	return this.each(function() {
		typeof options == 'string' ?
			$.datepicker['_' + options + 'Datepicker'].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.8.12";

// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window['DP_jQuery_' + dpuuid] = $;

})(jQuery);
/*
 * jQuery UI Dialog 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *  jquery.ui.button.js
 *	jquery.ui.draggable.js
 *	jquery.ui.mouse.js
 *	jquery.ui.position.js
 *	jquery.ui.resizable.js
 */
(function( $, undefined ) {

var uiDialogClasses =
		'ui-dialog ' +
		'ui-widget ' +
		'ui-widget-content ' +
		'ui-corner-all ',
	sizeRelatedOptions = {
		buttons: true,
		height: true,
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true,
		width: true
	},
	resizableRelatedOptions = {
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true
	},
	// support for jQuery 1.3.2 - handle common attrFn methods for dialog
	attrFn = $.attrFn || {
		val: true,
		css: true,
		html: true,
		text: true,
		data: true,
		width: true,
		height: true,
		offset: true,
		click: true
	};

$.widget("ui.dialog", {
	options: {
		autoOpen: true,
		buttons: {},
		closeOnEscape: true,
		closeText: 'close',
		dialogClass: '',
		draggable: true,
		hide: null,
		height: 'auto',
		maxHeight: false,
		maxWidth: false,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: {
			my: 'center',
			at: 'center',
			collision: 'fit',
			// ensure that the titlebar is never outside the document
			using: function(pos) {
				var topOffset = $(this).css(pos).offset().top;
				if (topOffset < 0) {
					$(this).css('top', pos.top - topOffset);
				}
			}
		},
		resizable: true,
		show: null,
		stack: true,
		title: '',
		width: 300,
		zIndex: 1000
	},

	_create: function() {
		this.originalTitle = this.element.attr('title');
		// #5742 - .attr() might return a DOMElement
		if ( typeof this.originalTitle !== "string" ) {
			this.originalTitle = "";
		}

		this.options.title = this.options.title || this.originalTitle;
		var self = this,
			options = self.options,

			title = options.title || '&#160;',
			titleId = $.ui.dialog.getTitleId(self.element),

			uiDialog = (self.uiDialog = $('<div></div>'))
				.appendTo(document.body)
				.hide()
				.addClass(uiDialogClasses + options.dialogClass)
				.css({
					zIndex: options.zIndex
				})
				// setting tabIndex makes the div focusable
				// setting outline to 0 prevents a border on focus in Mozilla
				.attr('tabIndex', -1).css('outline', 0).keydown(function(event) {
					if (options.closeOnEscape && event.keyCode &&
						event.keyCode === $.ui.keyCode.ESCAPE) {
						
						self.close(event);
						event.preventDefault();
					}
				})
				.attr({
					role: 'dialog',
					'aria-labelledby': titleId
				})
				.mousedown(function(event) {
					self.moveToTop(false, event);
				}),

			uiDialogContent = self.element
				.show()
				.removeAttr('title')
				.addClass(
					'ui-dialog-content ' +
					'ui-widget-content')
				.appendTo(uiDialog),

			uiDialogTitlebar = (self.uiDialogTitlebar = $('<div></div>'))
				.addClass(
					'ui-dialog-titlebar ' +
					'ui-widget-header ' +
					'ui-corner-top ' +
					'ui-helper-clearfix'
				)
				.prependTo(uiDialog),

			uiDialogTitlebarClose = $('<a href="#"></a>')
				.addClass(
					'ui-dialog-titlebar-close ' +
					'ui-corner-all'
				)
				.attr('role', 'button')
				.hover(
					function() {
						uiDialogTitlebarClose.addClass('ui-state-hover');
					},
					function() {
						uiDialogTitlebarClose.removeClass('ui-state-hover');
					}
				)
				.focus(function() {
					uiDialogTitlebarClose.addClass('ui-state-focus');
				})
				.blur(function() {
					uiDialogTitlebarClose.removeClass('ui-state-focus');
				})
				.click(function(event) {
					self.close(event);
					return false;
				})
				.appendTo(uiDialogTitlebar),

			uiDialogTitlebarCloseText = (self.uiDialogTitlebarCloseText = $('<span></span>'))
				.addClass(
					'ui-icon ' +
					'ui-icon-closethick'
				)
				.text(options.closeText)
				.appendTo(uiDialogTitlebarClose),

			uiDialogTitle = $('<span></span>')
				.addClass('ui-dialog-title')
				.attr('id', titleId)
				.html(title)
				.prependTo(uiDialogTitlebar);

		//handling of deprecated beforeclose (vs beforeClose) option
		//Ticket #4669 http://dev.jqueryui.com/ticket/4669
		//TODO: remove in 1.9pre
		if ($.isFunction(options.beforeclose) && !$.isFunction(options.beforeClose)) {
			options.beforeClose = options.beforeclose;
		}

		uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();

		if (options.draggable && $.fn.draggable) {
			self._makeDraggable();
		}
		if (options.resizable && $.fn.resizable) {
			self._makeResizable();
		}

		self._createButtons(options.buttons);
		self._isOpen = false;

		if ($.fn.bgiframe) {
			uiDialog.bgiframe();
		}
	},

	_init: function() {
		if ( this.options.autoOpen ) {
			this.open();
		}
	},

	destroy: function() {
		var self = this;
		
		if (self.overlay) {
			self.overlay.destroy();
		}
		self.uiDialog.hide();
		self.element
			.unbind('.dialog')
			.removeData('dialog')
			.removeClass('ui-dialog-content ui-widget-content')
			.hide().appendTo('body');
		self.uiDialog.remove();

		if (self.originalTitle) {
			self.element.attr('title', self.originalTitle);
		}

		return self;
	},

	widget: function() {
		return this.uiDialog;
	},

	close: function(event) {
		var self = this,
			maxZ, thisZ;
		
		if (false === self._trigger('beforeClose', event)) {
			return;
		}

		if (self.overlay) {
			self.overlay.destroy();
		}
		self.uiDialog.unbind('keypress.ui-dialog');

		self._isOpen = false;

		if (self.options.hide) {
			self.uiDialog.hide(self.options.hide, function() {
				self._trigger('close', event);
			});
		} else {
			self.uiDialog.hide();
			self._trigger('close', event);
		}

		$.ui.dialog.overlay.resize();

		// adjust the maxZ to allow other modal dialogs to continue to work (see #4309)
		if (self.options.modal) {
			maxZ = 0;
			$('.ui-dialog').each(function() {
				if (this !== self.uiDialog[0]) {
					thisZ = $(this).css('z-index');
					if(!isNaN(thisZ)) {
						maxZ = Math.max(maxZ, thisZ);
					}
				}
			});
			$.ui.dialog.maxZ = maxZ;
		}

		return self;
	},

	isOpen: function() {
		return this._isOpen;
	},

	// the force parameter allows us to move modal dialogs to their correct
	// position on open
	moveToTop: function(force, event) {
		var self = this,
			options = self.options,
			saveScroll;

		if ((options.modal && !force) ||
			(!options.stack && !options.modal)) {
			return self._trigger('focus', event);
		}

		if (options.zIndex > $.ui.dialog.maxZ) {
			$.ui.dialog.maxZ = options.zIndex;
		}
		if (self.overlay) {
			$.ui.dialog.maxZ += 1;
			self.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ);
		}

		//Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed.
		//  http://ui.jquery.com/bugs/ticket/3193
		saveScroll = { scrollTop: self.element.attr('scrollTop'), scrollLeft: self.element.attr('scrollLeft') };
		$.ui.dialog.maxZ += 1;
		self.uiDialog.css('z-index', $.ui.dialog.maxZ);
		self.element.attr(saveScroll);
		self._trigger('focus', event);

		return self;
	},

	open: function() {
		if (this._isOpen) { return; }

		var self = this,
			options = self.options,
			uiDialog = self.uiDialog;

		self.overlay = options.modal ? new $.ui.dialog.overlay(self) : null;
		self._size();
		self._position(options.position);
		uiDialog.show(options.show);
		self.moveToTop(true);

		// prevent tabbing out of modal dialogs
		if (options.modal) {
			uiDialog.bind('keypress.ui-dialog', function(event) {
				if (event.keyCode !== $.ui.keyCode.TAB) {
					return;
				}

				var tabbables = $(':tabbable', this),
					first = tabbables.filter(':first'),
					last  = tabbables.filter(':last');

				if (event.target === last[0] && !event.shiftKey) {
					first.focus(1);
					return false;
				} else if (event.target === first[0] && event.shiftKey) {
					last.focus(1);
					return false;
				}
			});
		}

		// set focus to the first tabbable element in the content area or the first button
		// if there are no tabbable elements, set focus on the dialog itself
		$(self.element.find(':tabbable').get().concat(
			uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat(
				uiDialog.get()))).eq(0).focus();

		self._isOpen = true;
		self._trigger('open');

		return self;
	},

	_createButtons: function(buttons) {
		var self = this,
			hasButtons = false,
			uiDialogButtonPane = $('<div></div>')
				.addClass(
					'ui-dialog-buttonpane ' +
					'ui-widget-content ' +
					'ui-helper-clearfix'
				),
			uiButtonSet = $( "<div></div>" )
				.addClass( "ui-dialog-buttonset" )
				.appendTo( uiDialogButtonPane );

		// if we already have a button pane, remove it
		self.uiDialog.find('.ui-dialog-buttonpane').remove();

		if (typeof buttons === 'object' && buttons !== null) {
			$.each(buttons, function() {
				return !(hasButtons = true);
			});
		}
		if (hasButtons) {
			$.each(buttons, function(name, props) {
				props = $.isFunction( props ) ?
					{ click: props, text: name } :
					props;
				var button = $('<button type="button"></button>')
					.click(function() {
						props.click.apply(self.element[0], arguments);
					})
					.appendTo(uiButtonSet);
				// can't use .attr( props, true ) with jQuery 1.3.2.
				$.each( props, function( key, value ) {
					if ( key === "click" ) {
						return;
					}
					if ( key in attrFn ) {
						button[ key ]( value );
					} else {
						button.attr( key, value );
					}
				});
				if ($.fn.button) {
					button.button();
				}
			});
			uiDialogButtonPane.appendTo(self.uiDialog);
		}
	},

	_makeDraggable: function() {
		var self = this,
			options = self.options,
			doc = $(document),
			heightBeforeDrag;

		function filteredUi(ui) {
			return {
				position: ui.position,
				offset: ui.offset
			};
		}

		self.uiDialog.draggable({
			cancel: '.ui-dialog-content, .ui-dialog-titlebar-close',
			handle: '.ui-dialog-titlebar',
			containment: 'document',
			start: function(event, ui) {
				heightBeforeDrag = options.height === "auto" ? "auto" : $(this).height();
				$(this).height($(this).height()).addClass("ui-dialog-dragging");
				self._trigger('dragStart', event, filteredUi(ui));
			},
			drag: function(event, ui) {
				self._trigger('drag', event, filteredUi(ui));
			},
			stop: function(event, ui) {
				options.position = [ui.position.left - doc.scrollLeft(),
					ui.position.top - doc.scrollTop()];
				$(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag);
				self._trigger('dragStop', event, filteredUi(ui));
				$.ui.dialog.overlay.resize();
			}
		});
	},

	_makeResizable: function(handles) {
		handles = (handles === undefined ? this.options.resizable : handles);
		var self = this,
			options = self.options,
			// .ui-resizable has position: relative defined in the stylesheet
			// but dialogs have to use absolute or fixed positioning
			position = self.uiDialog.css('position'),
			resizeHandles = (typeof handles === 'string' ?
				handles	:
				'n,e,s,w,se,sw,ne,nw'
			);

		function filteredUi(ui) {
			return {
				originalPosition: ui.originalPosition,
				originalSize: ui.originalSize,
				position: ui.position,
				size: ui.size
			};
		}

		self.uiDialog.resizable({
			cancel: '.ui-dialog-content',
			containment: 'document',
			alsoResize: self.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: self._minHeight(),
			handles: resizeHandles,
			start: function(event, ui) {
				$(this).addClass("ui-dialog-resizing");
				self._trigger('resizeStart', event, filteredUi(ui));
			},
			resize: function(event, ui) {
				self._trigger('resize', event, filteredUi(ui));
			},
			stop: function(event, ui) {
				$(this).removeClass("ui-dialog-resizing");
				options.height = $(this).height();
				options.width = $(this).width();
				self._trigger('resizeStop', event, filteredUi(ui));
				$.ui.dialog.overlay.resize();
			}
		})
		.css('position', position)
		.find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se');
	},

	_minHeight: function() {
		var options = this.options;

		if (options.height === 'auto') {
			return options.minHeight;
		} else {
			return Math.min(options.minHeight, options.height);
		}
	},

	_position: function(position) {
		var myAt = [],
			offset = [0, 0],
			isVisible;

		if (position) {
			// deep extending converts arrays to objects in jQuery <= 1.3.2 :-(
	//		if (typeof position == 'string' || $.isArray(position)) {
	//			myAt = $.isArray(position) ? position : position.split(' ');

			if (typeof position === 'string' || (typeof position === 'object' && '0' in position)) {
				myAt = position.split ? position.split(' ') : [position[0], position[1]];
				if (myAt.length === 1) {
					myAt[1] = myAt[0];
				}

				$.each(['left', 'top'], function(i, offsetPosition) {
					if (+myAt[i] === myAt[i]) {
						offset[i] = myAt[i];
						myAt[i] = offsetPosition;
					}
				});

				position = {
					my: myAt.join(" "),
					at: myAt.join(" "),
					offset: offset.join(" ")
				};
			} 

			position = $.extend({}, $.ui.dialog.prototype.options.position, position);
		} else {
			position = $.ui.dialog.prototype.options.position;
		}

		// need to show the dialog to get the actual offset in the position plugin
		isVisible = this.uiDialog.is(':visible');
		if (!isVisible) {
			this.uiDialog.show();
		}
		this.uiDialog
			// workaround for jQuery bug #5781 http://dev.jquery.com/ticket/5781
			.css({ top: 0, left: 0 })
			.position($.extend({ of: window }, position));
		if (!isVisible) {
			this.uiDialog.hide();
		}
	},

	_setOptions: function( options ) {
		var self = this,
			resizableOptions = {},
			resize = false;

		$.each( options, function( key, value ) {
			self._setOption( key, value );
			
			if ( key in sizeRelatedOptions ) {
				resize = true;
			}
			if ( key in resizableRelatedOptions ) {
				resizableOptions[ key ] = value;
			}
		});

		if ( resize ) {
			this._size();
		}
		if ( this.uiDialog.is( ":data(resizable)" ) ) {
			this.uiDialog.resizable( "option", resizableOptions );
		}
	},

	_setOption: function(key, value){
		var self = this,
			uiDialog = self.uiDialog;

		switch (key) {
			//handling of deprecated beforeclose (vs beforeClose) option
			//Ticket #4669 http://dev.jqueryui.com/ticket/4669
			//TODO: remove in 1.9pre
			case "beforeclose":
				key = "beforeClose";
				break;
			case "buttons":
				self._createButtons(value);
				break;
			case "closeText":
				// ensure that we always pass a string
				self.uiDialogTitlebarCloseText.text("" + value);
				break;
			case "dialogClass":
				uiDialog
					.removeClass(self.options.dialogClass)
					.addClass(uiDialogClasses + value);
				break;
			case "disabled":
				if (value) {
					uiDialog.addClass('ui-dialog-disabled');
				} else {
					uiDialog.removeClass('ui-dialog-disabled');
				}
				break;
			case "draggable":
				var isDraggable = uiDialog.is( ":data(draggable)" );
				if ( isDraggable && !value ) {
					uiDialog.draggable( "destroy" );
				}
				
				if ( !isDraggable && value ) {
					self._makeDraggable();
				}
				break;
			case "position":
				self._position(value);
				break;
			case "resizable":
				// currently resizable, becoming non-resizable
				var isResizable = uiDialog.is( ":data(resizable)" );
				if (isResizable && !value) {
					uiDialog.resizable('destroy');
				}

				// currently resizable, changing handles
				if (isResizable && typeof value === 'string') {
					uiDialog.resizable('option', 'handles', value);
				}

				// currently non-resizable, becoming resizable
				if (!isResizable && value !== false) {
					self._makeResizable(value);
				}
				break;
			case "title":
				// convert whatever was passed in o a string, for html() to not throw up
				$(".ui-dialog-title", self.uiDialogTitlebar).html("" + (value || '&#160;'));
				break;
		}

		$.Widget.prototype._setOption.apply(self, arguments);
	},

	_size: function() {
		/* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
		 * divs will both have width and height set, so we need to reset them
		 */
		var options = this.options,
			nonContentHeight,
			minContentHeight,
			isVisible = this.uiDialog.is( ":visible" );

		// reset content sizing
		this.element.show().css({
			width: 'auto',
			minHeight: 0,
			height: 0
		});

		if (options.minWidth > options.width) {
			options.width = options.minWidth;
		}

		// reset wrapper sizing
		// determine the height of all the non-content elements
		nonContentHeight = this.uiDialog.css({
				height: 'auto',
				width: options.width
			})
			.height();
		minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
		
		if ( options.height === "auto" ) {
			// only needed for IE6 support
			if ( $.support.minHeight ) {
				this.element.css({
					minHeight: minContentHeight,
					height: "auto"
				});
			} else {
				this.uiDialog.show();
				var autoHeight = this.element.css( "height", "auto" ).height();
				if ( !isVisible ) {
					this.uiDialog.hide();
				}
				this.element.height( Math.max( autoHeight, minContentHeight ) );
			}
		} else {
			this.element.height( Math.max( options.height - nonContentHeight, 0 ) );
		}

		if (this.uiDialog.is(':data(resizable)')) {
			this.uiDialog.resizable('option', 'minHeight', this._minHeight());
		}
	}
});

$.extend($.ui.dialog, {
	version: "1.8.12",

	uuid: 0,
	maxZ: 0,

	getTitleId: function($el) {
		var id = $el.attr('id');
		if (!id) {
			this.uuid += 1;
			id = this.uuid;
		}
		return 'ui-dialog-title-' + id;
	},

	overlay: function(dialog) {
		this.$el = $.ui.dialog.overlay.create(dialog);
	}
});

$.extend($.ui.dialog.overlay, {
	instances: [],
	// reuse old instances due to IE memory leak with alpha transparency (see #5185)
	oldInstances: [],
	maxZ: 0,
	events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
		function(event) { return event + '.dialog-overlay'; }).join(' '),
	create: function(dialog) {
		if (this.instances.length === 0) {
			// prevent use of anchors and inputs
			// we use a setTimeout in case the overlay is created from an
			// event that we're going to be cancelling (see #2804)
			setTimeout(function() {
				// handle $(el).dialog().dialog('close') (see #4065)
				if ($.ui.dialog.overlay.instances.length) {
					$(document).bind($.ui.dialog.overlay.events, function(event) {
						// stop events if the z-index of the target is < the z-index of the overlay
						// we cannot return true when we don't want to cancel the event (#3523)
						if ($(event.target).zIndex() < $.ui.dialog.overlay.maxZ) {
							return false;
						}
					});
				}
			}, 1);

			// allow closing by pressing the escape key
			$(document).bind('keydown.dialog-overlay', function(event) {
				if (dialog.options.closeOnEscape && event.keyCode &&
					event.keyCode === $.ui.keyCode.ESCAPE) {
					
					dialog.close(event);
					event.preventDefault();
				}
			});

			// handle window resize
			$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
		}

		var $el = (this.oldInstances.pop() || $('<div></div>').addClass('ui-widget-overlay'))
			.appendTo(document.body)
			.css({
				width: this.width(),
				height: this.height()
			});

		if ($.fn.bgiframe) {
			$el.bgiframe();
		}

		this.instances.push($el);
		return $el;
	},

	destroy: function($el) {
		var indexOf = $.inArray($el, this.instances);
		if (indexOf != -1){
			this.oldInstances.push(this.instances.splice(indexOf, 1)[0]);
		}

		if (this.instances.length === 0) {
			$([document, window]).unbind('.dialog-overlay');
		}

		$el.remove();
		
		// adjust the maxZ to allow other modal dialogs to continue to work (see #4309)
		var maxZ = 0;
		$.each(this.instances, function() {
			maxZ = Math.max(maxZ, this.css('z-index'));
		});
		this.maxZ = maxZ;
	},

	height: function() {
		var scrollHeight,
			offsetHeight;
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			scrollHeight = Math.max(
				document.documentElement.scrollHeight,
				document.body.scrollHeight
			);
			offsetHeight = Math.max(
				document.documentElement.offsetHeight,
				document.body.offsetHeight
			);

			if (scrollHeight < offsetHeight) {
				return $(window).height() + 'px';
			} else {
				return scrollHeight + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).height() + 'px';
		}
	},

	width: function() {
		var scrollWidth,
			offsetWidth;
		// handle IE 6
		if ($.browser.msie && $.browser.version < 7) {
			scrollWidth = Math.max(
				document.documentElement.scrollWidth,
				document.body.scrollWidth
			);
			offsetWidth = Math.max(
				document.documentElement.offsetWidth,
				document.body.offsetWidth
			);

			if (scrollWidth < offsetWidth) {
				return $(window).width() + 'px';
			} else {
				return scrollWidth + 'px';
			}
		// handle "good" browsers
		} else {
			return $(document).width() + 'px';
		}
	},

	resize: function() {
		/* If the dialog is draggable and the user drags it past the
		 * right edge of the window, the document becomes wider so we
		 * need to stretch the overlay. If the user then drags the
		 * dialog back to the left, the document will become narrower,
		 * so we need to shrink the overlay to the appropriate size.
		 * This is handled by shrinking the overlay before setting it
		 * to the full document size.
		 */
		var $overlays = $([]);
		$.each($.ui.dialog.overlay.instances, function() {
			$overlays = $overlays.add(this);
		});

		$overlays.css({
			width: 0,
			height: 0
		}).css({
			width: $.ui.dialog.overlay.width(),
			height: $.ui.dialog.overlay.height()
		});
	}
});

$.extend($.ui.dialog.overlay.prototype, {
	destroy: function() {
		$.ui.dialog.overlay.destroy(this.$el);
	}
});

}(jQuery));
/*
 * jQuery UI Position 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Position
 */
(function( $, undefined ) {

$.ui = $.ui || {};

var horizontalPositions = /left|center|right/,
	verticalPositions = /top|center|bottom/,
	center = "center",
	_position = $.fn.position,
	_offset = $.fn.offset;

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var target = $( options.of ),
		targetElem = target[0],
		collision = ( options.collision || "flip" ).split( " " ),
		offset = options.offset ? options.offset.split( " " ) : [ 0, 0 ],
		targetWidth,
		targetHeight,
		basePosition;

	if ( targetElem.nodeType === 9 ) {
		targetWidth = target.width();
		targetHeight = target.height();
		basePosition = { top: 0, left: 0 };
	// TODO: use $.isWindow() in 1.9
	} else if ( targetElem.setTimeout ) {
		targetWidth = target.width();
		targetHeight = target.height();
		basePosition = { top: target.scrollTop(), left: target.scrollLeft() };
	} else if ( targetElem.preventDefault ) {
		// force left top to allow flipping
		options.at = "left top";
		targetWidth = targetHeight = 0;
		basePosition = { top: options.of.pageY, left: options.of.pageX };
	} else {
		targetWidth = target.outerWidth();
		targetHeight = target.outerHeight();
		basePosition = target.offset();
	}

	// force my and at to have valid horizontal and veritcal positions
	// if a value is missing or invalid, it will be converted to center 
	$.each( [ "my", "at" ], function() {
		var pos = ( options[this] || "" ).split( " " );
		if ( pos.length === 1) {
			pos = horizontalPositions.test( pos[0] ) ?
				pos.concat( [center] ) :
				verticalPositions.test( pos[0] ) ?
					[ center ].concat( pos ) :
					[ center, center ];
		}
		pos[ 0 ] = horizontalPositions.test( pos[0] ) ? pos[ 0 ] : center;
		pos[ 1 ] = verticalPositions.test( pos[1] ) ? pos[ 1 ] : center;
		options[ this ] = pos;
	});

	// normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	// normalize offset option
	offset[ 0 ] = parseInt( offset[0], 10 ) || 0;
	if ( offset.length === 1 ) {
		offset[ 1 ] = offset[ 0 ];
	}
	offset[ 1 ] = parseInt( offset[1], 10 ) || 0;

	if ( options.at[0] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[0] === center ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[1] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[1] === center ) {
		basePosition.top += targetHeight / 2;
	}

	basePosition.left += offset[ 0 ];
	basePosition.top += offset[ 1 ];

	return this.each(function() {
		var elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseInt( $.curCSS( this, "marginLeft", true ) ) || 0,
			marginTop = parseInt( $.curCSS( this, "marginTop", true ) ) || 0,
			collisionWidth = elemWidth + marginLeft +
				( parseInt( $.curCSS( this, "marginRight", true ) ) || 0 ),
			collisionHeight = elemHeight + marginTop +
				( parseInt( $.curCSS( this, "marginBottom", true ) ) || 0 ),
			position = $.extend( {}, basePosition ),
			collisionPosition;

		if ( options.my[0] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[0] === center ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[1] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[1] === center ) {
			position.top -= elemHeight / 2;
		}

		// prevent fractions (see #5280)
		position.left = Math.round( position.left );
		position.top = Math.round( position.top );

		collisionPosition = {
			left: position.left - marginLeft,
			top: position.top - marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[i] ] ) {
				$.ui.position[ collision[i] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: offset,
					my: options.my,
					at: options.at
				});
			}
		});

		if ( $.fn.bgiframe ) {
			elem.bgiframe();
		}
		elem.offset( $.extend( position, { using: options.using } ) );
	});
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var win = $( window ),
				over = data.collisionPosition.left + data.collisionWidth - win.width() - win.scrollLeft();
			position.left = over > 0 ? position.left - over : Math.max( position.left - data.collisionPosition.left, position.left );
		},
		top: function( position, data ) {
			var win = $( window ),
				over = data.collisionPosition.top + data.collisionHeight - win.height() - win.scrollTop();
			position.top = over > 0 ? position.top - over : Math.max( position.top - data.collisionPosition.top, position.top );
		}
	},

	flip: {
		left: function( position, data ) {
			if ( data.at[0] === center ) {
				return;
			}
			var win = $( window ),
				over = data.collisionPosition.left + data.collisionWidth - win.width() - win.scrollLeft(),
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					-data.targetWidth,
				offset = -2 * data.offset[ 0 ];
			position.left += data.collisionPosition.left < 0 ?
				myOffset + atOffset + offset :
				over > 0 ?
					myOffset + atOffset + offset :
					0;
		},
		top: function( position, data ) {
			if ( data.at[1] === center ) {
				return;
			}
			var win = $( window ),
				over = data.collisionPosition.top + data.collisionHeight - win.height() - win.scrollTop(),
				myOffset = data.my[ 1 ] === "top" ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					-data.targetHeight,
				offset = -2 * data.offset[ 1 ];
			position.top += data.collisionPosition.top < 0 ?
				myOffset + atOffset + offset :
				over > 0 ?
					myOffset + atOffset + offset :
					0;
		}
	}
};

// offset setter from jQuery 1.4
if ( !$.offset.setOffset ) {
	$.offset.setOffset = function( elem, options ) {
		// set position first, in-case top/left are set even on static elem
		if ( /static/.test( $.curCSS( elem, "position" ) ) ) {
			elem.style.position = "relative";
		}
		var curElem   = $( elem ),
			curOffset = curElem.offset(),
			curTop    = parseInt( $.curCSS( elem, "top",  true ), 10 ) || 0,
			curLeft   = parseInt( $.curCSS( elem, "left", true ), 10)  || 0,
			props     = {
				top:  (options.top  - curOffset.top)  + curTop,
				left: (options.left - curOffset.left) + curLeft
			};
		
		if ( 'using' in options ) {
			options.using.call( elem, props );
		} else {
			curElem.css( props );
		}
	};

	$.fn.offset = function( options ) {
		var elem = this[ 0 ];
		if ( !elem || !elem.ownerDocument ) { return null; }
		if ( options ) { 
			return this.each(function() {
				$.offset.setOffset( this, options );
			});
		}
		return _offset.call( this );
	};
}

}( jQuery ));
/*
 * jQuery UI Progressbar 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Progressbar
 *
 * Depends:
 *   jquery.ui.core.js
 *   jquery.ui.widget.js
 */
(function( $, undefined ) {

$.widget( "ui.progressbar", {
	options: {
		value: 0,
		max: 100
	},

	min: 0,

	_create: function() {
		this.element
			.addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
			.attr({
				role: "progressbar",
				"aria-valuemin": this.min,
				"aria-valuemax": this.options.max,
				"aria-valuenow": this._value()
			});

		this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
			.appendTo( this.element );

		this.oldValue = this._value();
		this._refreshValue();
	},

	destroy: function() {
		this.element
			.removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "aria-valuenow" );

		this.valueDiv.remove();

		$.Widget.prototype.destroy.apply( this, arguments );
	},

	value: function( newValue ) {
		if ( newValue === undefined ) {
			return this._value();
		}

		this._setOption( "value", newValue );
		return this;
	},

	_setOption: function( key, value ) {
		if ( key === "value" ) {
			this.options.value = value;
			this._refreshValue();
			if ( this._value() === this.options.max ) {
				this._trigger( "complete" );
			}
		}

		$.Widget.prototype._setOption.apply( this, arguments );
	},

	_value: function() {
		var val = this.options.value;
		// normalize invalid value
		if ( typeof val !== "number" ) {
			val = 0;
		}
		return Math.min( this.options.max, Math.max( this.min, val ) );
	},

	_percentage: function() {
		return 100 * this._value() / this.options.max;
	},

	_refreshValue: function() {
		var value = this.value();
		var percentage = this._percentage();

		if ( this.oldValue !== value ) {
			this.oldValue = value;
			this._trigger( "change" );
		}

		this.valueDiv
			.toggle( value > this.min )
			.toggleClass( "ui-corner-right", value === this.options.max )
			.width( percentage.toFixed(0) + "%" );
		this.element.attr( "aria-valuenow", value );
	}
});

$.extend( $.ui.progressbar, {
	version: "1.8.12"
});

})( jQuery );
/*
 * jQuery UI Slider 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Slider
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.mouse.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

// number of pages in a slider
// (how many times can you page up/down to go through the whole range)
var numPages = 5;

$.widget( "ui.slider", $.ui.mouse, {

	widgetEventPrefix: "slide",

	options: {
		animate: false,
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null
	},

	_create: function() {
		var self = this,
			o = this.options;

		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();

		this.element
			.addClass( "ui-slider" +
				" ui-slider-" + this.orientation +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all" );
		
		if ( o.disabled ) {
			this.element.addClass( "ui-slider-disabled ui-disabled" );
		}

		this.range = $([]);

		if ( o.range ) {
			if ( o.range === true ) {
				this.range = $( "<div></div>" );
				if ( !o.values ) {
					o.values = [ this._valueMin(), this._valueMin() ];
				}
				if ( o.values.length && o.values.length !== 2 ) {
					o.values = [ o.values[0], o.values[0] ];
				}
			} else {
				this.range = $( "<div></div>" );
			}

			this.range
				.appendTo( this.element )
				.addClass( "ui-slider-range" );

			if ( o.range === "min" || o.range === "max" ) {
				this.range.addClass( "ui-slider-range-" + o.range );
			}

			// note: this isn't the most fittingly semantic framework class for this element,
			// but worked best visually with a variety of themes
			this.range.addClass( "ui-widget-header" );
		}

		if ( $( ".ui-slider-handle", this.element ).length === 0 ) {
			$( "<a href='#'></a>" )
				.appendTo( this.element )
				.addClass( "ui-slider-handle" );
		}

		if ( o.values && o.values.length ) {
			while ( $(".ui-slider-handle", this.element).length < o.values.length ) {
				$( "<a href='#'></a>" )
					.appendTo( this.element )
					.addClass( "ui-slider-handle" );
			}
		}

		this.handles = $( ".ui-slider-handle", this.element )
			.addClass( "ui-state-default" +
				" ui-corner-all" );

		this.handle = this.handles.eq( 0 );

		this.handles.add( this.range ).filter( "a" )
			.click(function( event ) {
				event.preventDefault();
			})
			.hover(function() {
				if ( !o.disabled ) {
					$( this ).addClass( "ui-state-hover" );
				}
			}, function() {
				$( this ).removeClass( "ui-state-hover" );
			})
			.focus(function() {
				if ( !o.disabled ) {
					$( ".ui-slider .ui-state-focus" ).removeClass( "ui-state-focus" );
					$( this ).addClass( "ui-state-focus" );
				} else {
					$( this ).blur();
				}
			})
			.blur(function() {
				$( this ).removeClass( "ui-state-focus" );
			});

		this.handles.each(function( i ) {
			$( this ).data( "index.ui-slider-handle", i );
		});

		this.handles
			.keydown(function( event ) {
				var ret = true,
					index = $( this ).data( "index.ui-slider-handle" ),
					allowed,
					curVal,
					newVal,
					step;
	
				if ( self.options.disabled ) {
					return;
				}
	
				switch ( event.keyCode ) {
					case $.ui.keyCode.HOME:
					case $.ui.keyCode.END:
					case $.ui.keyCode.PAGE_UP:
					case $.ui.keyCode.PAGE_DOWN:
					case $.ui.keyCode.UP:
					case $.ui.keyCode.RIGHT:
					case $.ui.keyCode.DOWN:
					case $.ui.keyCode.LEFT:
						ret = false;
						if ( !self._keySliding ) {
							self._keySliding = true;
							$( this ).addClass( "ui-state-active" );
							allowed = self._start( event, index );
							if ( allowed === false ) {
								return;
							}
						}
						break;
				}
	
				step = self.options.step;
				if ( self.options.values && self.options.values.length ) {
					curVal = newVal = self.values( index );
				} else {
					curVal = newVal = self.value();
				}
	
				switch ( event.keyCode ) {
					case $.ui.keyCode.HOME:
						newVal = self._valueMin();
						break;
					case $.ui.keyCode.END:
						newVal = self._valueMax();
						break;
					case $.ui.keyCode.PAGE_UP:
						newVal = self._trimAlignValue( curVal + ( (self._valueMax() - self._valueMin()) / numPages ) );
						break;
					case $.ui.keyCode.PAGE_DOWN:
						newVal = self._trimAlignValue( curVal - ( (self._valueMax() - self._valueMin()) / numPages ) );
						break;
					case $.ui.keyCode.UP:
					case $.ui.keyCode.RIGHT:
						if ( curVal === self._valueMax() ) {
							return;
						}
						newVal = self._trimAlignValue( curVal + step );
						break;
					case $.ui.keyCode.DOWN:
					case $.ui.keyCode.LEFT:
						if ( curVal === self._valueMin() ) {
							return;
						}
						newVal = self._trimAlignValue( curVal - step );
						break;
				}
	
				self._slide( event, index, newVal );
	
				return ret;
	
			})
			.keyup(function( event ) {
				var index = $( this ).data( "index.ui-slider-handle" );
	
				if ( self._keySliding ) {
					self._keySliding = false;
					self._stop( event, index );
					self._change( event, index );
					$( this ).removeClass( "ui-state-active" );
				}
	
			});

		this._refreshValue();

		this._animateOff = false;
	},

	destroy: function() {
		this.handles.remove();
		this.range.remove();

		this.element
			.removeClass( "ui-slider" +
				" ui-slider-horizontal" +
				" ui-slider-vertical" +
				" ui-slider-disabled" +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all" )
			.removeData( "slider" )
			.unbind( ".slider" );

		this._mouseDestroy();

		return this;
	},

	_mouseCapture: function( event ) {
		var o = this.options,
			position,
			normValue,
			distance,
			closestHandle,
			self,
			index,
			allowed,
			offset,
			mouseOverHandle;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		self = this;
		this.handles.each(function( i ) {
			var thisDistance = Math.abs( normValue - self.values(i) );
			if ( distance > thisDistance ) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		});

		// workaround for bug #3736 (if both handles of a range are at 0,
		// the first is always used as the one with least distance,
		// and moving it is obviously prevented by preventing negative ranges)
		if( o.range === true && this.values(1) === o.min ) {
			index += 1;
			closestHandle = $( this.handles[index] );
		}

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		self._handleIndex = index;

		closestHandle
			.addClass( "ui-state-active" )
			.focus();
		
		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().andSelf().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
				( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
				( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function( event ) {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );
		
		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this.handles.removeClass( "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},
	
	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_start: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}
		return this._trigger( "start", event, uiHash );
	},

	_slide: function( event, index, newVal ) {
		var otherVal,
			newValues,
			allowed;

		if ( this.options.values && this.options.values.length ) {
			otherVal = this.values( index ? 0 : 1 );

			if ( ( this.options.values.length === 2 && this.options.range === true ) && 
					( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
				) {
				newVal = otherVal;
			}

			if ( newVal !== this.values( index ) ) {
				newValues = this.values();
				newValues[ index ] = newVal;
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal,
					values: newValues
				} );
				otherVal = this.values( index ? 0 : 1 );
				if ( allowed !== false ) {
					this.values( index, newVal, true );
				}
			}
		} else {
			if ( newVal !== this.value() ) {
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal
				} );
				if ( allowed !== false ) {
					this.value( newVal );
				}
			}
		}
	},

	_stop: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}

		this._trigger( "stop", event, uiHash );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {
			var uiHash = {
				handle: this.handles[ index ],
				value: this.value()
			};
			if ( this.options.values && this.options.values.length ) {
				uiHash.value = this.values( index );
				uiHash.values = this.values();
			}

			this._trigger( "change", event, uiHash );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this.options.values && this.options.values.length ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		$.Widget.prototype._setOption.apply( this, arguments );

		switch ( key ) {
			case "disabled":
				if ( value ) {
					this.handles.filter( ".ui-state-focus" ).blur();
					this.handles.removeClass( "ui-state-hover" );
					this.handles.attr( "disabled", "disabled" );
					this.element.addClass( "ui-disabled" );
				} else {
					this.handles.removeAttr( "disabled" );
					this.element.removeClass( "ui-disabled" );
				}
				break;
			case "orientation":
				this._detectOrientation();
				this.element
					.removeClass( "ui-slider-horizontal ui-slider-vertical" )
					.addClass( "ui-slider-" + this.orientation );
				this._refreshValue();
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();
				for ( i = 0; i < valsLength; i += 1 ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
		}
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else {
			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i+= 1) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		}
	},
	
	// returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = (val - this._valueMin()) % step;
			alignValue = val - valModStep;

		if ( Math.abs(valModStep) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed(5) );
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.options.max;
	},
	
	_refreshValue: function() {
		var oRange = this.options.range,
			o = this.options,
			self = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			valPercent,
			_set = {},
			lastValPercent,
			value,
			valueMin,
			valueMax;

		if ( this.options.values && this.options.values.length ) {
			this.handles.each(function( i, j ) {
				valPercent = ( self.values(i) - self._valueMin() ) / ( self._valueMax() - self._valueMin() ) * 100;
				_set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( self.options.range === true ) {
					if ( self.orientation === "horizontal" ) {
						if ( i === 0 ) {
							self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
						}
						if ( i === 1 ) {
							self.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					} else {
						if ( i === 0 ) {
							self.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
						}
						if ( i === 1 ) {
							self.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ self.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
		}
	}

});

$.extend( $.ui.slider, {
	version: "1.8.12"
});

}(jQuery));
/*
 * jQuery UI Tabs 1.8.12
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Tabs
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {

var tabId = 0,
	listId = 0;

function getNextTabId() {
	return ++tabId;
}

function getNextListId() {
	return ++listId;
}

$.widget( "ui.tabs", {
	options: {
		add: null,
		ajaxOptions: null,
		cache: false,
		cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
		collapsible: false,
		disable: null,
		disabled: [],
		enable: null,
		event: "click",
		fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }
		idPrefix: "ui-tabs-",
		load: null,
		panelTemplate: "<div></div>",
		remove: null,
		select: null,
		show: null,
		spinner: "<em>Loading&#8230;</em>",
		tabTemplate: "<li><a href='#{href}'><span>#{label}</span></a></li>"
	},

	_create: function() {
		this._tabify( true );
	},

	_setOption: function( key, value ) {
		if ( key == "selected" ) {
			if (this.options.collapsible && value == this.options.selected ) {
				return;
			}
			this.select( value );
		} else {
			this.options[ key ] = value;
			this._tabify();
		}
	},

	_tabId: function( a ) {
		return a.title && a.title.replace( /\s/g, "_" ).replace( /[^\w\u00c0-\uFFFF-]/g, "" ) ||
			this.options.idPrefix + getNextTabId();
	},

	_sanitizeSelector: function( hash ) {
		// we need this because an id may contain a ":"
		return hash.replace( /:/g, "\\:" );
	},

	_cookie: function() {
		var cookie = this.cookie ||
			( this.cookie = this.options.cookie.name || "ui-tabs-" + getNextListId() );
		return $.cookie.apply( null, [ cookie ].concat( $.makeArray( arguments ) ) );
	},

	_ui: function( tab, panel ) {
		return {
			tab: tab,
			panel: panel,
			index: this.anchors.index( tab )
		};
	},

	_cleanup: function() {
		// restore all former loading tabs labels
		this.lis.filter( ".ui-state-processing" )
			.removeClass( "ui-state-processing" )
			.find( "span:data(label.tabs)" )
				.each(function() {
					var el = $( this );
					el.html( el.data( "label.tabs" ) ).removeData( "label.tabs" );
				});
	},

	_tabify: function( init ) {
		var self = this,
			o = this.options,
			fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash

		this.list = this.element.find( "ol,ul" ).eq( 0 );
		this.lis = $( " > li:has(a[href])", this.list );
		this.anchors = this.lis.map(function() {
			return $( "a", this )[ 0 ];
		});
		this.panels = $( [] );

		this.anchors.each(function( i, a ) {
			var href = $( a ).attr( "href" );
			// For dynamically created HTML that contains a hash as href IE < 8 expands
			// such href to the full page url with hash and then misinterprets tab as ajax.
			// Same consideration applies for an added tab with a fragment identifier
			// since a[href=#fragment-identifier] does unexpectedly not match.
			// Thus normalize href attribute...
			var hrefBase = href.split( "#" )[ 0 ],
				baseEl;
			if ( hrefBase && ( hrefBase === location.toString().split( "#" )[ 0 ] ||
					( baseEl = $( "base" )[ 0 ]) && hrefBase === baseEl.href ) ) {
				href = a.hash;
				a.href = href;
			}

			// inline tab
			if ( fragmentId.test( href ) ) {
				self.panels = self.panels.add( self.element.find( self._sanitizeSelector( href ) ) );
			// remote tab
			// prevent loading the page itself if href is just "#"
			} else if ( href && href !== "#" ) {
				// required for restore on destroy
				$.data( a, "href.tabs", href );

				// TODO until #3808 is fixed strip fragment identifier from url
				// (IE fails to load from such url)
				$.data( a, "load.tabs", href.replace( /#.*$/, "" ) );

				var id = self._tabId( a );
				a.href = "#" + id;
				var $panel = self.element.find( "#" + id );
				if ( !$panel.length ) {
					$panel = $( o.panelTemplate )
						.attr( "id", id )
						.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
						.insertAfter( self.panels[ i - 1 ] || self.list );
					$panel.data( "destroy.tabs", true );
				}
				self.panels = self.panels.add( $panel );
			// invalid tab href
			} else {
				o.disabled.push( i );
			}
		});

		// initialization from scratch
		if ( init ) {
			// attach necessary classes for styling
			this.element.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" );
			this.list.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" );
			this.lis.addClass( "ui-state-default ui-corner-top" );
			this.panels.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" );

			// Selected tab
			// use "selected" option or try to retrieve:
			// 1. from fragment identifier in url
			// 2. from cookie
			// 3. from selected class attribute on <li>
			if ( o.selected === undefined ) {
				if ( location.hash ) {
					this.anchors.each(function( i, a ) {
						if ( a.hash == location.hash ) {
							o.selected = i;
							return false;
						}
					});
				}
				if ( typeof o.selected !== "number" && o.cookie ) {
					o.selected = parseInt( self._cookie(), 10 );
				}
				if ( typeof o.selected !== "number" && this.lis.filter( ".ui-tabs-selected" ).length ) {
					o.selected = this.lis.index( this.lis.filter( ".ui-tabs-selected" ) );
				}
				o.selected = o.selected || ( this.lis.length ? 0 : -1 );
			} else if ( o.selected === null ) { // usage of null is deprecated, TODO remove in next release
				o.selected = -1;
			}

			// sanity check - default to first tab...
			o.selected = ( ( o.selected >= 0 && this.anchors[ o.selected ] ) || o.selected < 0 )
				? o.selected
				: 0;

			// Take disabling tabs via class attribute from HTML
			// into account and update option properly.
			// A selected tab cannot become disabled.
			o.disabled = $.unique( o.disabled.concat(
				$.map( this.lis.filter( ".ui-state-disabled" ), function( n, i ) {
					return self.lis.index( n );
				})
			) ).sort();

			if ( $.inArray( o.selected, o.disabled ) != -1 ) {
				o.disabled.splice( $.inArray( o.selected, o.disabled ), 1 );
			}

			// highlight selected tab
			this.panels.addClass( "ui-tabs-hide" );
			this.lis.removeClass( "ui-tabs-selected ui-state-active" );
			// check for length avoids error when initializing empty list
			if ( o.selected >= 0 && this.anchors.length ) {
				self.element.find( self._sanitizeSelector( self.anchors[ o.selected ].hash ) ).removeClass( "ui-tabs-hide" );
				this.lis.eq( o.selected ).addClass( "ui-tabs-selected ui-state-active" );

				// seems to be expected behavior that the show callback is fired
				self.element.queue( "tabs", function() {
					self._trigger( "show", null,
						self._ui( self.anchors[ o.selected ], self.element.find( self._sanitizeSelector( self.anchors[ o.selected ].hash ) )[ 0 ] ) );
				});

				this.load( o.selected );
			}

			// clean up to avoid memory leaks in certain versions of IE 6
			// TODO: namespace this event
			$( window ).bind( "unload", function() {
				self.lis.add( self.anchors ).unbind( ".tabs" );
				self.lis = self.anchors = self.panels = null;
			});
		// update selected after add/remove
		} else {
			o.selected = this.lis.index( this.lis.filter( ".ui-tabs-selected" ) );
		}

		// update collapsible
		// TODO: use .toggleClass()
		this.element[ o.collapsible ? "addClass" : "removeClass" ]( "ui-tabs-collapsible" );

		// set or update cookie after init and add/remove respectively
		if ( o.cookie ) {
			this._cookie( o.selected, o.cookie );
		}

		// disable tabs
		for ( var i = 0, li; ( li = this.lis[ i ] ); i++ ) {
			$( li )[ $.inArray( i, o.disabled ) != -1 &&
				// TODO: use .toggleClass()
				!$( li ).hasClass( "ui-tabs-selected" ) ? "addClass" : "removeClass" ]( "ui-state-disabled" );
		}

		// reset cache if switching from cached to not cached
		if ( o.cache === false ) {
			this.anchors.removeData( "cache.tabs" );
		}

		// remove all handlers before, tabify may run on existing tabs after add or option change
		this.lis.add( this.anchors ).unbind( ".tabs" );

		if ( o.event !== "mouseover" ) {
			var addState = function( state, el ) {
				if ( el.is( ":not(.ui-state-disabled)" ) ) {
					el.addClass( "ui-state-" + state );
				}
			};
			var removeState = function( state, el ) {
				el.removeClass( "ui-state-" + state );
			};
			this.lis.bind( "mouseover.tabs" , function() {
				addState( "hover", $( this ) );
			});
			this.lis.bind( "mouseout.tabs", function() {
				removeState( "hover", $( this ) );
			});
			this.anchors.bind( "focus.tabs", function() {
				addState( "focus", $( this ).closest( "li" ) );
			});
			this.anchors.bind( "blur.tabs", function() {
				removeState( "focus", $( this ).closest( "li" ) );
			});
		}

		// set up animations
		var hideFx, showFx;
		if ( o.fx ) {
			if ( $.isArray( o.fx ) ) {
				hideFx = o.fx[ 0 ];
				showFx = o.fx[ 1 ];
			} else {
				hideFx = showFx = o.fx;
			}
		}

		// Reset certain styles left over from animation
		// and prevent IE's ClearType bug...
		function resetStyle( $el, fx ) {
			$el.css( "display", "" );
			if ( !$.support.opacity && fx.opacity ) {
				$el[ 0 ].style.removeAttribute( "filter" );
			}
		}

		// Show a tab...
		var showTab = showFx
			? function( clicked, $show ) {
				$( clicked ).closest( "li" ).addClass( "ui-tabs-selected ui-state-active" );
				$show.hide().removeClass( "ui-tabs-hide" ) // avoid flicker that way
					.animate( showFx, showFx.duration || "normal", function() {
						resetStyle( $show, showFx );
						self._trigger( "show", null, self._ui( clicked, $show[ 0 ] ) );
					});
			}
			: function( clicked, $show ) {
				$( clicked ).closest( "li" ).addClass( "ui-tabs-selected ui-state-active" );
				$show.removeClass( "ui-tabs-hide" );
				self._trigger( "show", null, self._ui( clicked, $show[ 0 ] ) );
			};

		// Hide a tab, $show is optional...
		var hideTab = hideFx
			? function( clicked, $hide ) {
				$hide.animate( hideFx, hideFx.duration || "normal", function() {
					self.lis.removeClass( "ui-tabs-selected ui-state-active" );
					$hide.addClass( "ui-tabs-hide" );
					resetStyle( $hide, hideFx );
					self.element.dequeue( "tabs" );
				});
			}
			: function( clicked, $hide, $show ) {
				self.lis.removeClass( "ui-tabs-selected ui-state-active" );
				$hide.addClass( "ui-tabs-hide" );
				self.element.dequeue( "tabs" );
			};

		// attach tab event handler, unbind to avoid duplicates from former tabifying...
		this.anchors.bind( o.event + ".tabs", function() {
			var el = this,
				$li = $(el).closest( "li" ),
				$hide = self.panels.filter( ":not(.ui-tabs-hide)" ),
				$show = self.element.find( self._sanitizeSelector( el.hash ) );

			// If tab is already selected and not collapsible or tab disabled or
			// or is already loading or click callback returns false stop here.
			// Check if click handler returns false last so that it is not executed
			// for a disabled or loading tab!
			if ( ( $li.hasClass( "ui-tabs-selected" ) && !o.collapsible) ||
				$li.hasClass( "ui-state-disabled" ) ||
				$li.hasClass( "ui-state-processing" ) ||
				self.panels.filter( ":animated" ).length ||
				self._trigger( "select", null, self._ui( this, $show[ 0 ] ) ) === false ) {
				this.blur();
				return false;
			}

			o.selected = self.anchors.index( this );

			self.abort();

			// if tab may be closed
			if ( o.collapsible ) {
				if ( $li.hasClass( "ui-tabs-selected" ) ) {
					o.selected = -1;

					if ( o.cookie ) {
						self._cookie( o.selected, o.cookie );
					}

					self.element.queue( "tabs", function() {
						hideTab( el, $hide );
					}).dequeue( "tabs" );

					this.blur();
					return false;
				} else if ( !$hide.length ) {
					if ( o.cookie ) {
						self._cookie( o.selected, o.cookie );
					}

					self.element.queue( "tabs", function() {
						showTab( el, $show );
					});

					// TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171
					self.load( self.anchors.index( this ) );

					this.blur();
					return false;
				}
			}

			if ( o.cookie ) {
				self._cookie( o.selected, o.cookie );
			}

			// show new tab
			if ( $show.length ) {
				if ( $hide.length ) {
					self.element.queue( "tabs", function() {
						hideTab( el, $hide );
					});
				}
				self.element.queue( "tabs", function() {
					showTab( el, $show );
				});

				self.load( self.anchors.index( this ) );
			} else {
				throw "jQuery UI Tabs: Mismatching fragment identifier.";
			}

			// Prevent IE from keeping other link focussed when using the back button
			// and remove dotted border from clicked link. This is controlled via CSS
			// in modern browsers; blur() removes focus from address bar in Firefox
			// which can become a usability and annoying problem with tabs('rotate').
			if ( $.browser.msie ) {
				this.blur();
			}
		});

		// disable click in any case
		this.anchors.bind( "click.tabs", function(){
			return false;
		});
	},

    _getIndex: function( index ) {
		// meta-function to give users option to provide a href string instead of a numerical index.
		// also sanitizes numerical indexes to valid values.
		if ( typeof index == "string" ) {
			index = this.anchors.index( this.anchors.filter( "[href$=" + index + "]" ) );
		}

		return index;
	},

	destroy: function() {
		var o = this.options;

		this.abort();

		this.element
			.unbind( ".tabs" )
			.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" )
			.removeData( "tabs" );

		this.list.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" );

		this.anchors.each(function() {
			var href = $.data( this, "href.tabs" );
			if ( href ) {
				this.href = href;
			}
			var $this = $( this ).unbind( ".tabs" );
			$.each( [ "href", "load", "cache" ], function( i, prefix ) {
				$this.removeData( prefix + ".tabs" );
			});
		});

		this.lis.unbind( ".tabs" ).add( this.panels ).each(function() {
			if ( $.data( this, "destroy.tabs" ) ) {
				$( this ).remove();
			} else {
				$( this ).removeClass([
					"ui-state-default",
					"ui-corner-top",
					"ui-tabs-selected",
					"ui-state-active",
					"ui-state-hover",
					"ui-state-focus",
					"ui-state-disabled",
					"ui-tabs-panel",
					"ui-widget-content",
					"ui-corner-bottom",
					"ui-tabs-hide"
				].join( " " ) );
			}
		});

		if ( o.cookie ) {
			this._cookie( null, o.cookie );
		}

		return this;
	},

	add: function( url, label, index ) {
		if ( index === undefined ) {
			index = this.anchors.length;
		}

		var self = this,
			o = this.options,
			$li = $( o.tabTemplate.replace( /#\{href\}/g, url ).replace( /#\{label\}/g, label ) ),
			id = !url.indexOf( "#" ) ? url.replace( "#", "" ) : this._tabId( $( "a", $li )[ 0 ] );

		$li.addClass( "ui-state-default ui-corner-top" ).data( "destroy.tabs", true );

		// try to find an existing element before creating a new one
		var $panel = self.element.find( "#" + id );
		if ( !$panel.length ) {
			$panel = $( o.panelTemplate )
				.attr( "id", id )
				.data( "destroy.tabs", true );
		}
		$panel.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide" );

		if ( index >= this.lis.length ) {
			$li.appendTo( this.list );
			$panel.appendTo( this.list[ 0 ].parentNode );
		} else {
			$li.insertBefore( this.lis[ index ] );
			$panel.insertBefore( this.panels[ index ] );
		}

		o.disabled = $.map( o.disabled, function( n, i ) {
			return n >= index ? ++n : n;
		});

		this._tabify();

		if ( this.anchors.length == 1 ) {
			o.selected = 0;
			$li.addClass( "ui-tabs-selected ui-state-active" );
			$panel.removeClass( "ui-tabs-hide" );
			this.element.queue( "tabs", function() {
				self._trigger( "show", null, self._ui( self.anchors[ 0 ], self.panels[ 0 ] ) );
			});

			this.load( 0 );
		}

		this._trigger( "add", null, this._ui( this.anchors[ index ], this.panels[ index ] ) );
		return this;
	},

	remove: function( index ) {
		index = this._getIndex( index );
		var o = this.options,
			$li = this.lis.eq( index ).remove(),
			$panel = this.panels.eq( index ).remove();

		// If selected tab was removed focus tab to the right or
		// in case the last tab was removed the tab to the left.
		if ( $li.hasClass( "ui-tabs-selected" ) && this.anchors.length > 1) {
			this.select( index + ( index + 1 < this.anchors.length ? 1 : -1 ) );
		}

		o.disabled = $.map(
			$.grep( o.disabled, function(n, i) {
				return n != index;
			}),
			function( n, i ) {
				return n >= index ? --n : n;
			});

		this._tabify();

		this._trigger( "remove", null, this._ui( $li.find( "a" )[ 0 ], $panel[ 0 ] ) );
		return this;
	},

	enable: function( index ) {
		index = this._getIndex( index );
		var o = this.options;
		if ( $.inArray( index, o.disabled ) == -1 ) {
			return;
		}

		this.lis.eq( index ).removeClass( "ui-state-disabled" );
		o.disabled = $.grep( o.disabled, function( n, i ) {
			return n != index;
		});

		this._trigger( "enable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) );
		return this;
	},

	disable: function( index ) {
		index = this._getIndex( index );
		var self = this, o = this.options;
		// cannot disable already selected tab
		if ( index != o.selected ) {
			this.lis.eq( index ).addClass( "ui-state-disabled" );

			o.disabled.push( index );
			o.disabled.sort();

			this._trigger( "disable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) );
		}

		return this;
	},

	select: function( index ) {
		index = this._getIndex( index );
		if ( index == -1 ) {
			if ( this.options.collapsible && this.options.selected != -1 ) {
				index = this.options.selected;
			} else {
				return this;
			}
		}
		this.anchors.eq( index ).trigger( this.options.event + ".tabs" );
		return this;
	},

	load: function( index ) {
		index = this._getIndex( index );
		var self = this,
			o = this.options,
			a = this.anchors.eq( index )[ 0 ],
			url = $.data( a, "load.tabs" );

		this.abort();

		// not remote or from cache
		if ( !url || this.element.queue( "tabs" ).length !== 0 && $.data( a, "cache.tabs" ) ) {
			this.element.dequeue( "tabs" );
			return;
		}

		// load remote from here on
		this.lis.eq( index ).addClass( "ui-state-processing" );

		if ( o.spinner ) {
			var span = $( "span", a );
			span.data( "label.tabs", span.html() ).html( o.spinner );
		}

		this.xhr = $.ajax( $.extend( {}, o.ajaxOptions, {
			url: url,
			success: function( r, s ) {
				self.element.find( self._sanitizeSelector( a.hash ) ).html( r );

				// take care of tab labels
				self._cleanup();

				if ( o.cache ) {
					$.data( a, "cache.tabs", true );
				}

				self._trigger( "load", null, self._ui( self.anchors[ index ], self.panels[ index ] ) );
				try {
					o.ajaxOptions.success( r, s );
				}
				catch ( e ) {}
			},
			error: function( xhr, s, e ) {
				// take care of tab labels
				self._cleanup();

				self._trigger( "load", null, self._ui( self.anchors[ index ], self.panels[ index ] ) );
				try {
					// Passing index avoid a race condition when this method is
					// called after the user has selected another tab.
					// Pass the anchor that initiated this request allows
					// loadError to manipulate the tab content panel via $(a.hash)
					o.ajaxOptions.error( xhr, s, index, a );
				}
				catch ( e ) {}
			}
		} ) );

		// last, so that load event is fired before show...
		self.element.dequeue( "tabs" );

		return this;
	},

	abort: function() {
		// stop possibly running animations
		this.element.queue( [] );
		this.panels.stop( false, true );

		// "tabs" queue must not contain more than two elements,
		// which are the callbacks for the latest clicked tab...
		this.element.queue( "tabs", this.element.queue( "tabs" ).splice( -2, 2 ) );

		// terminate pending requests from other tabs
		if ( this.xhr ) {
			this.xhr.abort();
			delete this.xhr;
		}

		// take care of tab labels
		this._cleanup();
		return this;
	},

	url: function( index, url ) {
		this.anchors.eq( index ).removeData( "cache.tabs" ).data( "load.tabs", url );
		return this;
	},

	length: function() {
		return this.anchors.length;
	}
});

$.extend( $.ui.tabs, {
	version: "1.8.12"
});

/*
 * Tabs Extensions
 */

/*
 * Rotate
 */
$.extend( $.ui.tabs.prototype, {
	rotation: null,
	rotate: function( ms, continuing ) {
		var self = this,
			o = this.options;

		var rotate = self._rotate || ( self._rotate = function( e ) {
			clearTimeout( self.rotation );
			self.rotation = setTimeout(function() {
				var t = o.selected;
				self.select( ++t < self.anchors.length ? t : 0 );
			}, ms );
			
			if ( e ) {
				e.stopPropagation();
			}
		});

		var stop = self._unrotate || ( self._unrotate = !continuing
			? function(e) {
				if (e.clientX) { // in case of a true click
					self.rotate(null);
				}
			}
			: function( e ) {
				t = o.selected;
				rotate();
			});

		// start rotation
		if ( ms ) {
			this.element.bind( "tabsshow", rotate );
			this.anchors.bind( o.event + ".tabs", stop );
			rotate();
		// stop rotation
		} else {
			clearTimeout( self.rotation );
			this.element.unbind( "tabsshow", rotate );
			this.anchors.unbind( o.event + ".tabs", stop );
			delete this._rotate;
			delete this._unrotate;
		}

		return this;
	}
});

})( jQuery );
/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
 
;(function($) {
	
		// the tooltip element
	var helper = {},
		// the current tooltipped element
		current,
		// the title of the current element, used for restoring
		title,
		// timeout id for delayed tooltips
		tID,
		// IE 5.5 or 6
		IE = $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		// flag for mouse tracking
		track = false;
	
	$.tooltip = {
		blocked: false,
		defaults: {
			delay: 200,
			fade: false,
			showURL: true,
			extraClass: "",
			top: 15,
			left: 15,
			id: "tooltip"
		},
		block: function() {
			$.tooltip.blocked = !$.tooltip.blocked;
		}
	};
	
	$.fn.extend({
		tooltip: function(settings) {
			settings = $.extend({}, $.tooltip.defaults, settings);
			createHelper(settings);
			return this.each(function() {
					$.data(this, "tooltip", settings);
					this.tOpacity = helper.parent.css("opacity");
					// copy tooltip into its own expando and remove the title
					this.tooltipText = this.title;
					$(this).removeAttr("title");
					// also remove alt attribute to prevent default tooltip in IE
					this.alt = "";
				})
				.mouseover(save)
				.mouseout(hide)
				.click(hide);
		},
		fixPNG: IE ? function() {
			return this.each(function () {
				var image = $(this).css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
					image = RegExp.$1;
					$(this).css({
						'backgroundImage': 'none',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
					}).each(function () {
						var position = $(this).css('position');
						if (position != 'absolute' && position != 'relative')
							$(this).css('position', 'relative');
					});
				}
			});
		} : function() { return this; },
		unfixPNG: IE ? function() {
			return this.each(function () {
				$(this).css({'filter': '', backgroundImage: ''});
			});
		} : function() { return this; },
		hideWhenEmpty: function() {
			return this.each(function() {
				$(this)[ $(this).html() ? "show" : "hide" ]();
			});
		},
		url: function() {
			return this.attr('href') || this.attr('src');
		}
	});
	
	function createHelper(settings) {
		// there can be only one tooltip helper
		if( helper.parent )
			return;
		// create the helper, h3 for title, div for url
		helper.parent = $('<div id="' + settings.id + '"><h3></h3><div class="body"></div><div class="url"></div></div>')
			// add to document
			.appendTo(document.body)
			// hide it at first
			.hide();
			
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			helper.parent.bgiframe();
		
		// save references to title and url elements
		helper.title = $('h3', helper.parent);
		helper.body = $('div.body', helper.parent);
		helper.url = $('div.url', helper.parent);
	}
	
	function settings(element) {
		return $.data(element, "tooltip");
	}
	
	// main event handler to start showing tooltips
	function handle(event) {
		// show helper, either with timeout or on instant
		if( settings(this).delay )
			tID = setTimeout(show, settings(this).delay);
		else
			show();
		
		// if selected, update the helper position when the mouse moves
		track = !!settings(this).track;
		$(document.body).bind('mousemove', update);
			
		// update at least once
		update(event);
	}
	
	// save elements title before the tooltip is displayed
	function save() {
		// if this is the current source, or it has no title (occurs with click event), stop
		if ( $.tooltip.blocked || this == current || (!this.tooltipText && !settings(this).bodyHandler) )
			return;

		// save current
		current = this;
		title = this.tooltipText;
		
		if ( settings(this).bodyHandler ) {
			helper.title.hide();
			var bodyContent = settings(this).bodyHandler.call(this);
			if (bodyContent.nodeType || bodyContent.jquery) {
				helper.body.empty().append(bodyContent)
			} else {
				helper.body.html( bodyContent );
			}
			helper.body.show();
		} else if ( settings(this).showBody ) {
			var parts = title.split(settings(this).showBody);
			helper.title.html(parts.shift()).show();
			helper.body.empty();
			for(var i = 0, part; (part = parts[i]); i++) {
				if(i > 0)
					helper.body.append("<br/>");
				helper.body.append(part);
			}
			helper.body.hideWhenEmpty();
		} else {
			helper.title.html(title).show();
			helper.body.hide();
		}
		
		// if element has href or src, add and show it, otherwise hide it
		if( settings(this).showURL && $(this).url() )
			helper.url.html( $(this).url().replace('http://', '') ).show();
		else 
			helper.url.hide();
		
		// add an optional class for this tip
		helper.parent.addClass(settings(this).extraClass);

		// fix PNG background for IE
		if (settings(this).fixPNG )
			helper.parent.fixPNG();
			
		handle.apply(this, arguments);
	}
	
	// delete timeout and show helper
	function show() {
		tID = null;
		if ((!IE || !$.fn.bgiframe) && settings(current).fade) {
			if (helper.parent.is(":animated"))
				helper.parent.stop().show().fadeTo(settings(current).fade, current.tOpacity);
			else
				helper.parent.is(':visible') ? helper.parent.fadeTo(settings(current).fade, current.tOpacity) : helper.parent.fadeIn(settings(current).fade);
		} else {
			helper.parent.show();
		}
		update();
	}
	
	/**
	 * callback for mousemove
	 * updates the helper position
	 * removes itself when no current element
	 */
	function update(event)	{
		if($.tooltip.blocked)
			return;
		
		if (event && event.target.tagName == "OPTION") {
			return;
		}
		
		// stop updating when tracking is disabled and the tooltip is visible
		if ( !track && helper.parent.is(":visible")) {
			$(document.body).unbind('mousemove', update)
		}
		
		// if no current element is available, remove this listener
		if( current == null ) {
			$(document.body).unbind('mousemove', update);
			return;	
		}
		
		// remove position helper classes
		helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");
		
		var left = helper.parent[0].offsetLeft;
		var top = helper.parent[0].offsetTop;
		if (event) {
			// position the helper 15 pixel to bottom right, starting from mouse position
			left = event.pageX + settings(current).left;
			top = event.pageY + settings(current).top;
			var right='auto';
			if (settings(current).positionLeft) {
				right = $(window).width() - left;
				left = 'auto';
			}
			helper.parent.css({
				left: left,
				right: right,
				top: top
			});
		}
		
		var v = viewport(),
			h = helper.parent[0];
		// check horizontal position
		if (v.x + v.cx < h.offsetLeft + h.offsetWidth) {
			left -= h.offsetWidth + 20 + settings(current).left;
			helper.parent.css({left: left + 'px'}).addClass("viewport-right");
		}
		// check vertical position
		if (v.y + v.cy < h.offsetTop + h.offsetHeight) {
			top -= h.offsetHeight + 20 + settings(current).top;
			helper.parent.css({top: top + 'px'}).addClass("viewport-bottom");
		}
	}
	
	function viewport() {
		return {
			x: $(window).scrollLeft(),
			y: $(window).scrollTop(),
			cx: $(window).width(),
			cy: $(window).height()
		};
	}
	
	// hide helper and restore added classes and the title
	function hide(event) {
		if($.tooltip.blocked)
			return;
		// clear timeout if possible
		if(tID)
			clearTimeout(tID);
		// no more current element
		current = null;
		
		var tsettings = settings(this);
		function complete() {
			helper.parent.removeClass( tsettings.extraClass ).hide().css("opacity", "");
		}
		if ((!IE || !$.fn.bgiframe) && tsettings.fade) {
			if (helper.parent.is(':animated'))
				helper.parent.stop().fadeTo(tsettings.fade, 0, complete);
			else
				helper.parent.stop().fadeOut(tsettings.fade, complete);
		} else
			complete();
		
		if( settings(this).fixPNG )
			helper.parent.unfixPNG();
	}
	
})(jQuery);
/*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com

Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/

/*
 * Generate a random uuid.
 *
 * USAGE: Math.uuid(length, radix)
 *   length - the desired number of characters
 *   radix  - the number of allowable values for each character.
 *
 * EXAMPLES:
 *   // No arguments  - returns RFC4122, version 4 ID
 *   >>> Math.uuid()
 *   "92329D39-6F5C-4520-ABFC-AAB64544E172"
 *
 *   // One argument - returns ID of the specified length
 *   >>> Math.uuid(15)     // 15 character ID (default base=62)
 *   "VcydxgltxrVZSTV"
 *
 *   // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
 *   >>> Math.uuid(8, 2)  // 8 character ID (base=2)
 *   "01001010"
 *   >>> Math.uuid(8, 10) // 8 character ID (base=10)
 *   "47473046"
 *   >>> Math.uuid(8, 16) // 8 character ID (base=16)
 *   "098F4D35"
 */
(function() {
  // Private array of chars to use
  var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

  Math.uuid = function (len, radix) {
    var chars = CHARS, uuid = [], i;
    radix = radix || chars.length;

    if (len) {
      // Compact form
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    } else {
      // rfc4122, version 4 form
      var r;

      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random()*16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return uuid.join('');
  };

  // A more performant, but slightly bulkier, RFC4122v4 solution.  We boost performance
  // by minimizing calls to random()
  Math.uuidFast = function() {
    var chars = CHARS, uuid = new Array(36), rnd=0, r;
    for (var i = 0; i < 36; i++) {
      if (i==8 || i==13 ||  i==18 || i==23) {
        uuid[i] = '-';
      } else if (i==14) {
        uuid[i] = '4';
      } else {
        if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
        r = rnd & 0xf;
        rnd = rnd >> 4;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
    return uuid.join('');
  };

  // A more compact, but less performant, RFC4122v4 solution:
  Math.uuidCompact = function() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
      return v.toString(16);
    });
  };
})();
// jXHR.js (JSON-P XHR)
// v0.1 (c) Kyle Simpson
// MIT License

(function(global){
	var SETTIMEOUT = global.setTimeout, // for better compression
		doc = global.document,
		callback_counter = 0;
		
	global.jXHR = function() {
		var script_url,
			script_loaded,
			jsonp_callback,
			scriptElem,
			publicAPI = null;
			
		function removeScript() { try { scriptElem.parentNode.removeChild(scriptElem); } catch (err) { } }
			
		function reset() {
			script_loaded = false;
			script_url = "";
			removeScript();
			scriptElem = null;
			fireReadyStateChange(0);
		}
		
		function ThrowError(msg) {
			try { publicAPI.onerror.call(publicAPI,msg,script_url); } catch (err) { throw new Error(msg); }
		}

		function handleScriptLoad() {
			if ((this.readyState && this.readyState!=="complete" && this.readyState!=="loaded") || script_loaded) { return; }
			this.onload = this.onreadystatechange = null; // prevent memory leak
			script_loaded = true;
			if (publicAPI.readyState !== 4) ThrowError("Script failed to load ["+script_url+"].");
			removeScript();
		}
		
		function fireReadyStateChange(rs,args) {
			args = args || [];
			publicAPI.readyState = rs;
			if (typeof publicAPI.onreadystatechange === "function") publicAPI.onreadystatechange.apply(publicAPI,args);
		}
				
		publicAPI = {
			onerror:null,
			onreadystatechange:null,
			readyState:0,
			open:function(method,url){
				reset();
				internal_callback = "cb"+(callback_counter++);
				(function(icb){
					global.jXHR[icb] = function() {
						try { fireReadyStateChange.call(publicAPI,4,arguments); } 
						catch(err) { 
							publicAPI.readyState = -1;
							ThrowError("Script failed to run ["+script_url+"]."); 
						}
						global.jXHR[icb] = null;
					};
				})(internal_callback);
				script_url = url.replace(/=\?/,"=jXHR."+internal_callback);
				fireReadyStateChange(1);
			},
			send:function(){
				SETTIMEOUT(function(){
					scriptElem = doc.createElement("script");
					scriptElem.setAttribute("type","text/javascript");
					scriptElem.onload = scriptElem.onreadystatechange = function(){handleScriptLoad.call(scriptElem);};
					scriptElem.setAttribute("src",script_url);
					doc.getElementsByTagName("head")[0].appendChild(scriptElem);
				},0);
				fireReadyStateChange(2);
			},
			setRequestHeader:function(){}, // noop
			getResponseHeader:function(){return "";}, // basically noop
			getAllResponseHeaders:function(){return [];} // ditto
		};

		reset();
		
		return publicAPI;
	};
})(window);//////////////////////////////////////////////////////////////////////////////
//                                                                          //
// Wii Opera SDK - 3D Math Class v2.7.22 2008-12-14                         //
// (c) 2007-2008 Daniel Gump. All Rights Reserved.                          //
// http://wiioperasdk.com, http://hullbreachonline.com                      //
// hullbreach@hullbreachonline.com                                          //
//                                                                          //
//  Wii is a trademark of Nintendo Co., Ltd.                                //
//  Opera is a trademark of Opera, ASA.                                     //
//  This software package is not associated with either company             //
//  but was created to support users of both.  Its alternative name         //
//  when supporting other products is the HULLBREACH SDK.                   //
//                                                                          //
//  Redistribution and use in source and binary forms, with or without      //
//  modification, are permitted provided that the following conditions      //
//  are met:                                                                //
//    * Redistributions of source code must retain the above copyright      //
//      notice, this list of conditions and the following disclaimer.       //
//    * Redistributions in binary form must reproduce the above copyright   //
//      notice, this list of conditions and the following disclaimer in     //
//      the documentation and/or other materials provided with the          //
//      distribution.                                                       //
//    * Neither the names HULLBREACH ONLINE nor WII OPERA SDK nor the names //
//      of its contributors may be used to endorse or promote products      //
//      derived from this software without specific prior written           //
//      permission.                                                         //
//    * If the explicit purpose of the software is not to support the       //
//      Nintendo Wii or the Opera Web browser, then the names of such must  //
//      not be used in any derived product. The name shall be the           //
//      HULLBREACH SDK with a reference link to http://hullbreachonline.    //
//                                                                          //
//  THIS SOFTWARE IS PROVIDED BY Daniel Gump ''AS IS'' AND ANY EXPRESS OR   //
//  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED          //
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE  //
//  DISCLAIMED. IN NO EVENT SHALL Daniel Gump BE LIABLE FOR ANY DIRECT,     //
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES      //
//  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR      //
//  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)      //
//  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,     //
//  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING   //
//  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE      //
//  POSSIBILITY OF SUCH DAMAGE.                                             //
//////////////////////////////////////////////////////////////////////////////

function ThreeD(){
	POLYMESH = new Array();

	CENTERX = 400; CENTERY = 240;
	LIGHTX = -1000; LIGHTY = -1000; LIGHTZ = -1000;
	ORIGINX = 0; ORIGINY = 0; ORIGINZ = 0;
	ANGLEX = 0; ANGLEY = 0; ANGLEZ = 0;
}

ThreeD.prototype.setPoints = function(Points){
	POLYMESH = [];
	for(var value=Points.length;--value>=0;) POLYMESH[value] = Points[value].slice();
}
ThreeD.prototype.loadMesh = function(array){
	if(POLYMESH = array.split(";")) for(i=POLYMESH.length;--i>=0;) POLYMESH[i] = POLYMESH[i].split(",");
}
ThreeD.prototype.getPoints = function(){ return POLYMESH; }

ThreeD.prototype.setCenter = function(x,y){ CENTERX = x|0; CENTERY = y|0; }
ThreeD.prototype.setLight = function(x,y,z){ LIGHTX = x|0; LIGHTY = y|0; LIGHTZ = z|0; }

ThreeD.prototype.explode = function(z){
	var x1, y1, z1, x2, y2, z2;
	var normali, normalj, normalk, magNormal;

	for(var value=POLYMESH.length;--value>=0;){
		x1 = POLYMESH[value][3]-POLYMESH[value][0]; y1 = POLYMESH[value][4]-POLYMESH[value][1]; z1 = POLYMESH[value][5]-POLYMESH[value][2]; 
		x2 = POLYMESH[value][6]-POLYMESH[value][0]; y2 = POLYMESH[value][7]-POLYMESH[value][1]; z2 = POLYMESH[value][8]-POLYMESH[value][2]; 

		normali = y2*z1-y1*z2; normalj = x1*z2-x2*z1; normalk = x2*y1-x1*y2;
		magNormal = z/Math.sqrt(normali*normali+normalj*normalj+normalk*normalk);

		var movex = -normali*magNormal|0;
		var movey = -normalj*magNormal|0;
		var movez = -normalk*magNormal|0;

		POLYMESH[value][0] += movex; POLYMESH[value][1] += movey; POLYMESH[value][2] += movez;
		POLYMESH[value][3] += movex; POLYMESH[value][4] += movey; POLYMESH[value][5] += movez;
		POLYMESH[value][6] += movex; POLYMESH[value][7] += movey; POLYMESH[value][8] += movez;
	}
}
ThreeD.prototype.normalMap = function(normalMap){
	var x1, y1, z1, x2, y2, z2;
	var normali, normalj, normalk, magNormal;

	for(var value=POLYMESH.length;--value>=0;){
		x1 = POLYMESH[value][3]-POLYMESH[value][0]; y1 = POLYMESH[value][4]-POLYMESH[value][1]; z1 = POLYMESH[value][5]-POLYMESH[value][2]; 
		x2 = POLYMESH[value][6]-POLYMESH[value][0]; y2 = POLYMESH[value][7]-POLYMESH[value][1]; z2 = POLYMESH[value][8]-POLYMESH[value][2]; 

		normali = y2*z1-y1*z2; normalj = x1*z2-x2*z1; normalk = x2*y1-x1*y2;
		normal = 1/Math.sqrt(normali*normali+normalj*normalj+normalk*normalk);
		
		for(index2=0; index2<4; index2++){
			for(index=0; index<=index2; index++){
				magNormal = normalMap[index][index2]*normal|0;

				var movex = -normali*magNormal;
				var movey = -normalj*magNormal;
				var movez = -normalk*magNormal;
				
				POLYMESH[POLYMESH.length] = new Array(POLYMESH[value][0]+movex,POLYMESH[value][1]+movey,POLYMESH[value][2]+movez,
							POLYMESH[value][3]+movex,POLYMESH[value][4]+movey,POLYMESH[value][7]+movez,
							POLYMESH[value][6]+movex,POLYMESH[value][7]+movey,POLYMESH[value][8]+movez,
							POLYMESH[value][9],POLYMESH[value][10],POLYMESH[value][11],
							POLYMESH[value][12],POLYMESH[value][13], true, index, index2);
			}
		}
	}
}
ThreeD.prototype.move = function(x,y,z){
	for(var value=POLYMESH.length;--value>=0;)
		for(var point=-1;++point<3;){
			POLYMESH[value][point*3+2] += z;
			POLYMESH[value][point*3+1] += y;
			POLYMESH[value][point*3] += x;
		}
}
ThreeD.prototype.rotate = function(anglex,angley,anglez){
	var cosx = Math.cos(anglex*0.01745329); var sinx = Math.sin(anglex*0.01745329);
	var cosy = Math.cos(angley*0.01745329); var siny = Math.sin(angley*0.01745329);
	var cosz = Math.cos(anglez*0.01745329); var sinz = Math.sin(anglez*0.01745329);

	for(var value=POLYMESH.length;--value>=0;)
		for(var point=-1;++point<3;){
			var tempz = sinx*POLYMESH[value][point*3+1]+cosx*POLYMESH[value][point*3+2];
			var tempy = cosx*POLYMESH[value][point*3+1]-sinx*POLYMESH[value][point*3+2];
			var tempx = cosy*POLYMESH[value][point*3]+siny*tempz;
			POLYMESH[value][point*3+2] = cosy*tempz-siny*POLYMESH[value][point*3];
			POLYMESH[value][point*3+1] = sinz*tempx+cosz*tempy;
			POLYMESH[value][point*3] = cosz*tempx-sinz*tempy;
		}
}
ThreeD.prototype.scale = function(scalex,scaley,scalez){
	for(var value=POLYMESH.length;--value>=0;)
		for(var point=-1;++point<3;){
			POLYMESH[value][point*3+2] *= scalex;
			POLYMESH[value][point*3+1] *= scaley;
			POLYMESH[value][point*3] *= scalez;
		}
}

ThreeD.prototype.backface = function(){
	for(var value=POLYMESH.length, newvalue=0, TempPOLYMESH = [];--value>=0;)
		if((POLYMESH[value][3]-POLYMESH[value][0])*(POLYMESH[value][7]-POLYMESH[value][1])-(POLYMESH[value][6]-POLYMESH[value][0])*(POLYMESH[value][4]-POLYMESH[value][1])>0){
			TempPOLYMESH[newvalue++] = POLYMESH[value].slice();
		}
	POLYMESH = TempPOLYMESH;
}
ThreeD.prototype.zSort = function(){ POLYMESH.sort(function(b,a){return b[2]+b[5]+b[8]-a[2]-a[5]-a[8]}); }

ThreeD.prototype.fade = function(bright){
	for(var value=POLYMESH.length;--value>=0;) POLYMESH[value][13] += bright;
}
ThreeD.prototype.shade = function(){
	var x1, y1, z1, x2, y2, z2;
	var normali, normalj, normalk, magNormal;
	var lighti, lightj, lightk, magLight;

	for(var value=POLYMESH.length;--value>=0;){
		x1 = POLYMESH[value][3]-POLYMESH[value][0]; y1 = POLYMESH[value][4]-POLYMESH[value][1]; z1 = POLYMESH[value][5]-POLYMESH[value][2]; 
		x2 = POLYMESH[value][6]-POLYMESH[value][0]; y2 = POLYMESH[value][7]-POLYMESH[value][1]; z2 = POLYMESH[value][8]-POLYMESH[value][2]; 

		normali = y1*z2-y2*z1; normalj = x2*z1-x1*z2; normalk = x1*y2-x2*y1;

		lighti = LIGHTX-(POLYMESH[value][0]+POLYMESH[value][3]+POLYMESH[value][6])*0.33333333333333333;
		lightj = LIGHTY-(POLYMESH[value][1]+POLYMESH[value][4]+POLYMESH[value][7])*0.33333333333333333;
		lightk = LIGHTZ-(POLYMESH[value][2]+POLYMESH[value][5]+POLYMESH[value][8])*0.33333333333333333;

		POLYMESH[value][13] = 2*(normali*lighti + normalj*lightj + normalk*lightk)/Math.sqrt((normali*normali+normalj*normalj+normalk*normalk)*(lighti*lighti+lightj*lightj+lightk*lightk))-1;
	}
}
ThreeD.prototype.reColor = function(r,g,b){
	r=r>255?255:(r<0?0:r|0);
	g=g>255?255:(g<0?0:g|0);
	b=b>255?255:(b<0?0:b|0);
	for(var value=POLYMESH.length;--value>=0;){
		POLYMESH[value][9]=r;
		POLYMESH[value][10]=g;
		POLYMESH[value][11]=b;
	}
}
ThreeD.prototype.shadow = function(){
	rayorigins = []; 
	raynormals = [];
	edge1 = [];
	edge2 = [];

	for(var value=0, normali, normalj, normalk, magNormal;value<POLYMESH.length;value++){
		edge1[value] = new Array(POLYMESH[value][3]-POLYMESH[value][0], POLYMESH[value][4]-POLYMESH[value][1], POLYMESH[value][5]-POLYMESH[value][2]);
		edge2[value] = new Array(POLYMESH[value][6]-POLYMESH[value][0], POLYMESH[value][7]-POLYMESH[value][1], POLYMESH[value][8]-POLYMESH[value][2]);

		rayorigins[value] = new Array((POLYMESH[value][0]+POLYMESH[value][3]+POLYMESH[value][6])*0.33333333333333333, (POLYMESH[value][1]+POLYMESH[value][4]+POLYMESH[value][7])*0.33333333333333333, (POLYMESH[value][2]+POLYMESH[value][5]+POLYMESH[value][8])*0.33333333333333333);

		normali = LIGHTX-rayorigins[value][0];
		normalj = LIGHTY-rayorigins[value][1];
		normalk = LIGHTZ-rayorigins[value][2];
		magNormal = 1/Math.sqrt(normali*normali+normalj*normalj+normalk*normalk);
		raynormals[value] = new Array(normali*magNormal, normalj*magNormal, normalk*magNormal);
	}

	for(var value=POLYMESH.length;--value>=0;){
		for(var value2=POLYMESH.length;--value2>=0;){
			if(value2!=value){
				var pvecti = raynormals[value][1]*edge2[value2][2]-edge2[value2][1]*raynormals[value][2];
				var pvectj = edge2[value2][0]*raynormals[value][2]-raynormals[value][0]*edge2[value2][2];
				var pvectk = raynormals[value][0]*edge2[value2][1]-edge2[value2][0]*raynormals[value][1];

				if((det = edge1[value2][0]*pvecti+edge1[value2][1]*pvectj+edge1[value2][2]*pvectk)<0){
					det=1/det;

					var tvecti = rayorigins[value][0]-POLYMESH[value2][0];
					var tvectj = rayorigins[value][1]-POLYMESH[value2][1];
					var tvectk = rayorigins[value][2]-POLYMESH[value2][2];

					if((u = (pvecti*tvecti+pvectj*tvectj+pvectk*tvectk) * det)>=0 && u<=1){
						if((v = (raynormals[value][0]*(tvectj*edge1[value2][2]-edge1[value2][1]*tvectk)+raynormals[value][1]*(edge1[value2][0]*tvectk-tvecti*edge1[value2][2])+raynormals[value][2]*(tvecti*edge1[value2][1]-edge1[value2][0]*tvectj)) * det)>=0 && u+v<=1){
							POLYMESH[value][13] -=.5;
							break;
						}
					}
				}
				
			}
		}
	}
}

ThreeD.prototype.getTranslation = function(){
	for(var value=POLYMESH.length,newvalue=0,TransPOLYMESH = [];--value>=0;){
		var POLYMESH2=5000/(5000-POLYMESH[value][2]), POLYMESH5=5000/(5000-POLYMESH[value][5]), POLYMESH8=5000/(5000-POLYMESH[value][8]);
		TransPOLYMESH[newvalue++] = new Array((CENTERX+POLYMESH[value][0]*POLYMESH2),(CENTERY+POLYMESH[value][1]*POLYMESH2),
									(CENTERX+POLYMESH[value][3]*POLYMESH5),(CENTERY+POLYMESH[value][4]*POLYMESH5),
									(CENTERX+POLYMESH[value][6]*POLYMESH8),(CENTERY+POLYMESH[value][7]*POLYMESH8),
									POLYMESH[value][9]|0,POLYMESH[value][10]|0,POLYMESH[value][11]|0,POLYMESH[value][12]|0,POLYMESH[value][13]);
	}
	return TransPOLYMESH;
}

ThreeDee = new ThreeD();/**
 * @author mrdoob / http://mrdoob.com/
 */

var THREE = THREE || { REVISION: '51' };

if ( self.console === undefined ) {

    self.console = {

        info: function () {},
        log: function () {},
        debug: function () {},
        warn: function () {},
        error: function () {}

    };

}

if ( self.Int32Array === undefined ) {

    self.Int32Array = Array;
    self.Float32Array = Array;

}

// Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
// not sure we should have this, or at least not have it here

// http://stackoverflow.com/questions/646628/javascript-startswith
// http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
// http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras

if ( String.prototype.startsWith === undefined ) {

    String.prototype.startsWith = function ( str ) {

        return this.slice( 0, str.length ) === str;

    };

}

if ( String.prototype.endsWith === undefined ) {

    String.prototype.endsWith = function ( str ) {

        var t = String( str );
        var index = this.lastIndexOf( t );
        return index >= 0 && index === this.length - t.length;

    };

}

if ( ! String.prototype.trim === undefined ) {

    String.prototype.trim = function () {

        return this.replace( /^\s+|\s+$/g, '' );

    };

}

// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating

// requestAnimationFrame polyfill by Erik Möller
// fixes from Paul Irish and Tino Zijdel

( function () {

    var lastTime = 0;
    var vendors = [ 'ms', 'moz', 'webkit', 'o' ];

    for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {

        window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
        window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];

    }

    if ( window.requestAnimationFrame === undefined ) {

        window.requestAnimationFrame = function ( callback, element ) {

            var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
            var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
            lastTime = currTime + timeToCall;
            return id;

        };

    }


    if ( window.cancelAnimationFrame === undefined ) {

        window.cancelAnimationFrame = function ( id ) { clearTimeout( id ); };

    }

}() );


// MATERIAL CONSTANTS

// side

THREE.FrontSide = 0;
THREE.BackSide = 1;
THREE.DoubleSide = 2;

// shading

THREE.NoShading = 0;
THREE.FlatShading = 1;
THREE.SmoothShading = 2;

// colors

THREE.NoColors = 0;
THREE.FaceColors = 1;
THREE.VertexColors = 2;

// blending modes

THREE.NoBlending = 0;
THREE.NormalBlending = 1;
THREE.AdditiveBlending = 2;
THREE.SubtractiveBlending = 3;
THREE.MultiplyBlending = 4;
THREE.CustomBlending = 5;

// custom blending equations
// (numbers start from 100 not to clash with other
//  mappings to OpenGL constants defined in Texture.js)

THREE.AddEquation = 100;
THREE.SubtractEquation = 101;
THREE.ReverseSubtractEquation = 102;

// custom blending destination factors

THREE.ZeroFactor = 200;
THREE.OneFactor = 201;
THREE.SrcColorFactor = 202;
THREE.OneMinusSrcColorFactor = 203;
THREE.SrcAlphaFactor = 204;
THREE.OneMinusSrcAlphaFactor = 205;
THREE.DstAlphaFactor = 206;
THREE.OneMinusDstAlphaFactor = 207;

// custom blending source factors

//THREE.ZeroFactor = 200;
//THREE.OneFactor = 201;
//THREE.SrcAlphaFactor = 204;
//THREE.OneMinusSrcAlphaFactor = 205;
//THREE.DstAlphaFactor = 206;
//THREE.OneMinusDstAlphaFactor = 207;
THREE.DstColorFactor = 208;
THREE.OneMinusDstColorFactor = 209;
THREE.SrcAlphaSaturateFactor = 210;


// TEXTURE CONSTANTS

THREE.MultiplyOperation = 0;
THREE.MixOperation = 1;

// Mapping modes

THREE.UVMapping = function () {};

THREE.CubeReflectionMapping = function () {};
THREE.CubeRefractionMapping = function () {};

THREE.SphericalReflectionMapping = function () {};
THREE.SphericalRefractionMapping = function () {};

// Wrapping modes

THREE.RepeatWrapping = 1000;
THREE.ClampToEdgeWrapping = 1001;
THREE.MirroredRepeatWrapping = 1002;

// Filters

THREE.NearestFilter = 1003;
THREE.NearestMipMapNearestFilter = 1004;
THREE.NearestMipMapLinearFilter = 1005;
THREE.LinearFilter = 1006;
THREE.LinearMipMapNearestFilter = 1007;
THREE.LinearMipMapLinearFilter = 1008;

// Data types

THREE.UnsignedByteType = 1009;
THREE.ByteType = 1010;
THREE.ShortType = 1011;
THREE.UnsignedShortType = 1012;
THREE.IntType = 1013;
THREE.UnsignedIntType = 1014;
THREE.FloatType = 1015;

// Pixel types

//THREE.UnsignedByteType = 1009;
THREE.UnsignedShort4444Type = 1016;
THREE.UnsignedShort5551Type = 1017;
THREE.UnsignedShort565Type = 1018;

// Pixel formats

THREE.AlphaFormat = 1019;
THREE.RGBFormat = 1020;
THREE.RGBAFormat = 1021;
THREE.LuminanceFormat = 1022;
THREE.LuminanceAlphaFormat = 1023;

// Compressed texture formats

THREE.RGB_S3TC_DXT1_Format = 2001;
THREE.RGBA_S3TC_DXT1_Format = 2002;
THREE.RGBA_S3TC_DXT3_Format = 2003;
THREE.RGBA_S3TC_DXT5_Format = 2004;

/*
// Potential future PVRTC compressed texture formats
THREE.RGB_PVRTC_4BPPV1_Format = 2100;
THREE.RGB_PVRTC_2BPPV1_Format = 2101;
THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
*/
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Clock = function ( autoStart ) {

    this.autoStart = ( autoStart !== undefined ) ? autoStart : true;

    this.startTime = 0;
    this.oldTime = 0;
    this.elapsedTime = 0;

    this.running = false;

};

THREE.Clock.prototype.start = function () {

    this.startTime = Date.now();
    this.oldTime = this.startTime;

    this.running = true;

};

THREE.Clock.prototype.stop = function () {

    this.getElapsedTime();

    this.running = false;

};

THREE.Clock.prototype.getElapsedTime = function () {

    this.elapsedTime += this.getDelta();

    return this.elapsedTime;

};


THREE.Clock.prototype.getDelta = function () {

    var diff = 0;

    if ( this.autoStart && ! this.running ) {

        this.start();

    }

    if ( this.running ) {

        var newTime = Date.now();
        diff = 0.001 * ( newTime - this.oldTime );
        this.oldTime = newTime;

        this.elapsedTime += diff;

    }

    return diff;

};/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Color = function ( hex ) {

    if ( hex !== undefined ) this.setHex( hex );

    return this;

};

THREE.Color.prototype = {

    constructor: THREE.Color,

    r: 1, g: 1, b: 1,

    copy: function ( color ) {

        this.r = color.r;
        this.g = color.g;
        this.b = color.b;

        return this;

    },

    copyGammaToLinear: function ( color ) {

        this.r = color.r * color.r;
        this.g = color.g * color.g;
        this.b = color.b * color.b;

        return this;

    },

    copyLinearToGamma: function ( color ) {

        this.r = Math.sqrt( color.r );
        this.g = Math.sqrt( color.g );
        this.b = Math.sqrt( color.b );

        return this;

    },

    convertGammaToLinear: function () {

        var r = this.r, g = this.g, b = this.b;

        this.r = r * r;
        this.g = g * g;
        this.b = b * b;

        return this;

    },

    convertLinearToGamma: function () {

        this.r = Math.sqrt( this.r );
        this.g = Math.sqrt( this.g );
        this.b = Math.sqrt( this.b );

        return this;

    },

    setRGB: function ( r, g, b ) {

        this.r = r;
        this.g = g;
        this.b = b;

        return this;

    },

    setHSV: function ( h, s, v ) {

        // based on MochiKit implementation by Bob Ippolito
        // h,s,v ranges are < 0.0 - 1.0 >

        var i, f, p, q, t;

        if ( v === 0 ) {

            this.r = this.g = this.b = 0;

        } else {

            i = Math.floor( h * 6 );
            f = ( h * 6 ) - i;
            p = v * ( 1 - s );
            q = v * ( 1 - ( s * f ) );
            t = v * ( 1 - ( s * ( 1 - f ) ) );

            if ( i === 0 ) {

                this.r = v;
                this.g = t;
                this.b = p;

            } else if ( i === 1 ) {

                this.r = q;
                this.g = v;
                this.b = p;

            } else if ( i === 2 ) {

                this.r = p;
                this.g = v;
                this.b = t;

            } else if ( i === 3 ) {

                this.r = p;
                this.g = q;
                this.b = v;

            } else if ( i === 4 ) {

                this.r = t;
                this.g = p;
                this.b = v;

            } else if ( i === 5 ) {

                this.r = v;
                this.g = p;
                this.b = q;

            }

        }

        return this;

    },

    setHex: function ( hex ) {

        hex = Math.floor( hex );

        this.r = ( hex >> 16 & 255 ) / 255;
        this.g = ( hex >> 8 & 255 ) / 255;
        this.b = ( hex & 255 ) / 255;

        return this;

    },

    lerpSelf: function ( color, alpha ) {

        this.r += ( color.r - this.r ) * alpha;
        this.g += ( color.g - this.g ) * alpha;
        this.b += ( color.b - this.b ) * alpha;

        return this;

    },

    getHex: function () {

        return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;

    },

    getContextStyle: function () {

        return 'rgb(' + ( ( this.r * 255 ) | 0 )  + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';

    },

    clone: function () {

        return new THREE.Color().setRGB( this.r, this.g, this.b );

    }

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author philogb / http://blog.thejit.org/
 * @author egraether / http://egraether.com/
 * @author zz85 / http://www.lab4games.net/zz85/blog
 */

THREE.Vector2 = function ( x, y ) {

    this.x = x || 0;
    this.y = y || 0;

};

THREE.Vector2.prototype = {

    constructor: THREE.Vector2,

    set: function ( x, y ) {

        this.x = x;
        this.y = y;

        return this;

    },

    copy: function ( v ) {

        this.x = v.x;
        this.y = v.y;

        return this;

    },

    add: function ( a, b ) {

        this.x = a.x + b.x;
        this.y = a.y + b.y;

        return this;

    },

    addSelf: function ( v ) {

        this.x += v.x;
        this.y += v.y;

        return this;

    },

    sub: function ( a, b ) {

        this.x = a.x - b.x;
        this.y = a.y - b.y;

        return this;

    },

    subSelf: function ( v ) {

        this.x -= v.x;
        this.y -= v.y;

        return this;

    },

    multiplyScalar: function ( s ) {

        this.x *= s;
        this.y *= s;

        return this;

    },

    divideScalar: function ( s ) {

        if ( s ) {

            this.x /= s;
            this.y /= s;

        } else {

            this.set( 0, 0 );

        }

        return this;

    },

    negate: function() {

        return this.multiplyScalar( - 1 );

    },

    dot: function ( v ) {

        return this.x * v.x + this.y * v.y;

    },

    lengthSq: function () {

        return this.x * this.x + this.y * this.y;

    },

    length: function () {

        return Math.sqrt( this.lengthSq() );

    },

    normalize: function () {

        return this.divideScalar( this.length() );

    },

    distanceTo: function ( v ) {

        return Math.sqrt( this.distanceToSquared( v ) );

    },

    distanceToSquared: function ( v ) {

        var dx = this.x - v.x, dy = this.y - v.y;
        return dx * dx + dy * dy;

    },

    setLength: function ( l ) {

        return this.normalize().multiplyScalar( l );

    },

    lerpSelf: function ( v, alpha ) {

        this.x += ( v.x - this.x ) * alpha;
        this.y += ( v.y - this.y ) * alpha;

        return this;

    },

    equals: function( v ) {

        return ( ( v.x === this.x ) && ( v.y === this.y ) );

    },

    isZero: function () {

        return ( this.lengthSq() < 0.0001 /* almostZero */ );

    },

    clone: function () {

        return new THREE.Vector2( this.x, this.y );

    }

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author kile / http://kile.stravaganza.org/
 * @author philogb / http://blog.thejit.org/
 * @author mikael emtinger / http://gomo.se/
 * @author egraether / http://egraether.com/
 * @author WestLangley / http://github.com/WestLangley
 */

THREE.Vector3 = function ( x, y, z ) {

    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;

};


THREE.Vector3.prototype = {

    constructor: THREE.Vector3,

    set: function ( x, y, z ) {

        this.x = x;
        this.y = y;
        this.z = z;

        return this;

    },

    setX: function ( x ) {

        this.x = x;

        return this;

    },

    setY: function ( y ) {

        this.y = y;

        return this;

    },

    setZ: function ( z ) {

        this.z = z;

        return this;

    },

    copy: function ( v ) {

        this.x = v.x;
        this.y = v.y;
        this.z = v.z;

        return this;

    },

    add: function ( a, b ) {

        this.x = a.x + b.x;
        this.y = a.y + b.y;
        this.z = a.z + b.z;

        return this;

    },

    addSelf: function ( v ) {

        this.x += v.x;
        this.y += v.y;
        this.z += v.z;

        return this;

    },

    addScalar: function ( s ) {

        this.x += s;
        this.y += s;
        this.z += s;

        return this;

    },

    sub: function ( a, b ) {

        this.x = a.x - b.x;
        this.y = a.y - b.y;
        this.z = a.z - b.z;

        return this;

    },

    subSelf: function ( v ) {

        this.x -= v.x;
        this.y -= v.y;
        this.z -= v.z;

        return this;

    },

    multiply: function ( a, b ) {

        this.x = a.x * b.x;
        this.y = a.y * b.y;
        this.z = a.z * b.z;

        return this;

    },

    multiplySelf: function ( v ) {

        this.x *= v.x;
        this.y *= v.y;
        this.z *= v.z;

        return this;

    },

    multiplyScalar: function ( s ) {

        this.x *= s;
        this.y *= s;
        this.z *= s;

        return this;

    },

    divideSelf: function ( v ) {

        this.x /= v.x;
        this.y /= v.y;
        this.z /= v.z;

        return this;

    },

    divideScalar: function ( s ) {

        if ( s ) {

            this.x /= s;
            this.y /= s;
            this.z /= s;

        } else {

            this.x = 0;
            this.y = 0;
            this.z = 0;

        }

        return this;

    },


    negate: function() {

        return this.multiplyScalar( - 1 );

    },

    dot: function ( v ) {

        return this.x * v.x + this.y * v.y + this.z * v.z;

    },

    lengthSq: function () {

        return this.x * this.x + this.y * this.y + this.z * this.z;

    },

    length: function () {

        return Math.sqrt( this.lengthSq() );

    },

    lengthManhattan: function () {

        return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );

    },

    normalize: function () {

        return this.divideScalar( this.length() );

    },

    setLength: function ( l ) {

        return this.normalize().multiplyScalar( l );

    },

    lerpSelf: function ( v, alpha ) {

        this.x += ( v.x - this.x ) * alpha;
        this.y += ( v.y - this.y ) * alpha;
        this.z += ( v.z - this.z ) * alpha;

        return this;

    },

    cross: function ( a, b ) {

        this.x = a.y * b.z - a.z * b.y;
        this.y = a.z * b.x - a.x * b.z;
        this.z = a.x * b.y - a.y * b.x;

        return this;

    },

    crossSelf: function ( v ) {

        var x = this.x, y = this.y, z = this.z;

        this.x = y * v.z - z * v.y;
        this.y = z * v.x - x * v.z;
        this.z = x * v.y - y * v.x;

        return this;

    },

    distanceTo: function ( v ) {

        return Math.sqrt( this.distanceToSquared( v ) );

    },

    distanceToSquared: function ( v ) {

        return new THREE.Vector3().sub( this, v ).lengthSq();

    },

    getPositionFromMatrix: function ( m ) {

        this.x = m.elements[12];
        this.y = m.elements[13];
        this.z = m.elements[14];

        return this;

    },

    setEulerFromRotationMatrix: function ( m, order ) {

        // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

        // clamp, to handle numerical problems

        function clamp( x ) {

            return Math.min( Math.max( x, -1 ), 1 );

        }

        var te = m.elements;
        var m11 = te[0], m12 = te[4], m13 = te[8];
        var m21 = te[1], m22 = te[5], m23 = te[9];
        var m31 = te[2], m32 = te[6], m33 = te[10];

        if ( order === undefined || order === 'XYZ' ) {

            this.y = Math.asin( clamp( m13 ) );

            if ( Math.abs( m13 ) < 0.99999 ) {

                this.x = Math.atan2( - m23, m33 );
                this.z = Math.atan2( - m12, m11 );

            } else {

                this.x = Math.atan2( m32, m22 );
                this.z = 0;

            }

        } else if ( order === 'YXZ' ) {

            this.x = Math.asin( - clamp( m23 ) );

            if ( Math.abs( m23 ) < 0.99999 ) {

                this.y = Math.atan2( m13, m33 );
                this.z = Math.atan2( m21, m22 );

            } else {

                this.y = Math.atan2( - m31, m11 );
                this.z = 0;

            }

        } else if ( order === 'ZXY' ) {

            this.x = Math.asin( clamp( m32 ) );

            if ( Math.abs( m32 ) < 0.99999 ) {

                this.y = Math.atan2( - m31, m33 );
                this.z = Math.atan2( - m12, m22 );

            } else {

                this.y = 0;
                this.z = Math.atan2( m21, m11 );

            }

        } else if ( order === 'ZYX' ) {

            this.y = Math.asin( - clamp( m31 ) );

            if ( Math.abs( m31 ) < 0.99999 ) {

                this.x = Math.atan2( m32, m33 );
                this.z = Math.atan2( m21, m11 );

            } else {

                this.x = 0;
                this.z = Math.atan2( - m12, m22 );

            }

        } else if ( order === 'YZX' ) {

            this.z = Math.asin( clamp( m21 ) );

            if ( Math.abs( m21 ) < 0.99999 ) {

                this.x = Math.atan2( - m23, m22 );
                this.y = Math.atan2( - m31, m11 );

            } else {

                this.x = 0;
                this.y = Math.atan2( m13, m33 );

            }

        } else if ( order === 'XZY' ) {

            this.z = Math.asin( - clamp( m12 ) );

            if ( Math.abs( m12 ) < 0.99999 ) {

                this.x = Math.atan2( m32, m22 );
                this.y = Math.atan2( m13, m11 );

            } else {

                this.x = Math.atan2( - m23, m33 );
                this.y = 0;

            }

        }

        return this;

    },

    setEulerFromQuaternion: function ( q, order ) {

        // q is assumed to be normalized

        // clamp, to handle numerical problems

        function clamp( x ) {

            return Math.min( Math.max( x, -1 ), 1 );

        }

        // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m

        var sqx = q.x * q.x;
        var sqy = q.y * q.y;
        var sqz = q.z * q.z;
        var sqw = q.w * q.w;

        if ( order === undefined || order === 'XYZ' ) {

            this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
            this.y = Math.asin(  clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
            this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );

        } else if ( order ===  'YXZ' ) {

            this.x = Math.asin(  clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
            this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
            this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );

        } else if ( order === 'ZXY' ) {

            this.x = Math.asin(  clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
            this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
            this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );

        } else if ( order === 'ZYX' ) {

            this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
            this.y = Math.asin(  clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
            this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );

        } else if ( order === 'YZX' ) {

            this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
            this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
            this.z = Math.asin(  clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );

        } else if ( order === 'XZY' ) {

            this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
            this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
            this.z = Math.asin(  clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );

        }

        return this;

    },

    getScaleFromMatrix: function ( m ) {

        var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
        var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
        var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();

        this.x = sx;
        this.y = sy;
        this.z = sz;

        return this;
    },

    equals: function ( v ) {

        return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );

    },

    isZero: function () {

        return ( this.lengthSq() < 0.0001 /* almostZero */ );

    },

    clone: function () {

        return new THREE.Vector3( this.x, this.y, this.z );

    }

};

/**
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author philogb / http://blog.thejit.org/
 * @author mikael emtinger / http://gomo.se/
 * @author egraether / http://egraether.com/
 * @author WestLangley / http://github.com/WestLangley
 */

THREE.Vector4 = function ( x, y, z, w ) {

    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;
    this.w = ( w !== undefined ) ? w : 1;

};

THREE.Vector4.prototype = {

    constructor: THREE.Vector4,

    set: function ( x, y, z, w ) {

        this.x = x;
        this.y = y;
        this.z = z;
        this.w = w;

        return this;

    },

    copy: function ( v ) {

        this.x = v.x;
        this.y = v.y;
        this.z = v.z;
        this.w = ( v.w !== undefined ) ? v.w : 1;

        return this;

    },

    add: function ( a, b ) {

        this.x = a.x + b.x;
        this.y = a.y + b.y;
        this.z = a.z + b.z;
        this.w = a.w + b.w;

        return this;

    },

    addSelf: function ( v ) {

        this.x += v.x;
        this.y += v.y;
        this.z += v.z;
        this.w += v.w;

        return this;

    },

    sub: function ( a, b ) {

        this.x = a.x - b.x;
        this.y = a.y - b.y;
        this.z = a.z - b.z;
        this.w = a.w - b.w;

        return this;

    },

    subSelf: function ( v ) {

        this.x -= v.x;
        this.y -= v.y;
        this.z -= v.z;
        this.w -= v.w;

        return this;

    },

    multiplyScalar: function ( s ) {

        this.x *= s;
        this.y *= s;
        this.z *= s;
        this.w *= s;

        return this;

    },

    divideScalar: function ( s ) {

        if ( s ) {

            this.x /= s;
            this.y /= s;
            this.z /= s;
            this.w /= s;

        } else {

            this.x = 0;
            this.y = 0;
            this.z = 0;
            this.w = 1;

        }

        return this;

    },


    negate: function() {

        return this.multiplyScalar( -1 );

    },

    dot: function ( v ) {

        return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;

    },

    lengthSq: function () {

        return this.dot( this );

    },

    length: function () {

        return Math.sqrt( this.lengthSq() );

    },

    lengthManhattan: function () {

        return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );

    },

    normalize: function () {

        return this.divideScalar( this.length() );

    },

    setLength: function ( l ) {

        return this.normalize().multiplyScalar( l );

    },

    lerpSelf: function ( v, alpha ) {

        this.x += ( v.x - this.x ) * alpha;
        this.y += ( v.y - this.y ) * alpha;
        this.z += ( v.z - this.z ) * alpha;
        this.w += ( v.w - this.w ) * alpha;

        return this;

    },

    clone: function () {

        return new THREE.Vector4( this.x, this.y, this.z, this.w );

    },

    setAxisAngleFromQuaternion: function ( q ) {

        // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm

        // q is assumed to be normalized

        this.w = 2 * Math.acos( q.w );

        var s = Math.sqrt( 1 - q.w * q.w );

        if ( s < 0.0001 ) {

             this.x = 1;
             this.y = 0;
             this.z = 0;

        } else {

             this.x = q.x / s;
             this.y = q.y / s;
             this.z = q.z / s;

        }

        return this;

    },

    setAxisAngleFromRotationMatrix: function ( m ) {

        // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm

        // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

        var angle, x, y, z,        // variables for result
            epsilon = 0.01,        // margin to allow for rounding errors
            epsilon2 = 0.1,        // margin to distinguish between 0 and 180 degrees

            te = m.elements,

            m11 = te[0], m12 = te[4], m13 = te[8],
            m21 = te[1], m22 = te[5], m23 = te[9],
            m31 = te[2], m32 = te[6], m33 = te[10];

        if ( ( Math.abs( m12 - m21 ) < epsilon )
          && ( Math.abs( m13 - m31 ) < epsilon )
          && ( Math.abs( m23 - m32 ) < epsilon ) ) {

            // singularity found
            // first check for identity matrix which must have +1 for all terms
            // in leading diagonal and zero in other terms

            if ( ( Math.abs( m12 + m21 ) < epsilon2 )
              && ( Math.abs( m13 + m31 ) < epsilon2 )
              && ( Math.abs( m23 + m32 ) < epsilon2 )
              && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {

                // this singularity is identity matrix so angle = 0

                this.set( 1, 0, 0, 0 );

                return this; // zero angle, arbitrary axis

            }

            // otherwise this singularity is angle = 180

            angle = Math.PI;

            var xx = ( m11 + 1 ) / 2;
            var yy = ( m22 + 1 ) / 2;
            var zz = ( m33 + 1 ) / 2;
            var xy = ( m12 + m21 ) / 4;
            var xz = ( m13 + m31 ) / 4;
            var yz = ( m23 + m32 ) / 4;

            if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term

                if ( xx < epsilon ) {

                    x = 0;
                    y = 0.707106781;
                    z = 0.707106781;

                } else {

                    x = Math.sqrt( xx );
                    y = xy / x;
                    z = xz / x;

                }

            } else if ( yy > zz ) { // m22 is the largest diagonal term

                if ( yy < epsilon ) {

                    x = 0.707106781;
                    y = 0;
                    z = 0.707106781;

                } else {

                    y = Math.sqrt( yy );
                    x = xy / y;
                    z = yz / y;

                }

            } else { // m33 is the largest diagonal term so base result on this

                if ( zz < epsilon ) {

                    x = 0.707106781;
                    y = 0.707106781;
                    z = 0;

                } else {

                    z = Math.sqrt( zz );
                    x = xz / z;
                    y = yz / z;

                }

            }

            this.set( x, y, z, angle );

            return this; // return 180 deg rotation

        }

        // as we have reached here there are no singularities so we can handle normally

        var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
                         + ( m13 - m31 ) * ( m13 - m31 )
                         + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize

        if ( Math.abs( s ) < 0.001 ) s = 1;

        // prevent divide by zero, should not happen if matrix is orthogonal and should be
        // caught by singularity test above, but I've left it in just in case

        this.x = ( m32 - m23 ) / s;
        this.y = ( m13 - m31 ) / s;
        this.z = ( m21 - m12 ) / s;
        this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );

        return this;

    }

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Matrix3 = function () {

    this.elements = new Float32Array(9);

};

THREE.Matrix3.prototype = {

    constructor: THREE.Matrix3,

    getInverse: function ( matrix ) {

        // input: THREE.Matrix4
        // ( based on http://code.google.com/p/webgl-mjs/ )

        var me = matrix.elements;

        var a11 =   me[10] * me[5] - me[6] * me[9];
        var a21 = - me[10] * me[1] + me[2] * me[9];
        var a31 =   me[6] * me[1] - me[2] * me[5];
        var a12 = - me[10] * me[4] + me[6] * me[8];
        var a22 =   me[10] * me[0] - me[2] * me[8];
        var a32 = - me[6] * me[0] + me[2] * me[4];
        var a13 =   me[9] * me[4] - me[5] * me[8];
        var a23 = - me[9] * me[0] + me[1] * me[8];
        var a33 =   me[5] * me[0] - me[1] * me[4];

        var det = me[0] * a11 + me[1] * a12 + me[2] * a13;

        // no inverse

        if ( det === 0 ) {

            console.warn( "Matrix3.getInverse(): determinant == 0" );

        }

        var idet = 1.0 / det;

        var m = this.elements;

        m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
        m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
        m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;

        return this;

    },


    transpose: function () {

        var tmp, m = this.elements;

        tmp = m[1]; m[1] = m[3]; m[3] = tmp;
        tmp = m[2]; m[2] = m[6]; m[6] = tmp;
        tmp = m[5]; m[5] = m[7]; m[7] = tmp;

        return this;

    },


    transposeIntoArray: function ( r ) {

        var m = this.m;

        r[ 0 ] = m[ 0 ];
        r[ 1 ] = m[ 3 ];
        r[ 2 ] = m[ 6 ];
        r[ 3 ] = m[ 1 ];
        r[ 4 ] = m[ 4 ];
        r[ 5 ] = m[ 7 ];
        r[ 6 ] = m[ 2 ];
        r[ 7 ] = m[ 5 ];
        r[ 8 ] = m[ 8 ];

        return this;

    }

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author philogb / http://blog.thejit.org/
 * @author jordi_ros / http://plattsoft.com
 * @author D1plo1d / http://github.com/D1plo1d
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 * @author timknip / http://www.floorplanner.com/
 */


THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {

    this.elements = new Float32Array( 16 );

    this.set(

        ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
        n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
        n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
        n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1

    );

};

THREE.Matrix4.prototype = {

    constructor: THREE.Matrix4,

    set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {

        var te = this.elements;

        te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
        te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
        te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
        te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;

        return this;

    },

    identity: function () {

        this.set(

            1, 0, 0, 0,
            0, 1, 0, 0,
            0, 0, 1, 0,
            0, 0, 0, 1

        );

        return this;

    },

    copy: function ( m ) {

        var me = m.elements;

        this.set(

            me[0], me[4], me[8], me[12],
            me[1], me[5], me[9], me[13],
            me[2], me[6], me[10], me[14],
            me[3], me[7], me[11], me[15]

        );

        return this;

    },

    lookAt: function ( eye, target, up ) {

        var te = this.elements;

        var x = THREE.Matrix4.__v1;
        var y = THREE.Matrix4.__v2;
        var z = THREE.Matrix4.__v3;

        z.sub( eye, target ).normalize();

        if ( z.length() === 0 ) {

            z.z = 1;

        }

        x.cross( up, z ).normalize();

        if ( x.length() === 0 ) {

            z.x += 0.0001;
            x.cross( up, z ).normalize();

        }

        y.cross( z, x );


        te[0] = x.x; te[4] = y.x; te[8] = z.x;
        te[1] = x.y; te[5] = y.y; te[9] = z.y;
        te[2] = x.z; te[6] = y.z; te[10] = z.z;

        return this;

    },

    multiply: function ( a, b ) {

        var ae = a.elements;
        var be = b.elements;
        var te = this.elements;

        var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
        var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
        var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
        var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];

        var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
        var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
        var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
        var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];

        te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
        te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
        te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
        te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;

        te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
        te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
        te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
        te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;

        te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
        te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
        te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
        te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;

        te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
        te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
        te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
        te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;

        return this;

    },

    multiplySelf: function ( m ) {

        return this.multiply( this, m );

    },

    multiplyToArray: function ( a, b, r ) {

        var te = this.elements;

        this.multiply( a, b );

        r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
        r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
        r[ 8 ]  = te[8]; r[ 9 ]  = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
        r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];

        return this;

    },

    multiplyScalar: function ( s ) {

        var te = this.elements;

        te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
        te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
        te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
        te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;

        return this;

    },

    multiplyVector3: function ( v ) {

        var te = this.elements;

        var vx = v.x, vy = v.y, vz = v.z;
        var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );

        v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
        v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
        v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;

        return v;

    },

    multiplyVector4: function ( v ) {

        var te = this.elements;
        var vx = v.x, vy = v.y, vz = v.z, vw = v.w;

        v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
        v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
        v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
        v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;

        return v;

    },

    multiplyVector3Array: function ( a ) {

        var tmp = THREE.Matrix4.__v1;

        for ( var i = 0, il = a.length; i < il; i += 3 ) {

            tmp.x = a[ i ];
            tmp.y = a[ i + 1 ];
            tmp.z = a[ i + 2 ];

            this.multiplyVector3( tmp );

            a[ i ]     = tmp.x;
            a[ i + 1 ] = tmp.y;
            a[ i + 2 ] = tmp.z;

        }

        return a;

    },

    rotateAxis: function ( v ) {

        var te = this.elements;
        var vx = v.x, vy = v.y, vz = v.z;

        v.x = vx * te[0] + vy * te[4] + vz * te[8];
        v.y = vx * te[1] + vy * te[5] + vz * te[9];
        v.z = vx * te[2] + vy * te[6] + vz * te[10];

        v.normalize();

        return v;

    },

    crossVector: function ( a ) {

        var te = this.elements;
        var v = new THREE.Vector4();

        v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
        v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
        v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;

        v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;

        return v;

    },

    determinant: function () {

        var te = this.elements;

        var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
        var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
        var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
        var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];

        //TODO: make this more efficient
        //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )

        return (
            n14 * n23 * n32 * n41-
            n13 * n24 * n32 * n41-
            n14 * n22 * n33 * n41+
            n12 * n24 * n33 * n41+

            n13 * n22 * n34 * n41-
            n12 * n23 * n34 * n41-
            n14 * n23 * n31 * n42+
            n13 * n24 * n31 * n42+

            n14 * n21 * n33 * n42-
            n11 * n24 * n33 * n42-
            n13 * n21 * n34 * n42+
            n11 * n23 * n34 * n42+

            n14 * n22 * n31 * n43-
            n12 * n24 * n31 * n43-
            n14 * n21 * n32 * n43+
            n11 * n24 * n32 * n43+

            n12 * n21 * n34 * n43-
            n11 * n22 * n34 * n43-
            n13 * n22 * n31 * n44+
            n12 * n23 * n31 * n44+

            n13 * n21 * n32 * n44-
            n11 * n23 * n32 * n44-
            n12 * n21 * n33 * n44+
            n11 * n22 * n33 * n44
        );

    },

    transpose: function () {

        var te = this.elements;
        var tmp;

        tmp = te[1]; te[1] = te[4]; te[4] = tmp;
        tmp = te[2]; te[2] = te[8]; te[8] = tmp;
        tmp = te[6]; te[6] = te[9]; te[9] = tmp;

        tmp = te[3]; te[3] = te[12]; te[12] = tmp;
        tmp = te[7]; te[7] = te[13]; te[13] = tmp;
        tmp = te[11]; te[11] = te[14]; te[14] = tmp;

        return this;

    },

    flattenToArray: function ( flat ) {

        var te = this.elements;
        flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
        flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
        flat[ 8 ]  = te[8]; flat[ 9 ]  = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
        flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];

        return flat;

    },

    flattenToArrayOffset: function( flat, offset ) {

        var te = this.elements;
        flat[ offset ] = te[0];
        flat[ offset + 1 ] = te[1];
        flat[ offset + 2 ] = te[2];
        flat[ offset + 3 ] = te[3];

        flat[ offset + 4 ] = te[4];
        flat[ offset + 5 ] = te[5];
        flat[ offset + 6 ] = te[6];
        flat[ offset + 7 ] = te[7];

        flat[ offset + 8 ]  = te[8];
        flat[ offset + 9 ]  = te[9];
        flat[ offset + 10 ] = te[10];
        flat[ offset + 11 ] = te[11];

        flat[ offset + 12 ] = te[12];
        flat[ offset + 13 ] = te[13];
        flat[ offset + 14 ] = te[14];
        flat[ offset + 15 ] = te[15];

        return flat;

    },

    getPosition: function () {

        var te = this.elements;
        return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );

    },

    setPosition: function ( v ) {

        var te = this.elements;

        te[12] = v.x;
        te[13] = v.y;
        te[14] = v.z;

        return this;

    },

    getColumnX: function () {

        var te = this.elements;
        return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );

    },

    getColumnY: function () {

        var te = this.elements;
        return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );

    },

    getColumnZ: function() {

        var te = this.elements;
        return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );

    },

    getInverse: function ( m ) {

        // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
        var te = this.elements;
        var me = m.elements;

        var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
        var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
        var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
        var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];

        te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
        te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
        te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
        te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
        te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
        te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
        te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
        te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
        te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
        te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
        te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
        te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
        te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
        te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
        te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
        te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
        this.multiplyScalar( 1 / m.determinant() );

        return this;

    },

    setRotationFromEuler: function ( v, order ) {

        var te = this.elements;

        var x = v.x, y = v.y, z = v.z;
        var a = Math.cos( x ), b = Math.sin( x );
        var c = Math.cos( y ), d = Math.sin( y );
        var e = Math.cos( z ), f = Math.sin( z );

        if ( order === undefined || order === 'XYZ' ) {

            var ae = a * e, af = a * f, be = b * e, bf = b * f;

            te[0] = c * e;
            te[4] = - c * f;
            te[8] = d;

            te[1] = af + be * d;
            te[5] = ae - bf * d;
            te[9] = - b * c;

            te[2] = bf - ae * d;
            te[6] = be + af * d;
            te[10] = a * c;

        } else if ( order === 'YXZ' ) {

            var ce = c * e, cf = c * f, de = d * e, df = d * f;

            te[0] = ce + df * b;
            te[4] = de * b - cf;
            te[8] = a * d;

            te[1] = a * f;
            te[5] = a * e;
            te[9] = - b;

            te[2] = cf * b - de;
            te[6] = df + ce * b;
            te[10] = a * c;

        } else if ( order === 'ZXY' ) {

            var ce = c * e, cf = c * f, de = d * e, df = d * f;

            te[0] = ce - df * b;
            te[4] = - a * f;
            te[8] = de + cf * b;

            te[1] = cf + de * b;
            te[5] = a * e;
            te[9] = df - ce * b;

            te[2] = - a * d;
            te[6] = b;
            te[10] = a * c;

        } else if ( order === 'ZYX' ) {

            var ae = a * e, af = a * f, be = b * e, bf = b * f;

            te[0] = c * e;
            te[4] = be * d - af;
            te[8] = ae * d + bf;

            te[1] = c * f;
            te[5] = bf * d + ae;
            te[9] = af * d - be;

            te[2] = - d;
            te[6] = b * c;
            te[10] = a * c;

        } else if ( order === 'YZX' ) {

            var ac = a * c, ad = a * d, bc = b * c, bd = b * d;

            te[0] = c * e;
            te[4] = bd - ac * f;
            te[8] = bc * f + ad;

            te[1] = f;
            te[5] = a * e;
            te[9] = - b * e;

            te[2] = - d * e;
            te[6] = ad * f + bc;
            te[10] = ac - bd * f;

        } else if ( order === 'XZY' ) {

            var ac = a * c, ad = a * d, bc = b * c, bd = b * d;

            te[0] = c * e;
            te[4] = - f;
            te[8] = d * e;

            te[1] = ac * f + bd;
            te[5] = a * e;
            te[9] = ad * f - bc;

            te[2] = bc * f - ad;
            te[6] = b * e;
            te[10] = bd * f + ac;

        }

        return this;

    },


    setRotationFromQuaternion: function ( q ) {

        var te = this.elements;

        var x = q.x, y = q.y, z = q.z, w = q.w;
        var x2 = x + x, y2 = y + y, z2 = z + z;
        var xx = x * x2, xy = x * y2, xz = x * z2;
        var yy = y * y2, yz = y * z2, zz = z * z2;
        var wx = w * x2, wy = w * y2, wz = w * z2;

        te[0] = 1 - ( yy + zz );
        te[4] = xy - wz;
        te[8] = xz + wy;

        te[1] = xy + wz;
        te[5] = 1 - ( xx + zz );
        te[9] = yz - wx;

        te[2] = xz - wy;
        te[6] = yz + wx;
        te[10] = 1 - ( xx + yy );

        return this;

    },

    compose: function ( translation, rotation, scale ) {

        var te = this.elements;
        var mRotation = THREE.Matrix4.__m1;
        var mScale = THREE.Matrix4.__m2;

        mRotation.identity();
        mRotation.setRotationFromQuaternion( rotation );

        mScale.makeScale( scale.x, scale.y, scale.z );

        this.multiply( mRotation, mScale );

        te[12] = translation.x;
        te[13] = translation.y;
        te[14] = translation.z;

        return this;

    },

    decompose: function ( translation, rotation, scale ) {

        var te = this.elements;

        // grab the axis vectors
        var x = THREE.Matrix4.__v1;
        var y = THREE.Matrix4.__v2;
        var z = THREE.Matrix4.__v3;

        x.set( te[0], te[1], te[2] );
        y.set( te[4], te[5], te[6] );
        z.set( te[8], te[9], te[10] );

        translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
        rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
        scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();

        scale.x = x.length();
        scale.y = y.length();
        scale.z = z.length();

        translation.x = te[12];
        translation.y = te[13];
        translation.z = te[14];

        // scale the rotation part

        var matrix = THREE.Matrix4.__m1;

        matrix.copy( this );

        matrix.elements[0] /= scale.x;
        matrix.elements[1] /= scale.x;
        matrix.elements[2] /= scale.x;

        matrix.elements[4] /= scale.y;
        matrix.elements[5] /= scale.y;
        matrix.elements[6] /= scale.y;

        matrix.elements[8] /= scale.z;
        matrix.elements[9] /= scale.z;
        matrix.elements[10] /= scale.z;

        rotation.setFromRotationMatrix( matrix );

        return [ translation, rotation, scale ];

    },

    extractPosition: function ( m ) {

        var te = this.elements;
        var me = m.elements;

        te[12] = me[12];
        te[13] = me[13];
        te[14] = me[14];

        return this;

    },

    extractRotation: function ( m ) {

        var te = this.elements;
        var me = m.elements;

        var vector = THREE.Matrix4.__v1;

        var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
        var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
        var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();

        te[0] = me[0] * scaleX;
        te[1] = me[1] * scaleX;
        te[2] = me[2] * scaleX;

        te[4] = me[4] * scaleY;
        te[5] = me[5] * scaleY;
        te[6] = me[6] * scaleY;

        te[8] = me[8] * scaleZ;
        te[9] = me[9] * scaleZ;
        te[10] = me[10] * scaleZ;

        return this;

    },

    //

    translate: function ( v ) {

        var te = this.elements;
        var x = v.x, y = v.y, z = v.z;

        te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
        te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
        te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
        te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];

        return this;

    },

    rotateX: function ( angle ) {

        var te = this.elements;
        var m12 = te[4];
        var m22 = te[5];
        var m32 = te[6];
        var m42 = te[7];
        var m13 = te[8];
        var m23 = te[9];
        var m33 = te[10];
        var m43 = te[11];
        var c = Math.cos( angle );
        var s = Math.sin( angle );

        te[4] = c * m12 + s * m13;
        te[5] = c * m22 + s * m23;
        te[6] = c * m32 + s * m33;
        te[7] = c * m42 + s * m43;

        te[8] = c * m13 - s * m12;
        te[9] = c * m23 - s * m22;
        te[10] = c * m33 - s * m32;
        te[11] = c * m43 - s * m42;

        return this;

    },

    rotateY: function ( angle ) {

        var te = this.elements;
        var m11 = te[0];
        var m21 = te[1];
        var m31 = te[2];
        var m41 = te[3];
        var m13 = te[8];
        var m23 = te[9];
        var m33 = te[10];
        var m43 = te[11];
        var c = Math.cos( angle );
        var s = Math.sin( angle );

        te[0] = c * m11 - s * m13;
        te[1] = c * m21 - s * m23;
        te[2] = c * m31 - s * m33;
        te[3] = c * m41 - s * m43;

        te[8] = c * m13 + s * m11;
        te[9] = c * m23 + s * m21;
        te[10] = c * m33 + s * m31;
        te[11] = c * m43 + s * m41;

        return this;

    },

    rotateZ: function ( angle ) {

        var te = this.elements;
        var m11 = te[0];
        var m21 = te[1];
        var m31 = te[2];
        var m41 = te[3];
        var m12 = te[4];
        var m22 = te[5];
        var m32 = te[6];
        var m42 = te[7];
        var c = Math.cos( angle );
        var s = Math.sin( angle );

        te[0] = c * m11 + s * m12;
        te[1] = c * m21 + s * m22;
        te[2] = c * m31 + s * m32;
        te[3] = c * m41 + s * m42;

        te[4] = c * m12 - s * m11;
        te[5] = c * m22 - s * m21;
        te[6] = c * m32 - s * m31;
        te[7] = c * m42 - s * m41;

        return this;

    },

    rotateByAxis: function ( axis, angle ) {

        var te = this.elements;

        // optimize by checking axis

        if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {

            return this.rotateX( angle );

        } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {

            return this.rotateY( angle );

        } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {

            return this.rotateZ( angle );

        }

        var x = axis.x, y = axis.y, z = axis.z;
        var n = Math.sqrt(x * x + y * y + z * z);

        x /= n;
        y /= n;
        z /= n;

        var xx = x * x, yy = y * y, zz = z * z;
        var c = Math.cos( angle );
        var s = Math.sin( angle );
        var oneMinusCosine = 1 - c;
        var xy = x * y * oneMinusCosine;
        var xz = x * z * oneMinusCosine;
        var yz = y * z * oneMinusCosine;
        var xs = x * s;
        var ys = y * s;
        var zs = z * s;

        var r11 = xx + (1 - xx) * c;
        var r21 = xy + zs;
        var r31 = xz - ys;
        var r12 = xy - zs;
        var r22 = yy + (1 - yy) * c;
        var r32 = yz + xs;
        var r13 = xz + ys;
        var r23 = yz - xs;
        var r33 = zz + (1 - zz) * c;

        var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
        var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
        var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
        var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];

        te[0] = r11 * m11 + r21 * m12 + r31 * m13;
        te[1] = r11 * m21 + r21 * m22 + r31 * m23;
        te[2] = r11 * m31 + r21 * m32 + r31 * m33;
        te[3] = r11 * m41 + r21 * m42 + r31 * m43;

        te[4] = r12 * m11 + r22 * m12 + r32 * m13;
        te[5] = r12 * m21 + r22 * m22 + r32 * m23;
        te[6] = r12 * m31 + r22 * m32 + r32 * m33;
        te[7] = r12 * m41 + r22 * m42 + r32 * m43;

        te[8] = r13 * m11 + r23 * m12 + r33 * m13;
        te[9] = r13 * m21 + r23 * m22 + r33 * m23;
        te[10] = r13 * m31 + r23 * m32 + r33 * m33;
        te[11] = r13 * m41 + r23 * m42 + r33 * m43;

        return this;

    },

    scale: function ( v ) {

        var te = this.elements;
        var x = v.x, y = v.y, z = v.z;

        te[0] *= x; te[4] *= y; te[8] *= z;
        te[1] *= x; te[5] *= y; te[9] *= z;
        te[2] *= x; te[6] *= y; te[10] *= z;
        te[3] *= x; te[7] *= y; te[11] *= z;

        return this;

    },

    getMaxScaleOnAxis: function () {

        var te = this.elements;

        var scaleXSq =  te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
        var scaleYSq =  te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
        var scaleZSq =  te[8] * te[8] + te[9] * te[9] + te[10] * te[10];

        return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );

    },

    //

    makeTranslation: function ( x, y, z ) {

        this.set(

            1, 0, 0, x,
            0, 1, 0, y,
            0, 0, 1, z,
            0, 0, 0, 1

        );

        return this;

    },

    makeRotationX: function ( theta ) {

        var c = Math.cos( theta ), s = Math.sin( theta );

        this.set(

            1, 0,  0, 0,
            0, c, -s, 0,
            0, s,  c, 0,
            0, 0,  0, 1

        );

        return this;

    },

    makeRotationY: function ( theta ) {

        var c = Math.cos( theta ), s = Math.sin( theta );

        this.set(

             c, 0, s, 0,
             0, 1, 0, 0,
            -s, 0, c, 0,
             0, 0, 0, 1

        );

        return this;

    },

    makeRotationZ: function ( theta ) {

        var c = Math.cos( theta ), s = Math.sin( theta );

        this.set(

            c, -s, 0, 0,
            s,  c, 0, 0,
            0,  0, 1, 0,
            0,  0, 0, 1

        );

        return this;

    },

    makeRotationAxis: function ( axis, angle ) {

        // Based on http://www.gamedev.net/reference/articles/article1199.asp

        var c = Math.cos( angle );
        var s = Math.sin( angle );
        var t = 1 - c;
        var x = axis.x, y = axis.y, z = axis.z;
        var tx = t * x, ty = t * y;

        this.set(

            tx * x + c, tx * y - s * z, tx * z + s * y, 0,
            tx * y + s * z, ty * y + c, ty * z - s * x, 0,
            tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
            0, 0, 0, 1

        );

         return this;

    },

    makeScale: function ( x, y, z ) {

        this.set(

            x, 0, 0, 0,
            0, y, 0, 0,
            0, 0, z, 0,
            0, 0, 0, 1

        );

        return this;

    },

    makeFrustum: function ( left, right, bottom, top, near, far ) {

        var te = this.elements;
        var x = 2 * near / ( right - left );
        var y = 2 * near / ( top - bottom );

        var a = ( right + left ) / ( right - left );
        var b = ( top + bottom ) / ( top - bottom );
        var c = - ( far + near ) / ( far - near );
        var d = - 2 * far * near / ( far - near );

        te[0] = x;  te[4] = 0;  te[8] = a;   te[12] = 0;
        te[1] = 0;  te[5] = y;  te[9] = b;   te[13] = 0;
        te[2] = 0;  te[6] = 0;  te[10] = c;   te[14] = d;
        te[3] = 0;  te[7] = 0;  te[11] = - 1; te[15] = 0;

        return this;

    },

    makePerspective: function ( fov, aspect, near, far ) {

        var ymax = near * Math.tan( fov * Math.PI / 360 );
        var ymin = - ymax;
        var xmin = ymin * aspect;
        var xmax = ymax * aspect;

        return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );

    },

    makeOrthographic: function ( left, right, top, bottom, near, far ) {

        var te = this.elements;
        var w = right - left;
        var h = top - bottom;
        var p = far - near;

        var x = ( right + left ) / w;
        var y = ( top + bottom ) / h;
        var z = ( far + near ) / p;

        te[0] = 2 / w; te[4] = 0;     te[8] = 0;      te[12] = -x;
        te[1] = 0;     te[5] = 2 / h; te[9] = 0;      te[13] = -y;
        te[2] = 0;     te[6] = 0;     te[10] = -2 / p; te[14] = -z;
        te[3] = 0;     te[7] = 0;     te[11] = 0;      te[15] = 1;

        return this;

    },


    clone: function () {

        var te = this.elements;

        return new THREE.Matrix4(

            te[0], te[4], te[8], te[12],
            te[1], te[5], te[9], te[13],
            te[2], te[6], te[10], te[14],
            te[3], te[7], te[11], te[15]

        );

    }

};

THREE.Matrix4.__v1 = new THREE.Vector3();
THREE.Matrix4.__v2 = new THREE.Vector3();
THREE.Matrix4.__v3 = new THREE.Vector3();

THREE.Matrix4.__m1 = new THREE.Matrix4();
THREE.Matrix4.__m2 = new THREE.Matrix4();
/**
 * https://github.com/mrdoob/eventtarget.js/
 */

THREE.EventTarget = function () {

    var listeners = {};

    this.addEventListener = function ( type, listener ) {

        if ( listeners[ type ] === undefined ) {

            listeners[ type ] = [];

        }

        if ( listeners[ type ].indexOf( listener ) === - 1 ) {

            listeners[ type ].push( listener );

        }

    };

    this.dispatchEvent = function ( event ) {

        for ( var listener in listeners[ event.type ] ) {

            listeners[ event.type ][ listener ]( event );

        }

    };

    this.removeEventListener = function ( type, listener ) {

        var index = listeners[ type ].indexOf( listener );

        if ( index !== - 1 ) {

            listeners[ type ].splice( index, 1 );

        }

    };

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Frustum = function ( ) {

    this.planes = [

        new THREE.Vector4(),
        new THREE.Vector4(),
        new THREE.Vector4(),
        new THREE.Vector4(),
        new THREE.Vector4(),
        new THREE.Vector4()

    ];

};

THREE.Frustum.prototype.setFromMatrix = function ( m ) {

    var plane;
    var planes = this.planes;

    var me = m.elements;
    var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
    var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
    var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
    var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];

    planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
    planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
    planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
    planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
    planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
    planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );

    for ( var i = 0; i < 6; i ++ ) {

        plane = planes[ i ];
        plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );

    }

};

THREE.Frustum.prototype.contains = function ( object ) {

    var distance = 0.0;
    var planes = this.planes;
    var matrix = object.matrixWorld;
    var me = matrix.elements;
    var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();

    for ( var i = 0; i < 6; i ++ ) {

        distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
        if ( distance <= radius ) return false;

    }

    return true;

};

THREE.Frustum.__v1 = new THREE.Vector3();
/**
 * @author mrdoob / http://mrdoob.com/
 */

( function ( THREE ) {

    THREE.Ray = function ( origin, direction, near, far ) {

        this.origin = origin || new THREE.Vector3();
        this.direction = direction || new THREE.Vector3();
        this.near = near || 0;
        this.far = far || Infinity;

    };

    var originCopy = new THREE.Vector3();

    var localOriginCopy = new THREE.Vector3();
    var localDirectionCopy = new THREE.Vector3();

    var vector = new THREE.Vector3();
    var normal = new THREE.Vector3();
    var intersectPoint = new THREE.Vector3();

    var inverseMatrix = new THREE.Matrix4();

    var descSort = function ( a, b ) {

        return a.distance - b.distance;

    };

    var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();

    var distanceFromIntersection = function ( origin, direction, position ) {

        v0.sub( position, origin );

        var dot = v0.dot( direction );

        var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
        var distance = position.distanceTo( intersect );

        return distance;

    };

    // http://www.blackpawn.com/texts/pointinpoly/default.html

    var pointInFace3 = function ( p, a, b, c ) {

        v0.sub( c, a );
        v1.sub( b, a );
        v2.sub( p, a );

        var dot00 = v0.dot( v0 );
        var dot01 = v0.dot( v1 );
        var dot02 = v0.dot( v2 );
        var dot11 = v1.dot( v1 );
        var dot12 = v1.dot( v2 );

        var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
        var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
        var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;

        return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );

    };

    var intersectObject = function ( object, ray, intersects ) {

        var distance,intersect;

        if ( object instanceof THREE.Particle ) {

            distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );

            if ( distance > object.scale.x ) {

                return intersects;

            }

            intersect = {

                distance: distance,
                point: object.position,
                face: null,
                object: object

            };

            intersects.push( intersect );

        } else if ( object instanceof THREE.Mesh ) {

            // Checking boundingSphere

            var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();

            // Checking distance to ray

            distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );

            if ( distance > scaledRadius) {

                return intersects;

            }

            // Checking faces

            var f, fl, face, dot, scalar,
            geometry = object.geometry,
            vertices = geometry.vertices,
            objMatrix, geometryMaterials,
            isFaceMaterial, material, side, point;

            geometryMaterials = object.geometry.materials;
            isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
            side = object.material.side;

            var a, b, c, d;
            var precision = ray.precision;

            object.matrixRotationWorld.extractRotation( object.matrixWorld );

            originCopy.copy( ray.origin );

            objMatrix = object.matrixWorld;
            inverseMatrix.getInverse( objMatrix );

            localOriginCopy.copy( originCopy );
            inverseMatrix.multiplyVector3( localOriginCopy );

            localDirectionCopy.copy( ray.direction );
            inverseMatrix.rotateAxis( localDirectionCopy ).normalize();

            for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {

                face = geometry.faces[ f ];

                material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
                if ( material === undefined ) continue;
                side = material.side;

                vector.sub( face.centroid, localOriginCopy );
                normal = face.normal;
                dot = localDirectionCopy.dot( normal );

                // bail if ray and plane are parallel

                if ( Math.abs( dot ) < precision ) continue;

                // calc distance to plane

                scalar = normal.dot( vector ) / dot;

                // if negative distance, then plane is behind ray

                if ( scalar < 0 ) continue;

                if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {

                    intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );

                    if ( face instanceof THREE.Face3 ) {

                        a = vertices[ face.a ];
                        b = vertices[ face.b ];
                        c = vertices[ face.c ];

                        if ( pointInFace3( intersectPoint, a, b, c ) ) {

                            point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
                            distance = originCopy.distanceTo( point );

                            if ( distance < ray.near || distance > ray.far ) continue;

                            intersect = {

                                distance: distance,
                                point: point,
                                face: face,
                                faceIndex: f,
                                object: object

                            };

                            intersects.push( intersect );

                        }

                    } else if ( face instanceof THREE.Face4 ) {

                        a = vertices[ face.a ];
                        b = vertices[ face.b ];
                        c = vertices[ face.c ];
                        d = vertices[ face.d ];

                        if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {

                            point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
                            distance = originCopy.distanceTo( point );

                            if ( distance < ray.near || distance > ray.far ) continue;

                            intersect = {

                                distance: distance,
                                point: point,
                                face: face,
                                faceIndex: f,
                                object: object

                            };

                            intersects.push( intersect );

                        }

                    }

                }

            }

        }

    };

    var intersectDescendants = function ( object, ray, intersects ) {

        var descendants = object.getDescendants();

        for ( var i = 0, l = descendants.length; i < l; i ++ ) {

            intersectObject( descendants[ i ], ray, intersects );

        }
    };

    //

    THREE.Ray.prototype.precision = 0.0001;

    THREE.Ray.prototype.set = function ( origin, direction ) {

        this.origin = origin;
        this.direction = direction;

    };

    THREE.Ray.prototype.intersectObject = function ( object, recursive ) {

        var intersects = [];

        if ( recursive === true ) {

            intersectDescendants( object, this, intersects );

        }

        intersectObject( object, this, intersects );

        intersects.sort( descSort );

        return intersects;

    };

    THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {

        var intersects = [];

        for ( var i = 0, l = objects.length; i < l; i ++ ) {

            intersectObject( objects[ i ], this, intersects );

            if ( recursive === true ) {

                intersectDescendants( objects[ i ], this, intersects );

            }
        }

        intersects.sort( descSort );

        return intersects;

    };

}( THREE ) );
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Rectangle = function () {

    var _left = 0;
    var _top = 0;
    var _right = 0;
    var _bottom = 0;
    var _width = 0;
    var _height = 0;
    var _isEmpty = true;

    function resize() {

        _width = _right - _left;
        _height = _bottom - _top;

    }

    this.getX = function () {

        return _left;

    };

    this.getY = function () {

        return _top;

    };

    this.getWidth = function () {

        return _width;

    };

    this.getHeight = function () {

        return _height;

    };

    this.getLeft = function() {

        return _left;

    };

    this.getTop = function() {

        return _top;

    };

    this.getRight = function() {

        return _right;

    };

    this.getBottom = function() {

        return _bottom;

    };

    this.set = function ( left, top, right, bottom ) {

        _isEmpty = false;

        _left = left; _top = top;
        _right = right; _bottom = bottom;

        resize();

    };

    this.addPoint = function ( x, y ) {

        if ( _isEmpty === true ) {

            _isEmpty = false;
            _left = x; _top = y;
            _right = x; _bottom = y;

            resize();

        } else {

            _left = _left < x ? _left : x; // Math.min( _left, x );
            _top = _top < y ? _top : y; // Math.min( _top, y );
            _right = _right > x ? _right : x; // Math.max( _right, x );
            _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );

            resize();
        }

    };

    this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {

        if ( _isEmpty === true ) {

            _isEmpty = false;
            _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
            _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
            _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
            _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );

            resize();

        } else {

            _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
            _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
            _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
            _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );

            resize();

        };

    };

    this.addRectangle = function ( r ) {

        if ( _isEmpty === true ) {

            _isEmpty = false;
            _left = r.getLeft(); _top = r.getTop();
            _right = r.getRight(); _bottom = r.getBottom();

            resize();

        } else {

            _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
            _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
            _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
            _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );

            resize();

        }

    };

    this.inflate = function ( v ) {

        _left -= v; _top -= v;
        _right += v; _bottom += v;

        resize();

    };

    this.minSelf = function ( r ) {

        _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
        _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
        _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
        _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );

        resize();

    };

    this.intersects = function ( r ) {

        // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/

        if ( _right < r.getLeft() ) return false;
        if ( _left > r.getRight() ) return false;
        if ( _bottom < r.getTop() ) return false;
        if ( _top > r.getBottom() ) return false;

        return true;

    };

    this.empty = function () {

        _isEmpty = true;

        _left = 0; _top = 0;
        _right = 0; _bottom = 0;

        resize();

    };

    this.isEmpty = function () {

        return _isEmpty;

    };

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Math = {

    // Clamp value to range <a, b>

    clamp: function ( x, a, b ) {

        return ( x < a ) ? a : ( ( x > b ) ? b : x );

    },

    // Clamp value to range <a, inf)

    clampBottom: function ( x, a ) {

        return x < a ? a : x;

    },

    // Linear mapping from range <a1, a2> to range <b1, b2>

    mapLinear: function ( x, a1, a2, b1, b2 ) {

        return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );

    },

    // Random float from <0, 1> with 16 bits of randomness
    // (standard Math.random() creates repetitive patterns when applied over larger space)

    random16: function () {

        return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;

    },

    // Random integer from <low, high> interval

    randInt: function ( low, high ) {

        return low + Math.floor( Math.random() * ( high - low + 1 ) );

    },

    // Random float from <low, high> interval

    randFloat: function ( low, high ) {

        return low + Math.random() * ( high - low );

    },

    // Random float from <-range/2, range/2> interval

    randFloatSpread: function ( range ) {

        return range * ( 0.5 - Math.random() );

    },

    sign: function ( x ) {

        return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );

    }

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Object3D = function () {

    this.id = THREE.Object3DCount ++;

    this.name = '';
    this.properties = {};

    this.parent = undefined;
    this.children = [];

    this.up = new THREE.Vector3( 0, 1, 0 );

    this.position = new THREE.Vector3();
    this.rotation = new THREE.Vector3();
    this.eulerOrder = 'XYZ';
    this.scale = new THREE.Vector3( 1, 1, 1 );

    this.renderDepth = null;

    this.rotationAutoUpdate = true;

    this.matrix = new THREE.Matrix4();
    this.matrixWorld = new THREE.Matrix4();
    this.matrixRotationWorld = new THREE.Matrix4();

    this.matrixAutoUpdate = true;
    this.matrixWorldNeedsUpdate = true;

    this.quaternion = new THREE.Quaternion();
    this.useQuaternion = false;

    this.boundRadius = 0.0;
    this.boundRadiusScale = 1.0;

    this.visible = true;

    this.castShadow = false;
    this.receiveShadow = false;

    this.frustumCulled = true;

    this._vector = new THREE.Vector3();

};


THREE.Object3D.prototype = {

    constructor: THREE.Object3D,

    applyMatrix: function ( matrix ) {

        this.matrix.multiply( matrix, this.matrix );

        this.scale.getScaleFromMatrix( this.matrix );

        var mat = new THREE.Matrix4().extractRotation( this.matrix );
        this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );

        this.position.getPositionFromMatrix( this.matrix );

    },

    translate: function ( distance, axis ) {

        this.matrix.rotateAxis( axis );
        this.position.addSelf( axis.multiplyScalar( distance ) );

    },

    translateX: function ( distance ) {

        this.translate( distance, this._vector.set( 1, 0, 0 ) );

    },

    translateY: function ( distance ) {

        this.translate( distance, this._vector.set( 0, 1, 0 ) );

    },

    translateZ: function ( distance ) {

        this.translate( distance, this._vector.set( 0, 0, 1 ) );

    },

    localToWorld: function ( vector ) {

        return this.matrixWorld.multiplyVector3( vector );

    },

    worldToLocal: function ( vector ) {

        return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );

    },

    lookAt: function ( vector ) {

        // TODO: Add hierarchy support.

        this.matrix.lookAt( vector, this.position, this.up );

        if ( this.rotationAutoUpdate ) {

            this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );

        }

    },

    add: function ( object ) {

        if ( object === this ) {

            console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
            return;

        }

        if ( object instanceof THREE.Object3D ) {

            if ( object.parent !== undefined ) {

                object.parent.remove( object );

            }

            object.parent = this;
            this.children.push( object );

            // add to scene

            var scene = this;

            while ( scene.parent !== undefined ) {

                scene = scene.parent;

            }

            if ( scene !== undefined && scene instanceof THREE.Scene )  {

                scene.__addObject( object );

            }

        }

    },

    remove: function ( object ) {

        var index = this.children.indexOf( object );

        if ( index !== - 1 ) {

            object.parent = undefined;
            this.children.splice( index, 1 );

            // remove from scene

            var scene = this;

            while ( scene.parent !== undefined ) {

                scene = scene.parent;

            }

            if ( scene !== undefined && scene instanceof THREE.Scene ) {

                scene.__removeObject( object );

            }

        }

    },

    getChildByName: function ( name, recursive ) {

        var c, cl, child;

        for ( c = 0, cl = this.children.length; c < cl; c ++ ) {

            child = this.children[ c ];

            if ( child.name === name ) {

                return child;

            }

            if ( recursive ) {

                child = child.getChildByName( name, recursive );

                if ( child !== undefined ) {

                    return child;

                }

            }

        }

        return undefined;

    },

    getDescendants: function ( array ) {

        if ( array === undefined ) array = [];

        Array.prototype.push.apply( array, this.children );

        for ( var i = 0, l = this.children.length; i < l; i ++ ) {

            this.children[ i ].getDescendants( array );

        };

        return array;

    },

    updateMatrix: function () {

        this.matrix.setPosition( this.position );

        if ( this.useQuaternion === false )  {

            this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );

        } else {

            this.matrix.setRotationFromQuaternion( this.quaternion );

        }

        if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {

            this.matrix.scale( this.scale );
            this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );

        }

        this.matrixWorldNeedsUpdate = true;

    },

    updateMatrixWorld: function ( force ) {

        if ( this.matrixAutoUpdate === true ) this.updateMatrix();

        if ( this.matrixWorldNeedsUpdate === true || force === true ) {

            if ( this.parent === undefined ) {

                this.matrixWorld.copy( this.matrix );

            } else {

                this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );

            }

            this.matrixWorldNeedsUpdate = false;

            force = true;

        }

        // update children

        for ( var i = 0, l = this.children.length; i < l; i ++ ) {

            this.children[ i ].updateMatrixWorld( force );

        }

    },

    clone: function () {

        // TODO

    }

};

THREE.Object3D.__m1 = new THREE.Matrix4();

THREE.Object3DCount = 0;
/**
 * @author mrdoob / http://mrdoob.com/
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author julianwa / https://github.com/julianwa
 */

THREE.Projector = function() {

    var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
    _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
    _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
    _face4Count, _face4Pool = [], _face4PoolLength = 0,
    _line, _lineCount, _linePool = [], _linePoolLength = 0,
    _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,

    _renderData = { objects: [], sprites: [], lights: [], elements: [] },

    _vector3 = new THREE.Vector3(),
    _vector4 = new THREE.Vector4(),

    _viewProjectionMatrix = new THREE.Matrix4(),
    _modelViewProjectionMatrix = new THREE.Matrix4(),

    _frustum = new THREE.Frustum(),

    _clippedVertex1PositionScreen = new THREE.Vector4(),
    _clippedVertex2PositionScreen = new THREE.Vector4(),

    _face3VertexNormals;

    this.projectVector = function ( vector, camera ) {

        camera.matrixWorldInverse.getInverse( camera.matrixWorld );

        _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
        _viewProjectionMatrix.multiplyVector3( vector );

        return vector;

    };

    this.unprojectVector = function ( vector, camera ) {

        camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );

        _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
        _viewProjectionMatrix.multiplyVector3( vector );

        return vector;

    };

    this.pickingRay = function ( vector, camera ) {

        var end, ray, t;

        // set two vectors with opposing z values
        vector.z = -1.0;
        end = new THREE.Vector3( vector.x, vector.y, 1.0 );

        this.unprojectVector( vector, camera );
        this.unprojectVector( end, camera );

        // find direction from vector to end
        end.subSelf( vector ).normalize();

        return new THREE.Ray( vector, end );

    };

    var projectGraph = function ( root, sortObjects ) {

        _objectCount = 0;

        _renderData.objects.length = 0;
        _renderData.sprites.length = 0;
        _renderData.lights.length = 0;

        var projectObject = function ( parent ) {

            for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {

                var object = parent.children[ c ];

                if ( object.visible === false ) continue;

                if ( object instanceof THREE.Light ) {

                    _renderData.lights.push( object );

                } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {

                    if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {

                        _object = getNextObjectInPool();
                        _object.object = object;

                        if ( object.renderDepth !== null ) {

                            _object.z = object.renderDepth;

                        } else {

                            _vector3.copy( object.matrixWorld.getPosition() );
                            _viewProjectionMatrix.multiplyVector3( _vector3 );
                            _object.z = _vector3.z;

                        }

                        _renderData.objects.push( _object );

                    }

                } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {

                    _object = getNextObjectInPool();
                    _object.object = object;

                    // TODO: Find an elegant and performant solution and remove this dupe code.

                    if ( object.renderDepth !== null ) {

                        _object.z = object.renderDepth;

                    } else {

                        _vector3.copy( object.matrixWorld.getPosition() );
                        _viewProjectionMatrix.multiplyVector3( _vector3 );
                        _object.z = _vector3.z;

                    }

                    _renderData.sprites.push( _object );

                } else {

                    _object = getNextObjectInPool();
                    _object.object = object;

                    if ( object.renderDepth !== null ) {

                        _object.z = object.renderDepth;

                    } else {

                        _vector3.copy( object.matrixWorld.getPosition() );
                        _viewProjectionMatrix.multiplyVector3( _vector3 );
                        _object.z = _vector3.z;

                    }

                    _renderData.objects.push( _object );

                }

                projectObject( object );

            }

        };

        projectObject( root );

        if ( sortObjects === true ) _renderData.objects.sort( painterSort );

        return _renderData;

    };

    this.projectScene = function ( scene, camera, sortObjects, sortElements ) {

        var near = camera.near, far = camera.far, visible = false,
        o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
        modelMatrix, rotationMatrix,
        geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
        faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
        v1, v2, v3, v4, isFaceMaterial, material, side;

        _face3Count = 0;
        _face4Count = 0;
        _lineCount = 0;
        _particleCount = 0;

        _renderData.elements.length = 0;

        scene.updateMatrixWorld();

        if ( camera.parent === undefined ) camera.updateMatrixWorld();

        camera.matrixWorldInverse.getInverse( camera.matrixWorld );

        _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );

        _frustum.setFromMatrix( _viewProjectionMatrix );

        _renderData = projectGraph( scene, sortObjects );

        for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {

            object = _renderData.objects[ o ].object;

            modelMatrix = object.matrixWorld;

            _vertexCount = 0;

            if ( object instanceof THREE.Mesh ) {

                geometry = object.geometry;
                geometryMaterials = object.geometry.materials;
                vertices = geometry.vertices;
                faces = geometry.faces;
                faceVertexUvs = geometry.faceVertexUvs;

                rotationMatrix = object.matrixRotationWorld.extractRotation( modelMatrix );

                isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
                side = object.material.side;

                for ( v = 0, vl = vertices.length; v < vl; v ++ ) {

                    _vertex = getNextVertexInPool();
                    _vertex.positionWorld.copy( vertices[ v ] );

                    modelMatrix.multiplyVector3( _vertex.positionWorld );

                    _vertex.positionScreen.copy( _vertex.positionWorld );
                    _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );

                    _vertex.positionScreen.x /= _vertex.positionScreen.w;
                    _vertex.positionScreen.y /= _vertex.positionScreen.w;

                    _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;

                }

                for ( f = 0, fl = faces.length; f < fl; f ++ ) {

                    face = faces[ f ];

                    material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;

                    if ( material === undefined ) continue;

                    side = material.side;

                    if ( face instanceof THREE.Face3 ) {

                        v1 = _vertexPool[ face.a ];
                        v2 = _vertexPool[ face.b ];
                        v3 = _vertexPool[ face.c ];

                        if ( v1.visible === true && v2.visible === true && v3.visible === true ) {

                            visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
                                ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;

                            if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {

                                _face = getNextFace3InPool();

                                _face.v1.copy( v1 );
                                _face.v2.copy( v2 );
                                _face.v3.copy( v3 );

                            } else {

                                continue;

                            }

                        } else {

                            continue;

                        }

                    } else if ( face instanceof THREE.Face4 ) {

                        v1 = _vertexPool[ face.a ];
                        v2 = _vertexPool[ face.b ];
                        v3 = _vertexPool[ face.c ];
                        v4 = _vertexPool[ face.d ];

                        if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {

                            visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
                                ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
                                ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
                                ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;


                            if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {

                                _face = getNextFace4InPool();

                                _face.v1.copy( v1 );
                                _face.v2.copy( v2 );
                                _face.v3.copy( v3 );
                                _face.v4.copy( v4 );

                            } else {

                                continue;

                            }

                        } else {

                            continue;

                        }

                    }

                    _face.normalWorld.copy( face.normal );

                    if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
                    rotationMatrix.multiplyVector3( _face.normalWorld );

                    _face.centroidWorld.copy( face.centroid );
                    modelMatrix.multiplyVector3( _face.centroidWorld );

                    _face.centroidScreen.copy( _face.centroidWorld );
                    _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );

                    faceVertexNormals = face.vertexNormals;

                    for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {

                        normal = _face.vertexNormalsWorld[ n ];
                        normal.copy( faceVertexNormals[ n ] );

                        if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();

                        rotationMatrix.multiplyVector3( normal );

                    }

                    _face.vertexNormalsLength = faceVertexNormals.length;

                    for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {

                        uvs = faceVertexUvs[ c ][ f ];

                        if ( uvs === undefined ) continue;

                        for ( u = 0, ul = uvs.length; u < ul; u ++ ) {

                            _face.uvs[ c ][ u ] = uvs[ u ];

                        }

                    }

                    _face.material = material;

                    _face.z = _face.centroidScreen.z;

                    _renderData.elements.push( _face );

                }

            } else if ( object instanceof THREE.Line ) {

                _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );

                vertices = object.geometry.vertices;

                v1 = getNextVertexInPool();
                v1.positionScreen.copy( vertices[ 0 ] );
                _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );

                // Handle LineStrip and LinePieces
                var step = object.type === THREE.LinePieces ? 2 : 1;

                for ( v = 1, vl = vertices.length; v < vl; v ++ ) {

                    v1 = getNextVertexInPool();
                    v1.positionScreen.copy( vertices[ v ] );
                    _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );

                    if ( ( v + 1 ) % step > 0 ) continue;

                    v2 = _vertexPool[ _vertexCount - 2 ];

                    _clippedVertex1PositionScreen.copy( v1.positionScreen );
                    _clippedVertex2PositionScreen.copy( v2.positionScreen );

                    if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {

                        // Perform the perspective divide
                        _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
                        _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );

                        _line = getNextLineInPool();
                        _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
                        _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );

                        _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );

                        _line.material = object.material;

                        _renderData.elements.push( _line );

                    }

                }

            }

        }

        for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {

            object = _renderData.sprites[ o ].object;

            modelMatrix = object.matrixWorld;

            if ( object instanceof THREE.Particle ) {

                _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
                _viewProjectionMatrix.multiplyVector4( _vector4 );

                _vector4.z /= _vector4.w;

                if ( _vector4.z > 0 && _vector4.z < 1 ) {

                    _particle = getNextParticleInPool();
                    _particle.object = object;
                    _particle.x = _vector4.x / _vector4.w;
                    _particle.y = _vector4.y / _vector4.w;
                    _particle.z = _vector4.z;

                    _particle.rotation = object.rotation.z;

                    _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
                    _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );

                    _particle.material = object.material;

                    _renderData.elements.push( _particle );

                }

            }

        }

        if ( sortElements === true ) _renderData.elements.sort( painterSort );

        return _renderData;

    };

    // Pools

    function getNextObjectInPool() {

        if ( _objectCount === _objectPoolLength ) {

            var object = new THREE.RenderableObject();
            _objectPool.push( object );
            _objectPoolLength ++;
            _objectCount ++;
            return object;

        }

        return _objectPool[ _objectCount ++ ];

    }

    function getNextVertexInPool() {

        if ( _vertexCount === _vertexPoolLength ) {

            var vertex = new THREE.RenderableVertex();
            _vertexPool.push( vertex );
            _vertexPoolLength ++;
            _vertexCount ++;
            return vertex;

        }

        return _vertexPool[ _vertexCount ++ ];

    }

    function getNextFace3InPool() {

        if ( _face3Count === _face3PoolLength ) {

            var face = new THREE.RenderableFace3();
            _face3Pool.push( face );
            _face3PoolLength ++;
            _face3Count ++;
            return face;

        }

        return _face3Pool[ _face3Count ++ ];


    }

    function getNextFace4InPool() {

        if ( _face4Count === _face4PoolLength ) {

            var face = new THREE.RenderableFace4();
            _face4Pool.push( face );
            _face4PoolLength ++;
            _face4Count ++;
            return face;

        }

        return _face4Pool[ _face4Count ++ ];

    }

    function getNextLineInPool() {

        if ( _lineCount === _linePoolLength ) {

            var line = new THREE.RenderableLine();
            _linePool.push( line );
            _linePoolLength ++;
            _lineCount ++
            return line;

        }

        return _linePool[ _lineCount ++ ];

    }

    function getNextParticleInPool() {

        if ( _particleCount === _particlePoolLength ) {

            var particle = new THREE.RenderableParticle();
            _particlePool.push( particle );
            _particlePoolLength ++;
            _particleCount ++
            return particle;

        }

        return _particlePool[ _particleCount ++ ];

    }

    //

    function painterSort( a, b ) {

        return b.z - a.z;

    }

    function clipLine( s1, s2 ) {

        var alpha1 = 0, alpha2 = 1,

        // Calculate the boundary coordinate of each vertex for the near and far clip planes,
        // Z = -1 and Z = +1, respectively.
        bc1near =  s1.z + s1.w,
        bc2near =  s2.z + s2.w,
        bc1far =  - s1.z + s1.w,
        bc2far =  - s2.z + s2.w;

        if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {

            // Both vertices lie entirely within all clip planes.
            return true;

        } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {

            // Both vertices lie entirely outside one of the clip planes.
            return false;

        } else {

            // The line segment spans at least one clip plane.

            if ( bc1near < 0 ) {

                // v1 lies outside the near plane, v2 inside
                alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );

            } else if ( bc2near < 0 ) {

                // v2 lies outside the near plane, v1 inside
                alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );

            }

            if ( bc1far < 0 ) {

                // v1 lies outside the far plane, v2 inside
                alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );

            } else if ( bc2far < 0 ) {

                // v2 lies outside the far plane, v2 inside
                alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );

            }

            if ( alpha2 < alpha1 ) {

                // The line segment spans two boundaries, but is outside both of them.
                // (This can't happen when we're only clipping against just near/far but good
                //  to leave the check here for future usage if other clip planes are added.)
                return false;

            } else {

                // Update the s1 and s2 vertices to match the clipped line segment.
                s1.lerpSelf( s2, alpha1 );
                s2.lerpSelf( s1, 1 - alpha2 );

                return true;

            }

        }

    }

};
/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author WestLangley / http://github.com/WestLangley
 */

THREE.Quaternion = function( x, y, z, w ) {

    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;
    this.w = ( w !== undefined ) ? w : 1;

};

THREE.Quaternion.prototype = {

    constructor: THREE.Quaternion,

    set: function ( x, y, z, w ) {

        this.x = x;
        this.y = y;
        this.z = z;
        this.w = w;

        return this;

    },

    copy: function ( q ) {

        this.x = q.x;
        this.y = q.y;
        this.z = q.z;
        this.w = q.w;

        return this;

    },

    setFromEuler: function ( v, order ) {

        // http://www.mathworks.com/matlabcentral/fileexchange/
        //     20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
        //    content/SpinCalc.m

        var c1 = Math.cos( v.x / 2 );
        var c2 = Math.cos( v.y / 2 );
        var c3 = Math.cos( v.z / 2 );
        var s1 = Math.sin( v.x / 2 );
        var s2 = Math.sin( v.y / 2 );
        var s3 = Math.sin( v.z / 2 );

        if ( order === undefined || order === 'XYZ' ) {

            this.x = s1 * c2 * c3 + c1 * s2 * s3;
            this.y = c1 * s2 * c3 - s1 * c2 * s3;
            this.z = c1 * c2 * s3 + s1 * s2 * c3;
            this.w = c1 * c2 * c3 - s1 * s2 * s3;

        } else if ( order === 'YXZ' ) {

            this.x = s1 * c2 * c3 + c1 * s2 * s3;
            this.y = c1 * s2 * c3 - s1 * c2 * s3;
            this.z = c1 * c2 * s3 - s1 * s2 * c3;
            this.w = c1 * c2 * c3 + s1 * s2 * s3;

        } else if ( order === 'ZXY' ) {

            this.x = s1 * c2 * c3 - c1 * s2 * s3;
            this.y = c1 * s2 * c3 + s1 * c2 * s3;
            this.z = c1 * c2 * s3 + s1 * s2 * c3;
            this.w = c1 * c2 * c3 - s1 * s2 * s3;

        } else if ( order === 'ZYX' ) {

            this.x = s1 * c2 * c3 - c1 * s2 * s3;
            this.y = c1 * s2 * c3 + s1 * c2 * s3;
            this.z = c1 * c2 * s3 - s1 * s2 * c3;
            this.w = c1 * c2 * c3 + s1 * s2 * s3;

        } else if ( order === 'YZX' ) {

            this.x = s1 * c2 * c3 + c1 * s2 * s3;
            this.y = c1 * s2 * c3 + s1 * c2 * s3;
            this.z = c1 * c2 * s3 - s1 * s2 * c3;
            this.w = c1 * c2 * c3 - s1 * s2 * s3;

        } else if ( order === 'XZY' ) {

            this.x = s1 * c2 * c3 - c1 * s2 * s3;
            this.y = c1 * s2 * c3 - s1 * c2 * s3;
            this.z = c1 * c2 * s3 + s1 * s2 * c3;
            this.w = c1 * c2 * c3 + s1 * s2 * s3;

        }

        return this;

    },

    setFromAxisAngle: function ( axis, angle ) {

        // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
        // axis have to be normalized

        var halfAngle = angle / 2,
            s = Math.sin( halfAngle );

        this.x = axis.x * s;
        this.y = axis.y * s;
        this.z = axis.z * s;
        this.w = Math.cos( halfAngle );

        return this;

    },

    setFromRotationMatrix: function ( m ) {

        // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm

        // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)

        var te = m.elements,

            m11 = te[0], m12 = te[4], m13 = te[8],
            m21 = te[1], m22 = te[5], m23 = te[9],
            m31 = te[2], m32 = te[6], m33 = te[10],

            trace = m11 + m22 + m33,
            s;

        if( trace > 0 ) {

            s = 0.5 / Math.sqrt( trace + 1.0 );

            this.w = 0.25 / s;
            this.x = ( m32 - m23 ) * s;
            this.y = ( m13 - m31 ) * s;
            this.z = ( m21 - m12 ) * s;

        } else if ( m11 > m22 && m11 > m33 ) {

            s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );

            this.w = (m32 - m23 ) / s;
            this.x = 0.25 * s;
            this.y = (m12 + m21 ) / s;
            this.z = (m13 + m31 ) / s;

        } else if (m22 > m33) {

            s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );

            this.w = (m13 - m31 ) / s;
            this.x = (m12 + m21 ) / s;
            this.y = 0.25 * s;
            this.z = (m23 + m32 ) / s;

        } else {

            s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );

            this.w = ( m21 - m12 ) / s;
            this.x = ( m13 + m31 ) / s;
            this.y = ( m23 + m32 ) / s;
            this.z = 0.25 * s;

        }

        return this;

    },

    calculateW : function () {

        this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );

        return this;

    },

    inverse: function () {

        this.x *= -1;
        this.y *= -1;
        this.z *= -1;

        return this;

    },

    length: function () {

        return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );

    },

    normalize: function () {

        var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );

        if ( l === 0 ) {

            this.x = 0;
            this.y = 0;
            this.z = 0;
            this.w = 0;

        } else {

            l = 1 / l;

            this.x = this.x * l;
            this.y = this.y * l;
            this.z = this.z * l;
            this.w = this.w * l;

        }

        return this;

    },

    multiply: function ( a, b ) {

        // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
        var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
        qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;

        this.x =  qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
        this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
        this.z =  qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
        this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;

        return this;

    },

    multiplySelf: function ( b ) {

        var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
        qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;

        this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
        this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
        this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
        this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;

        return this;

    },

    multiplyVector3: function ( vector, dest ) {

        if ( !dest ) { dest = vector; }

        var x    = vector.x,  y  = vector.y,  z  = vector.z,
            qx   = this.x, qy = this.y, qz = this.z, qw = this.w;

        // calculate quat * vector

        var ix =  qw * x + qy * z - qz * y,
            iy =  qw * y + qz * x - qx * z,
            iz =  qw * z + qx * y - qy * x,
            iw = -qx * x - qy * y - qz * z;

        // calculate result * inverse quat

        dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
        dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
        dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;

        return dest;

    },

    slerpSelf: function ( qb, t ) {

        var x = this.x, y = this.y, z = this.z, w = this.w;

        // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/

        var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;

        if ( cosHalfTheta < 0 ) {

            this.w = -qb.w;
            this.x = -qb.x;
            this.y = -qb.y;
            this.z = -qb.z;

            cosHalfTheta = -cosHalfTheta;

        } else {

            this.copy( qb );

        }

        if ( cosHalfTheta >= 1.0 ) {

            this.w = w;
            this.x = x;
            this.y = y;
            this.z = z;

            return this;

        }

        var halfTheta = Math.acos( cosHalfTheta );
        var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );

        if ( Math.abs( sinHalfTheta ) < 0.001 ) {

            this.w = 0.5 * ( w + this.w );
            this.x = 0.5 * ( x + this.x );
            this.y = 0.5 * ( y + this.y );
            this.z = 0.5 * ( z + this.z );

            return this;

        }

        var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
        ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;

        this.w = ( w * ratioA + this.w * ratioB );
        this.x = ( x * ratioA + this.x * ratioB );
        this.y = ( y * ratioA + this.y * ratioB );
        this.z = ( z * ratioA + this.z * ratioB );

        return this;

    },

    clone: function () {

        return new THREE.Quaternion( this.x, this.y, this.z, this.w );

    }

}

THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {

    // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/

    var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;

    if ( cosHalfTheta < 0 ) {

        qm.w = -qb.w;
        qm.x = -qb.x;
        qm.y = -qb.y;
        qm.z = -qb.z;

        cosHalfTheta = -cosHalfTheta;

    } else {

        qm.copy( qb );

    }

    if ( Math.abs( cosHalfTheta ) >= 1.0 ) {

        qm.w = qa.w;
        qm.x = qa.x;
        qm.y = qa.y;
        qm.z = qa.z;

        return qm;

    }

    var halfTheta = Math.acos( cosHalfTheta );
    var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );

    if ( Math.abs( sinHalfTheta ) < 0.001 ) {

        qm.w = 0.5 * ( qa.w + qm.w );
        qm.x = 0.5 * ( qa.x + qm.x );
        qm.y = 0.5 * ( qa.y + qm.y );
        qm.z = 0.5 * ( qa.z + qm.z );

        return qm;

    }

    var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
    var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;

    qm.w = ( qa.w * ratioA + qm.w * ratioB );
    qm.x = ( qa.x * ratioA + qm.x * ratioB );
    qm.y = ( qa.y * ratioA + qm.y * ratioB );
    qm.z = ( qa.z * ratioA + qm.z * ratioB );

    return qm;

}
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Vertex = function ( v ) {

    console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
    return v;

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {

    this.a = a;
    this.b = b;
    this.c = c;

    this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
    this.vertexNormals = normal instanceof Array ? normal : [ ];

    this.color = color instanceof THREE.Color ? color : new THREE.Color();
    this.vertexColors = color instanceof Array ? color : [];

    this.vertexTangents = [];

    this.materialIndex = materialIndex;

    this.centroid = new THREE.Vector3();

};

THREE.Face3.prototype = {

    constructor: THREE.Face3,

    clone: function () {

        var face = new THREE.Face3( this.a, this.b, this.c );

        face.normal.copy( this.normal );
        face.color.copy( this.color );
        face.centroid.copy( this.centroid );

        face.materialIndex = this.materialIndex;

        var i, il;
        for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
        for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
        for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();

        return face;

    }

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {

    this.a = a;
    this.b = b;
    this.c = c;
    this.d = d;

    this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
    this.vertexNormals = normal instanceof Array ? normal : [ ];

    this.color = color instanceof THREE.Color ? color : new THREE.Color();
    this.vertexColors = color instanceof Array ? color : [];

    this.vertexTangents = [];

    this.materialIndex = materialIndex;

    this.centroid = new THREE.Vector3();

};

THREE.Face4.prototype = {

    constructor: THREE.Face4,

    clone: function () {

        var face = new THREE.Face4( this.a, this.b, this.c, this.d );

        face.normal.copy( this.normal );
        face.color.copy( this.color );
        face.centroid.copy( this.centroid );

        face.materialIndex = this.materialIndex;

        var i, il;
        for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
        for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
        for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();

        return face;

    }

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.UV = function ( u, v ) {

    this.u = u || 0;
    this.v = v || 0;

};

THREE.UV.prototype = {

    constructor: THREE.UV,

    set: function ( u, v ) {

        this.u = u;
        this.v = v;

        return this;

    },

    copy: function ( uv ) {

        this.u = uv.u;
        this.v = uv.v;

        return this;

    },

    lerpSelf: function ( uv, alpha ) {

        this.u += ( uv.u - this.u ) * alpha;
        this.v += ( uv.v - this.v ) * alpha;

        return this;

    },

    clone: function () {

        return new THREE.UV( this.u, this.v );

    }

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author kile / http://kile.stravaganza.org/
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 * @author zz85 / http://www.lab4games.net/zz85/blog
 */

THREE.Geometry = function () {

    this.id = THREE.GeometryCount ++;

    this.name = '';

    this.vertices = [];
    this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon

    this.materials = [];

    this.faces = [];

    this.faceUvs = [[]];
    this.faceVertexUvs = [[]];

    this.morphTargets = [];
    this.morphColors = [];
    this.morphNormals = [];

    this.skinWeights = [];
    this.skinIndices = [];

    this.boundingBox = null;
    this.boundingSphere = null;

    this.hasTangents = false;

    this.dynamic = true; // the intermediate typearrays will be deleted when set to false

};

THREE.Geometry.prototype = {

    constructor : THREE.Geometry,

    applyMatrix: function ( matrix ) {

        var matrixRotation = new THREE.Matrix4();
        matrixRotation.extractRotation( matrix );

        for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {

            var vertex = this.vertices[ i ];

            matrix.multiplyVector3( vertex );

        }

        for ( var i = 0, il = this.faces.length; i < il; i ++ ) {

            var face = this.faces[ i ];

            matrixRotation.multiplyVector3( face.normal );

            for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {

                matrixRotation.multiplyVector3( face.vertexNormals[ j ] );

            }

            matrix.multiplyVector3( face.centroid );

        }

    },

    computeCentroids: function () {

        var f, fl, face;

        for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

            face = this.faces[ f ];
            face.centroid.set( 0, 0, 0 );

            if ( face instanceof THREE.Face3 ) {

                face.centroid.addSelf( this.vertices[ face.a ] );
                face.centroid.addSelf( this.vertices[ face.b ] );
                face.centroid.addSelf( this.vertices[ face.c ] );
                face.centroid.divideScalar( 3 );

            } else if ( face instanceof THREE.Face4 ) {

                face.centroid.addSelf( this.vertices[ face.a ] );
                face.centroid.addSelf( this.vertices[ face.b ] );
                face.centroid.addSelf( this.vertices[ face.c ] );
                face.centroid.addSelf( this.vertices[ face.d ] );
                face.centroid.divideScalar( 4 );

            }

        }

    },

    computeFaceNormals: function () {

        var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
        cb = new THREE.Vector3(), ab = new THREE.Vector3();

        for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

            face = this.faces[ f ];

            vA = this.vertices[ face.a ];
            vB = this.vertices[ face.b ];
            vC = this.vertices[ face.c ];

            cb.sub( vC, vB );
            ab.sub( vA, vB );
            cb.crossSelf( ab );

            if ( !cb.isZero() ) {

                cb.normalize();

            }

            face.normal.copy( cb );

        }

    },

    computeVertexNormals: function () {

        var v, vl, f, fl, face, vertices;

        // create internal buffers for reuse when calling this method repeatedly
        // (otherwise memory allocation / deallocation every frame is big resource hog)

        if ( this.__tmpVertices === undefined ) {

            this.__tmpVertices = new Array( this.vertices.length );
            vertices = this.__tmpVertices;

            for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {

                vertices[ v ] = new THREE.Vector3();

            }

            for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

                face = this.faces[ f ];

                if ( face instanceof THREE.Face3 ) {

                    face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];

                } else if ( face instanceof THREE.Face4 ) {

                    face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];

                }

            }

        } else {

            vertices = this.__tmpVertices;

            for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {

                vertices[ v ].set( 0, 0, 0 );

            }

        }

        for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

            face = this.faces[ f ];

            if ( face instanceof THREE.Face3 ) {

                vertices[ face.a ].addSelf( face.normal );
                vertices[ face.b ].addSelf( face.normal );
                vertices[ face.c ].addSelf( face.normal );

            } else if ( face instanceof THREE.Face4 ) {

                vertices[ face.a ].addSelf( face.normal );
                vertices[ face.b ].addSelf( face.normal );
                vertices[ face.c ].addSelf( face.normal );
                vertices[ face.d ].addSelf( face.normal );

            }

        }

        for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {

            vertices[ v ].normalize();

        }

        for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

            face = this.faces[ f ];

            if ( face instanceof THREE.Face3 ) {

                face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
                face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
                face.vertexNormals[ 2 ].copy( vertices[ face.c ] );

            } else if ( face instanceof THREE.Face4 ) {

                face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
                face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
                face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
                face.vertexNormals[ 3 ].copy( vertices[ face.d ] );

            }

        }

    },

    computeMorphNormals: function () {

        var i, il, f, fl, face;

        // save original normals
        // - create temp variables on first access
        //   otherwise just copy (for faster repeated calls)

        for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

            face = this.faces[ f ];

            if ( ! face.__originalFaceNormal ) {

                face.__originalFaceNormal = face.normal.clone();

            } else {

                face.__originalFaceNormal.copy( face.normal );

            }

            if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];

            for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {

                if ( ! face.__originalVertexNormals[ i ] ) {

                    face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();

                } else {

                    face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );

                }

            }

        }

        // use temp geometry to compute face and vertex normals for each morph

        var tmpGeo = new THREE.Geometry();
        tmpGeo.faces = this.faces;

        for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {

            // create on first access

            if ( ! this.morphNormals[ i ] ) {

                this.morphNormals[ i ] = {};
                this.morphNormals[ i ].faceNormals = [];
                this.morphNormals[ i ].vertexNormals = [];

                var dstNormalsFace = this.morphNormals[ i ].faceNormals;
                var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;

                var faceNormal, vertexNormals;

                for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

                    face = this.faces[ f ];

                    faceNormal = new THREE.Vector3();

                    if ( face instanceof THREE.Face3 ) {

                        vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };

                    } else {

                        vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };

                    }

                    dstNormalsFace.push( faceNormal );
                    dstNormalsVertex.push( vertexNormals );

                }

            }

            var morphNormals = this.morphNormals[ i ];

            // set vertices to morph target

            tmpGeo.vertices = this.morphTargets[ i ].vertices;

            // compute morph normals

            tmpGeo.computeFaceNormals();
            tmpGeo.computeVertexNormals();

            // store morph normals

            var faceNormal, vertexNormals;

            for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

                face = this.faces[ f ];

                faceNormal = morphNormals.faceNormals[ f ];
                vertexNormals = morphNormals.vertexNormals[ f ];

                faceNormal.copy( face.normal );

                if ( face instanceof THREE.Face3 ) {

                    vertexNormals.a.copy( face.vertexNormals[ 0 ] );
                    vertexNormals.b.copy( face.vertexNormals[ 1 ] );
                    vertexNormals.c.copy( face.vertexNormals[ 2 ] );

                } else {

                    vertexNormals.a.copy( face.vertexNormals[ 0 ] );
                    vertexNormals.b.copy( face.vertexNormals[ 1 ] );
                    vertexNormals.c.copy( face.vertexNormals[ 2 ] );
                    vertexNormals.d.copy( face.vertexNormals[ 3 ] );

                }

            }

        }

        // restore original normals

        for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

            face = this.faces[ f ];

            face.normal = face.__originalFaceNormal;
            face.vertexNormals = face.__originalVertexNormals;

        }

    },

    computeTangents: function () {

        // based on http://www.terathon.com/code/tangent.html
        // tangents go to vertices

        var f, fl, v, vl, i, il, vertexIndex,
            face, uv, vA, vB, vC, uvA, uvB, uvC,
            x1, x2, y1, y2, z1, z2,
            s1, s2, t1, t2, r, t, test,
            tan1 = [], tan2 = [],
            sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
            tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
            n = new THREE.Vector3(), w;

        for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {

            tan1[ v ] = new THREE.Vector3();
            tan2[ v ] = new THREE.Vector3();

        }

        function handleTriangle( context, a, b, c, ua, ub, uc ) {

            vA = context.vertices[ a ];
            vB = context.vertices[ b ];
            vC = context.vertices[ c ];

            uvA = uv[ ua ];
            uvB = uv[ ub ];
            uvC = uv[ uc ];

            x1 = vB.x - vA.x;
            x2 = vC.x - vA.x;
            y1 = vB.y - vA.y;
            y2 = vC.y - vA.y;
            z1 = vB.z - vA.z;
            z2 = vC.z - vA.z;

            s1 = uvB.u - uvA.u;
            s2 = uvC.u - uvA.u;
            t1 = uvB.v - uvA.v;
            t2 = uvC.v - uvA.v;

            r = 1.0 / ( s1 * t2 - s2 * t1 );
            sdir.set( ( t2 * x1 - t1 * x2 ) * r,
                      ( t2 * y1 - t1 * y2 ) * r,
                      ( t2 * z1 - t1 * z2 ) * r );
            tdir.set( ( s1 * x2 - s2 * x1 ) * r,
                      ( s1 * y2 - s2 * y1 ) * r,
                      ( s1 * z2 - s2 * z1 ) * r );

            tan1[ a ].addSelf( sdir );
            tan1[ b ].addSelf( sdir );
            tan1[ c ].addSelf( sdir );

            tan2[ a ].addSelf( tdir );
            tan2[ b ].addSelf( tdir );
            tan2[ c ].addSelf( tdir );

        }

        for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

            face = this.faces[ f ];
            uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents

            if ( face instanceof THREE.Face3 ) {

                handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );

            } else if ( face instanceof THREE.Face4 ) {

                handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
                handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );

            }

        }

        var faceIndex = [ 'a', 'b', 'c', 'd' ];

        for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {

            face = this.faces[ f ];

            for ( i = 0; i < face.vertexNormals.length; i++ ) {

                n.copy( face.vertexNormals[ i ] );

                vertexIndex = face[ faceIndex[ i ] ];

                t = tan1[ vertexIndex ];

                // Gram-Schmidt orthogonalize

                tmp.copy( t );
                tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();

                // Calculate handedness

                tmp2.cross( face.vertexNormals[ i ], t );
                test = tmp2.dot( tan2[ vertexIndex ] );
                w = (test < 0.0) ? -1.0 : 1.0;

                face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );

            }

        }

        this.hasTangents = true;

    },

    computeBoundingBox: function () {

        if ( ! this.boundingBox ) {

            this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };

        }

        if ( this.vertices.length > 0 ) {

            var position, firstPosition = this.vertices[ 0 ];

            this.boundingBox.min.copy( firstPosition );
            this.boundingBox.max.copy( firstPosition );

            var min = this.boundingBox.min,
                max = this.boundingBox.max;

            for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {

                position = this.vertices[ v ];

                if ( position.x < min.x ) {

                    min.x = position.x;

                } else if ( position.x > max.x ) {

                    max.x = position.x;

                }

                if ( position.y < min.y ) {

                    min.y = position.y;

                } else if ( position.y > max.y ) {

                    max.y = position.y;

                }

                if ( position.z < min.z ) {

                    min.z = position.z;

                } else if ( position.z > max.z ) {

                    max.z = position.z;

                }

            }

        } else {

            this.boundingBox.min.set( 0, 0, 0 );
            this.boundingBox.max.set( 0, 0, 0 );

        }

    },

    computeBoundingSphere: function () {

        var maxRadiusSq = 0;

        if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };

        for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {

            var radiusSq = this.vertices[ i ].lengthSq();
            if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;

        }

        this.boundingSphere.radius = Math.sqrt( maxRadiusSq );

    },

    /*
     * Checks for duplicate vertices with hashmap.
     * Duplicated vertices are removed
     * and faces' vertices are updated.
     */

    mergeVertices: function () {

        var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
        var unique = [], changes = [];

        var v, key;
        var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
        var precision = Math.pow( 10, precisionPoints );
        var i,il, face;
        var abcd = 'abcd', o, k, j, jl, u;

        for ( i = 0, il = this.vertices.length; i < il; i ++ ) {

            v = this.vertices[ i ];
            key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );

            if ( verticesMap[ key ] === undefined ) {

                verticesMap[ key ] = i;
                unique.push( this.vertices[ i ] );
                changes[ i ] = unique.length - 1;

            } else {

                //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
                changes[ i ] = changes[ verticesMap[ key ] ];

            }

        };


        // Start to patch face indices

        for( i = 0, il = this.faces.length; i < il; i ++ ) {

            face = this.faces[ i ];

            if ( face instanceof THREE.Face3 ) {

                face.a = changes[ face.a ];
                face.b = changes[ face.b ];
                face.c = changes[ face.c ];

            } else if ( face instanceof THREE.Face4 ) {

                face.a = changes[ face.a ];
                face.b = changes[ face.b ];
                face.c = changes[ face.c ];
                face.d = changes[ face.d ];

                // check dups in (a, b, c, d) and convert to -> face3

                o = [ face.a, face.b, face.c, face.d ];

                for ( k = 3; k > 0; k -- ) {

                    if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {

                        // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);

                        o.splice( k, 1 );

                        this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );

                        for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {

                            u = this.faceVertexUvs[ j ][ i ];
                            if ( u ) u.splice( k, 1 );

                        }

                        this.faces[ i ].vertexColors = face.vertexColors;

                        break;
                    }

                }

            }

        }

        // Use unique set of vertices

        var diff = this.vertices.length - unique.length;
        this.vertices = unique;
        return diff;

    },

    clone: function () {

        // TODO

    }

};

THREE.GeometryCount = 0;
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.BufferGeometry = function () {

    this.id = THREE.GeometryCount ++;

    // attributes

    this.attributes = {};

    // attributes typed arrays are kept only if dynamic flag is set

    this.dynamic = false;

    // boundings

    this.boundingBox = null;
    this.boundingSphere = null;

    this.hasTangents = false;

    // for compatibility

    this.morphTargets = [];

};

THREE.BufferGeometry.prototype = {

    constructor : THREE.BufferGeometry,

    applyMatrix: function ( matrix ) {

        var positionArray;
        var normalArray;

        if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
        if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;

        if ( positionArray !== undefined ) {

            matrix.multiplyVector3Array( positionArray );
            this.verticesNeedUpdate = true;

        }

        if ( normalArray !== undefined ) {

            var matrixRotation = new THREE.Matrix4();
            matrixRotation.extractRotation( matrix );

            matrixRotation.multiplyVector3Array( normalArray );
            this.normalsNeedUpdate = true;

        }

    },

    computeBoundingBox: function () {

        if ( ! this.boundingBox ) {

            this.boundingBox = {

                min: new THREE.Vector3( Infinity, Infinity, Infinity ),
                max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )

            };

        }

        var positions = this.attributes[ "position" ].array;

        if ( positions ) {

            var bb = this.boundingBox;
            var x, y, z;

            for ( var i = 0, il = positions.length; i < il; i += 3 ) {

                x = positions[ i ];
                y = positions[ i + 1 ];
                z = positions[ i + 2 ];

                // bounding box

                if ( x < bb.min.x ) {

                    bb.min.x = x;

                } else if ( x > bb.max.x ) {

                    bb.max.x = x;

                }

                if ( y < bb.min.y ) {

                    bb.min.y = y;

                } else if ( y > bb.max.y ) {

                    bb.max.y = y;

                }

                if ( z < bb.min.z ) {

                    bb.min.z = z;

                } else if ( z > bb.max.z ) {

                    bb.max.z = z;

                }

            }

        }

        if ( positions === undefined || positions.length === 0 ) {

            this.boundingBox.min.set( 0, 0, 0 );
            this.boundingBox.max.set( 0, 0, 0 );

        }

    },

    computeBoundingSphere: function () {

        if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };

        var positions = this.attributes[ "position" ].array;

        if ( positions ) {

            var radiusSq, maxRadiusSq = 0;
            var x, y, z;

            for ( var i = 0, il = positions.length; i < il; i += 3 ) {

                x = positions[ i ];
                y = positions[ i + 1 ];
                z = positions[ i + 2 ];

                radiusSq =  x * x + y * y + z * z;
                if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;

            }

            this.boundingSphere.radius = Math.sqrt( maxRadiusSq );

        }

    },

    computeVertexNormals: function () {

        if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {

            var i, il;
            var j, jl;

            var nVertexElements = this.attributes[ "position" ].array.length;

            if ( this.attributes[ "normal" ] === undefined ) {

                this.attributes[ "normal" ] = {

                    itemSize: 3,
                    array: new Float32Array( nVertexElements ),
                    numItems: nVertexElements

                };

            } else {

                // reset existing normals to zero

                for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {

                    this.attributes[ "normal" ].array[ i ] = 0;

                }

            }

            var offsets = this.offsets;

            var indices = this.attributes[ "index" ].array;
            var positions = this.attributes[ "position" ].array;
            var normals = this.attributes[ "normal" ].array;

            var vA, vB, vC, x, y, z,

            pA = new THREE.Vector3(),
            pB = new THREE.Vector3(),
            pC = new THREE.Vector3(),

            cb = new THREE.Vector3(),
            ab = new THREE.Vector3();

            for ( j = 0, jl = offsets.length; j < jl; ++ j ) {

                var start = offsets[ j ].start;
                var count = offsets[ j ].count;
                var index = offsets[ j ].index;

                for ( i = start, il = start + count; i < il; i += 3 ) {

                    vA = index + indices[ i ];
                    vB = index + indices[ i + 1 ];
                    vC = index + indices[ i + 2 ];

                    x = positions[ vA * 3 ];
                    y = positions[ vA * 3 + 1 ];
                    z = positions[ vA * 3 + 2 ];
                    pA.set( x, y, z );

                    x = positions[ vB * 3 ];
                    y = positions[ vB * 3 + 1 ];
                    z = positions[ vB * 3 + 2 ];
                    pB.set( x, y, z );

                    x = positions[ vC * 3 ];
                    y = positions[ vC * 3 + 1 ];
                    z = positions[ vC * 3 + 2 ];
                    pC.set( x, y, z );

                    cb.sub( pC, pB );
                    ab.sub( pA, pB );
                    cb.crossSelf( ab );

                    normals[ vA * 3 ] += cb.x;
                    normals[ vA * 3 + 1 ] += cb.y;
                    normals[ vA * 3 + 2 ] += cb.z;

                    normals[ vB * 3 ] += cb.x;
                    normals[ vB * 3 + 1 ] += cb.y;
                    normals[ vB * 3 + 2 ] += cb.z;

                    normals[ vC * 3 ] += cb.x;
                    normals[ vC * 3 + 1 ] += cb.y;
                    normals[ vC * 3 + 2 ] += cb.z;

                }

            }

            // normalize normals

            for ( i = 0, il = normals.length; i < il; i += 3 ) {

                x = normals[ i ];
                y = normals[ i + 1 ];
                z = normals[ i + 2 ];

                var n = 1.0 / Math.sqrt( x * x + y * y + z * z );

                normals[ i ] *= n;
                normals[ i + 1 ] *= n;
                normals[ i + 2 ] *= n;

            }

            this.normalsNeedUpdate = true;

        }

    },

    computeTangents: function () {

        // based on http://www.terathon.com/code/tangent.html
        // (per vertex tangents)

        if ( this.attributes[ "index" ] === undefined ||
             this.attributes[ "position" ] === undefined ||
             this.attributes[ "normal" ] === undefined ||
             this.attributes[ "uv" ] === undefined ) {

            console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
            return;

        }

        var indices = this.attributes[ "index" ].array;
        var positions = this.attributes[ "position" ].array;
        var normals = this.attributes[ "normal" ].array;
        var uvs = this.attributes[ "uv" ].array;

        var nVertices = positions.length / 3;

        if ( this.attributes[ "tangent" ] === undefined ) {

            var nTangentElements = 4 * nVertices;

            this.attributes[ "tangent" ] = {

                itemSize: 4,
                array: new Float32Array( nTangentElements ),
                numItems: nTangentElements

            };

        }

        var tangents = this.attributes[ "tangent" ].array;

        var tan1 = [], tan2 = [];

        for ( var k = 0; k < nVertices; k ++ ) {

            tan1[ k ] = new THREE.Vector3();
            tan2[ k ] = new THREE.Vector3();

        }

        var xA, yA, zA,
            xB, yB, zB,
            xC, yC, zC,

            uA, vA,
            uB, vB,
            uC, vC,

            x1, x2, y1, y2, z1, z2,
            s1, s2, t1, t2, r;

        var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();

        function handleTriangle( a, b, c ) {

            xA = positions[ a * 3 ];
            yA = positions[ a * 3 + 1 ];
            zA = positions[ a * 3 + 2 ];

            xB = positions[ b * 3 ];
            yB = positions[ b * 3 + 1 ];
            zB = positions[ b * 3 + 2 ];

            xC = positions[ c * 3 ];
            yC = positions[ c * 3 + 1 ];
            zC = positions[ c * 3 + 2 ];

            uA = uvs[ a * 2 ];
            vA = uvs[ a * 2 + 1 ];

            uB = uvs[ b * 2 ];
            vB = uvs[ b * 2 + 1 ];

            uC = uvs[ c * 2 ];
            vC = uvs[ c * 2 + 1 ];

            x1 = xB - xA;
            x2 = xC - xA;

            y1 = yB - yA;
            y2 = yC - yA;

            z1 = zB - zA;
            z2 = zC - zA;

            s1 = uB - uA;
            s2 = uC - uA;

            t1 = vB - vA;
            t2 = vC - vA;

            r = 1.0 / ( s1 * t2 - s2 * t1 );

            sdir.set(
                ( t2 * x1 - t1 * x2 ) * r,
                ( t2 * y1 - t1 * y2 ) * r,
                ( t2 * z1 - t1 * z2 ) * r
            );

            tdir.set(
                ( s1 * x2 - s2 * x1 ) * r,
                ( s1 * y2 - s2 * y1 ) * r,
                ( s1 * z2 - s2 * z1 ) * r
            );

            tan1[ a ].addSelf( sdir );
            tan1[ b ].addSelf( sdir );
            tan1[ c ].addSelf( sdir );

            tan2[ a ].addSelf( tdir );
            tan2[ b ].addSelf( tdir );
            tan2[ c ].addSelf( tdir );

        }

        var i, il;
        var j, jl;
        var iA, iB, iC;

        var offsets = this.offsets;

        for ( j = 0, jl = offsets.length; j < jl; ++ j ) {

            var start = offsets[ j ].start;
            var count = offsets[ j ].count;
            var index = offsets[ j ].index;

            for ( i = start, il = start + count; i < il; i += 3 ) {

                iA = index + indices[ i ];
                iB = index + indices[ i + 1 ];
                iC = index + indices[ i + 2 ];

                handleTriangle( iA, iB, iC );

            }

        }

        var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
        var n = new THREE.Vector3(), n2 = new THREE.Vector3();
        var w, t, test;
        var nx, ny, nz;

        function handleVertex( v ) {

            n.x = normals[ v * 3 ];
            n.y = normals[ v * 3 + 1 ];
            n.z = normals[ v * 3 + 2 ];

            n2.copy( n );

            t = tan1[ v ];

            // Gram-Schmidt orthogonalize

            tmp.copy( t );
            tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();

            // Calculate handedness

            tmp2.cross( n2, t );
            test = tmp2.dot( tan2[ v ] );
            w = ( test < 0.0 ) ? -1.0 : 1.0;

            tangents[ v * 4 ]       = tmp.x;
            tangents[ v * 4 + 1 ] = tmp.y;
            tangents[ v * 4 + 2 ] = tmp.z;
            tangents[ v * 4 + 3 ] = w;

        }

        for ( j = 0, jl = offsets.length; j < jl; ++ j ) {

            var start = offsets[ j ].start;
            var count = offsets[ j ].count;
            var index = offsets[ j ].index;

            for ( i = start, il = start + count; i < il; i += 3 ) {

                iA = index + indices[ i ];
                iB = index + indices[ i + 1 ];
                iC = index + indices[ i + 2 ];

                handleVertex( iA );
                handleVertex( iB );
                handleVertex( iC );

            }

        }

        this.hasTangents = true;
        this.tangentsNeedUpdate = true;

    }

};

/**
 * Spline from Tween.js, slightly optimized (and trashed)
 * http://sole.github.com/tween.js/examples/05_spline.html
 *
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Spline = function ( points ) {

    this.points = points;

    var c = [], v3 = { x: 0, y: 0, z: 0 },
    point, intPoint, weight, w2, w3,
    pa, pb, pc, pd;

    this.initFromArray = function( a ) {

        this.points = [];

        for ( var i = 0; i < a.length; i++ ) {

            this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };

        }

    };

    this.getPoint = function ( k ) {

        point = ( this.points.length - 1 ) * k;
        intPoint = Math.floor( point );
        weight = point - intPoint;

        c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
        c[ 1 ] = intPoint;
        c[ 2 ] = intPoint  > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
        c[ 3 ] = intPoint  > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;

        pa = this.points[ c[ 0 ] ];
        pb = this.points[ c[ 1 ] ];
        pc = this.points[ c[ 2 ] ];
        pd = this.points[ c[ 3 ] ];

        w2 = weight * weight;
        w3 = weight * w2;

        v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
        v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
        v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );

        return v3;

    };

    this.getControlPointsArray = function () {

        var i, p, l = this.points.length,
            coords = [];

        for ( i = 0; i < l; i ++ ) {

            p = this.points[ i ];
            coords[ i ] = [ p.x, p.y, p.z ];

        }

        return coords;

    };

    // approximate length by summing linear segments

    this.getLength = function ( nSubDivisions ) {

        var i, index, nSamples, position,
            point = 0, intPoint = 0, oldIntPoint = 0,
            oldPosition = new THREE.Vector3(),
            tmpVec = new THREE.Vector3(),
            chunkLengths = [],
            totalLength = 0;

        // first point has 0 length

        chunkLengths[ 0 ] = 0;

        if ( !nSubDivisions ) nSubDivisions = 100;

        nSamples = this.points.length * nSubDivisions;

        oldPosition.copy( this.points[ 0 ] );

        for ( i = 1; i < nSamples; i ++ ) {

            index = i / nSamples;

            position = this.getPoint( index );
            tmpVec.copy( position );

            totalLength += tmpVec.distanceTo( oldPosition );

            oldPosition.copy( position );

            point = ( this.points.length - 1 ) * index;
            intPoint = Math.floor( point );

            if ( intPoint != oldIntPoint ) {

                chunkLengths[ intPoint ] = totalLength;
                oldIntPoint = intPoint;

            }

        }

        // last point ends with total length

        chunkLengths[ chunkLengths.length ] = totalLength;

        return { chunks: chunkLengths, total: totalLength };

    };

    this.reparametrizeByArcLength = function ( samplingCoef ) {

        var i, j,
            index, indexCurrent, indexNext,
            linearDistance, realDistance,
            sampling, position,
            newpoints = [],
            tmpVec = new THREE.Vector3(),
            sl = this.getLength();

        newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );

        for ( i = 1; i < this.points.length; i++ ) {

            //tmpVec.copy( this.points[ i - 1 ] );
            //linearDistance = tmpVec.distanceTo( this.points[ i ] );

            realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];

            sampling = Math.ceil( samplingCoef * realDistance / sl.total );

            indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
            indexNext = i / ( this.points.length - 1 );

            for ( j = 1; j < sampling - 1; j++ ) {

                index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );

                position = this.getPoint( index );
                newpoints.push( tmpVec.copy( position ).clone() );

            }

            newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );

        }

        this.points = newpoints;

    };

    // Catmull-Rom

    function interpolate( p0, p1, p2, p3, t, t2, t3 ) {

        var v0 = ( p2 - p0 ) * 0.5,
            v1 = ( p3 - p1 ) * 0.5;

        return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;

    };

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author mikael emtinger / http://gomo.se/
 */

THREE.Camera = function () {

    THREE.Object3D.call( this );

    this.matrixWorldInverse = new THREE.Matrix4();

    this.projectionMatrix = new THREE.Matrix4();
    this.projectionMatrixInverse = new THREE.Matrix4();

};

THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );

THREE.Camera.prototype.lookAt = function ( vector ) {

    // TODO: Add hierarchy support.

    this.matrix.lookAt( this.position, vector, this.up );

    if ( this.rotationAutoUpdate === true ) {

        this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );

    }

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {

    THREE.Camera.call( this );

    this.left = left;
    this.right = right;
    this.top = top;
    this.bottom = bottom;

    this.near = ( near !== undefined ) ? near : 0.1;
    this.far = ( far !== undefined ) ? far : 2000;

    this.updateProjectionMatrix();

};

THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );

THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {

    this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author greggman / http://games.greggman.com/
 * @author zz85 / http://www.lab4games.net/zz85/blog
 */

THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {

    THREE.Camera.call( this );

    this.fov = fov !== undefined ? fov : 50;
    this.aspect = aspect !== undefined ? aspect : 1;
    this.near = near !== undefined ? near : 0.1;
    this.far = far !== undefined ? far : 2000;

    this.updateProjectionMatrix();

};

THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );


/**
 * Uses Focal Length (in mm) to estimate and set FOV
 * 35mm (fullframe) camera is used if frame size is not specified;
 * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
 */

THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {

    if ( frameHeight === undefined ) frameHeight = 24;

    this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
    this.updateProjectionMatrix();

}


/**
 * Sets an offset in a larger frustum. This is useful for multi-window or
 * multi-monitor/multi-machine setups.
 *
 * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
 * the monitors are in grid like this
 *
 *   +---+---+---+
 *   | A | B | C |
 *   +---+---+---+
 *   | D | E | F |
 *   +---+---+---+
 *
 * then for each monitor you would call it like this
 *
 *   var w = 1920;
 *   var h = 1080;
 *   var fullWidth = w * 3;
 *   var fullHeight = h * 2;
 *
 *   --A--
 *   camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
 *   --B--
 *   camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
 *   --C--
 *   camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
 *   --D--
 *   camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
 *   --E--
 *   camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
 *   --F--
 *   camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
 *
 *   Note there is no reason monitors have to be the same size or in a grid.
 */

THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {

    this.fullWidth = fullWidth;
    this.fullHeight = fullHeight;
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;

    this.updateProjectionMatrix();

};


THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {

    if ( this.fullWidth ) {

        var aspect = this.fullWidth / this.fullHeight;
        var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
        var bottom = -top;
        var left = aspect * bottom;
        var right = aspect * top;
        var width = Math.abs( right - left );
        var height = Math.abs( top - bottom );

        this.projectionMatrix.makeFrustum(
            left + this.x * width / this.fullWidth,
            left + ( this.x + this.width ) * width / this.fullWidth,
            top - ( this.y + this.height ) * height / this.fullHeight,
            top - this.y * height / this.fullHeight,
            this.near,
            this.far
        );

    } else {

        this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );

    }

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Light = function ( hex ) {

    THREE.Object3D.call( this );

    this.color = new THREE.Color( hex );

};

THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.AmbientLight = function ( hex ) {

    THREE.Light.call( this, hex );

};

THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.DirectionalLight = function ( hex, intensity, distance ) {

    THREE.Light.call( this, hex );

    this.position = new THREE.Vector3( 0, 1, 0 );
    this.target = new THREE.Object3D();

    this.intensity = ( intensity !== undefined ) ? intensity : 1;
    this.distance = ( distance !== undefined ) ? distance : 0;

    this.castShadow = false;
    this.onlyShadow = false;

    //

    this.shadowCameraNear = 50;
    this.shadowCameraFar = 5000;

    this.shadowCameraLeft = -500;
    this.shadowCameraRight = 500;
    this.shadowCameraTop = 500;
    this.shadowCameraBottom = -500;

    this.shadowCameraVisible = false;

    this.shadowBias = 0;
    this.shadowDarkness = 0.5;

    this.shadowMapWidth = 512;
    this.shadowMapHeight = 512;

    //

    this.shadowCascade = false;

    this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
    this.shadowCascadeCount = 2;

    this.shadowCascadeBias = [ 0, 0, 0 ];
    this.shadowCascadeWidth = [ 512, 512, 512 ];
    this.shadowCascadeHeight = [ 512, 512, 512 ];

    this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
    this.shadowCascadeFarZ  = [  0.990, 0.998, 1.000 ];

    this.shadowCascadeArray = [];

    //

    this.shadowMap = null;
    this.shadowMapSize = null;
    this.shadowCamera = null;
    this.shadowMatrix = null;

};

THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {

    THREE.Light.call( this, skyColorHex );

    this.groundColor = new THREE.Color( groundColorHex );

    this.position = new THREE.Vector3( 0, 100, 0 );

    this.intensity = ( intensity !== undefined ) ? intensity : 1;

};

THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.PointLight = function ( hex, intensity, distance ) {

    THREE.Light.call( this, hex );

    this.position = new THREE.Vector3( 0, 0, 0 );
    this.intensity = ( intensity !== undefined ) ? intensity : 1;
    this.distance = ( distance !== undefined ) ? distance : 0;

};

THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {

    THREE.Light.call( this, hex );

    this.position = new THREE.Vector3( 0, 1, 0 );
    this.target = new THREE.Object3D();

    this.intensity = ( intensity !== undefined ) ? intensity : 1;
    this.distance = ( distance !== undefined ) ? distance : 0;
    this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
    this.exponent = ( exponent !== undefined ) ? exponent : 10;

    this.castShadow = false;
    this.onlyShadow = false;

    //

    this.shadowCameraNear = 50;
    this.shadowCameraFar = 5000;
    this.shadowCameraFov = 50;

    this.shadowCameraVisible = false;

    this.shadowBias = 0;
    this.shadowDarkness = 0.5;

    this.shadowMapWidth = 512;
    this.shadowMapHeight = 512;

    //

    this.shadowMap = null;
    this.shadowMapSize = null;
    this.shadowCamera = null;
    this.shadowMatrix = null;

};

THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Loader = function ( showStatus ) {

    this.showStatus = showStatus;
    this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;

    this.onLoadStart = function () {};
    this.onLoadProgress = function () {};
    this.onLoadComplete = function () {};

};

THREE.Loader.prototype = {

    constructor: THREE.Loader,

    crossOrigin: 'anonymous',

    addStatusElement: function () {

        var e = document.createElement( "div" );

        e.style.position = "absolute";
        e.style.right = "0px";
        e.style.top = "0px";
        e.style.fontSize = "0.8em";
        e.style.textAlign = "left";
        e.style.background = "rgba(0,0,0,0.25)";
        e.style.color = "#fff";
        e.style.width = "120px";
        e.style.padding = "0.5em 0.5em 0.5em 0.5em";
        e.style.zIndex = 1000;

        e.innerHTML = "Loading ...";

        return e;

    },

    updateProgress: function ( progress ) {

        var message = "Loaded ";

        if ( progress.total ) {

            message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";


        } else {

            message += ( progress.loaded / 1000 ).toFixed(2) + " KB";

        }

        this.statusDomElement.innerHTML = message;

    },

    extractUrlBase: function ( url ) {

        var parts = url.split( '/' );
        parts.pop();
        return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';

    },

    initMaterials: function ( scope, materials, texturePath ) {

        scope.materials = [];

        for ( var i = 0; i < materials.length; ++ i ) {

            scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );

        }

    },

    hasNormals: function ( scope ) {

        var m, i, il = scope.materials.length;

        for( i = 0; i < il; i ++ ) {

            m = scope.materials[ i ];

            if ( m instanceof THREE.ShaderMaterial ) return true;

        }

        return false;

    },

    createMaterial: function ( m, texturePath ) {

        var _this = this;

        function is_pow2( n ) {

            var l = Math.log( n ) / Math.LN2;
            return Math.floor( l ) == l;

        }

        function nearest_pow2( n ) {

            var l = Math.log( n ) / Math.LN2;
            return Math.pow( 2, Math.round(  l ) );

        }

        function load_image( where, url ) {

            var image = new Image();

            image.onload = function () {

                if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {

                    var width = nearest_pow2( this.width );
                    var height = nearest_pow2( this.height );

                    where.image.width = width;
                    where.image.height = height;
                    where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );

                } else {

                    where.image = this;

                }

                where.needsUpdate = true;

            };

            image.crossOrigin = _this.crossOrigin;
            image.src = url;

        }

        function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {

            var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
            var fullPath = texturePath + "/" + sourceFile;

            if ( isCompressed ) {

                var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );

                where[ name ] = texture;

            } else {

                var texture = document.createElement( 'canvas' );

                where[ name ] = new THREE.Texture( texture );

            }

            where[ name ].sourceFile = sourceFile;

            if( repeat ) {

                where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );

                if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
                if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;

            }

            if ( offset ) {

                where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );

            }

            if ( wrap ) {

                var wrapMap = {
                    "repeat": THREE.RepeatWrapping,
                    "mirror": THREE.MirroredRepeatWrapping
                }

                if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
                if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];

            }

            if ( anisotropy ) {

                where[ name ].anisotropy = anisotropy;

            }

            if ( ! isCompressed ) {

                load_image( where[ name ], fullPath );

            }

        }

        function rgb2hex( rgb ) {

            return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;

        }

        // defaults

        var mtype = "MeshLambertMaterial";
        var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };

        // parameters from model file

        if ( m.shading ) {

            var shading = m.shading.toLowerCase();

            if ( shading === "phong" ) mtype = "MeshPhongMaterial";
            else if ( shading === "basic" ) mtype = "MeshBasicMaterial";

        }

        if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {

            mpars.blending = THREE[ m.blending ];

        }

        if ( m.transparent !== undefined || m.opacity < 1.0 ) {

            mpars.transparent = m.transparent;

        }

        if ( m.depthTest !== undefined ) {

            mpars.depthTest = m.depthTest;

        }

        if ( m.depthWrite !== undefined ) {

            mpars.depthWrite = m.depthWrite;

        }

        if ( m.visible !== undefined ) {

            mpars.visible = m.visible;

        }

        if ( m.flipSided !== undefined ) {

            mpars.side = THREE.BackSide;

        }

        if ( m.doubleSided !== undefined ) {

            mpars.side = THREE.DoubleSide;

        }

        if ( m.wireframe !== undefined ) {

            mpars.wireframe = m.wireframe;

        }

        if ( m.vertexColors !== undefined ) {

            if ( m.vertexColors === "face" ) {

                mpars.vertexColors = THREE.FaceColors;

            } else if ( m.vertexColors ) {

                mpars.vertexColors = THREE.VertexColors;

            }

        }

        // colors

        if ( m.colorDiffuse ) {

            mpars.color = rgb2hex( m.colorDiffuse );

        } else if ( m.DbgColor ) {

            mpars.color = m.DbgColor;

        }

        if ( m.colorSpecular ) {

            mpars.specular = rgb2hex( m.colorSpecular );

        }

        if ( m.colorAmbient ) {

            mpars.ambient = rgb2hex( m.colorAmbient );

        }

        // modifiers

        if ( m.transparency ) {

            mpars.opacity = m.transparency;

        }

        if ( m.specularCoef ) {

            mpars.shininess = m.specularCoef;

        }

        // textures

        if ( m.mapDiffuse && texturePath ) {

            create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );

        }

        if ( m.mapLight && texturePath ) {

            create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );

        }

        if ( m.mapBump && texturePath ) {

            create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );

        }

        if ( m.mapNormal && texturePath ) {

            create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );

        }

        if ( m.mapSpecular && texturePath ) {

            create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );

        }

        //

        if ( m.mapBumpScale ) {

            mpars.bumpScale = m.mapBumpScale;

        }

        // special case for normal mapped material

        if ( m.mapNormal ) {

            var shader = THREE.ShaderUtils.lib[ "normal" ];
            var uniforms = THREE.UniformsUtils.clone( shader.uniforms );

            uniforms[ "tNormal" ].value = mpars.normalMap;

            if ( m.mapNormalFactor ) {

                uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );

            }

            if ( mpars.map ) {

                uniforms[ "tDiffuse" ].value = mpars.map;
                uniforms[ "enableDiffuse" ].value = true;

            }

            if ( mpars.specularMap ) {

                uniforms[ "tSpecular" ].value = mpars.specularMap;
                uniforms[ "enableSpecular" ].value = true;

            }

            if ( mpars.lightMap ) {

                uniforms[ "tAO" ].value = mpars.lightMap;
                uniforms[ "enableAO" ].value = true;

            }

            // for the moment don't handle displacement texture

            uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
            uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
            uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );

            uniforms[ "uShininess" ].value = mpars.shininess;

            if ( mpars.opacity !== undefined ) {

                uniforms[ "uOpacity" ].value = mpars.opacity;

            }

            var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
            var material = new THREE.ShaderMaterial( parameters );

        } else {

            var material = new THREE[ mtype ]( mpars );

        }

        if ( m.DbgName !== undefined ) material.name = m.DbgName;

        return material;

    }

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.BinaryLoader = function ( showStatus ) {

    THREE.Loader.call( this, showStatus );

};

THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );

// Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
//  - binary models consist of two files: JS and BIN
//  - parameters
//        - url (required)
//        - callback (required)
//        - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
//        - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)

THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {

    texturePath = texturePath ? texturePath : this.extractUrlBase( url );
    binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );

    var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;

    this.onLoadStart();

    // #1 load JS part via web worker

    this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );

};

THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {

        if ( xhr.readyState == 4 ) {

            if ( xhr.status == 200 || xhr.status == 0 ) {

                var json = JSON.parse( xhr.responseText );
                context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );

            } else {

                console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );

            }

        }

    };

    xhr.open( "GET", url, true );
    xhr.send( null );

};

THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {

    var xhr = new XMLHttpRequest(),
        url = binaryPath + "/" + json.buffers;

    var length = 0;

    xhr.onreadystatechange = function () {

        if ( xhr.readyState == 4 ) {

            if ( xhr.status == 200 || xhr.status == 0 ) {

                var buffer = xhr.response;
                if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
                THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );

            } else {

                console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );

            }

        } else if ( xhr.readyState == 3 ) {

            if ( callbackProgress ) {

                if ( length == 0 ) {

                    length = xhr.getResponseHeader( "Content-Length" );

                }

                callbackProgress( { total: length, loaded: xhr.responseText.length } );

            }

        } else if ( xhr.readyState == 2 ) {

            length = xhr.getResponseHeader( "Content-Length" );

        }

    };

    xhr.open( "GET", url, true );
    xhr.responseType = "arraybuffer";
    xhr.send( null );

};

// Binary AJAX parser

THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {

    var Model = function ( texturePath ) {

        var scope = this,
            currentOffset = 0,
            md,
            normals = [],
            uvs = [],
            start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
            start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
            tri_size, quad_size,
            len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
            len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;


        THREE.Geometry.call( this );

        THREE.Loader.prototype.initMaterials( scope, materials, texturePath );

        md = parseMetaData( data, currentOffset );

        currentOffset += md.header_bytes;
/*
        md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
        md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
        md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
        md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
*/
        // buffers sizes

        tri_size =  md.vertex_index_bytes * 3 + md.material_index_bytes;
        quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;

        len_tri_flat      = md.ntri_flat      * ( tri_size );
        len_tri_smooth    = md.ntri_smooth    * ( tri_size + md.normal_index_bytes * 3 );
        len_tri_flat_uv   = md.ntri_flat_uv   * ( tri_size + md.uv_index_bytes * 3 );
        len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );

        len_quad_flat      = md.nquad_flat      * ( quad_size );
        len_quad_smooth    = md.nquad_smooth    * ( quad_size + md.normal_index_bytes * 4 );
        len_quad_flat_uv   = md.nquad_flat_uv   * ( quad_size + md.uv_index_bytes * 4 );
        len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );

        // read buffers

        currentOffset += init_vertices( currentOffset );

        currentOffset += init_normals( currentOffset );
        currentOffset += handlePadding( md.nnormals * 3 );

        currentOffset += init_uvs( currentOffset );

        start_tri_flat         = currentOffset;
        start_tri_smooth    = start_tri_flat    + len_tri_flat    + handlePadding( md.ntri_flat * 2 );
        start_tri_flat_uv   = start_tri_smooth  + len_tri_smooth  + handlePadding( md.ntri_smooth * 2 );
        start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );

        start_quad_flat     = start_tri_smooth_uv + len_tri_smooth_uv  + handlePadding( md.ntri_smooth_uv * 2 );
        start_quad_smooth   = start_quad_flat     + len_quad_flat       + handlePadding( md.nquad_flat * 2 );
        start_quad_flat_uv  = start_quad_smooth   + len_quad_smooth    + handlePadding( md.nquad_smooth * 2 );
        start_quad_smooth_uv= start_quad_flat_uv  + len_quad_flat_uv   + handlePadding( md.nquad_flat_uv * 2 );

        // have to first process faces with uvs
        // so that face and uv indices match

        init_triangles_flat_uv( start_tri_flat_uv );
        init_triangles_smooth_uv( start_tri_smooth_uv );

        init_quads_flat_uv( start_quad_flat_uv );
        init_quads_smooth_uv( start_quad_smooth_uv );

        // now we can process untextured faces

        init_triangles_flat( start_tri_flat );
        init_triangles_smooth( start_tri_smooth );

        init_quads_flat( start_quad_flat );
        init_quads_smooth( start_quad_smooth );

        this.computeCentroids();
        this.computeFaceNormals();

        if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();

        function handlePadding( n ) {

            return ( n % 4 ) ? ( 4 - n % 4 ) : 0;

        };

        function parseMetaData( data, offset ) {

            var metaData = {

                'signature'               :parseString( data, offset,  12 ),
                'header_bytes'            :parseUChar8( data, offset + 12 ),

                'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
                'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
                'uv_coordinate_bytes'     :parseUChar8( data, offset + 15 ),

                'vertex_index_bytes'      :parseUChar8( data, offset + 16 ),
                'normal_index_bytes'      :parseUChar8( data, offset + 17 ),
                'uv_index_bytes'          :parseUChar8( data, offset + 18 ),
                'material_index_bytes'    :parseUChar8( data, offset + 19 ),

                'nvertices'    :parseUInt32( data, offset + 20 ),
                'nnormals'     :parseUInt32( data, offset + 20 + 4*1 ),
                'nuvs'         :parseUInt32( data, offset + 20 + 4*2 ),

                'ntri_flat'      :parseUInt32( data, offset + 20 + 4*3 ),
                'ntri_smooth'    :parseUInt32( data, offset + 20 + 4*4 ),
                'ntri_flat_uv'   :parseUInt32( data, offset + 20 + 4*5 ),
                'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),

                'nquad_flat'      :parseUInt32( data, offset + 20 + 4*7 ),
                'nquad_smooth'    :parseUInt32( data, offset + 20 + 4*8 ),
                'nquad_flat_uv'   :parseUInt32( data, offset + 20 + 4*9 ),
                'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )

            };
/*
            console.log( "signature: " + metaData.signature );

            console.log( "header_bytes: " + metaData.header_bytes );
            console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
            console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
            console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );

            console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
            console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
            console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
            console.log( "material_index_bytes: " + metaData.material_index_bytes );

            console.log( "nvertices: " + metaData.nvertices );
            console.log( "nnormals: " + metaData.nnormals );
            console.log( "nuvs: " + metaData.nuvs );

            console.log( "ntri_flat: " + metaData.ntri_flat );
            console.log( "ntri_smooth: " + metaData.ntri_smooth );
            console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
            console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );

            console.log( "nquad_flat: " + metaData.nquad_flat );
            console.log( "nquad_smooth: " + metaData.nquad_smooth );
            console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
            console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );

            var total = metaData.header_bytes
                      + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
                      + metaData.nnormals * metaData.normal_coordinate_bytes * 3
                      + metaData.nuvs * metaData.uv_coordinate_bytes * 2
                      + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
                      + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
                      + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
                      + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
                      + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
                      + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
                      + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
                      + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
            console.log( "total bytes: " + total );
*/

            return metaData;

        };

        function parseString( data, offset, length ) {

            var charArray = new Uint8Array( data, offset, length );

            var text = "";

            for ( var i = 0; i < length; i ++ ) {

                text += String.fromCharCode( charArray[ offset + i ] );

            }

            return text;

        };

        function parseUChar8( data, offset ) {

            var charArray = new Uint8Array( data, offset, 1 );

            return charArray[ 0 ];

        };

        function parseUInt32( data, offset ) {

            var intArray = new Uint32Array( data, offset, 1 );

            return intArray[ 0 ];

        };

        function init_vertices( start ) {

            var nElements = md.nvertices;

            var coordArray = new Float32Array( data, start, nElements * 3 );

            var i, x, y, z;

            for( i = 0; i < nElements; i ++ ) {

                x = coordArray[ i * 3 ];
                y = coordArray[ i * 3 + 1 ];
                z = coordArray[ i * 3 + 2 ];

                vertex( scope, x, y, z );

            }

            return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;

        };

        function init_normals( start ) {

            var nElements = md.nnormals;

            if ( nElements ) {

                var normalArray = new Int8Array( data, start, nElements * 3 );

                var i, x, y, z;

                for( i = 0; i < nElements; i ++ ) {

                    x = normalArray[ i * 3 ];
                    y = normalArray[ i * 3 + 1 ];
                    z = normalArray[ i * 3 + 2 ];

                    normals.push( x/127, y/127, z/127 );

                }

            }

            return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;

        };

        function init_uvs( start ) {

            var nElements = md.nuvs;

            if ( nElements ) {

                var uvArray = new Float32Array( data, start, nElements * 2 );

                var i, u, v;

                for( i = 0; i < nElements; i ++ ) {

                    u = uvArray[ i * 2 ];
                    v = uvArray[ i * 2 + 1 ];

                    uvs.push( u, v );

                }

            }

            return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;

        };

        function init_uvs3( nElements, offset ) {

            var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;

            var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );

            for( i = 0; i < nElements; i ++ ) {

                uva = uvIndexBuffer[ i * 3 ];
                uvb = uvIndexBuffer[ i * 3 + 1 ];
                uvc = uvIndexBuffer[ i * 3 + 2 ];

                u1 = uvs[ uva*2 ];
                v1 = uvs[ uva*2 + 1 ];

                u2 = uvs[ uvb*2 ];
                v2 = uvs[ uvb*2 + 1 ];

                u3 = uvs[ uvc*2 ];
                v3 = uvs[ uvc*2 + 1 ];

                uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );

            }

        };

        function init_uvs4( nElements, offset ) {

            var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;

            var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );

            for( i = 0; i < nElements; i ++ ) {

                uva = uvIndexBuffer[ i * 4 ];
                uvb = uvIndexBuffer[ i * 4 + 1 ];
                uvc = uvIndexBuffer[ i * 4 + 2 ];
                uvd = uvIndexBuffer[ i * 4 + 3 ];

                u1 = uvs[ uva*2 ];
                v1 = uvs[ uva*2 + 1 ];

                u2 = uvs[ uvb*2 ];
                v2 = uvs[ uvb*2 + 1 ];

                u3 = uvs[ uvc*2 ];
                v3 = uvs[ uvc*2 + 1 ];

                u4 = uvs[ uvd*2 ];
                v4 = uvs[ uvd*2 + 1 ];

                uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );

            }

        };

        function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {

            var i, a, b, c, m;

            var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
            var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );

            for( i = 0; i < nElements; i ++ ) {

                a = vertexIndexBuffer[ i * 3 ];
                b = vertexIndexBuffer[ i * 3 + 1 ];
                c = vertexIndexBuffer[ i * 3 + 2 ];

                m = materialIndexBuffer[ i ];

                f3( scope, a, b, c, m );

            }

        };

        function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {

            var i, a, b, c, d, m;

            var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
            var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );

            for( i = 0; i < nElements; i ++ ) {

                a = vertexIndexBuffer[ i * 4 ];
                b = vertexIndexBuffer[ i * 4 + 1 ];
                c = vertexIndexBuffer[ i * 4 + 2 ];
                d = vertexIndexBuffer[ i * 4 + 3 ];

                m = materialIndexBuffer[ i ];

                f4( scope, a, b, c, d, m );

            }

        };

        function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {

            var i, a, b, c, m;
            var na, nb, nc;

            var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
            var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
            var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );

            for( i = 0; i < nElements; i ++ ) {

                a = vertexIndexBuffer[ i * 3 ];
                b = vertexIndexBuffer[ i * 3 + 1 ];
                c = vertexIndexBuffer[ i * 3 + 2 ];

                na = normalIndexBuffer[ i * 3 ];
                nb = normalIndexBuffer[ i * 3 + 1 ];
                nc = normalIndexBuffer[ i * 3 + 2 ];

                m = materialIndexBuffer[ i ];

                f3n( scope, normals, a, b, c, m, na, nb, nc );

            }

        };

        function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {

            var i, a, b, c, d, m;
            var na, nb, nc, nd;

            var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
            var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
            var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );

            for( i = 0; i < nElements; i ++ ) {

                a = vertexIndexBuffer[ i * 4 ];
                b = vertexIndexBuffer[ i * 4 + 1 ];
                c = vertexIndexBuffer[ i * 4 + 2 ];
                d = vertexIndexBuffer[ i * 4 + 3 ];

                na = normalIndexBuffer[ i * 4 ];
                nb = normalIndexBuffer[ i * 4 + 1 ];
                nc = normalIndexBuffer[ i * 4 + 2 ];
                nd = normalIndexBuffer[ i * 4 + 3 ];

                m = materialIndexBuffer[ i ];

                f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );

            }

        };

        function init_triangles_flat( start ) {

            var nElements = md.ntri_flat;

            if ( nElements ) {

                var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
                init_faces3_flat( nElements, start, offsetMaterials );

            }

        };

        function init_triangles_flat_uv( start ) {

            var nElements = md.ntri_flat_uv;

            if ( nElements ) {

                var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
                var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;

                init_faces3_flat( nElements, start, offsetMaterials );
                init_uvs3( nElements, offsetUvs );

            }

        };

        function init_triangles_smooth( start ) {

            var nElements = md.ntri_smooth;

            if ( nElements ) {

                var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
                var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;

                init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );

            }

        };

        function init_triangles_smooth_uv( start ) {

            var nElements = md.ntri_smooth_uv;

            if ( nElements ) {

                var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
                var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
                var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;

                init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
                init_uvs3( nElements, offsetUvs );

            }

        };

        function init_quads_flat( start ) {

            var nElements = md.nquad_flat;

            if ( nElements ) {

                var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
                init_faces4_flat( nElements, start, offsetMaterials );

            }

        };

        function init_quads_flat_uv( start ) {

            var nElements = md.nquad_flat_uv;

            if ( nElements ) {

                var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
                var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;

                init_faces4_flat( nElements, start, offsetMaterials );
                init_uvs4( nElements, offsetUvs );

            }

        };

        function init_quads_smooth( start ) {

            var nElements = md.nquad_smooth;

            if ( nElements ) {

                var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
                var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;

                init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );

            }

        };

        function init_quads_smooth_uv( start ) {

            var nElements = md.nquad_smooth_uv;

            if ( nElements ) {

                var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
                var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
                var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;

                init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
                init_uvs4( nElements, offsetUvs );

            }

        };

    };

    function vertex ( scope, x, y, z ) {

        scope.vertices.push( new THREE.Vector3( x, y, z ) );

    };

    function f3 ( scope, a, b, c, mi ) {

        scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );

    };

    function f4 ( scope, a, b, c, d, mi ) {

        scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );

    };

    function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {

        var nax = normals[ na*3     ],
            nay = normals[ na*3 + 1 ],
            naz = normals[ na*3 + 2 ],

            nbx = normals[ nb*3     ],
            nby = normals[ nb*3 + 1 ],
            nbz = normals[ nb*3 + 2 ],

            ncx = normals[ nc*3     ],
            ncy = normals[ nc*3 + 1 ],
            ncz = normals[ nc*3 + 2 ];

        scope.faces.push( new THREE.Face3( a, b, c,
                          [new THREE.Vector3( nax, nay, naz ),
                           new THREE.Vector3( nbx, nby, nbz ),
                           new THREE.Vector3( ncx, ncy, ncz )],
                          null,
                          mi ) );

    };

    function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {

        var nax = normals[ na*3     ],
            nay = normals[ na*3 + 1 ],
            naz = normals[ na*3 + 2 ],

            nbx = normals[ nb*3     ],
            nby = normals[ nb*3 + 1 ],
            nbz = normals[ nb*3 + 2 ],

            ncx = normals[ nc*3     ],
            ncy = normals[ nc*3 + 1 ],
            ncz = normals[ nc*3 + 2 ],

            ndx = normals[ nd*3     ],
            ndy = normals[ nd*3 + 1 ],
            ndz = normals[ nd*3 + 2 ];

        scope.faces.push( new THREE.Face4( a, b, c, d,
                          [new THREE.Vector3( nax, nay, naz ),
                           new THREE.Vector3( nbx, nby, nbz ),
                           new THREE.Vector3( ncx, ncy, ncz ),
                           new THREE.Vector3( ndx, ndy, ndz )],
                          null,
                          mi ) );

    };

    function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {

        var uv = [];
        uv.push( new THREE.UV( u1, v1 ) );
        uv.push( new THREE.UV( u2, v2 ) );
        uv.push( new THREE.UV( u3, v3 ) );
        where.push( uv );

    };

    function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {

        var uv = [];
        uv.push( new THREE.UV( u1, v1 ) );
        uv.push( new THREE.UV( u2, v2 ) );
        uv.push( new THREE.UV( u3, v3 ) );
        uv.push( new THREE.UV( u4, v4 ) );
        where.push( uv );

    };

    Model.prototype = Object.create( THREE.Geometry.prototype );

    callback( new Model( texturePath ) );

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.ImageLoader = function () {

    THREE.EventTarget.call( this );

    this.crossOrigin = null;

};

THREE.ImageLoader.prototype = {

    constructor: THREE.ImageLoader,

    load: function ( url, image ) {

        var scope = this;

        if ( image === undefined ) image = new Image();

        image.addEventListener( 'load', function () {

            scope.dispatchEvent( { type: 'load', content: image } );

        }, false );

        image.addEventListener( 'error', function () {

            scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );

        }, false );

        if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;

        image.src = url;

    }

}
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.JSONLoader = function ( showStatus ) {

    THREE.Loader.call( this, showStatus );

};

THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );

THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {

    var scope = this;

    texturePath = texturePath ? texturePath : this.extractUrlBase( url );

    this.onLoadStart();
    this.loadAjaxJSON( this, url, callback, texturePath );

};

THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {

    var xhr = new XMLHttpRequest();

    var length = 0;

    xhr.onreadystatechange = function () {

        if ( xhr.readyState === xhr.DONE ) {

            if ( xhr.status === 200 || xhr.status === 0 ) {

                if ( xhr.responseText ) {

                    var json = JSON.parse( xhr.responseText );
                    context.createModel( json, callback, texturePath );

                } else {

                    console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );

                }

                // in context of more complex asset initialization
                // do not block on single failed file
                // maybe should go even one more level up

                context.onLoadComplete();

            } else {

                console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );

            }

        } else if ( xhr.readyState === xhr.LOADING ) {

            if ( callbackProgress ) {

                if ( length === 0 ) {

                    length = xhr.getResponseHeader( "Content-Length" );

                }

                callbackProgress( { total: length, loaded: xhr.responseText.length } );

            }

        } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {

            length = xhr.getResponseHeader( "Content-Length" );

        }

    };

    xhr.open( "GET", url, true );
    xhr.send( null );

};

THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {

    var scope = this,
    geometry = new THREE.Geometry(),
    scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;

    this.initMaterials( geometry, json.materials, texturePath );

    parseModel( scale );

    parseSkin();
    parseMorphing( scale );

    geometry.computeCentroids();
    geometry.computeFaceNormals();

    if ( this.hasNormals( geometry ) ) geometry.computeTangents();


    function parseModel( scale ) {

        function isBitSet( value, position ) {

            return value & ( 1 << position );

        }

        var i, j, fi,

        offset, zLength, nVertices,

        colorIndex, normalIndex, uvIndex, materialIndex,

        type,
        isQuad,
        hasMaterial,
        hasFaceUv, hasFaceVertexUv,
        hasFaceNormal, hasFaceVertexNormal,
        hasFaceColor, hasFaceVertexColor,

        vertex, face, color, normal,

        uvLayer, uvs, u, v,

        faces = json.faces,
        vertices = json.vertices,
        normals = json.normals,
        colors = json.colors,

        nUvLayers = 0;

        // disregard empty arrays

        for ( i = 0; i < json.uvs.length; i++ ) {

            if ( json.uvs[ i ].length ) nUvLayers ++;

        }

        for ( i = 0; i < nUvLayers; i++ ) {

            geometry.faceUvs[ i ] = [];
            geometry.faceVertexUvs[ i ] = [];

        }

        offset = 0;
        zLength = vertices.length;

        while ( offset < zLength ) {

            vertex = new THREE.Vector3();

            vertex.x = vertices[ offset ++ ] * scale;
            vertex.y = vertices[ offset ++ ] * scale;
            vertex.z = vertices[ offset ++ ] * scale;

            geometry.vertices.push( vertex );

        }

        offset = 0;
        zLength = faces.length;

        while ( offset < zLength ) {

            type = faces[ offset ++ ];


            isQuad              = isBitSet( type, 0 );
            hasMaterial         = isBitSet( type, 1 );
            hasFaceUv           = isBitSet( type, 2 );
            hasFaceVertexUv     = isBitSet( type, 3 );
            hasFaceNormal       = isBitSet( type, 4 );
            hasFaceVertexNormal = isBitSet( type, 5 );
            hasFaceColor        = isBitSet( type, 6 );
            hasFaceVertexColor  = isBitSet( type, 7 );

            //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);

            if ( isQuad ) {

                face = new THREE.Face4();

                face.a = faces[ offset ++ ];
                face.b = faces[ offset ++ ];
                face.c = faces[ offset ++ ];
                face.d = faces[ offset ++ ];

                nVertices = 4;

            } else {

                face = new THREE.Face3();

                face.a = faces[ offset ++ ];
                face.b = faces[ offset ++ ];
                face.c = faces[ offset ++ ];

                nVertices = 3;

            }

            if ( hasMaterial ) {

                materialIndex = faces[ offset ++ ];
                face.materialIndex = materialIndex;

            }

            // to get face <=> uv index correspondence

            fi = geometry.faces.length;

            if ( hasFaceUv ) {

                for ( i = 0; i < nUvLayers; i++ ) {

                    uvLayer = json.uvs[ i ];

                    uvIndex = faces[ offset ++ ];

                    u = uvLayer[ uvIndex * 2 ];
                    v = uvLayer[ uvIndex * 2 + 1 ];

                    geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );

                }

            }

            if ( hasFaceVertexUv ) {

                for ( i = 0; i < nUvLayers; i++ ) {

                    uvLayer = json.uvs[ i ];

                    uvs = [];

                    for ( j = 0; j < nVertices; j ++ ) {

                        uvIndex = faces[ offset ++ ];

                        u = uvLayer[ uvIndex * 2 ];
                        v = uvLayer[ uvIndex * 2 + 1 ];

                        uvs[ j ] = new THREE.UV( u, v );

                    }

                    geometry.faceVertexUvs[ i ][ fi ] = uvs;

                }

            }

            if ( hasFaceNormal ) {

                normalIndex = faces[ offset ++ ] * 3;

                normal = new THREE.Vector3();

                normal.x = normals[ normalIndex ++ ];
                normal.y = normals[ normalIndex ++ ];
                normal.z = normals[ normalIndex ];

                face.normal = normal;

            }

            if ( hasFaceVertexNormal ) {

                for ( i = 0; i < nVertices; i++ ) {

                    normalIndex = faces[ offset ++ ] * 3;

                    normal = new THREE.Vector3();

                    normal.x = normals[ normalIndex ++ ];
                    normal.y = normals[ normalIndex ++ ];
                    normal.z = normals[ normalIndex ];

                    face.vertexNormals.push( normal );

                }

            }


            if ( hasFaceColor ) {

                colorIndex = faces[ offset ++ ];

                color = new THREE.Color( colors[ colorIndex ] );
                face.color = color;

            }


            if ( hasFaceVertexColor ) {

                for ( i = 0; i < nVertices; i++ ) {

                    colorIndex = faces[ offset ++ ];

                    color = new THREE.Color( colors[ colorIndex ] );
                    face.vertexColors.push( color );

                }

            }

            geometry.faces.push( face );

        }

    };

    function parseSkin() {

        var i, l, x, y, z, w, a, b, c, d;

        if ( json.skinWeights ) {

            for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {

                x = json.skinWeights[ i     ];
                y = json.skinWeights[ i + 1 ];
                z = 0;
                w = 0;

                geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );

            }

        }

        if ( json.skinIndices ) {

            for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {

                a = json.skinIndices[ i     ];
                b = json.skinIndices[ i + 1 ];
                c = 0;
                d = 0;

                geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );

            }

        }

        geometry.bones = json.bones;
        geometry.animation = json.animation;

    };

    function parseMorphing( scale ) {

        if ( json.morphTargets !== undefined ) {

            var i, l, v, vl, dstVertices, srcVertices;

            for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {

                geometry.morphTargets[ i ] = {};
                geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
                geometry.morphTargets[ i ].vertices = [];

                dstVertices = geometry.morphTargets[ i ].vertices;
                srcVertices = json.morphTargets [ i ].vertices;

                for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {

                    var vertex = new THREE.Vector3();
                    vertex.x = srcVertices[ v ] * scale;
                    vertex.y = srcVertices[ v + 1 ] * scale;
                    vertex.z = srcVertices[ v + 2 ] * scale;

                    dstVertices.push( vertex );

                }

            }

        }

        if ( json.morphColors !== undefined ) {

            var i, l, c, cl, dstColors, srcColors, color;

            for ( i = 0, l = json.morphColors.length; i < l; i++ ) {

                geometry.morphColors[ i ] = {};
                geometry.morphColors[ i ].name = json.morphColors[ i ].name;
                geometry.morphColors[ i ].colors = [];

                dstColors = geometry.morphColors[ i ].colors;
                srcColors = json.morphColors [ i ].colors;

                for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {

                    color = new THREE.Color( 0xffaa00 );
                    color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
                    dstColors.push( color );

                }

            }

        }

    };

    callback( geometry );

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.LoadingMonitor = function () {

    THREE.EventTarget.call( this );

    var scope = this;

    var loaded = 0;
    var total = 0;

    var onLoad = function ( event ) {

        loaded ++;

        scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );

        if ( loaded === total ) {

            scope.dispatchEvent( { type: 'load' } );

        }

    };

    this.add = function ( loader ) {

        total ++;

        loader.addEventListener( 'load', onLoad, false );

    };

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.GeometryLoader = function () {

    THREE.EventTarget.call( this );

    this.crossOrigin = null;
    this.path = null;


};

THREE.GeometryLoader.prototype = {

    constructor: THREE.GeometryLoader,

    load: function ( url ) {

        var scope = this;
        var geometry = null;

        if ( scope.path === null ) {

            var parts = url.split( '/' ); parts.pop();
            scope.path = ( parts.length < 1 ? '.' : parts.join( '/' ) );

        }

        //

        var xhr = new XMLHttpRequest();

        xhr.addEventListener( 'load', function ( event ) {

            if ( event.target.responseText ) {

                geometry = scope.parse( JSON.parse( event.target.responseText ), monitor );

            } else {

                scope.dispatchEvent( { type: 'error', message: 'Invalid file [' + url + ']' } );

            }

        }, false );

        xhr.addEventListener( 'error', function () {

            scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );

        }, false );

        xhr.open( 'GET', url, true );
        xhr.send( null );

        //

        var monitor = new THREE.LoadingMonitor();

        monitor.addEventListener( 'load', function ( event ) {

            scope.dispatchEvent( { type: 'load', content: geometry } );

        } );

        monitor.add( xhr );

    },

    parse: function ( data, monitor ) {

        var scope = this;
        var geometry = new THREE.Geometry();

        var scale = ( data.scale !== undefined ) ? 1 / data.scale : 1;

        // materials

        if ( data.materials ) {

            geometry.materials = [];

            for ( var i = 0; i < data.materials.length; ++ i ) {

                var m = data.materials[ i ];

                function isPow2( n ) {

                    var l = Math.log( n ) / Math.LN2;
                    return Math.floor( l ) == l;

                }

                function nearestPow2( n ) {

                    var l = Math.log( n ) / Math.LN2;
                    return Math.pow( 2, Math.round(  l ) );

                }

                function createTexture( where, name, sourceFile, repeat, offset, wrap ) {

                    where[ name ] = new THREE.Texture();
                    where[ name ].sourceFile = sourceFile;

                    if ( repeat ) {

                        where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );

                        if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
                        if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;

                    }

                    if ( offset ) {

                        where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );

                    }

                    if ( wrap ) {

                        var wrapMap = {

                            "repeat": THREE.RepeatWrapping,
                            "mirror": THREE.MirroredRepeatWrapping

                        }

                        if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
                        if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];

                    }

                    // load image

                    var texture = where[ name ];

                    var loader = new THREE.ImageLoader();
                    loader.addEventListener( 'load', function ( event ) {

                        var image = event.content;

                        if ( !isPow2( image.width ) || !isPow2( image.height ) ) {

                            var width = nearestPow2( image.width );
                            var height = nearestPow2( image.height );

                            texture.image = document.createElement( 'canvas' );
                            texture.image.width = width;
                            texture.image.height = height;
                            texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );

                        } else {

                            texture.image = image;

                        }

                        texture.needsUpdate = true;

                    } );
                    loader.crossOrigin = scope.crossOrigin;
                    loader.load( scope.path + '/' + sourceFile );

                    if ( monitor ) monitor.add( loader );

                }

                function rgb2hex( rgb ) {

                    return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;

                }

                // defaults

                var mtype = "MeshLambertMaterial";
                var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };

                // parameters from model file

                if ( m.shading ) {

                    var shading = m.shading.toLowerCase();

                    if ( shading === "phong" ) mtype = "MeshPhongMaterial";
                    else if ( shading === "basic" ) mtype = "MeshBasicMaterial";

                }

                if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {

                    mpars.blending = THREE[ m.blending ];

                }

                if ( m.transparent !== undefined || m.opacity < 1.0 ) {

                    mpars.transparent = m.transparent;

                }

                if ( m.depthTest !== undefined ) {

                    mpars.depthTest = m.depthTest;

                }

                if ( m.depthWrite !== undefined ) {

                    mpars.depthWrite = m.depthWrite;

                }

                if ( m.vertexColors !== undefined ) {

                    if ( m.vertexColors == "face" ) {

                        mpars.vertexColors = THREE.FaceColors;

                    } else if ( m.vertexColors ) {

                        mpars.vertexColors = THREE.VertexColors;

                    }

                }

                // colors

                if ( m.colorDiffuse ) {

                    mpars.color = rgb2hex( m.colorDiffuse );

                } else if ( m.DbgColor ) {

                    mpars.color = m.DbgColor;

                }

                if ( m.colorSpecular ) {

                    mpars.specular = rgb2hex( m.colorSpecular );

                }

                if ( m.colorAmbient ) {

                    mpars.ambient = rgb2hex( m.colorAmbient );

                }

                // modifiers

                if ( m.transparency ) {

                    mpars.opacity = m.transparency;

                }

                if ( m.specularCoef ) {

                    mpars.shininess = m.specularCoef;

                }

                if ( m.visible !== undefined ) {

                    mpars.visible = m.visible;

                }

                if ( m.flipSided !== undefined ) {

                    mpars.side = THREE.BackSide;

                }

                if ( m.doubleSided !== undefined ) {

                    mpars.side = THREE.DoubleSide;

                }

                if ( m.wireframe !== undefined ) {

                    mpars.wireframe = m.wireframe;

                }

                // textures

                if ( m.mapDiffuse ) {

                    createTexture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );

                }

                if ( m.mapLight ) {

                    createTexture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );

                }

                if ( m.mapBump ) {

                    createTexture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );

                }

                if ( m.mapNormal ) {

                    createTexture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );

                }

                if ( m.mapSpecular ) {

                    createTexture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );

                }

                // special case for normal mapped material

                if ( m.mapNormal ) {

                    var shader = THREE.ShaderUtils.lib[ "normal" ];
                    var uniforms = THREE.UniformsUtils.clone( shader.uniforms );

                    uniforms[ "tNormal" ].value = mpars.normalMap;

                    if ( m.mapNormalFactor ) {

                        uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );

                    }

                    if ( mpars.map ) {

                        uniforms[ "tDiffuse" ].value = mpars.map;
                        uniforms[ "enableDiffuse" ].value = true;

                    }

                    if ( mpars.specularMap ) {

                        uniforms[ "tSpecular" ].value = mpars.specularMap;
                        uniforms[ "enableSpecular" ].value = true;

                    }

                    if ( mpars.lightMap ) {

                        uniforms[ "tAO" ].value = mpars.lightMap;
                        uniforms[ "enableAO" ].value = true;

                    }

                    // for the moment don't handle displacement texture

                    uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
                    uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
                    uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );

                    uniforms[ "uShininess" ].value = mpars.shininess;

                    if ( mpars.opacity !== undefined ) {

                        uniforms[ "uOpacity" ].value = mpars.opacity;

                    }

                    var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
                    var material = new THREE.ShaderMaterial( parameters );

                } else {

                    var material = new THREE[ mtype ]( mpars );

                }

                if ( m.DbgName !== undefined ) material.name = m.DbgName;

                geometry.materials[ i ] = material;

            }

        }

        // geometry

        function isBitSet( value, position ) {

            return value & ( 1 << position );

        }

        var faces = data.faces;
        var vertices = data.vertices;
        var normals = data.normals;
        var colors = data.colors;
        var nUvLayers = 0;

        // disregard empty arrays

        if ( data.uvs ) {

            for ( var i = 0; i < data.uvs.length; i ++ ) {

                if ( data.uvs[ i ].length ) nUvLayers ++;

            }

        }

        for ( var i = 0; i < nUvLayers; i ++ ) {

            geometry.faceUvs[ i ] = [];
            geometry.faceVertexUvs[ i ] = [];

        }

        var offset = 0;
        var zLength = vertices.length;

        while ( offset < zLength ) {

            var vertex = new THREE.Vector3();

            vertex.x = vertices[ offset ++ ] * scale;
            vertex.y = vertices[ offset ++ ] * scale;
            vertex.z = vertices[ offset ++ ] * scale;

            geometry.vertices.push( vertex );

        }

        offset = 0;
        zLength = faces.length;

        while ( offset < zLength ) {

            var type = faces[ offset ++ ];

            var isQuad = isBitSet( type, 0 );

            var hasMaterial = isBitSet( type, 1 );
            var hasFaceUv = isBitSet( type, 2 );
            var hasFaceVertexUv = isBitSet( type, 3 );
            var hasFaceNormal = isBitSet( type, 4 );
            var hasFaceVertexNormal = isBitSet( type, 5 );
            var hasFaceColor = isBitSet( type, 6 );
            var hasFaceVertexColor = isBitSet( type, 7 );

            // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);

            if ( isQuad ) {

                var face = new THREE.Face4();

                face.a = faces[ offset ++ ];
                face.b = faces[ offset ++ ];
                face.c = faces[ offset ++ ];
                face.d = faces[ offset ++ ];

                var nVertices = 4;

            } else {

                var face = new THREE.Face3();

                face.a = faces[ offset ++ ];
                face.b = faces[ offset ++ ];
                face.c = faces[ offset ++ ];

                var nVertices = 3;

            }

            if ( hasMaterial ) {

                var materialIndex = faces[ offset ++ ];
                face.materialIndex = materialIndex;

            }

            // to get face <=> uv index correspondence

            var fi = geometry.faces.length;

            if ( hasFaceUv ) {

                for ( var i = 0; i < nUvLayers; i ++ ) {

                    var uvLayer = data.uvs[ i ];

                    var uvIndex = faces[ offset ++ ];

                    var u = uvLayer[ uvIndex * 2 ];
                    var v = uvLayer[ uvIndex * 2 + 1 ];

                    geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );

                }

            }

            if ( hasFaceVertexUv ) {

                for ( var i = 0; i < nUvLayers; i ++ ) {

                    var uvLayer = data.uvs[ i ];

                    var uvs = [];

                    for ( var j = 0; j < nVertices; j ++ ) {

                        var uvIndex = faces[ offset ++ ];

                        var u = uvLayer[ uvIndex * 2 ];
                        var v = uvLayer[ uvIndex * 2 + 1 ];

                        uvs[ j ] = new THREE.UV( u, v );

                    }

                    geometry.faceVertexUvs[ i ][ fi ] = uvs;

                }

            }

            if ( hasFaceNormal ) {

                var normalIndex = faces[ offset ++ ] * 3;

                var normal = new THREE.Vector3();

                normal.x = normals[ normalIndex ++ ];
                normal.y = normals[ normalIndex ++ ];
                normal.z = normals[ normalIndex ];

                face.normal = normal;

            }

            if ( hasFaceVertexNormal ) {

                for ( i = 0; i < nVertices; i ++ ) {

                    var normalIndex = faces[ offset ++ ] * 3;

                    var normal = new THREE.Vector3();

                    normal.x = normals[ normalIndex ++ ];
                    normal.y = normals[ normalIndex ++ ];
                    normal.z = normals[ normalIndex ];

                    face.vertexNormals.push( normal );

                }

            }


            if ( hasFaceColor ) {

                var colorIndex = faces[ offset ++ ];

                face.color = new THREE.Color( colors[ colorIndex ] );

            }


            if ( hasFaceVertexColor ) {

                for ( var i = 0; i < nVertices; i ++ ) {

                    var colorIndex = faces[ offset ++ ];

                    face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );

                }

            }

            geometry.faces.push( face );

        }


        // skin

        if ( data.skinWeights ) {

            for ( var i = 0, l = data.skinWeights.length; i < l; i += 2 ) {

                var x = data.skinWeights[ i ];
                var y = data.skinWeights[ i + 1 ];
                var z = 0;
                var w = 0;

                geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );

            }

        }

        if ( data.skinIndices ) {

            for ( var i = 0, l = data.skinIndices.length; i < l; i += 2 ) {

                var a = data.skinIndices[ i ];
                var b = data.skinIndices[ i + 1 ];
                var c = 0;
                var d = 0;

                geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );

            }

        }

        geometry.bones = data.bones;
        geometry.animation = data.animation;


        // morphing

        if ( data.morphTargets ) {

            for ( var i = 0, l = data.morphTargets.length; i < l; i ++ ) {

                geometry.morphTargets[ i ] = {};
                geometry.morphTargets[ i ].name = data.morphTargets[ i ].name;
                geometry.morphTargets[ i ].vertices = [];

                var dstVertices = geometry.morphTargets[ i ].vertices;
                var srcVertices = data.morphTargets [ i ].vertices;

                for( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {

                    var vertex = new THREE.Vector3();
                    vertex.x = srcVertices[ v ] * scale;
                    vertex.y = srcVertices[ v + 1 ] * scale;
                    vertex.z = srcVertices[ v + 2 ] * scale;

                    dstVertices.push( vertex );

                }

            }

        }

        if ( data.morphColors ) {

            for ( var i = 0, l = data.morphColors.length; i < l; i++ ) {

                geometry.morphColors[ i ] = {};
                geometry.morphColors[ i ].name = data.morphColors[ i ].name;
                geometry.morphColors[ i ].colors = [];

                var dstColors = geometry.morphColors[ i ].colors;
                var srcColors = data.morphColors [ i ].colors;

                for ( var c = 0, cl = srcColors.length; c < cl; c += 3 ) {

                    var color = new THREE.Color( 0xffaa00 );
                    color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );

                    dstColors.push( color );

                }

            }

        }

        geometry.computeCentroids();
        geometry.computeFaceNormals();

        return geometry;

    }

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.SceneLoader = function () {

    this.onLoadStart = function () {};
    this.onLoadProgress = function() {};
    this.onLoadComplete = function () {};

    this.callbackSync = function () {};
    this.callbackProgress = function () {};

    this.geometryHandlerMap = {};

    this.addGeometryHandler( "ascii", THREE.JSONLoader );
    this.addGeometryHandler( "binary", THREE.BinaryLoader );

};

THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;

THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {

    var scope = this;

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {

        if ( xhr.readyState === 4 ) {

            if ( xhr.status === 200 || xhr.status === 0 ) {

                var json = JSON.parse( xhr.responseText );
                scope.parse( json, callbackFinished, url );

            } else {

                console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );

            }

        }

    };

    xhr.open( "GET", url, true );
    xhr.send( null );

};

THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {

    this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };

};

THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {

    var scope = this;

    var urlBase = THREE.Loader.prototype.extractUrlBase( url );

    var dg, dm, dl, dc, df, dt,
        g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
        geometry, material, camera, fog,
        texture, images,
        light,
        counter_models, counter_textures,
        total_models, total_textures,
        result;

    var data = json;

    // async geometry loaders

    for ( var typeID in this.geometryHandlerMap ) {

        var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
        this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();

    }

    counter_models = 0;
    counter_textures = 0;

    result = {

        scene: new THREE.Scene(),
        geometries: {},
        materials: {},
        textures: {},
        objects: {},
        cameras: {},
        lights: {},
        fogs: {},
        empties: {}

    };

    if ( data.transform ) {

        var position = data.transform.position,
            rotation = data.transform.rotation,
            scale = data.transform.scale;

        if ( position )
            result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );

        if ( rotation )
            result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );

        if ( scale )
            result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );

        if ( position || rotation || scale ) {

            result.scene.updateMatrix();
            result.scene.updateMatrixWorld();

        }

    }

    function get_url( source_url, url_type ) {

        if ( url_type == "relativeToHTML" ) {

            return source_url;

        } else {

            return urlBase + "/" + source_url;

        }

    };

    // toplevel loader function, delegates to handle_children

    function handle_objects() {

        handle_children( result.scene, data.objects );

    }

    // handle all the children from the loaded json and attach them to given parent

    function handle_children( parent, children ) {

        for ( var dd in children ) {

            // check by id if child has already been handled,
            // if not, create new object

            if ( result.objects[ dd ] === undefined ) {

                var o = children[ dd ];

                var object = null;

                if ( o.geometry !== undefined ) {

                    geometry = result.geometries[ o.geometry ];

                    // geometry already loaded

                    if ( geometry ) {

                        var hasNormals = false;

                        // not anymore support for multiple materials
                        // shouldn't really be array

                        material = result.materials[ o.materials[ 0 ] ];
                        hasNormals = material instanceof THREE.ShaderMaterial;

                        if ( hasNormals ) {

                            geometry.computeTangents();

                        }

                        p = o.position;
                        r = o.rotation;
                        q = o.quaternion;
                        s = o.scale;
                        m = o.matrix;

                        // turn off quaternions, for the moment

                        q = 0;

                        if ( o.materials.length === 0 ) {

                            material = new THREE.MeshFaceMaterial();

                        }

                        // dirty hack to handle meshes with multiple materials
                        // just use face materials defined in model

                        if ( o.materials.length > 1 ) {

                            material = new THREE.MeshFaceMaterial();

                        }

                        if ( o.morph ) {

                            object = new THREE.MorphAnimMesh( geometry, material );

                            if ( o.duration !== undefined ) {

                                object.duration = o.duration;

                            }

                            if ( o.time !== undefined ) {

                                object.time = o.time;

                            }

                            if ( o.mirroredLoop !== undefined ) {

                                object.mirroredLoop = o.mirroredLoop;

                            }

                            if ( material.morphNormals ) {

                                geometry.computeMorphNormals();

                            }

                        } else {

                            object = new THREE.Mesh( geometry, material );

                        }

                        object.name = dd;

                        if ( m ) {

                            object.matrixAutoUpdate = false;
                            object.matrix.set(
                                m[0], m[1], m[2], m[3],
                                m[4], m[5], m[6], m[7],
                                m[8], m[9], m[10], m[11],
                                m[12], m[13], m[14], m[15]
                            );

                        } else {

                            object.position.set( p[0], p[1], p[2] );

                            if ( q ) {

                                object.quaternion.set( q[0], q[1], q[2], q[3] );
                                object.useQuaternion = true;

                            } else {

                                object.rotation.set( r[0], r[1], r[2] );

                            }

                            object.scale.set( s[0], s[1], s[2] );

                        }

                        object.visible = o.visible;
                        object.castShadow = o.castShadow;
                        object.receiveShadow = o.receiveShadow;

                        parent.add( object );

                        result.objects[ dd ] = object;

                    }

                // pure Object3D

                } else {

                    p = o.position;
                    r = o.rotation;
                    q = o.quaternion;
                    s = o.scale;

                    // turn off quaternions, for the moment

                    q = 0;

                    object = new THREE.Object3D();
                    object.name = dd;
                    object.position.set( p[0], p[1], p[2] );

                    if ( q ) {

                        object.quaternion.set( q[0], q[1], q[2], q[3] );
                        object.useQuaternion = true;

                    } else {

                        object.rotation.set( r[0], r[1], r[2] );

                    }

                    object.scale.set( s[0], s[1], s[2] );
                    object.visible = ( o.visible !== undefined ) ? o.visible : false;

                    parent.add( object );

                    result.objects[ dd ] = object;
                    result.empties[ dd ] = object;

                }

                if ( object ) {

                    if ( o.properties !== undefined )  {

                        for ( var key in o.properties ) {

                            var value = o.properties[ key ];
                            object.properties[ key ] = value;

                        }

                    }

                    if ( o.children !== undefined ) {

                        handle_children( object, o.children );

                    }

                }

            }

        }

    };

    function handle_mesh( geo, id ) {

        result.geometries[ id ] = geo;
        handle_objects();

    };

    function create_callback( id ) {

        return function( geo ) {

            handle_mesh( geo, id );

            counter_models -= 1;

            scope.onLoadComplete();

            async_callback_gate();

        }

    };

    function create_callback_embed( id ) {

        return function( geo ) {

            result.geometries[ id ] = geo;

        }

    };

    function async_callback_gate() {

        var progress = {

            totalModels : total_models,
            totalTextures : total_textures,
            loadedModels : total_models - counter_models,
            loadedTextures : total_textures - counter_textures

        };

        scope.callbackProgress( progress, result );

        scope.onLoadProgress();

        if ( counter_models === 0 && counter_textures === 0 ) {

            callbackFinished( result );

        }

    };

    var callbackTexture = function ( count ) {

        counter_textures -= count;
        async_callback_gate();

        scope.onLoadComplete();

    };

    // must use this instead of just directly calling callbackTexture
    // because of closure in the calling context loop

    var generateTextureCallback = function ( count ) {

        return function() {

            callbackTexture( count );

        };

    };

    // first go synchronous elements

    // cameras

    for( dc in data.cameras ) {

        c = data.cameras[ dc ];

        if ( c.type === "perspective" ) {

            camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );

        } else if ( c.type === "ortho" ) {

            camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );

        }

        p = c.position;
        t = c.target;
        u = c.up;

        camera.position.set( p[0], p[1], p[2] );
        camera.target = new THREE.Vector3( t[0], t[1], t[2] );
        if ( u ) camera.up.set( u[0], u[1], u[2] );

        result.cameras[ dc ] = camera;

    }

    // lights

    var hex, intensity;

    for ( dl in data.lights ) {

        l = data.lights[ dl ];

        hex = ( l.color !== undefined ) ? l.color : 0xffffff;
        intensity = ( l.intensity !== undefined ) ? l.intensity : 1;

        if ( l.type === "directional" ) {

            p = l.direction;

            light = new THREE.DirectionalLight( hex, intensity );
            light.position.set( p[0], p[1], p[2] );
            light.position.normalize();

        } else if ( l.type === "point" ) {

            p = l.position;
            d = l.distance;

            light = new THREE.PointLight( hex, intensity, d );
            light.position.set( p[0], p[1], p[2] );

        } else if ( l.type === "ambient" ) {

            light = new THREE.AmbientLight( hex );

        }

        result.scene.add( light );

        result.lights[ dl ] = light;

    }

    // fogs

    for( df in data.fogs ) {

        f = data.fogs[ df ];

        if ( f.type === "linear" ) {

            fog = new THREE.Fog( 0x000000, f.near, f.far );

        } else if ( f.type === "exp2" ) {

            fog = new THREE.FogExp2( 0x000000, f.density );

        }

        c = f.color;
        fog.color.setRGB( c[0], c[1], c[2] );

        result.fogs[ df ] = fog;

    }

    // defaults

    if ( result.cameras && data.defaults && data.defaults.camera ) {

        result.currentCamera = result.cameras[ data.defaults.camera ];

    }

    if ( result.fogs && data.defaults && data.defaults.fog ) {

        result.scene.fog = result.fogs[ data.defaults.fog ];

    }

    c = data.defaults.bgcolor;
    result.bgColor = new THREE.Color();
    result.bgColor.setRGB( c[0], c[1], c[2] );

    result.bgColorAlpha = data.defaults.bgalpha;

    // now come potentially asynchronous elements

    // geometries

    // count how many models will be loaded asynchronously

    for( dg in data.geometries ) {

        g = data.geometries[ dg ];

        if ( g.type in this.geometryHandlerMap ) {

            counter_models += 1;

            scope.onLoadStart();

        }

    }

    total_models = counter_models;

    for ( dg in data.geometries ) {

        g = data.geometries[ dg ];

        if ( g.type === "cube" ) {

            geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
            result.geometries[ dg ] = geometry;

        } else if ( g.type === "plane" ) {

            geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
            result.geometries[ dg ] = geometry;

        } else if ( g.type === "sphere" ) {

            geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
            result.geometries[ dg ] = geometry;

        } else if ( g.type === "cylinder" ) {

            geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
            result.geometries[ dg ] = geometry;

        } else if ( g.type === "torus" ) {

            geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
            result.geometries[ dg ] = geometry;

        } else if ( g.type === "icosahedron" ) {

            geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
            result.geometries[ dg ] = geometry;

        } else if ( g.type in this.geometryHandlerMap ) {

            var loaderParameters = {};
            for ( var parType in g ) {

                if ( parType !== "type" && parType !== "url" ) {

                    loaderParameters[ parType ] = g[ parType ];

                }

            }

            var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
            loader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ), loaderParameters );

        } else if ( g.type === "embedded" ) {

            var modelJson = data.embeds[ g.id ],
                texture_path = "";

            // pass metadata along to jsonLoader so it knows the format version

            modelJson.metadata = data.metadata;

            if ( modelJson ) {

                var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
                jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );

            }

        }

    }

    // textures

    // count how many textures will be loaded asynchronously

    for( dt in data.textures ) {

        tt = data.textures[ dt ];

        if( tt.url instanceof Array ) {

            counter_textures += tt.url.length;

            for( var n = 0; n < tt.url.length; n ++ ) {

                scope.onLoadStart();

            }

        } else {

            counter_textures += 1;

            scope.onLoadStart();

        }

    }

    total_textures = counter_textures;

    for ( dt in data.textures ) {

        tt = data.textures[ dt ];

        if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined  ) {

            tt.mapping = new THREE[ tt.mapping ]();

        }

        if ( tt.url instanceof Array ) {

            var count = tt.url.length;
            var url_array = [];

            for( var i = 0; i < count; i ++ ) {

                url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );

            }

            var isCompressed = url_array[ 0 ].endsWith( ".dds" );

            if ( isCompressed ) {

                texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );

            } else {

                texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );

            }

        } else {

            var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
            var fullUrl = get_url( tt.url, data.urlBaseType );
            var textureCallback = generateTextureCallback( 1 );

            if ( isCompressed ) {

                texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );

            } else {

                texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );

            }

            if ( THREE[ tt.minFilter ] !== undefined )
                texture.minFilter = THREE[ tt.minFilter ];

            if ( THREE[ tt.magFilter ] !== undefined )
                texture.magFilter = THREE[ tt.magFilter ];

            if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;

            if ( tt.repeat ) {

                texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );

                if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
                if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;

            }

            if ( tt.offset ) {

                texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );

            }

            // handle wrap after repeat so that default repeat can be overriden

            if ( tt.wrap ) {

                var wrapMap = {
                "repeat"     : THREE.RepeatWrapping,
                "mirror"    : THREE.MirroredRepeatWrapping
                }

                if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
                if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];

            }

        }

        result.textures[ dt ] = texture;

    }

    // materials

    for ( dm in data.materials ) {

        m = data.materials[ dm ];

        for ( pp in m.parameters ) {

            if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {

                m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];

            } else if ( pp === "shading" ) {

                m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;

            } else if ( pp === "side" ) {

                if (  m.parameters[ pp ] == "double" ) {

                    m.parameters[ pp ] = THREE.DoubleSide;

                } else if ( m.parameters[ pp ] == "back" ) {

                    m.parameters[ pp ] = THREE.BackSide;

                } else {

                    m.parameters[ pp ] = THREE.FrontSide;

                }

            } else if ( pp === "blending" ) {

                m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;

            } else if ( pp === "combine" ) {

                m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;

            } else if ( pp === "vertexColors" ) {

                if ( m.parameters[ pp ] == "face" ) {

                    m.parameters[ pp ] = THREE.FaceColors;

                // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false

                } else if ( m.parameters[ pp ] )   {

                    m.parameters[ pp ] = THREE.VertexColors;

                }

            } else if ( pp === "wrapRGB" ) {

                var v3 = m.parameters[ pp ];
                m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );

            }

        }

        if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {

            m.parameters.transparent = true;

        }

        if ( m.parameters.normalMap ) {

            var shader = THREE.ShaderUtils.lib[ "normal" ];
            var uniforms = THREE.UniformsUtils.clone( shader.uniforms );

            var diffuse = m.parameters.color;
            var specular = m.parameters.specular;
            var ambient = m.parameters.ambient;
            var shininess = m.parameters.shininess;

            uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];

            if ( m.parameters.normalScale ) {

                uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );

            }

            if ( m.parameters.map ) {

                uniforms[ "tDiffuse" ].value = m.parameters.map;
                uniforms[ "enableDiffuse" ].value = true;

            }

            if ( m.parameters.envMap ) {

                uniforms[ "tCube" ].value = m.parameters.envMap;
                uniforms[ "enableReflection" ].value = true;
                uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;

            }

            if ( m.parameters.lightMap ) {

                uniforms[ "tAO" ].value = m.parameters.lightMap;
                uniforms[ "enableAO" ].value = true;

            }

            if ( m.parameters.specularMap ) {

                uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
                uniforms[ "enableSpecular" ].value = true;

            }

            if ( m.parameters.displacementMap ) {

                uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
                uniforms[ "enableDisplacement" ].value = true;

                uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
                uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;

            }

            uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
            uniforms[ "uSpecularColor" ].value.setHex( specular );
            uniforms[ "uAmbientColor" ].value.setHex( ambient );

            uniforms[ "uShininess" ].value = shininess;

            if ( m.parameters.opacity ) {

                uniforms[ "uOpacity" ].value = m.parameters.opacity;

            }

            var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };

            material = new THREE.ShaderMaterial( parameters );

        } else {

            material = new THREE[ m.type ]( m.parameters );

        }

        result.materials[ dm ] = material;

    }

    // objects ( synchronous init of procedural primitives )

    handle_objects();

    // synchronous callback

    scope.callbackSync( result );

    // just in case there are no async elements

    async_callback_gate();

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.TextureLoader = function () {

    THREE.EventTarget.call( this );

    this.crossOrigin = null;

};

THREE.TextureLoader.prototype = {

    constructor: THREE.TextureLoader,

    load: function ( url ) {

        var scope = this;

        var image = new Image();

        image.addEventListener( 'load', function () {

            var texture = new THREE.Texture( image );
            texture.needsUpdate = true;

            scope.dispatchEvent( { type: 'load', content: texture } );

        }, false );

        image.addEventListener( 'error', function () {

            scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );

        }, false );

        if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;

        image.src = url;

    }

}
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Material = function () {

    this.id = THREE.MaterialCount ++;

    this.name = '';

    this.side = THREE.FrontSide;

    this.opacity = 1;
    this.transparent = false;

    this.blending = THREE.NormalBlending;

    this.blendSrc = THREE.SrcAlphaFactor;
    this.blendDst = THREE.OneMinusSrcAlphaFactor;
    this.blendEquation = THREE.AddEquation;

    this.depthTest = true;
    this.depthWrite = true;

    this.polygonOffset = false;
    this.polygonOffsetFactor = 0;
    this.polygonOffsetUnits = 0;

    this.alphaTest = 0;

    this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer

    this.visible = true;

    this.needsUpdate = true;

};

THREE.Material.prototype.setValues = function ( values ) {

    if ( values === undefined ) return;

    for ( var key in values ) {

        var newValue = values[ key ];

        if ( newValue === undefined ) {

            console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
            continue;

        }

        if ( key in this ) {

            var currentValue = this[ key ];

            if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {

                currentValue.copy( newValue );

            } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {

                currentValue.setHex( newValue );

            } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {

                currentValue.copy( newValue );

            } else {

                this[ key ] = newValue;

            }

        }

    }

};

THREE.Material.prototype.clone = function ( material ) {

    if ( material === undefined ) material = new THREE.Material();

    material.name = this.name;

    material.side = this.side;

    material.opacity = this.opacity;
    material.transparent = this.transparent;

    material.blending = this.blending;

    material.blendSrc = this.blendSrc;
    material.blendDst = this.blendDst;
    material.blendEquation = this.blendEquation;

    material.depthTest = this.depthTest;
    material.depthWrite = this.depthWrite;

    material.polygonOffset = this.polygonOffset;
    material.polygonOffsetFactor = this.polygonOffsetFactor;
    material.polygonOffsetUnits = this.polygonOffsetUnits;

    material.alphaTest = this.alphaTest;

    material.overdraw = this.overdraw;

    material.visible = this.visible;

    return material;

};

THREE.MaterialCount = 0;
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  opacity: <float>,
 *
 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,
 *
 *  linewidth: <float>,
 *  linecap: "round",
 *  linejoin: "round",
 *
 *  vertexColors: <bool>
 *
 *  fog: <bool>
 * }
 */

THREE.LineBasicMaterial = function ( parameters ) {

    THREE.Material.call( this );

    this.color = new THREE.Color( 0xffffff );

    this.linewidth = 1;
    this.linecap = 'round';
    this.linejoin = 'round';

    this.vertexColors = false;

    this.fog = true;

    this.setValues( parameters );

};

THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.LineBasicMaterial.prototype.clone = function () {

    var material = new THREE.LineBasicMaterial();

    THREE.Material.prototype.clone.call( this, material );

    material.color.copy( this.color );

    material.linewidth = this.linewidth;
    material.linecap = this.linecap;
    material.linejoin = this.linejoin;

    material.vertexColors = this.vertexColors;

    material.fog = this.fog;

    return material;

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  opacity: <float>,
 *  map: new THREE.Texture( <Image> ),
 *
 *  lightMap: new THREE.Texture( <Image> ),
 *
 *  specularMap: new THREE.Texture( <Image> ),
 *
 *  envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
 *  combine: THREE.Multiply,
 *  reflectivity: <float>,
 *  refractionRatio: <float>,
 *
 *  shading: THREE.SmoothShading,
 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *
 *  fog: <bool>
 * }
 */

THREE.MeshBasicMaterial = function ( parameters ) {

    THREE.Material.call( this );

    this.color = new THREE.Color( 0xffffff ); // emissive

    this.map = null;

    this.lightMap = null;

    this.specularMap = null;

    this.envMap = null;
    this.combine = THREE.MultiplyOperation;
    this.reflectivity = 1;
    this.refractionRatio = 0.98;

    this.fog = true;

    this.shading = THREE.SmoothShading;

    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = 'round';
    this.wireframeLinejoin = 'round';

    this.vertexColors = THREE.NoColors;

    this.skinning = false;
    this.morphTargets = false;

    this.setValues( parameters );

};

THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.MeshBasicMaterial.prototype.clone = function () {

    var material = new THREE.MeshBasicMaterial();

    THREE.Material.prototype.clone.call( this, material );

    material.color.copy( this.color );

    material.map = this.map;

    material.lightMap = this.lightMap;

    material.specularMap = this.specularMap;

    material.envMap = this.envMap;
    material.combine = this.combine;
    material.reflectivity = this.reflectivity;
    material.refractionRatio = this.refractionRatio;

    material.fog = this.fog;

    material.shading = this.shading;

    material.wireframe = this.wireframe;
    material.wireframeLinewidth = this.wireframeLinewidth;
    material.wireframeLinecap = this.wireframeLinecap;
    material.wireframeLinejoin = this.wireframeLinejoin;

    material.vertexColors = this.vertexColors;

    material.skinning = this.skinning;
    material.morphTargets = this.morphTargets;

    return material;

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  ambient: <hex>,
 *  emissive: <hex>,
 *  opacity: <float>,
 *
 *  map: new THREE.Texture( <Image> ),
 *
 *  lightMap: new THREE.Texture( <Image> ),
 *
 *  specularMap: new THREE.Texture( <Image> ),
 *
 *  envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
 *  combine: THREE.Multiply,
 *  reflectivity: <float>,
 *  refractionRatio: <float>,
 *
 *  shading: THREE.SmoothShading,
 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>,
 *
 *    fog: <bool>
 * }
 */

THREE.MeshLambertMaterial = function ( parameters ) {

    THREE.Material.call( this );

    this.color = new THREE.Color( 0xffffff ); // diffuse
    this.ambient = new THREE.Color( 0xffffff );
    this.emissive = new THREE.Color( 0x000000 );

    this.wrapAround = false;
    this.wrapRGB = new THREE.Vector3( 1, 1, 1 );

    this.map = null;

    this.lightMap = null;

    this.specularMap = null;

    this.envMap = null;
    this.combine = THREE.MultiplyOperation;
    this.reflectivity = 1;
    this.refractionRatio = 0.98;

    this.fog = true;

    this.shading = THREE.SmoothShading;

    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = 'round';
    this.wireframeLinejoin = 'round';

    this.vertexColors = THREE.NoColors;

    this.skinning = false;
    this.morphTargets = false;
    this.morphNormals = false;

    this.setValues( parameters );

};

THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.MeshLambertMaterial.prototype.clone = function () {

    var material = new THREE.MeshLambertMaterial();

    THREE.Material.prototype.clone.call( this, material );

    material.color.copy( this.color );
    material.ambient.copy( this.ambient );
    material.emissive.copy( this.emissive );

    material.wrapAround = this.wrapAround;
    material.wrapRGB.copy( this.wrapRGB );

    material.map = this.map;

    material.lightMap = this.lightMap;

    material.specularMap = this.specularMap;

    material.envMap = this.envMap;
    material.combine = this.combine;
    material.reflectivity = this.reflectivity;
    material.refractionRatio = this.refractionRatio;

    material.fog = this.fog;

    material.shading = this.shading;

    material.wireframe = this.wireframe;
    material.wireframeLinewidth = this.wireframeLinewidth;
    material.wireframeLinecap = this.wireframeLinecap;
    material.wireframeLinejoin = this.wireframeLinejoin;

    material.vertexColors = this.vertexColors;

    material.skinning = this.skinning;
    material.morphTargets = this.morphTargets;
    material.morphNormals = this.morphNormals;

    return material;

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  ambient: <hex>,
 *  emissive: <hex>,
 *  specular: <hex>,
 *  shininess: <float>,
 *  opacity: <float>,
 *
 *  map: new THREE.Texture( <Image> ),
 *
 *  lightMap: new THREE.Texture( <Image> ),
 *
 *  bumpMap: new THREE.Texture( <Image> ),
 *  bumpScale: <float>,
 *
 *  normalMap: new THREE.Texture( <Image> ),
 *  normalScale: <Vector2>,
 *
 *  specularMap: new THREE.Texture( <Image> ),
 *
 *  envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
 *  combine: THREE.Multiply,
 *  reflectivity: <float>,
 *  refractionRatio: <float>,
 *
 *  shading: THREE.SmoothShading,
 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>,
 *
 *    fog: <bool>
 * }
 */

THREE.MeshPhongMaterial = function ( parameters ) {

    THREE.Material.call( this );

    this.color = new THREE.Color( 0xffffff ); // diffuse
    this.ambient = new THREE.Color( 0xffffff );
    this.emissive = new THREE.Color( 0x000000 );
    this.specular = new THREE.Color( 0x111111 );
    this.shininess = 30;

    this.metal = false;
    this.perPixel = false;

    this.wrapAround = false;
    this.wrapRGB = new THREE.Vector3( 1, 1, 1 );

    this.map = null;

    this.lightMap = null;

    this.bumpMap = null;
    this.bumpScale = 1;

    this.normalMap = null;
    this.normalScale = new THREE.Vector2( 1, 1 );

    this.specularMap = null;

    this.envMap = null;
    this.combine = THREE.MultiplyOperation;
    this.reflectivity = 1;
    this.refractionRatio = 0.98;

    this.fog = true;

    this.shading = THREE.SmoothShading;

    this.wireframe = false;
    this.wireframeLinewidth = 1;
    this.wireframeLinecap = 'round';
    this.wireframeLinejoin = 'round';

    this.vertexColors = THREE.NoColors;

    this.skinning = false;
    this.morphTargets = false;
    this.morphNormals = false;

    this.setValues( parameters );

};

THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.MeshPhongMaterial.prototype.clone = function () {

    var material = new THREE.MeshPhongMaterial();

    THREE.Material.prototype.clone.call( this, material );

    material.color.copy( this.color );
    material.ambient.copy( this.ambient );
    material.emissive.copy( this.emissive );
    material.specular.copy( this.specular );
    material.shininess = this.shininess;

    material.metal = this.metal;
    material.perPixel = this.perPixel;

    material.wrapAround = this.wrapAround;
    material.wrapRGB.copy( this.wrapRGB );

    material.map = this.map;

    material.lightMap = this.lightMap;

    material.bumpMap = this.bumpMap;
    material.bumpScale = this.bumpScale;

    material.normalMap = this.normalMap;
    material.normalScale.copy( this.normalScale );

    material.specularMap = this.specularMap;

    material.envMap = this.envMap;
    material.combine = this.combine;
    material.reflectivity = this.reflectivity;
    material.refractionRatio = this.refractionRatio;

    material.fog = this.fog;

    material.shading = this.shading;

    material.wireframe = this.wireframe;
    material.wireframeLinewidth = this.wireframeLinewidth;
    material.wireframeLinecap = this.wireframeLinecap;
    material.wireframeLinejoin = this.wireframeLinejoin;

    material.vertexColors = this.vertexColors;

    material.skinning = this.skinning;
    material.morphTargets = this.morphTargets;
    material.morphNormals = this.morphNormals;

    return material;

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  opacity: <float>,

 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,

 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>
 * }
 */

THREE.MeshDepthMaterial = function ( parameters ) {

    THREE.Material.call( this );

    this.wireframe = false;
    this.wireframeLinewidth = 1;

    this.setValues( parameters );

};

THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.MeshDepthMaterial.prototype.clone = function () {

    var material = new THREE.LineBasicMaterial();

    THREE.Material.prototype.clone.call( this, material );

    material.wireframe = this.wireframe;
    material.wireframeLinewidth = this.wireframeLinewidth;

    return material;

};
/**
 * @author mrdoob / http://mrdoob.com/
 *
 * parameters = {
 *  opacity: <float>,

 *  shading: THREE.FlatShading,
 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,

 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>
 * }
 */

THREE.MeshNormalMaterial = function ( parameters ) {

    THREE.Material.call( this, parameters );

    this.shading = THREE.FlatShading;

    this.wireframe = false;
    this.wireframeLinewidth = 1;

    this.setValues( parameters );

};

THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.MeshNormalMaterial.prototype.clone = function () {

    var material = new THREE.MeshNormalMaterial();

    THREE.Material.prototype.clone.call( this, material );

    material.shading = this.shading;

    material.wireframe = this.wireframe;
    material.wireframeLinewidth = this.wireframeLinewidth;

    return material;

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.MeshFaceMaterial = function () {};

THREE.MeshFaceMaterial.prototype.clone = function () {

    return new THREE.MeshFaceMaterial();

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  color: <hex>,
 *  opacity: <float>,
 *  map: new THREE.Texture( <Image> ),
 *
 *  size: <float>,
 *
 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,
 *
 *  vertexColors: <bool>,
 *
 *  fog: <bool>
 * }
 */

THREE.ParticleBasicMaterial = function ( parameters ) {

    THREE.Material.call( this );

    this.color = new THREE.Color( 0xffffff );

    this.map = null;

    this.size = 1;
    this.sizeAttenuation = true;

    this.vertexColors = false;

    this.fog = true;

    this.setValues( parameters );

};

THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.ParticleBasicMaterial.prototype.clone = function () {

    var material = new THREE.ParticleBasicMaterial();

    THREE.Material.prototype.clone.call( this, material );

    material.color.copy( this.color );

    material.map = this.map;

    material.size = this.size;
    material.sizeAttenuation = this.sizeAttenuation;

    material.vertexColors = this.vertexColors;

    material.fog = this.fog;

    return material;

};
/**
 * @author mrdoob / http://mrdoob.com/
 *
 * parameters = {
 *  color: <hex>,
 *  program: <function>,
 *  opacity: <float>,
 *  blending: THREE.NormalBlending
 * }
 */

THREE.ParticleCanvasMaterial = function ( parameters ) {

    THREE.Material.call( this );

    this.color = new THREE.Color( 0xffffff );
    this.program = function ( context, color ) {};

    this.setValues( parameters );

};

THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.ParticleCanvasMaterial.prototype.clone = function () {

    var material = new THREE.ParticleCanvasMaterial();

    THREE.Material.prototype.clone.call( this, material );

    material.color.copy( this.color );
    material.program = this.program;

    return material;

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.ParticleDOMMaterial = function ( element ) {

    this.element = element;

};

THREE.ParticleDOMMaterial.prototype.clone = function(){

    return new THREE.ParticleDOMMaterial( this.element );

};
/**
 * @author alteredq / http://alteredqualia.com/
 *
 * parameters = {
 *  fragmentShader: <string>,
 *  vertexShader: <string>,
 *
 *  uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
 *
 *  shading: THREE.SmoothShading,
 *  blending: THREE.NormalBlending,
 *  depthTest: <bool>,
 *
 *  wireframe: <boolean>,
 *  wireframeLinewidth: <float>,
 *
 *  lights: <bool>,
 *
 *  vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
 *
 *  skinning: <bool>,
 *  morphTargets: <bool>,
 *  morphNormals: <bool>,
 *
 *    fog: <bool>
 * }
 */

THREE.ShaderMaterial = function ( parameters ) {

    THREE.Material.call( this );

    this.fragmentShader = "void main() {}";
    this.vertexShader = "void main() {}";
    this.uniforms = {};
    this.attributes = null;

    this.shading = THREE.SmoothShading;

    this.wireframe = false;
    this.wireframeLinewidth = 1;

    this.fog = false; // set to use scene fog

    this.lights = false; // set to use scene lights

    this.vertexColors = THREE.NoColors; // set to use "color" attribute stream

    this.skinning = false; // set to use skinning attribute streams

    this.morphTargets = false; // set to use morph targets
    this.morphNormals = false; // set to use morph normals

    this.setValues( parameters );

};

THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );

THREE.ShaderMaterial.prototype.clone = function () {

    var material = new THREE.ShaderMaterial();

    THREE.Material.prototype.clone.call( this, material );

    material.fragmentShader = this.fragmentShader;
    material.vertexShader = this.vertexShader;
    material.uniforms = this.uniforms;
    material.attributes = this.attributes;

    material.shading = this.shading;

    material.wireframe = this.wireframe;
    material.wireframeLinewidth = this.wireframeLinewidth;

    material.fog = this.fog;

    material.lights = this.lights;

    material.vertexColors = this.vertexColors;

    material.skinning = this.skinning;

    material.morphTargets = this.morphTargets;
    material.morphNormals = this.morphNormals;

    return material;

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author szimek / https://github.com/szimek/
 */

THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {

    this.id = THREE.TextureCount ++;

    this.image = image;

    this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();

    this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
    this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;

    this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
    this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;

    this.anisotropy = anisotropy !== undefined ? anisotropy : 1;

    this.format = format !== undefined ? format : THREE.RGBAFormat;
    this.type = type !== undefined ? type : THREE.UnsignedByteType;

    this.offset = new THREE.Vector2( 0, 0 );
    this.repeat = new THREE.Vector2( 1, 1 );

    this.generateMipmaps = true;
    this.premultiplyAlpha = false;
    this.flipY = true;

    this.needsUpdate = false;
    this.onUpdate = null;

};

THREE.Texture.prototype = {

    constructor: THREE.Texture,

    clone: function () {

        var texture = new THREE.Texture();

        texture.image = this.image;

        texture.mapping = this.mapping;

        texture.wrapS = this.wrapS;
        texture.wrapT = this.wrapT;

        texture.magFilter = this.magFilter;
        texture.minFilter = this.minFilter;

        texture.anisotropy = this.anisotropy;

        texture.format = this.format;
        texture.type = this.type;

        texture.offset.copy( this.offset );
        texture.repeat.copy( this.repeat );

        texture.generateMipmaps = this.generateMipmaps;
        texture.premultiplyAlpha = this.premultiplyAlpha;
        texture.flipY = this.flipY;

        return texture;

    }

};

THREE.TextureCount = 0;
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {

    THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );

    this.image = { width: width, height: height };
    this.mipmaps = mipmaps;

};

THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );

THREE.CompressedTexture.prototype.clone = function () {

    var texture = new THREE.CompressedTexture();

    texture.image = this.image;
    texture.mipmaps = this.mipmaps;

    texture.format = this.format;
    texture.type = this.type;

    texture.mapping = this.mapping;

    texture.wrapS = this.wrapS;
    texture.wrapT = this.wrapT;

    texture.magFilter = this.magFilter;
    texture.minFilter = this.minFilter;

    texture.anisotropy = this.anisotropy;

    texture.offset.copy( this.offset );
    texture.repeat.copy( this.repeat );

    return texture;

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {

    THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );

    this.image = { data: data, width: width, height: height };

};

THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );

THREE.DataTexture.prototype.clone = function () {

    var clonedTexture = new THREE.DataTexture( this.image.data,  this.image.width, this.image.height, this.format, this.type, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter );

    clonedTexture.offset.copy( this.offset );
    clonedTexture.repeat.copy( this.repeat );

    return clonedTexture;

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Particle = function ( material ) {

    THREE.Object3D.call( this );

    this.material = material;

};

THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.ParticleSystem = function ( geometry, material ) {

    THREE.Object3D.call( this );

    this.geometry = geometry;
    this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );

    this.sortParticles = false;

    if ( this.geometry ) {

        // calc bound radius

        if( !this.geometry.boundingSphere ) {

            this.geometry.computeBoundingSphere();

        }

        this.boundRadius = geometry.boundingSphere.radius;

    }

    this.frustumCulled = false;

};

THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Line = function ( geometry, material, type ) {

    THREE.Object3D.call( this );

    this.geometry = geometry;
    this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
    this.type = ( type !== undefined ) ? type : THREE.LineStrip;

    if ( this.geometry ) {

        if ( ! this.geometry.boundingSphere ) {

            this.geometry.computeBoundingSphere();

        }

    }

};

THREE.LineStrip = 0;
THREE.LinePieces = 1;

THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author mikael emtinger / http://gomo.se/
 */

THREE.Mesh = function ( geometry, material ) {

    THREE.Object3D.call( this );

    this.geometry = geometry;
    this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );

    if ( this.geometry ) {

        // calc bound radius

        if ( ! this.geometry.boundingSphere ) {

            this.geometry.computeBoundingSphere();

        }

        this.boundRadius = geometry.boundingSphere.radius;


        // setup morph targets

        if( this.geometry.morphTargets.length ) {

            this.morphTargetBase = -1;
            this.morphTargetForcedOrder = [];
            this.morphTargetInfluences = [];
            this.morphTargetDictionary = {};

            for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {

                this.morphTargetInfluences.push( 0 );
                this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;

            }

        }

    }

}

THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );


/*
 * Get Morph Target Index by Name
 */

THREE.Mesh.prototype.getMorphTargetIndexByName = function( name ) {

    if ( this.morphTargetDictionary[ name ] !== undefined ) {

        return this.morphTargetDictionary[ name ];
    }

    console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
    return 0;

}
/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Bone = function( belongsToSkin ) {

    THREE.Object3D.call( this );

    this.skin = belongsToSkin;
    this.skinMatrix = new THREE.Matrix4();

};

THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );

THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {

    // update local

    if ( this.matrixAutoUpdate ) {

        forceUpdate |= this.updateMatrix();

    }

    // update skin matrix

    if ( forceUpdate || this.matrixWorldNeedsUpdate ) {

        if( parentSkinMatrix ) {

            this.skinMatrix.multiply( parentSkinMatrix, this.matrix );

        } else {

            this.skinMatrix.copy( this.matrix );

        }

        this.matrixWorldNeedsUpdate = false;
        forceUpdate = true;

    }

    // update children

    var child, i, l = this.children.length;

    for ( i = 0; i < l; i ++ ) {

        this.children[ i ].update( this.skinMatrix, forceUpdate );

    }

};

/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {

    THREE.Mesh.call( this, geometry, material );

    //

    this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;

    // init bones

    this.identityMatrix = new THREE.Matrix4();

    this.bones = [];
    this.boneMatrices = [];

    var b, bone, gbone, p, q, s;

    if ( this.geometry.bones !== undefined ) {

        for ( b = 0; b < this.geometry.bones.length; b ++ ) {

            gbone = this.geometry.bones[ b ];

            p = gbone.pos;
            q = gbone.rotq;
            s = gbone.scl;

            bone = this.addBone();

            bone.name = gbone.name;
            bone.position.set( p[0], p[1], p[2] );
            bone.quaternion.set( q[0], q[1], q[2], q[3] );
            bone.useQuaternion = true;

            if ( s !== undefined ) {

                bone.scale.set( s[0], s[1], s[2] );

            } else {

                bone.scale.set( 1, 1, 1 );

            }

        }

        for ( b = 0; b < this.bones.length; b ++ ) {

            gbone = this.geometry.bones[ b ];
            bone = this.bones[ b ];

            if ( gbone.parent === -1 ) {

                this.add( bone );

            } else {

                this.bones[ gbone.parent ].add( bone );

            }

        }

        //

        var nBones = this.bones.length;

        if ( this.useVertexTexture ) {

            // layout (1 matrix = 4 pixels)
            //    RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
            //  with  8x8  pixel texture max   16 bones  (8 * 8  / 4)
            //       16x16 pixel texture max   64 bones (16 * 16 / 4)
            //       32x32 pixel texture max  256 bones (32 * 32 / 4)
            //       64x64 pixel texture max 1024 bones (64 * 64 / 4)

            var size;

            if ( nBones > 256 )
                size = 64;
            else if ( nBones > 64 )
                size = 32;
            else if ( nBones > 16 )
                size = 16;
            else
                size = 8;

            this.boneTextureWidth = size;
            this.boneTextureHeight = size;

            this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
            this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
            this.boneTexture.minFilter = THREE.NearestFilter;
            this.boneTexture.magFilter = THREE.NearestFilter;
            this.boneTexture.generateMipmaps = false;
            this.boneTexture.flipY = false;

        } else {

            this.boneMatrices = new Float32Array( 16 * nBones );

        }

        this.pose();

    }

};

THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );

THREE.SkinnedMesh.prototype.addBone = function( bone ) {

    if ( bone === undefined ) {

        bone = new THREE.Bone( this );

    }

    this.bones.push( bone );

    return bone;

};

THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {

    this.matrixAutoUpdate && this.updateMatrix();

    // update matrixWorld

    if ( this.matrixWorldNeedsUpdate || force ) {

        if ( this.parent ) {

            this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );

        } else {

            this.matrixWorld.copy( this.matrix );

        }

        this.matrixWorldNeedsUpdate = false;

        force = true;

    }

    // update children

    for ( var i = 0, l = this.children.length; i < l; i ++ ) {

        var child = this.children[ i ];

        if ( child instanceof THREE.Bone ) {

            child.update( this.identityMatrix, false );

        } else {

            child.updateMatrixWorld( true );

        }

    }

    // make a snapshot of the bones' rest position

    if ( this.boneInverses == undefined ) {

        this.boneInverses = [];

        for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {

            var inverse = new THREE.Matrix4();

            inverse.getInverse( this.bones[ b ].skinMatrix );

            this.boneInverses.push( inverse );

        }

    }

    // flatten bone matrices to array

    for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {

        // compute the offset between the current and the original transform;

        //TODO: we could get rid of this multiplication step if the skinMatrix
        // was already representing the offset; however, this requires some
        // major changes to the animation system

        THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );

        THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );

    }

    if ( this.useVertexTexture ) {

        this.boneTexture.needsUpdate = true;

    }

};

/*
 * Pose
 */

THREE.SkinnedMesh.prototype.pose = function() {

    this.updateMatrixWorld( true );

    for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {

        // normalize weights

        var sw = this.geometry.skinWeights[ i ];

        var scale = 1.0 / sw.lengthManhattan();

        if ( scale !== Infinity ) {

            sw.multiplyScalar( scale );

        } else {

            sw.set( 1 ); // this will be normalized by the shader anyway

        }

    }

};

THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();

/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.MorphAnimMesh = function ( geometry, material ) {

    THREE.Mesh.call( this, geometry, material );

    // API

    this.duration = 1000; // milliseconds
    this.mirroredLoop = false;
    this.time = 0;

    // internals

    this.lastKeyframe = 0;
    this.currentKeyframe = 0;

    this.direction = 1;
    this.directionBackwards = false;

    this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );

};

THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );

THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {

    this.startKeyframe = start;
    this.endKeyframe = end;

    this.length = this.endKeyframe - this.startKeyframe + 1;

};

THREE.MorphAnimMesh.prototype.setDirectionForward = function () {

    this.direction = 1;
    this.directionBackwards = false;

};

THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {

    this.direction = -1;
    this.directionBackwards = true;

};

THREE.MorphAnimMesh.prototype.parseAnimations = function () {

    var geometry = this.geometry;

    if ( ! geometry.animations ) geometry.animations = {};

    var firstAnimation, animations = geometry.animations;

    var pattern = /([a-z]+)(\d+)/;

    for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {

        var morph = geometry.morphTargets[ i ];
        var parts = morph.name.match( pattern );

        if ( parts && parts.length > 1 ) {

            var label = parts[ 1 ];
            var num = parts[ 2 ];

            if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };

            var animation = animations[ label ];

            if ( i < animation.start ) animation.start = i;
            if ( i > animation.end ) animation.end = i;

            if ( ! firstAnimation ) firstAnimation = label;

        }

    }

    geometry.firstAnimation = firstAnimation;

};

THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {

    if ( ! this.geometry.animations ) this.geometry.animations = {};

    this.geometry.animations[ label ] = { start: start, end: end };

};

THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {

    var animation = this.geometry.animations[ label ];

    if ( animation ) {

        this.setFrameRange( animation.start, animation.end );
        this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
        this.time = 0;

    } else {

        console.warn( "animation[" + label + "] undefined" );

    }

};

THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {

    var frameTime = this.duration / this.length;

    this.time += this.direction * delta;

    if ( this.mirroredLoop ) {

        if ( this.time > this.duration || this.time < 0 ) {

            this.direction *= -1;

            if ( this.time > this.duration ) {

                this.time = this.duration;
                this.directionBackwards = true;

            }

            if ( this.time < 0 ) {

                this.time = 0;
                this.directionBackwards = false;

            }

        }

    } else {

        this.time = this.time % this.duration;

        if ( this.time < 0 ) this.time += this.duration;

    }

    var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );

    if ( keyframe !== this.currentKeyframe ) {

        this.morphTargetInfluences[ this.lastKeyframe ] = 0;
        this.morphTargetInfluences[ this.currentKeyframe ] = 1;

        this.morphTargetInfluences[ keyframe ] = 0;

        this.lastKeyframe = this.currentKeyframe;
        this.currentKeyframe = keyframe;

    }

    var mix = ( this.time % frameTime ) / frameTime;

    if ( this.directionBackwards ) {

        mix = 1 - mix;

    }

    this.morphTargetInfluences[ this.currentKeyframe ] = mix;
    this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Ribbon = function ( geometry, material ) {

    THREE.Object3D.call( this );

    this.geometry = geometry;
    this.material = material;

};

THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 */

THREE.LOD = function () {

    THREE.Object3D.call( this );

    this.LODs = [];

};


THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );

THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {

    if ( visibleAtDistance === undefined ) {

        visibleAtDistance = 0;

    }

    visibleAtDistance = Math.abs( visibleAtDistance );

    for ( var l = 0; l < this.LODs.length; l ++ ) {

        if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {

            break;

        }

    }

    this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
    this.add( object3D );

};

THREE.LOD.prototype.update = function ( camera ) {

    if ( this.LODs.length > 1 ) {

        camera.matrixWorldInverse.getInverse( camera.matrixWorld );

        var inverse  = camera.matrixWorldInverse;
        var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );

        this.LODs[ 0 ].object3D.visible = true;

        for ( var l = 1; l < this.LODs.length; l ++ ) {

            if( distance >= this.LODs[ l ].visibleAtDistance ) {

                this.LODs[ l - 1 ].object3D.visible = false;
                this.LODs[ l     ].object3D.visible = true;

            } else {

                break;

            }

        }

        for( ; l < this.LODs.length; l ++ ) {

            this.LODs[ l ].object3D.visible = false;

        }

    }

};
/**
 * @author mikael emtinger / http://gomo.se/
 */

THREE.Sprite = function ( parameters ) {

    THREE.Object3D.call( this );

    this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
    this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();

    this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;

    this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
    this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
    this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;

    this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
    this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
    this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
    this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
    this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;

    this.rotation3d = this.rotation;
    this.rotation = 0;
    this.opacity = 1;

    this.uvOffset = new THREE.Vector2( 0, 0 );
    this.uvScale  = new THREE.Vector2( 1, 1 );

};

THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );

/*
 * Custom update matrix
 */

THREE.Sprite.prototype.updateMatrix = function () {

    this.matrix.setPosition( this.position );

    this.rotation3d.set( 0, 0, this.rotation );
    this.matrix.setRotationFromEuler( this.rotation3d );

    if ( this.scale.x !== 1 || this.scale.y !== 1 ) {

        this.matrix.scale( this.scale );
        this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );

    }

    this.matrixWorldNeedsUpdate = true;

};

/*
 * Alignment
 */

THREE.SpriteAlignment = {};
THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.Scene = function () {

    THREE.Object3D.call( this );

    this.fog = null;
    this.overrideMaterial = null;

    this.matrixAutoUpdate = false;

    this.__objects = [];
    this.__lights = [];

    this.__objectsAdded = [];
    this.__objectsRemoved = [];

};

THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );

THREE.Scene.prototype.__addObject = function ( object ) {

    if ( object instanceof THREE.Light ) {

        if ( this.__lights.indexOf( object ) === - 1 ) {

            this.__lights.push( object );

        }

        if ( object.target && object.target.parent === undefined ) {

            this.add( object.target );

        }

    } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {

        if ( this.__objects.indexOf( object ) === - 1 ) {

            this.__objects.push( object );
            this.__objectsAdded.push( object );

            // check if previously removed

            var i = this.__objectsRemoved.indexOf( object );

            if ( i !== -1 ) {

                this.__objectsRemoved.splice( i, 1 );

            }

        }

    }

    for ( var c = 0; c < object.children.length; c ++ ) {

        this.__addObject( object.children[ c ] );

    }

};

THREE.Scene.prototype.__removeObject = function ( object ) {

    if ( object instanceof THREE.Light ) {

        var i = this.__lights.indexOf( object );

        if ( i !== -1 ) {

            this.__lights.splice( i, 1 );

        }

    } else if ( !( object instanceof THREE.Camera ) ) {

        var i = this.__objects.indexOf( object );

        if( i !== -1 ) {

            this.__objects.splice( i, 1 );
            this.__objectsRemoved.push( object );

            // check if previously added

            var ai = this.__objectsAdded.indexOf( object );

            if ( ai !== -1 ) {

                this.__objectsAdded.splice( ai, 1 );

            }

        }

    }

    for ( var c = 0; c < object.children.length; c ++ ) {

        this.__removeObject( object.children[ c ] );

    }

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Fog = function ( hex, near, far ) {

    this.color = new THREE.Color( hex );

    this.near = ( near !== undefined ) ? near : 1;
    this.far = ( far !== undefined ) ? far : 1000;

};
/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.FogExp2 = function ( hex, density ) {

    this.color = new THREE.Color( hex );
    this.density = ( density !== undefined ) ? density : 0.00025;

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.CanvasRenderer = function ( parameters ) {

    console.log( 'THREE.CanvasRenderer', THREE.REVISION );

    parameters = parameters || {};

    var _this = this,
    _renderData, _elements, _lights,
    _projector = new THREE.Projector(),

    _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),

    _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
    _context = _canvas.getContext( '2d' ),

    _clearColor = new THREE.Color( 0x000000 ),
    _clearOpacity = 0,

    _contextGlobalAlpha = 1,
    _contextGlobalCompositeOperation = 0,
    _contextStrokeStyle = null,
    _contextFillStyle = null,
    _contextLineWidth = null,
    _contextLineCap = null,
    _contextLineJoin = null,

    _v1, _v2, _v3, _v4,
    _v5 = new THREE.RenderableVertex(),
    _v6 = new THREE.RenderableVertex(),

    _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
    _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,

    _color = new THREE.Color(),
    _color1 = new THREE.Color(),
    _color2 = new THREE.Color(),
    _color3 = new THREE.Color(),
    _color4 = new THREE.Color(),

    _patterns = {}, _imagedatas = {},

    _near, _far,

    _image, _uvs,
    _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,

    _clipRect = new THREE.Rectangle(),
    _clearRect = new THREE.Rectangle(),
    _bboxRect = new THREE.Rectangle(),

    _enableLighting = false,
    _ambientLight = new THREE.Color(),
    _directionalLights = new THREE.Color(),
    _pointLights = new THREE.Color(),

    _pi2 = Math.PI * 2,
    _vector3 = new THREE.Vector3(), // Needed for PointLight

    _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
    _gradientMap, _gradientMapContext, _gradientMapQuality = 16;

    _pixelMap = document.createElement( 'canvas' );
    _pixelMap.width = _pixelMap.height = 2;

    _pixelMapContext = _pixelMap.getContext( '2d' );
    _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
    _pixelMapContext.fillRect( 0, 0, 2, 2 );

    _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
    _pixelMapData = _pixelMapImage.data;

    _gradientMap = document.createElement( 'canvas' );
    _gradientMap.width = _gradientMap.height = _gradientMapQuality;

    _gradientMapContext = _gradientMap.getContext( '2d' );
    _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
    _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );

    _gradientMapQuality --; // Fix UVs

    this.domElement = _canvas;

    this.autoClear = true;
    this.sortObjects = true;
    this.sortElements = true;

    this.info = {

        render: {

            vertices: 0,
            faces: 0

        }

    }

    this.setSize = function ( width, height ) {

        _canvasWidth = width;
        _canvasHeight = height;
        _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
        _canvasHeightHalf = Math.floor( _canvasHeight / 2 );

        _canvas.width = _canvasWidth;
        _canvas.height = _canvasHeight;

        _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
        _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );

        _contextGlobalAlpha = 1;
        _contextGlobalCompositeOperation = 0;
        _contextStrokeStyle = null;
        _contextFillStyle = null;
        _contextLineWidth = null;
        _contextLineCap = null;
        _contextLineJoin = null;

    };

    this.setClearColor = function ( color, opacity ) {

        _clearColor.copy( color );
        _clearOpacity = opacity !== undefined ? opacity : 1;

        _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );

    };

    this.setClearColorHex = function ( hex, opacity ) {

        _clearColor.setHex( hex );
        _clearOpacity = opacity !== undefined ? opacity : 1;

        _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );

    };

    this.getMaxAnisotropy  = function () {

        return 0;

    };

    this.clear = function () {

        _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );

        if ( _clearRect.isEmpty() === false ) {

            _clearRect.minSelf( _clipRect );
            _clearRect.inflate( 2 );

            if ( _clearOpacity < 1 ) {

                _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );

            }

            if ( _clearOpacity > 0 ) {

                setBlending( THREE.NormalBlending );
                setOpacity( 1 );

                setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );

                _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );

            }

            _clearRect.empty();

        }


    };

    this.render = function ( scene, camera ) {

        if ( camera instanceof THREE.Camera === false ) {

            console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
            return;

        }

        var e, el, element, material;

        this.autoClear === true ? this.clear() : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );

        _this.info.render.vertices = 0;
        _this.info.render.faces = 0;

        _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
        _elements = _renderData.elements;
        _lights = _renderData.lights;

        /* DEBUG
        _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
        _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
        */

        _enableLighting = _lights.length > 0;

        if ( _enableLighting === true ) {

             calculateLights();

        }

        for ( e = 0, el = _elements.length; e < el; e++ ) {

            element = _elements[ e ];

            material = element.material;

            if ( material === undefined || material.visible === false ) continue;

            _bboxRect.empty();

            if ( element instanceof THREE.RenderableParticle ) {

                _v1 = element;
                _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;

                renderParticle( _v1, element, material, scene );

            } else if ( element instanceof THREE.RenderableLine ) {

                _v1 = element.v1; _v2 = element.v2;

                _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
                _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;

                _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
                _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );

                if ( _clipRect.intersects( _bboxRect ) === true ) {

                    renderLine( _v1, _v2, element, material, scene );

                }


            } else if ( element instanceof THREE.RenderableFace3 ) {

                _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;

                _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
                _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
                _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;

                if ( material.overdraw === true ) {

                    expand( _v1.positionScreen, _v2.positionScreen );
                    expand( _v2.positionScreen, _v3.positionScreen );
                    expand( _v3.positionScreen, _v1.positionScreen );

                }

                _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
                              _v2.positionScreen.x, _v2.positionScreen.y,
                              _v3.positionScreen.x, _v3.positionScreen.y );

                if ( _clipRect.intersects( _bboxRect ) === true ) {

                    renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );

                }

            } else if ( element instanceof THREE.RenderableFace4 ) {

                _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;

                _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
                _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
                _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
                _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;

                _v5.positionScreen.copy( _v2.positionScreen );
                _v6.positionScreen.copy( _v4.positionScreen );

                if ( material.overdraw === true ) {

                    expand( _v1.positionScreen, _v2.positionScreen );
                    expand( _v2.positionScreen, _v4.positionScreen );
                    expand( _v4.positionScreen, _v1.positionScreen );

                    expand( _v3.positionScreen, _v5.positionScreen );
                    expand( _v3.positionScreen, _v6.positionScreen );

                }

                _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
                _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
                _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
                _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );

                if ( _clipRect.intersects( _bboxRect ) === true ) {

                    renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );

                }

            }

            /* DEBUG
            _context.lineWidth = 1;
            _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
            _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
            */

            _clearRect.addRectangle( _bboxRect );


        }

        /* DEBUG
        _context.lineWidth = 1;
        _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
        _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
        */

        _context.setTransform( 1, 0, 0, 1, 0, 0 );

        //

        function calculateLights() {

            _ambientLight.setRGB( 0, 0, 0 );
            _directionalLights.setRGB( 0, 0, 0 );
            _pointLights.setRGB( 0, 0, 0 );

            for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {

                var light = _lights[ l ];
                var lightColor = light.color;

                if ( light instanceof THREE.AmbientLight ) {

                    _ambientLight.r += lightColor.r;
                    _ambientLight.g += lightColor.g;
                    _ambientLight.b += lightColor.b;

                } else if ( light instanceof THREE.DirectionalLight ) {

                    // for particles

                    _directionalLights.r += lightColor.r;
                    _directionalLights.g += lightColor.g;
                    _directionalLights.b += lightColor.b;

                } else if ( light instanceof THREE.PointLight ) {

                    // for particles

                    _pointLights.r += lightColor.r;
                    _pointLights.g += lightColor.g;
                    _pointLights.b += lightColor.b;

                }

            }

        }

        function calculateLight( position, normal, color ) {

            for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {

                var light = _lights[ l ];
                var lightColor = light.color;

                if ( light instanceof THREE.DirectionalLight ) {

                    var lightPosition = light.matrixWorld.getPosition().normalize();

                    var amount = normal.dot( lightPosition );

                    if ( amount <= 0 ) continue;

                    amount *= light.intensity;

                    color.r += lightColor.r * amount;
                    color.g += lightColor.g * amount;
                    color.b += lightColor.b * amount;

                } else if ( light instanceof THREE.PointLight ) {

                    var lightPosition = light.matrixWorld.getPosition();

                    var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );

                    if ( amount <= 0 ) continue;

                    amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );

                    if ( amount == 0 ) continue;

                    amount *= light.intensity;

                    color.r += lightColor.r * amount;
                    color.g += lightColor.g * amount;
                    color.b += lightColor.b * amount;

                }

            }

        }

        function renderParticle( v1, element, material, scene ) {

            setOpacity( material.opacity );
            setBlending( material.blending );

            var width, height, scaleX, scaleY,
            bitmap, bitmapWidth, bitmapHeight;

            if ( material instanceof THREE.ParticleBasicMaterial ) {

                if ( material.map === null ) {

                    scaleX = element.object.scale.x;
                    scaleY = element.object.scale.y;

                    // TODO: Be able to disable this

                    scaleX *= element.scale.x * _canvasWidthHalf;
                    scaleY *= element.scale.y * _canvasHeightHalf;

                    _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x  + scaleX, v1.y + scaleY );

                    if ( _clipRect.intersects( _bboxRect ) === false ) {

                        return;

                    }

                    setFillStyle( material.color.getContextStyle() );

                    _context.save();
                    _context.translate( v1.x, v1.y );
                    _context.rotate( - element.rotation );
                    _context.scale( scaleX, scaleY );
                    _context.fillRect( -1, -1, 2, 2 );
                    _context.restore();

                } else {

                    bitmap = material.map.image;
                    bitmapWidth = bitmap.width >> 1;
                    bitmapHeight = bitmap.height >> 1;

                    scaleX = element.scale.x * _canvasWidthHalf;
                    scaleY = element.scale.y * _canvasHeightHalf;

                    width = scaleX * bitmapWidth;
                    height = scaleY * bitmapHeight;

                    // TODO: Rotations break this...

                    _bboxRect.set( v1.x - width, v1.y - height, v1.x  + width, v1.y + height );

                    if ( _clipRect.intersects( _bboxRect ) === false ) {

                        return;

                    }

                    _context.save();
                    _context.translate( v1.x, v1.y );
                    _context.rotate( - element.rotation );
                    _context.scale( scaleX, - scaleY );

                    _context.translate( - bitmapWidth, - bitmapHeight );
                    _context.drawImage( bitmap, 0, 0 );
                    _context.restore();

                }

                /* DEBUG
                setStrokeStyle( 'rgb(255,255,0)' );
                _context.beginPath();
                _context.moveTo( v1.x - 10, v1.y );
                _context.lineTo( v1.x + 10, v1.y );
                _context.moveTo( v1.x, v1.y - 10 );
                _context.lineTo( v1.x, v1.y + 10 );
                _context.stroke();
                */

            } else if ( material instanceof THREE.ParticleCanvasMaterial ) {

                width = element.scale.x * _canvasWidthHalf;
                height = element.scale.y * _canvasHeightHalf;

                _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );

                if ( _clipRect.intersects( _bboxRect ) === false ) {

                    return;

                }

                setStrokeStyle( material.color.getContextStyle() );
                setFillStyle( material.color.getContextStyle() );

                _context.save();
                _context.translate( v1.x, v1.y );
                _context.rotate( - element.rotation );
                _context.scale( width, height );

                material.program( _context );

                _context.restore();

            }

        }

        function renderLine( v1, v2, element, material, scene ) {

            setOpacity( material.opacity );
            setBlending( material.blending );

            _context.beginPath();
            _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
            _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );

            if ( material instanceof THREE.LineBasicMaterial ) {

                setLineWidth( material.linewidth );
                setLineCap( material.linecap );
                setLineJoin( material.linejoin );
                setStrokeStyle( material.color.getContextStyle() );

                _context.stroke();
                _bboxRect.inflate( material.linewidth * 2 );

            }

        }

        function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {

            _this.info.render.vertices += 3;
            _this.info.render.faces ++;

            setOpacity( material.opacity );
            setBlending( material.blending );

            _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
            _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
            _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;

            drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );

            if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {

                if ( _enableLighting === true ) {

                    var diffuse = material.color;
                    var emissive = material.emissive;

                    if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {

                        _color1.r = _color2.r = _color3.r = _ambientLight.r;
                        _color1.g = _color2.g = _color3.g = _ambientLight.g;
                        _color1.b = _color2.b = _color3.b = _ambientLight.b;

                        calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
                        calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
                        calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );

                        _color1.r = diffuse.r * _color1.r + emissive.r;
                        _color1.g = diffuse.g * _color1.g + emissive.g;
                        _color1.b = diffuse.b * _color1.b + emissive.b;

                        _color2.r = diffuse.r * _color2.r + emissive.r;
                        _color2.g = diffuse.g * _color2.g + emissive.g;
                        _color2.b = diffuse.b * _color2.b + emissive.b;

                        _color3.r = diffuse.r * _color3.r + emissive.r;
                        _color3.g = diffuse.g * _color3.g + emissive.g;
                        _color3.b = diffuse.b * _color3.b + emissive.b;

                        _color4.r = ( _color2.r + _color3.r ) * 0.5;
                        _color4.g = ( _color2.g + _color3.g ) * 0.5;
                        _color4.b = ( _color2.b + _color3.b ) * 0.5;

                        _image = getGradientTexture( _color1, _color2, _color3, _color4 );

                        clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );

                    } else {

                        _color.r = _ambientLight.r;
                        _color.g = _ambientLight.g;
                        _color.b = _ambientLight.b;

                        calculateLight( element.centroidWorld, element.normalWorld, _color );

                        _color.r = diffuse.r * _color.r + emissive.r;
                        _color.g = diffuse.g * _color.g + emissive.g;
                        _color.b = diffuse.b * _color.b + emissive.b;

                        material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );

                    }

                } else {

                    material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );

                }

            } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {

                if ( material.map !== null ) {

                    if ( material.map.mapping instanceof THREE.UVMapping ) {

                        _uvs = element.uvs[ 0 ];
                        patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].u, _uvs[ uv1 ].v, _uvs[ uv2 ].u, _uvs[ uv2 ].v, _uvs[ uv3 ].u, _uvs[ uv3 ].v, material.map );

                    }


                } else if ( material.envMap !== null ) {

                    if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {

                        var cameraMatrix = camera.matrixWorldInverse;

                        _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
                        _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
                        _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;

                        _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
                        _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
                        _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;

                        _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
                        _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
                        _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;

                        patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );

                    }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {



                    }*/


                } else {

                    material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );

                }

            } else if ( material instanceof THREE.MeshDepthMaterial ) {

                _near = camera.near;
                _far = camera.far;

                _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
                _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
                _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );

                _color4.r = ( _color2.r + _color3.r ) * 0.5;
                _color4.g = ( _color2.g + _color3.g ) * 0.5;
                _color4.b = ( _color2.b + _color3.b ) * 0.5;

                _image = getGradientTexture( _color1, _color2, _color3, _color4 );

                clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );

            } else if ( material instanceof THREE.MeshNormalMaterial ) {

                _color.r = normalToComponent( element.normalWorld.x );
                _color.g = normalToComponent( element.normalWorld.y );
                _color.b = normalToComponent( element.normalWorld.z );

                material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );

            }

        }

        function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {

            _this.info.render.vertices += 4;
            _this.info.render.faces ++;

            setOpacity( material.opacity );
            setBlending( material.blending );

            if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {

                // Let renderFace3() handle this

                renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
                renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );

                return;

            }

            _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
            _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
            _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
            _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
            _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
            _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;

            if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {

                if ( _enableLighting === true ) {

                    var diffuse = material.color;
                    var emissive = material.emissive;

                    if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {

                        _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
                        _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
                        _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;

                        calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
                        calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
                        calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
                        calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );

                        _color1.r = diffuse.r * _color1.r + emissive.r;
                        _color1.g = diffuse.g * _color1.g + emissive.g;
                        _color1.b = diffuse.b * _color1.b + emissive.b;

                        _color2.r = diffuse.r * _color2.r + emissive.r;
                        _color2.g = diffuse.g * _color2.g + emissive.g;
                        _color2.b = diffuse.b * _color2.b + emissive.b;

                        _color3.r = diffuse.r * _color3.r + emissive.r;
                        _color3.g = diffuse.g * _color3.g + emissive.g;
                        _color3.b = diffuse.b * _color3.b + emissive.b;

                        _color4.r = diffuse.r * _color4.r + emissive.r;
                        _color4.g = diffuse.g * _color4.g + emissive.g;
                        _color4.b = diffuse.b * _color4.b + emissive.b;

                        _image = getGradientTexture( _color1, _color2, _color3, _color4 );

                        // TODO: UVs are incorrect, v4->v3?

                        drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
                        clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );

                        drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
                        clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );

                    } else {

                        _color.r = _ambientLight.r;
                        _color.g = _ambientLight.g;
                        _color.b = _ambientLight.b;

                        calculateLight( element.centroidWorld, element.normalWorld, _color );

                        _color.r = diffuse.r * _color.r + emissive.r;
                        _color.g = diffuse.g * _color.g + emissive.g;
                        _color.b = diffuse.b * _color.b + emissive.b;

                        drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );

                        material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );

                    }

                } else {

                    drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );

                    material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );

                }

            } else if ( material instanceof THREE.MeshBasicMaterial ) {

                drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );

                material.wireframe === true ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );

            } else if ( material instanceof THREE.MeshNormalMaterial ) {

                _color.r = normalToComponent( element.normalWorld.x );
                _color.g = normalToComponent( element.normalWorld.y );
                _color.b = normalToComponent( element.normalWorld.z );

                drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );

                material.wireframe === true ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );

            } else if ( material instanceof THREE.MeshDepthMaterial ) {

                _near = camera.near;
                _far = camera.far;

                _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
                _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
                _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
                _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );

                _image = getGradientTexture( _color1, _color2, _color3, _color4 );

                // TODO: UVs are incorrect, v4->v3?

                drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
                clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );

                drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
                clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );

            }

        }

        //

        function drawTriangle( x0, y0, x1, y1, x2, y2 ) {

            _context.beginPath();
            _context.moveTo( x0, y0 );
            _context.lineTo( x1, y1 );
            _context.lineTo( x2, y2 );
            _context.closePath();

        }

        function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {

            _context.beginPath();
            _context.moveTo( x0, y0 );
            _context.lineTo( x1, y1 );
            _context.lineTo( x2, y2 );
            _context.lineTo( x3, y3 );
            _context.closePath();

        }

        function strokePath( color, linewidth, linecap, linejoin ) {

            setLineWidth( linewidth );
            setLineCap( linecap );
            setLineJoin( linejoin );
            setStrokeStyle( color.getContextStyle() );

            _context.stroke();

            _bboxRect.inflate( linewidth * 2 );

        }

        function fillPath( color ) {

            setFillStyle( color.getContextStyle() );
            _context.fill();

        }

        function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {

            if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;

            if ( texture.needsUpdate === true ) {

                var repeatX = texture.wrapS == THREE.RepeatWrapping;
                var repeatY = texture.wrapT == THREE.RepeatWrapping;

                _patterns[ texture.id ] = _context.createPattern(
                    texture.image, repeatX === true && repeatY === true
                        ? 'repeat'
                        : repeatX === true && repeatY === false
                            ? 'repeat-x'
                            : repeatX === false && repeatY === true
                                ? 'repeat-y'
                                : 'no-repeat'
                );

                texture.needsUpdate = false;

            }

            _patterns[ texture.id ] === undefined
                ? setFillStyle( 'rgba(0,0,0,1)' )
                : setFillStyle( _patterns[ texture.id ] );

            // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120

            var a, b, c, d, e, f, det, idet,
            offsetX = texture.offset.x / texture.repeat.x,
            offsetY = texture.offset.y / texture.repeat.y,
            width = texture.image.width * texture.repeat.x,
            height = texture.image.height * texture.repeat.y;

            u0 = ( u0 + offsetX ) * width;
            v0 = ( 1.0 - v0 + offsetY ) * height;

            u1 = ( u1 + offsetX ) * width;
            v1 = ( 1.0 - v1 + offsetY ) * height;

            u2 = ( u2 + offsetX ) * width;
            v2 = ( 1.0 - v2 + offsetY ) * height;

            x1 -= x0; y1 -= y0;
            x2 -= x0; y2 -= y0;

            u1 -= u0; v1 -= v0;
            u2 -= u0; v2 -= v0;

            det = u1 * v2 - u2 * v1;

            if ( det === 0 ) {

                if ( _imagedatas[ texture.id ] === undefined ) {

                    var canvas = document.createElement( 'canvas' )
                    canvas.width = texture.image.width;
                    canvas.height = texture.image.height;

                    var context = canvas.getContext( '2d' );
                    context.drawImage( texture.image, 0, 0 );

                    _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;

                }

                var data = _imagedatas[ texture.id ];
                var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;

                _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
                fillPath( _color );

                return;

            }

            idet = 1 / det;

            a = ( v2 * x1 - v1 * x2 ) * idet;
            b = ( v2 * y1 - v1 * y2 ) * idet;
            c = ( u1 * x2 - u2 * x1 ) * idet;
            d = ( u1 * y2 - u2 * y1 ) * idet;

            e = x0 - a * u0 - c * v0;
            f = y0 - b * u0 - d * v0;

            _context.save();
            _context.transform( a, b, c, d, e, f );
            _context.fill();
            _context.restore();

        }

        function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {

            // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120

            var a, b, c, d, e, f, det, idet,
            width = image.width - 1,
            height = image.height - 1;

            u0 *= width; v0 *= height;
            u1 *= width; v1 *= height;
            u2 *= width; v2 *= height;

            x1 -= x0; y1 -= y0;
            x2 -= x0; y2 -= y0;

            u1 -= u0; v1 -= v0;
            u2 -= u0; v2 -= v0;

            det = u1 * v2 - u2 * v1;

            idet = 1 / det;

            a = ( v2 * x1 - v1 * x2 ) * idet;
            b = ( v2 * y1 - v1 * y2 ) * idet;
            c = ( u1 * x2 - u2 * x1 ) * idet;
            d = ( u1 * y2 - u2 * y1 ) * idet;

            e = x0 - a * u0 - c * v0;
            f = y0 - b * u0 - d * v0;

            _context.save();
            _context.transform( a, b, c, d, e, f );
            _context.clip();
            _context.drawImage( image, 0, 0 );
            _context.restore();

        }

        function getGradientTexture( color1, color2, color3, color4 ) {

            // http://mrdoob.com/blog/post/710

            _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
            _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
            _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;

            _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
            _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
            _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;

            _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
            _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
            _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;

            _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
            _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
            _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;

            _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
            _gradientMapContext.drawImage( _pixelMap, 0, 0 );

            return _gradientMap;

        }

        function smoothstep( value, min, max ) {

            var x = ( value - min ) / ( max - min );
            return x * x * ( 3 - 2 * x );

        }

        function normalToComponent( normal ) {

            var component = ( normal + 1 ) * 0.5;
            return component < 0 ? 0 : ( component > 1 ? 1 : component );

        }

        // Hide anti-alias gaps

        function expand( v1, v2 ) {

            var x = v2.x - v1.x, y =  v2.y - v1.y,
            det = x * x + y * y, idet;

            if ( det === 0 ) return;

            idet = 1 / Math.sqrt( det );

            x *= idet; y *= idet;

            v2.x += x; v2.y += y;
            v1.x -= x; v1.y -= y;

        }
    };

    // Context cached methods.

    function setOpacity( value ) {

        if ( _contextGlobalAlpha !== value ) {

            _context.globalAlpha = value;
            _contextGlobalAlpha = value;

        }

    }

    function setBlending( value ) {

        if ( _contextGlobalCompositeOperation !== value ) {

            if ( value === THREE.NormalBlending ) {

                _context.globalCompositeOperation = 'source-over';

            } else if ( value === THREE.AdditiveBlending ) {

                _context.globalCompositeOperation = 'lighter';

            } else if ( value === THREE.SubtractiveBlending ) {

                _context.globalCompositeOperation = 'darker';

            }

            _contextGlobalCompositeOperation = value;

        }

    }

    function setLineWidth( value ) {

        if ( _contextLineWidth !== value ) {

            _context.lineWidth = value;
            _contextLineWidth = value;

        }

    }

    function setLineCap( value ) {

        // "butt", "round", "square"

        if ( _contextLineCap !== value ) {

            _context.lineCap = value;
            _contextLineCap = value;

        }

    }

    function setLineJoin( value ) {

        // "round", "bevel", "miter"

        if ( _contextLineJoin !== value ) {

            _context.lineJoin = value;
            _contextLineJoin = value;

        }

    }

    function setStrokeStyle( value ) {

        if ( _contextStrokeStyle !== value ) {

            _context.strokeStyle = value;
            _contextStrokeStyle = value;

        }

    }

    function setFillStyle( value ) {

        if ( _contextFillStyle !== value ) {

            _context.fillStyle = value;
            _contextFillStyle = value;

        }

    }

};
/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 * @author mikael emtinger / http://gomo.se/
 */

THREE.ShaderChunk = {

    // FOG

    fog_pars_fragment: [

        "#ifdef USE_FOG",

            "uniform vec3 fogColor;",

            "#ifdef FOG_EXP2",

                "uniform float fogDensity;",

            "#else",

                "uniform float fogNear;",
                "uniform float fogFar;",

            "#endif",

        "#endif"

    ].join("\n"),

    fog_fragment: [

        "#ifdef USE_FOG",

            "float depth = gl_FragCoord.z / gl_FragCoord.w;",

            "#ifdef FOG_EXP2",

                "const float LOG2 = 1.442695;",
                "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
                "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",

            "#else",

                "float fogFactor = smoothstep( fogNear, fogFar, depth );",

            "#endif",

            "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",

        "#endif"

    ].join("\n"),

    // ENVIRONMENT MAP

    envmap_pars_fragment: [

        "#ifdef USE_ENVMAP",

            "uniform float reflectivity;",
            "uniform samplerCube envMap;",
            "uniform float flipEnvMap;",
            "uniform int combine;",

            "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",

                "uniform bool useRefract;",
                "uniform float refractionRatio;",

            "#else",

                "varying vec3 vReflect;",

            "#endif",

        "#endif"

    ].join("\n"),

    envmap_fragment: [

        "#ifdef USE_ENVMAP",

            "vec3 reflectVec;",

            "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",

                "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",

                "if ( useRefract ) {",

                    "reflectVec = refract( cameraToVertex, normal, refractionRatio );",

                "} else { ",

                    "reflectVec = reflect( cameraToVertex, normal );",

                "}",

            "#else",

                "reflectVec = vReflect;",

            "#endif",

            "#ifdef DOUBLE_SIDED",

                "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
                "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",

            "#else",

                "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",

            "#endif",

            "#ifdef GAMMA_INPUT",

                "cubeColor.xyz *= cubeColor.xyz;",

            "#endif",

            "if ( combine == 1 ) {",

                "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",

            "} else {",

                "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",

            "}",

        "#endif"

    ].join("\n"),

    envmap_pars_vertex: [

        "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",

            "varying vec3 vReflect;",

            "uniform float refractionRatio;",
            "uniform bool useRefract;",

        "#endif"

    ].join("\n"),

    worldpos_vertex : [

        "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",

            "#ifdef USE_SKINNING",

                "vec4 mPosition = modelMatrix * skinned;",

            "#endif",

            "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",

                "vec4 mPosition = modelMatrix * vec4( morphed, 1.0 );",

            "#endif",

            "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",

                "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",

            "#endif",

        "#endif"

    ].join("\n"),

    envmap_vertex : [

        "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",

            "vec3 nWorld = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",

            "if ( useRefract ) {",

                "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",

            "} else {",

                "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",

            "}",

        "#endif"

    ].join("\n"),

    // COLOR MAP (particles)

    map_particle_pars_fragment: [

        "#ifdef USE_MAP",

            "uniform sampler2D map;",

        "#endif"

    ].join("\n"),


    map_particle_fragment: [

        "#ifdef USE_MAP",

            "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",

        "#endif"

    ].join("\n"),

    // COLOR MAP (triangles)

    map_pars_vertex: [

        "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",

            "varying vec2 vUv;",
            "uniform vec4 offsetRepeat;",

        "#endif"

    ].join("\n"),

    map_pars_fragment: [

        "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",

            "varying vec2 vUv;",

        "#endif",

        "#ifdef USE_MAP",

            "uniform sampler2D map;",

        "#endif",

    ].join("\n"),

    map_vertex: [

        "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",

            "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",

        "#endif"

    ].join("\n"),

    map_fragment: [

        "#ifdef USE_MAP",

            "#ifdef GAMMA_INPUT",

                "vec4 texelColor = texture2D( map, vUv );",
                "texelColor.xyz *= texelColor.xyz;",

                "gl_FragColor = gl_FragColor * texelColor;",

            "#else",

                "gl_FragColor = gl_FragColor * texture2D( map, vUv );",

            "#endif",

        "#endif"

    ].join("\n"),

    // LIGHT MAP

    lightmap_pars_fragment: [

        "#ifdef USE_LIGHTMAP",

            "varying vec2 vUv2;",
            "uniform sampler2D lightMap;",

        "#endif"

    ].join("\n"),

    lightmap_pars_vertex: [

        "#ifdef USE_LIGHTMAP",

            "varying vec2 vUv2;",

        "#endif"

    ].join("\n"),

    lightmap_fragment: [

        "#ifdef USE_LIGHTMAP",

            "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",

        "#endif"

    ].join("\n"),

    lightmap_vertex: [

        "#ifdef USE_LIGHTMAP",

            "vUv2 = uv2;",

        "#endif"

    ].join("\n"),

    // BUMP MAP

    bumpmap_pars_fragment: [

        "#ifdef USE_BUMPMAP",

            "uniform sampler2D bumpMap;",
            "uniform float bumpScale;",

            // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
            //    http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html

            // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)

            "vec2 dHdxy_fwd() {",

                "vec2 dSTdx = dFdx( vUv );",
                "vec2 dSTdy = dFdy( vUv );",

                "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
                "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
                "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",

                "return vec2( dBx, dBy );",

            "}",

            "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",

                "vec3 vSigmaX = dFdx( surf_pos );",
                "vec3 vSigmaY = dFdy( surf_pos );",
                "vec3 vN = surf_norm;",        // normalized

                "vec3 R1 = cross( vSigmaY, vN );",
                "vec3 R2 = cross( vN, vSigmaX );",

                "float fDet = dot( vSigmaX, R1 );",

                "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
                "return normalize( abs( fDet ) * surf_norm - vGrad );",

            "}",

        "#endif"

    ].join("\n"),

    // NORMAL MAP

    normalmap_pars_fragment: [

        "#ifdef USE_NORMALMAP",

            "uniform sampler2D normalMap;",
            "uniform vec2 normalScale;",

            // Per-Pixel Tangent Space Normal Mapping
            // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html

            "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",

                "vec3 q0 = dFdx( eye_pos.xyz );",
                "vec3 q1 = dFdy( eye_pos.xyz );",
                "vec2 st0 = dFdx( vUv.st );",
                "vec2 st1 = dFdy( vUv.st );",

                "vec3 S = normalize(  q0 * st1.t - q1 * st0.t );",
                "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
                "vec3 N = normalize( surf_norm );",

                "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
                "mapN.xy = normalScale * mapN.xy;",
                "mat3 tsn = mat3( S, T, N );",
                "return normalize( tsn * mapN );",

            "}",

        "#endif"

    ].join("\n"),

    // SPECULAR MAP

    specularmap_pars_fragment: [

        "#ifdef USE_SPECULARMAP",

            "uniform sampler2D specularMap;",

        "#endif"

    ].join("\n"),

    specularmap_fragment: [

        "float specularStrength;",

        "#ifdef USE_SPECULARMAP",

            "vec4 texelSpecular = texture2D( specularMap, vUv );",
            "specularStrength = texelSpecular.r;",

        "#else",

            "specularStrength = 1.0;",

        "#endif"

    ].join("\n"),

    // LIGHTS LAMBERT

    lights_lambert_pars_vertex: [

        "uniform vec3 ambient;",
        "uniform vec3 diffuse;",
        "uniform vec3 emissive;",

        "uniform vec3 ambientLightColor;",

        "#if MAX_DIR_LIGHTS > 0",

            "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
            "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",

        "#endif",

        "#if MAX_HEMI_LIGHTS > 0",

            "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
            "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
            "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",

        "#endif",

        "#if MAX_POINT_LIGHTS > 0",

            "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
            "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
            "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0",

            "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
            "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
            "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
            "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
            "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
            "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",

        "#endif",

        "#ifdef WRAP_AROUND",

            "uniform vec3 wrapRGB;",

        "#endif"

    ].join("\n"),

    lights_lambert_vertex: [

        "vLightFront = vec3( 0.0 );",

        "#ifdef DOUBLE_SIDED",

            "vLightBack = vec3( 0.0 );",

        "#endif",

        "transformedNormal = normalize( transformedNormal );",

        "#if MAX_DIR_LIGHTS > 0",

        "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",

            "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
            "vec3 dirVector = normalize( lDirection.xyz );",

            "float dotProduct = dot( transformedNormal, dirVector );",
            "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",

            "#ifdef DOUBLE_SIDED",

                "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",

                "#ifdef WRAP_AROUND",

                    "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",

                "#endif",

            "#endif",

            "#ifdef WRAP_AROUND",

                "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
                "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",

                "#ifdef DOUBLE_SIDED",

                    "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",

                "#endif",

            "#endif",

            "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",

            "#ifdef DOUBLE_SIDED",

                "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",

            "#endif",

        "}",

        "#endif",

        "#if MAX_POINT_LIGHTS > 0",

            "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",

                "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
                "vec3 lVector = lPosition.xyz - mvPosition.xyz;",

                "float lDistance = 1.0;",
                "if ( pointLightDistance[ i ] > 0.0 )",
                    "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",

                "lVector = normalize( lVector );",
                "float dotProduct = dot( transformedNormal, lVector );",

                "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",

                "#ifdef DOUBLE_SIDED",

                    "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",

                    "#ifdef WRAP_AROUND",

                        "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",

                    "#endif",

                "#endif",

                "#ifdef WRAP_AROUND",

                    "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
                    "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",

                    "#ifdef DOUBLE_SIDED",

                        "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",

                    "#endif",

                "#endif",

                "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",

                "#ifdef DOUBLE_SIDED",

                    "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",

                "#endif",

            "}",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0",

            "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",

                "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
                "vec3 lVector = lPosition.xyz - mvPosition.xyz;",

                "lVector = normalize( lVector );",

                "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - mPosition.xyz ) );",

                "if ( spotEffect > spotLightAngle[ i ] ) {",

                    "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",

                    "float lDistance = 1.0;",
                    "if ( spotLightDistance[ i ] > 0.0 )",
                        "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",

                    "float dotProduct = dot( transformedNormal, lVector );",
                    "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",

                    "#ifdef DOUBLE_SIDED",

                        "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",

                        "#ifdef WRAP_AROUND",

                            "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",

                        "#endif",

                    "#endif",

                    "#ifdef WRAP_AROUND",

                        "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
                        "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",

                        "#ifdef DOUBLE_SIDED",

                            "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",

                        "#endif",

                    "#endif",

                    "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",

                    "#ifdef DOUBLE_SIDED",

                        "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",

                    "#endif",

                "}",

            "}",

        "#endif",

        "#if MAX_HEMI_LIGHTS > 0",

            "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",

                "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
                "vec3 lVector = lPosition.xyz - mvPosition.xyz;",

                "lVector = normalize( lVector );",

                "float dotProduct = dot( transformedNormal, lVector );",

                "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
                "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",

                "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",

                "#ifdef DOUBLE_SIDED",

                    "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",

                "#endif",

            "}",

        "#endif",

        "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",

        "#ifdef DOUBLE_SIDED",

            "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",

        "#endif"

    ].join("\n"),

    // LIGHTS PHONG

    lights_phong_pars_vertex: [

        "#ifndef PHONG_PER_PIXEL",

        "#if MAX_POINT_LIGHTS > 0",

            "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
            "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",

            "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0",

            "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
            "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",

            "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",

        "#endif",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",

            "varying vec3 vWorldPosition;",

        "#endif"

    ].join("\n"),


    lights_phong_vertex: [

        "#ifndef PHONG_PER_PIXEL",

        "#if MAX_POINT_LIGHTS > 0",

            "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",

                "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
                "vec3 lVector = lPosition.xyz - mvPosition.xyz;",

                "float lDistance = 1.0;",
                "if ( pointLightDistance[ i ] > 0.0 )",
                    "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",

                "vPointLight[ i ] = vec4( lVector, lDistance );",

            "}",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0",

            "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",

                "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
                "vec3 lVector = lPosition.xyz - mvPosition.xyz;",

                "float lDistance = 1.0;",
                "if ( spotLightDistance[ i ] > 0.0 )",
                    "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",

                "vSpotLight[ i ] = vec4( lVector, lDistance );",

            "}",

        "#endif",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",

            "vWorldPosition = mPosition.xyz;",

        "#endif"

    ].join("\n"),

    lights_phong_pars_fragment: [

        "uniform vec3 ambientLightColor;",

        "#if MAX_DIR_LIGHTS > 0",

            "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
            "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",

        "#endif",

        "#if MAX_HEMI_LIGHTS > 0",

            "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
            "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
            "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",

        "#endif",

        "#if MAX_POINT_LIGHTS > 0",

            "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",

            "#ifdef PHONG_PER_PIXEL",

                "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
                "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",

            "#else",

                "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",

            "#endif",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0",

            "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
            "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
            "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
            "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
            "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",

            "#ifdef PHONG_PER_PIXEL",

                "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",

            "#else",

                "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",

            "#endif",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",

            "varying vec3 vWorldPosition;",

        "#endif",

        "#ifdef WRAP_AROUND",

            "uniform vec3 wrapRGB;",

        "#endif",

        "varying vec3 vViewPosition;",
        "varying vec3 vNormal;"

    ].join("\n"),

    lights_phong_fragment: [

        "vec3 normal = normalize( vNormal );",
        "vec3 viewPosition = normalize( vViewPosition );",

        "#ifdef DOUBLE_SIDED",

            "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",

        "#endif",

        "#ifdef USE_NORMALMAP",

            "normal = perturbNormal2Arb( -viewPosition, normal );",

        "#elif defined( USE_BUMPMAP )",

            "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",

        "#endif",

        "#if MAX_POINT_LIGHTS > 0",

            "vec3 pointDiffuse  = vec3( 0.0 );",
            "vec3 pointSpecular = vec3( 0.0 );",

            "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",

                "#ifdef PHONG_PER_PIXEL",

                    "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
                    "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",

                    "float lDistance = 1.0;",
                    "if ( pointLightDistance[ i ] > 0.0 )",
                        "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",

                    "lVector = normalize( lVector );",

                "#else",

                    "vec3 lVector = normalize( vPointLight[ i ].xyz );",
                    "float lDistance = vPointLight[ i ].w;",

                "#endif",

                // diffuse

                "float dotProduct = dot( normal, lVector );",

                "#ifdef WRAP_AROUND",

                    "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
                    "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",

                    "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",

                "#else",

                    "float pointDiffuseWeight = max( dotProduct, 0.0 );",

                "#endif",

                "pointDiffuse  += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",

                // specular

                "vec3 pointHalfVector = normalize( lVector + viewPosition );",
                "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
                "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",

                "#ifdef PHYSICALLY_BASED_SHADING",

                    // 2.0 => 2.0001 is hack to work around ANGLE bug

                    "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",

                    "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
                    "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",

                "#else",

                    "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",

                "#endif",

            "}",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0",

            "vec3 spotDiffuse  = vec3( 0.0 );",
            "vec3 spotSpecular = vec3( 0.0 );",

            "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",

                "#ifdef PHONG_PER_PIXEL",

                    "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
                    "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",

                    "float lDistance = 1.0;",
                    "if ( spotLightDistance[ i ] > 0.0 )",
                        "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",

                    "lVector = normalize( lVector );",

                "#else",

                    "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
                    "float lDistance = vSpotLight[ i ].w;",

                "#endif",

                "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",

                "if ( spotEffect > spotLightAngle[ i ] ) {",

                    "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",

                    // diffuse

                    "float dotProduct = dot( normal, lVector );",

                    "#ifdef WRAP_AROUND",

                        "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
                        "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",

                        "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",

                    "#else",

                        "float spotDiffuseWeight = max( dotProduct, 0.0 );",

                    "#endif",

                    "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",

                    // specular

                    "vec3 spotHalfVector = normalize( lVector + viewPosition );",
                    "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
                    "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",

                    "#ifdef PHYSICALLY_BASED_SHADING",

                        // 2.0 => 2.0001 is hack to work around ANGLE bug

                        "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",

                        "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
                        "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",

                    "#else",

                        "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",

                    "#endif",

                "}",

            "}",

        "#endif",

        "#if MAX_DIR_LIGHTS > 0",

            "vec3 dirDiffuse  = vec3( 0.0 );",
            "vec3 dirSpecular = vec3( 0.0 );" ,

            "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",

                "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
                "vec3 dirVector = normalize( lDirection.xyz );",

                // diffuse

                "float dotProduct = dot( normal, dirVector );",

                "#ifdef WRAP_AROUND",

                    "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
                    "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",

                    "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",

                "#else",

                    "float dirDiffuseWeight = max( dotProduct, 0.0 );",

                "#endif",

                "dirDiffuse  += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",

                // specular

                "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
                "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
                "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",

                "#ifdef PHYSICALLY_BASED_SHADING",

                    /*
                    // fresnel term from skin shader
                    "const float F0 = 0.128;",

                    "float base = 1.0 - dot( viewPosition, dirHalfVector );",
                    "float exponential = pow( base, 5.0 );",

                    "float fresnel = exponential + F0 * ( 1.0 - exponential );",
                    */

                    /*
                    // fresnel term from fresnel shader
                    "const float mFresnelBias = 0.08;",
                    "const float mFresnelScale = 0.3;",
                    "const float mFresnelPower = 5.0;",

                    "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
                    */

                    // 2.0 => 2.0001 is hack to work around ANGLE bug

                    "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",

                    //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",

                    "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
                    "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",

                "#else",

                    "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",

                "#endif",

            "}",

        "#endif",

        "#if MAX_HEMI_LIGHTS > 0",

            "vec3 hemiDiffuse  = vec3( 0.0 );",
            "vec3 hemiSpecular = vec3( 0.0 );" ,

            "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",

                "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
                "vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",

                // diffuse

                "float dotProduct = dot( normal, lVector );",
                "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",

                "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",

                "hemiDiffuse += diffuse * hemiColor;",

                // specular (sky light)

                "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
                "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
                "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",

                // specular (ground light)

                "vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",

                "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
                "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
                "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",

                "#ifdef PHYSICALLY_BASED_SHADING",

                    "float dotProductGround = dot( normal, lVectorGround );",

                    // 2.0 => 2.0001 is hack to work around ANGLE bug

                    "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",

                    "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
                    "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
                    "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",

                "#else",

                    "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",

                "#endif",

            "}",

        "#endif",

        "vec3 totalDiffuse = vec3( 0.0 );",
        "vec3 totalSpecular = vec3( 0.0 );",

        "#if MAX_DIR_LIGHTS > 0",

            "totalDiffuse += dirDiffuse;",
            "totalSpecular += dirSpecular;",

        "#endif",

        "#if MAX_HEMI_LIGHTS > 0",

            "totalDiffuse += hemiDiffuse;",
            "totalSpecular += hemiSpecular;",

        "#endif",

        "#if MAX_POINT_LIGHTS > 0",

            "totalDiffuse += pointDiffuse;",
            "totalSpecular += pointSpecular;",

        "#endif",

        "#if MAX_SPOT_LIGHTS > 0",

            "totalDiffuse += spotDiffuse;",
            "totalSpecular += spotSpecular;",

        "#endif",

        "#ifdef METAL",

            "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",

        "#else",

            "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",

        "#endif"

    ].join("\n"),

    // VERTEX COLORS

    color_pars_fragment: [

        "#ifdef USE_COLOR",

            "varying vec3 vColor;",

        "#endif"

    ].join("\n"),


    color_fragment: [

        "#ifdef USE_COLOR",

            "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",

        "#endif"

    ].join("\n"),

    color_pars_vertex: [

        "#ifdef USE_COLOR",

            "varying vec3 vColor;",

        "#endif"

    ].join("\n"),


    color_vertex: [

        "#ifdef USE_COLOR",

            "#ifdef GAMMA_INPUT",

                "vColor = color * color;",

            "#else",

                "vColor = color;",

            "#endif",

        "#endif"

    ].join("\n"),

    // SKINNING

    skinning_pars_vertex: [

        "#ifdef USE_SKINNING",

            "#ifdef BONE_TEXTURE",

                "uniform sampler2D boneTexture;",

                "mat4 getBoneMatrix( const in float i ) {",

                    "float j = i * 4.0;",
                    "float x = mod( j, N_BONE_PIXEL_X );",
                    "float y = floor( j / N_BONE_PIXEL_X );",

                    "const float dx = 1.0 / N_BONE_PIXEL_X;",
                    "const float dy = 1.0 / N_BONE_PIXEL_Y;",

                    "y = dy * ( y + 0.5 );",

                    "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
                    "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
                    "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
                    "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",

                    "mat4 bone = mat4( v1, v2, v3, v4 );",

                    "return bone;",

                "}",

            "#else",

                "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",

                "mat4 getBoneMatrix( const in float i ) {",

                    "mat4 bone = boneGlobalMatrices[ int(i) ];",
                    "return bone;",

                "}",

            "#endif",

        "#endif"

    ].join("\n"),

    skinbase_vertex: [

        "#ifdef USE_SKINNING",

            "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
            "mat4 boneMatY = getBoneMatrix( skinIndex.y );",

        "#endif"

    ].join("\n"),

    skinning_vertex: [

        "#ifdef USE_SKINNING",

            "#ifdef USE_MORPHTARGETS",

            "vec4 skinVertex = vec4( morphed, 1.0 );",

            "#else",

            "vec4 skinVertex = vec4( position, 1.0 );",

            "#endif",

            "vec4 skinned  = boneMatX * skinVertex * skinWeight.x;",
            "skinned       += boneMatY * skinVertex * skinWeight.y;",

        "#endif"

    ].join("\n"),

    // MORPHING

    morphtarget_pars_vertex: [

        "#ifdef USE_MORPHTARGETS",

            "#ifndef USE_MORPHNORMALS",

            "uniform float morphTargetInfluences[ 8 ];",

            "#else",

            "uniform float morphTargetInfluences[ 4 ];",

            "#endif",

        "#endif"

    ].join("\n"),

    morphtarget_vertex: [

        "#ifdef USE_MORPHTARGETS",

            "vec3 morphed = vec3( 0.0 );",
            "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
            "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
            "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
            "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",

            "#ifndef USE_MORPHNORMALS",

            "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
            "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
            "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
            "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",

            "#endif",

            "morphed += position;",

        "#endif"

    ].join("\n"),

    default_vertex : [

        "vec4 mvPosition;",

        "#ifdef USE_SKINNING",

            "mvPosition = modelViewMatrix * skinned;",

        "#endif",

        "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",

            "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",

        "#endif",

        "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",

            "mvPosition = modelViewMatrix * vec4( position, 1.0 );",

        "#endif",

        "gl_Position = projectionMatrix * mvPosition;",

    ].join("\n"),

    morphnormal_vertex: [

        "#ifdef USE_MORPHNORMALS",

            "vec3 morphedNormal = vec3( 0.0 );",

            "morphedNormal +=  ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
            "morphedNormal +=  ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
            "morphedNormal +=  ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
            "morphedNormal +=  ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",

            "morphedNormal += normal;",

        "#endif"

    ].join("\n"),

    skinnormal_vertex: [

        "#ifdef USE_SKINNING",

            "mat4 skinMatrix = skinWeight.x * boneMatX;",
            "skinMatrix     += skinWeight.y * boneMatY;",

            "#ifdef USE_MORPHNORMALS",

            "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",

            "#else",

            "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",

            "#endif",

        "#endif"

    ].join("\n"),

    defaultnormal_vertex: [

        "vec3 objectNormal;",

        "#ifdef USE_SKINNING",

            "objectNormal = skinnedNormal.xyz;",

        "#endif",

        "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",

            "objectNormal = morphedNormal;",

        "#endif",

        "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",

            "objectNormal = normal;",

        "#endif",

        "#ifdef FLIP_SIDED",

            "objectNormal = -objectNormal;",

        "#endif",

        "vec3 transformedNormal = normalMatrix * objectNormal;",

    ].join("\n"),

    // SHADOW MAP

    // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
    //  http://spidergl.org/example.php?id=6
    //     http://fabiensanglard.net/shadowmapping

    shadowmap_pars_fragment: [

        "#ifdef USE_SHADOWMAP",

            "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
            "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",

            "uniform float shadowDarkness[ MAX_SHADOWS ];",
            "uniform float shadowBias[ MAX_SHADOWS ];",

            "varying vec4 vShadowCoord[ MAX_SHADOWS ];",

            "float unpackDepth( const in vec4 rgba_depth ) {",

                "const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );",
                "float depth = dot( rgba_depth, bit_shift );",
                "return depth;",

            "}",

        "#endif"

    ].join("\n"),

    shadowmap_fragment: [

        "#ifdef USE_SHADOWMAP",

            "#ifdef SHADOWMAP_DEBUG",

                "vec3 frustumColors[3];",
                "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
                "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
                "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",

            "#endif",

            "#ifdef SHADOWMAP_CASCADE",

                "int inFrustumCount = 0;",

            "#endif",

            "float fDepth;",
            "vec3 shadowColor = vec3( 1.0 );",

            "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",

                "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",

                // "if ( something && something )"          breaks ATI OpenGL shader compiler
                // "if ( all( something, something ) )"  using this instead

                "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
                "bool inFrustum = all( inFrustumVec );",

                // don't shadow pixels outside of light frustum
                // use just first frustum (for cascades)
                // don't shadow pixels behind far plane of light frustum

                "#ifdef SHADOWMAP_CASCADE",

                    "inFrustumCount += int( inFrustum );",
                    "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",

                "#else",

                    "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",

                "#endif",

                "bool frustumTest = all( frustumTestVec );",

                "if ( frustumTest ) {",

                    "shadowCoord.z += shadowBias[ i ];",

                    "#ifdef SHADOWMAP_SOFT",

                        // Percentage-close filtering
                        // (9 pixel kernel)
                        // http://fabiensanglard.net/shadowmappingPCF/

                        "float shadow = 0.0;",

                        /*
                        // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
                        // must enroll loop manually

                        "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
                            "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",

                                "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",

                                // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
                                //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",

                                "float fDepth = unpackDepth( rgbaDepth );",

                                "if ( fDepth < shadowCoord.z )",
                                    "shadow += 1.0;",

                        "}",

                        "shadow /= 9.0;",

                        */

                        "const float shadowDelta = 1.0 / 9.0;",

                        "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
                        "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",

                        "float dx0 = -1.25 * xPixelOffset;",
                        "float dy0 = -1.25 * yPixelOffset;",
                        "float dx1 = 1.25 * xPixelOffset;",
                        "float dy1 = 1.25 * yPixelOffset;",

                        "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
                        "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",

                        "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
                        "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",

                        "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
                        "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",

                        "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
                        "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",

                        "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
                        "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",

                        "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
                        "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",

                        "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
                        "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",

                        "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
                        "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",

                        "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
                        "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",

                        "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",

                    "#else",

                        "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
                        "float fDepth = unpackDepth( rgbaDepth );",

                        "if ( fDepth < shadowCoord.z )",

                            // spot with multiple shadows is darker

                            "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",

                            // spot with multiple shadows has the same color as single shadow spot

                            //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",

                    "#endif",

                "}",


                "#ifdef SHADOWMAP_DEBUG",

                    "#ifdef SHADOWMAP_CASCADE",

                        "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",

                    "#else",

                        "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",

                    "#endif",

                "#endif",

            "}",

            "#ifdef GAMMA_OUTPUT",

                "shadowColor *= shadowColor;",

            "#endif",

            "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",

        "#endif"

    ].join("\n"),

    shadowmap_pars_vertex: [

        "#ifdef USE_SHADOWMAP",

            "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
            "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",

        "#endif"

    ].join("\n"),

    shadowmap_vertex: [

        "#ifdef USE_SHADOWMAP",

            "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",

                "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",

            "}",

        "#endif"

    ].join("\n"),

    // ALPHATEST

    alphatest_fragment: [

        "#ifdef ALPHATEST",

            "if ( gl_FragColor.a < ALPHATEST ) discard;",

        "#endif"

    ].join("\n"),

    // LINEAR SPACE

    linear_to_gamma_fragment: [

        "#ifdef GAMMA_OUTPUT",

            "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",

        "#endif"

    ].join("\n"),


};

THREE.UniformsUtils = {

    merge: function ( uniforms ) {

        var u, p, tmp, merged = {};

        for ( u = 0; u < uniforms.length; u ++ ) {

            tmp = this.clone( uniforms[ u ] );

            for ( p in tmp ) {

                merged[ p ] = tmp[ p ];

            }

        }

        return merged;

    },

    clone: function ( uniforms_src ) {

        var u, p, parameter, parameter_src, uniforms_dst = {};

        for ( u in uniforms_src ) {

            uniforms_dst[ u ] = {};

            for ( p in uniforms_src[ u ] ) {

                parameter_src = uniforms_src[ u ][ p ];

                if ( parameter_src instanceof THREE.Color ||
                     parameter_src instanceof THREE.Vector2 ||
                     parameter_src instanceof THREE.Vector3 ||
                     parameter_src instanceof THREE.Vector4 ||
                     parameter_src instanceof THREE.Matrix4 ||
                     parameter_src instanceof THREE.Texture ) {

                    uniforms_dst[ u ][ p ] = parameter_src.clone();

                } else if ( parameter_src instanceof Array ) {

                    uniforms_dst[ u ][ p ] = parameter_src.slice();

                } else {

                    uniforms_dst[ u ][ p ] = parameter_src;

                }

            }

        }

        return uniforms_dst;

    }

};

THREE.UniformsLib = {

    common: {

        "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
        "opacity" : { type: "f", value: 1.0 },

        "map" : { type: "t", value: null },
        "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },

        "lightMap" : { type: "t", value: null },
        "specularMap" : { type: "t", value: null },

        "envMap" : { type: "t", value: null },
        "flipEnvMap" : { type: "f", value: -1 },
        "useRefract" : { type: "i", value: 0 },
        "reflectivity" : { type: "f", value: 1.0 },
        "refractionRatio" : { type: "f", value: 0.98 },
        "combine" : { type: "i", value: 0 },

        "morphTargetInfluences" : { type: "f", value: 0 }

    },

    bump: {

        "bumpMap" : { type: "t", value: null },
        "bumpScale" : { type: "f", value: 1 }

    },

    normalmap: {

        "normalMap" : { type: "t", value: null },
        "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
    },

    fog : {

        "fogDensity" : { type: "f", value: 0.00025 },
        "fogNear" : { type: "f", value: 1 },
        "fogFar" : { type: "f", value: 2000 },
        "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }

    },

    lights: {

        "ambientLightColor" : { type: "fv", value: [] },

        "directionalLightDirection" : { type: "fv", value: [] },
        "directionalLightColor" : { type: "fv", value: [] },

        "hemisphereLightPosition" : { type: "fv", value: [] },
        "hemisphereLightSkyColor" : { type: "fv", value: [] },
        "hemisphereLightGroundColor" : { type: "fv", value: [] },

        "pointLightColor" : { type: "fv", value: [] },
        "pointLightPosition" : { type: "fv", value: [] },
        "pointLightDistance" : { type: "fv1", value: [] },

        "spotLightColor" : { type: "fv", value: [] },
        "spotLightPosition" : { type: "fv", value: [] },
        "spotLightDirection" : { type: "fv", value: [] },
        "spotLightDistance" : { type: "fv1", value: [] },
        "spotLightAngle" : { type: "fv1", value: [] },
        "spotLightExponent" : { type: "fv1", value: [] }

    },

    particle: {

        "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
        "opacity" : { type: "f", value: 1.0 },
        "size" : { type: "f", value: 1.0 },
        "scale" : { type: "f", value: 1.0 },
        "map" : { type: "t", value: null },

        "fogDensity" : { type: "f", value: 0.00025 },
        "fogNear" : { type: "f", value: 1 },
        "fogFar" : { type: "f", value: 2000 },
        "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }

    },

    shadowmap: {

        "shadowMap": { type: "tv", value: [] },
        "shadowMapSize": { type: "v2v", value: [] },

        "shadowBias" : { type: "fv1", value: [] },
        "shadowDarkness": { type: "fv1", value: [] },

        "shadowMatrix" : { type: "m4v", value: [] },

    }

};

THREE.ShaderLib = {

    'depth': {

        uniforms: {

            "mNear": { type: "f", value: 1.0 },
            "mFar" : { type: "f", value: 2000.0 },
            "opacity" : { type: "f", value: 1.0 }

        },

        vertexShader: [

            "void main() {",

                "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

            "}"

        ].join("\n"),

        fragmentShader: [

            "uniform float mNear;",
            "uniform float mFar;",
            "uniform float opacity;",

            "void main() {",

                "float depth = gl_FragCoord.z / gl_FragCoord.w;",
                "float color = 1.0 - smoothstep( mNear, mFar, depth );",
                "gl_FragColor = vec4( vec3( color ), opacity );",

            "}"

        ].join("\n")

    },

    'normal': {

        uniforms: {

            "opacity" : { type: "f", value: 1.0 }

        },

        vertexShader: [

            "varying vec3 vNormal;",

            "void main() {",

                "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
                "vNormal = normalMatrix * normal;",

                "gl_Position = projectionMatrix * mvPosition;",

            "}"

        ].join("\n"),

        fragmentShader: [

            "uniform float opacity;",
            "varying vec3 vNormal;",

            "void main() {",

                "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",

            "}"

        ].join("\n")

    },

    'basic': {

        uniforms: THREE.UniformsUtils.merge( [

            THREE.UniformsLib[ "common" ],
            THREE.UniformsLib[ "fog" ],
            THREE.UniformsLib[ "shadowmap" ]

        ] ),

        vertexShader: [

            THREE.ShaderChunk[ "map_pars_vertex" ],
            THREE.ShaderChunk[ "lightmap_pars_vertex" ],
            THREE.ShaderChunk[ "envmap_pars_vertex" ],
            THREE.ShaderChunk[ "color_pars_vertex" ],
            THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
            THREE.ShaderChunk[ "skinning_pars_vertex" ],
            THREE.ShaderChunk[ "shadowmap_pars_vertex" ],

            "void main() {",

                THREE.ShaderChunk[ "map_vertex" ],
                THREE.ShaderChunk[ "lightmap_vertex" ],
                THREE.ShaderChunk[ "color_vertex" ],

                "#ifdef USE_ENVMAP",

                THREE.ShaderChunk[ "morphnormal_vertex" ],
                THREE.ShaderChunk[ "skinbase_vertex" ],
                THREE.ShaderChunk[ "skinnormal_vertex" ],
                THREE.ShaderChunk[ "defaultnormal_vertex" ],

                "#endif",

                THREE.ShaderChunk[ "morphtarget_vertex" ],
                THREE.ShaderChunk[ "skinning_vertex" ],
                THREE.ShaderChunk[ "default_vertex" ],

                THREE.ShaderChunk[ "worldpos_vertex" ],
                THREE.ShaderChunk[ "envmap_vertex" ],
                THREE.ShaderChunk[ "shadowmap_vertex" ],

            "}"

        ].join("\n"),

        fragmentShader: [

            "uniform vec3 diffuse;",
            "uniform float opacity;",

            THREE.ShaderChunk[ "color_pars_fragment" ],
            THREE.ShaderChunk[ "map_pars_fragment" ],
            THREE.ShaderChunk[ "lightmap_pars_fragment" ],
            THREE.ShaderChunk[ "envmap_pars_fragment" ],
            THREE.ShaderChunk[ "fog_pars_fragment" ],
            THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
            THREE.ShaderChunk[ "specularmap_pars_fragment" ],

            "void main() {",

                "gl_FragColor = vec4( diffuse, opacity );",

                THREE.ShaderChunk[ "map_fragment" ],
                THREE.ShaderChunk[ "alphatest_fragment" ],
                THREE.ShaderChunk[ "specularmap_fragment" ],
                THREE.ShaderChunk[ "lightmap_fragment" ],
                THREE.ShaderChunk[ "color_fragment" ],
                THREE.ShaderChunk[ "envmap_fragment" ],
                THREE.ShaderChunk[ "shadowmap_fragment" ],

                THREE.ShaderChunk[ "linear_to_gamma_fragment" ],

                THREE.ShaderChunk[ "fog_fragment" ],

            "}"

        ].join("\n")

    },

    'lambert': {

        uniforms: THREE.UniformsUtils.merge( [

            THREE.UniformsLib[ "common" ],
            THREE.UniformsLib[ "fog" ],
            THREE.UniformsLib[ "lights" ],
            THREE.UniformsLib[ "shadowmap" ],

            {
                "ambient"  : { type: "c", value: new THREE.Color( 0xffffff ) },
                "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
                "wrapRGB"  : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
            }

        ] ),

        vertexShader: [

            "#define LAMBERT",

            "varying vec3 vLightFront;",

            "#ifdef DOUBLE_SIDED",

                "varying vec3 vLightBack;",

            "#endif",

            THREE.ShaderChunk[ "map_pars_vertex" ],
            THREE.ShaderChunk[ "lightmap_pars_vertex" ],
            THREE.ShaderChunk[ "envmap_pars_vertex" ],
            THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
            THREE.ShaderChunk[ "color_pars_vertex" ],
            THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
            THREE.ShaderChunk[ "skinning_pars_vertex" ],
            THREE.ShaderChunk[ "shadowmap_pars_vertex" ],

            "void main() {",

                THREE.ShaderChunk[ "map_vertex" ],
                THREE.ShaderChunk[ "lightmap_vertex" ],
                THREE.ShaderChunk[ "color_vertex" ],

                THREE.ShaderChunk[ "morphnormal_vertex" ],
                THREE.ShaderChunk[ "skinbase_vertex" ],
                THREE.ShaderChunk[ "skinnormal_vertex" ],
                THREE.ShaderChunk[ "defaultnormal_vertex" ],

                THREE.ShaderChunk[ "morphtarget_vertex" ],
                THREE.ShaderChunk[ "skinning_vertex" ],
                THREE.ShaderChunk[ "default_vertex" ],

                THREE.ShaderChunk[ "worldpos_vertex" ],
                THREE.ShaderChunk[ "envmap_vertex" ],
                THREE.ShaderChunk[ "lights_lambert_vertex" ],
                THREE.ShaderChunk[ "shadowmap_vertex" ],

            "}"

        ].join("\n"),

        fragmentShader: [

            "uniform float opacity;",

            "varying vec3 vLightFront;",

            "#ifdef DOUBLE_SIDED",

                "varying vec3 vLightBack;",

            "#endif",

            THREE.ShaderChunk[ "color_pars_fragment" ],
            THREE.ShaderChunk[ "map_pars_fragment" ],
            THREE.ShaderChunk[ "lightmap_pars_fragment" ],
            THREE.ShaderChunk[ "envmap_pars_fragment" ],
            THREE.ShaderChunk[ "fog_pars_fragment" ],
            THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
            THREE.ShaderChunk[ "specularmap_pars_fragment" ],

            "void main() {",

                "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",

                THREE.ShaderChunk[ "map_fragment" ],
                THREE.ShaderChunk[ "alphatest_fragment" ],
                THREE.ShaderChunk[ "specularmap_fragment" ],

                "#ifdef DOUBLE_SIDED",

                    //"float isFront = float( gl_FrontFacing );",
                    //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",

                    "if ( gl_FrontFacing )",
                        "gl_FragColor.xyz *= vLightFront;",
                    "else",
                        "gl_FragColor.xyz *= vLightBack;",

                "#else",

                    "gl_FragColor.xyz *= vLightFront;",

                "#endif",

                THREE.ShaderChunk[ "lightmap_fragment" ],
                THREE.ShaderChunk[ "color_fragment" ],
                THREE.ShaderChunk[ "envmap_fragment" ],
                THREE.ShaderChunk[ "shadowmap_fragment" ],

                THREE.ShaderChunk[ "linear_to_gamma_fragment" ],

                THREE.ShaderChunk[ "fog_fragment" ],

            "}"

        ].join("\n")

    },

    'phong': {

        uniforms: THREE.UniformsUtils.merge( [

            THREE.UniformsLib[ "common" ],
            THREE.UniformsLib[ "bump" ],
            THREE.UniformsLib[ "normalmap" ],
            THREE.UniformsLib[ "fog" ],
            THREE.UniformsLib[ "lights" ],
            THREE.UniformsLib[ "shadowmap" ],

            {
                "ambient"  : { type: "c", value: new THREE.Color( 0xffffff ) },
                "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
                "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
                "shininess": { type: "f", value: 30 },
                "wrapRGB"  : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
            }

        ] ),

        vertexShader: [

            "#define PHONG",

            "varying vec3 vViewPosition;",
            "varying vec3 vNormal;",

            THREE.ShaderChunk[ "map_pars_vertex" ],
            THREE.ShaderChunk[ "lightmap_pars_vertex" ],
            THREE.ShaderChunk[ "envmap_pars_vertex" ],
            THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
            THREE.ShaderChunk[ "color_pars_vertex" ],
            THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
            THREE.ShaderChunk[ "skinning_pars_vertex" ],
            THREE.ShaderChunk[ "shadowmap_pars_vertex" ],

            "void main() {",

                THREE.ShaderChunk[ "map_vertex" ],
                THREE.ShaderChunk[ "lightmap_vertex" ],
                THREE.ShaderChunk[ "color_vertex" ],

                THREE.ShaderChunk[ "morphnormal_vertex" ],
                THREE.ShaderChunk[ "skinbase_vertex" ],
                THREE.ShaderChunk[ "skinnormal_vertex" ],
                THREE.ShaderChunk[ "defaultnormal_vertex" ],

                "vNormal = transformedNormal;",

                THREE.ShaderChunk[ "morphtarget_vertex" ],
                THREE.ShaderChunk[ "skinning_vertex" ],
                THREE.ShaderChunk[ "default_vertex" ],

                "vViewPosition = -mvPosition.xyz;",

                THREE.ShaderChunk[ "worldpos_vertex" ],
                THREE.ShaderChunk[ "envmap_vertex" ],
                THREE.ShaderChunk[ "lights_phong_vertex" ],
                THREE.ShaderChunk[ "shadowmap_vertex" ],

            "}"

        ].join("\n"),

        fragmentShader: [

            "uniform vec3 diffuse;",
            "uniform float opacity;",

            "uniform vec3 ambient;",
            "uniform vec3 emissive;",
            "uniform vec3 specular;",
            "uniform float shininess;",

            THREE.ShaderChunk[ "color_pars_fragment" ],
            THREE.ShaderChunk[ "map_pars_fragment" ],
            THREE.ShaderChunk[ "lightmap_pars_fragment" ],
            THREE.ShaderChunk[ "envmap_pars_fragment" ],
            THREE.ShaderChunk[ "fog_pars_fragment" ],
            THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
            THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
            THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
            THREE.ShaderChunk[ "normalmap_pars_fragment" ],
            THREE.ShaderChunk[ "specularmap_pars_fragment" ],

            "void main() {",

                "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",

                THREE.ShaderChunk[ "map_fragment" ],
                THREE.ShaderChunk[ "alphatest_fragment" ],
                THREE.ShaderChunk[ "specularmap_fragment" ],

                THREE.ShaderChunk[ "lights_phong_fragment" ],

                THREE.ShaderChunk[ "lightmap_fragment" ],
                THREE.ShaderChunk[ "color_fragment" ],
                THREE.ShaderChunk[ "envmap_fragment" ],
                THREE.ShaderChunk[ "shadowmap_fragment" ],

                THREE.ShaderChunk[ "linear_to_gamma_fragment" ],

                THREE.ShaderChunk[ "fog_fragment" ],

            "}"

        ].join("\n")

    },

    'particle_basic': {

        uniforms:  THREE.UniformsUtils.merge( [

            THREE.UniformsLib[ "particle" ],
            THREE.UniformsLib[ "shadowmap" ]

        ] ),

        vertexShader: [

            "uniform float size;",
            "uniform float scale;",

            THREE.ShaderChunk[ "color_pars_vertex" ],
            THREE.ShaderChunk[ "shadowmap_pars_vertex" ],

            "void main() {",

                THREE.ShaderChunk[ "color_vertex" ],

                "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",

                "#ifdef USE_SIZEATTENUATION",
                    "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
                "#else",
                    "gl_PointSize = size;",
                "#endif",

                "gl_Position = projectionMatrix * mvPosition;",

                THREE.ShaderChunk[ "worldpos_vertex" ],
                THREE.ShaderChunk[ "shadowmap_vertex" ],

            "}"

        ].join("\n"),

        fragmentShader: [

            "uniform vec3 psColor;",
            "uniform float opacity;",

            THREE.ShaderChunk[ "color_pars_fragment" ],
            THREE.ShaderChunk[ "map_particle_pars_fragment" ],
            THREE.ShaderChunk[ "fog_pars_fragment" ],
            THREE.ShaderChunk[ "shadowmap_pars_fragment" ],

            "void main() {",

                "gl_FragColor = vec4( psColor, opacity );",

                THREE.ShaderChunk[ "map_particle_fragment" ],
                THREE.ShaderChunk[ "alphatest_fragment" ],
                THREE.ShaderChunk[ "color_fragment" ],
                THREE.ShaderChunk[ "shadowmap_fragment" ],
                THREE.ShaderChunk[ "fog_fragment" ],

            "}"

        ].join("\n")

    },

    // Depth encoding into RGBA texture
    //     based on SpiderGL shadow map example
    //         http://spidergl.org/example.php?id=6
    //     originally from
    //        http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
    //     see also here:
    //        http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/

    'depthRGBA': {

        uniforms: {},

        vertexShader: [

            THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
            THREE.ShaderChunk[ "skinning_pars_vertex" ],

            "void main() {",

                THREE.ShaderChunk[ "skinbase_vertex" ],
                THREE.ShaderChunk[ "morphtarget_vertex" ],
                THREE.ShaderChunk[ "skinning_vertex" ],
                THREE.ShaderChunk[ "default_vertex" ],

            "}"

        ].join("\n"),

        fragmentShader: [

            "vec4 pack_depth( const in float depth ) {",

                "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
                "const vec4 bit_mask  = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
                "vec4 res = fract( depth * bit_shift );",
                "res -= res.xxyz * bit_mask;",
                "return res;",

            "}",

            "void main() {",

                "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",

                //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
                //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
                //"gl_FragData[ 0 ] = pack_depth( z );",
                //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",

            "}"

        ].join("\n")

    }

};
/**
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author szimek / https://github.com/szimek/
 */

THREE.WebGLRenderer = function ( parameters ) {

    console.log( 'THREE.WebGLRenderer', THREE.REVISION );

    parameters = parameters || {};

    var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),

    _precision = parameters.precision !== undefined ? parameters.precision : 'highp',

    _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
    _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
    _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
    _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
    _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,

    _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
    _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,

    _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;

    // public properties

    this.domElement = _canvas;
    this.context = null;

    // clearing

    this.autoClear = true;
    this.autoClearColor = true;
    this.autoClearDepth = true;
    this.autoClearStencil = true;

    // scene graph

    this.sortObjects = true;

    this.autoUpdateObjects = true;
    this.autoUpdateScene = true;

    // physically based shading

    this.gammaInput = false;
    this.gammaOutput = false;
    this.physicallyBasedShading = false;

    // shadow map

    this.shadowMapEnabled = false;
    this.shadowMapAutoUpdate = true;
    this.shadowMapSoft = true;
    this.shadowMapCullFrontFaces = true;
    this.shadowMapDebug = false;
    this.shadowMapCascade = false;

    // morphs

    this.maxMorphTargets = 8;
    this.maxMorphNormals = 4;

    // flags

    this.autoScaleCubemaps = true;

    // custom render plugins

    this.renderPluginsPre = [];
    this.renderPluginsPost = [];

    // info

    this.info = {

        memory: {

            programs: 0,
            geometries: 0,
            textures: 0

        },

        render: {

            calls: 0,
            vertices: 0,
            faces: 0,
            points: 0

        }

    };

    // internal properties

    var _this = this,

    _programs = [],
    _programs_counter = 0,

    // internal state cache

    _currentProgram = null,
    _currentFramebuffer = null,
    _currentMaterialId = -1,
    _currentGeometryGroupHash = null,
    _currentCamera = null,
    _geometryGroupCounter = 0,

    _usedTextureUnits = 0,

    // GL state cache

    _oldDoubleSided = -1,
    _oldFlipSided = -1,

    _oldBlending = -1,

    _oldBlendEquation = -1,
    _oldBlendSrc = -1,
    _oldBlendDst = -1,

    _oldDepthTest = -1,
    _oldDepthWrite = -1,

    _oldPolygonOffset = null,
    _oldPolygonOffsetFactor = null,
    _oldPolygonOffsetUnits = null,

    _oldLineWidth = null,

    _viewportX = 0,
    _viewportY = 0,
    _viewportWidth = 0,
    _viewportHeight = 0,
    _currentWidth = 0,
    _currentHeight = 0,

    // frustum

    _frustum = new THREE.Frustum(),

     // camera matrices cache

    _projScreenMatrix = new THREE.Matrix4(),
    _projScreenMatrixPS = new THREE.Matrix4(),

    _vector3 = new THREE.Vector4(),

    // light arrays cache

    _direction = new THREE.Vector3(),

    _lightsNeedUpdate = true,

    _lights = {

        ambient: [ 0, 0, 0 ],
        directional: { length: 0, colors: new Array(), positions: new Array() },
        point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
        spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), angles: new Array(), exponents: new Array() },
        hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }

    };

    // initialize

    var _gl;

    var _glExtensionTextureFloat;
    var _glExtensionStandardDerivatives;
    var _glExtensionTextureFilterAnisotropic;
    var _glExtensionCompressedTextureS3TC;

    initGL();

    setDefaultGLState();

    this.context = _gl;

    // GPU capabilities

    var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
    var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
    var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
    var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );

    var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;

    var _supportsVertexTextures = ( _maxVertexTextures > 0 );
    var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;

    var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];

    // API

    this.getContext = function () {

        return _gl;

    };

    this.supportsVertexTextures = function () {

        return _supportsVertexTextures;

    };

    this.getMaxAnisotropy  = function () {

        return _maxAnisotropy;

    };

    this.setSize = function ( width, height ) {

        _canvas.width = width;
        _canvas.height = height;

        this.setViewport( 0, 0, _canvas.width, _canvas.height );

    };

    this.setViewport = function ( x, y, width, height ) {

        _viewportX = x !== undefined ? x : 0;
        _viewportY = y !== undefined ? y : 0;

        _viewportWidth = width !== undefined ? width : _canvas.width;
        _viewportHeight = height !== undefined ? height : _canvas.height;

        _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );

    };

    this.setScissor = function ( x, y, width, height ) {

        _gl.scissor( x, y, width, height );

    };

    this.enableScissorTest = function ( enable ) {

        enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );

    };

    // Clearing

    this.setClearColorHex = function ( hex, alpha ) {

        _clearColor.setHex( hex );
        _clearAlpha = alpha;

        _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );

    };

    this.setClearColor = function ( color, alpha ) {

        _clearColor.copy( color );
        _clearAlpha = alpha;

        _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );

    };

    this.getClearColor = function () {

        return _clearColor;

    };

    this.getClearAlpha = function () {

        return _clearAlpha;

    };

    this.clear = function ( color, depth, stencil ) {

        var bits = 0;

        if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
        if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
        if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;

        _gl.clear( bits );

    };

    this.clearTarget = function ( renderTarget, color, depth, stencil ) {

        this.setRenderTarget( renderTarget );
        this.clear( color, depth, stencil );

    };

    // Plugins

    this.addPostPlugin = function ( plugin ) {

        plugin.init( this );
        this.renderPluginsPost.push( plugin );

    };

    this.addPrePlugin = function ( plugin ) {

        plugin.init( this );
        this.renderPluginsPre.push( plugin );

    };

    // Deallocation

    this.deallocateObject = function ( object ) {

        if ( ! object.__webglInit ) return;

        object.__webglInit = false;

        delete object._modelViewMatrix;
        delete object._normalMatrix;

        delete object._normalMatrixArray;
        delete object._modelViewMatrixArray;
        delete object._modelMatrixArray;

        if ( object instanceof THREE.Mesh ) {

            for ( var g in object.geometry.geometryGroups ) {

                deleteMeshBuffers( object.geometry.geometryGroups[ g ] );

            }

        } else if ( object instanceof THREE.Ribbon ) {

            deleteRibbonBuffers( object.geometry );

        } else if ( object instanceof THREE.Line ) {

            deleteLineBuffers( object.geometry );

        } else if ( object instanceof THREE.ParticleSystem ) {

            deleteParticleBuffers( object.geometry );

        }

    };

    this.deallocateTexture = function ( texture ) {

        if ( ! texture.__webglInit ) return;

        texture.__webglInit = false;
        _gl.deleteTexture( texture.__webglTexture );

        _this.info.memory.textures --;

    };

    this.deallocateRenderTarget = function ( renderTarget ) {

        if ( !renderTarget || ! renderTarget.__webglTexture ) return;

        _gl.deleteTexture( renderTarget.__webglTexture );

        if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {

            for ( var i = 0; i < 6; i ++ ) {

                _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
                _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );

            }

        } else {

            _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
            _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );

        }

    };

    this.deallocateMaterial = function ( material ) {

        var program = material.program;

        if ( ! program ) return;

        material.program = undefined;

        // only deallocate GL program if this was the last use of shared program
        // assumed there is only single copy of any program in the _programs list
        // (that's how it's constructed)

        var i, il, programInfo;
        var deleteProgram = false;

        for ( i = 0, il = _programs.length; i < il; i ++ ) {

            programInfo = _programs[ i ];

            if ( programInfo.program === program ) {

                programInfo.usedTimes --;

                if ( programInfo.usedTimes === 0 ) {

                    deleteProgram = true;

                }

                break;

            }

        }

        if ( deleteProgram ) {

            // avoid using array.splice, this is costlier than creating new array from scratch

            var newPrograms = [];

            for ( i = 0, il = _programs.length; i < il; i ++ ) {

                programInfo = _programs[ i ];

                if ( programInfo.program !== program ) {

                    newPrograms.push( programInfo );

                }

            }

            _programs = newPrograms;

            _gl.deleteProgram( program );

            _this.info.memory.programs --;

        }

    };

    // Rendering

    this.updateShadowMap = function ( scene, camera ) {

        _currentProgram = null;
        _oldBlending = -1;
        _oldDepthTest = -1;
        _oldDepthWrite = -1;
        _currentGeometryGroupHash = -1;
        _currentMaterialId = -1;
        _lightsNeedUpdate = true;
        _oldDoubleSided = -1;
        _oldFlipSided = -1;

        this.shadowMapPlugin.update( scene, camera );

    };

    // Internal functions

    // Buffer allocation

    function createParticleBuffers ( geometry ) {

        geometry.__webglVertexBuffer = _gl.createBuffer();
        geometry.__webglColorBuffer = _gl.createBuffer();

        _this.info.memory.geometries ++;

    };

    function createLineBuffers ( geometry ) {

        geometry.__webglVertexBuffer = _gl.createBuffer();
        geometry.__webglColorBuffer = _gl.createBuffer();

        _this.info.memory.geometries ++;

    };

    function createRibbonBuffers ( geometry ) {

        geometry.__webglVertexBuffer = _gl.createBuffer();
        geometry.__webglColorBuffer = _gl.createBuffer();

        _this.info.memory.geometries ++;

    };

    function createMeshBuffers ( geometryGroup ) {

        geometryGroup.__webglVertexBuffer = _gl.createBuffer();
        geometryGroup.__webglNormalBuffer = _gl.createBuffer();
        geometryGroup.__webglTangentBuffer = _gl.createBuffer();
        geometryGroup.__webglColorBuffer = _gl.createBuffer();
        geometryGroup.__webglUVBuffer = _gl.createBuffer();
        geometryGroup.__webglUV2Buffer = _gl.createBuffer();

        geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
        geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();

        geometryGroup.__webglFaceBuffer = _gl.createBuffer();
        geometryGroup.__webglLineBuffer = _gl.createBuffer();

        var m, ml;

        if ( geometryGroup.numMorphTargets ) {

            geometryGroup.__webglMorphTargetsBuffers = [];

            for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {

                geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );

            }

        }

        if ( geometryGroup.numMorphNormals ) {

            geometryGroup.__webglMorphNormalsBuffers = [];

            for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {

                geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );

            }

        }

        _this.info.memory.geometries ++;

    };

    // Buffer deallocation

    function deleteParticleBuffers ( geometry ) {

        _gl.deleteBuffer( geometry.__webglVertexBuffer );
        _gl.deleteBuffer( geometry.__webglColorBuffer );

        _this.info.memory.geometries --;

    };

    function deleteLineBuffers ( geometry ) {

        _gl.deleteBuffer( geometry.__webglVertexBuffer );
        _gl.deleteBuffer( geometry.__webglColorBuffer );

        _this.info.memory.geometries --;

    };

    function deleteRibbonBuffers ( geometry ) {

        _gl.deleteBuffer( geometry.__webglVertexBuffer );
        _gl.deleteBuffer( geometry.__webglColorBuffer );

        _this.info.memory.geometries --;

    };

    function deleteMeshBuffers ( geometryGroup ) {

        _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
        _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
        _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
        _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
        _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
        _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );

        _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
        _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );

        _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
        _gl.deleteBuffer( geometryGroup.__webglLineBuffer );

        var m, ml;

        if ( geometryGroup.numMorphTargets ) {

            for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {

                _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );

            }

        }

        if ( geometryGroup.numMorphNormals ) {

            for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {

                _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );

            }

        }


        if ( geometryGroup.__webglCustomAttributesList ) {

            for ( var id in geometryGroup.__webglCustomAttributesList ) {

                _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );

            }

        }

        _this.info.memory.geometries --;

    };

    // Buffer initialization

    function initCustomAttributes ( geometry, object ) {

        var nvertices = geometry.vertices.length;

        var material = object.material;

        if ( material.attributes ) {

            if ( geometry.__webglCustomAttributesList === undefined ) {

                geometry.__webglCustomAttributesList = [];

            }

            for ( var a in material.attributes ) {

                var attribute = material.attributes[ a ];

                if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {

                    attribute.__webglInitialized = true;

                    var size = 1;        // "f" and "i"

                    if ( attribute.type === "v2" ) size = 2;
                    else if ( attribute.type === "v3" ) size = 3;
                    else if ( attribute.type === "v4" ) size = 4;
                    else if ( attribute.type === "c"  ) size = 3;

                    attribute.size = size;

                    attribute.array = new Float32Array( nvertices * size );

                    attribute.buffer = _gl.createBuffer();
                    attribute.buffer.belongsToAttribute = a;

                    attribute.needsUpdate = true;

                }

                geometry.__webglCustomAttributesList.push( attribute );

            }

        }

    };

    function initParticleBuffers ( geometry, object ) {

        var nvertices = geometry.vertices.length;

        geometry.__vertexArray = new Float32Array( nvertices * 3 );
        geometry.__colorArray = new Float32Array( nvertices * 3 );

        geometry.__sortArray = [];

        geometry.__webglParticleCount = nvertices;

        initCustomAttributes ( geometry, object );

    };

    function initLineBuffers ( geometry, object ) {

        var nvertices = geometry.vertices.length;

        geometry.__vertexArray = new Float32Array( nvertices * 3 );
        geometry.__colorArray = new Float32Array( nvertices * 3 );

        geometry.__webglLineCount = nvertices;

        initCustomAttributes ( geometry, object );

    };

    function initRibbonBuffers ( geometry ) {

        var nvertices = geometry.vertices.length;

        geometry.__vertexArray = new Float32Array( nvertices * 3 );
        geometry.__colorArray = new Float32Array( nvertices * 3 );

        geometry.__webglVertexCount = nvertices;

    };

    function initMeshBuffers ( geometryGroup, object ) {

        var geometry = object.geometry,
            faces3 = geometryGroup.faces3,
            faces4 = geometryGroup.faces4,

            nvertices = faces3.length * 3 + faces4.length * 4,
            ntris     = faces3.length * 1 + faces4.length * 2,
            nlines    = faces3.length * 3 + faces4.length * 4,

            material = getBufferMaterial( object, geometryGroup ),

            uvType = bufferGuessUVType( material ),
            normalType = bufferGuessNormalType( material ),
            vertexColorType = bufferGuessVertexColorType( material );

        //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );

        geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );

        if ( normalType ) {

            geometryGroup.__normalArray = new Float32Array( nvertices * 3 );

        }

        if ( geometry.hasTangents ) {

            geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );

        }

        if ( vertexColorType ) {

            geometryGroup.__colorArray = new Float32Array( nvertices * 3 );

        }

        if ( uvType ) {

            if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {

                geometryGroup.__uvArray = new Float32Array( nvertices * 2 );

            }

            if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {

                geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );

            }

        }

        if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {

            geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
            geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );

        }

        geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
        geometryGroup.__lineArray = new Uint16Array( nlines * 2 );

        var m, ml;

        if ( geometryGroup.numMorphTargets ) {

            geometryGroup.__morphTargetsArrays = [];

            for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {

                geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );

            }

        }

        if ( geometryGroup.numMorphNormals ) {

            geometryGroup.__morphNormalsArrays = [];

            for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {

                geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );

            }

        }

        geometryGroup.__webglFaceCount = ntris * 3;
        geometryGroup.__webglLineCount = nlines * 2;


        // custom attributes

        if ( material.attributes ) {

            if ( geometryGroup.__webglCustomAttributesList === undefined ) {

                geometryGroup.__webglCustomAttributesList = [];

            }

            for ( var a in material.attributes ) {

                // Do a shallow copy of the attribute object so different geometryGroup chunks use different
                // attribute buffers which are correctly indexed in the setMeshBuffers function

                var originalAttribute = material.attributes[ a ];

                var attribute = {};

                for ( var property in originalAttribute ) {

                    attribute[ property ] = originalAttribute[ property ];

                }

                if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {

                    attribute.__webglInitialized = true;

                    var size = 1;        // "f" and "i"

                    if( attribute.type === "v2" ) size = 2;
                    else if( attribute.type === "v3" ) size = 3;
                    else if( attribute.type === "v4" ) size = 4;
                    else if( attribute.type === "c"  ) size = 3;

                    attribute.size = size;

                    attribute.array = new Float32Array( nvertices * size );

                    attribute.buffer = _gl.createBuffer();
                    attribute.buffer.belongsToAttribute = a;

                    originalAttribute.needsUpdate = true;
                    attribute.__original = originalAttribute;

                }

                geometryGroup.__webglCustomAttributesList.push( attribute );

            }

        }

        geometryGroup.__inittedArrays = true;

    };

    function getBufferMaterial( object, geometryGroup ) {

        if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {

            return object.material;

        } else if ( geometryGroup.materialIndex >= 0 ) {

            return object.geometry.materials[ geometryGroup.materialIndex ];

        }

    };

    function materialNeedsSmoothNormals ( material ) {

        return material && material.shading !== undefined && material.shading === THREE.SmoothShading;

    };

    function bufferGuessNormalType ( material ) {

        // only MeshBasicMaterial and MeshDepthMaterial don't need normals

        if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {

            return false;

        }

        if ( materialNeedsSmoothNormals( material ) ) {

            return THREE.SmoothShading;

        } else {

            return THREE.FlatShading;

        }

    };

    function bufferGuessVertexColorType ( material ) {

        if ( material.vertexColors ) {

            return material.vertexColors;

        }

        return false;

    };

    function bufferGuessUVType ( material ) {

        // material must use some texture to require uvs

        if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {

            return true;

        }

        return false;

    };

    //

    function initDirectBuffers( geometry ) {

        var a, attribute, type;

        for ( a in geometry.attributes ) {

            if ( a === "index" ) {

                type = _gl.ELEMENT_ARRAY_BUFFER;

            } else {

                type = _gl.ARRAY_BUFFER;

            }

            attribute = geometry.attributes[ a ];

            attribute.buffer = _gl.createBuffer();

            _gl.bindBuffer( type, attribute.buffer );
            _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );

        }

    };

    // Buffer setting

    function setParticleBuffers ( geometry, hint, object ) {

        var v, c, vertex, offset, index, color,

        vertices = geometry.vertices,
        vl = vertices.length,

        colors = geometry.colors,
        cl = colors.length,

        vertexArray = geometry.__vertexArray,
        colorArray = geometry.__colorArray,

        sortArray = geometry.__sortArray,

        dirtyVertices = geometry.verticesNeedUpdate,
        dirtyElements = geometry.elementsNeedUpdate,
        dirtyColors = geometry.colorsNeedUpdate,

        customAttributes = geometry.__webglCustomAttributesList,
        i, il,
        a, ca, cal, value,
        customAttribute;

        if ( object.sortParticles ) {

            _projScreenMatrixPS.copy( _projScreenMatrix );
            _projScreenMatrixPS.multiplySelf( object.matrixWorld );

            for ( v = 0; v < vl; v ++ ) {

                vertex = vertices[ v ];

                _vector3.copy( vertex );
                _projScreenMatrixPS.multiplyVector3( _vector3 );

                sortArray[ v ] = [ _vector3.z, v ];

            }

            sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );

            for ( v = 0; v < vl; v ++ ) {

                vertex = vertices[ sortArray[v][1] ];

                offset = v * 3;

                vertexArray[ offset ]     = vertex.x;
                vertexArray[ offset + 1 ] = vertex.y;
                vertexArray[ offset + 2 ] = vertex.z;

            }

            for ( c = 0; c < cl; c ++ ) {

                offset = c * 3;

                color = colors[ sortArray[c][1] ];

                colorArray[ offset ]     = color.r;
                colorArray[ offset + 1 ] = color.g;
                colorArray[ offset + 2 ] = color.b;

            }

            if ( customAttributes ) {

                for ( i = 0, il = customAttributes.length; i < il; i ++ ) {

                    customAttribute = customAttributes[ i ];

                    if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;

                    offset = 0;

                    cal = customAttribute.value.length;

                    if ( customAttribute.size === 1 ) {

                        for ( ca = 0; ca < cal; ca ++ ) {

                            index = sortArray[ ca ][ 1 ];

                            customAttribute.array[ ca ] = customAttribute.value[ index ];

                        }

                    } else if ( customAttribute.size === 2 ) {

                        for ( ca = 0; ca < cal; ca ++ ) {

                            index = sortArray[ ca ][ 1 ];

                            value = customAttribute.value[ index ];

                            customAttribute.array[ offset ]     = value.x;
                            customAttribute.array[ offset + 1 ] = value.y;

                            offset += 2;

                        }

                    } else if ( customAttribute.size === 3 ) {

                        if ( customAttribute.type === "c" ) {

                            for ( ca = 0; ca < cal; ca ++ ) {

                                index = sortArray[ ca ][ 1 ];

                                value = customAttribute.value[ index ];

                                customAttribute.array[ offset ]     = value.r;
                                customAttribute.array[ offset + 1 ] = value.g;
                                customAttribute.array[ offset + 2 ] = value.b;

                                offset += 3;

                            }

                        } else {

                            for ( ca = 0; ca < cal; ca ++ ) {

                                index = sortArray[ ca ][ 1 ];

                                value = customAttribute.value[ index ];

                                customAttribute.array[ offset ]     = value.x;
                                customAttribute.array[ offset + 1 ] = value.y;
                                customAttribute.array[ offset + 2 ] = value.z;

                                offset += 3;

                            }

                        }

                    } else if ( customAttribute.size === 4 ) {

                        for ( ca = 0; ca < cal; ca ++ ) {

                            index = sortArray[ ca ][ 1 ];

                            value = customAttribute.value[ index ];

                            customAttribute.array[ offset ]      = value.x;
                            customAttribute.array[ offset + 1  ] = value.y;
                            customAttribute.array[ offset + 2  ] = value.z;
                            customAttribute.array[ offset + 3  ] = value.w;

                            offset += 4;

                        }

                    }

                }

            }

        } else {

            if ( dirtyVertices ) {

                for ( v = 0; v < vl; v ++ ) {

                    vertex = vertices[ v ];

                    offset = v * 3;

                    vertexArray[ offset ]     = vertex.x;
                    vertexArray[ offset + 1 ] = vertex.y;
                    vertexArray[ offset + 2 ] = vertex.z;

                }

            }

            if ( dirtyColors ) {

                for ( c = 0; c < cl; c ++ ) {

                    color = colors[ c ];

                    offset = c * 3;

                    colorArray[ offset ]     = color.r;
                    colorArray[ offset + 1 ] = color.g;
                    colorArray[ offset + 2 ] = color.b;

                }

            }

            if ( customAttributes ) {

                for ( i = 0, il = customAttributes.length; i < il; i ++ ) {

                    customAttribute = customAttributes[ i ];

                    if ( customAttribute.needsUpdate &&
                         ( customAttribute.boundTo === undefined ||
                           customAttribute.boundTo === "vertices") ) {

                        cal = customAttribute.value.length;

                        offset = 0;

                        if ( customAttribute.size === 1 ) {

                            for ( ca = 0; ca < cal; ca ++ ) {

                                customAttribute.array[ ca ] = customAttribute.value[ ca ];

                            }

                        } else if ( customAttribute.size === 2 ) {

                            for ( ca = 0; ca < cal; ca ++ ) {

                                value = customAttribute.value[ ca ];

                                customAttribute.array[ offset ]     = value.x;
                                customAttribute.array[ offset + 1 ] = value.y;

                                offset += 2;

                            }

                        } else if ( customAttribute.size === 3 ) {

                            if ( customAttribute.type === "c" ) {

                                for ( ca = 0; ca < cal; ca ++ ) {

                                    value = customAttribute.value[ ca ];

                                    customAttribute.array[ offset ]     = value.r;
                                    customAttribute.array[ offset + 1 ] = value.g;
                                    customAttribute.array[ offset + 2 ] = value.b;

                                    offset += 3;

                                }

                            } else {

                                for ( ca = 0; ca < cal; ca ++ ) {

                                    value = customAttribute.value[ ca ];

                                    customAttribute.array[ offset ]     = value.x;
                                    customAttribute.array[ offset + 1 ] = value.y;
                                    customAttribute.array[ offset + 2 ] = value.z;

                                    offset += 3;

                                }

                            }

                        } else if ( customAttribute.size === 4 ) {

                            for ( ca = 0; ca < cal; ca ++ ) {

                                value = customAttribute.value[ ca ];

                                customAttribute.array[ offset ]      = value.x;
                                customAttribute.array[ offset + 1  ] = value.y;
                                customAttribute.array[ offset + 2  ] = value.z;
                                customAttribute.array[ offset + 3  ] = value.w;

                                offset += 4;

                            }

                        }

                    }

                }

            }

        }

        if ( dirtyVertices || object.sortParticles ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );

        }

        if ( dirtyColors || object.sortParticles ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );

        }

        if ( customAttributes ) {

            for ( i = 0, il = customAttributes.length; i < il; i ++ ) {

                customAttribute = customAttributes[ i ];

                if ( customAttribute.needsUpdate || object.sortParticles ) {

                    _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
                    _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );

                }

            }

        }


    };

    function setLineBuffers ( geometry, hint ) {

        var v, c, vertex, offset, color,

        vertices = geometry.vertices,
        colors = geometry.colors,
        vl = vertices.length,
        cl = colors.length,

        vertexArray = geometry.__vertexArray,
        colorArray = geometry.__colorArray,

        dirtyVertices = geometry.verticesNeedUpdate,
        dirtyColors = geometry.colorsNeedUpdate,

        customAttributes = geometry.__webglCustomAttributesList,

        i, il,
        a, ca, cal, value,
        customAttribute;

        if ( dirtyVertices ) {

            for ( v = 0; v < vl; v ++ ) {

                vertex = vertices[ v ];

                offset = v * 3;

                vertexArray[ offset ]     = vertex.x;
                vertexArray[ offset + 1 ] = vertex.y;
                vertexArray[ offset + 2 ] = vertex.z;

            }

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );

        }

        if ( dirtyColors ) {

            for ( c = 0; c < cl; c ++ ) {

                color = colors[ c ];

                offset = c * 3;

                colorArray[ offset ]     = color.r;
                colorArray[ offset + 1 ] = color.g;
                colorArray[ offset + 2 ] = color.b;

            }

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );

        }

        if ( customAttributes ) {

            for ( i = 0, il = customAttributes.length; i < il; i ++ ) {

                customAttribute = customAttributes[ i ];

                if ( customAttribute.needsUpdate &&
                     ( customAttribute.boundTo === undefined ||
                       customAttribute.boundTo === "vertices" ) ) {

                    offset = 0;

                    cal = customAttribute.value.length;

                    if ( customAttribute.size === 1 ) {

                        for ( ca = 0; ca < cal; ca ++ ) {

                            customAttribute.array[ ca ] = customAttribute.value[ ca ];

                        }

                    } else if ( customAttribute.size === 2 ) {

                        for ( ca = 0; ca < cal; ca ++ ) {

                            value = customAttribute.value[ ca ];

                            customAttribute.array[ offset ]     = value.x;
                            customAttribute.array[ offset + 1 ] = value.y;

                            offset += 2;

                        }

                    } else if ( customAttribute.size === 3 ) {

                        if ( customAttribute.type === "c" ) {

                            for ( ca = 0; ca < cal; ca ++ ) {

                                value = customAttribute.value[ ca ];

                                customAttribute.array[ offset ]     = value.r;
                                customAttribute.array[ offset + 1 ] = value.g;
                                customAttribute.array[ offset + 2 ] = value.b;

                                offset += 3;

                            }

                        } else {

                            for ( ca = 0; ca < cal; ca ++ ) {

                                value = customAttribute.value[ ca ];

                                customAttribute.array[ offset ]     = value.x;
                                customAttribute.array[ offset + 1 ] = value.y;
                                customAttribute.array[ offset + 2 ] = value.z;

                                offset += 3;

                            }

                        }

                    } else if ( customAttribute.size === 4 ) {

                        for ( ca = 0; ca < cal; ca ++ ) {

                            value = customAttribute.value[ ca ];

                            customAttribute.array[ offset ]      = value.x;
                            customAttribute.array[ offset + 1  ] = value.y;
                            customAttribute.array[ offset + 2  ] = value.z;
                            customAttribute.array[ offset + 3  ] = value.w;

                            offset += 4;

                        }

                    }

                    _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
                    _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );

                }

            }

        }

    };

    function setRibbonBuffers ( geometry, hint ) {

        var v, c, vertex, offset, color,

        vertices = geometry.vertices,
        colors = geometry.colors,
        vl = vertices.length,
        cl = colors.length,

        vertexArray = geometry.__vertexArray,
        colorArray = geometry.__colorArray,

        dirtyVertices = geometry.verticesNeedUpdate,
        dirtyColors = geometry.colorsNeedUpdate;

        if ( dirtyVertices ) {

            for ( v = 0; v < vl; v ++ ) {

                vertex = vertices[ v ];

                offset = v * 3;

                vertexArray[ offset ]     = vertex.x;
                vertexArray[ offset + 1 ] = vertex.y;
                vertexArray[ offset + 2 ] = vertex.z;

            }

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );

        }

        if ( dirtyColors ) {

            for ( c = 0; c < cl; c ++ ) {

                color = colors[ c ];

                offset = c * 3;

                colorArray[ offset ]     = color.r;
                colorArray[ offset + 1 ] = color.g;
                colorArray[ offset + 2 ] = color.b;

            }

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );

        }

    };

    function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {

        if ( ! geometryGroup.__inittedArrays ) {

            // console.log( object );
            return;

        }

        var normalType = bufferGuessNormalType( material ),
        vertexColorType = bufferGuessVertexColorType( material ),
        uvType = bufferGuessUVType( material ),

        needsSmoothNormals = ( normalType === THREE.SmoothShading );

        var f, fl, fi, face,
        vertexNormals, faceNormal, normal,
        vertexColors, faceColor,
        vertexTangents,
        uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
        c1, c2, c3, c4,
        sw1, sw2, sw3, sw4,
        si1, si2, si3, si4,
        sa1, sa2, sa3, sa4,
        sb1, sb2, sb3, sb4,
        m, ml, i, il,
        vn, uvi, uv2i,
        vk, vkl, vka,
        nka, chf, faceVertexNormals,
        a,

        vertexIndex = 0,

        offset = 0,
        offset_uv = 0,
        offset_uv2 = 0,
        offset_face = 0,
        offset_normal = 0,
        offset_tangent = 0,
        offset_line = 0,
        offset_color = 0,
        offset_skin = 0,
        offset_morphTarget = 0,
        offset_custom = 0,
        offset_customSrc = 0,

        value,

        vertexArray = geometryGroup.__vertexArray,
        uvArray = geometryGroup.__uvArray,
        uv2Array = geometryGroup.__uv2Array,
        normalArray = geometryGroup.__normalArray,
        tangentArray = geometryGroup.__tangentArray,
        colorArray = geometryGroup.__colorArray,

        skinIndexArray = geometryGroup.__skinIndexArray,
        skinWeightArray = geometryGroup.__skinWeightArray,

        morphTargetsArrays = geometryGroup.__morphTargetsArrays,
        morphNormalsArrays = geometryGroup.__morphNormalsArrays,

        customAttributes = geometryGroup.__webglCustomAttributesList,
        customAttribute,

        faceArray = geometryGroup.__faceArray,
        lineArray = geometryGroup.__lineArray,

        geometry = object.geometry, // this is shared for all chunks

        dirtyVertices = geometry.verticesNeedUpdate,
        dirtyElements = geometry.elementsNeedUpdate,
        dirtyUvs = geometry.uvsNeedUpdate,
        dirtyNormals = geometry.normalsNeedUpdate,
        dirtyTangents = geometry.tangentsNeedUpdate,
        dirtyColors = geometry.colorsNeedUpdate,
        dirtyMorphTargets = geometry.morphTargetsNeedUpdate,

        vertices = geometry.vertices,
        chunk_faces3 = geometryGroup.faces3,
        chunk_faces4 = geometryGroup.faces4,
        obj_faces = geometry.faces,

        obj_uvs  = geometry.faceVertexUvs[ 0 ],
        obj_uvs2 = geometry.faceVertexUvs[ 1 ],

        obj_colors = geometry.colors,

        obj_skinIndices = geometry.skinIndices,
        obj_skinWeights = geometry.skinWeights,

        morphTargets = geometry.morphTargets,
        morphNormals = geometry.morphNormals;

        if ( dirtyVertices ) {

            for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces3[ f ] ];

                v1 = vertices[ face.a ];
                v2 = vertices[ face.b ];
                v3 = vertices[ face.c ];

                vertexArray[ offset ]     = v1.x;
                vertexArray[ offset + 1 ] = v1.y;
                vertexArray[ offset + 2 ] = v1.z;

                vertexArray[ offset + 3 ] = v2.x;
                vertexArray[ offset + 4 ] = v2.y;
                vertexArray[ offset + 5 ] = v2.z;

                vertexArray[ offset + 6 ] = v3.x;
                vertexArray[ offset + 7 ] = v3.y;
                vertexArray[ offset + 8 ] = v3.z;

                offset += 9;

            }

            for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces4[ f ] ];

                v1 = vertices[ face.a ];
                v2 = vertices[ face.b ];
                v3 = vertices[ face.c ];
                v4 = vertices[ face.d ];

                vertexArray[ offset ]     = v1.x;
                vertexArray[ offset + 1 ] = v1.y;
                vertexArray[ offset + 2 ] = v1.z;

                vertexArray[ offset + 3 ] = v2.x;
                vertexArray[ offset + 4 ] = v2.y;
                vertexArray[ offset + 5 ] = v2.z;

                vertexArray[ offset + 6 ] = v3.x;
                vertexArray[ offset + 7 ] = v3.y;
                vertexArray[ offset + 8 ] = v3.z;

                vertexArray[ offset + 9 ]  = v4.x;
                vertexArray[ offset + 10 ] = v4.y;
                vertexArray[ offset + 11 ] = v4.z;

                offset += 12;

            }

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );

        }

        if ( dirtyMorphTargets ) {

            for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {

                offset_morphTarget = 0;

                for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                    chf = chunk_faces3[ f ];
                    face = obj_faces[ chf ];

                    // morph positions

                    v1 = morphTargets[ vk ].vertices[ face.a ];
                    v2 = morphTargets[ vk ].vertices[ face.b ];
                    v3 = morphTargets[ vk ].vertices[ face.c ];

                    vka = morphTargetsArrays[ vk ];

                    vka[ offset_morphTarget ]       = v1.x;
                    vka[ offset_morphTarget + 1 ] = v1.y;
                    vka[ offset_morphTarget + 2 ] = v1.z;

                    vka[ offset_morphTarget + 3 ] = v2.x;
                    vka[ offset_morphTarget + 4 ] = v2.y;
                    vka[ offset_morphTarget + 5 ] = v2.z;

                    vka[ offset_morphTarget + 6 ] = v3.x;
                    vka[ offset_morphTarget + 7 ] = v3.y;
                    vka[ offset_morphTarget + 8 ] = v3.z;

                    // morph normals

                    if ( material.morphNormals ) {

                        if ( needsSmoothNormals ) {

                            faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];

                            n1 = faceVertexNormals.a;
                            n2 = faceVertexNormals.b;
                            n3 = faceVertexNormals.c;

                        } else {

                            n1 = morphNormals[ vk ].faceNormals[ chf ];
                            n2 = n1;
                            n3 = n1;

                        }

                        nka = morphNormalsArrays[ vk ];

                        nka[ offset_morphTarget ]       = n1.x;
                        nka[ offset_morphTarget + 1 ] = n1.y;
                        nka[ offset_morphTarget + 2 ] = n1.z;

                        nka[ offset_morphTarget + 3 ] = n2.x;
                        nka[ offset_morphTarget + 4 ] = n2.y;
                        nka[ offset_morphTarget + 5 ] = n2.z;

                        nka[ offset_morphTarget + 6 ] = n3.x;
                        nka[ offset_morphTarget + 7 ] = n3.y;
                        nka[ offset_morphTarget + 8 ] = n3.z;

                    }

                    //

                    offset_morphTarget += 9;

                }

                for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                    chf = chunk_faces4[ f ];
                    face = obj_faces[ chf ];

                    // morph positions

                    v1 = morphTargets[ vk ].vertices[ face.a ];
                    v2 = morphTargets[ vk ].vertices[ face.b ];
                    v3 = morphTargets[ vk ].vertices[ face.c ];
                    v4 = morphTargets[ vk ].vertices[ face.d ];

                    vka = morphTargetsArrays[ vk ];

                    vka[ offset_morphTarget ]       = v1.x;
                    vka[ offset_morphTarget + 1 ] = v1.y;
                    vka[ offset_morphTarget + 2 ] = v1.z;

                    vka[ offset_morphTarget + 3 ] = v2.x;
                    vka[ offset_morphTarget + 4 ] = v2.y;
                    vka[ offset_morphTarget + 5 ] = v2.z;

                    vka[ offset_morphTarget + 6 ] = v3.x;
                    vka[ offset_morphTarget + 7 ] = v3.y;
                    vka[ offset_morphTarget + 8 ] = v3.z;

                    vka[ offset_morphTarget + 9 ]  = v4.x;
                    vka[ offset_morphTarget + 10 ] = v4.y;
                    vka[ offset_morphTarget + 11 ] = v4.z;

                    // morph normals

                    if ( material.morphNormals ) {

                        if ( needsSmoothNormals ) {

                            faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];

                            n1 = faceVertexNormals.a;
                            n2 = faceVertexNormals.b;
                            n3 = faceVertexNormals.c;
                            n4 = faceVertexNormals.d;

                        } else {

                            n1 = morphNormals[ vk ].faceNormals[ chf ];
                            n2 = n1;
                            n3 = n1;
                            n4 = n1;

                        }

                        nka = morphNormalsArrays[ vk ];

                        nka[ offset_morphTarget ]       = n1.x;
                        nka[ offset_morphTarget + 1 ] = n1.y;
                        nka[ offset_morphTarget + 2 ] = n1.z;

                        nka[ offset_morphTarget + 3 ] = n2.x;
                        nka[ offset_morphTarget + 4 ] = n2.y;
                        nka[ offset_morphTarget + 5 ] = n2.z;

                        nka[ offset_morphTarget + 6 ] = n3.x;
                        nka[ offset_morphTarget + 7 ] = n3.y;
                        nka[ offset_morphTarget + 8 ] = n3.z;

                        nka[ offset_morphTarget + 9 ]  = n4.x;
                        nka[ offset_morphTarget + 10 ] = n4.y;
                        nka[ offset_morphTarget + 11 ] = n4.z;

                    }

                    //

                    offset_morphTarget += 12;

                }

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
                _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );

                if ( material.morphNormals ) {

                    _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
                    _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );

                }

            }

        }

        if ( obj_skinWeights.length ) {

            for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces3[ f ]    ];

                // weights

                sw1 = obj_skinWeights[ face.a ];
                sw2 = obj_skinWeights[ face.b ];
                sw3 = obj_skinWeights[ face.c ];

                skinWeightArray[ offset_skin ]     = sw1.x;
                skinWeightArray[ offset_skin + 1 ] = sw1.y;
                skinWeightArray[ offset_skin + 2 ] = sw1.z;
                skinWeightArray[ offset_skin + 3 ] = sw1.w;

                skinWeightArray[ offset_skin + 4 ] = sw2.x;
                skinWeightArray[ offset_skin + 5 ] = sw2.y;
                skinWeightArray[ offset_skin + 6 ] = sw2.z;
                skinWeightArray[ offset_skin + 7 ] = sw2.w;

                skinWeightArray[ offset_skin + 8 ]  = sw3.x;
                skinWeightArray[ offset_skin + 9 ]  = sw3.y;
                skinWeightArray[ offset_skin + 10 ] = sw3.z;
                skinWeightArray[ offset_skin + 11 ] = sw3.w;

                // indices

                si1 = obj_skinIndices[ face.a ];
                si2 = obj_skinIndices[ face.b ];
                si3 = obj_skinIndices[ face.c ];

                skinIndexArray[ offset_skin ]     = si1.x;
                skinIndexArray[ offset_skin + 1 ] = si1.y;
                skinIndexArray[ offset_skin + 2 ] = si1.z;
                skinIndexArray[ offset_skin + 3 ] = si1.w;

                skinIndexArray[ offset_skin + 4 ] = si2.x;
                skinIndexArray[ offset_skin + 5 ] = si2.y;
                skinIndexArray[ offset_skin + 6 ] = si2.z;
                skinIndexArray[ offset_skin + 7 ] = si2.w;

                skinIndexArray[ offset_skin + 8 ]  = si3.x;
                skinIndexArray[ offset_skin + 9 ]  = si3.y;
                skinIndexArray[ offset_skin + 10 ] = si3.z;
                skinIndexArray[ offset_skin + 11 ] = si3.w;

                offset_skin += 12;

            }

            for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces4[ f ] ];

                // weights

                sw1 = obj_skinWeights[ face.a ];
                sw2 = obj_skinWeights[ face.b ];
                sw3 = obj_skinWeights[ face.c ];
                sw4 = obj_skinWeights[ face.d ];

                skinWeightArray[ offset_skin ]     = sw1.x;
                skinWeightArray[ offset_skin + 1 ] = sw1.y;
                skinWeightArray[ offset_skin + 2 ] = sw1.z;
                skinWeightArray[ offset_skin + 3 ] = sw1.w;

                skinWeightArray[ offset_skin + 4 ] = sw2.x;
                skinWeightArray[ offset_skin + 5 ] = sw2.y;
                skinWeightArray[ offset_skin + 6 ] = sw2.z;
                skinWeightArray[ offset_skin + 7 ] = sw2.w;

                skinWeightArray[ offset_skin + 8 ]  = sw3.x;
                skinWeightArray[ offset_skin + 9 ]  = sw3.y;
                skinWeightArray[ offset_skin + 10 ] = sw3.z;
                skinWeightArray[ offset_skin + 11 ] = sw3.w;

                skinWeightArray[ offset_skin + 12 ] = sw4.x;
                skinWeightArray[ offset_skin + 13 ] = sw4.y;
                skinWeightArray[ offset_skin + 14 ] = sw4.z;
                skinWeightArray[ offset_skin + 15 ] = sw4.w;

                // indices

                si1 = obj_skinIndices[ face.a ];
                si2 = obj_skinIndices[ face.b ];
                si3 = obj_skinIndices[ face.c ];
                si4 = obj_skinIndices[ face.d ];

                skinIndexArray[ offset_skin ]     = si1.x;
                skinIndexArray[ offset_skin + 1 ] = si1.y;
                skinIndexArray[ offset_skin + 2 ] = si1.z;
                skinIndexArray[ offset_skin + 3 ] = si1.w;

                skinIndexArray[ offset_skin + 4 ] = si2.x;
                skinIndexArray[ offset_skin + 5 ] = si2.y;
                skinIndexArray[ offset_skin + 6 ] = si2.z;
                skinIndexArray[ offset_skin + 7 ] = si2.w;

                skinIndexArray[ offset_skin + 8 ]  = si3.x;
                skinIndexArray[ offset_skin + 9 ]  = si3.y;
                skinIndexArray[ offset_skin + 10 ] = si3.z;
                skinIndexArray[ offset_skin + 11 ] = si3.w;

                skinIndexArray[ offset_skin + 12 ] = si4.x;
                skinIndexArray[ offset_skin + 13 ] = si4.y;
                skinIndexArray[ offset_skin + 14 ] = si4.z;
                skinIndexArray[ offset_skin + 15 ] = si4.w;

                offset_skin += 16;

            }

            if ( offset_skin > 0 ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
                _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
                _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );

            }

        }

        if ( dirtyColors && vertexColorType ) {

            for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces3[ f ]    ];

                vertexColors = face.vertexColors;
                faceColor = face.color;

                if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {

                    c1 = vertexColors[ 0 ];
                    c2 = vertexColors[ 1 ];
                    c3 = vertexColors[ 2 ];

                } else {

                    c1 = faceColor;
                    c2 = faceColor;
                    c3 = faceColor;

                }

                colorArray[ offset_color ]     = c1.r;
                colorArray[ offset_color + 1 ] = c1.g;
                colorArray[ offset_color + 2 ] = c1.b;

                colorArray[ offset_color + 3 ] = c2.r;
                colorArray[ offset_color + 4 ] = c2.g;
                colorArray[ offset_color + 5 ] = c2.b;

                colorArray[ offset_color + 6 ] = c3.r;
                colorArray[ offset_color + 7 ] = c3.g;
                colorArray[ offset_color + 8 ] = c3.b;

                offset_color += 9;

            }

            for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces4[ f ] ];

                vertexColors = face.vertexColors;
                faceColor = face.color;

                if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {

                    c1 = vertexColors[ 0 ];
                    c2 = vertexColors[ 1 ];
                    c3 = vertexColors[ 2 ];
                    c4 = vertexColors[ 3 ];

                } else {

                    c1 = faceColor;
                    c2 = faceColor;
                    c3 = faceColor;
                    c4 = faceColor;

                }

                colorArray[ offset_color ]     = c1.r;
                colorArray[ offset_color + 1 ] = c1.g;
                colorArray[ offset_color + 2 ] = c1.b;

                colorArray[ offset_color + 3 ] = c2.r;
                colorArray[ offset_color + 4 ] = c2.g;
                colorArray[ offset_color + 5 ] = c2.b;

                colorArray[ offset_color + 6 ] = c3.r;
                colorArray[ offset_color + 7 ] = c3.g;
                colorArray[ offset_color + 8 ] = c3.b;

                colorArray[ offset_color + 9 ]  = c4.r;
                colorArray[ offset_color + 10 ] = c4.g;
                colorArray[ offset_color + 11 ] = c4.b;

                offset_color += 12;

            }

            if ( offset_color > 0 ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
                _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );

            }

        }

        if ( dirtyTangents && geometry.hasTangents ) {

            for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces3[ f ]    ];

                vertexTangents = face.vertexTangents;

                t1 = vertexTangents[ 0 ];
                t2 = vertexTangents[ 1 ];
                t3 = vertexTangents[ 2 ];

                tangentArray[ offset_tangent ]     = t1.x;
                tangentArray[ offset_tangent + 1 ] = t1.y;
                tangentArray[ offset_tangent + 2 ] = t1.z;
                tangentArray[ offset_tangent + 3 ] = t1.w;

                tangentArray[ offset_tangent + 4 ] = t2.x;
                tangentArray[ offset_tangent + 5 ] = t2.y;
                tangentArray[ offset_tangent + 6 ] = t2.z;
                tangentArray[ offset_tangent + 7 ] = t2.w;

                tangentArray[ offset_tangent + 8 ]  = t3.x;
                tangentArray[ offset_tangent + 9 ]  = t3.y;
                tangentArray[ offset_tangent + 10 ] = t3.z;
                tangentArray[ offset_tangent + 11 ] = t3.w;

                offset_tangent += 12;

            }

            for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces4[ f ] ];

                vertexTangents = face.vertexTangents;

                t1 = vertexTangents[ 0 ];
                t2 = vertexTangents[ 1 ];
                t3 = vertexTangents[ 2 ];
                t4 = vertexTangents[ 3 ];

                tangentArray[ offset_tangent ]     = t1.x;
                tangentArray[ offset_tangent + 1 ] = t1.y;
                tangentArray[ offset_tangent + 2 ] = t1.z;
                tangentArray[ offset_tangent + 3 ] = t1.w;

                tangentArray[ offset_tangent + 4 ] = t2.x;
                tangentArray[ offset_tangent + 5 ] = t2.y;
                tangentArray[ offset_tangent + 6 ] = t2.z;
                tangentArray[ offset_tangent + 7 ] = t2.w;

                tangentArray[ offset_tangent + 8 ]  = t3.x;
                tangentArray[ offset_tangent + 9 ]  = t3.y;
                tangentArray[ offset_tangent + 10 ] = t3.z;
                tangentArray[ offset_tangent + 11 ] = t3.w;

                tangentArray[ offset_tangent + 12 ] = t4.x;
                tangentArray[ offset_tangent + 13 ] = t4.y;
                tangentArray[ offset_tangent + 14 ] = t4.z;
                tangentArray[ offset_tangent + 15 ] = t4.w;

                offset_tangent += 16;

            }

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );

        }

        if ( dirtyNormals && normalType ) {

            for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces3[ f ]    ];

                vertexNormals = face.vertexNormals;
                faceNormal = face.normal;

                if ( vertexNormals.length === 3 && needsSmoothNormals ) {

                    for ( i = 0; i < 3; i ++ ) {

                        vn = vertexNormals[ i ];

                        normalArray[ offset_normal ]     = vn.x;
                        normalArray[ offset_normal + 1 ] = vn.y;
                        normalArray[ offset_normal + 2 ] = vn.z;

                        offset_normal += 3;

                    }

                } else {

                    for ( i = 0; i < 3; i ++ ) {

                        normalArray[ offset_normal ]     = faceNormal.x;
                        normalArray[ offset_normal + 1 ] = faceNormal.y;
                        normalArray[ offset_normal + 2 ] = faceNormal.z;

                        offset_normal += 3;

                    }

                }

            }

            for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces4[ f ] ];

                vertexNormals = face.vertexNormals;
                faceNormal = face.normal;

                if ( vertexNormals.length === 4 && needsSmoothNormals ) {

                    for ( i = 0; i < 4; i ++ ) {

                        vn = vertexNormals[ i ];

                        normalArray[ offset_normal ]     = vn.x;
                        normalArray[ offset_normal + 1 ] = vn.y;
                        normalArray[ offset_normal + 2 ] = vn.z;

                        offset_normal += 3;

                    }

                } else {

                    for ( i = 0; i < 4; i ++ ) {

                        normalArray[ offset_normal ]     = faceNormal.x;
                        normalArray[ offset_normal + 1 ] = faceNormal.y;
                        normalArray[ offset_normal + 2 ] = faceNormal.z;

                        offset_normal += 3;

                    }

                }

            }

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );

        }

        if ( dirtyUvs && obj_uvs && uvType ) {

            for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                fi = chunk_faces3[ f ];

                face = obj_faces[ fi ];
                uv = obj_uvs[ fi ];

                if ( uv === undefined ) continue;

                for ( i = 0; i < 3; i ++ ) {

                    uvi = uv[ i ];

                    uvArray[ offset_uv ]     = uvi.u;
                    uvArray[ offset_uv + 1 ] = uvi.v;

                    offset_uv += 2;

                }

            }

            for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                fi = chunk_faces4[ f ];

                face = obj_faces[ fi ];
                uv = obj_uvs[ fi ];

                if ( uv === undefined ) continue;

                for ( i = 0; i < 4; i ++ ) {

                    uvi = uv[ i ];

                    uvArray[ offset_uv ]     = uvi.u;
                    uvArray[ offset_uv + 1 ] = uvi.v;

                    offset_uv += 2;

                }

            }

            if ( offset_uv > 0 ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
                _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );

            }

        }

        if ( dirtyUvs && obj_uvs2 && uvType ) {

            for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                fi = chunk_faces3[ f ];

                face = obj_faces[ fi ];
                uv2 = obj_uvs2[ fi ];

                if ( uv2 === undefined ) continue;

                for ( i = 0; i < 3; i ++ ) {

                    uv2i = uv2[ i ];

                    uv2Array[ offset_uv2 ]     = uv2i.u;
                    uv2Array[ offset_uv2 + 1 ] = uv2i.v;

                    offset_uv2 += 2;

                }

            }

            for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                fi = chunk_faces4[ f ];

                face = obj_faces[ fi ];
                uv2 = obj_uvs2[ fi ];

                if ( uv2 === undefined ) continue;

                for ( i = 0; i < 4; i ++ ) {

                    uv2i = uv2[ i ];

                    uv2Array[ offset_uv2 ]     = uv2i.u;
                    uv2Array[ offset_uv2 + 1 ] = uv2i.v;

                    offset_uv2 += 2;

                }

            }

            if ( offset_uv2 > 0 ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
                _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );

            }

        }

        if ( dirtyElements ) {

            for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces3[ f ]    ];

                faceArray[ offset_face ]      = vertexIndex;
                faceArray[ offset_face + 1 ] = vertexIndex + 1;
                faceArray[ offset_face + 2 ] = vertexIndex + 2;

                offset_face += 3;

                lineArray[ offset_line ]     = vertexIndex;
                lineArray[ offset_line + 1 ] = vertexIndex + 1;

                lineArray[ offset_line + 2 ] = vertexIndex;
                lineArray[ offset_line + 3 ] = vertexIndex + 2;

                lineArray[ offset_line + 4 ] = vertexIndex + 1;
                lineArray[ offset_line + 5 ] = vertexIndex + 2;

                offset_line += 6;

                vertexIndex += 3;

            }

            for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                face = obj_faces[ chunk_faces4[ f ] ];

                faceArray[ offset_face ]     = vertexIndex;
                faceArray[ offset_face + 1 ] = vertexIndex + 1;
                faceArray[ offset_face + 2 ] = vertexIndex + 3;

                faceArray[ offset_face + 3 ] = vertexIndex + 1;
                faceArray[ offset_face + 4 ] = vertexIndex + 2;
                faceArray[ offset_face + 5 ] = vertexIndex + 3;

                offset_face += 6;

                lineArray[ offset_line ]     = vertexIndex;
                lineArray[ offset_line + 1 ] = vertexIndex + 1;

                lineArray[ offset_line + 2 ] = vertexIndex;
                lineArray[ offset_line + 3 ] = vertexIndex + 3;

                lineArray[ offset_line + 4 ] = vertexIndex + 1;
                lineArray[ offset_line + 5 ] = vertexIndex + 2;

                lineArray[ offset_line + 6 ] = vertexIndex + 2;
                lineArray[ offset_line + 7 ] = vertexIndex + 3;

                offset_line += 8;

                vertexIndex += 4;

            }

            _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
            _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );

            _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
            _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );

        }

        if ( customAttributes ) {

            for ( i = 0, il = customAttributes.length; i < il; i ++ ) {

                customAttribute = customAttributes[ i ];

                if ( ! customAttribute.__original.needsUpdate ) continue;

                offset_custom = 0;
                offset_customSrc = 0;

                if ( customAttribute.size === 1 ) {

                    if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            face = obj_faces[ chunk_faces3[ f ]    ];

                            customAttribute.array[ offset_custom ]        = customAttribute.value[ face.a ];
                            customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
                            customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];

                            offset_custom += 3;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            face = obj_faces[ chunk_faces4[ f ] ];

                            customAttribute.array[ offset_custom ]        = customAttribute.value[ face.a ];
                            customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
                            customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
                            customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];

                            offset_custom += 4;

                        }

                    } else if ( customAttribute.boundTo === "faces" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces3[ f ] ];

                            customAttribute.array[ offset_custom ]        = value;
                            customAttribute.array[ offset_custom + 1 ] = value;
                            customAttribute.array[ offset_custom + 2 ] = value;

                            offset_custom += 3;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces4[ f ] ];

                            customAttribute.array[ offset_custom ]        = value;
                            customAttribute.array[ offset_custom + 1 ] = value;
                            customAttribute.array[ offset_custom + 2 ] = value;
                            customAttribute.array[ offset_custom + 3 ] = value;

                            offset_custom += 4;

                        }

                    }

                } else if ( customAttribute.size === 2 ) {

                    if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            face = obj_faces[ chunk_faces3[ f ]    ];

                            v1 = customAttribute.value[ face.a ];
                            v2 = customAttribute.value[ face.b ];
                            v3 = customAttribute.value[ face.c ];

                            customAttribute.array[ offset_custom ]        = v1.x;
                            customAttribute.array[ offset_custom + 1 ] = v1.y;

                            customAttribute.array[ offset_custom + 2 ] = v2.x;
                            customAttribute.array[ offset_custom + 3 ] = v2.y;

                            customAttribute.array[ offset_custom + 4 ] = v3.x;
                            customAttribute.array[ offset_custom + 5 ] = v3.y;

                            offset_custom += 6;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            face = obj_faces[ chunk_faces4[ f ] ];

                            v1 = customAttribute.value[ face.a ];
                            v2 = customAttribute.value[ face.b ];
                            v3 = customAttribute.value[ face.c ];
                            v4 = customAttribute.value[ face.d ];

                            customAttribute.array[ offset_custom ]        = v1.x;
                            customAttribute.array[ offset_custom + 1 ] = v1.y;

                            customAttribute.array[ offset_custom + 2 ] = v2.x;
                            customAttribute.array[ offset_custom + 3 ] = v2.y;

                            customAttribute.array[ offset_custom + 4 ] = v3.x;
                            customAttribute.array[ offset_custom + 5 ] = v3.y;

                            customAttribute.array[ offset_custom + 6 ] = v4.x;
                            customAttribute.array[ offset_custom + 7 ] = v4.y;

                            offset_custom += 8;

                        }

                    } else if ( customAttribute.boundTo === "faces" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces3[ f ] ];

                            v1 = value;
                            v2 = value;
                            v3 = value;

                            customAttribute.array[ offset_custom ]        = v1.x;
                            customAttribute.array[ offset_custom + 1 ] = v1.y;

                            customAttribute.array[ offset_custom + 2 ] = v2.x;
                            customAttribute.array[ offset_custom + 3 ] = v2.y;

                            customAttribute.array[ offset_custom + 4 ] = v3.x;
                            customAttribute.array[ offset_custom + 5 ] = v3.y;

                            offset_custom += 6;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces4[ f ] ];

                            v1 = value;
                            v2 = value;
                            v3 = value;
                            v4 = value;

                            customAttribute.array[ offset_custom ]        = v1.x;
                            customAttribute.array[ offset_custom + 1 ] = v1.y;

                            customAttribute.array[ offset_custom + 2 ] = v2.x;
                            customAttribute.array[ offset_custom + 3 ] = v2.y;

                            customAttribute.array[ offset_custom + 4 ] = v3.x;
                            customAttribute.array[ offset_custom + 5 ] = v3.y;

                            customAttribute.array[ offset_custom + 6 ] = v4.x;
                            customAttribute.array[ offset_custom + 7 ] = v4.y;

                            offset_custom += 8;

                        }

                    }

                } else if ( customAttribute.size === 3 ) {

                    var pp;

                    if ( customAttribute.type === "c" ) {

                        pp = [ "r", "g", "b" ];

                    } else {

                        pp = [ "x", "y", "z" ];

                    }

                    if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            face = obj_faces[ chunk_faces3[ f ]    ];

                            v1 = customAttribute.value[ face.a ];
                            v2 = customAttribute.value[ face.b ];
                            v3 = customAttribute.value[ face.c ];

                            customAttribute.array[ offset_custom ]        = v1[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];

                            offset_custom += 9;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            face = obj_faces[ chunk_faces4[ f ] ];

                            v1 = customAttribute.value[ face.a ];
                            v2 = customAttribute.value[ face.b ];
                            v3 = customAttribute.value[ face.c ];
                            v4 = customAttribute.value[ face.d ];

                            customAttribute.array[ offset_custom  ]     = v1[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 1  ] = v1[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 2  ] = v1[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 3  ] = v2[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 4  ] = v2[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 5  ] = v2[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 6  ] = v3[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 7  ] = v3[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 8  ] = v3[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 9  ] = v4[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];

                            offset_custom += 12;

                        }

                    } else if ( customAttribute.boundTo === "faces" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces3[ f ] ];

                            v1 = value;
                            v2 = value;
                            v3 = value;

                            customAttribute.array[ offset_custom ]        = v1[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];

                            offset_custom += 9;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces4[ f ] ];

                            v1 = value;
                            v2 = value;
                            v3 = value;
                            v4 = value;

                            customAttribute.array[ offset_custom  ]     = v1[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 1  ] = v1[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 2  ] = v1[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 3  ] = v2[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 4  ] = v2[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 5  ] = v2[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 6  ] = v3[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 7  ] = v3[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 8  ] = v3[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 9  ] = v4[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];

                            offset_custom += 12;

                        }

                    } else if ( customAttribute.boundTo === "faceVertices" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces3[ f ] ];

                            v1 = value[ 0 ];
                            v2 = value[ 1 ];
                            v3 = value[ 2 ];

                            customAttribute.array[ offset_custom ]        = v1[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];

                            offset_custom += 9;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces4[ f ] ];

                            v1 = value[ 0 ];
                            v2 = value[ 1 ];
                            v3 = value[ 2 ];
                            v4 = value[ 3 ];

                            customAttribute.array[ offset_custom  ]     = v1[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 1  ] = v1[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 2  ] = v1[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 3  ] = v2[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 4  ] = v2[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 5  ] = v2[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 6  ] = v3[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 7  ] = v3[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 8  ] = v3[ pp[ 2 ] ];

                            customAttribute.array[ offset_custom + 9  ] = v4[ pp[ 0 ] ];
                            customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
                            customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];

                            offset_custom += 12;

                        }

                    }

                } else if ( customAttribute.size === 4 ) {

                    if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            face = obj_faces[ chunk_faces3[ f ]    ];

                            v1 = customAttribute.value[ face.a ];
                            v2 = customAttribute.value[ face.b ];
                            v3 = customAttribute.value[ face.c ];

                            customAttribute.array[ offset_custom  ]     = v1.x;
                            customAttribute.array[ offset_custom + 1  ] = v1.y;
                            customAttribute.array[ offset_custom + 2  ] = v1.z;
                            customAttribute.array[ offset_custom + 3  ] = v1.w;

                            customAttribute.array[ offset_custom + 4  ] = v2.x;
                            customAttribute.array[ offset_custom + 5  ] = v2.y;
                            customAttribute.array[ offset_custom + 6  ] = v2.z;
                            customAttribute.array[ offset_custom + 7  ] = v2.w;

                            customAttribute.array[ offset_custom + 8  ] = v3.x;
                            customAttribute.array[ offset_custom + 9  ] = v3.y;
                            customAttribute.array[ offset_custom + 10 ] = v3.z;
                            customAttribute.array[ offset_custom + 11 ] = v3.w;

                            offset_custom += 12;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            face = obj_faces[ chunk_faces4[ f ] ];

                            v1 = customAttribute.value[ face.a ];
                            v2 = customAttribute.value[ face.b ];
                            v3 = customAttribute.value[ face.c ];
                            v4 = customAttribute.value[ face.d ];

                            customAttribute.array[ offset_custom  ]     = v1.x;
                            customAttribute.array[ offset_custom + 1  ] = v1.y;
                            customAttribute.array[ offset_custom + 2  ] = v1.z;
                            customAttribute.array[ offset_custom + 3  ] = v1.w;

                            customAttribute.array[ offset_custom + 4  ] = v2.x;
                            customAttribute.array[ offset_custom + 5  ] = v2.y;
                            customAttribute.array[ offset_custom + 6  ] = v2.z;
                            customAttribute.array[ offset_custom + 7  ] = v2.w;

                            customAttribute.array[ offset_custom + 8  ] = v3.x;
                            customAttribute.array[ offset_custom + 9  ] = v3.y;
                            customAttribute.array[ offset_custom + 10 ] = v3.z;
                            customAttribute.array[ offset_custom + 11 ] = v3.w;

                            customAttribute.array[ offset_custom + 12 ] = v4.x;
                            customAttribute.array[ offset_custom + 13 ] = v4.y;
                            customAttribute.array[ offset_custom + 14 ] = v4.z;
                            customAttribute.array[ offset_custom + 15 ] = v4.w;

                            offset_custom += 16;

                        }

                    } else if ( customAttribute.boundTo === "faces" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces3[ f ] ];

                            v1 = value;
                            v2 = value;
                            v3 = value;

                            customAttribute.array[ offset_custom  ]     = v1.x;
                            customAttribute.array[ offset_custom + 1  ] = v1.y;
                            customAttribute.array[ offset_custom + 2  ] = v1.z;
                            customAttribute.array[ offset_custom + 3  ] = v1.w;

                            customAttribute.array[ offset_custom + 4  ] = v2.x;
                            customAttribute.array[ offset_custom + 5  ] = v2.y;
                            customAttribute.array[ offset_custom + 6  ] = v2.z;
                            customAttribute.array[ offset_custom + 7  ] = v2.w;

                            customAttribute.array[ offset_custom + 8  ] = v3.x;
                            customAttribute.array[ offset_custom + 9  ] = v3.y;
                            customAttribute.array[ offset_custom + 10 ] = v3.z;
                            customAttribute.array[ offset_custom + 11 ] = v3.w;

                            offset_custom += 12;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces4[ f ] ];

                            v1 = value;
                            v2 = value;
                            v3 = value;
                            v4 = value;

                            customAttribute.array[ offset_custom  ]     = v1.x;
                            customAttribute.array[ offset_custom + 1  ] = v1.y;
                            customAttribute.array[ offset_custom + 2  ] = v1.z;
                            customAttribute.array[ offset_custom + 3  ] = v1.w;

                            customAttribute.array[ offset_custom + 4  ] = v2.x;
                            customAttribute.array[ offset_custom + 5  ] = v2.y;
                            customAttribute.array[ offset_custom + 6  ] = v2.z;
                            customAttribute.array[ offset_custom + 7  ] = v2.w;

                            customAttribute.array[ offset_custom + 8  ] = v3.x;
                            customAttribute.array[ offset_custom + 9  ] = v3.y;
                            customAttribute.array[ offset_custom + 10 ] = v3.z;
                            customAttribute.array[ offset_custom + 11 ] = v3.w;

                            customAttribute.array[ offset_custom + 12 ] = v4.x;
                            customAttribute.array[ offset_custom + 13 ] = v4.y;
                            customAttribute.array[ offset_custom + 14 ] = v4.z;
                            customAttribute.array[ offset_custom + 15 ] = v4.w;

                            offset_custom += 16;

                        }

                    } else if ( customAttribute.boundTo === "faceVertices" ) {

                        for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces3[ f ] ];

                            v1 = value[ 0 ];
                            v2 = value[ 1 ];
                            v3 = value[ 2 ];

                            customAttribute.array[ offset_custom  ]     = v1.x;
                            customAttribute.array[ offset_custom + 1  ] = v1.y;
                            customAttribute.array[ offset_custom + 2  ] = v1.z;
                            customAttribute.array[ offset_custom + 3  ] = v1.w;

                            customAttribute.array[ offset_custom + 4  ] = v2.x;
                            customAttribute.array[ offset_custom + 5  ] = v2.y;
                            customAttribute.array[ offset_custom + 6  ] = v2.z;
                            customAttribute.array[ offset_custom + 7  ] = v2.w;

                            customAttribute.array[ offset_custom + 8  ] = v3.x;
                            customAttribute.array[ offset_custom + 9  ] = v3.y;
                            customAttribute.array[ offset_custom + 10 ] = v3.z;
                            customAttribute.array[ offset_custom + 11 ] = v3.w;

                            offset_custom += 12;

                        }

                        for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {

                            value = customAttribute.value[ chunk_faces4[ f ] ];

                            v1 = value[ 0 ];
                            v2 = value[ 1 ];
                            v3 = value[ 2 ];
                            v4 = value[ 3 ];

                            customAttribute.array[ offset_custom  ]     = v1.x;
                            customAttribute.array[ offset_custom + 1  ] = v1.y;
                            customAttribute.array[ offset_custom + 2  ] = v1.z;
                            customAttribute.array[ offset_custom + 3  ] = v1.w;

                            customAttribute.array[ offset_custom + 4  ] = v2.x;
                            customAttribute.array[ offset_custom + 5  ] = v2.y;
                            customAttribute.array[ offset_custom + 6  ] = v2.z;
                            customAttribute.array[ offset_custom + 7  ] = v2.w;

                            customAttribute.array[ offset_custom + 8  ] = v3.x;
                            customAttribute.array[ offset_custom + 9  ] = v3.y;
                            customAttribute.array[ offset_custom + 10 ] = v3.z;
                            customAttribute.array[ offset_custom + 11 ] = v3.w;

                            customAttribute.array[ offset_custom + 12 ] = v4.x;
                            customAttribute.array[ offset_custom + 13 ] = v4.y;
                            customAttribute.array[ offset_custom + 14 ] = v4.z;
                            customAttribute.array[ offset_custom + 15 ] = v4.w;

                            offset_custom += 16;

                        }

                    }

                }

                _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
                _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );

            }

        }

        if ( dispose ) {

            delete geometryGroup.__inittedArrays;
            delete geometryGroup.__colorArray;
            delete geometryGroup.__normalArray;
            delete geometryGroup.__tangentArray;
            delete geometryGroup.__uvArray;
            delete geometryGroup.__uv2Array;
            delete geometryGroup.__faceArray;
            delete geometryGroup.__vertexArray;
            delete geometryGroup.__lineArray;
            delete geometryGroup.__skinIndexArray;
            delete geometryGroup.__skinWeightArray;

        }

    };

    function setDirectBuffers ( geometry, hint, dispose ) {

        var attributes = geometry.attributes;

        var index = attributes[ "index" ];
        var position = attributes[ "position" ];
        var normal = attributes[ "normal" ];
        var uv = attributes[ "uv" ];
        var color = attributes[ "color" ];
        var tangent = attributes[ "tangent" ];

        if ( geometry.elementsNeedUpdate && index !== undefined ) {

            _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
            _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );

        }

        if ( geometry.verticesNeedUpdate && position !== undefined ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );

        }

        if ( geometry.normalsNeedUpdate && normal !== undefined ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );

        }

        if ( geometry.uvsNeedUpdate && uv !== undefined ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );

        }

        if ( geometry.colorsNeedUpdate && color !== undefined ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );

        }

        if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );

        }

        if ( dispose ) {

            for ( var i in geometry.attributes ) {

                delete geometry.attributes[ i ].array;

            }

        }

    };

    // Buffer rendering

    this.renderBufferImmediate = function ( object, program, material ) {

        if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
        if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
        if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
        if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();

        if ( object.hasPositions ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
            _gl.enableVertexAttribArray( program.attributes.position );
            _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );

        }

        if ( object.hasNormals ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );

            if ( material.shading === THREE.FlatShading ) {

                var nx, ny, nz,
                    nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
                    normalArray,
                    i, il = object.count * 3;

                for( i = 0; i < il; i += 9 ) {

                    normalArray = object.normalArray;

                    nax  = normalArray[ i ];
                    nay  = normalArray[ i + 1 ];
                    naz  = normalArray[ i + 2 ];

                    nbx  = normalArray[ i + 3 ];
                    nby  = normalArray[ i + 4 ];
                    nbz  = normalArray[ i + 5 ];

                    ncx  = normalArray[ i + 6 ];
                    ncy  = normalArray[ i + 7 ];
                    ncz  = normalArray[ i + 8 ];

                    nx = ( nax + nbx + ncx ) / 3;
                    ny = ( nay + nby + ncy ) / 3;
                    nz = ( naz + nbz + ncz ) / 3;

                    normalArray[ i ]      = nx;
                    normalArray[ i + 1 ] = ny;
                    normalArray[ i + 2 ] = nz;

                    normalArray[ i + 3 ] = nx;
                    normalArray[ i + 4 ] = ny;
                    normalArray[ i + 5 ] = nz;

                    normalArray[ i + 6 ] = nx;
                    normalArray[ i + 7 ] = ny;
                    normalArray[ i + 8 ] = nz;

                }

            }

            _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
            _gl.enableVertexAttribArray( program.attributes.normal );
            _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );

        }

        if ( object.hasUvs && material.map ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
            _gl.enableVertexAttribArray( program.attributes.uv );
            _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );

        }

        if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
            _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
            _gl.enableVertexAttribArray( program.attributes.color );
            _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );

        }

        _gl.drawArrays( _gl.TRIANGLES, 0, object.count );

        object.count = 0;

    };

    this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {

        if ( material.visible === false ) return;

        var program, attributes, linewidth, primitives, a, attribute;

        program = setProgram( camera, lights, fog, material, object );

        attributes = program.attributes;

        var updateBuffers = false,
            wireframeBit = material.wireframe ? 1 : 0,
            geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;

        if ( geometryHash !== _currentGeometryGroupHash ) {

            _currentGeometryGroupHash = geometryHash;
            updateBuffers = true;

        }

        // render mesh

        if ( object instanceof THREE.Mesh ) {

            var offsets = geometry.offsets;

            // if there is more than 1 chunk
            // must set attribute pointers to use new offsets for each chunk
            // even if geometry and materials didn't change

            if ( offsets.length > 1 ) updateBuffers = true;

            for ( var i = 0, il = offsets.length; i < il; ++ i ) {

                var startIndex = offsets[ i ].index;

                if ( updateBuffers ) {

                    // vertices

                    var position = geometry.attributes[ "position" ];
                    var positionSize = position.itemSize;

                    _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
                    _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32

                    // normals

                    var normal = geometry.attributes[ "normal" ];

                    if ( attributes.normal >= 0 && normal ) {

                        var normalSize = normal.itemSize;

                        _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
                        _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );

                    }

                    // uvs

                    var uv = geometry.attributes[ "uv" ];

                    if ( attributes.uv >= 0 && uv ) {

                        if ( uv.buffer ) {

                            var uvSize = uv.itemSize;

                            _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
                            _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );

                            _gl.enableVertexAttribArray( attributes.uv );

                        } else {

                            _gl.disableVertexAttribArray( attributes.uv );

                        }

                    }

                    // colors

                    var color = geometry.attributes[ "color" ];

                    if ( attributes.color >= 0 && color ) {

                        var colorSize = color.itemSize;

                        _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
                        _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );

                    }

                    // tangents

                    var tangent = geometry.attributes[ "tangent" ];

                    if ( attributes.tangent >= 0 && tangent ) {

                        var tangentSize = tangent.itemSize;

                        _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
                        _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );

                    }

                    // indices

                    var index = geometry.attributes[ "index" ];

                    _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );

                }

                // render indexed triangles

                _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16

                _this.info.render.calls ++;
                _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
                _this.info.render.faces += offsets[ i ].count / 3;

            }

        // render particles

        } else if ( object instanceof THREE.ParticleSystem ) {

            if ( updateBuffers ) {

                // vertices

                var position = geometry.attributes[ "position" ];
                var positionSize = position.itemSize;

                _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
                _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );

                // colors

                var color = geometry.attributes[ "color" ];

                if ( attributes.color >= 0 && color ) {

                    var colorSize = color.itemSize;

                    _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
                    _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );

                }

                // render particles

                _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );

                _this.info.render.calls ++;
                _this.info.render.points += position.numItems / 3;

            }

        }

    };

    this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {

        if ( material.visible === false ) return;

        var program, attributes, linewidth, primitives, a, attribute, i, il;

        program = setProgram( camera, lights, fog, material, object );

        attributes = program.attributes;

        var updateBuffers = false,
            wireframeBit = material.wireframe ? 1 : 0,
            geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;

        if ( geometryGroupHash !== _currentGeometryGroupHash ) {

            _currentGeometryGroupHash = geometryGroupHash;
            updateBuffers = true;

        }

        // vertices

        if ( !material.morphTargets && attributes.position >= 0 ) {

            if ( updateBuffers ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
                _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );

            }

        } else {

            if ( object.morphTargetBase ) {

                setupMorphTargets( material, geometryGroup, object );

            }

        }


        if ( updateBuffers ) {

            // custom attributes

            // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers

            if ( geometryGroup.__webglCustomAttributesList ) {

                for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {

                    attribute = geometryGroup.__webglCustomAttributesList[ i ];

                    if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {

                        _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
                        _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );

                    }

                }

            }


            // colors

            if ( attributes.color >= 0 ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
                _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );

            }

            // normals

            if ( attributes.normal >= 0 ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
                _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );

            }

            // tangents

            if ( attributes.tangent >= 0 ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
                _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );

            }

            // uvs

            if ( attributes.uv >= 0 ) {

                if ( geometryGroup.__webglUVBuffer ) {

                    _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
                    _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );

                    _gl.enableVertexAttribArray( attributes.uv );

                } else {

                    _gl.disableVertexAttribArray( attributes.uv );

                }

            }

            if ( attributes.uv2 >= 0 ) {

                if ( geometryGroup.__webglUV2Buffer ) {

                    _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
                    _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );

                    _gl.enableVertexAttribArray( attributes.uv2 );

                } else {

                    _gl.disableVertexAttribArray( attributes.uv2 );

                }

            }

            if ( material.skinning &&
                 attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
                _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
                _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );

            }

        }

        // render mesh

        if ( object instanceof THREE.Mesh ) {

            // wireframe

            if ( material.wireframe ) {

                setLineWidth( material.wireframeLinewidth );

                if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
                _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );

            // triangles

            } else {

                if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
                _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );

            }

            _this.info.render.calls ++;
            _this.info.render.vertices += geometryGroup.__webglFaceCount;
            _this.info.render.faces += geometryGroup.__webglFaceCount / 3;

        // render lines

        } else if ( object instanceof THREE.Line ) {

            primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;

            setLineWidth( material.linewidth );

            _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );

            _this.info.render.calls ++;

        // render particles

        } else if ( object instanceof THREE.ParticleSystem ) {

            _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );

            _this.info.render.calls ++;
            _this.info.render.points += geometryGroup.__webglParticleCount;

        // render ribbon

        } else if ( object instanceof THREE.Ribbon ) {

            _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );

            _this.info.render.calls ++;

        }

    };

    function setupMorphTargets ( material, geometryGroup, object ) {

        // set base

        var attributes = material.program.attributes;

        if ( object.morphTargetBase !== -1 ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
            _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );

        } else if ( attributes.position >= 0 ) {

            _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
            _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );

        }

        if ( object.morphTargetForcedOrder.length ) {

            // set forced order

            var m = 0;
            var order = object.morphTargetForcedOrder;
            var influences = object.morphTargetInfluences;

            while ( m < material.numSupportedMorphTargets && m < order.length ) {

                _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
                _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );

                if ( material.morphNormals ) {

                    _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
                    _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );

                }

                object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];

                m ++;
            }

        } else {

            // find the most influencing

            var influence, activeInfluenceIndices = [];
            var influences = object.morphTargetInfluences;
            var i, il = influences.length;

            for ( i = 0; i < il; i ++ ) {

                influence = influences[ i ];

                if ( influence > 0 ) {

                    activeInfluenceIndices.push( [ i, influence ] );

                }

            }

            if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {

                activeInfluenceIndices.sort( numericalSort );
                activeInfluenceIndices.length = material.numSupportedMorphTargets;

            } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {

                activeInfluenceIndices.sort( numericalSort );

            } else if ( activeInfluenceIndices.length === 0 ) {

                activeInfluenceIndices.push( [ 0, 0 ] );

            };

            var influenceIndex, m = 0;

            while ( m < material.numSupportedMorphTargets ) {

                if ( activeInfluenceIndices[ m ] ) {

                    influenceIndex = activeInfluenceIndices[ m ][ 0 ];

                    _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );

                    _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );

                    if ( material.morphNormals ) {

                        _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
                        _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );

                    }

                    object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];

                } else {

                    _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );

                    if ( material.morphNormals ) {

                        _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );

                    }

                    object.__webglMorphTargetInfluences[ m ] = 0;

                }

                m ++;

            }

        }

        // load updated influences uniform

        if ( material.program.uniforms.morphTargetInfluences !== null ) {

            _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );

        }

    };

    // Sorting

    function painterSort ( a, b ) {

        return b.z - a.z;

    };

    function numericalSort ( a, b ) {

        return b[ 1 ] - a[ 1 ];

    };


    // Rendering

    this.render = function ( scene, camera, renderTarget, forceClear ) {

        if ( camera instanceof THREE.Camera === false ) {

            console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
            return;

        }

        var i, il,

        webglObject, object,
        renderList,

        lights = scene.__lights,
        fog = scene.fog;

        // reset caching for this frame

        _currentMaterialId = -1;
        _lightsNeedUpdate = true;

        // update scene graph

        if ( this.autoUpdateScene ) scene.updateMatrixWorld();

        // update camera matrices and frustum

        if ( camera.parent === undefined ) camera.updateMatrixWorld();

        if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
        if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );

        camera.matrixWorldInverse.getInverse( camera.matrixWorld );

        camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
        camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );

        _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
        _frustum.setFromMatrix( _projScreenMatrix );

        // update WebGL objects

        if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );

        // custom render plugins (pre pass)

        renderPlugins( this.renderPluginsPre, scene, camera );

        //

        _this.info.render.calls = 0;
        _this.info.render.vertices = 0;
        _this.info.render.faces = 0;
        _this.info.render.points = 0;

        this.setRenderTarget( renderTarget );

        if ( this.autoClear || forceClear ) {

            this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );

        }

        // set matrices for regular objects (frustum culled)

        renderList = scene.__webglObjects;

        for ( i = 0, il = renderList.length; i < il; i ++ ) {

            webglObject = renderList[ i ];
            object = webglObject.object;

            webglObject.render = false;

            if ( object.visible ) {

                if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {

                    //object.matrixWorld.flattenToArray( object._modelMatrixArray );

                    setupMatrices( object, camera );

                    unrollBufferMaterial( webglObject );

                    webglObject.render = true;

                    if ( this.sortObjects === true ) {

                        if ( object.renderDepth !== null ) {

                            webglObject.z = object.renderDepth;

                        } else {

                            _vector3.copy( object.matrixWorld.getPosition() );
                            _projScreenMatrix.multiplyVector3( _vector3 );

                            webglObject.z = _vector3.z;

                        }

                    }

                }

            }

        }

        if ( this.sortObjects ) {

            renderList.sort( painterSort );

        }

        // set matrices for immediate objects

        renderList = scene.__webglObjectsImmediate;

        for ( i = 0, il = renderList.length; i < il; i ++ ) {

            webglObject = renderList[ i ];
            object = webglObject.object;

            if ( object.visible ) {

                /*
                if ( object.matrixAutoUpdate ) {

                    object.matrixWorld.flattenToArray( object._modelMatrixArray );

                }
                */

                setupMatrices( object, camera );

                unrollImmediateBufferMaterial( webglObject );

            }

        }

        if ( scene.overrideMaterial ) {

            var material = scene.overrideMaterial;

            this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
            this.setDepthTest( material.depthTest );
            this.setDepthWrite( material.depthWrite );
            setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );

            renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
            renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );

        } else {

            // opaque pass (front-to-back order)

            this.setBlending( THREE.NormalBlending );

            renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
            renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );

            // transparent pass (back-to-front order)

            renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
            renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );

        }

        // custom render plugins (post pass)

        renderPlugins( this.renderPluginsPost, scene, camera );


        // Generate mipmap if we're using any kind of mipmap filtering

        if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {

            updateRenderTargetMipmap( renderTarget );

        }

        // Ensure depth buffer writing is enabled so it can be cleared on next render

        this.setDepthTest( true );
        this.setDepthWrite( true );

        // _gl.finish();

    };

    function renderPlugins( plugins, scene, camera ) {

        if ( ! plugins.length ) return;

        for ( var i = 0, il = plugins.length; i < il; i ++ ) {

            // reset state for plugin (to start from clean slate)

            _currentProgram = null;
            _currentCamera = null;

            _oldBlending = -1;
            _oldDepthTest = -1;
            _oldDepthWrite = -1;
            _oldDoubleSided = -1;
            _oldFlipSided = -1;
            _currentGeometryGroupHash = -1;
            _currentMaterialId = -1;

            _lightsNeedUpdate = true;

            plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );

            // reset state after plugin (anything could have changed)

            _currentProgram = null;
            _currentCamera = null;

            _oldBlending = -1;
            _oldDepthTest = -1;
            _oldDepthWrite = -1;
            _oldDoubleSided = -1;
            _oldFlipSided = -1;
            _currentGeometryGroupHash = -1;
            _currentMaterialId = -1;

            _lightsNeedUpdate = true;

        }

    };

    function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {

        var webglObject, object, buffer, material, start, end, delta;

        if ( reverse ) {

            start = renderList.length - 1;
            end = -1;
            delta = -1;

        } else {

            start = 0;
            end = renderList.length;
            delta = 1;
        }

        for ( var i = start; i !== end; i += delta ) {

            webglObject = renderList[ i ];

            if ( webglObject.render ) {

                object = webglObject.object;
                buffer = webglObject.buffer;

                if ( overrideMaterial ) {

                    material = overrideMaterial;

                } else {

                    material = webglObject[ materialType ];

                    if ( ! material ) continue;

                    if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );

                    _this.setDepthTest( material.depthTest );
                    _this.setDepthWrite( material.depthWrite );
                    setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );

                }

                _this.setMaterialFaces( material );

                if ( buffer instanceof THREE.BufferGeometry ) {

                    _this.renderBufferDirect( camera, lights, fog, material, buffer, object );

                } else {

                    _this.renderBuffer( camera, lights, fog, material, buffer, object );

                }

            }

        }

    };

    function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {

        var webglObject, object, material, program;

        for ( var i = 0, il = renderList.length; i < il; i ++ ) {

            webglObject = renderList[ i ];
            object = webglObject.object;

            if ( object.visible ) {

                if ( overrideMaterial ) {

                    material = overrideMaterial;

                } else {

                    material = webglObject[ materialType ];

                    if ( ! material ) continue;

                    if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );

                    _this.setDepthTest( material.depthTest );
                    _this.setDepthWrite( material.depthWrite );
                    setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );

                }

                _this.renderImmediateObject( camera, lights, fog, material, object );

            }

        }

    };

    this.renderImmediateObject = function ( camera, lights, fog, material, object ) {

        var program = setProgram( camera, lights, fog, material, object );

        _currentGeometryGroupHash = -1;

        _this.setMaterialFaces( material );

        if ( object.immediateRenderCallback ) {

            object.immediateRenderCallback( program, _gl, _frustum );

        } else {

            object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );

        }

    };

    function unrollImmediateBufferMaterial ( globject ) {

        var object = globject.object,
            material = object.material;

        if ( material.transparent ) {

            globject.transparent = material;
            globject.opaque = null;

        } else {

            globject.opaque = material;
            globject.transparent = null;

        }

    };

    function unrollBufferMaterial ( globject ) {

        var object = globject.object,
            buffer = globject.buffer,
            material, materialIndex, meshMaterial;

        meshMaterial = object.material;

        if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {

            materialIndex = buffer.materialIndex;

            if ( materialIndex >= 0 ) {

                material = object.geometry.materials[ materialIndex ];

                if ( material.transparent ) {

                    globject.transparent = material;
                    globject.opaque = null;

                } else {

                    globject.opaque = material;
                    globject.transparent = null;

                }

            }

        } else {

            material = meshMaterial;

            if ( material ) {

                if ( material.transparent ) {

                    globject.transparent = material;
                    globject.opaque = null;

                } else {

                    globject.opaque = material;
                    globject.transparent = null;

                }

            }

        }

    };

    // Geometry splitting

    function sortFacesByMaterial ( geometry ) {

        var f, fl, face, materialIndex, vertices,
            materialHash, groupHash,
            hash_map = {};

        var numMorphTargets = geometry.morphTargets.length;
        var numMorphNormals = geometry.morphNormals.length;

        geometry.geometryGroups = {};

        for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {

            face = geometry.faces[ f ];
            materialIndex = face.materialIndex;

            materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;

            if ( hash_map[ materialHash ] === undefined ) {

                hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };

            }

            groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;

            if ( geometry.geometryGroups[ groupHash ] === undefined ) {

                geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };

            }

            vertices = face instanceof THREE.Face3 ? 3 : 4;

            if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {

                hash_map[ materialHash ].counter += 1;
                groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;

                if ( geometry.geometryGroups[ groupHash ] === undefined ) {

                    geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };

                }

            }

            if ( face instanceof THREE.Face3 ) {

                geometry.geometryGroups[ groupHash ].faces3.push( f );

            } else {

                geometry.geometryGroups[ groupHash ].faces4.push( f );

            }

            geometry.geometryGroups[ groupHash ].vertices += vertices;

        }

        geometry.geometryGroupsList = [];

        for ( var g in geometry.geometryGroups ) {

            geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;

            geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );

        }

    };

    // Objects refresh

    this.initWebGLObjects = function ( scene ) {

        if ( !scene.__webglObjects ) {

            scene.__webglObjects = [];
            scene.__webglObjectsImmediate = [];
            scene.__webglSprites = [];
            scene.__webglFlares = [];

        }

        while ( scene.__objectsAdded.length ) {

            addObject( scene.__objectsAdded[ 0 ], scene );
            scene.__objectsAdded.splice( 0, 1 );

        }

        while ( scene.__objectsRemoved.length ) {

            removeObject( scene.__objectsRemoved[ 0 ], scene );
            scene.__objectsRemoved.splice( 0, 1 );

        }

        // update must be called after objects adding / removal

        for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {

            updateObject( scene.__webglObjects[ o ].object );

        }

    };

    // Objects adding

    function addObject ( object, scene ) {

        var g, geometry, geometryGroup;

        if ( ! object.__webglInit ) {

            object.__webglInit = true;

            object._modelViewMatrix = new THREE.Matrix4();
            object._normalMatrix = new THREE.Matrix3();

            if ( object instanceof THREE.Mesh ) {

                geometry = object.geometry;

                if ( geometry instanceof THREE.Geometry ) {

                    if ( geometry.geometryGroups === undefined ) {

                        sortFacesByMaterial( geometry );

                    }

                    // create separate VBOs per geometry chunk

                    for ( g in geometry.geometryGroups ) {

                        geometryGroup = geometry.geometryGroups[ g ];

                        // initialise VBO on the first access

                        if ( ! geometryGroup.__webglVertexBuffer ) {

                            createMeshBuffers( geometryGroup );
                            initMeshBuffers( geometryGroup, object );

                            geometry.verticesNeedUpdate = true;
                            geometry.morphTargetsNeedUpdate = true;
                            geometry.elementsNeedUpdate = true;
                            geometry.uvsNeedUpdate = true;
                            geometry.normalsNeedUpdate = true;
                            geometry.tangentsNeedUpdate = true;
                            geometry.colorsNeedUpdate = true;

                        }

                    }

                } else if ( geometry instanceof THREE.BufferGeometry ) {

                    initDirectBuffers( geometry );

                }

            } else if ( object instanceof THREE.Ribbon ) {

                geometry = object.geometry;

                if( ! geometry.__webglVertexBuffer ) {

                    createRibbonBuffers( geometry );
                    initRibbonBuffers( geometry );

                    geometry.verticesNeedUpdate = true;
                    geometry.colorsNeedUpdate = true;

                }

            } else if ( object instanceof THREE.Line ) {

                geometry = object.geometry;

                if( ! geometry.__webglVertexBuffer ) {

                    createLineBuffers( geometry );
                    initLineBuffers( geometry, object );

                    geometry.verticesNeedUpdate = true;
                    geometry.colorsNeedUpdate = true;

                }

            } else if ( object instanceof THREE.ParticleSystem ) {

                geometry = object.geometry;

                if ( ! geometry.__webglVertexBuffer ) {

                    if ( geometry instanceof THREE.Geometry ) {

                        createParticleBuffers( geometry );
                        initParticleBuffers( geometry, object );

                        geometry.verticesNeedUpdate = true;
                        geometry.colorsNeedUpdate = true;

                    } else if ( geometry instanceof THREE.BufferGeometry ) {

                        initDirectBuffers( geometry );

                    }


                }

            }

        }

        if ( ! object.__webglActive ) {

            if ( object instanceof THREE.Mesh ) {

                geometry = object.geometry;

                if ( geometry instanceof THREE.BufferGeometry ) {

                    addBuffer( scene.__webglObjects, geometry, object );

                } else {

                    for ( g in geometry.geometryGroups ) {

                        geometryGroup = geometry.geometryGroups[ g ];

                        addBuffer( scene.__webglObjects, geometryGroup, object );

                    }

                }

            } else if ( object instanceof THREE.Ribbon ||
                        object instanceof THREE.Line ||
                        object instanceof THREE.ParticleSystem ) {

                geometry = object.geometry;
                addBuffer( scene.__webglObjects, geometry, object );

            } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {

                addBufferImmediate( scene.__webglObjectsImmediate, object );

            } else if ( object instanceof THREE.Sprite ) {

                scene.__webglSprites.push( object );

            } else if ( object instanceof THREE.LensFlare ) {

                scene.__webglFlares.push( object );

            }

            object.__webglActive = true;

        }

    };

    function addBuffer ( objlist, buffer, object ) {

        objlist.push(
            {
                buffer: buffer,
                object: object,
                opaque: null,
                transparent: null
            }
        );

    };

    function addBufferImmediate ( objlist, object ) {

        objlist.push(
            {
                object: object,
                opaque: null,
                transparent: null
            }
        );

    };

    // Objects updates

    function updateObject ( object ) {

        var geometry = object.geometry,
            geometryGroup, customAttributesDirty, material;

        if ( object instanceof THREE.Mesh ) {

            if ( geometry instanceof THREE.BufferGeometry ) {

                if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
                     geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
                     geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {

                    setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );

                }

                geometry.verticesNeedUpdate = false;
                geometry.elementsNeedUpdate = false;
                geometry.uvsNeedUpdate = false;
                geometry.normalsNeedUpdate = false;
                geometry.colorsNeedUpdate = false;
                geometry.tangentsNeedUpdate = false;

            } else {

                // check all geometry groups

                for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {

                    geometryGroup = geometry.geometryGroupsList[ i ];

                    material = getBufferMaterial( object, geometryGroup );

                    customAttributesDirty = material.attributes && areCustomAttributesDirty( material );

                    if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
                         geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
                         geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {

                        setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );

                    }

                }

                geometry.verticesNeedUpdate = false;
                geometry.morphTargetsNeedUpdate = false;
                geometry.elementsNeedUpdate = false;
                geometry.uvsNeedUpdate = false;
                geometry.normalsNeedUpdate = false;
                geometry.colorsNeedUpdate = false;
                geometry.tangentsNeedUpdate = false;

                material.attributes && clearCustomAttributes( material );

            }

        } else if ( object instanceof THREE.Ribbon ) {

            if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {

                setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );

            }

            geometry.verticesNeedUpdate = false;
            geometry.colorsNeedUpdate = false;

        } else if ( object instanceof THREE.Line ) {

            material = getBufferMaterial( object, geometryGroup );

            customAttributesDirty = material.attributes && areCustomAttributesDirty( material );

            if ( geometry.verticesNeedUpdate ||  geometry.colorsNeedUpdate || customAttributesDirty ) {

                setLineBuffers( geometry, _gl.DYNAMIC_DRAW );

            }

            geometry.verticesNeedUpdate = false;
            geometry.colorsNeedUpdate = false;

            material.attributes && clearCustomAttributes( material );

        } else if ( object instanceof THREE.ParticleSystem ) {

            if ( geometry instanceof THREE.BufferGeometry ) {

                if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {

                    setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );

                }

                geometry.verticesNeedUpdate = false;
                geometry.colorsNeedUpdate = false;

            } else {

                material = getBufferMaterial( object, geometryGroup );

                customAttributesDirty = material.attributes && areCustomAttributesDirty( material );

                if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {

                    setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );

                }

                geometry.verticesNeedUpdate = false;
                geometry.colorsNeedUpdate = false;

                material.attributes && clearCustomAttributes( material );

            }

        }

    };

    // Objects updates - custom attributes check

    function areCustomAttributesDirty ( material ) {

        for ( var a in material.attributes ) {

            if ( material.attributes[ a ].needsUpdate ) return true;

        }

        return false;

    };

    function clearCustomAttributes ( material ) {

        for ( var a in material.attributes ) {

            material.attributes[ a ].needsUpdate = false;

        }

    };

    // Objects removal

    function removeObject ( object, scene ) {

        if ( object instanceof THREE.Mesh  ||
             object instanceof THREE.ParticleSystem ||
             object instanceof THREE.Ribbon ||
             object instanceof THREE.Line ) {

            removeInstances( scene.__webglObjects, object );

        } else if ( object instanceof THREE.Sprite ) {

            removeInstancesDirect( scene.__webglSprites, object );

        } else if ( object instanceof THREE.LensFlare ) {

            removeInstancesDirect( scene.__webglFlares, object );

        } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {

            removeInstances( scene.__webglObjectsImmediate, object );

        }

        object.__webglActive = false;

    };

    function removeInstances ( objlist, object ) {

        for ( var o = objlist.length - 1; o >= 0; o -- ) {

            if ( objlist[ o ].object === object ) {

                objlist.splice( o, 1 );

            }

        }

    };

    function removeInstancesDirect ( objlist, object ) {

        for ( var o = objlist.length - 1; o >= 0; o -- ) {

            if ( objlist[ o ] === object ) {

                objlist.splice( o, 1 );

            }

        }

    };

    // Materials

    this.initMaterial = function ( material, lights, fog, object ) {

        var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;

        if ( material instanceof THREE.MeshDepthMaterial ) {

            shaderID = 'depth';

        } else if ( material instanceof THREE.MeshNormalMaterial ) {

            shaderID = 'normal';

        } else if ( material instanceof THREE.MeshBasicMaterial ) {

            shaderID = 'basic';

        } else if ( material instanceof THREE.MeshLambertMaterial ) {

            shaderID = 'lambert';

        } else if ( material instanceof THREE.MeshPhongMaterial ) {

            shaderID = 'phong';

        } else if ( material instanceof THREE.LineBasicMaterial ) {

            shaderID = 'basic';

        } else if ( material instanceof THREE.ParticleBasicMaterial ) {

            shaderID = 'particle_basic';

        }

        if ( shaderID ) {

            setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );

        }

        // heuristics to create shader parameters according to lights in the scene
        // (not to blow over maxLights budget)

        maxLightCount = allocateLights( lights );

        maxShadows = allocateShadows( lights );

        maxBones = allocateBones( object );

        parameters = {

            map: !!material.map,
            envMap: !!material.envMap,
            lightMap: !!material.lightMap,
            bumpMap: !!material.bumpMap,
            normalMap: !!material.normalMap,
            specularMap: !!material.specularMap,

            vertexColors: material.vertexColors,

            fog: fog,
            useFog: material.fog,

            sizeAttenuation: material.sizeAttenuation,

            skinning: material.skinning,
            maxBones: maxBones,
            useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
            boneTextureWidth: object && object.boneTextureWidth,
            boneTextureHeight: object && object.boneTextureHeight,

            morphTargets: material.morphTargets,
            morphNormals: material.morphNormals,
            maxMorphTargets: this.maxMorphTargets,
            maxMorphNormals: this.maxMorphNormals,

            maxDirLights: maxLightCount.directional,
            maxPointLights: maxLightCount.point,
            maxSpotLights: maxLightCount.spot,
            maxHemiLights: maxLightCount.hemi,

            maxShadows: maxShadows,
            shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
            shadowMapSoft: this.shadowMapSoft,
            shadowMapDebug: this.shadowMapDebug,
            shadowMapCascade: this.shadowMapCascade,

            alphaTest: material.alphaTest,
            metal: material.metal,
            perPixel: material.perPixel,
            wrapAround: material.wrapAround,
            doubleSided: material.side === THREE.DoubleSide,
            flipSided: material.side === THREE.BackSide

        };

        material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters );

        var attributes = material.program.attributes;

        if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
        if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
        if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
        if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );

        if ( material.skinning &&
             attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {

            _gl.enableVertexAttribArray( attributes.skinIndex );
            _gl.enableVertexAttribArray( attributes.skinWeight );

        }

        if ( material.attributes ) {

            for ( a in material.attributes ) {

                if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );

            }

        }

        if ( material.morphTargets ) {

            material.numSupportedMorphTargets = 0;

            var id, base = "morphTarget";

            for ( i = 0; i < this.maxMorphTargets; i ++ ) {

                id = base + i;

                if ( attributes[ id ] >= 0 ) {

                    _gl.enableVertexAttribArray( attributes[ id ] );
                    material.numSupportedMorphTargets ++;

                }

            }

        }

        if ( material.morphNormals ) {

            material.numSupportedMorphNormals = 0;

            var id, base = "morphNormal";

            for ( i = 0; i < this.maxMorphNormals; i ++ ) {

                id = base + i;

                if ( attributes[ id ] >= 0 ) {

                    _gl.enableVertexAttribArray( attributes[ id ] );
                    material.numSupportedMorphNormals ++;

                }

            }

        }

        material.uniformsList = [];

        for ( u in material.uniforms ) {

            material.uniformsList.push( [ material.uniforms[ u ], u ] );

        }

    };

    function setMaterialShaders( material, shaders ) {

        material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
        material.vertexShader = shaders.vertexShader;
        material.fragmentShader = shaders.fragmentShader;

    };

    function setProgram( camera, lights, fog, material, object ) {

        _usedTextureUnits = 0;

        if ( material.needsUpdate ) {

            if ( material.program ) _this.deallocateMaterial( material );

            _this.initMaterial( material, lights, fog, object );
            material.needsUpdate = false;

        }

        if ( material.morphTargets ) {

            if ( ! object.__webglMorphTargetInfluences ) {

                object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );

            }

        }

        var refreshMaterial = false;

        var program = material.program,
            p_uniforms = program.uniforms,
            m_uniforms = material.uniforms;

        if ( program !== _currentProgram ) {

            _gl.useProgram( program );
            _currentProgram = program;

            refreshMaterial = true;

        }

        if ( material.id !== _currentMaterialId ) {

            _currentMaterialId = material.id;
            refreshMaterial = true;

        }

        if ( refreshMaterial || camera !== _currentCamera ) {

            _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );

            if ( camera !== _currentCamera ) _currentCamera = camera;

        }

        // skinning uniforms must be set even if material didn't change
        // auto-setting of texture unit for bone texture must go before other textures
        // not sure why, but otherwise weird things happen

        if ( material.skinning ) {

            if ( _supportsBoneTextures && object.useVertexTexture ) {

                if ( p_uniforms.boneTexture !== null ) {

                    var textureUnit = getTextureUnit();

                    _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
                    _this.setTexture( object.boneTexture, textureUnit );

                }

            } else {

                if ( p_uniforms.boneGlobalMatrices !== null ) {

                    _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );

                }

            }

        }

        if ( refreshMaterial ) {

            // refresh uniforms common to several materials

            if ( fog && material.fog ) {

                refreshUniformsFog( m_uniforms, fog );

            }

            if ( material instanceof THREE.MeshPhongMaterial ||
                 material instanceof THREE.MeshLambertMaterial ||
                 material.lights ) {

                if ( _lightsNeedUpdate ) {

                    setupLights( program, lights );
                    _lightsNeedUpdate = false;

                }

                refreshUniformsLights( m_uniforms, _lights );

            }

            if ( material instanceof THREE.MeshBasicMaterial ||
                 material instanceof THREE.MeshLambertMaterial ||
                 material instanceof THREE.MeshPhongMaterial ) {

                refreshUniformsCommon( m_uniforms, material );

            }

            // refresh single material specific uniforms

            if ( material instanceof THREE.LineBasicMaterial ) {

                refreshUniformsLine( m_uniforms, material );

            } else if ( material instanceof THREE.ParticleBasicMaterial ) {

                refreshUniformsParticle( m_uniforms, material );

            } else if ( material instanceof THREE.MeshPhongMaterial ) {

                refreshUniformsPhong( m_uniforms, material );

            } else if ( material instanceof THREE.MeshLambertMaterial ) {

                refreshUniformsLambert( m_uniforms, material );

            } else if ( material instanceof THREE.MeshDepthMaterial ) {

                m_uniforms.mNear.value = camera.near;
                m_uniforms.mFar.value = camera.far;
                m_uniforms.opacity.value = material.opacity;

            } else if ( material instanceof THREE.MeshNormalMaterial ) {

                m_uniforms.opacity.value = material.opacity;

            }

            if ( object.receiveShadow && ! material._shadowPass ) {

                refreshUniformsShadow( m_uniforms, lights );

            }

            // load common uniforms

            loadUniformsGeneric( program, material.uniformsList );

            // load material specific uniforms
            // (shader material also gets them for the sake of genericity)

            if ( material instanceof THREE.ShaderMaterial ||
                 material instanceof THREE.MeshPhongMaterial ||
                 material.envMap ) {

                if ( p_uniforms.cameraPosition !== null ) {

                    var position = camera.matrixWorld.getPosition();
                    _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );

                }

            }

            if ( material instanceof THREE.MeshPhongMaterial ||
                 material instanceof THREE.MeshLambertMaterial ||
                 material instanceof THREE.ShaderMaterial ||
                 material.skinning ) {

                if ( p_uniforms.viewMatrix !== null ) {

                    _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );

                }

            }

        }

        loadUniformsMatrices( p_uniforms, object );

        if ( p_uniforms.modelMatrix !== null ) {

            _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );

        }

        return program;

    };

    // Uniforms (refresh uniforms objects)

    function refreshUniformsCommon ( uniforms, material ) {

        uniforms.opacity.value = material.opacity;

        if ( _this.gammaInput ) {

            uniforms.diffuse.value.copyGammaToLinear( material.color );

        } else {

            uniforms.diffuse.value = material.color;

        }

        uniforms.map.value = material.map;
        uniforms.lightMap.value = material.lightMap;
        uniforms.specularMap.value = material.specularMap;

        if ( material.bumpMap ) {

            uniforms.bumpMap.value = material.bumpMap;
            uniforms.bumpScale.value = material.bumpScale;

        }

        if ( material.normalMap ) {

            uniforms.normalMap.value = material.normalMap;
            uniforms.normalScale.value.copy( material.normalScale );

        }

        // uv repeat and offset setting priorities
        //    1. color map
        //    2. specular map
        //    3. normal map
        //    4. bump map

        var uvScaleMap;

        if ( material.map ) {

            uvScaleMap = material.map;

        } else if ( material.specularMap ) {

            uvScaleMap = material.specularMap;

        } else if ( material.normalMap ) {

            uvScaleMap = material.normalMap;

        } else if ( material.bumpMap ) {

            uvScaleMap = material.bumpMap;

        }

        if ( uvScaleMap !== undefined ) {

            var offset = uvScaleMap.offset;
            var repeat = uvScaleMap.repeat;

            uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );

        }

        uniforms.envMap.value = material.envMap;
        uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;

        if ( _this.gammaInput ) {

            //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
            uniforms.reflectivity.value = material.reflectivity;

        } else {

            uniforms.reflectivity.value = material.reflectivity;

        }

        uniforms.refractionRatio.value = material.refractionRatio;
        uniforms.combine.value = material.combine;
        uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;

    };

    function refreshUniformsLine ( uniforms, material ) {

        uniforms.diffuse.value = material.color;
        uniforms.opacity.value = material.opacity;

    };

    function refreshUniformsParticle ( uniforms, material ) {

        uniforms.psColor.value = material.color;
        uniforms.opacity.value = material.opacity;
        uniforms.size.value = material.size;
        uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.

        uniforms.map.value = material.map;

    };

    function refreshUniformsFog ( uniforms, fog ) {

        uniforms.fogColor.value = fog.color;

        if ( fog instanceof THREE.Fog ) {

            uniforms.fogNear.value = fog.near;
            uniforms.fogFar.value = fog.far;

        } else if ( fog instanceof THREE.FogExp2 ) {

            uniforms.fogDensity.value = fog.density;

        }

    };

    function refreshUniformsPhong ( uniforms, material ) {

        uniforms.shininess.value = material.shininess;

        if ( _this.gammaInput ) {

            uniforms.ambient.value.copyGammaToLinear( material.ambient );
            uniforms.emissive.value.copyGammaToLinear( material.emissive );
            uniforms.specular.value.copyGammaToLinear( material.specular );

        } else {

            uniforms.ambient.value = material.ambient;
            uniforms.emissive.value = material.emissive;
            uniforms.specular.value = material.specular;

        }

        if ( material.wrapAround ) {

            uniforms.wrapRGB.value.copy( material.wrapRGB );

        }

    };

    function refreshUniformsLambert ( uniforms, material ) {

        if ( _this.gammaInput ) {

            uniforms.ambient.value.copyGammaToLinear( material.ambient );
            uniforms.emissive.value.copyGammaToLinear( material.emissive );

        } else {

            uniforms.ambient.value = material.ambient;
            uniforms.emissive.value = material.emissive;

        }

        if ( material.wrapAround ) {

            uniforms.wrapRGB.value.copy( material.wrapRGB );

        }

    };

    function refreshUniformsLights ( uniforms, lights ) {

        uniforms.ambientLightColor.value = lights.ambient;

        uniforms.directionalLightColor.value = lights.directional.colors;
        uniforms.directionalLightDirection.value = lights.directional.positions;

        uniforms.pointLightColor.value = lights.point.colors;
        uniforms.pointLightPosition.value = lights.point.positions;
        uniforms.pointLightDistance.value = lights.point.distances;

        uniforms.spotLightColor.value = lights.spot.colors;
        uniforms.spotLightPosition.value = lights.spot.positions;
        uniforms.spotLightDistance.value = lights.spot.distances;
        uniforms.spotLightDirection.value = lights.spot.directions;
        uniforms.spotLightAngle.value = lights.spot.angles;
        uniforms.spotLightExponent.value = lights.spot.exponents;

        uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
        uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
        uniforms.hemisphereLightPosition.value = lights.hemi.positions;

    };

    function refreshUniformsShadow ( uniforms, lights ) {

        if ( uniforms.shadowMatrix ) {

            var j = 0;

            for ( var i = 0, il = lights.length; i < il; i ++ ) {

                var light = lights[ i ];

                if ( ! light.castShadow ) continue;

                if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {

                    uniforms.shadowMap.value[ j ] = light.shadowMap;
                    uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;

                    uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;

                    uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
                    uniforms.shadowBias.value[ j ] = light.shadowBias;

                    j ++;

                }

            }

        }

    };

    // Uniforms (load to GPU)

    function loadUniformsMatrices ( uniforms, object ) {

        _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );

        if ( uniforms.normalMatrix ) {

            _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );

        }

    };

    function getTextureUnit() {

        var textureUnit = _usedTextureUnits;

        if ( textureUnit >= _maxTextures ) {

            console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );

        }

        _usedTextureUnits += 1;

        return textureUnit;

    };

    function loadUniformsGeneric ( program, uniforms ) {

        var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;

        for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {

            location = program.uniforms[ uniforms[ j ][ 1 ] ];
            if ( !location ) continue;

            uniform = uniforms[ j ][ 0 ];

            type = uniform.type;
            value = uniform.value;

            if ( type === "i" ) { // single integer

                _gl.uniform1i( location, value );

            } else if ( type === "f" ) { // single float

                _gl.uniform1f( location, value );

            } else if ( type === "v2" ) { // single THREE.Vector2

                _gl.uniform2f( location, value.x, value.y );

            } else if ( type === "v3" ) { // single THREE.Vector3

                _gl.uniform3f( location, value.x, value.y, value.z );

            } else if ( type === "v4" ) { // single THREE.Vector4

                _gl.uniform4f( location, value.x, value.y, value.z, value.w );

            } else if ( type === "c" ) { // single THREE.Color

                _gl.uniform3f( location, value.r, value.g, value.b );

            } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)

                _gl.uniform1iv( location, value );

            } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)

                _gl.uniform3iv( location, value );

            } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)

                _gl.uniform1fv( location, value );

            } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)

                _gl.uniform3fv( location, value );

            } else if ( type === "v2v" ) { // array of THREE.Vector2

                if ( uniform._array === undefined ) {

                    uniform._array = new Float32Array( 2 * value.length );

                }

                for ( i = 0, il = value.length; i < il; i ++ ) {

                    offset = i * 2;

                    uniform._array[ offset ]      = value[ i ].x;
                    uniform._array[ offset + 1 ] = value[ i ].y;

                }

                _gl.uniform2fv( location, uniform._array );

            } else if ( type === "v3v" ) { // array of THREE.Vector3

                if ( uniform._array === undefined ) {

                    uniform._array = new Float32Array( 3 * value.length );

                }

                for ( i = 0, il = value.length; i < il; i ++ ) {

                    offset = i * 3;

                    uniform._array[ offset ]      = value[ i ].x;
                    uniform._array[ offset + 1 ] = value[ i ].y;
                    uniform._array[ offset + 2 ] = value[ i ].z;

                }

                _gl.uniform3fv( location, uniform._array );

            } else if ( type === "v4v" ) { // array of THREE.Vector4

                if ( uniform._array === undefined ) {

                    uniform._array = new Float32Array( 4 * value.length );

                }

                for ( i = 0, il = value.length; i < il; i ++ ) {

                    offset = i * 4;

                    uniform._array[ offset ]      = value[ i ].x;
                    uniform._array[ offset + 1 ] = value[ i ].y;
                    uniform._array[ offset + 2 ] = value[ i ].z;
                    uniform._array[ offset + 3 ] = value[ i ].w;

                }

                _gl.uniform4fv( location, uniform._array );

            } else if ( type === "m4") { // single THREE.Matrix4

                if ( uniform._array === undefined ) {

                    uniform._array = new Float32Array( 16 );

                }

                value.flattenToArray( uniform._array );
                _gl.uniformMatrix4fv( location, false, uniform._array );

            } else if ( type === "m4v" ) { // array of THREE.Matrix4

                if ( uniform._array === undefined ) {

                    uniform._array = new Float32Array( 16 * value.length );

                }

                for ( i = 0, il = value.length; i < il; i ++ ) {

                    value[ i ].flattenToArrayOffset( uniform._array, i * 16 );

                }

                _gl.uniformMatrix4fv( location, false, uniform._array );

            } else if ( type === "t" ) { // single THREE.Texture (2d or cube)

                texture = value;
                textureUnit = getTextureUnit();

                _gl.uniform1i( location, textureUnit );

                if ( !texture ) continue;

                if ( texture.image instanceof Array && texture.image.length === 6 ) {

                    setCubeTexture( texture, textureUnit );

                } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {

                    setCubeTextureDynamic( texture, textureUnit );

                } else {

                    _this.setTexture( texture, textureUnit );

                }

            } else if ( type === "tv" ) { // array of THREE.Texture (2d)

                if ( uniform._array === undefined ) {

                    uniform._array = [];

                }

                for( i = 0, il = uniform.value.length; i < il; i ++ ) {

                    uniform._array[ i ] = getTextureUnit();

                }

                _gl.uniform1iv( location, uniform._array );

                for( i = 0, il = uniform.value.length; i < il; i ++ ) {

                    texture = uniform.value[ i ];
                    textureUnit = uniform._array[ i ];

                    if ( !texture ) continue;

                    _this.setTexture( texture, textureUnit );

                }

            }

        }

    };

    function setupMatrices ( object, camera ) {

        object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );

        object._normalMatrix.getInverse( object._modelViewMatrix );
        object._normalMatrix.transpose();

    };

    //

    function setColorGamma( array, offset, color, intensitySq ) {

        array[ offset ]     = color.r * color.r * intensitySq;
        array[ offset + 1 ] = color.g * color.g * intensitySq;
        array[ offset + 2 ] = color.b * color.b * intensitySq;

    };

    function setColorLinear( array, offset, color, intensity ) {

        array[ offset ]     = color.r * intensity;
        array[ offset + 1 ] = color.g * intensity;
        array[ offset + 2 ] = color.b * intensity;

    };

    function setupLights ( program, lights ) {

        var l, ll, light, n,
        r = 0, g = 0, b = 0,
        color, skyColor, groundColor,
        intensity,  intensitySq,
        position,
        distance,

        zlights = _lights,

        dirColors = zlights.directional.colors,
        dirPositions = zlights.directional.positions,

        pointColors = zlights.point.colors,
        pointPositions = zlights.point.positions,
        pointDistances = zlights.point.distances,

        spotColors = zlights.spot.colors,
        spotPositions = zlights.spot.positions,
        spotDistances = zlights.spot.distances,
        spotDirections = zlights.spot.directions,
        spotAngles = zlights.spot.angles,
        spotExponents = zlights.spot.exponents,

        hemiSkyColors = zlights.hemi.skyColors,
        hemiGroundColors = zlights.hemi.groundColors,
        hemiPositions = zlights.hemi.positions,

        dirLength = 0,
        pointLength = 0,
        spotLength = 0,
        hemiLength = 0,

        dirOffset = 0,
        pointOffset = 0,
        spotOffset = 0,
        hemiOffset = 0;

        for ( l = 0, ll = lights.length; l < ll; l ++ ) {

            light = lights[ l ];

            if ( light.onlyShadow || ! light.visible ) continue;

            color = light.color;
            intensity = light.intensity;
            distance = light.distance;

            if ( light instanceof THREE.AmbientLight ) {

                if ( _this.gammaInput ) {

                    r += color.r * color.r;
                    g += color.g * color.g;
                    b += color.b * color.b;

                } else {

                    r += color.r;
                    g += color.g;
                    b += color.b;

                }

            } else if ( light instanceof THREE.DirectionalLight ) {

                dirOffset = dirLength * 3;

                if ( _this.gammaInput ) {

                    setColorGamma( dirColors, dirOffset, color, intensity * intensity );

                } else {

                    setColorLinear( dirColors, dirOffset, color, intensity );

                }

                _direction.copy( light.matrixWorld.getPosition() );
                _direction.subSelf( light.target.matrixWorld.getPosition() );
                _direction.normalize();

                dirPositions[ dirOffset ]     = _direction.x;
                dirPositions[ dirOffset + 1 ] = _direction.y;
                dirPositions[ dirOffset + 2 ] = _direction.z;

                dirLength += 1;

            } else if( light instanceof THREE.PointLight ) {

                pointOffset = pointLength * 3;

                if ( _this.gammaInput ) {

                    setColorGamma( pointColors, pointOffset, color, intensity * intensity );

                } else {

                    setColorLinear( pointColors, pointOffset, color, intensity );

                }

                position = light.matrixWorld.getPosition();

                pointPositions[ pointOffset ]     = position.x;
                pointPositions[ pointOffset + 1 ] = position.y;
                pointPositions[ pointOffset + 2 ] = position.z;

                pointDistances[ pointLength ] = distance;

                pointLength += 1;

            } else if( light instanceof THREE.SpotLight ) {

                spotOffset = spotLength * 3;

                if ( _this.gammaInput ) {

                    setColorGamma( spotColors, spotOffset, color, intensity * intensity );

                } else {

                    setColorLinear( spotColors, spotOffset, color, intensity );

                }

                position = light.matrixWorld.getPosition();

                spotPositions[ spotOffset ]     = position.x;
                spotPositions[ spotOffset + 1 ] = position.y;
                spotPositions[ spotOffset + 2 ] = position.z;

                spotDistances[ spotLength ] = distance;

                _direction.copy( position );
                _direction.subSelf( light.target.matrixWorld.getPosition() );
                _direction.normalize();

                spotDirections[ spotOffset ]     = _direction.x;
                spotDirections[ spotOffset + 1 ] = _direction.y;
                spotDirections[ spotOffset + 2 ] = _direction.z;

                spotAngles[ spotLength ] = Math.cos( light.angle );
                spotExponents[ spotLength ] = light.exponent;

                spotLength += 1;

            } else if ( light instanceof THREE.HemisphereLight ) {

                skyColor = light.color;
                groundColor = light.groundColor;

                hemiOffset = hemiLength * 3;

                if ( _this.gammaInput ) {

                    intensitySq = intensity * intensity;

                    setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
                    setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );

                } else {

                    setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
                    setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );

                }

                position = light.matrixWorld.getPosition();

                hemiPositions[ hemiOffset ]     = position.x;
                hemiPositions[ hemiOffset + 1 ] = position.y;
                hemiPositions[ hemiOffset + 2 ] = position.z;

                hemiLength += 1;

            }

        }

        // null eventual remains from removed lights
        // (this is to avoid if in shader)

        for ( l = dirLength * 3, ll = dirColors.length; l < ll; l ++ ) dirColors[ l ] = 0.0;
        for ( l = pointLength * 3, ll = pointColors.length; l < ll; l ++ ) pointColors[ l ] = 0.0;
        for ( l = spotLength * 3, ll = spotColors.length; l < ll; l ++ ) spotColors[ l ] = 0.0;
        for ( l = hemiLength * 3, ll = hemiSkyColors.length; l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
        for ( l = hemiLength * 3, ll = hemiGroundColors.length; l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;

        zlights.directional.length = dirLength;
        zlights.point.length = pointLength;
        zlights.spot.length = spotLength;
        zlights.hemi.length = hemiLength;

        zlights.ambient[ 0 ] = r;
        zlights.ambient[ 1 ] = g;
        zlights.ambient[ 2 ] = b;

    };

    // GL state setting

    this.setFaceCulling = function ( cullFace, frontFace ) {

        if ( cullFace ) {

            if ( !frontFace || frontFace === "ccw" ) {

                _gl.frontFace( _gl.CCW );

            } else {

                _gl.frontFace( _gl.CW );

            }

            if( cullFace === "back" ) {

                _gl.cullFace( _gl.BACK );

            } else if( cullFace === "front" ) {

                _gl.cullFace( _gl.FRONT );

            } else {

                _gl.cullFace( _gl.FRONT_AND_BACK );

            }

            _gl.enable( _gl.CULL_FACE );

        } else {

            _gl.disable( _gl.CULL_FACE );

        }

    };

    this.setMaterialFaces = function ( material ) {

        var doubleSided = material.side === THREE.DoubleSide;
        var flipSided = material.side === THREE.BackSide;

        if ( _oldDoubleSided !== doubleSided ) {

            if ( doubleSided ) {

                _gl.disable( _gl.CULL_FACE );

            } else {

                _gl.enable( _gl.CULL_FACE );

            }

            _oldDoubleSided = doubleSided;

        }

        if ( _oldFlipSided !== flipSided ) {

            if ( flipSided ) {

                _gl.frontFace( _gl.CW );

            } else {

                _gl.frontFace( _gl.CCW );

            }

            _oldFlipSided = flipSided;

        }

    };

    this.setDepthTest = function ( depthTest ) {

        if ( _oldDepthTest !== depthTest ) {

            if ( depthTest ) {

                _gl.enable( _gl.DEPTH_TEST );

            } else {

                _gl.disable( _gl.DEPTH_TEST );

            }

            _oldDepthTest = depthTest;

        }

    };

    this.setDepthWrite = function ( depthWrite ) {

        if ( _oldDepthWrite !== depthWrite ) {

            _gl.depthMask( depthWrite );
            _oldDepthWrite = depthWrite;

        }

    };

    function setLineWidth ( width ) {

        if ( width !== _oldLineWidth ) {

            _gl.lineWidth( width );

            _oldLineWidth = width;

        }

    };

    function setPolygonOffset ( polygonoffset, factor, units ) {

        if ( _oldPolygonOffset !== polygonoffset ) {

            if ( polygonoffset ) {

                _gl.enable( _gl.POLYGON_OFFSET_FILL );

            } else {

                _gl.disable( _gl.POLYGON_OFFSET_FILL );

            }

            _oldPolygonOffset = polygonoffset;

        }

        if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {

            _gl.polygonOffset( factor, units );

            _oldPolygonOffsetFactor = factor;
            _oldPolygonOffsetUnits = units;

        }

    };

    this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {

        if ( blending !== _oldBlending ) {

            if ( blending === THREE.NoBlending ) {

                _gl.disable( _gl.BLEND );

            } else if ( blending === THREE.AdditiveBlending ) {

                _gl.enable( _gl.BLEND );
                _gl.blendEquation( _gl.FUNC_ADD );
                _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );

            } else if ( blending === THREE.SubtractiveBlending ) {

                // TODO: Find blendFuncSeparate() combination
                _gl.enable( _gl.BLEND );
                _gl.blendEquation( _gl.FUNC_ADD );
                _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );

            } else if ( blending === THREE.MultiplyBlending ) {

                // TODO: Find blendFuncSeparate() combination
                _gl.enable( _gl.BLEND );
                _gl.blendEquation( _gl.FUNC_ADD );
                _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );

            } else if ( blending === THREE.CustomBlending ) {

                _gl.enable( _gl.BLEND );

            } else {

                _gl.enable( _gl.BLEND );
                _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
                _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );

            }

            _oldBlending = blending;

        }

        if ( blending === THREE.CustomBlending ) {

            if ( blendEquation !== _oldBlendEquation ) {

                _gl.blendEquation( paramThreeToGL( blendEquation ) );

                _oldBlendEquation = blendEquation;

            }

            if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {

                _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );

                _oldBlendSrc = blendSrc;
                _oldBlendDst = blendDst;

            }

        } else {

            _oldBlendEquation = null;
            _oldBlendSrc = null;
            _oldBlendDst = null;

        }

    };

    // Shaders

    function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) {

        var p, pl, program, code;
        var chunks = [];

        // Generate code

        if ( shaderID ) {

            chunks.push( shaderID );

        } else {

            chunks.push( fragmentShader );
            chunks.push( vertexShader );

        }

        for ( p in parameters ) {

            chunks.push( p );
            chunks.push( parameters[ p ] );

        }

        code = chunks.join();

        // Check if code has been already compiled

        for ( p = 0, pl = _programs.length; p < pl; p ++ ) {

            var programInfo = _programs[ p ];

            if ( programInfo.code === code ) {

                // console.log( "Code already compiled." /*: \n\n" + code*/ );

                programInfo.usedTimes ++;

                return programInfo.program;

            }

        }

        //console.log( "building new program " );

        //

        program = _gl.createProgram();

        var prefix_vertex = [

            "precision " + _precision + " float;",

            _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",

            _this.gammaInput ? "#define GAMMA_INPUT" : "",
            _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
            _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",

            "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
            "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
            "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
            "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,

            "#define MAX_SHADOWS " + parameters.maxShadows,

            "#define MAX_BONES " + parameters.maxBones,

            parameters.map ? "#define USE_MAP" : "",
            parameters.envMap ? "#define USE_ENVMAP" : "",
            parameters.lightMap ? "#define USE_LIGHTMAP" : "",
            parameters.bumpMap ? "#define USE_BUMPMAP" : "",
            parameters.normalMap ? "#define USE_NORMALMAP" : "",
            parameters.specularMap ? "#define USE_SPECULARMAP" : "",
            parameters.vertexColors ? "#define USE_COLOR" : "",

            parameters.skinning ? "#define USE_SKINNING" : "",
            parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
            parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
            parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",

            parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
            parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
            parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
            parameters.wrapAround ? "#define WRAP_AROUND" : "",
            parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
            parameters.flipSided ? "#define FLIP_SIDED" : "",

            parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
            parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
            parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
            parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",

            parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",

            "uniform mat4 modelMatrix;",
            "uniform mat4 modelViewMatrix;",
            "uniform mat4 projectionMatrix;",
            "uniform mat4 viewMatrix;",
            "uniform mat3 normalMatrix;",
            "uniform vec3 cameraPosition;",

            "attribute vec3 position;",
            "attribute vec3 normal;",
            "attribute vec2 uv;",
            "attribute vec2 uv2;",

            "#ifdef USE_COLOR",

                "attribute vec3 color;",

            "#endif",

            "#ifdef USE_MORPHTARGETS",

                "attribute vec3 morphTarget0;",
                "attribute vec3 morphTarget1;",
                "attribute vec3 morphTarget2;",
                "attribute vec3 morphTarget3;",

                "#ifdef USE_MORPHNORMALS",

                    "attribute vec3 morphNormal0;",
                    "attribute vec3 morphNormal1;",
                    "attribute vec3 morphNormal2;",
                    "attribute vec3 morphNormal3;",

                "#else",

                    "attribute vec3 morphTarget4;",
                    "attribute vec3 morphTarget5;",
                    "attribute vec3 morphTarget6;",
                    "attribute vec3 morphTarget7;",

                "#endif",

            "#endif",

            "#ifdef USE_SKINNING",

                "attribute vec4 skinIndex;",
                "attribute vec4 skinWeight;",

            "#endif",

            ""

        ].join("\n");

        var prefix_fragment = [

            "precision " + _precision + " float;",

            ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",

            "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
            "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
            "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
            "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,

            "#define MAX_SHADOWS " + parameters.maxShadows,

            parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",

            _this.gammaInput ? "#define GAMMA_INPUT" : "",
            _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
            _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",

            ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
            ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",

            parameters.map ? "#define USE_MAP" : "",
            parameters.envMap ? "#define USE_ENVMAP" : "",
            parameters.lightMap ? "#define USE_LIGHTMAP" : "",
            parameters.bumpMap ? "#define USE_BUMPMAP" : "",
            parameters.normalMap ? "#define USE_NORMALMAP" : "",
            parameters.specularMap ? "#define USE_SPECULARMAP" : "",
            parameters.vertexColors ? "#define USE_COLOR" : "",

            parameters.metal ? "#define METAL" : "",
            parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
            parameters.wrapAround ? "#define WRAP_AROUND" : "",
            parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
            parameters.flipSided ? "#define FLIP_SIDED" : "",

            parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
            parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
            parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
            parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",

            "uniform mat4 viewMatrix;",
            "uniform vec3 cameraPosition;",
            ""

        ].join("\n");

        var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
        var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );

        _gl.attachShader( program, glVertexShader );
        _gl.attachShader( program, glFragmentShader );

        _gl.linkProgram( program );

        if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {

            console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );

        }

        // clean up

        _gl.deleteShader( glFragmentShader );
        _gl.deleteShader( glVertexShader );

        //console.log( prefix_fragment + fragmentShader );
        //console.log( prefix_vertex + vertexShader );

        program.uniforms = {};
        program.attributes = {};

        var identifiers, u, a, i;

        // cache uniform locations

        identifiers = [

            'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
            'morphTargetInfluences'

        ];

        if ( parameters.useVertexTexture ) {

            identifiers.push( 'boneTexture' );

        } else {

            identifiers.push( 'boneGlobalMatrices' );

        }

        for ( u in uniforms ) {

            identifiers.push( u );

        }

        cacheUniformLocations( program, identifiers );

        // cache attributes locations

        identifiers = [

            "position", "normal", "uv", "uv2", "tangent", "color",
            "skinIndex", "skinWeight"

        ];

        for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {

            identifiers.push( "morphTarget" + i );

        }

        for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {

            identifiers.push( "morphNormal" + i );

        }

        for ( a in attributes ) {

            identifiers.push( a );

        }

        cacheAttributeLocations( program, identifiers );

        program.id = _programs_counter ++;

        _programs.push( { program: program, code: code, usedTimes: 1 } );

        _this.info.memory.programs = _programs.length;

        return program;

    };

    // Shader parameters cache

    function cacheUniformLocations ( program, identifiers ) {

        var i, l, id;

        for( i = 0, l = identifiers.length; i < l; i ++ ) {

            id = identifiers[ i ];
            program.uniforms[ id ] = _gl.getUniformLocation( program, id );

        }

    };

    function cacheAttributeLocations ( program, identifiers ) {

        var i, l, id;

        for( i = 0, l = identifiers.length; i < l; i ++ ) {

            id = identifiers[ i ];
            program.attributes[ id ] = _gl.getAttribLocation( program, id );

        }

    };

    function addLineNumbers ( string ) {

        var chunks = string.split( "\n" );

        for ( var i = 0, il = chunks.length; i < il; i ++ ) {

            // Chrome reports shader errors on lines
            // starting counting from 1

            chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];

        }

        return chunks.join( "\n" );

    };

    function getShader ( type, string ) {

        var shader;

        if ( type === "fragment" ) {

            shader = _gl.createShader( _gl.FRAGMENT_SHADER );

        } else if ( type === "vertex" ) {

            shader = _gl.createShader( _gl.VERTEX_SHADER );

        }

        _gl.shaderSource( shader, string );
        _gl.compileShader( shader );

        if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {

            console.error( _gl.getShaderInfoLog( shader ) );
            console.error( addLineNumbers( string ) );
            return null;

        }

        return shader;

    };

    // Textures


    function isPowerOfTwo ( value ) {

        return ( value & ( value - 1 ) ) === 0;

    };

    function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {

        if ( isImagePowerOfTwo ) {

            _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
            _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );

            _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
            _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );

        } else {

            _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
            _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );

            _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
            _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );

        }

        if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {

            if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {

                _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
                texture.__oldAnisotropy = texture.anisotropy;

            }

        }

    };

    this.setTexture = function ( texture, slot ) {

        if ( texture.needsUpdate ) {

            if ( ! texture.__webglInit ) {

                texture.__webglInit = true;
                texture.__webglTexture = _gl.createTexture();

                _this.info.memory.textures ++;

            }

            _gl.activeTexture( _gl.TEXTURE0 + slot );
            _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );

            _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
            _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );

            var image = texture.image,
            isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
            glFormat = paramThreeToGL( texture.format ),
            glType = paramThreeToGL( texture.type );

            setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );

            if ( texture instanceof THREE.CompressedTexture ) {

                var mipmap, mipmaps = texture.mipmaps;

                for( var i = 0, il = mipmaps.length; i < il; i ++ ) {

                    mipmap = mipmaps[ i ];
                    _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );

                }

            } else if ( texture instanceof THREE.DataTexture ) {

                _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );

            } else {

                _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );

            }

            if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );

            texture.needsUpdate = false;

            if ( texture.onUpdate ) texture.onUpdate();

        } else {

            _gl.activeTexture( _gl.TEXTURE0 + slot );
            _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );

        }

    };

    function clampToMaxSize ( image, maxSize ) {

        if ( image.width <= maxSize && image.height <= maxSize ) {

            return image;

        }

        // Warning: Scaling through the canvas will only work with images that use
        // premultiplied alpha.

        var maxDimension = Math.max( image.width, image.height );
        var newWidth = Math.floor( image.width * maxSize / maxDimension );
        var newHeight = Math.floor( image.height * maxSize / maxDimension );

        var canvas = document.createElement( 'canvas' );
        canvas.width = newWidth;
        canvas.height = newHeight;

        var ctx = canvas.getContext( "2d" );
        ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );

        return canvas;

    }

    function setCubeTexture ( texture, slot ) {

        if ( texture.image.length === 6 ) {

            if ( texture.needsUpdate ) {

                if ( ! texture.image.__webglTextureCube ) {

                    texture.image.__webglTextureCube = _gl.createTexture();

                }

                _gl.activeTexture( _gl.TEXTURE0 + slot );
                _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );

                _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );

                var isCompressed = texture instanceof THREE.CompressedTexture;

                var cubeImage = [];

                for ( var i = 0; i < 6; i ++ ) {

                    if ( _this.autoScaleCubemaps && ! isCompressed ) {

                        cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );

                    } else {

                        cubeImage[ i ] = texture.image[ i ];

                    }

                }

                var image = cubeImage[ 0 ],
                isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
                glFormat = paramThreeToGL( texture.format ),
                glType = paramThreeToGL( texture.type );

                setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );

                for ( var i = 0; i < 6; i ++ ) {

                    if ( isCompressed ) {

                        var mipmap, mipmaps = cubeImage[ i ].mipmaps;

                        for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {

                            mipmap = mipmaps[ j ];
                            _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );

                        }

                    } else {

                        _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );

                    }

                }

                if ( texture.generateMipmaps && isImagePowerOfTwo ) {

                    _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );

                }

                texture.needsUpdate = false;

                if ( texture.onUpdate ) texture.onUpdate();

            } else {

                _gl.activeTexture( _gl.TEXTURE0 + slot );
                _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );

            }

        }

    };

    function setCubeTextureDynamic ( texture, slot ) {

        _gl.activeTexture( _gl.TEXTURE0 + slot );
        _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );

    };

    // Render targets

    function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {

        _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
        _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );

    };

    function setupRenderBuffer ( renderbuffer, renderTarget  ) {

        _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );

        if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {

            _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
            _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );

        /* For some reason this is not working. Defaulting to RGBA4.
        } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {

            _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
            _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
        */
        } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {

            _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
            _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );

        } else {

            _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );

        }

    };

    this.setRenderTarget = function ( renderTarget ) {

        var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );

        if ( renderTarget && ! renderTarget.__webglFramebuffer ) {

            if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
            if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;

            renderTarget.__webglTexture = _gl.createTexture();

            // Setup texture, create render and frame buffers

            var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
                glFormat = paramThreeToGL( renderTarget.format ),
                glType = paramThreeToGL( renderTarget.type );

            if ( isCube ) {

                renderTarget.__webglFramebuffer = [];
                renderTarget.__webglRenderbuffer = [];

                _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
                setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );

                for ( var i = 0; i < 6; i ++ ) {

                    renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
                    renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();

                    _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );

                    setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
                    setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );

                }

                if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );

            } else {

                renderTarget.__webglFramebuffer = _gl.createFramebuffer();
                renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();

                _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
                setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );

                _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );

                setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
                setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );

                if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );

            }

            // Release everything

            if ( isCube ) {

                _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );

            } else {

                _gl.bindTexture( _gl.TEXTURE_2D, null );

            }

            _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
            _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);

        }

        var framebuffer, width, height, vx, vy;

        if ( renderTarget ) {

            if ( isCube ) {

                framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];

            } else {

                framebuffer = renderTarget.__webglFramebuffer;

            }

            width = renderTarget.width;
            height = renderTarget.height;

            vx = 0;
            vy = 0;

        } else {

            framebuffer = null;

            width = _viewportWidth;
            height = _viewportHeight;

            vx = _viewportX;
            vy = _viewportY;

        }

        if ( framebuffer !== _currentFramebuffer ) {

            _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
            _gl.viewport( vx, vy, width, height );

            _currentFramebuffer = framebuffer;

        }

        _currentWidth = width;
        _currentHeight = height;

    };

    function updateRenderTargetMipmap ( renderTarget ) {

        if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {

            _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
            _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
            _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );

        } else {

            _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
            _gl.generateMipmap( _gl.TEXTURE_2D );
            _gl.bindTexture( _gl.TEXTURE_2D, null );

        }

    };

    // Fallback filters for non-power-of-2 textures

    function filterFallback ( f ) {

        if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {

            return _gl.NEAREST;

        }

        return _gl.LINEAR;

    };

    // Map three.js constants to WebGL constants

    function paramThreeToGL ( p ) {

        if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
        if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
        if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;

        if ( p === THREE.NearestFilter ) return _gl.NEAREST;
        if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
        if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;

        if ( p === THREE.LinearFilter ) return _gl.LINEAR;
        if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
        if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;

        if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
        if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
        if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
        if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;

        if ( p === THREE.ByteType ) return _gl.BYTE;
        if ( p === THREE.ShortType ) return _gl.SHORT;
        if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
        if ( p === THREE.IntType ) return _gl.INT;
        if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
        if ( p === THREE.FloatType ) return _gl.FLOAT;

        if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
        if ( p === THREE.RGBFormat ) return _gl.RGB;
        if ( p === THREE.RGBAFormat ) return _gl.RGBA;
        if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
        if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;

        if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
        if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
        if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;

        if ( p === THREE.ZeroFactor ) return _gl.ZERO;
        if ( p === THREE.OneFactor ) return _gl.ONE;
        if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
        if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
        if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
        if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
        if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
        if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;

        if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
        if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
        if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;

        if ( _glExtensionCompressedTextureS3TC !== undefined ) {

            if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
            if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
            if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
            if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;

        }

        return 0;

    };

    // Allocations

    function allocateBones ( object ) {

        if ( _supportsBoneTextures && object && object.useVertexTexture ) {

            return 1024;

        } else {

            // default for when object is not specified
            // ( for example when prebuilding shader
            //   to be used with multiple objects )
            //
            //     - leave some extra space for other uniforms
            //  - limit here is ANGLE's 254 max uniform vectors
            //    (up to 54 should be safe)

            var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
            var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );

            var maxBones = nVertexMatrices;

            if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {

                maxBones = Math.min( object.bones.length, maxBones );

                if ( maxBones < object.bones.length ) {

                    console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );

                }

            }

            return maxBones;

        }

    };

    function allocateLights ( lights ) {

        var l, ll, light, dirLights, pointLights, spotLights, hemiLights, maxDirLights, maxPointLights, maxSpotLights, maxHemiLights;

        dirLights = pointLights = spotLights = hemiLights = maxDirLights = maxPointLights = maxSpotLights = maxHemiLights = 0;

        for ( l = 0, ll = lights.length; l < ll; l ++ ) {

            light = lights[ l ];

            if ( light.onlyShadow ) continue;

            if ( light instanceof THREE.DirectionalLight ) dirLights ++;
            if ( light instanceof THREE.PointLight ) pointLights ++;
            if ( light instanceof THREE.SpotLight ) spotLights ++;
            if ( light instanceof THREE.HemisphereLight ) hemiLights ++;

        }

        if ( ( pointLights + spotLights + dirLights + hemiLights) <= _maxLights ) {

            maxDirLights = dirLights;
            maxPointLights = pointLights;
            maxSpotLights = spotLights;
            maxHemiLights = hemiLights;

        } else {

            maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
            maxPointLights = _maxLights - maxDirLights;

            // these are not really correct

            maxSpotLights = maxPointLights;
            maxHemiLights = maxDirLights;

        }

        return { 'directional' : maxDirLights, 'point' : maxPointLights, 'spot': maxSpotLights, 'hemi': maxHemiLights };

    };

    function allocateShadows ( lights ) {

        var l, ll, light, maxShadows = 0;

        for ( l = 0, ll = lights.length; l < ll; l++ ) {

            light = lights[ l ];

            if ( ! light.castShadow ) continue;

            if ( light instanceof THREE.SpotLight ) maxShadows ++;
            if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;

        }

        return maxShadows;

    };

    // Initialization

    function initGL () {

        try {

            if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {

                throw 'Error creating WebGL context.';

            }

        } catch ( error ) {

            console.error( error );

        }

        _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
        _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );

        _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
                                               _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
                                               _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );


        _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
                                            _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
                                            _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );

        if ( ! _glExtensionTextureFloat ) {

            console.log( 'THREE.WebGLRenderer: Float textures not supported.' );

        }

        if ( ! _glExtensionStandardDerivatives ) {

            console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );

        }

        if ( ! _glExtensionTextureFilterAnisotropic ) {

            console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );

        }

        if ( ! _glExtensionCompressedTextureS3TC ) {

            console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );

        }

    };

    function setDefaultGLState () {

        _gl.clearColor( 0, 0, 0, 1 );
        _gl.clearDepth( 1 );
        _gl.clearStencil( 0 );

        _gl.enable( _gl.DEPTH_TEST );
        _gl.depthFunc( _gl.LEQUAL );

        _gl.frontFace( _gl.CCW );
        _gl.cullFace( _gl.BACK );
        _gl.enable( _gl.CULL_FACE );

        _gl.enable( _gl.BLEND );
        _gl.blendEquation( _gl.FUNC_ADD );
        _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );

        _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );

    };

    // default plugins (order is important)

    this.shadowMapPlugin = new THREE.ShadowMapPlugin();
    this.addPrePlugin( this.shadowMapPlugin );

    this.addPostPlugin( new THREE.SpritePlugin() );
    this.addPostPlugin( new THREE.LensFlarePlugin() );

};
/**
 * @author szimek / https://github.com/szimek/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.WebGLRenderTarget = function ( width, height, options ) {

    this.width = width;
    this.height = height;

    options = options || {};

    this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
    this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;

    this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
    this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;

    this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;

    this.offset = new THREE.Vector2( 0, 0 );
    this.repeat = new THREE.Vector2( 1, 1 );

    this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
    this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;

    this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
    this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;

    this.generateMipmaps = true;

};

THREE.WebGLRenderTarget.prototype.clone = function() {

    var tmp = new THREE.WebGLRenderTarget( this.width, this.height );

    tmp.wrapS = this.wrapS;
    tmp.wrapT = this.wrapT;

    tmp.magFilter = this.magFilter;
    tmp.anisotropy = this.anisotropy;

    tmp.minFilter = this.minFilter;

    tmp.offset.copy( this.offset );
    tmp.repeat.copy( this.repeat );

    tmp.format = this.format;
    tmp.type = this.type;

    tmp.depthBuffer = this.depthBuffer;
    tmp.stencilBuffer = this.stencilBuffer;

    tmp.generateMipmaps = this.generateMipmaps;

    return tmp;

};
/**
 * @author alteredq / http://alteredqualia.com
 */

THREE.WebGLRenderTargetCube = function ( width, height, options ) {

    THREE.WebGLRenderTarget.call( this, width, height, options );

    this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5

};

THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.RenderableVertex = function () {

    this.positionWorld = new THREE.Vector3();
    this.positionScreen = new THREE.Vector4();

    this.visible = true;

};

THREE.RenderableVertex.prototype.copy = function ( vertex ) {

    this.positionWorld.copy( vertex.positionWorld );
    this.positionScreen.copy( vertex.positionScreen );

}
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.RenderableFace3 = function () {

    this.v1 = new THREE.RenderableVertex();
    this.v2 = new THREE.RenderableVertex();
    this.v3 = new THREE.RenderableVertex();

    this.centroidWorld = new THREE.Vector3();
    this.centroidScreen = new THREE.Vector3();

    this.normalWorld = new THREE.Vector3();
    this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
    this.vertexNormalsLength = 0;

    this.material = null;
    this.uvs = [[]];

    this.z = null;

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.RenderableFace4 = function () {

    this.v1 = new THREE.RenderableVertex();
    this.v2 = new THREE.RenderableVertex();
    this.v3 = new THREE.RenderableVertex();
    this.v4 = new THREE.RenderableVertex();

    this.centroidWorld = new THREE.Vector3();
    this.centroidScreen = new THREE.Vector3();

    this.normalWorld = new THREE.Vector3();
    this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
    this.vertexNormalsLength = 0;

    this.material = null;
    this.uvs = [[]];

    this.z = null;

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.RenderableObject = function () {

    this.object = null;
    this.z = null;

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.RenderableParticle = function () {

    this.object = null;

    this.x = null;
    this.y = null;
    this.z = null;

    this.rotation = null;
    this.scale = new THREE.Vector2();

    this.material = null;

};
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.RenderableLine = function () {

    this.z = null;

    this.v1 = new THREE.RenderableVertex();
    this.v2 = new THREE.RenderableVertex();

    this.material = null;

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.ColorUtils = {

    adjustHSV : function ( color, h, s, v ) {

        var hsv = THREE.ColorUtils.__hsv;

        THREE.ColorUtils.rgbToHsv( color, hsv );

        hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
        hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
        hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );

        color.setHSV( hsv.h, hsv.s, hsv.v );

    },

    // based on MochiKit implementation by Bob Ippolito

    rgbToHsv : function ( color, hsv ) {

        var r = color.r;
        var g = color.g;
        var b = color.b;

        var max = Math.max( Math.max( r, g ), b );
        var min = Math.min( Math.min( r, g ), b );

        var hue;
        var saturation;
        var value = max;

        if ( min === max )    {

            hue = 0;
            saturation = 0;

        } else {

            var delta = ( max - min );
            saturation = delta / max;

            if ( r === max ) {

                hue = ( g - b ) / delta;

            } else if ( g === max ) {

                hue = 2 + ( ( b - r ) / delta );

            } else    {

                hue = 4 + ( ( r - g ) / delta );
            }

            hue /= 6;

            if ( hue < 0 ) {

                hue += 1;

            }

            if ( hue > 1 ) {

                hue -= 1;

            }

        }

        if ( hsv === undefined ) {

            hsv = { h: 0, s: 0, v: 0 };

        }

        hsv.h = hue;
        hsv.s = saturation;
        hsv.v = value;

        return hsv;

    }

};

THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.GeometryUtils = {

    // Merge two geometries or geometry and geometry from object (using object's transform)

    merge: function ( geometry1, object2 /* mesh | geometry */ ) {

        var matrix, matrixRotation,
        vertexOffset = geometry1.vertices.length,
        uvPosition = geometry1.faceVertexUvs[ 0 ].length,
        geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
        vertices1 = geometry1.vertices,
        vertices2 = geometry2.vertices,
        faces1 = geometry1.faces,
        faces2 = geometry2.faces,
        uvs1 = geometry1.faceVertexUvs[ 0 ],
        uvs2 = geometry2.faceVertexUvs[ 0 ];

        var geo1MaterialsMap = {};

        for ( var i = 0; i < geometry1.materials.length; i ++ ) {

            var id = geometry1.materials[ i ].id;

            geo1MaterialsMap[ id ] = i;

        }

        if ( object2 instanceof THREE.Mesh ) {

            object2.matrixAutoUpdate && object2.updateMatrix();

            matrix = object2.matrix;
            matrixRotation = new THREE.Matrix4();
            matrixRotation.extractRotation( matrix, object2.scale );

        }

        // vertices

        for ( var i = 0, il = vertices2.length; i < il; i ++ ) {

            var vertex = vertices2[ i ];

            var vertexCopy = vertex.clone();

            if ( matrix ) matrix.multiplyVector3( vertexCopy );

            vertices1.push( vertexCopy );

        }

        // faces

        for ( i = 0, il = faces2.length; i < il; i ++ ) {

            var face = faces2[ i ], faceCopy, normal, color,
            faceVertexNormals = face.vertexNormals,
            faceVertexColors = face.vertexColors;

            if ( face instanceof THREE.Face3 ) {

                faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );

            } else if ( face instanceof THREE.Face4 ) {

                faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );

            }

            faceCopy.normal.copy( face.normal );

            if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );

            for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {

                normal = faceVertexNormals[ j ].clone();

                if ( matrixRotation ) matrixRotation.multiplyVector3( normal );

                faceCopy.vertexNormals.push( normal );

            }

            faceCopy.color.copy( face.color );

            for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {

                color = faceVertexColors[ j ];
                faceCopy.vertexColors.push( color.clone() );

            }

            if ( face.materialIndex !== undefined ) {

                var material2 = geometry2.materials[ face.materialIndex ];
                var materialId2 = material2.id;

                var materialIndex = geo1MaterialsMap[ materialId2 ];

                if ( materialIndex === undefined ) {

                    materialIndex = geometry1.materials.length;
                    geo1MaterialsMap[ materialId2 ] = materialIndex;

                    geometry1.materials.push( material2 );

                }

                faceCopy.materialIndex = materialIndex;

            }

            faceCopy.centroid.copy( face.centroid );
            if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );

            faces1.push( faceCopy );

        }

        // uvs

        for ( i = 0, il = uvs2.length; i < il; i ++ ) {

            var uv = uvs2[ i ], uvCopy = [];

            for ( var j = 0, jl = uv.length; j < jl; j ++ ) {

                uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );

            }

            uvs1.push( uvCopy );

        }

    },

    clone: function ( geometry ) {

        var cloneGeo = new THREE.Geometry();

        var i, il;

        var vertices = geometry.vertices,
            faces = geometry.faces,
            uvs = geometry.faceVertexUvs[ 0 ];

        // materials

        if ( geometry.materials ) {

            cloneGeo.materials = geometry.materials.slice();

        }

        // vertices

        for ( i = 0, il = vertices.length; i < il; i ++ ) {

            var vertex = vertices[ i ];

            cloneGeo.vertices.push( vertex.clone() );

        }

        // faces

        for ( i = 0, il = faces.length; i < il; i ++ ) {

            var face = faces[ i ];

            cloneGeo.faces.push( face.clone() );

        }

        // uvs

        for ( i = 0, il = uvs.length; i < il; i ++ ) {

            var uv = uvs[ i ], uvCopy = [];

            for ( var j = 0, jl = uv.length; j < jl; j ++ ) {

                uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );

            }

            cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );

        }

        return cloneGeo;

    },

    // Get random point in triangle (via barycentric coordinates)
    //     (uniform distribution)
    //     http://www.cgafaq.info/wiki/Random_Point_In_Triangle

    randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {

        var a, b, c,
            point = new THREE.Vector3(),
            tmp = THREE.GeometryUtils.__v1;

        a = THREE.GeometryUtils.random();
        b = THREE.GeometryUtils.random();

        if ( ( a + b ) > 1 ) {

            a = 1 - a;
            b = 1 - b;

        }

        c = 1 - a - b;

        point.copy( vectorA );
        point.multiplyScalar( a );

        tmp.copy( vectorB );
        tmp.multiplyScalar( b );

        point.addSelf( tmp );

        tmp.copy( vectorC );
        tmp.multiplyScalar( c );

        point.addSelf( tmp );

        return point;

    },

    // Get random point in face (triangle / quad)
    // (uniform distribution)

    randomPointInFace: function ( face, geometry, useCachedAreas ) {

        var vA, vB, vC, vD;

        if ( face instanceof THREE.Face3 ) {

            vA = geometry.vertices[ face.a ];
            vB = geometry.vertices[ face.b ];
            vC = geometry.vertices[ face.c ];

            return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );

        } else if ( face instanceof THREE.Face4 ) {

            vA = geometry.vertices[ face.a ];
            vB = geometry.vertices[ face.b ];
            vC = geometry.vertices[ face.c ];
            vD = geometry.vertices[ face.d ];

            var area1, area2;

            if ( useCachedAreas ) {

                if ( face._area1 && face._area2 ) {

                    area1 = face._area1;
                    area2 = face._area2;

                } else {

                    area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
                    area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );

                    face._area1 = area1;
                    face._area2 = area2;

                }

            } else {

                area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
                area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );

            }

            var r = THREE.GeometryUtils.random() * ( area1 + area2 );

            if ( r < area1 ) {

                return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );

            } else {

                return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );

            }

        }

    },

    // Get uniformly distributed random points in mesh
    //     - create array with cumulative sums of face areas
    //  - pick random number from 0 to total area
    //  - find corresponding place in area array by binary search
    //    - get random point in face

    randomPointsInGeometry: function ( geometry, n ) {

        var face, i,
            faces = geometry.faces,
            vertices = geometry.vertices,
            il = faces.length,
            totalArea = 0,
            cumulativeAreas = [],
            vA, vB, vC, vD;

        // precompute face areas

        for ( i = 0; i < il; i ++ ) {

            face = faces[ i ];

            if ( face instanceof THREE.Face3 ) {

                vA = vertices[ face.a ];
                vB = vertices[ face.b ];
                vC = vertices[ face.c ];

                face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );

            } else if ( face instanceof THREE.Face4 ) {

                vA = vertices[ face.a ];
                vB = vertices[ face.b ];
                vC = vertices[ face.c ];
                vD = vertices[ face.d ];

                face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
                face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );

                face._area = face._area1 + face._area2;

            }

            totalArea += face._area;

            cumulativeAreas[ i ] = totalArea;

        }

        // binary search cumulative areas array

        function binarySearchIndices( value ) {

            function binarySearch( start, end ) {

                // return closest larger index
                // if exact number is not found

                if ( end < start )
                    return start;

                var mid = start + Math.floor( ( end - start ) / 2 );

                if ( cumulativeAreas[ mid ] > value ) {

                    return binarySearch( start, mid - 1 );

                } else if ( cumulativeAreas[ mid ] < value ) {

                    return binarySearch( mid + 1, end );

                } else {

                    return mid;

                }

            }

            var result = binarySearch( 0, cumulativeAreas.length - 1 )
            return result;

        }

        // pick random face weighted by face area

        var r, index,
            result = [];

        var stats = {};

        for ( i = 0; i < n; i ++ ) {

            r = THREE.GeometryUtils.random() * totalArea;

            index = binarySearchIndices( r );

            result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );

            if ( ! stats[ index ] ) {

                stats[ index ] = 1;

            } else {

                stats[ index ] += 1;

            }

        }

        return result;

    },

    // Get triangle area (by Heron's formula)
    //     http://en.wikipedia.org/wiki/Heron%27s_formula

    triangleArea: function ( vectorA, vectorB, vectorC ) {

        var s, a, b, c,
            tmp = THREE.GeometryUtils.__v1;

        tmp.sub( vectorA, vectorB );
        a = tmp.length();

        tmp.sub( vectorA, vectorC );
        b = tmp.length();

        tmp.sub( vectorB, vectorC );
        c = tmp.length();

        s = 0.5 * ( a + b + c );

        return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );

    },

    // Center geometry so that 0,0,0 is in center of bounding box

    center: function ( geometry ) {

        geometry.computeBoundingBox();

        var bb = geometry.boundingBox;

        var offset = new THREE.Vector3();

        offset.add( bb.min, bb.max );
        offset.multiplyScalar( -0.5 );

        geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
        geometry.computeBoundingBox();

        return offset;

    },

    // Normalize UVs to be from <0,1>
    // (for now just the first set of UVs)

    normalizeUVs: function ( geometry ) {

        var uvSet = geometry.faceVertexUvs[ 0 ];

        for ( var i = 0, il = uvSet.length; i < il; i ++ ) {

            var uvs = uvSet[ i ];

            for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {

                // texture repeat

                if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
                if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );

            }

        }

    },

    triangulateQuads: function ( geometry ) {

        var i, il, j, jl;

        var faces = [];
        var faceUvs = [];
        var faceVertexUvs = [];

        for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {

            faceUvs[ i ] = [];

        }

        for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {

            faceVertexUvs[ i ] = [];

        }

        for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {

            var face = geometry.faces[ i ];

            if ( face instanceof THREE.Face4 ) {

                var a = face.a;
                var b = face.b;
                var c = face.c;
                var d = face.d;

                var triA = new THREE.Face3();
                var triB = new THREE.Face3();

                triA.color.copy( face.color );
                triB.color.copy( face.color );

                triA.materialIndex = face.materialIndex;
                triB.materialIndex = face.materialIndex;

                triA.a = a;
                triA.b = b;
                triA.c = d;

                triB.a = b;
                triB.b = c;
                triB.c = d;

                if ( face.vertexColors.length === 4 ) {

                    triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
                    triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
                    triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();

                    triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
                    triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
                    triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();

                }

                faces.push( triA, triB );

                for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {

                    if ( geometry.faceVertexUvs[ j ].length ) {

                        var uvs = geometry.faceVertexUvs[ j ][ i ];

                        var uvA = uvs[ 0 ];
                        var uvB = uvs[ 1 ];
                        var uvC = uvs[ 2 ];
                        var uvD = uvs[ 3 ];

                        var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
                        var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];

                        faceVertexUvs[ j ].push( uvsTriA, uvsTriB );

                    }

                }

                for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {

                    if ( geometry.faceUvs[ j ].length ) {

                        var faceUv = geometry.faceUvs[ j ][ i ];

                        faceUvs[ j ].push( faceUv, faceUv );

                    }

                }

            } else {

                faces.push( face );

                for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {

                    faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );

                }

                for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {

                    faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );

                }

            }

        }

        geometry.faces = faces;
        geometry.faceUvs = faceUvs;
        geometry.faceVertexUvs = faceVertexUvs;

        geometry.computeCentroids();
        geometry.computeFaceNormals();
        geometry.computeVertexNormals();

        if ( geometry.hasTangents ) geometry.computeTangents();

    },

    // Make all faces use unique vertices
    // so that each face can be separated from others

    explode: function( geometry ) {

        var vertices = [];

        for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {

            var n = vertices.length;

            var face = geometry.faces[ i ];

            if ( face instanceof THREE.Face4 ) {

                var a = face.a;
                var b = face.b;
                var c = face.c;
                var d = face.d;

                var va = geometry.vertices[ a ];
                var vb = geometry.vertices[ b ];
                var vc = geometry.vertices[ c ];
                var vd = geometry.vertices[ d ];

                vertices.push( va.clone() );
                vertices.push( vb.clone() );
                vertices.push( vc.clone() );
                vertices.push( vd.clone() );

                face.a = n;
                face.b = n + 1;
                face.c = n + 2;
                face.d = n + 3;

            } else {

                var a = face.a;
                var b = face.b;
                var c = face.c;

                var va = geometry.vertices[ a ];
                var vb = geometry.vertices[ b ];
                var vc = geometry.vertices[ c ];

                vertices.push( va.clone() );
                vertices.push( vb.clone() );
                vertices.push( vc.clone() );

                face.a = n;
                face.b = n + 1;
                face.c = n + 2;

            }

        }

        geometry.vertices = vertices;
        delete geometry.__tmpVertices;

    },

    // Break faces with edges longer than maxEdgeLength
    // - not recursive

    tessellate: function ( geometry, maxEdgeLength ) {

        var i, il, face,
        a, b, c, d,
        va, vb, vc, vd,
        dab, dbc, dac, dcd, dad,
        m, m1, m2,
        vm, vm1, vm2,
        vnm, vnm1, vnm2,
        vcm, vcm1, vcm2,
        triA, triB,
        quadA, quadB,
        edge;

        var faces = [];
        var faceVertexUvs = [];

        for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {

            faceVertexUvs[ i ] = [];

        }

        for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {

            face = geometry.faces[ i ];

            if ( face instanceof THREE.Face3 ) {

                a = face.a;
                b = face.b;
                c = face.c;

                va = geometry.vertices[ a ];
                vb = geometry.vertices[ b ];
                vc = geometry.vertices[ c ];

                dab = va.distanceTo( vb );
                dbc = vb.distanceTo( vc );
                dac = va.distanceTo( vc );

                if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {

                    m = geometry.vertices.length;

                    triA = face.clone();
                    triB = face.clone();

                    if ( dab >= dbc && dab >= dac ) {

                        vm = va.clone();
                        vm.lerpSelf( vb, 0.5 );

                        triA.a = a;
                        triA.b = m;
                        triA.c = c;

                        triB.a = m;
                        triB.b = b;
                        triB.c = c;

                        if ( face.vertexNormals.length === 3 ) {

                            vnm = face.vertexNormals[ 0 ].clone();
                            vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );

                            triA.vertexNormals[ 1 ].copy( vnm );
                            triB.vertexNormals[ 0 ].copy( vnm );

                        }

                        if ( face.vertexColors.length === 3 ) {

                            vcm = face.vertexColors[ 0 ].clone();
                            vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );

                            triA.vertexColors[ 1 ].copy( vcm );
                            triB.vertexColors[ 0 ].copy( vcm );

                        }

                        edge = 0;

                    } else if ( dbc >= dab && dbc >= dac ) {

                        vm = vb.clone();
                        vm.lerpSelf( vc, 0.5 );

                        triA.a = a;
                        triA.b = b;
                        triA.c = m;

                        triB.a = m;
                        triB.b = c;
                        triB.c = a;

                        if ( face.vertexNormals.length === 3 ) {

                            vnm = face.vertexNormals[ 1 ].clone();
                            vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );

                            triA.vertexNormals[ 2 ].copy( vnm );

                            triB.vertexNormals[ 0 ].copy( vnm );
                            triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
                            triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );

                        }

                        if ( face.vertexColors.length === 3 ) {

                            vcm = face.vertexColors[ 1 ].clone();
                            vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );

                            triA.vertexColors[ 2 ].copy( vcm );

                            triB.vertexColors[ 0 ].copy( vcm );
                            triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
                            triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );

                        }

                        edge = 1;

                    } else {

                        vm = va.clone();
                        vm.lerpSelf( vc, 0.5 );

                        triA.a = a;
                        triA.b = b;
                        triA.c = m;

                        triB.a = m;
                        triB.b = b;
                        triB.c = c;

                        if ( face.vertexNormals.length === 3 ) {

                            vnm = face.vertexNormals[ 0 ].clone();
                            vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );

                            triA.vertexNormals[ 2 ].copy( vnm );
                            triB.vertexNormals[ 0 ].copy( vnm );

                        }

                        if ( face.vertexColors.length === 3 ) {

                            vcm = face.vertexColors[ 0 ].clone();
                            vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );

                            triA.vertexColors[ 2 ].copy( vcm );
                            triB.vertexColors[ 0 ].copy( vcm );

                        }

                        edge = 2;

                    }

                    faces.push( triA, triB );
                    geometry.vertices.push( vm );

                    var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;

                    for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {

                        if ( geometry.faceVertexUvs[ j ].length ) {

                            uvs = geometry.faceVertexUvs[ j ][ i ];

                            uvA = uvs[ 0 ];
                            uvB = uvs[ 1 ];
                            uvC = uvs[ 2 ];

                            // AB

                            if ( edge === 0 ) {

                                uvM = uvA.clone();
                                uvM.lerpSelf( uvB, 0.5 );

                                uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
                                uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];

                            // BC

                            } else if ( edge === 1 ) {

                                uvM = uvB.clone();
                                uvM.lerpSelf( uvC, 0.5 );

                                uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
                                uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];

                            // AC

                            } else {

                                uvM = uvA.clone();
                                uvM.lerpSelf( uvC, 0.5 );

                                uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
                                uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];

                            }

                            faceVertexUvs[ j ].push( uvsTriA, uvsTriB );

                        }

                    }

                } else {

                    faces.push( face );

                    for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {

                        faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );

                    }

                }

            } else {

                a = face.a;
                b = face.b;
                c = face.c;
                d = face.d;

                va = geometry.vertices[ a ];
                vb = geometry.vertices[ b ];
                vc = geometry.vertices[ c ];
                vd = geometry.vertices[ d ];

                dab = va.distanceTo( vb );
                dbc = vb.distanceTo( vc );
                dcd = vc.distanceTo( vd );
                dad = va.distanceTo( vd );

                if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {

                    m1 = geometry.vertices.length;
                    m2 = geometry.vertices.length + 1;

                    quadA = face.clone();
                    quadB = face.clone();

                    if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {

                        vm1 = va.clone();
                        vm1.lerpSelf( vb, 0.5 );

                        vm2 = vc.clone();
                        vm2.lerpSelf( vd, 0.5 );

                        quadA.a = a;
                        quadA.b = m1;
                        quadA.c = m2;
                        quadA.d = d;

                        quadB.a = m1;
                        quadB.b = b;
                        quadB.c = c;
                        quadB.d = m2;

                        if ( face.vertexNormals.length === 4 ) {

                            vnm1 = face.vertexNormals[ 0 ].clone();
                            vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );

                            vnm2 = face.vertexNormals[ 2 ].clone();
                            vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );

                            quadA.vertexNormals[ 1 ].copy( vnm1 );
                            quadA.vertexNormals[ 2 ].copy( vnm2 );

                            quadB.vertexNormals[ 0 ].copy( vnm1 );
                            quadB.vertexNormals[ 3 ].copy( vnm2 );

                        }

                        if ( face.vertexColors.length === 4 ) {

                            vcm1 = face.vertexColors[ 0 ].clone();
                            vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );

                            vcm2 = face.vertexColors[ 2 ].clone();
                            vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );

                            quadA.vertexColors[ 1 ].copy( vcm1 );
                            quadA.vertexColors[ 2 ].copy( vcm2 );

                            quadB.vertexColors[ 0 ].copy( vcm1 );
                            quadB.vertexColors[ 3 ].copy( vcm2 );

                        }

                        edge = 0;

                    } else {

                        vm1 = vb.clone();
                        vm1.lerpSelf( vc, 0.5 );

                        vm2 = vd.clone();
                        vm2.lerpSelf( va, 0.5 );

                        quadA.a = a;
                        quadA.b = b;
                        quadA.c = m1;
                        quadA.d = m2;

                        quadB.a = m2;
                        quadB.b = m1;
                        quadB.c = c;
                        quadB.d = d;

                        if ( face.vertexNormals.length === 4 ) {

                            vnm1 = face.vertexNormals[ 1 ].clone();
                            vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );

                            vnm2 = face.vertexNormals[ 3 ].clone();
                            vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );

                            quadA.vertexNormals[ 2 ].copy( vnm1 );
                            quadA.vertexNormals[ 3 ].copy( vnm2 );

                            quadB.vertexNormals[ 0 ].copy( vnm2 );
                            quadB.vertexNormals[ 1 ].copy( vnm1 );

                        }

                        if ( face.vertexColors.length === 4 ) {

                            vcm1 = face.vertexColors[ 1 ].clone();
                            vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );

                            vcm2 = face.vertexColors[ 3 ].clone();
                            vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );

                            quadA.vertexColors[ 2 ].copy( vcm1 );
                            quadA.vertexColors[ 3 ].copy( vcm2 );

                            quadB.vertexColors[ 0 ].copy( vcm2 );
                            quadB.vertexColors[ 1 ].copy( vcm1 );

                        }

                        edge = 1;

                    }

                    faces.push( quadA, quadB );
                    geometry.vertices.push( vm1, vm2 );

                    var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;

                    for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {

                        if ( geometry.faceVertexUvs[ j ].length ) {

                            uvs = geometry.faceVertexUvs[ j ][ i ];

                            uvA = uvs[ 0 ];
                            uvB = uvs[ 1 ];
                            uvC = uvs[ 2 ];
                            uvD = uvs[ 3 ];

                            // AB + CD

                            if ( edge === 0 ) {

                                uvM1 = uvA.clone();
                                uvM1.lerpSelf( uvB, 0.5 );

                                uvM2 = uvC.clone();
                                uvM2.lerpSelf( uvD, 0.5 );

                                uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
                                uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];

                            // BC + AD

                            } else {

                                uvM1 = uvB.clone();
                                uvM1.lerpSelf( uvC, 0.5 );

                                uvM2 = uvD.clone();
                                uvM2.lerpSelf( uvA, 0.5 );

                                uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
                                uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];

                            }

                            faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );

                        }

                    }

                } else {

                    faces.push( face );

                    for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {

                        faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );

                    }

                }

            }

        }

        geometry.faces = faces;
        geometry.faceVertexUvs = faceVertexUvs;

    }

};

THREE.GeometryUtils.random = THREE.Math.random16;

THREE.GeometryUtils.__v1 = new THREE.Vector3();
/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 */

THREE.ImageUtils = {

    crossOrigin: 'anonymous',

    loadTexture: function ( url, mapping, onLoad, onError ) {

        var image = new Image();
        var texture = new THREE.Texture( image, mapping );

        var loader = new THREE.ImageLoader();

        loader.addEventListener( 'load', function ( event ) {

            texture.image = event.content;
            texture.needsUpdate = true;

            if ( onLoad ) onLoad( texture );

        } );

        loader.addEventListener( 'error', function ( event ) {

            if ( onError ) onError( event.message );

        } );

        loader.crossOrigin = this.crossOrigin;
        loader.load( url, image );

        return texture;

    },

    loadCompressedTexture: function ( url, mapping, onLoad, onError ) {

        var texture = new THREE.CompressedTexture();
        texture.mapping = mapping;

        var request = new XMLHttpRequest();

        request.onload = function () {

            var buffer = request.response;
            var dds = THREE.ImageUtils.parseDDS( buffer, true );

            texture.format = dds.format;

            texture.mipmaps = dds.mipmaps;
            texture.image.width = dds.width;
            texture.image.height = dds.height;

            // gl.generateMipmap fails for compressed textures
            // mipmaps must be embedded in the DDS file
            // or texture filters must not use mipmapping

            texture.generateMipmaps = false;

            texture.needsUpdate = true;

            if ( onLoad ) onLoad( texture );

        }

        request.onerror = onError;

        request.open( 'GET', url, true );
        request.responseType = "arraybuffer";
        request.send( null );

        return texture;

    },

    loadTextureCube: function ( array, mapping, onLoad, onError ) {

        var images = [];
        images.loadCount = 0;

        var texture = new THREE.Texture();
        texture.image = images;
        if ( mapping !== undefined ) texture.mapping = mapping;

        // no flipping needed for cube textures

        texture.flipY = false;

        for ( var i = 0, il = array.length; i < il; ++ i ) {

            var cubeImage = new Image();
            images[ i ] = cubeImage;

            cubeImage.onload = function () {

                images.loadCount += 1;

                if ( images.loadCount === 6 ) {

                    texture.needsUpdate = true;
                    if ( onLoad ) onLoad();

                }

            };

            cubeImage.onerror = onError;

            cubeImage.crossOrigin = this.crossOrigin;
            cubeImage.src = array[ i ];

        }

        return texture;

    },

    loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {

        var images = [];
        images.loadCount = 0;

        var texture = new THREE.CompressedTexture();
        texture.image = images;
        if ( mapping !== undefined ) texture.mapping = mapping;

        // no flipping for cube textures
        // (also flipping doesn't work for compressed textures )

        texture.flipY = false;

        // can't generate mipmaps for compressed textures
        // mips must be embedded in DDS files

        texture.generateMipmaps = false;

        var generateCubeFaceCallback = function ( rq, img ) {

            return function () {

                var buffer = rq.response;
                var dds = THREE.ImageUtils.parseDDS( buffer, true );

                img.format = dds.format;

                img.mipmaps = dds.mipmaps;
                img.width = dds.width;
                img.height = dds.height;

                images.loadCount += 1;

                if ( images.loadCount === 6 ) {

                    texture.format = dds.format;
                    texture.needsUpdate = true;
                    if ( onLoad ) onLoad();

                }

            }

        }

        for ( var i = 0, il = array.length; i < il; ++ i ) {

            var cubeImage = {};
            images[ i ] = cubeImage;

            var request = new XMLHttpRequest();

            request.onload = generateCubeFaceCallback( request, cubeImage );
            request.onerror = onError;

            var url = array[ i ];

            request.open( 'GET', url, true );
            request.responseType = "arraybuffer";
            request.send( null );

        }

        return texture;

    },

    parseDDS: function ( buffer, loadMipmaps ) {

        var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };

        // Adapted from @toji's DDS utils
        //    https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js

        // All values and structures referenced from:
        // http://msdn.microsoft.com/en-us/library/bb943991.aspx/

        var DDS_MAGIC = 0x20534444;

        var DDSD_CAPS = 0x1,
            DDSD_HEIGHT = 0x2,
            DDSD_WIDTH = 0x4,
            DDSD_PITCH = 0x8,
            DDSD_PIXELFORMAT = 0x1000,
            DDSD_MIPMAPCOUNT = 0x20000,
            DDSD_LINEARSIZE = 0x80000,
            DDSD_DEPTH = 0x800000;

        var DDSCAPS_COMPLEX = 0x8,
            DDSCAPS_MIPMAP = 0x400000,
            DDSCAPS_TEXTURE = 0x1000;

        var DDSCAPS2_CUBEMAP = 0x200,
            DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
            DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
            DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
            DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
            DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
            DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
            DDSCAPS2_VOLUME = 0x200000;

        var DDPF_ALPHAPIXELS = 0x1,
            DDPF_ALPHA = 0x2,
            DDPF_FOURCC = 0x4,
            DDPF_RGB = 0x40,
            DDPF_YUV = 0x200,
            DDPF_LUMINANCE = 0x20000;

        function fourCCToInt32( value ) {

            return value.charCodeAt(0) +
                (value.charCodeAt(1) << 8) +
                (value.charCodeAt(2) << 16) +
                (value.charCodeAt(3) << 24);

        }

        function int32ToFourCC( value ) {

            return String.fromCharCode(
                value & 0xff,
                (value >> 8) & 0xff,
                (value >> 16) & 0xff,
                (value >> 24) & 0xff
            );
        }

        var FOURCC_DXT1 = fourCCToInt32("DXT1");
        var FOURCC_DXT3 = fourCCToInt32("DXT3");
        var FOURCC_DXT5 = fourCCToInt32("DXT5");

        var headerLengthInt = 31; // The header length in 32 bit ints

        // Offsets into the header array

        var off_magic = 0;

        var off_size = 1;
        var off_flags = 2;
        var off_height = 3;
        var off_width = 4;

        var off_mipmapCount = 7;

        var off_pfFlags = 20;
        var off_pfFourCC = 21;

        // Parse header

        var header = new Int32Array( buffer, 0, headerLengthInt );

        if ( header[ off_magic ] !== DDS_MAGIC ) {

            console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
            return dds;

        }

        if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {

            console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
            return dds;

        }

        var blockBytes;

        var fourCC = header[ off_pfFourCC ];

        switch ( fourCC ) {

            case FOURCC_DXT1:

                blockBytes = 8;
                dds.format = THREE.RGB_S3TC_DXT1_Format;
                break;

            case FOURCC_DXT3:

                blockBytes = 16;
                dds.format = THREE.RGBA_S3TC_DXT3_Format;
                break;

            case FOURCC_DXT5:

                blockBytes = 16;
                dds.format = THREE.RGBA_S3TC_DXT5_Format;
                break;

            default:

                console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
                return dds;

        }

        dds.mipmapCount = 1;

        if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {

            dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );

        }

        dds.width = header[ off_width ];
        dds.height = header[ off_height ];

        var dataOffset = header[ off_size ] + 4;

        // Extract mipmaps buffers

        var width = dds.width;
        var height = dds.height;

        for ( var i = 0; i < dds.mipmapCount; i ++ ) {

            var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
            var byteArray = new Uint8Array( buffer, dataOffset, dataLength );

            var mipmap = { "data": byteArray, "width": width, "height": height };
            dds.mipmaps.push( mipmap );

            dataOffset += dataLength;

            width = Math.max( width * 0.5, 1 );
            height = Math.max( height * 0.5, 1 );

        }

        return dds;

    },

    getNormalMap: function ( image, depth ) {

        // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/

        var cross = function ( a, b ) {

            return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ];

        }

        var subtract = function ( a, b ) {

            return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];

        }

        var normalize = function ( a ) {

            var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
            return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];

        }

        depth = depth | 1;

        var width = image.width;
        var height = image.height;

        var canvas = document.createElement( 'canvas' );
        canvas.width = width;
        canvas.height = height;

        var context = canvas.getContext( '2d' );
        context.drawImage( image, 0, 0 );

        var data = context.getImageData( 0, 0, width, height ).data;
        var imageData = context.createImageData( width, height );
        var output = imageData.data;

        for ( var x = 0; x < width; x ++ ) {

            for ( var y = 0; y < height; y ++ ) {

                var ly = y - 1 < 0 ? 0 : y - 1;
                var uy = y + 1 > height - 1 ? height - 1 : y + 1;
                var lx = x - 1 < 0 ? 0 : x - 1;
                var ux = x + 1 > width - 1 ? width - 1 : x + 1;

                var points = [];
                var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
                points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
                points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
                points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
                points.push( [  1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
                points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
                points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
                points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
                points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );

                var normals = [];
                var num_points = points.length;

                for ( var i = 0; i < num_points; i ++ ) {

                    var v1 = points[ i ];
                    var v2 = points[ ( i + 1 ) % num_points ];
                    v1 = subtract( v1, origin );
                    v2 = subtract( v2, origin );
                    normals.push( normalize( cross( v1, v2 ) ) );

                }

                var normal = [ 0, 0, 0 ];

                for ( var i = 0; i < normals.length; i ++ ) {

                    normal[ 0 ] += normals[ i ][ 0 ];
                    normal[ 1 ] += normals[ i ][ 1 ];
                    normal[ 2 ] += normals[ i ][ 2 ];

                }

                normal[ 0 ] /= normals.length;
                normal[ 1 ] /= normals.length;
                normal[ 2 ] /= normals.length;

                var idx = ( y * width + x ) * 4;

                output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
                output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
                output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
                output[ idx + 3 ] = 255;

            }

        }

        context.putImageData( imageData, 0, 0 );

        return canvas;

    },

    generateDataTexture: function ( width, height, color ) {

        var size = width * height;
        var data = new Uint8Array( 3 * size );

        var r = Math.floor( color.r * 255 );
        var g = Math.floor( color.g * 255 );
        var b = Math.floor( color.b * 255 );

        for ( var i = 0; i < size; i ++ ) {

            data[ i * 3 ]       = r;
            data[ i * 3 + 1 ] = g;
            data[ i * 3 + 2 ] = b;

        }

        var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
        texture.needsUpdate = true;

        return texture;

    }

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.SceneUtils = {

    showHierarchy : function ( root, visible ) {

        THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );

    },

    traverseHierarchy : function ( root, callback ) {

        var n, i, l = root.children.length;

        for ( i = 0; i < l; i ++ ) {

            n = root.children[ i ];

            callback( n );

            THREE.SceneUtils.traverseHierarchy( n, callback );

        }

    },

    createMultiMaterialObject : function ( geometry, materials ) {

        var i, il = materials.length,
            group = new THREE.Object3D();

        for ( i = 0; i < il; i ++ ) {

            var object = new THREE.Mesh( geometry, materials[ i ] );
            group.add( object );

        }

        return group;

    },

    cloneObject: function ( source ) {

        var object;

        // subclass specific properties
        // (must process in order from more specific subclasses to more abstract classes)

        if ( source instanceof THREE.MorphAnimMesh ) {

            object = new THREE.MorphAnimMesh( source.geometry, source.material );

            object.duration = source.duration;
            object.mirroredLoop = source.mirroredLoop;
            object.time = source.time;

            object.lastKeyframe = source.lastKeyframe;
            object.currentKeyframe = source.currentKeyframe;

            object.direction = source.direction;
            object.directionBackwards = source.directionBackwards;

        } else if ( source instanceof THREE.SkinnedMesh ) {

            object = new THREE.SkinnedMesh( source.geometry, source.material, source.useVertexTexture );

        } else if ( source instanceof THREE.Mesh ) {

            object = new THREE.Mesh( source.geometry, source.material );

        } else if ( source instanceof THREE.Line ) {

            object = new THREE.Line( source.geometry, source.material, source.type );

        } else if ( source instanceof THREE.Ribbon ) {

            object = new THREE.Ribbon( source.geometry, source.material );

        } else if ( source instanceof THREE.ParticleSystem ) {

            object = new THREE.ParticleSystem( source.geometry, source.material );
            object.sortParticles = source.sortParticles;

        } else if ( source instanceof THREE.Particle ) {

            object = new THREE.Particle( source.material );

        } else if ( source instanceof THREE.Sprite ) {

            object = new THREE.Sprite( {} );

            object.color.copy( source.color );
            object.map = source.map;
            object.blending = source.blending;

            object.useScreenCoordinates = source.useScreenCoordinates;
            object.mergeWith3D = source.mergeWith3D;
            object.affectedByDistance = source.affectedByDistance;
            object.scaleByViewport = source.scaleByViewport;
            object.alignment = source.alignment;

            object.rotation3d.copy( source.rotation3d );
            object.rotation = source.rotation;
            object.opacity = source.opacity;

            object.uvOffset.copy( source.uvOffset );
            object.uvScale.copy( source.uvScale);

        } else if ( source instanceof THREE.LOD ) {

            object = new THREE.LOD();

        /*
        } else if ( source instanceof THREE.MarchingCubes ) {

            object = new THREE.MarchingCubes( source.resolution, source.material );
            object.field.set( source.field );
            object.isolation = source.isolation;
        */

        } else if ( source instanceof THREE.Object3D ) {

            object = new THREE.Object3D();

        }

        // base class properties

        object.name = source.name;

        object.parent = source.parent;

        object.up.copy( source.up );

        object.position.copy( source.position );

        // because of Sprite madness

        if ( object.rotation instanceof THREE.Vector3 )
            object.rotation.copy( source.rotation );

        object.eulerOrder = source.eulerOrder;

        object.scale.copy( source.scale );

        object.dynamic = source.dynamic;

        object.renderDepth = source.renderDepth;

        object.rotationAutoUpdate = source.rotationAutoUpdate;

        object.matrix.copy( source.matrix );
        object.matrixWorld.copy( source.matrixWorld );
        object.matrixRotationWorld.copy( source.matrixRotationWorld );

        object.matrixAutoUpdate = source.matrixAutoUpdate;
        object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;

        object.quaternion.copy( source.quaternion );
        object.useQuaternion = source.useQuaternion;

        object.boundRadius = source.boundRadius;
        object.boundRadiusScale = source.boundRadiusScale;

        object.visible = source.visible;

        object.castShadow = source.castShadow;
        object.receiveShadow = source.receiveShadow;

        object.frustumCulled = source.frustumCulled;

        // children

        for ( var i = 0; i < source.children.length; i ++ ) {

            var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
            object.children[ i ] = child;

            child.parent = object;

        }

        // LODs need to be patched separately to use cloned children

        if ( source instanceof THREE.LOD ) {

            for ( var i = 0; i < source.LODs.length; i ++ ) {

                var lod = source.LODs[ i ];
                object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };

            }

        }

        return object;

    },

    detach : function ( child, parent, scene ) {

        child.applyMatrix( parent.matrixWorld );
        parent.remove( child );
        scene.add( child );

    },

    attach: function ( child, scene, parent ) {

        var matrixWorldInverse = new THREE.Matrix4();
        matrixWorldInverse.getInverse( parent.matrixWorld );
        child.applyMatrix( matrixWorldInverse );

        scene.remove( child );
        parent.add( child );

    }

};
/**
 * @author alteredq / http://alteredqualia.com/
 * @author mrdoob / http://mrdoob.com/
 *
 * ShaderUtils currently contains:
 *
 *    fresnel
 *    normal
 *     cube
 *
 */

if ( THREE.WebGLRenderer ) {

THREE.ShaderUtils = {

    lib: {

        /* -------------------------------------------------------------------------
        //    Fresnel shader
        //    - based on Nvidia Cg tutorial
         ------------------------------------------------------------------------- */

        'fresnel': {

            uniforms: {

                "mRefractionRatio": { type: "f", value: 1.02 },
                "mFresnelBias": { type: "f", value: 0.1 },
                "mFresnelPower": { type: "f", value: 2.0 },
                "mFresnelScale": { type: "f", value: 1.0 },
                "tCube": { type: "t", value: null }

            },

            fragmentShader: [

                "uniform samplerCube tCube;",

                "varying vec3 vReflect;",
                "varying vec3 vRefract[3];",
                "varying float vReflectionFactor;",

                "void main() {",

                    "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
                    "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",

                    "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
                    "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
                    "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
                    "refractedColor.a = 1.0;",

                    "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",

                "}"

            ].join("\n"),

            vertexShader: [

                "uniform float mRefractionRatio;",
                "uniform float mFresnelBias;",
                "uniform float mFresnelScale;",
                "uniform float mFresnelPower;",

                "varying vec3 vReflect;",
                "varying vec3 vRefract[3];",
                "varying float vReflectionFactor;",

                "void main() {",

                    "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
                    "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",

                    "vec3 nWorld = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",

                    "vec3 I = mPosition.xyz - cameraPosition;",

                    "vReflect = reflect( I, nWorld );",
                    "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
                    "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
                    "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
                    "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",

                    "gl_Position = projectionMatrix * mvPosition;",

                "}"

            ].join("\n")

        },

        /* -------------------------------------------------------------------------
        //    Normal map shader
        //        - Blinn-Phong
        //        - normal + diffuse + specular + AO + displacement + reflection + shadow maps
        //        - point and directional lights (use with "lights: true" material option)
         ------------------------------------------------------------------------- */

        'normal' : {

            uniforms: THREE.UniformsUtils.merge( [

                THREE.UniformsLib[ "fog" ],
                THREE.UniformsLib[ "lights" ],
                THREE.UniformsLib[ "shadowmap" ],

                {

                "enableAO"          : { type: "i", value: 0 },
                "enableDiffuse"      : { type: "i", value: 0 },
                "enableSpecular"  : { type: "i", value: 0 },
                "enableReflection": { type: "i", value: 0 },
                "enableDisplacement": { type: "i", value: 0 },

                "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
                "tDiffuse"       : { type: "t", value: null },
                "tCube"           : { type: "t", value: null },
                "tNormal"       : { type: "t", value: null },
                "tSpecular"       : { type: "t", value: null },
                "tAO"           : { type: "t", value: null },

                "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },

                "uDisplacementBias": { type: "f", value: 0.0 },
                "uDisplacementScale": { type: "f", value: 1.0 },

                "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
                "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
                "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
                "uShininess": { type: "f", value: 30 },
                "uOpacity": { type: "f", value: 1 },

                "useRefract": { type: "i", value: 0 },
                "uRefractionRatio": { type: "f", value: 0.98 },
                "uReflectivity": { type: "f", value: 0.5 },

                "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
                "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },

                "wrapRGB"  : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }

                }

            ] ),

            fragmentShader: [

                "uniform vec3 uAmbientColor;",
                "uniform vec3 uDiffuseColor;",
                "uniform vec3 uSpecularColor;",
                "uniform float uShininess;",
                "uniform float uOpacity;",

                "uniform bool enableDiffuse;",
                "uniform bool enableSpecular;",
                "uniform bool enableAO;",
                "uniform bool enableReflection;",

                "uniform sampler2D tDiffuse;",
                "uniform sampler2D tNormal;",
                "uniform sampler2D tSpecular;",
                "uniform sampler2D tAO;",

                "uniform samplerCube tCube;",

                "uniform vec2 uNormalScale;",

                "uniform bool useRefract;",
                "uniform float uRefractionRatio;",
                "uniform float uReflectivity;",

                "varying vec3 vTangent;",
                "varying vec3 vBinormal;",
                "varying vec3 vNormal;",
                "varying vec2 vUv;",

                "uniform vec3 ambientLightColor;",

                "#if MAX_DIR_LIGHTS > 0",

                    "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
                    "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",

                "#endif",

                "#if MAX_HEMI_LIGHTS > 0",

                    "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
                    "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
                    "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",

                "#endif",

                "#if MAX_POINT_LIGHTS > 0",

                    "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
                    "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
                    "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",

                "#endif",

                "#if MAX_SPOT_LIGHTS > 0",

                    "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
                    "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
                    "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
                    "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
                    "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
                    "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",

                "#endif",

                "#ifdef WRAP_AROUND",

                    "uniform vec3 wrapRGB;",

                "#endif",

                "varying vec3 vWorldPosition;",
                "varying vec3 vViewPosition;",

                THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
                THREE.ShaderChunk[ "fog_pars_fragment" ],

                "void main() {",

                    "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",

                    "vec3 specularTex = vec3( 1.0 );",

                    "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
                    "normalTex.xy *= uNormalScale;",
                    "normalTex = normalize( normalTex );",

                    "if( enableDiffuse ) {",

                        "#ifdef GAMMA_INPUT",

                            "vec4 texelColor = texture2D( tDiffuse, vUv );",
                            "texelColor.xyz *= texelColor.xyz;",

                            "gl_FragColor = gl_FragColor * texelColor;",

                        "#else",

                            "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",

                        "#endif",

                    "}",

                    "if( enableAO ) {",

                        "#ifdef GAMMA_INPUT",

                            "vec4 aoColor = texture2D( tAO, vUv );",
                            "aoColor.xyz *= aoColor.xyz;",

                            "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",

                        "#else",

                            "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",

                        "#endif",

                    "}",

                    "if( enableSpecular )",
                        "specularTex = texture2D( tSpecular, vUv ).xyz;",

                    "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
                    "vec3 finalNormal = tsb * normalTex;",

                    "#ifdef FLIP_SIDED",

                        "finalNormal = -finalNormal;",

                    "#endif",

                    "vec3 normal = normalize( finalNormal );",
                    "vec3 viewPosition = normalize( vViewPosition );",

                    // point lights

                    "#if MAX_POINT_LIGHTS > 0",

                        "vec3 pointDiffuse = vec3( 0.0 );",
                        "vec3 pointSpecular = vec3( 0.0 );",

                        "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",

                            "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
                            "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",

                            "float pointDistance = 1.0;",
                            "if ( pointLightDistance[ i ] > 0.0 )",
                                "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",

                            "pointVector = normalize( pointVector );",

                            // diffuse

                            "#ifdef WRAP_AROUND",

                                "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
                                "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",

                                "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",

                            "#else",

                                "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",

                            "#endif",

                            "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",

                            // specular

                            "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
                            "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
                            "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",

                            "#ifdef PHYSICALLY_BASED_SHADING",

                                // 2.0 => 2.0001 is hack to work around ANGLE bug

                                "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",

                                "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
                                "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",

                            "#else",

                                "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",

                            "#endif",

                        "}",

                    "#endif",

                    // spot lights

                    "#if MAX_SPOT_LIGHTS > 0",

                        "vec3 spotDiffuse = vec3( 0.0 );",
                        "vec3 spotSpecular = vec3( 0.0 );",

                        "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",

                            "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
                            "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",

                            "float spotDistance = 1.0;",
                            "if ( spotLightDistance[ i ] > 0.0 )",
                                "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",

                            "spotVector = normalize( spotVector );",

                            "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",

                            "if ( spotEffect > spotLightAngle[ i ] ) {",

                                "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",

                                // diffuse

                                "#ifdef WRAP_AROUND",

                                    "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
                                    "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",

                                    "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",

                                "#else",

                                    "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",

                                "#endif",

                                "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",

                                // specular

                                "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
                                "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
                                "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",

                                "#ifdef PHYSICALLY_BASED_SHADING",

                                    // 2.0 => 2.0001 is hack to work around ANGLE bug

                                    "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",

                                    "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
                                    "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",

                                "#else",

                                    "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",

                                "#endif",

                            "}",

                        "}",

                    "#endif",

                    // directional lights

                    "#if MAX_DIR_LIGHTS > 0",

                        "vec3 dirDiffuse = vec3( 0.0 );",
                        "vec3 dirSpecular = vec3( 0.0 );",

                        "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",

                            "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
                            "vec3 dirVector = normalize( lDirection.xyz );",

                            // diffuse

                            "#ifdef WRAP_AROUND",

                                "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
                                "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",

                                "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",

                            "#else",

                                "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",

                            "#endif",

                            "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",

                            // specular

                            "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
                            "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
                            "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",

                            "#ifdef PHYSICALLY_BASED_SHADING",

                                // 2.0 => 2.0001 is hack to work around ANGLE bug

                                "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",

                                "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
                                "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",

                            "#else",

                                "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",

                            "#endif",

                        "}",

                    "#endif",

                    // hemisphere lights

                    "#if MAX_HEMI_LIGHTS > 0",

                        "vec3 hemiDiffuse  = vec3( 0.0 );",
                        "vec3 hemiSpecular = vec3( 0.0 );" ,

                        "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",

                            "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
                            "vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",

                            // diffuse

                            "float dotProduct = dot( normal, lVector );",
                            "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",

                            "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",

                            "hemiDiffuse += uDiffuseColor * hemiColor;",

                            // specular (sky light)


                            "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
                            "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
                            "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",

                            // specular (ground light)

                            "vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",

                            "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
                            "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
                            "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",

                            "#ifdef PHYSICALLY_BASED_SHADING",

                                "float dotProductGround = dot( normal, lVectorGround );",

                                // 2.0 => 2.0001 is hack to work around ANGLE bug

                                "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",

                                "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
                                "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
                                "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",

                            "#else",

                                "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",

                            "#endif",

                        "}",

                    "#endif",

                    // all lights contribution summation

                    "vec3 totalDiffuse = vec3( 0.0 );",
                    "vec3 totalSpecular = vec3( 0.0 );",

                    "#if MAX_DIR_LIGHTS > 0",

                        "totalDiffuse += dirDiffuse;",
                        "totalSpecular += dirSpecular;",

                    "#endif",

                    "#if MAX_HEMI_LIGHTS > 0",

                        "totalDiffuse += hemiDiffuse;",
                        "totalSpecular += hemiSpecular;",

                    "#endif",

                    "#if MAX_POINT_LIGHTS > 0",

                        "totalDiffuse += pointDiffuse;",
                        "totalSpecular += pointSpecular;",

                    "#endif",

                    "#if MAX_SPOT_LIGHTS > 0",

                        "totalDiffuse += spotDiffuse;",
                        "totalSpecular += spotSpecular;",

                    "#endif",

                    "#ifdef METAL",

                        "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",

                    "#else",

                        "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",

                    "#endif",

                    "if ( enableReflection ) {",

                        "vec3 vReflect;",
                        "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",

                        "if ( useRefract ) {",

                            "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",

                        "} else {",

                            "vReflect = reflect( cameraToVertex, normal );",

                        "}",

                        "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",

                        "#ifdef GAMMA_INPUT",

                            "cubeColor.xyz *= cubeColor.xyz;",

                        "#endif",

                        "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",

                    "}",

                    THREE.ShaderChunk[ "shadowmap_fragment" ],
                    THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
                    THREE.ShaderChunk[ "fog_fragment" ],

                "}"

            ].join("\n"),

            vertexShader: [

                "attribute vec4 tangent;",

                "uniform vec2 uOffset;",
                "uniform vec2 uRepeat;",

                "uniform bool enableDisplacement;",

                "#ifdef VERTEX_TEXTURES",

                    "uniform sampler2D tDisplacement;",
                    "uniform float uDisplacementScale;",
                    "uniform float uDisplacementBias;",

                "#endif",

                "varying vec3 vTangent;",
                "varying vec3 vBinormal;",
                "varying vec3 vNormal;",
                "varying vec2 vUv;",

                "varying vec3 vWorldPosition;",
                "varying vec3 vViewPosition;",

                THREE.ShaderChunk[ "skinning_pars_vertex" ],
                THREE.ShaderChunk[ "shadowmap_pars_vertex" ],

                "void main() {",

                    THREE.ShaderChunk[ "skinbase_vertex" ],
                    THREE.ShaderChunk[ "skinnormal_vertex" ],

                    // normal, tangent and binormal vectors

                    "#ifdef USE_SKINNING",

                        "vNormal = normalMatrix * skinnedNormal.xyz;",

                        "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
                        "vTangent = normalMatrix * skinnedTangent.xyz;",

                    "#else",

                        "vNormal = normalMatrix * normal;",
                        "vTangent = normalMatrix * tangent.xyz;",

                    "#endif",

                    "vBinormal = cross( vNormal, vTangent ) * tangent.w;",

                    "vUv = uv * uRepeat + uOffset;",

                    // displacement mapping

                    "vec3 displacedPosition;",

                    "#ifdef VERTEX_TEXTURES",

                        "if ( enableDisplacement ) {",

                            "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
                            "float df = uDisplacementScale * dv.x + uDisplacementBias;",
                            "displacedPosition = position + normalize( normal ) * df;",

                        "} else {",

                            "#ifdef USE_SKINNING",

                                "vec4 skinVertex = vec4( position, 1.0 );",

                                "vec4 skinned  = boneMatX * skinVertex * skinWeight.x;",
                                "skinned       += boneMatY * skinVertex * skinWeight.y;",

                                "displacedPosition  = skinned.xyz;",

                            "#else",

                                "displacedPosition = position;",

                            "#endif",

                        "}",

                    "#else",

                        "#ifdef USE_SKINNING",

                            "vec4 skinVertex = vec4( position, 1.0 );",

                            "vec4 skinned  = boneMatX * skinVertex * skinWeight.x;",
                            "skinned       += boneMatY * skinVertex * skinWeight.y;",

                            "displacedPosition  = skinned.xyz;",

                        "#else",

                            "displacedPosition = position;",

                        "#endif",

                    "#endif",

                    //

                    "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
                    "vec4 mPosition = modelMatrix * vec4( displacedPosition, 1.0 );",

                    "gl_Position = projectionMatrix * mvPosition;",

                    //

                    "vWorldPosition = mPosition.xyz;",
                    "vViewPosition = -mvPosition.xyz;",

                    // shadows

                    "#ifdef USE_SHADOWMAP",

                        "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",

                            "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",

                        "}",

                    "#endif",

                "}"

            ].join("\n")

        },

        /* -------------------------------------------------------------------------
        //    Cube map shader
         ------------------------------------------------------------------------- */

        'cube': {

            uniforms: { "tCube": { type: "t", value: null },
                        "tFlip": { type: "f", value: -1 } },

            vertexShader: [

                "varying vec3 vViewPosition;",

                "void main() {",

                    "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
                    "vViewPosition = cameraPosition - mPosition.xyz;",

                    "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

                "}"

            ].join("\n"),

            fragmentShader: [

                "uniform samplerCube tCube;",
                "uniform float tFlip;",

                "varying vec3 vViewPosition;",

                "void main() {",

                    "vec3 wPos = cameraPosition - vViewPosition;",
                    "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",

                "}"

            ].join("\n")

        }

    }

};

};
/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * @author alteredq / http://alteredqualia.com/
 *
 * For Text operations in three.js (See TextGeometry)
 *
 * It uses techniques used in:
 *
 *     typeface.js and canvastext
 *         For converting fonts and rendering with javascript
 *        http://typeface.neocracy.org
 *
 *    Triangulation ported from AS3
 *        Simple Polygon Triangulation
 *        http://actionsnippet.com/?p=1462
 *
 *     A Method to triangulate shapes with holes
 *        http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
 *
 */

THREE.FontUtils = {

    faces : {},

    // Just for now. face[weight][style]

    face : "helvetiker",
    weight: "normal",
    style : "normal",
    size : 150,
    divisions : 10,

    getFace : function() {

        return this.faces[ this.face ][ this.weight ][ this.style ];

    },

    loadFace : function( data ) {

        var family = data.familyName.toLowerCase();

        var ThreeFont = this;

        ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};

        ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
        ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;

        var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;

        return data;

    },

    drawText : function( text ) {

        var characterPts = [], allPts = [];

        // RenderText

        var i, p,
            face = this.getFace(),
            scale = this.size / face.resolution,
            offset = 0,
            chars = String( text ).split( '' ),
            length = chars.length;

        var fontPaths = [];

        for ( i = 0; i < length; i ++ ) {

            var path = new THREE.Path();

            var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
            offset += ret.offset;

            fontPaths.push( ret.path );

        }

        // get the width

        var width = offset / 2;
        //
        // for ( p = 0; p < allPts.length; p++ ) {
        //
        //     allPts[ p ].x -= width;
        //
        // }

        //var extract = this.extractPoints( allPts, characterPts );
        //extract.contour = allPts;

        //extract.paths = fontPaths;
        //extract.offset = width;

        return { paths : fontPaths, offset : width };

    },




    extractGlyphPoints : function( c, face, scale, offset, path ) {

        var pts = [];

        var i, i2, divisions,
            outline, action, length,
            scaleX, scaleY,
            x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
            laste,
            glyph = face.glyphs[ c ] || face.glyphs[ '?' ];

        if ( !glyph ) return;

        if ( glyph.o ) {

            outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
            length = outline.length;

            scaleX = scale;
            scaleY = scale;

            for ( i = 0; i < length; ) {

                action = outline[ i ++ ];

                //console.log( action );

                switch( action ) {

                case 'm':

                    // Move To

                    x = outline[ i++ ] * scaleX + offset;
                    y = outline[ i++ ] * scaleY;

                    path.moveTo( x, y );
                    break;

                case 'l':

                    // Line To

                    x = outline[ i++ ] * scaleX + offset;
                    y = outline[ i++ ] * scaleY;
                    path.lineTo(x,y);
                    break;

                case 'q':

                    // QuadraticCurveTo

                    cpx  = outline[ i++ ] * scaleX + offset;
                    cpy  = outline[ i++ ] * scaleY;
                    cpx1 = outline[ i++ ] * scaleX + offset;
                    cpy1 = outline[ i++ ] * scaleY;

                    path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);

                    laste = pts[ pts.length - 1 ];

                    if ( laste ) {

                        cpx0 = laste.x;
                        cpy0 = laste.y;

                        for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {

                            var t = i2 / divisions;
                            var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
                            var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
                      }

                  }

                  break;

                case 'b':

                    // Cubic Bezier Curve

                    cpx  = outline[ i++ ] *  scaleX + offset;
                    cpy  = outline[ i++ ] *  scaleY;
                    cpx1 = outline[ i++ ] *  scaleX + offset;
                    cpy1 = outline[ i++ ] * -scaleY;
                    cpx2 = outline[ i++ ] *  scaleX + offset;
                    cpy2 = outline[ i++ ] * -scaleY;

                    path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );

                    laste = pts[ pts.length - 1 ];

                    if ( laste ) {

                        cpx0 = laste.x;
                        cpy0 = laste.y;

                        for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {

                            var t = i2 / divisions;
                            var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
                            var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );

                        }

                    }

                    break;

                }

            }
        }



        return { offset: glyph.ha*scale, path:path};
    }

};


THREE.FontUtils.generateShapes = function( text, parameters ) {

    // Parameters

    parameters = parameters || {};

    var size = parameters.size !== undefined ? parameters.size : 100;
    var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;

    var font = parameters.font !== undefined ? parameters.font : "helvetiker";
    var weight = parameters.weight !== undefined ? parameters.weight : "normal";
    var style = parameters.style !== undefined ? parameters.style : "normal";

    THREE.FontUtils.size = size;
    THREE.FontUtils.divisions = curveSegments;

    THREE.FontUtils.face = font;
    THREE.FontUtils.weight = weight;
    THREE.FontUtils.style = style;

    // Get a Font data json object

    var data = THREE.FontUtils.drawText( text );

    var paths = data.paths;
    var shapes = [];

    for ( var p = 0, pl = paths.length; p < pl; p ++ ) {

        Array.prototype.push.apply( shapes, paths[ p ].toShapes() );

    }

    return shapes;

};


/**
 * This code is a quick port of code written in C++ which was submitted to
 * flipcode.com by John W. Ratcliff  // July 22, 2000
 * See original code and more information here:
 * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
 *
 * ported to actionscript by Zevan Rosser
 * www.actionsnippet.com
 *
 * ported to javascript by Joshua Koo
 * http://www.lab4games.net/zz85/blog
 *
 */


( function( namespace ) {

    var EPSILON = 0.0000000001;

    // takes in an contour array and returns

    var process = function( contour, indices ) {

        var n = contour.length;

        if ( n < 3 ) return null;

        var result = [],
            verts = [],
            vertIndices = [];

        /* we want a counter-clockwise polygon in verts */

        var u, v, w;

        if ( area( contour ) > 0.0 ) {

            for ( v = 0; v < n; v++ ) verts[ v ] = v;

        } else {

            for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;

        }

        var nv = n;

        /*  remove nv - 2 vertices, creating 1 triangle every time */

        var count = 2 * nv;   /* error detection */

        for( v = nv - 1; nv > 2; ) {

            /* if we loop, it is probably a non-simple polygon */

            if ( ( count-- ) <= 0 ) {

                //** Triangulate: ERROR - probable bad polygon!

                //throw ( "Warning, unable to triangulate polygon!" );
                //return null;
                // Sometimes warning is fine, especially polygons are triangulated in reverse.
                console.log( "Warning, unable to triangulate polygon!" );

                if ( indices ) return vertIndices;
                return result;

            }

            /* three consecutive vertices in current polygon, <u,v,w> */

            u = v;          if ( nv <= u ) u = 0;     /* previous */
            v = u + 1;  if ( nv <= v ) v = 0;     /* new v    */
            w = v + 1;  if ( nv <= w ) w = 0;     /* next     */

            if ( snip( contour, u, v, w, nv, verts ) ) {

                var a, b, c, s, t;

                /* true names of the vertices */

                a = verts[ u ];
                b = verts[ v ];
                c = verts[ w ];

                /* output Triangle */

                /*
                result.push( contour[ a ] );
                result.push( contour[ b ] );
                result.push( contour[ c ] );
                */
                result.push( [ contour[ a ],
                    contour[ b ],
                    contour[ c ] ] );


                vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );

                /* remove v from the remaining polygon */

                for( s = v, t = v + 1; t < nv; s++, t++ ) {

                    verts[ s ] = verts[ t ];

                }

                nv--;

                /* reset error detection counter */

                count = 2 * nv;

            }

        }

        if ( indices ) return vertIndices;
        return result;

    };

    // calculate area of the contour polygon

    var area = function ( contour ) {

        var n = contour.length;
        var a = 0.0;

        for( var p = n - 1, q = 0; q < n; p = q++ ) {

            a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;

        }

        return a * 0.5;

    };

    // see if p is inside triangle abc

    var insideTriangle = function( ax, ay,
                                   bx, by,
                                   cx, cy,
                                   px, py ) {

          var aX, aY, bX, bY;
          var cX, cY, apx, apy;
          var bpx, bpy, cpx, cpy;
          var cCROSSap, bCROSScp, aCROSSbp;

          aX = cx - bx;  aY = cy - by;
          bX = ax - cx;  bY = ay - cy;
          cX = bx - ax;  cY = by - ay;
          apx= px  -ax;  apy= py - ay;
          bpx= px - bx;  bpy= py - by;
          cpx= px - cx;  cpy= py - cy;

          aCROSSbp = aX*bpy - aY*bpx;
          cCROSSap = cX*apy - cY*apx;
          bCROSScp = bX*cpy - bY*cpx;

          return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );

    };


    var snip = function ( contour, u, v, w, n, verts ) {

        var p;
        var ax, ay, bx, by;
        var cx, cy, px, py;

        ax = contour[ verts[ u ] ].x;
        ay = contour[ verts[ u ] ].y;

        bx = contour[ verts[ v ] ].x;
        by = contour[ verts[ v ] ].y;

        cx = contour[ verts[ w ] ].x;
        cy = contour[ verts[ w ] ].y;

        if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;

            for ( p = 0; p < n; p++ ) {

                if( (p == u) || (p == v) || (p == w) ) continue;

                px = contour[ verts[ p ] ].x
                py = contour[ verts[ p ] ].y

                if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;

          }

          return true;

    };


    namespace.Triangulate = process;
    namespace.Triangulate.area = area;

    return namespace;

})(THREE.FontUtils);

// To use the typeface.js face files, hook up the API
self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * Extensible curve object
 *
 * Some common of Curve methods
 * .getPoint(t), getTangent(t)
 * .getPointAt(u), getTagentAt(u)
 * .getPoints(), .getSpacedPoints()
 * .getLength()
 * .updateArcLengths()
 *
 * This file contains following classes:
 *
 * -- 2d classes --
 * THREE.Curve
 * THREE.LineCurve
 * THREE.QuadraticBezierCurve
 * THREE.CubicBezierCurve
 * THREE.SplineCurve
 * THREE.ArcCurve
 * THREE.EllipseCurve
 *
 * -- 3d classes --
 * THREE.LineCurve3
 * THREE.QuadraticBezierCurve3
 * THREE.CubicBezierCurve3
 * THREE.SplineCurve3
 * THREE.ClosedSplineCurve3
 *
 * A series of curves can be represented as a THREE.CurvePath
 *
 **/

/**************************************************************
 *    Abstract Curve base class
 **************************************************************/

THREE.Curve = function () {

};

// Virtual base class method to overwrite and implement in subclasses
//    - t [0 .. 1]

THREE.Curve.prototype.getPoint = function ( t ) {

    console.log( "Warning, getPoint() not implemented!" );
    return null;

};

// Get point at relative position in curve according to arc length
// - u [0 .. 1]

THREE.Curve.prototype.getPointAt = function ( u ) {

    var t = this.getUtoTmapping( u );
    return this.getPoint( t );

};

// Get sequence of points using getPoint( t )

THREE.Curve.prototype.getPoints = function ( divisions ) {

    if ( !divisions ) divisions = 5;

    var d, pts = [];

    for ( d = 0; d <= divisions; d ++ ) {

        pts.push( this.getPoint( d / divisions ) );

    }

    return pts;

};

// Get sequence of points using getPointAt( u )

THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {

    if ( !divisions ) divisions = 5;

    var d, pts = [];

    for ( d = 0; d <= divisions; d ++ ) {

        pts.push( this.getPointAt( d / divisions ) );

    }

    return pts;

};

// Get total curve arc length

THREE.Curve.prototype.getLength = function () {

    var lengths = this.getLengths();
    return lengths[ lengths.length - 1 ];

};

// Get list of cumulative segment lengths

THREE.Curve.prototype.getLengths = function ( divisions ) {

    if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;

    if ( this.cacheArcLengths
        && ( this.cacheArcLengths.length == divisions + 1 )
        && !this.needsUpdate) {

        //console.log( "cached", this.cacheArcLengths );
        return this.cacheArcLengths;

    }

    this.needsUpdate = false;

    var cache = [];
    var current, last = this.getPoint( 0 );
    var p, sum = 0;

    cache.push( 0 );

    for ( p = 1; p <= divisions; p ++ ) {

        current = this.getPoint ( p / divisions );
        sum += current.distanceTo( last );
        cache.push( sum );
        last = current;

    }

    this.cacheArcLengths = cache;

    return cache; // { sums: cache, sum:sum }; Sum is in the last element.

};


THREE.Curve.prototype.updateArcLengths = function() {
    this.needsUpdate = true;
    this.getLengths();
};

// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance

THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {

    var arcLengths = this.getLengths();

    var i = 0, il = arcLengths.length;

    var targetArcLength; // The targeted u distance value to get

    if ( distance ) {

        targetArcLength = distance;

    } else {

        targetArcLength = u * arcLengths[ il - 1 ];

    }

    //var time = Date.now();

    // binary search for the index with largest value smaller than target u distance

    var low = 0, high = il - 1, comparison;

    while ( low <= high ) {

        i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats

        comparison = arcLengths[ i ] - targetArcLength;

        if ( comparison < 0 ) {

            low = i + 1;
            continue;

        } else if ( comparison > 0 ) {

            high = i - 1;
            continue;

        } else {

            high = i;
            break;

            // DONE

        }

    }

    i = high;

    //console.log('b' , i, low, high, Date.now()- time);

    if ( arcLengths[ i ] == targetArcLength ) {

        var t = i / ( il - 1 );
        return t;

    }

    // we could get finer grain at lengths, or use simple interpolatation between two points

    var lengthBefore = arcLengths[ i ];
    var lengthAfter = arcLengths[ i + 1 ];

    var segmentLength = lengthAfter - lengthBefore;

    // determine where we are between the 'before' and 'after' points

    var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;

    // add that fractional amount to t

    var t = ( i + segmentFraction ) / ( il -1 );

    return t;

};


// In 2D space, there are actually 2 normal vectors,
// and in 3D space, infinte
// TODO this should be depreciated.
THREE.Curve.prototype.getNormalVector = function( t ) {

    var vec = this.getTangent( t );

    return new THREE.Vector2( -vec.y , vec.x );

};

// Returns a unit vector tangent at t
// In case any sub curve does not implement its tangent / normal finding,
// we get 2 points with a small delta and find a gradient of the 2 points
// which seems to make a reasonable approximation

THREE.Curve.prototype.getTangent = function( t ) {

    var delta = 0.0001;
    var t1 = t - delta;
    var t2 = t + delta;

    // Capping in case of danger

    if ( t1 < 0 ) t1 = 0;
    if ( t2 > 1 ) t2 = 1;

    var pt1 = this.getPoint( t1 );
    var pt2 = this.getPoint( t2 );

    var vec = pt2.clone().subSelf(pt1);
    return vec.normalize();

};


THREE.Curve.prototype.getTangentAt = function ( u ) {

    var t = this.getUtoTmapping( u );
    return this.getTangent( t );

};

/**************************************************************
 *    Line
 **************************************************************/

THREE.LineCurve = function ( v1, v2 ) {

    this.v1 = v1;
    this.v2 = v2;

};

THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );

THREE.LineCurve.prototype.getPoint = function ( t ) {

    var point = this.v2.clone().subSelf(this.v1);
    point.multiplyScalar( t ).addSelf( this.v1 );

    return point;

};

// Line curve is linear, so we can overwrite default getPointAt

THREE.LineCurve.prototype.getPointAt = function ( u ) {

    return this.getPoint( u );

};

THREE.LineCurve.prototype.getTangent = function( t ) {

    var tangent = this.v2.clone().subSelf(this.v1);

    return tangent.normalize();

};

/**************************************************************
 *    Quadratic Bezier curve
 **************************************************************/


THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {

    this.v0 = v0;
    this.v1 = v1;
    this.v2 = v2;

};

THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );


THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {

    var tx, ty;

    tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
    ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );

    return new THREE.Vector2( tx, ty );

};


THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {

    var tx, ty;

    tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
    ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );

    // returns unit vector

    var tangent = new THREE.Vector2( tx, ty );
    tangent.normalize();

    return tangent;

};


/**************************************************************
 *    Cubic Bezier curve
 **************************************************************/

THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {

    this.v0 = v0;
    this.v1 = v1;
    this.v2 = v2;
    this.v3 = v3;

};

THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );

THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {

    var tx, ty;

    tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
    ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );

    return new THREE.Vector2( tx, ty );

};

THREE.CubicBezierCurve.prototype.getTangent = function( t ) {

    var tx, ty;

    tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
    ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );

    var tangent = new THREE.Vector2( tx, ty );
    tangent.normalize();

    return tangent;

};


/**************************************************************
 *    Spline curve
 **************************************************************/

THREE.SplineCurve = function ( points /* array of Vector2 */ ) {

    this.points = (points == undefined) ? [] : points;

};

THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );

THREE.SplineCurve.prototype.getPoint = function ( t ) {

    var v = new THREE.Vector2();
    var c = [];
    var points = this.points, point, intPoint, weight;
    point = ( points.length - 1 ) * t;

    intPoint = Math.floor( point );
    weight = point - intPoint;

    c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
    c[ 1 ] = intPoint;
    c[ 2 ] = intPoint  > points.length - 2 ? points.length -1 : intPoint + 1;
    c[ 3 ] = intPoint  > points.length - 3 ? points.length -1 : intPoint + 2;

    v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
    v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );

    return v;

};

/**************************************************************
 *    Ellipse curve
 **************************************************************/

THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
                            aStartAngle, aEndAngle,
                            aClockwise ) {

    this.aX = aX;
    this.aY = aY;

    this.xRadius = xRadius;
    this.yRadius = yRadius;

    this.aStartAngle = aStartAngle;
    this.aEndAngle = aEndAngle;

    this.aClockwise = aClockwise;

};

THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );

THREE.EllipseCurve.prototype.getPoint = function ( t ) {

    var deltaAngle = this.aEndAngle - this.aStartAngle;

    if ( !this.aClockwise ) {

        t = 1 - t;

    }

    var angle = this.aStartAngle + t * deltaAngle;

    var tx = this.aX + this.xRadius * Math.cos( angle );
    var ty = this.aY + this.yRadius * Math.sin( angle );

    return new THREE.Vector2( tx, ty );

};

/**************************************************************
 *    Arc curve
 **************************************************************/

THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {

    THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
};

THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );


/**************************************************************
 *    Utils
 **************************************************************/

THREE.Curve.Utils = {

    tangentQuadraticBezier: function ( t, p0, p1, p2 ) {

        return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );

    },

    // Puay Bing, thanks for helping with this derivative!

    tangentCubicBezier: function (t, p0, p1, p2, p3 ) {

        return -3 * p0 * (1 - t) * (1 - t)  +
            3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
            6 * t *  p2 * (1-t) - 3 * t * t * p2 +
            3 * t * t * p3;
    },


    tangentSpline: function ( t, p0, p1, p2, p3 ) {

        // To check if my formulas are correct

        var h00 = 6 * t * t - 6 * t;     // derived from 2t^3 − 3t^2 + 1
        var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
        var h01 = -6 * t * t + 6 * t;     // − 2t3 + 3t2
        var h11 = 3 * t * t - 2 * t;    // t3 − t2

        return h00 + h10 + h01 + h11;

    },

    // Catmull-Rom

    interpolate: function( p0, p1, p2, p3, t ) {

        var v0 = ( p2 - p0 ) * 0.5;
        var v1 = ( p3 - p1 ) * 0.5;
        var t2 = t * t;
        var t3 = t * t2;
        return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;

    }

};


// TODO: Transformation for Curves?

/**************************************************************
 *    3D Curves
 **************************************************************/

// A Factory method for creating new curve subclasses

THREE.Curve.create = function ( constructor, getPointFunc ) {

    constructor.prototype = Object.create( THREE.Curve.prototype );
    constructor.prototype.getPoint = getPointFunc;

    return constructor;

};


/**************************************************************
 *    Line3D
 **************************************************************/

THREE.LineCurve3 = THREE.Curve.create(

    function ( v1, v2 ) {

        this.v1 = v1;
        this.v2 = v2;

    },

    function ( t ) {

        var r = new THREE.Vector3();


        r.sub( this.v2, this.v1 ); // diff
        r.multiplyScalar( t );
        r.addSelf( this.v1 );

        return r;

    }

);


/**************************************************************
 *    Quadratic Bezier 3D curve
 **************************************************************/

THREE.QuadraticBezierCurve3 = THREE.Curve.create(

    function ( v0, v1, v2 ) {

        this.v0 = v0;
        this.v1 = v1;
        this.v2 = v2;

    },

    function ( t ) {

        var tx, ty, tz;

        tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
        ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
        tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );

        return new THREE.Vector3( tx, ty, tz );

    }

);



/**************************************************************
 *    Cubic Bezier 3D curve
 **************************************************************/

THREE.CubicBezierCurve3 = THREE.Curve.create(

    function ( v0, v1, v2, v3 ) {

        this.v0 = v0;
        this.v1 = v1;
        this.v2 = v2;
        this.v3 = v3;

    },

    function ( t ) {

        var tx, ty, tz;

        tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
        ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
        tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );

        return new THREE.Vector3( tx, ty, tz );

    }

);



/**************************************************************
 *    Spline 3D curve
 **************************************************************/


THREE.SplineCurve3 = THREE.Curve.create(

    function ( points /* array of Vector3 */) {

        this.points = (points == undefined) ? [] : points;

    },

    function ( t ) {

        var v = new THREE.Vector3();
        var c = [];
        var points = this.points, point, intPoint, weight;
        point = ( points.length - 1 ) * t;

        intPoint = Math.floor( point );
        weight = point - intPoint;

        c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
        c[ 1 ] = intPoint;
        c[ 2 ] = intPoint  > points.length - 2 ? points.length - 1 : intPoint + 1;
        c[ 3 ] = intPoint  > points.length - 3 ? points.length - 1 : intPoint + 2;

        var pt0 = points[ c[0] ],
            pt1 = points[ c[1] ],
            pt2 = points[ c[2] ],
            pt3 = points[ c[3] ];

        v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
        v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
        v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);

        return v;

    }

);


// THREE.SplineCurve3.prototype.getTangent = function(t) {
//         var v = new THREE.Vector3();
//         var c = [];
//         var points = this.points, point, intPoint, weight;
//         point = ( points.length - 1 ) * t;

//         intPoint = Math.floor( point );
//         weight = point - intPoint;

//         c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
//         c[ 1 ] = intPoint;
//         c[ 2 ] = intPoint  > points.length - 2 ? points.length - 1 : intPoint + 1;
//         c[ 3 ] = intPoint  > points.length - 3 ? points.length - 1 : intPoint + 2;

//         var pt0 = points[ c[0] ],
//             pt1 = points[ c[1] ],
//             pt2 = points[ c[2] ],
//             pt3 = points[ c[3] ];

//     // t = weight;
//     v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
//     v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
//     v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );

//     return v;

// }

/**************************************************************
 *    Closed Spline 3D curve
 **************************************************************/


THREE.ClosedSplineCurve3 = THREE.Curve.create(

    function ( points /* array of Vector3 */) {

        this.points = (points == undefined) ? [] : points;

    },

    function ( t ) {

        var v = new THREE.Vector3();
        var c = [];
        var points = this.points, point, intPoint, weight;
        point = ( points.length - 0 ) * t;
            // This needs to be from 0-length +1

        intPoint = Math.floor( point );
        weight = point - intPoint;

        intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
        c[ 0 ] = ( intPoint - 1 ) % points.length;
        c[ 1 ] = ( intPoint ) % points.length;
        c[ 2 ] = ( intPoint + 1 ) % points.length;
        c[ 3 ] = ( intPoint + 2 ) % points.length;

        v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
        v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
        v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );

        return v;

    }

);
/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 *
 **/

/**************************************************************
 *    Curved Path - a curve path is simply a array of connected
 *  curves, but retains the api of a curve
 **************************************************************/

THREE.CurvePath = function () {

    this.curves = [];
    this.bends = [];

    this.autoClose = false; // Automatically closes the path
};

THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );

THREE.CurvePath.prototype.add = function ( curve ) {

    this.curves.push( curve );

};

THREE.CurvePath.prototype.checkConnection = function() {
    // TODO
    // If the ending of curve is not connected to the starting
    // or the next curve, then, this is not a real path
};

THREE.CurvePath.prototype.closePath = function() {
    // TODO Test
    // and verify for vector3 (needs to implement equals)
    // Add a line curve if start and end of lines are not connected
    var startPoint = this.curves[0].getPoint(0);
    var endPoint = this.curves[this.curves.length-1].getPoint(1);

    if (!startPoint.equals(endPoint)) {
        this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
    }

};

// To get accurate point with reference to
// entire path distance at time t,
// following has to be done:

// 1. Length of each sub path have to be known
// 2. Locate and identify type of curve
// 3. Get t for the curve
// 4. Return curve.getPointAt(t')

THREE.CurvePath.prototype.getPoint = function( t ) {

    var d = t * this.getLength();
    var curveLengths = this.getCurveLengths();
    var i = 0, diff, curve;

    // To think about boundaries points.

    while ( i < curveLengths.length ) {

        if ( curveLengths[ i ] >= d ) {

            diff = curveLengths[ i ] - d;
            curve = this.curves[ i ];

            var u = 1 - diff / curve.getLength();

            return curve.getPointAt( u );

            break;
        }

        i ++;

    }

    return null;

    // loop where sum != 0, sum > d , sum+1 <d

};

/*
THREE.CurvePath.prototype.getTangent = function( t ) {
};*/


// We cannot use the default THREE.Curve getPoint() with getLength() because in
// THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
// getPoint() depends on getLength

THREE.CurvePath.prototype.getLength = function() {

    var lens = this.getCurveLengths();
    return lens[ lens.length - 1 ];

};

// Compute lengths and cache them
// We cannot overwrite getLengths() because UtoT mapping uses it.

THREE.CurvePath.prototype.getCurveLengths = function() {

    // We use cache values if curves and cache array are same length

    if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {

        return this.cacheLengths;

    };

    // Get length of subsurve
    // Push sums into cached array

    var lengths = [], sums = 0;
    var i, il = this.curves.length;

    for ( i = 0; i < il; i ++ ) {

        sums += this.curves[ i ].getLength();
        lengths.push( sums );

    }

    this.cacheLengths = lengths;

    return lengths;

};



// Returns min and max coordinates, as well as centroid

THREE.CurvePath.prototype.getBoundingBox = function () {

    var points = this.getPoints();

    var maxX, maxY, maxZ;
    var minX, minY, minZ;

    maxX = maxY = Number.NEGATIVE_INFINITY;
    minX = minY = Number.POSITIVE_INFINITY;

    var p, i, il, sum;

    var v3 = points[0] instanceof THREE.Vector3;

    sum = v3 ? new THREE.Vector3() : new THREE.Vector2();

    for ( i = 0, il = points.length; i < il; i ++ ) {

        p = points[ i ];

        if ( p.x > maxX ) maxX = p.x;
        else if ( p.x < minX ) minX = p.x;

        if ( p.y > maxY ) maxY = p.y;
        else if ( p.y < minY ) minY = p.y;

        if (v3) {

            if ( p.z > maxZ ) maxZ = p.z;
            else if ( p.z < minZ ) minZ = p.z;

        }

        sum.addSelf( p );

    }

    var ret = {

        minX: minX,
        minY: minY,
        maxX: maxX,
        maxY: maxY,
        centroid: sum.divideScalar( il )

    };

    if (v3) {

        ret.maxZ = maxZ;
        ret.minZ = minZ;

    }

    return ret;

};

/**************************************************************
 *    Create Geometries Helpers
 **************************************************************/

/// Generate geometry from path points (for Line or ParticleSystem objects)

THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {

    var pts = this.getPoints( divisions, true );
    return this.createGeometry( pts );

};

// Generate geometry from equidistance sampling along the path

THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {

    var pts = this.getSpacedPoints( divisions, true );
    return this.createGeometry( pts );

};

THREE.CurvePath.prototype.createGeometry = function( points ) {

    var geometry = new THREE.Geometry();

    for ( var i = 0; i < points.length; i ++ ) {

        geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );

    }

    return geometry;

};


/**************************************************************
 *    Bend / Wrap Helper Methods
 **************************************************************/

// Wrap path / Bend modifiers?

THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {

    this.bends.push( bendpath );

};

THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {

    var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
    var i, il;

    if ( !bends ) {

        bends = this.bends;

    }

    for ( i = 0, il = bends.length; i < il; i ++ ) {

        oldPts = this.getWrapPoints( oldPts, bends[ i ] );

    }

    return oldPts;

};

THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {

    var oldPts = this.getSpacedPoints( segments );

    var i, il;

    if ( !bends ) {

        bends = this.bends;

    }

    for ( i = 0, il = bends.length; i < il; i ++ ) {

        oldPts = this.getWrapPoints( oldPts, bends[ i ] );

    }

    return oldPts;

};

// This returns getPoints() bend/wrapped around the contour of a path.
// Read http://www.planetclegg.com/projects/WarpingTextToSplines.html

THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {

    var bounds = this.getBoundingBox();

    var i, il, p, oldX, oldY, xNorm;

    for ( i = 0, il = oldPts.length; i < il; i ++ ) {

        p = oldPts[ i ];

        oldX = p.x;
        oldY = p.y;

        xNorm = oldX / bounds.maxX;

        // If using actual distance, for length > path, requires line extrusions
        //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance

        xNorm = path.getUtoTmapping( xNorm, oldX );

        // check for out of bounds?

        var pathPt = path.getPoint( xNorm );
        var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );

        p.x = pathPt.x + normal.x;
        p.y = pathPt.y + normal.y;

    }

    return oldPts;

};

/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Gyroscope = function () {

    THREE.Object3D.call( this );

};

THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );

THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {

    this.matrixAutoUpdate && this.updateMatrix();

    // update matrixWorld

    if ( this.matrixWorldNeedsUpdate || force ) {

        if ( this.parent ) {

            this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );

            this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
            this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );

            this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );


        } else {

            this.matrixWorld.copy( this.matrix );

        }


        this.matrixWorldNeedsUpdate = false;

        force = true;

    }

    // update children

    for ( var i = 0, l = this.children.length; i < l; i ++ ) {

        this.children[ i ].updateMatrixWorld( force );

    }

};

THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();

/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * Creates free form 2d path using series of points, lines or curves.
 *
 **/

THREE.Path = function ( points ) {

    THREE.CurvePath.call(this);

    this.actions = [];

    if ( points ) {

        this.fromPoints( points );

    }

};

THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );

THREE.PathActions = {

    MOVE_TO: 'moveTo',
    LINE_TO: 'lineTo',
    QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
    BEZIER_CURVE_TO: 'bezierCurveTo',         // Bezier cubic curve
    CSPLINE_THRU: 'splineThru',                // Catmull-rom spline
    ARC: 'arc',                                // Circle
    ELLIPSE: 'ellipse'
};

// TODO Clean up PATH API

// Create path using straight lines to connect all points
// - vectors: array of Vector2

THREE.Path.prototype.fromPoints = function ( vectors ) {

    this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );

    for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {

        this.lineTo( vectors[ v ].x, vectors[ v ].y );

    };

};

// startPath() endPath()?

THREE.Path.prototype.moveTo = function ( x, y ) {

    var args = Array.prototype.slice.call( arguments );
    this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );

};

THREE.Path.prototype.lineTo = function ( x, y ) {

    var args = Array.prototype.slice.call( arguments );

    var lastargs = this.actions[ this.actions.length - 1 ].args;

    var x0 = lastargs[ lastargs.length - 2 ];
    var y0 = lastargs[ lastargs.length - 1 ];

    var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
    this.curves.push( curve );

    this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );

};

THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {

    var args = Array.prototype.slice.call( arguments );

    var lastargs = this.actions[ this.actions.length - 1 ].args;

    var x0 = lastargs[ lastargs.length - 2 ];
    var y0 = lastargs[ lastargs.length - 1 ];

    var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
                                                new THREE.Vector2( aCPx, aCPy ),
                                                new THREE.Vector2( aX, aY ) );
    this.curves.push( curve );

    this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );

};

THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
                                               aCP2x, aCP2y,
                                               aX, aY ) {

    var args = Array.prototype.slice.call( arguments );

    var lastargs = this.actions[ this.actions.length - 1 ].args;

    var x0 = lastargs[ lastargs.length - 2 ];
    var y0 = lastargs[ lastargs.length - 1 ];

    var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
                                            new THREE.Vector2( aCP1x, aCP1y ),
                                            new THREE.Vector2( aCP2x, aCP2y ),
                                            new THREE.Vector2( aX, aY ) );
    this.curves.push( curve );

    this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );

};

THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {

    var args = Array.prototype.slice.call( arguments );
    var lastargs = this.actions[ this.actions.length - 1 ].args;

    var x0 = lastargs[ lastargs.length - 2 ];
    var y0 = lastargs[ lastargs.length - 1 ];
//---
    var npts = [ new THREE.Vector2( x0, y0 ) ];
    Array.prototype.push.apply( npts, pts );

    var curve = new THREE.SplineCurve( npts );
    this.curves.push( curve );

    this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );

};

// FUTURE: Change the API or follow canvas API?

THREE.Path.prototype.arc = function ( aX, aY, aRadius,
                                      aStartAngle, aEndAngle, aClockwise ) {

    var lastargs = this.actions[ this.actions.length - 1].args;
    var x0 = lastargs[ lastargs.length - 2 ];
    var y0 = lastargs[ lastargs.length - 1 ];

    this.absarc(aX + x0, aY + y0, aRadius,
        aStartAngle, aEndAngle, aClockwise );

 };

 THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
                                      aStartAngle, aEndAngle, aClockwise ) {
    this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
 };

THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
                                      aStartAngle, aEndAngle, aClockwise ) {

    var lastargs = this.actions[ this.actions.length - 1].args;
    var x0 = lastargs[ lastargs.length - 2 ];
    var y0 = lastargs[ lastargs.length - 1 ];

    this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
        aStartAngle, aEndAngle, aClockwise );

 };


THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
                                      aStartAngle, aEndAngle, aClockwise ) {

    var args = Array.prototype.slice.call( arguments );
    var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
                                    aStartAngle, aEndAngle, aClockwise );
    this.curves.push( curve );

    var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
    args.push(lastPoint.x);
    args.push(lastPoint.y);

    this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );

 };

THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {

    if ( ! divisions ) divisions = 40;

    var points = [];

    for ( var i = 0; i < divisions; i ++ ) {

        points.push( this.getPoint( i / divisions ) );

        //if( !this.getPoint( i / divisions ) ) throw "DIE";

    }

    // if ( closedPath ) {
    //
    //     points.push( points[ 0 ] );
    //
    // }

    return points;

};

/* Return an array of vectors based on contour of the path */

THREE.Path.prototype.getPoints = function( divisions, closedPath ) {

    if (this.useSpacedPoints) {
        console.log('tata');
        return this.getSpacedPoints( divisions, closedPath );
    }

    divisions = divisions || 12;

    var points = [];

    var i, il, item, action, args;
    var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
        laste, j,
        t, tx, ty;

    for ( i = 0, il = this.actions.length; i < il; i ++ ) {

        item = this.actions[ i ];

        action = item.action;
        args = item.args;

        switch( action ) {

        case THREE.PathActions.MOVE_TO:

            points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );

            break;

        case THREE.PathActions.LINE_TO:

            points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );

            break;

        case THREE.PathActions.QUADRATIC_CURVE_TO:

            cpx  = args[ 2 ];
            cpy  = args[ 3 ];

            cpx1 = args[ 0 ];
            cpy1 = args[ 1 ];

            if ( points.length > 0 ) {

                laste = points[ points.length - 1 ];

                cpx0 = laste.x;
                cpy0 = laste.y;

            } else {

                laste = this.actions[ i - 1 ].args;

                cpx0 = laste[ laste.length - 2 ];
                cpy0 = laste[ laste.length - 1 ];

            }

            for ( j = 1; j <= divisions; j ++ ) {

                t = j / divisions;

                tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
                ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );

                points.push( new THREE.Vector2( tx, ty ) );

              }

            break;

        case THREE.PathActions.BEZIER_CURVE_TO:

            cpx  = args[ 4 ];
            cpy  = args[ 5 ];

            cpx1 = args[ 0 ];
            cpy1 = args[ 1 ];

            cpx2 = args[ 2 ];
            cpy2 = args[ 3 ];

            if ( points.length > 0 ) {

                laste = points[ points.length - 1 ];

                cpx0 = laste.x;
                cpy0 = laste.y;

            } else {

                laste = this.actions[ i - 1 ].args;

                cpx0 = laste[ laste.length - 2 ];
                cpy0 = laste[ laste.length - 1 ];

            }


            for ( j = 1; j <= divisions; j ++ ) {

                t = j / divisions;

                tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
                ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );

                points.push( new THREE.Vector2( tx, ty ) );

            }

            break;

        case THREE.PathActions.CSPLINE_THRU:

            laste = this.actions[ i - 1 ].args;

            var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
            var spts = [ last ];

            var n = divisions * args[ 0 ].length;

            spts = spts.concat( args[ 0 ] );

            var spline = new THREE.SplineCurve( spts );

            for ( j = 1; j <= n; j ++ ) {

                points.push( spline.getPointAt( j / n ) ) ;

            }

            break;

        case THREE.PathActions.ARC:

            var aX = args[ 0 ], aY = args[ 1 ],
                aRadius = args[ 2 ],
                aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
                aClockwise = !!args[ 5 ];

            var deltaAngle = aEndAngle - aStartAngle;
            var angle;
            var tdivisions = divisions * 2;

            for ( j = 1; j <= tdivisions; j ++ ) {

                t = j / tdivisions;

                if ( ! aClockwise ) {

                    t = 1 - t;

                }

                angle = aStartAngle + t * deltaAngle;

                tx = aX + aRadius * Math.cos( angle );
                ty = aY + aRadius * Math.sin( angle );

                //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);

                points.push( new THREE.Vector2( tx, ty ) );

            }

            //console.log(points);

          break;

        case THREE.PathActions.ELLIPSE:

            var aX = args[ 0 ], aY = args[ 1 ],
                xRadius = args[ 2 ],
                yRadius = args[ 3 ],
                aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
                aClockwise = !!args[ 6 ];


            var deltaAngle = aEndAngle - aStartAngle;
            var angle;
            var tdivisions = divisions * 2;

            for ( j = 1; j <= tdivisions; j ++ ) {

                t = j / tdivisions;

                if ( ! aClockwise ) {

                    t = 1 - t;

                }

                angle = aStartAngle + t * deltaAngle;

                tx = aX + xRadius * Math.cos( angle );
                ty = aY + yRadius * Math.sin( angle );

                //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);

                points.push( new THREE.Vector2( tx, ty ) );

            }

            //console.log(points);

          break;

        } // end switch

    }



    // Normalize to remove the closing point by default.
    var lastPoint = points[ points.length - 1];
    var EPSILON = 0.0000000001;
    if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
             Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
        points.splice( points.length - 1, 1);
    if ( closedPath ) {

        points.push( points[ 0 ] );

    }

    return points;

};

// Breaks path into shapes

THREE.Path.prototype.toShapes = function() {

    var i, il, item, action, args;

    var subPaths = [], lastPath = new THREE.Path();

    for ( i = 0, il = this.actions.length; i < il; i ++ ) {

        item = this.actions[ i ];

        args = item.args;
        action = item.action;

        if ( action == THREE.PathActions.MOVE_TO ) {

            if ( lastPath.actions.length != 0 ) {

                subPaths.push( lastPath );
                lastPath = new THREE.Path();

            }

        }

        lastPath[ action ].apply( lastPath, args );

    }

    if ( lastPath.actions.length != 0 ) {

        subPaths.push( lastPath );

    }

    // console.log(subPaths);

    if ( subPaths.length == 0 ) return [];

    var tmpPath, tmpShape, shapes = [];

    var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
    // console.log("Holes first", holesFirst);

    if ( subPaths.length == 1) {
        tmpPath = subPaths[0];
        tmpShape = new THREE.Shape();
        tmpShape.actions = tmpPath.actions;
        tmpShape.curves = tmpPath.curves;
        shapes.push( tmpShape );
        return shapes;
    };

    if ( holesFirst ) {

        tmpShape = new THREE.Shape();

        for ( i = 0, il = subPaths.length; i < il; i ++ ) {

            tmpPath = subPaths[ i ];

            if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {

                tmpShape.actions = tmpPath.actions;
                tmpShape.curves = tmpPath.curves;

                shapes.push( tmpShape );
                tmpShape = new THREE.Shape();

                //console.log('cw', i);

            } else {

                tmpShape.holes.push( tmpPath );

                //console.log('ccw', i);

            }

        }

    } else {

        // Shapes first

        for ( i = 0, il = subPaths.length; i < il; i ++ ) {

            tmpPath = subPaths[ i ];

            if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {


                if ( tmpShape ) shapes.push( tmpShape );

                tmpShape = new THREE.Shape();
                tmpShape.actions = tmpPath.actions;
                tmpShape.curves = tmpPath.curves;

            } else {

                tmpShape.holes.push( tmpPath );

            }

        }

        shapes.push( tmpShape );

    }

    //console.log("shape", shapes);

    return shapes;

};
/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * Defines a 2d shape plane using paths.
 **/

// STEP 1 Create a path.
// STEP 2 Turn path into shape.
// STEP 3 ExtrudeGeometry takes in Shape/Shapes
// STEP 3a - Extract points from each shape, turn to vertices
// STEP 3b - Triangulate each shape, add faces.

THREE.Shape = function ( ) {

    THREE.Path.apply( this, arguments );
    this.holes = [];

};

THREE.Shape.prototype = Object.create( THREE.Path.prototype );

// Convenience method to return ExtrudeGeometry

THREE.Shape.prototype.extrude = function ( options ) {

    var extruded = new THREE.ExtrudeGeometry( this, options );
    return extruded;

};

// Convenience method to return ShapeGeometry

THREE.Shape.prototype.makeGeometry = function ( options ) {

    var geometry = new THREE.ShapeGeometry( this, options );
    return geometry;

};

// Get points of holes

THREE.Shape.prototype.getPointsHoles = function ( divisions ) {

    var i, il = this.holes.length, holesPts = [];

    for ( i = 0; i < il; i ++ ) {

        holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );

    }

    return holesPts;

};

// Get points of holes (spaced by regular distance)

THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {

    var i, il = this.holes.length, holesPts = [];

    for ( i = 0; i < il; i ++ ) {

        holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );

    }

    return holesPts;

};


// Get points of shape and holes (keypoints based on segments parameter)

THREE.Shape.prototype.extractAllPoints = function ( divisions ) {

    return {

        shape: this.getTransformedPoints( divisions ),
        holes: this.getPointsHoles( divisions )

    };

};

THREE.Shape.prototype.extractPoints = function ( divisions ) {

    if (this.useSpacedPoints) {
        return this.extractAllSpacedPoints(divisions);
    }

    return this.extractAllPoints(divisions);

};

//
// THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
//
//     return {
//
//         shape: this.transform( bend, divisions ),
//         holes: this.getPointsHoles( divisions, bend )
//
//     };
//
// };

// Get points of shape and holes (spaced by regular distance)

THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {

    return {

        shape: this.getTransformedSpacedPoints( divisions ),
        holes: this.getSpacedPointsHoles( divisions )

    };

};

/**************************************************************
 *    Utils
 **************************************************************/

THREE.Shape.Utils = {

    /*
        contour - array of vector2 for contour
        holes   - array of array of vector2
    */

    removeHoles: function ( contour, holes ) {

        var shape = contour.concat(); // work on this shape
        var allpoints = shape.concat();

        /* For each isolated shape, find the closest points and break to the hole to allow triangulation */


        var prevShapeVert, nextShapeVert,
            prevHoleVert, nextHoleVert,
            holeIndex, shapeIndex,
            shapeId, shapeGroup,
            h, h2,
            hole, shortest, d,
            p, pts1, pts2,
            tmpShape1, tmpShape2,
            tmpHole1, tmpHole2,
            verts = [];

        for ( h = 0; h < holes.length; h ++ ) {

            hole = holes[ h ];

            /*
            shapeholes[ h ].concat(); // preserves original
            holes.push( hole );
            */

            Array.prototype.push.apply( allpoints, hole );

            shortest = Number.POSITIVE_INFINITY;


            // Find the shortest pair of pts between shape and hole

            // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
            // Using distanceToSquared() intead of distanceTo() should speed a little
            // since running square roots operations are reduced.

            for ( h2 = 0; h2 < hole.length; h2 ++ ) {

                pts1 = hole[ h2 ];
                var dist = [];

                for ( p = 0; p < shape.length; p++ ) {

                    pts2 = shape[ p ];
                    d = pts1.distanceToSquared( pts2 );
                    dist.push( d );

                    if ( d < shortest ) {

                        shortest = d;
                        holeIndex = h2;
                        shapeIndex = p;

                    }

                }

            }

            //console.log("shortest", shortest, dist);

            prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
            prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;

            var areaapts = [

                hole[ holeIndex ],
                shape[ shapeIndex ],
                shape[ prevShapeVert ]

            ];

            var areaa = THREE.FontUtils.Triangulate.area( areaapts );

            var areabpts = [

                hole[ holeIndex ],
                hole[ prevHoleVert ],
                shape[ shapeIndex ]

            ];

            var areab = THREE.FontUtils.Triangulate.area( areabpts );

            var shapeOffset = 1;
            var holeOffset = -1;

            var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
            shapeIndex += shapeOffset;
            holeIndex += holeOffset;

            if ( shapeIndex < 0 ) { shapeIndex += shape.length;  }
            shapeIndex %= shape.length;

            if ( holeIndex < 0 ) { holeIndex += hole.length;  }
            holeIndex %= hole.length;

            prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
            prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;

            areaapts = [

                hole[ holeIndex ],
                shape[ shapeIndex ],
                shape[ prevShapeVert ]

            ];

            var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );

            areabpts = [

                hole[ holeIndex ],
                hole[ prevHoleVert ],
                shape[ shapeIndex ]

            ];

            var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
            //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ),  ( areaa2 + areab2 ));

            if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {

                // In case areas are not correct.
                //console.log("USE THIS");

                shapeIndex = oldShapeIndex;
                holeIndex = oldHoleIndex ;

                if ( shapeIndex < 0 ) { shapeIndex += shape.length;  }
                shapeIndex %= shape.length;

                if ( holeIndex < 0 ) { holeIndex += hole.length;  }
                holeIndex %= hole.length;

                prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
                prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;

            } else {

                //console.log("USE THAT ")

            }

            tmpShape1 = shape.slice( 0, shapeIndex );
            tmpShape2 = shape.slice( shapeIndex );
            tmpHole1 = hole.slice( holeIndex );
            tmpHole2 = hole.slice( 0, holeIndex );

            // Should check orders here again?

            var trianglea = [

                hole[ holeIndex ],
                shape[ shapeIndex ],
                shape[ prevShapeVert ]

            ];

            var triangleb = [

                hole[ holeIndex ] ,
                hole[ prevHoleVert ],
                shape[ shapeIndex ]

            ];

            verts.push( trianglea );
            verts.push( triangleb );

            shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );

        }

        return {

            shape:shape,         /* shape with no holes */
            isolatedPts: verts, /* isolated faces */
            allpoints: allpoints

        }


    },

    triangulateShape: function ( contour, holes ) {

        var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );

        var shape = shapeWithoutHoles.shape,
            allpoints = shapeWithoutHoles.allpoints,
            isolatedPts = shapeWithoutHoles.isolatedPts;

        var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape

        // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.

        //console.log( "triangles",triangles, triangles.length );
        //console.log( "allpoints",allpoints, allpoints.length );

        var i, il, f, face,
            key, index,
            allPointsMap = {},
            isolatedPointsMap = {};

        // prepare all points map

        for ( i = 0, il = allpoints.length; i < il; i ++ ) {

            key = allpoints[ i ].x + ":" + allpoints[ i ].y;

            if ( allPointsMap[ key ] !== undefined ) {

                console.log( "Duplicate point", key );

            }

            allPointsMap[ key ] = i;

        }

        // check all face vertices against all points map

        for ( i = 0, il = triangles.length; i < il; i ++ ) {

            face = triangles[ i ];

            for ( f = 0; f < 3; f ++ ) {

                key = face[ f ].x + ":" + face[ f ].y;

                index = allPointsMap[ key ];

                if ( index !== undefined ) {

                    face[ f ] = index;

                }

            }

        }

        // check isolated points vertices against all points map

        for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {

            face = isolatedPts[ i ];

            for ( f = 0; f < 3; f ++ ) {

                key = face[ f ].x + ":" + face[ f ].y;

                index = allPointsMap[ key ];

                if ( index !== undefined ) {

                    face[ f ] = index;

                }

            }

        }

        return triangles.concat( isolatedPts );

    }, // end triangulate shapes

    /*
    triangulate2 : function( pts, holes ) {

        // For use with Poly2Tri.js

        var allpts = pts.concat();
        var shape = [];
        for (var p in pts) {
            shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
        }

        var swctx = new js.poly2tri.SweepContext(shape);

        for (var h in holes) {
            var aHole = holes[h];
            var newHole = []
            for (i in aHole) {
                newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
                allpts.push(aHole[i]);
            }
            swctx.AddHole(newHole);
        }

        var find;
        var findIndexForPt = function (pt) {
            find = new THREE.Vector2(pt.x, pt.y);
            var p;
            for (p=0, pl = allpts.length; p<pl; p++) {
                if (allpts[p].equals(find)) return p;
            }
            return -1;
        };

        // triangulate
        js.poly2tri.sweep.Triangulate(swctx);

        var triangles =  swctx.GetTriangles();
        var tr ;
        var facesPts = [];
        for (var t in triangles) {
            tr =  triangles[t];
            facesPts.push([
                findIndexForPt(tr.GetPoint(0)),
                findIndexForPt(tr.GetPoint(1)),
                findIndexForPt(tr.GetPoint(2))
                    ]);
        }


    //    console.log(facesPts);
    //    console.log("triangles", triangles.length, triangles);

        // Returns array of faces with 3 element each
    return facesPts;
    },
*/

    isClockWise: function ( pts ) {

        return THREE.FontUtils.Triangulate.area( pts ) < 0;

    },

    // Bezier Curves formulas obtained from
    // http://en.wikipedia.org/wiki/B%C3%A9zier_curve

    // Quad Bezier Functions

    b2p0: function ( t, p ) {

        var k = 1 - t;
        return k * k * p;

    },

    b2p1: function ( t, p ) {

        return 2 * ( 1 - t ) * t * p;

    },

    b2p2: function ( t, p ) {

        return t * t * p;

    },

    b2: function ( t, p0, p1, p2 ) {

        return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );

    },

    // Cubic Bezier Functions

    b3p0: function ( t, p ) {

        var k = 1 - t;
        return k * k * k * p;

    },

    b3p1: function ( t, p ) {

        var k = 1 - t;
        return 3 * k * k * t * p;

    },

    b3p2: function ( t, p ) {

        var k = 1 - t;
        return 3 * k * t * t * p;

    },

    b3p3: function ( t, p ) {

        return t * t * t * p;

    },

    b3: function ( t, p0, p1, p2, p3 ) {

        return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) +  this.b3p3( t, p3 );

    }

};

/**
 * @author mikael emtinger / http://gomo.se/
 */

THREE.AnimationHandler = (function() {

    var playing = [];
    var library = {};
    var that    = {};


    //--- update ---

    that.update = function( deltaTimeMS ) {

        for( var i = 0; i < playing.length; i ++ )
            playing[ i ].update( deltaTimeMS );

    };


    //--- add ---

    that.addToUpdate = function( animation ) {

        if ( playing.indexOf( animation ) === -1 )
            playing.push( animation );

    };


    //--- remove ---

    that.removeFromUpdate = function( animation ) {

        var index = playing.indexOf( animation );

        if( index !== -1 )
            playing.splice( index, 1 );

    };


    //--- add ---

    that.add = function( data ) {

        if ( library[ data.name ] !== undefined )
            console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );

        library[ data.name ] = data;
        initData( data );

    };


    //--- get ---

    that.get = function( name ) {

        if ( typeof name === "string" ) {

            if ( library[ name ] ) {

                return library[ name ];

            } else {

                console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
                return null;

            }

        } else {

            // todo: add simple tween library

        }

    };

    //--- parse ---

    that.parse = function( root ) {

        // setup hierarchy

        var hierarchy = [];

        if ( root instanceof THREE.SkinnedMesh ) {

            for( var b = 0; b < root.bones.length; b++ ) {

                hierarchy.push( root.bones[ b ] );

            }

        } else {

            parseRecurseHierarchy( root, hierarchy );

        }

        return hierarchy;

    };

    var parseRecurseHierarchy = function( root, hierarchy ) {

        hierarchy.push( root );

        for( var c = 0; c < root.children.length; c++ )
            parseRecurseHierarchy( root.children[ c ], hierarchy );

    }


    //--- init data ---

    var initData = function( data ) {

        if( data.initialized === true )
            return;


        // loop through all keys

        for( var h = 0; h < data.hierarchy.length; h ++ ) {

            for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {

                // remove minus times

                if( data.hierarchy[ h ].keys[ k ].time < 0 )
                    data.hierarchy[ h ].keys[ k ].time = 0;


                // create quaternions

                if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
                 !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {

                    var quat = data.hierarchy[ h ].keys[ k ].rot;
                    data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );

                }

            }


            // prepare morph target keys

            if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {

                // get all used

                var usedMorphTargets = {};

                for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {

                    for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {

                        var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
                        usedMorphTargets[ morphTargetName ] = -1;

                    }

                }

                data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;


                // set all used on all frames

                for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {

                    var influences = {};

                    for ( var morphTargetName in usedMorphTargets ) {

                        for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {

                            if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {

                                influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
                                break;

                            }

                        }

                        if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {

                            influences[ morphTargetName ] = 0;

                        }

                    }

                    data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;

                }

            }


            // remove all keys that are on the same time

            for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {

                if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {

                    data.hierarchy[ h ].keys.splice( k, 1 );
                    k --;

                }

            }


            // set index

            for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {

                data.hierarchy[ h ].keys[ k ].index = k;

            }

        }


        // JIT

        var lengthInFrames = parseInt( data.length * data.fps, 10 );

        data.JIT = {};
        data.JIT.hierarchy = [];

        for( var h = 0; h < data.hierarchy.length; h ++ )
            data.JIT.hierarchy.push( new Array( lengthInFrames ) );


        // done

        data.initialized = true;

    };


    // interpolation types

    that.LINEAR = 0;
    that.CATMULLROM = 1;
    that.CATMULLROM_FORWARD = 2;

    return that;

}());
/**
 * @author mikael emtinger / http://gomo.se/
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.Animation = function ( root, name, interpolationType ) {

    this.root = root;
    this.data = THREE.AnimationHandler.get( name );
    this.hierarchy = THREE.AnimationHandler.parse( root );

    this.currentTime = 0;
    this.timeScale = 1;

    this.isPlaying = false;
    this.isPaused = true;
    this.loop = true;

    this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;

    this.points = [];
    this.target = new THREE.Vector3();

};

THREE.Animation.prototype.play = function ( loop, startTimeMS ) {

    if ( this.isPlaying === false ) {

        this.isPlaying = true;
        this.loop = loop !== undefined ? loop : true;
        this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;

        // reset key cache

        var h, hl = this.hierarchy.length,
            object;

        for ( h = 0; h < hl; h ++ ) {

            object = this.hierarchy[ h ];

            if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {

                object.useQuaternion = true;

            }

            object.matrixAutoUpdate = true;

            if ( object.animationCache === undefined ) {

                object.animationCache = {};
                object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
                object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
                object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;

            }

            var prevKey = object.animationCache.prevKey;
            var nextKey = object.animationCache.nextKey;

            prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
            prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
            prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];

            nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
            nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
            nextKey.scl = this.getNextKeyWith( "scl", h, 1 );

        }

        this.update( 0 );

    }

    this.isPaused = false;

    THREE.AnimationHandler.addToUpdate( this );

};


THREE.Animation.prototype.pause = function() {

    if ( this.isPaused === true ) {

        THREE.AnimationHandler.addToUpdate( this );

    } else {

        THREE.AnimationHandler.removeFromUpdate( this );

    }

    this.isPaused = !this.isPaused;

};


THREE.Animation.prototype.stop = function() {

    this.isPlaying = false;
    this.isPaused  = false;
    THREE.AnimationHandler.removeFromUpdate( this );

};


THREE.Animation.prototype.update = function ( deltaTimeMS ) {

    // early out

    if ( this.isPlaying === false ) return;


    // vars

    var types = [ "pos", "rot", "scl" ];
    var type;
    var scale;
    var vector;
    var prevXYZ, nextXYZ;
    var prevKey, nextKey;
    var object;
    var animationCache;
    var frame;
    var JIThierarchy = this.data.JIT.hierarchy;
    var currentTime, unloopedCurrentTime;
    var currentPoint, forwardPoint, angle;


    this.currentTime += deltaTimeMS * this.timeScale;

    unloopedCurrentTime = this.currentTime;
    currentTime = this.currentTime = this.currentTime % this.data.length;
    frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );


    for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {

        object = this.hierarchy[ h ];
        animationCache = object.animationCache;

        // loop through pos/rot/scl

        for ( var t = 0; t < 3; t ++ ) {

            // get keys

            type    = types[ t ];
            prevKey = animationCache.prevKey[ type ];
            nextKey = animationCache.nextKey[ type ];

            // switch keys?

            if ( nextKey.time <= unloopedCurrentTime ) {

                // did we loop?

                if ( currentTime < unloopedCurrentTime ) {

                    if ( this.loop ) {

                        prevKey = this.data.hierarchy[ h ].keys[ 0 ];
                        nextKey = this.getNextKeyWith( type, h, 1 );

                        while( nextKey.time < currentTime ) {

                            prevKey = nextKey;
                            nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );

                        }

                    } else {

                        this.stop();
                        return;

                    }

                } else {

                    do {

                        prevKey = nextKey;
                        nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );

                    } while( nextKey.time < currentTime )

                }

                animationCache.prevKey[ type ] = prevKey;
                animationCache.nextKey[ type ] = nextKey;

            }


            object.matrixAutoUpdate = true;
            object.matrixWorldNeedsUpdate = true;

            scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
            prevXYZ = prevKey[ type ];
            nextXYZ = nextKey[ type ];


            // check scale error

            if ( scale < 0 || scale > 1 ) {

                console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
                scale = scale < 0 ? 0 : 1;

            }

            // interpolate

            if ( type === "pos" ) {

                vector = object.position;

                if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {

                    vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
                    vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
                    vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;

                } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
                            this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

                    this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
                    this.points[ 1 ] = prevXYZ;
                    this.points[ 2 ] = nextXYZ;
                    this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];

                    scale = scale * 0.33 + 0.33;

                    currentPoint = this.interpolateCatmullRom( this.points, scale );

                    vector.x = currentPoint[ 0 ];
                    vector.y = currentPoint[ 1 ];
                    vector.z = currentPoint[ 2 ];

                    if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

                        forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );

                        this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
                        this.target.subSelf( vector );
                        this.target.y = 0;
                        this.target.normalize();

                        angle = Math.atan2( this.target.x, this.target.z );
                        object.rotation.set( 0, angle, 0 );

                    }

                }

            } else if ( type === "rot" ) {

                THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );

            } else if ( type === "scl" ) {

                vector = object.scale;

                vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
                vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
                vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;

            }

        }

    }

};

// Catmull-Rom spline

THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {

    var c = [], v3 = [],
    point, intPoint, weight, w2, w3,
    pa, pb, pc, pd;

    point = ( points.length - 1 ) * scale;
    intPoint = Math.floor( point );
    weight = point - intPoint;

    c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
    c[ 1 ] = intPoint;
    c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
    c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;

    pa = points[ c[ 0 ] ];
    pb = points[ c[ 1 ] ];
    pc = points[ c[ 2 ] ];
    pd = points[ c[ 3 ] ];

    w2 = weight * weight;
    w3 = weight * w2;

    v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
    v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
    v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );

    return v3;

};

THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {

    var v0 = ( p2 - p0 ) * 0.5,
        v1 = ( p3 - p1 ) * 0.5;

    return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;

};



// Get next key with

THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {

    var keys = this.data.hierarchy[ h ].keys;

    if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
         this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

        key = key < keys.length - 1 ? key : keys.length - 1;

    } else {

        key = key % keys.length;

    }

    for ( ; key < keys.length; key++ ) {

        if ( keys[ key ][ type ] !== undefined ) {

            return keys[ key ];

        }

    }

    return this.data.hierarchy[ h ].keys[ 0 ];

};

// Get previous key with

THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {

    var keys = this.data.hierarchy[ h ].keys;

    if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
         this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {

        key = key > 0 ? key : 0;

    } else {

        key = key >= 0 ? key : key + keys.length;

    }


    for ( ; key >= 0; key -- ) {

        if ( keys[ key ][ type ] !== undefined ) {

            return keys[ key ];

        }

    }

    return this.data.hierarchy[ h ].keys[ keys.length - 1 ];

};
/**
 * @author mikael emtinger / http://gomo.se/
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author khang duong
 * @author erik kitson
 */

THREE.KeyFrameAnimation = function( root, data, JITCompile ) {

    this.root = root;
    this.data = THREE.AnimationHandler.get( data );
    this.hierarchy = THREE.AnimationHandler.parse( root );
    this.currentTime = 0;
    this.timeScale = 0.001;
    this.isPlaying = false;
    this.isPaused = true;
    this.loop = true;
    this.JITCompile = JITCompile !== undefined ? JITCompile : true;

    // initialize to first keyframes

    for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {

        var keys = this.data.hierarchy[h].keys,
            sids = this.data.hierarchy[h].sids,
            obj = this.hierarchy[h];

        if ( keys.length && sids ) {

            for ( var s = 0; s < sids.length; s++ ) {

                var sid = sids[ s ],
                    next = this.getNextKeyWith( sid, h, 0 );

                if ( next ) {

                    next.apply( sid );

                }

            }

            obj.matrixAutoUpdate = false;
            this.data.hierarchy[h].node.updateMatrix();
            obj.matrixWorldNeedsUpdate = true;

        }

    }

};

// Play

THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {

    if( !this.isPlaying ) {

        this.isPlaying = true;
        this.loop = loop !== undefined ? loop : true;
        this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
        this.startTimeMs = startTimeMS;
        this.startTime = 10000000;
        this.endTime = -this.startTime;


        // reset key cache

        var h, hl = this.hierarchy.length,
            object,
            node;

        for ( h = 0; h < hl; h++ ) {

            object = this.hierarchy[ h ];
            node = this.data.hierarchy[ h ];
            object.useQuaternion = true;

            if ( node.animationCache === undefined ) {

                node.animationCache = {};
                node.animationCache.prevKey = null;
                node.animationCache.nextKey = null;
                node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;

            }

            var keys = this.data.hierarchy[h].keys;

            if (keys.length) {

                node.animationCache.prevKey = keys[ 0 ];
                node.animationCache.nextKey = keys[ 1 ];

                this.startTime = Math.min( keys[0].time, this.startTime );
                this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );

            }

        }

        this.update( 0 );

    }

    this.isPaused = false;

    THREE.AnimationHandler.addToUpdate( this );

};



// Pause

THREE.KeyFrameAnimation.prototype.pause = function() {

    if( this.isPaused ) {

        THREE.AnimationHandler.addToUpdate( this );

    } else {

        THREE.AnimationHandler.removeFromUpdate( this );

    }

    this.isPaused = !this.isPaused;

};


// Stop

THREE.KeyFrameAnimation.prototype.stop = function() {

    this.isPlaying = false;
    this.isPaused  = false;
    THREE.AnimationHandler.removeFromUpdate( this );


    // reset JIT matrix and remove cache

    for ( var h = 0; h < this.data.hierarchy.length; h++ ) {

        var obj = this.hierarchy[ h ];
        var node = this.data.hierarchy[ h ];

        if ( node.animationCache !== undefined ) {

            var original = node.animationCache.originalMatrix;

            if( obj instanceof THREE.Bone ) {

                original.copy( obj.skinMatrix );
                obj.skinMatrix = original;

            } else {

                original.copy( obj.matrix );
                obj.matrix = original;

            }

            delete node.animationCache;

        }

    }

};


// Update

THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {

    // early out

    if( !this.isPlaying ) return;


    // vars

    var prevKey, nextKey;
    var object;
    var node;
    var frame;
    var JIThierarchy = this.data.JIT.hierarchy;
    var currentTime, unloopedCurrentTime;
    var looped;


    // update

    this.currentTime += deltaTimeMS * this.timeScale;

    unloopedCurrentTime = this.currentTime;
    currentTime         = this.currentTime = this.currentTime % this.data.length;

    // if looped around, the current time should be based on the startTime
    if ( currentTime < this.startTimeMs ) {

        currentTime = this.currentTime = this.startTimeMs + currentTime;

    }

    frame               = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
    looped                 = currentTime < unloopedCurrentTime;

    if ( looped && !this.loop ) {

        // Set the animation to the last keyframes and stop
        for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {

            var keys = this.data.hierarchy[h].keys,
                sids = this.data.hierarchy[h].sids,
                end = keys.length-1,
                obj = this.hierarchy[h];

            if ( keys.length ) {

                for ( var s = 0; s < sids.length; s++ ) {

                    var sid = sids[ s ],
                        prev = this.getPrevKeyWith( sid, h, end );

                    if ( prev ) {
                        prev.apply( sid );

                    }

                }

                this.data.hierarchy[h].node.updateMatrix();
                obj.matrixWorldNeedsUpdate = true;

            }

        }

        this.stop();
        return;

    }

    // check pre-infinity
    if ( currentTime < this.startTime ) {

        return;

    }

    // update

    for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {

        object = this.hierarchy[ h ];
        node = this.data.hierarchy[ h ];

        var keys = node.keys,
            animationCache = node.animationCache;

        // use JIT?

        if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {

            if( object instanceof THREE.Bone ) {

                object.skinMatrix = JIThierarchy[ h ][ frame ];
                object.matrixWorldNeedsUpdate = false;

            } else {

                object.matrix = JIThierarchy[ h ][ frame ];
                object.matrixWorldNeedsUpdate = true;

            }

        // use interpolation

        } else if ( keys.length ) {

            // make sure so original matrix and not JIT matrix is set

            if ( this.JITCompile && animationCache ) {

                if( object instanceof THREE.Bone ) {

                    object.skinMatrix = animationCache.originalMatrix;

                } else {

                    object.matrix = animationCache.originalMatrix;

                }

            }

            prevKey = animationCache.prevKey;
            nextKey = animationCache.nextKey;

            if ( prevKey && nextKey ) {

                // switch keys?

                if ( nextKey.time <= unloopedCurrentTime ) {

                    // did we loop?

                    if ( looped && this.loop ) {

                        prevKey = keys[ 0 ];
                        nextKey = keys[ 1 ];

                        while ( nextKey.time < currentTime ) {

                            prevKey = nextKey;
                            nextKey = keys[ prevKey.index + 1 ];

                        }

                    } else if ( !looped ) {

                        var lastIndex = keys.length - 1;

                        while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {

                            prevKey = nextKey;
                            nextKey = keys[ prevKey.index + 1 ];

                        }

                    }

                    animationCache.prevKey = prevKey;
                    animationCache.nextKey = nextKey;

                }
                if(nextKey.time >= currentTime)
                    prevKey.interpolate( nextKey, currentTime );
                else
                    prevKey.interpolate( nextKey, nextKey.time);

            }

            this.data.hierarchy[h].node.updateMatrix();
            object.matrixWorldNeedsUpdate = true;

        }

    }

    // update JIT?

    if ( this.JITCompile ) {

        if ( JIThierarchy[ 0 ][ frame ] === undefined ) {

            this.hierarchy[ 0 ].updateMatrixWorld( true );

            for ( var h = 0; h < this.hierarchy.length; h++ ) {

                if( this.hierarchy[ h ] instanceof THREE.Bone ) {

                    JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();

                } else {

                    JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();

                }

            }

        }

    }

};

// Get next key with

THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {

    var keys = this.data.hierarchy[ h ].keys;
    key = key % keys.length;

    for ( ; key < keys.length; key++ ) {

        if ( keys[ key ].hasTarget( sid ) ) {

            return keys[ key ];

        }

    }

    return keys[ 0 ];

};

// Get previous key with

THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {

    var keys = this.data.hierarchy[ h ].keys;
    key = key >= 0 ? key : key + keys.length;

    for ( ; key >= 0; key-- ) {

        if ( keys[ key ].hasTarget( sid ) ) {

            return keys[ key ];

        }

    }

    return keys[ keys.length - 1 ];

};
/**
 * Camera for rendering cube maps
 *    - renders scene into axis-aligned cube
 *
 * @author alteredq / http://alteredqualia.com/
 */

THREE.CubeCamera = function ( near, far, cubeResolution ) {

    THREE.Object3D.call( this );

    var fov = 90, aspect = 1;

    var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
    cameraPX.up.set( 0, -1, 0 );
    cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
    this.add( cameraPX );

    var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
    cameraNX.up.set( 0, -1, 0 );
    cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
    this.add( cameraNX );

    var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
    cameraPY.up.set( 0, 0, 1 );
    cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
    this.add( cameraPY );

    var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
    cameraNY.up.set( 0, 0, -1 );
    cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
    this.add( cameraNY );

    var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
    cameraPZ.up.set( 0, -1, 0 );
    cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
    this.add( cameraPZ );

    var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
    cameraNZ.up.set( 0, -1, 0 );
    cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
    this.add( cameraNZ );

    this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );

    this.updateCubeMap = function ( renderer, scene ) {

        var renderTarget = this.renderTarget;
        var generateMipmaps = renderTarget.generateMipmaps;

        renderTarget.generateMipmaps = false;

        renderTarget.activeCubeFace = 0;
        renderer.render( scene, cameraPX, renderTarget );

        renderTarget.activeCubeFace = 1;
        renderer.render( scene, cameraNX, renderTarget );

        renderTarget.activeCubeFace = 2;
        renderer.render( scene, cameraPY, renderTarget );

        renderTarget.activeCubeFace = 3;
        renderer.render( scene, cameraNY, renderTarget );

        renderTarget.activeCubeFace = 4;
        renderer.render( scene, cameraPZ, renderTarget );

        renderTarget.generateMipmaps = generateMipmaps;

        renderTarget.activeCubeFace = 5;
        renderer.render( scene, cameraNZ, renderTarget );

    };

};

THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
/*
 *    @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
 *
 *    A general perpose camera, for setting FOV, Lens Focal Length,
 *        and switching between perspective and orthographic views easily.
 *        Use this only if you do not wish to manage
 *        both a Orthographic and Perspective Camera
 *
 */


THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {

    THREE.Camera.call( this );

    this.fov = fov;

    this.left = -width / 2;
    this.right = width / 2
    this.top = height / 2;
    this.bottom = -height / 2;

    // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects

    this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2,     orthoNear, orthoFar );
    this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );

    this.zoom = 1;

    this.toPerspective();

    var aspect = width/height;

};

THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );

THREE.CombinedCamera.prototype.toPerspective = function () {

    // Switches to the Perspective Camera

    this.near = this.cameraP.near;
    this.far = this.cameraP.far;

    this.cameraP.fov =  this.fov / this.zoom ;

    this.cameraP.updateProjectionMatrix();

    this.projectionMatrix = this.cameraP.projectionMatrix;

    this.inPerspectiveMode = true;
    this.inOrthographicMode = false;

};

THREE.CombinedCamera.prototype.toOrthographic = function () {

    // Switches to the Orthographic camera estimating viewport from Perspective

    var fov = this.fov;
    var aspect = this.cameraP.aspect;
    var near = this.cameraP.near;
    var far = this.cameraP.far;

    // The size that we set is the mid plane of the viewing frustum

    var hyperfocus = ( near + far ) / 2;

    var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
    var planeHeight = 2 * halfHeight;
    var planeWidth = planeHeight * aspect;
    var halfWidth = planeWidth / 2;

    halfHeight /= this.zoom;
    halfWidth /= this.zoom;

    this.cameraO.left = -halfWidth;
    this.cameraO.right = halfWidth;
    this.cameraO.top = halfHeight;
    this.cameraO.bottom = -halfHeight;

    // this.cameraO.left = -farHalfWidth;
    // this.cameraO.right = farHalfWidth;
    // this.cameraO.top = farHalfHeight;
    // this.cameraO.bottom = -farHalfHeight;

    // this.cameraO.left = this.left / this.zoom;
    // this.cameraO.right = this.right / this.zoom;
    // this.cameraO.top = this.top / this.zoom;
    // this.cameraO.bottom = this.bottom / this.zoom;

    this.cameraO.updateProjectionMatrix();

    this.near = this.cameraO.near;
    this.far = this.cameraO.far;
    this.projectionMatrix = this.cameraO.projectionMatrix;

    this.inPerspectiveMode = false;
    this.inOrthographicMode = true;

};


THREE.CombinedCamera.prototype.setSize = function( width, height ) {

    this.cameraP.aspect = width / height;
    this.left = -width / 2;
    this.right = width / 2
    this.top = height / 2;
    this.bottom = -height / 2;

};


THREE.CombinedCamera.prototype.setFov = function( fov ) {

    this.fov = fov;

    if ( this.inPerspectiveMode ) {

        this.toPerspective();

    } else {

        this.toOrthographic();

    }

};

// For mantaining similar API with PerspectiveCamera

THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {

    if ( this.inPerspectiveMode ) {

        this.toPerspective();

    } else {

        this.toPerspective();
        this.toOrthographic();

    }

};

/*
* Uses Focal Length (in mm) to estimate and set FOV
* 35mm (fullframe) camera is used if frame size is not specified;
* Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
*/
THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {

    if ( frameHeight === undefined ) frameHeight = 24;

    var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );

    this.setFov( fov );

    return fov;
};


THREE.CombinedCamera.prototype.setZoom = function( zoom ) {

    this.zoom = zoom;

    if ( this.inPerspectiveMode ) {

        this.toPerspective();

    } else {

        this.toOrthographic();

    }

};

THREE.CombinedCamera.prototype.toFrontView = function() {

    this.rotation.x = 0;
    this.rotation.y = 0;
    this.rotation.z = 0;

    // should we be modifing the matrix instead?

    this.rotationAutoUpdate = false;

};

THREE.CombinedCamera.prototype.toBackView = function() {

    this.rotation.x = 0;
    this.rotation.y = Math.PI;
    this.rotation.z = 0;
    this.rotationAutoUpdate = false;

};

THREE.CombinedCamera.prototype.toLeftView = function() {

    this.rotation.x = 0;
    this.rotation.y = - Math.PI / 2;
    this.rotation.z = 0;
    this.rotationAutoUpdate = false;

};

THREE.CombinedCamera.prototype.toRightView = function() {

    this.rotation.x = 0;
    this.rotation.y = Math.PI / 2;
    this.rotation.z = 0;
    this.rotationAutoUpdate = false;

};

THREE.CombinedCamera.prototype.toTopView = function() {

    this.rotation.x = - Math.PI / 2;
    this.rotation.y = 0;
    this.rotation.z = 0;
    this.rotationAutoUpdate = false;

};

THREE.CombinedCamera.prototype.toBottomView = function() {

    this.rotation.x = Math.PI / 2;
    this.rotation.y = 0;
    this.rotation.z = 0;
    this.rotationAutoUpdate = false;

};

/**
 * @author mrdoob / http://mrdoob.com/
 * @author alteredq / http://alteredqualia.com/
 * @author paulirish / http://paulirish.com/
 */

THREE.FirstPersonControls = function ( object, domElement ) {

    this.object = object;
    this.target = new THREE.Vector3( 0, 0, 0 );

    this.domElement = ( domElement !== undefined ) ? domElement : document;

    this.movementSpeed = 1.0;
    this.lookSpeed = 0.005;

    this.lookVertical = true;
    this.autoForward = false;
    // this.invertVertical = false;

    this.activeLook = true;

    this.heightSpeed = false;
    this.heightCoef = 1.0;
    this.heightMin = 0.0;
    this.heightMax = 1.0;

    this.constrainVertical = false;
    this.verticalMin = 0;
    this.verticalMax = Math.PI;

    this.autoSpeedFactor = 0.0;

    this.mouseX = 0;
    this.mouseY = 0;

    this.lat = 0;
    this.lon = 0;
    this.phi = 0;
    this.theta = 0;

    this.moveForward = false;
    this.moveBackward = false;
    this.moveLeft = false;
    this.moveRight = false;
    this.freeze = false;

    this.mouseDragOn = false;

    this.viewHalfX = 0;
    this.viewHalfY = 0;

    if ( this.domElement !== document ) {

        this.domElement.setAttribute( 'tabindex', -1 );

    }

    //

    this.handleResize = function () {

        if ( this.domElement === document ) {

            this.viewHalfX = window.innerWidth / 2;
            this.viewHalfY = window.innerHeight / 2;

        } else {

            this.viewHalfX = this.domElement.offsetWidth / 2;
            this.viewHalfY = this.domElement.offsetHeight / 2;

        }

    };

    this.onMouseDown = function ( event ) {

        if ( this.domElement !== document ) {

            this.domElement.focus();

        }

        event.preventDefault();
        event.stopPropagation();

        if ( this.activeLook ) {

            switch ( event.button ) {

                case 0: this.moveForward = true; break;
                case 2: this.moveBackward = true; break;

            }

        }

        this.mouseDragOn = true;

    };

    this.onMouseUp = function ( event ) {

        event.preventDefault();
        event.stopPropagation();

        if ( this.activeLook ) {

            switch ( event.button ) {

                case 0: this.moveForward = false; break;
                case 2: this.moveBackward = false; break;

            }

        }

        this.mouseDragOn = false;

    };

    this.onMouseMove = function ( event ) {

        if ( this.domElement === document ) {

            this.mouseX = event.pageX - this.viewHalfX;
            this.mouseY = event.pageY - this.viewHalfY;

        } else {

            this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
            this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;

        }

    };

    this.onKeyDown = function ( event ) {

        //event.preventDefault();

        switch ( event.keyCode ) {

            case 38: /*up*/
            case 87: /*W*/ this.moveForward = true; break;

            case 37: /*left*/
            case 65: /*A*/ this.moveLeft = true; break;

            case 40: /*down*/
            case 83: /*S*/ this.moveBackward = true; break;

            case 39: /*right*/
            case 68: /*D*/ this.moveRight = true; break;

            case 82: /*R*/ this.moveUp = true; break;
            case 70: /*F*/ this.moveDown = true; break;

            case 81: /*Q*/ this.freeze = !this.freeze; break;

        }

    };

    this.onKeyUp = function ( event ) {

        switch( event.keyCode ) {

            case 38: /*up*/
            case 87: /*W*/ this.moveForward = false; break;

            case 37: /*left*/
            case 65: /*A*/ this.moveLeft = false; break;

            case 40: /*down*/
            case 83: /*S*/ this.moveBackward = false; break;

            case 39: /*right*/
            case 68: /*D*/ this.moveRight = false; break;

            case 82: /*R*/ this.moveUp = false; break;
            case 70: /*F*/ this.moveDown = false; break;

        }

    };

    this.update = function( delta ) {
        var actualMoveSpeed = 0;

        if ( this.freeze ) {

            return;

        } else {

            if ( this.heightSpeed ) {

                var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
                var heightDelta = y - this.heightMin;

                this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );

            } else {

                this.autoSpeedFactor = 0.0;

            }

            actualMoveSpeed = delta * this.movementSpeed;

            if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
            if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );

            if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
            if ( this.moveRight ) this.object.translateX( actualMoveSpeed );

            if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
            if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );

            var actualLookSpeed = delta * this.lookSpeed;

            if ( !this.activeLook ) {

                actualLookSpeed = 0;

            }

            this.lon += this.mouseX * actualLookSpeed;
            if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed; // * this.invertVertical?-1:1;

            this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
            this.phi = ( 90 - this.lat ) * Math.PI / 180;
            this.theta = this.lon * Math.PI / 180;

            var targetPosition = this.target,
                position = this.object.position;

            targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
            targetPosition.y = position.y + 100 * Math.cos( this.phi );
            targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );

        }

        var verticalLookRatio = 1;

        if ( this.constrainVertical ) {

            verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );

        }

        this.lon += this.mouseX * actualLookSpeed;
        if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;

        this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
        this.phi = ( 90 - this.lat ) * Math.PI / 180;

        this.theta = this.lon * Math.PI / 180;

        if ( this.constrainVertical ) {

            this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );

        }

        var targetPosition = this.target,
            position = this.object.position;

        targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
        targetPosition.y = position.y + 100 * Math.cos( this.phi );
        targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );

        this.object.lookAt( targetPosition );

    };


    this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

    this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
    this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
    this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
    this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
    this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );

    function bind( scope, fn ) {

        return function () {

            fn.apply( scope, arguments );

        };

    };

    this.handleResize();

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.PathControls = function ( object, domElement ) {

    this.object = object;
    this.domElement = ( domElement !== undefined ) ? domElement : document;

    this.id = "PathControls" + THREE.PathControlsIdCounter ++;

    // API

    this.duration = 10 * 1000; // milliseconds
    this.waypoints = [];

    this.useConstantSpeed = true;
    this.resamplingCoef = 50;

    this.debugPath = new THREE.Object3D();
    this.debugDummy = new THREE.Object3D();

    this.animationParent = new THREE.Object3D();

    this.lookSpeed = 0.005;
    this.lookVertical = true;
    this.lookHorizontal = true;
    this.verticalAngleMap   = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
    this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };

    // internals

    this.target = new THREE.Object3D();

    this.mouseX = 0;
    this.mouseY = 0;

    this.lat = 0;
    this.lon = 0;

    this.phi = 0;
    this.theta = 0;

    var PI2 = Math.PI * 2,
        PI180 = Math.PI / 180;

    this.viewHalfX = 0;
    this.viewHalfY = 0;

    if ( this.domElement !== document ) {

        this.domElement.setAttribute( 'tabindex', -1 );

    }

    // methods

    this.handleResize = function () {

        if ( this.domElement === document ) {

            this.viewHalfX = window.innerWidth / 2;
            this.viewHalfY = window.innerHeight / 2;

        } else {

            this.viewHalfX = this.domElement.offsetWidth / 2;
            this.viewHalfY = this.domElement.offsetHeight / 2;

        }

    };

    this.update = function ( delta ) {

        var srcRange, dstRange;

        if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
        if( this.lookVertical )   this.lat -= this.mouseY * this.lookSpeed * delta;

        this.lon = Math.max( 0, Math.min( 360, this.lon ) );
        this.lat = Math.max( - 85, Math.min( 85, this.lat ) );

        this.phi = ( 90 - this.lat ) * PI180;
        this.theta = this.lon * PI180;

        this.phi = normalize_angle_rad( this.phi );

        // constrain vertical look angle

        srcRange = this.verticalAngleMap.srcRange;
        dstRange = this.verticalAngleMap.dstRange;

        var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
        var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
        var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;

        this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];

        // constrain horizontal look angle

        srcRange = this.horizontalAngleMap.srcRange;
        dstRange = this.horizontalAngleMap.dstRange;

        var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
        var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
        var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;

        this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];

        var targetPosition = this.target.position,
            position = this.object.position;

        targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
        targetPosition.y = 100 * Math.cos( this.phi );
        targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );

        this.object.lookAt( this.target.position );

    };

    this.onMouseMove = function ( event ) {

        if ( this.domElement === document ) {

            this.mouseX = event.pageX - this.viewHalfX;
            this.mouseY = event.pageY - this.viewHalfY;

        } else {

            this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
            this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;

        }

    };

    // utils

    function normalize_angle_rad( a ) {

        var b = a % PI2;
        return b >= 0 ? b : b + PI2;

    };

    function distance( a, b ) {

        var dx = a[ 0 ] - b[ 0 ],
            dy = a[ 1 ] - b[ 1 ],
            dz = a[ 2 ] - b[ 2 ];

        return Math.sqrt( dx * dx + dy * dy + dz * dz );

    };

    function QuadraticEaseInOut ( k ) {

        if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
        return - 0.5 * ( --k * ( k - 2 ) - 1 );

    };

    function bind( scope, fn ) {

        return function () {

            fn.apply( scope, arguments );

        };

    };

    function initAnimationPath( parent, spline, name, duration ) {

        var animationData = {

           name: name,
           fps: 0.6,
           length: duration,

           hierarchy: []

        };

        var i,
            parentAnimation, childAnimation,
            path = spline.getControlPointsArray(),
            sl = spline.getLength(),
            pl = path.length,
            t = 0,
            first = 0,
            last  = pl - 1;

        parentAnimation = { parent: -1, keys: [] };
        parentAnimation.keys[ first ] = { time: 0,        pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
        parentAnimation.keys[ last  ] = { time: duration, pos: path[ last ],  rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };

        for ( i = 1; i < pl - 1; i++ ) {

            // real distance (approximation via linear segments)

            t = duration * sl.chunks[ i ] / sl.total;

            // equal distance

            //t = duration * ( i / pl );

            // linear distance

            //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;

            parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };

        }

        animationData.hierarchy[ 0 ] = parentAnimation;

        THREE.AnimationHandler.add( animationData );

        return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );

    };


    function createSplineGeometry( spline, n_sub ) {

        var i, index, position,
            geometry = new THREE.Geometry();

        for ( i = 0; i < spline.points.length * n_sub; i ++ ) {

            index = i / ( spline.points.length * n_sub );
            position = spline.getPoint( index );

            geometry.vertices[ i ] = new THREE.Vector3( position.x, position.y, position.z );

        }

        return geometry;

    };

    function createPath( parent, spline ) {

        var lineGeo = createSplineGeometry( spline, 10 ),
            particleGeo = createSplineGeometry( spline, 10 ),
            lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
            lineObj = new THREE.Line( lineGeo, lineMat ),
            particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );

        lineObj.scale.set( 1, 1, 1 );
        parent.add( lineObj );

        particleObj.scale.set( 1, 1, 1 );
        parent.add( particleObj );

        var waypoint,
            geo = new THREE.SphereGeometry( 1, 16, 8 ),
            mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );

        for ( var i = 0; i < spline.points.length; i ++ ) {

            waypoint = new THREE.Mesh( geo, mat );
            waypoint.position.copy( spline.points[ i ] );
            parent.add( waypoint );

        }

    };

    this.init = function ( ) {

        // constructor

        this.spline = new THREE.Spline();
        this.spline.initFromArray( this.waypoints );

        if ( this.useConstantSpeed ) {

            this.spline.reparametrizeByArcLength( this.resamplingCoef );

        }

        if ( this.createDebugDummy ) {

            var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
            dummyChildMaterial  = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
            dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
            dummyChildGeo  = new THREE.CubeGeometry( 2, 2, 10 );

            this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );

            var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
            dummyChild.position.set( 0, 10, 0 );

            this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );

            this.animationParent.add( this.object );
            this.animationParent.add( this.target );
            this.animationParent.add( dummyChild );

        } else {

            this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
            this.animationParent.add( this.target );
            this.animationParent.add( this.object );

        }

        if ( this.createDebugPath ) {

            createPath( this.debugPath, this.spline );

        }

        this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );

    };

    this.handleResize();

};

THREE.PathControlsIdCounter = 0;
/**
 * @author James Baicoianu / http://www.baicoianu.com/
 */

THREE.FlyControls = function ( object, domElement ) {

    this.object = object;

    this.domElement = ( domElement !== undefined ) ? domElement : document;
    if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );

    // API

    this.movementSpeed = 1.0;
    this.rollSpeed = 0.005;

    this.dragToLook = false;
    this.autoForward = false;

    // disable default target object behavior

    this.object.useQuaternion = true;

    // internals

    this.tmpQuaternion = new THREE.Quaternion();

    this.mouseStatus = 0;

    this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
    this.moveVector = new THREE.Vector3( 0, 0, 0 );
    this.rotationVector = new THREE.Vector3( 0, 0, 0 );

    this.handleEvent = function ( event ) {

        if ( typeof this[ event.type ] == 'function' ) {

            this[ event.type ]( event );

        }

    };

    this.keydown = function( event ) {

        if ( event.altKey ) {

            return;

        }

        //event.preventDefault();

        switch ( event.keyCode ) {

            case 16: /* shift */ this.movementSpeedMultiplier = .1; break;

            case 87: /*W*/ this.moveState.forward = 1; break;
            case 83: /*S*/ this.moveState.back = 1; break;

            case 65: /*A*/ this.moveState.left = 1; break;
            case 68: /*D*/ this.moveState.right = 1; break;

            case 82: /*R*/ this.moveState.up = 1; break;
            case 70: /*F*/ this.moveState.down = 1; break;

            case 38: /*up*/ this.moveState.pitchUp = 1; break;
            case 40: /*down*/ this.moveState.pitchDown = 1; break;

            case 37: /*left*/ this.moveState.yawLeft = 1; break;
            case 39: /*right*/ this.moveState.yawRight = 1; break;

            case 81: /*Q*/ this.moveState.rollLeft = 1; break;
            case 69: /*E*/ this.moveState.rollRight = 1; break;

        }

        this.updateMovementVector();
        this.updateRotationVector();

    };

    this.keyup = function( event ) {

        switch( event.keyCode ) {

            case 16: /* shift */ this.movementSpeedMultiplier = 1; break;

            case 87: /*W*/ this.moveState.forward = 0; break;
            case 83: /*S*/ this.moveState.back = 0; break;

            case 65: /*A*/ this.moveState.left = 0; break;
            case 68: /*D*/ this.moveState.right = 0; break;

            case 82: /*R*/ this.moveState.up = 0; break;
            case 70: /*F*/ this.moveState.down = 0; break;

            case 38: /*up*/ this.moveState.pitchUp = 0; break;
            case 40: /*down*/ this.moveState.pitchDown = 0; break;

            case 37: /*left*/ this.moveState.yawLeft = 0; break;
            case 39: /*right*/ this.moveState.yawRight = 0; break;

            case 81: /*Q*/ this.moveState.rollLeft = 0; break;
            case 69: /*E*/ this.moveState.rollRight = 0; break;

        }

        this.updateMovementVector();
        this.updateRotationVector();

    };

    this.mousedown = function( event ) {

        if ( this.domElement !== document ) {

            this.domElement.focus();

        }

        event.preventDefault();
        event.stopPropagation();

        if ( this.dragToLook ) {

            this.mouseStatus ++;

        } else {

            switch ( event.button ) {

                case 0: this.object.moveForward = true; break;
                case 2: this.object.moveBackward = true; break;

            }

        }

    };

    this.mousemove = function( event ) {

        if ( !this.dragToLook || this.mouseStatus > 0 ) {

            var container = this.getContainerDimensions();
            var halfWidth  = container.size[ 0 ] / 2;
            var halfHeight = container.size[ 1 ] / 2;

            this.moveState.yawLeft   = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth  ) / halfWidth;
            this.moveState.pitchDown =   ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;

            this.updateRotationVector();

        }

    };

    this.mouseup = function( event ) {

        event.preventDefault();
        event.stopPropagation();

        if ( this.dragToLook ) {

            this.mouseStatus --;

            this.moveState.yawLeft = this.moveState.pitchDown = 0;

        } else {

            switch ( event.button ) {

                case 0: this.moveForward = false; break;
                case 2: this.moveBackward = false; break;

            }

        }

        this.updateRotationVector();

    };

    this.update = function( delta ) {

        var moveMult = delta * this.movementSpeed;
        var rotMult = delta * this.rollSpeed;

        this.object.translateX( this.moveVector.x * moveMult );
        this.object.translateY( this.moveVector.y * moveMult );
        this.object.translateZ( this.moveVector.z * moveMult );

        this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
        this.object.quaternion.multiplySelf( this.tmpQuaternion );

        this.object.matrix.setPosition( this.object.position );
        this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
        this.object.matrixWorldNeedsUpdate = true;


    };

    this.updateMovementVector = function() {

        var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;

        this.moveVector.x = ( -this.moveState.left    + this.moveState.right );
        this.moveVector.y = ( -this.moveState.down    + this.moveState.up );
        this.moveVector.z = ( -forward + this.moveState.back );

        //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );

    };

    this.updateRotationVector = function() {

        this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
        this.rotationVector.y = ( -this.moveState.yawRight  + this.moveState.yawLeft );
        this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );

        //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );

    };

    this.getContainerDimensions = function() {

        if ( this.domElement != document ) {

            return {
                size    : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
                offset    : [ this.domElement.offsetLeft,  this.domElement.offsetTop ]
            };

        } else {

            return {
                size    : [ window.innerWidth, window.innerHeight ],
                offset    : [ 0, 0 ]
            };

        }

    };

    function bind( scope, fn ) {

        return function () {

            fn.apply( scope, arguments );

        };

    };

    this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
    this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
    this.domElement.addEventListener( 'mouseup',   bind( this, this.mouseup ), false );

    this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
    this.domElement.addEventListener( 'keyup',   bind( this, this.keyup ), false );

    this.updateMovementVector();
    this.updateRotationVector();

};
/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.RollControls = function ( object, domElement ) {

    this.object = object;
    this.domElement = ( domElement !== undefined ) ? domElement : document;

    // API

    this.mouseLook = true;
    this.autoForward = false;

    this.lookSpeed = 1;
    this.movementSpeed = 1;
    this.rollSpeed = 1;

    this.constrainVertical = [ -0.9, 0.9 ];

    // disable default target object behavior

    this.object.matrixAutoUpdate = false;

    // internals

    this.forward = new THREE.Vector3( 0, 0, 1 );
    this.roll = 0;

    var xTemp = new THREE.Vector3();
    var yTemp = new THREE.Vector3();
    var zTemp = new THREE.Vector3();
    var rollMatrix = new THREE.Matrix4();

    var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;

    var mouseX = 0, mouseY = 0;

    var windowHalfX = 0;
    var windowHalfY = 0;

    //

    this.handleResize = function () {

        windowHalfX = window.innerWidth / 2;
        windowHalfY = window.innerHeight / 2;

    };

    // custom update

    this.update = function ( delta ) {

        if ( this.mouseLook ) {

            var actualLookSpeed = delta * this.lookSpeed;

            this.rotateHorizontally( actualLookSpeed * mouseX );
            this.rotateVertically( actualLookSpeed * mouseY );

        }

        var actualSpeed = delta * this.movementSpeed;
        var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;

        this.object.translateZ( -actualSpeed * forwardOrAuto );
        this.object.translateX( actualSpeed * sideSpeed );
        this.object.translateY( actualSpeed * upSpeed );

        if( doRoll ) {

            this.roll += this.rollSpeed * delta * rollDirection;

        }

        // cap forward up / down

        if( this.forward.y > this.constrainVertical[ 1 ] ) {

            this.forward.y = this.constrainVertical[ 1 ];
            this.forward.normalize();

        } else if( this.forward.y < this.constrainVertical[ 0 ] ) {

            this.forward.y = this.constrainVertical[ 0 ];
            this.forward.normalize();

        }


        // construct unrolled camera matrix

        zTemp.copy( this.forward );
        yTemp.set( 0, 1, 0 );

        xTemp.cross( yTemp, zTemp ).normalize();
        yTemp.cross( zTemp, xTemp ).normalize();

        this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
        this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
        this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;

        // calculate roll matrix

        rollMatrix.identity();
        rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
        rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] =  Math.cos( this.roll );

        // multiply camera with roll

        this.object.matrix.multiplySelf( rollMatrix );
        this.object.matrixWorldNeedsUpdate = true;

        // set position

        this.object.matrix.elements[12] = this.object.position.x;
        this.object.matrix.elements[13] = this.object.position.y;
        this.object.matrix.elements[14] = this.object.position.z;


    };

    this.translateX = function ( distance ) {

        this.object.position.x += this.object.matrix.elements[0] * distance;
        this.object.position.y += this.object.matrix.elements[1] * distance;
        this.object.position.z += this.object.matrix.elements[2] * distance;

    };

    this.translateY = function ( distance ) {

        this.object.position.x += this.object.matrix.elements[4] * distance;
        this.object.position.y += this.object.matrix.elements[5] * distance;
        this.object.position.z += this.object.matrix.elements[6] * distance;

    };

    this.translateZ = function ( distance ) {

        this.object.position.x -= this.object.matrix.elements[8] * distance;
        this.object.position.y -= this.object.matrix.elements[9] * distance;
        this.object.position.z -= this.object.matrix.elements[10] * distance;

    };


    this.rotateHorizontally = function ( amount ) {

        // please note that the amount is NOT degrees, but a scale value

        xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
        xTemp.multiplyScalar( amount );

        this.forward.subSelf( xTemp );
        this.forward.normalize();

    };

    this.rotateVertically = function ( amount ) {

        // please note that the amount is NOT degrees, but a scale value

        yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
        yTemp.multiplyScalar( amount );

        this.forward.addSelf( yTemp );
        this.forward.normalize();

    };

    function onKeyDown( event ) {

        //event.preventDefault();

        switch ( event.keyCode ) {

            case 38: /*up*/
            case 87: /*W*/ forwardSpeed = 1; break;

            case 37: /*left*/
            case 65: /*A*/ sideSpeed = -1; break;

            case 40: /*down*/
            case 83: /*S*/ forwardSpeed = -1; break;

            case 39: /*right*/
            case 68: /*D*/ sideSpeed = 1; break;

            case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
            case 69: /*E*/ doRoll = true; rollDirection = -1; break;

            case 82: /*R*/ upSpeed = 1; break;
            case 70: /*F*/ upSpeed = -1; break;

        }

    };

    function onKeyUp( event ) {

        switch( event.keyCode ) {

            case 38: /*up*/
            case 87: /*W*/ forwardSpeed = 0; break;

            case 37: /*left*/
            case 65: /*A*/ sideSpeed = 0; break;

            case 40: /*down*/
            case 83: /*S*/ forwardSpeed = 0; break;

            case 39: /*right*/
            case 68: /*D*/ sideSpeed = 0; break;

            case 81: /*Q*/ doRoll = false; break;
            case 69: /*E*/ doRoll = false; break;

            case 82: /*R*/ upSpeed = 0; break;
            case 70: /*F*/ upSpeed = 0; break;

        }

    };

    function onMouseMove( event ) {

        mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
        mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;

    };

    function onMouseDown ( event ) {

        event.preventDefault();
        event.stopPropagation();

        switch ( event.button ) {

            case 0: forwardSpeed = 1; break;
            case 2: forwardSpeed = -1; break;

        }

    };

    function onMouseUp ( event ) {

        event.preventDefault();
        event.stopPropagation();

        switch ( event.button ) {

            case 0: forwardSpeed = 0; break;
            case 2: forwardSpeed = 0; break;

        }

    };

    this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

    this.domElement.addEventListener( 'mousemove', onMouseMove, false );
    this.domElement.addEventListener( 'mousedown', onMouseDown, false );
    this.domElement.addEventListener( 'mouseup', onMouseUp, false );
    this.domElement.addEventListener( 'keydown', onKeyDown, false );
    this.domElement.addEventListener( 'keyup', onKeyUp, false );

    this.handleResize();

};
/**
 * @author Eberhard Graether / http://egraether.com/
 */

THREE.TrackballControls = function ( object, domElement ) {

    THREE.EventTarget.call( this );

    var _this = this,
    STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };

    this.object = object;
    this.domElement = ( domElement !== undefined ) ? domElement : document;

    // API

    this.enabled = true;

    this.screen = { width: 0, height: 0, offsetLeft: 0, offsetTop: 0 };
    this.radius = ( this.screen.width + this.screen.height ) / 4;

    this.rotateSpeed = 1.0;
    this.zoomSpeed = 1.2;
    this.panSpeed = 0.3;

    this.noRotate = false;
    this.noZoom = false;
    this.noPan = false;

    this.staticMoving = false;
    this.dynamicDampingFactor = 0.2;

    this.minDistance = 0;
    this.maxDistance = Infinity;

    this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];

    // internals

    this.target = new THREE.Vector3();

    var lastPosition = new THREE.Vector3();

    var _keyPressed = false,
    _state = STATE.NONE,

    _eye = new THREE.Vector3(),

    _rotateStart = new THREE.Vector3(),
    _rotateEnd = new THREE.Vector3(),

    _zoomStart = new THREE.Vector2(),
    _zoomEnd = new THREE.Vector2(),

    _panStart = new THREE.Vector2(),
    _panEnd = new THREE.Vector2();

    // events

    var changeEvent = { type: 'change' };


    // methods

    this.handleResize = function () {

        this.screen.width = window.innerWidth;
        this.screen.height = window.innerHeight;

        this.screen.offsetLeft = 0;
        this.screen.offsetTop = 0;

        this.radius = ( this.screen.width + this.screen.height ) / 4;
    };

    this.handleEvent = function ( event ) {

        if ( typeof this[ event.type ] == 'function' ) {

            this[ event.type ]( event );

        }

    };

    this.getMouseOnScreen = function ( clientX, clientY ) {

        return new THREE.Vector2(
            ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
            ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
        );

    };

    this.getMouseProjectionOnBall = function ( clientX, clientY ) {

        var mouseOnBall = new THREE.Vector3(
            ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
            ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
            0.0
        );

        var length = mouseOnBall.length();

        if ( length > 1.0 ) {

            mouseOnBall.normalize();

        } else {

            mouseOnBall.z = Math.sqrt( 1.0 - length * length );

        }

        _eye.copy( _this.object.position ).subSelf( _this.target );

        var projection = _this.object.up.clone().setLength( mouseOnBall.y );
        projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
        projection.addSelf( _eye.setLength( mouseOnBall.z ) );

        return projection;

    };

    this.rotateCamera = function () {

        var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );

        if ( angle ) {

            var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
                quaternion = new THREE.Quaternion();

            angle *= _this.rotateSpeed;

            quaternion.setFromAxisAngle( axis, -angle );

            quaternion.multiplyVector3( _eye );
            quaternion.multiplyVector3( _this.object.up );

            quaternion.multiplyVector3( _rotateEnd );

            if ( _this.staticMoving ) {

                _rotateStart.copy( _rotateEnd );

            } else {

                quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
                quaternion.multiplyVector3( _rotateStart );

            }

        }

    };

    this.zoomCamera = function () {

        var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;

        if ( factor !== 1.0 && factor > 0.0 ) {

            _eye.multiplyScalar( factor );

            if ( _this.staticMoving ) {

                _zoomStart.copy( _zoomEnd );

            } else {

                _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;

            }

        }

    };

    this.panCamera = function () {

        var mouseChange = _panEnd.clone().subSelf( _panStart );

        if ( mouseChange.lengthSq() ) {

            mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );

            var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
            pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );

            _this.object.position.addSelf( pan );
            _this.target.addSelf( pan );

            if ( _this.staticMoving ) {

                _panStart = _panEnd;

            } else {

                _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );

            }

        }

    };

    this.checkDistances = function () {

        if ( !_this.noZoom || !_this.noPan ) {

            if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {

                _this.object.position.setLength( _this.maxDistance );

            }

            if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {

                _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );

            }

        }

    };

    this.update = function () {

        _eye.copy( _this.object.position ).subSelf( _this.target );

        if ( !_this.noRotate ) {

            _this.rotateCamera();

        }

        if ( !_this.noZoom ) {

            _this.zoomCamera();

        }

        if ( !_this.noPan ) {

            _this.panCamera();

        }

        _this.object.position.add( _this.target, _eye );

        _this.checkDistances();

        _this.object.lookAt( _this.target );

        if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {

            _this.dispatchEvent( changeEvent );

            lastPosition.copy( _this.object.position );

        }

    };

    // listeners

    function keydown( event ) {

        if ( ! _this.enabled ) return;

        //event.preventDefault();

        if ( _state !== STATE.NONE ) {

            return;

        } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {

            _state = STATE.ROTATE;

        } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {

            _state = STATE.ZOOM;

        } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {

            _state = STATE.PAN;

        }

        if ( _state !== STATE.NONE ) {

            _keyPressed = true;

        }

    }

    function keyup( event ) {

        if ( ! _this.enabled ) return;

        if ( _state !== STATE.NONE ) {

            _state = STATE.NONE;

        }

    }

    function mousedown( event ) {

        if ( ! _this.enabled ) return;

        event.preventDefault();
        event.stopPropagation();

        if ( _state === STATE.NONE ) {

            _state = event.button;

            if ( _state === STATE.ROTATE && !_this.noRotate ) {

                _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );

            } else if ( _state === STATE.ZOOM && !_this.noZoom ) {

                _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

            } else if ( !this.noPan ) {

                _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

            }

        }

    }

    function mousemove( event ) {

        if ( ! _this.enabled ) return;

        if ( _keyPressed ) {

            _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
            _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
            _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

            _keyPressed = false;

        }

        if ( _state === STATE.NONE ) {

            return;

        } else if ( _state === STATE.ROTATE && !_this.noRotate ) {

            _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );

        } else if ( _state === STATE.ZOOM && !_this.noZoom ) {

            _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

        } else if ( _state === STATE.PAN && !_this.noPan ) {

            _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

        }

    }

    function mouseup( event ) {

        if ( ! _this.enabled ) return;

        event.preventDefault();
        event.stopPropagation();

        _state = STATE.NONE;

    }

    function mousewheel( event ) {

        if ( ! _this.enabled ) return;

        event.preventDefault();
        event.stopPropagation();

        var delta = 0;

        if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9

            delta = event.wheelDelta / 40;

        } else if ( event.detail ) { // Firefox

            delta = - event.detail / 3;

        }

        _zoomStart.y += ( 1 / delta ) * 0.05;

    }

    this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

    this.domElement.addEventListener( 'mousemove', mousemove, false );
    this.domElement.addEventListener( 'mousedown', mousedown, false );
    this.domElement.addEventListener( 'mouseup', mouseup, false );
    this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false );
    this.domElement.addEventListener( 'mousewheel', mousewheel, false );

    window.addEventListener( 'keydown', keydown, false );
    window.addEventListener( 'keyup', keyup, false );

    this.handleResize();

};
/**
 * @author qiao / https://github.com/qiao
 * @author mrdoob / http://mrdoob.com
 * @author alteredq / http://alteredqualia.com/
 */

THREE.OrbitControls = function ( object, domElement ) {

    THREE.EventTarget.call( this );

    this.object = object;
    this.domElement = ( domElement !== undefined ) ? domElement : document;

    // API

    this.center = new THREE.Vector3();

    this.userZoom = true;
    this.userZoomSpeed = 1.0;

    this.userRotate = true;
    this.userRotateSpeed = 1.0;

    this.autoRotate = false;
    this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60

    // internals

    var scope = this;

    var EPS = 0.000001;
    var PIXELS_PER_ROUND = 1800;

    var rotateStart = new THREE.Vector2();
    var rotateEnd = new THREE.Vector2();
    var rotateDelta = new THREE.Vector2();

    var zoomStart = new THREE.Vector2();
    var zoomEnd = new THREE.Vector2();
    var zoomDelta = new THREE.Vector2();

    var phiDelta = 0;
    var thetaDelta = 0;
    var scale = 1;

    var lastPosition = new THREE.Vector3();

    var STATE = { NONE : -1, ROTATE : 0, ZOOM : 1 };
    var state = STATE.NONE;

    // events

    var changeEvent = { type: 'change' };


    this.rotateLeft = function ( angle ) {

        if ( angle === undefined ) {

            angle = getAutoRotationAngle();

        }

        thetaDelta -= angle;

    };

    this.rotateRight = function ( angle ) {

        if ( angle === undefined ) {

            angle = getAutoRotationAngle();

        }

        thetaDelta += angle;

    };

    this.rotateUp = function ( angle ) {

        if ( angle === undefined ) {

            angle = getAutoRotationAngle();

        }

        phiDelta -= angle;

    };

    this.rotateDown = function ( angle ) {

        if ( angle === undefined ) {

            angle = getAutoRotationAngle();

        }

        phiDelta += angle;

    };

    this.zoomIn = function ( zoomScale ) {

        if ( zoomScale === undefined ) {

            zoomScale = getZoomScale();

        }

        scale /= zoomScale;

    };

    this.zoomOut = function ( zoomScale ) {

        if ( zoomScale === undefined ) {

            zoomScale = getZoomScale();

        }

        scale *= zoomScale;

    };

    this.update = function () {

        var position = this.object.position;
        var offset = position.clone().subSelf( this.center )

        // angle from z-axis around y-axis

        var theta = Math.atan2( offset.x, offset.z );

        // angle from y-axis

        var phi = Math.atan2( Math.sqrt( offset.x * offset.x + offset.z * offset.z ), offset.y );

        if ( this.autoRotate ) {

            this.rotateLeft( getAutoRotationAngle() );

        }

        theta += thetaDelta;
        phi += phiDelta;

        // restrict phi to be betwee EPS and PI-EPS

        phi = Math.max( EPS, Math.min( Math.PI - EPS, phi ) );

        var radius = offset.length();
        offset.x = radius * Math.sin( phi ) * Math.sin( theta );
        offset.y = radius * Math.cos( phi );
        offset.z = radius * Math.sin( phi ) * Math.cos( theta );
        offset.multiplyScalar( scale );

        position.copy( this.center ).addSelf( offset );

        this.object.lookAt( this.center );

        thetaDelta = 0;
        phiDelta = 0;
        scale = 1;

        if ( lastPosition.distanceTo( this.object.position ) > 0 ) {

            this.dispatchEvent( changeEvent );

            lastPosition.copy( this.object.position );

        }

    };


    function getAutoRotationAngle() {

        return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;

    }

    function getZoomScale() {

        return Math.pow( 0.95, scope.userZoomSpeed );

    }

    function onMouseDown( event ) {

        if ( !scope.userRotate ) return;

        event.preventDefault();

        if ( event.button === 0 || event.button === 2 ) {

            state = STATE.ROTATE;

            rotateStart.set( event.clientX, event.clientY );

        } else if ( event.button === 1 ) {

            state = STATE.ZOOM;

            zoomStart.set( event.clientX, event.clientY );

        }

        document.addEventListener( 'mousemove', onMouseMove, false );
        document.addEventListener( 'mouseup', onMouseUp, false );

    }

    function onMouseMove( event ) {

        event.preventDefault();

        if ( state === STATE.ROTATE ) {

            rotateEnd.set( event.clientX, event.clientY );
            rotateDelta.sub( rotateEnd, rotateStart );

            scope.rotateLeft( 2 * Math.PI * rotateDelta.x / PIXELS_PER_ROUND * scope.userRotateSpeed );
            scope.rotateUp( 2 * Math.PI * rotateDelta.y / PIXELS_PER_ROUND * scope.userRotateSpeed );

            rotateStart.copy( rotateEnd );

        } else if ( state === STATE.ZOOM ) {

            zoomEnd.set( event.clientX, event.clientY );
            zoomDelta.sub( zoomEnd, zoomStart );

            if ( zoomDelta.y > 0 ) {

                scope.zoomIn();

            } else {

                scope.zoomOut();

            }

            zoomStart.copy( zoomEnd );

        }

    }

    function onMouseUp( event ) {

        if ( ! scope.userRotate ) return;

        document.removeEventListener( 'mousemove', onMouseMove, false );
        document.removeEventListener( 'mouseup', onMouseUp, false );

        state = STATE.NONE;

    }

    function onMouseWheel( event ) {

        if ( ! scope.userZoom ) return;

        if ( event.wheelDelta > 0 ) {

            scope.zoomOut();

        } else {

            scope.zoomIn();

        }

    }

    this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
    this.domElement.addEventListener( 'mousedown', onMouseDown, false );
    this.domElement.addEventListener( 'mousewheel', onMouseWheel, false );

};
/**
 * @author hughes
 */

THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {

    THREE.Geometry.call( this );

    radius = radius || 50;

    thetaStart = thetaStart !== undefined ? thetaStart : 0;
    thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
    segments = segments !== undefined ? Math.max( 3, segments ) : 8;

    var i, uvs = [],
    center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );

    this.vertices.push(center);
    uvs.push( centerUV );

    for ( i = 0; i <= segments; i ++ ) {

        var vertex = new THREE.Vector3();

        vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
        vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );

        this.vertices.push( vertex );
        uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );

    }

    var n = new THREE.Vector3( 0, 0, -1 );

    for ( i = 1; i <= segments; i ++ ) {

        var v1 = i;
        var v2 = i + 1 ;
        var v3 = 0;

        this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
        this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );

    }

    this.computeCentroids();
    this.computeFaceNormals();

    this.boundingSphere = { radius: radius };

};

THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
 */

THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {

    THREE.Geometry.call( this );

    var scope = this,
    width_half = width / 2,
    height_half = height / 2,
    depth_half = depth / 2;

    var mpx, mpy, mpz, mnx, mny, mnz;

    if ( materials !== undefined ) {

        if ( materials instanceof Array ) {

            this.materials = materials;

        } else {

            this.materials = [];

            for ( var i = 0; i < 6; i ++ ) {

                this.materials.push( materials );

            }

        }

        mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;

    } else {

        this.materials = [];

    }

    this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };

    if ( sides != undefined ) {

        for ( var s in sides ) {

            if ( this.sides[ s ] !== undefined ) {

                this.sides[ s ] = sides[ s ];

            }

        }

    }

    this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
    this.sides.nx && buildPlane( 'z', 'y',   1, - 1, depth, height, - width_half, mnx ); // nx
    this.sides.py && buildPlane( 'x', 'z',   1,   1, width, depth, height_half, mpy ); // py
    this.sides.ny && buildPlane( 'x', 'z',   1, - 1, width, depth, - height_half, mny ); // ny
    this.sides.pz && buildPlane( 'x', 'y',   1, - 1, width, height, depth_half, mpz ); // pz
    this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz

    function buildPlane( u, v, udir, vdir, width, height, depth, material ) {

        var w, ix, iy,
        gridX = segmentsWidth || 1,
        gridY = segmentsHeight || 1,
        width_half = width / 2,
        height_half = height / 2,
        offset = scope.vertices.length;

        if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {

            w = 'z';

        } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {

            w = 'y';
            gridY = segmentsDepth || 1;

        } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {

            w = 'x';
            gridX = segmentsDepth || 1;

        }

        var gridX1 = gridX + 1,
        gridY1 = gridY + 1,
        segment_width = width / gridX,
        segment_height = height / gridY,
        normal = new THREE.Vector3();

        normal[ w ] = depth > 0 ? 1 : - 1;

        for ( iy = 0; iy < gridY1; iy ++ ) {

            for ( ix = 0; ix < gridX1; ix ++ ) {

                var vector = new THREE.Vector3();
                vector[ u ] = ( ix * segment_width - width_half ) * udir;
                vector[ v ] = ( iy * segment_height - height_half ) * vdir;
                vector[ w ] = depth;

                scope.vertices.push( vector );

            }

        }

        for ( iy = 0; iy < gridY; iy++ ) {

            for ( ix = 0; ix < gridX; ix++ ) {

                var a = ix + gridX1 * iy;
                var b = ix + gridX1 * ( iy + 1 );
                var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
                var d = ( ix + 1 ) + gridX1 * iy;

                var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
                face.normal.copy( normal );
                face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
                face.materialIndex = material;

                scope.faces.push( face );
                scope.faceVertexUvs[ 0 ].push( [
                            new THREE.UV( ix / gridX, 1 - iy / gridY ),
                            new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
                            new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
                            new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
                        ] );

            }

        }

    }

    this.computeCentroids();
    this.mergeVertices();

};

THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {

    THREE.Geometry.call( this );

    radiusTop = radiusTop !== undefined ? radiusTop : 20;
    radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
    height = height !== undefined ? height : 100;

    var heightHalf = height / 2;
    var segmentsX = segmentsRadius || 8;
    var segmentsY = segmentsHeight || 1;

    var x, y, vertices = [], uvs = [];

    for ( y = 0; y <= segmentsY; y ++ ) {

        var verticesRow = [];
        var uvsRow = [];

        var v = y / segmentsY;
        var radius = v * ( radiusBottom - radiusTop ) + radiusTop;

        for ( x = 0; x <= segmentsX; x ++ ) {

            var u = x / segmentsX;

            var vertex = new THREE.Vector3();
            vertex.x = radius * Math.sin( u * Math.PI * 2 );
            vertex.y = - v * height + heightHalf;
            vertex.z = radius * Math.cos( u * Math.PI * 2 );

            this.vertices.push( vertex );

            verticesRow.push( this.vertices.length - 1 );
            uvsRow.push( new THREE.UV( u, 1 - v ) );

        }

        vertices.push( verticesRow );
        uvs.push( uvsRow );

    }

    var tanTheta = ( radiusBottom - radiusTop ) / height;
    var na, nb;

    for ( x = 0; x < segmentsX; x ++ ) {

        if ( radiusTop !== 0 ) {

            na = this.vertices[ vertices[ 0 ][ x ] ].clone();
            nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();

        } else {

            na = this.vertices[ vertices[ 1 ][ x ] ].clone();
            nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();

        }

        na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
        nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();

        for ( y = 0; y < segmentsY; y ++ ) {

            var v1 = vertices[ y ][ x ];
            var v2 = vertices[ y + 1 ][ x ];
            var v3 = vertices[ y + 1 ][ x + 1 ];
            var v4 = vertices[ y ][ x + 1 ];

            var n1 = na.clone();
            var n2 = na.clone();
            var n3 = nb.clone();
            var n4 = nb.clone();

            var uv1 = uvs[ y ][ x ].clone();
            var uv2 = uvs[ y + 1 ][ x ].clone();
            var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
            var uv4 = uvs[ y ][ x + 1 ].clone();

            this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
            this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );

        }

    }

    // top cap

    if ( !openEnded && radiusTop > 0 ) {

        this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );

        for ( x = 0; x < segmentsX; x ++ ) {

            var v1 = vertices[ 0 ][ x ];
            var v2 = vertices[ 0 ][ x + 1 ];
            var v3 = this.vertices.length - 1;

            var n1 = new THREE.Vector3( 0, 1, 0 );
            var n2 = new THREE.Vector3( 0, 1, 0 );
            var n3 = new THREE.Vector3( 0, 1, 0 );

            var uv1 = uvs[ 0 ][ x ].clone();
            var uv2 = uvs[ 0 ][ x + 1 ].clone();
            var uv3 = new THREE.UV( uv2.u, 0 );

            this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
            this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );

        }

    }

    // bottom cap

    if ( !openEnded && radiusBottom > 0 ) {

        this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );

        for ( x = 0; x < segmentsX; x ++ ) {

            var v1 = vertices[ y ][ x + 1 ];
            var v2 = vertices[ y ][ x ];
            var v3 = this.vertices.length - 1;

            var n1 = new THREE.Vector3( 0, - 1, 0 );
            var n2 = new THREE.Vector3( 0, - 1, 0 );
            var n3 = new THREE.Vector3( 0, - 1, 0 );

            var uv1 = uvs[ y ][ x + 1 ].clone();
            var uv2 = uvs[ y ][ x ].clone();
            var uv3 = new THREE.UV( uv2.u, 1 );

            this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
            this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );

        }

    }

    this.computeCentroids();
    this.computeFaceNormals();

}

THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 *
 * Creates extruded geometry from a path shape.
 *
 * parameters = {
 *
 *  size: <float>, // size of the text
 *  height: <float>, // thickness to extrude text
 *  curveSegments: <int>, // number of points on the curves
 *  steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
 *  amount: <int>, // Amount
 *
 *  bevelEnabled: <bool>, // turn on bevel
 *  bevelThickness: <float>, // how deep into text bevel goes
 *  bevelSize: <float>, // how far from text outline is bevel
 *  bevelSegments: <int>, // number of bevel layers
 *
 *  extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
 *  frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
 *
 *  material: <int> // material index for front and back faces
 *  extrudeMaterial: <int> // material index for extrusion and beveled faces
 *  uvGenerator: <Object> // object that provides UV generator functions
 *
 * }
 **/

THREE.ExtrudeGeometry = function ( shapes, options ) {

    if ( typeof( shapes ) === "undefined" ) {
        shapes = [];
        return;
    }

    THREE.Geometry.call( this );

    shapes = shapes instanceof Array ? shapes : [ shapes ];

    this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();

    this.addShapeList( shapes, options );

    this.computeCentroids();
    this.computeFaceNormals();

    // can't really use automatic vertex normals
    // as then front and back sides get smoothed too
    // should do separate smoothing just for sides

    //this.computeVertexNormals();

    //console.log( "took", ( Date.now() - startTime ) );

};

THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );

THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
    var sl = shapes.length;

    for ( var s = 0; s < sl; s ++ ) {
        var shape = shapes[ s ];
        this.addShape( shape, options );
    }
};

THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {

    var amount = options.amount !== undefined ? options.amount : 100;

    var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
    var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
    var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;

    var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false

    var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;

    var steps = options.steps !== undefined ? options.steps : 1;

    var extrudePath = options.extrudePath;
    var extrudePts, extrudeByPath = false;

    var material = options.material;
    var extrudeMaterial = options.extrudeMaterial;

    // Use default WorldUVGenerator if no UV generators are specified.
    var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;

    var shapebb = this.shapebb;
    //shapebb = shape.getBoundingBox();



    var splineTube, binormal, normal, position2;
    if ( extrudePath ) {

        extrudePts = extrudePath.getSpacedPoints( steps );

        extrudeByPath = true;
        bevelEnabled = false; // bevels not supported for path extrusion

        // SETUP TNB variables

        // Reuse TNB from TubeGeomtry for now.
        // TODO1 - have a .isClosed in spline?

        splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);

        // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);

        binormal = new THREE.Vector3();
        normal = new THREE.Vector3();
        position2 = new THREE.Vector3();

    }

    // Safeguards if bevels are not enabled

    if ( ! bevelEnabled ) {

        bevelSegments = 0;
        bevelThickness = 0;
        bevelSize = 0;

    }

    // Variables initalization

    var ahole, h, hl; // looping of holes
    var scope = this;
    var bevelPoints = [];

    var shapesOffset = this.vertices.length;

    var shapePoints = shape.extractPoints();

    var vertices = shapePoints.shape;
    var holes = shapePoints.holes;

    var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;

    if ( reverse ) {

        vertices = vertices.reverse();

        // Maybe we should also check if holes are in the opposite direction, just to be safe ...

        for ( h = 0, hl = holes.length; h < hl; h ++ ) {

            ahole = holes[ h ];

            if ( THREE.Shape.Utils.isClockWise( ahole ) ) {

                holes[ h ] = ahole.reverse();

            }

        }

        reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!

    }


    var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );

    /* Vertices */

    var contour = vertices; // vertices has all points but contour has only points of circumference

    for ( h = 0, hl = holes.length;  h < hl; h ++ ) {

        ahole = holes[ h ];

        vertices = vertices.concat( ahole );

    }


    function scalePt2 ( pt, vec, size ) {

        if ( !vec ) console.log( "die" );

        return vec.clone().multiplyScalar( size ).addSelf( pt );

    }

    var b, bs, t, z,
        vert, vlen = vertices.length,
        face, flen = faces.length,
        cont, clen = contour.length;


    // Find directions for point movement

    var RAD_TO_DEGREES = 180 / Math.PI;


    function getBevelVec( pt_i, pt_j, pt_k ) {

        // Algorithm 2

        return getBevelVec2( pt_i, pt_j, pt_k );

    }

    function getBevelVec1( pt_i, pt_j, pt_k ) {

        var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
        var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );

        if ( anglea > angleb ) {

            angleb += Math.PI * 2;

        }

        var anglec = ( anglea + angleb ) / 2;


        //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);

        var x = - Math.cos( anglec );
        var y = - Math.sin( anglec );

        var vec = new THREE.Vector2( x, y ); //.normalize();

        return vec;

    }

    function getBevelVec2( pt_i, pt_j, pt_k ) {

        var a = THREE.ExtrudeGeometry.__v1,
            b = THREE.ExtrudeGeometry.__v2,
            v_hat = THREE.ExtrudeGeometry.__v3,
            w_hat = THREE.ExtrudeGeometry.__v4,
            p = THREE.ExtrudeGeometry.__v5,
            q = THREE.ExtrudeGeometry.__v6,
            v, w,
            v_dot_w_hat, q_sub_p_dot_w_hat,
            s, intersection;

        // good reading for line-line intersection
        // http://sputsoft.com/blog/2010/03/line-line-intersection.html

        // define a as vector j->i
        // define b as vectot k->i

        a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
        b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );

        // get unit vectors

        v = a.normalize();
        w = b.normalize();

        // normals from pt i

        v_hat.set( -v.y, v.x );
        w_hat.set( w.y, -w.x );

        // pts from i

        p.copy( pt_i ).addSelf( v_hat );
        q.copy( pt_i ).addSelf( w_hat );

        if ( p.equals( q ) ) {

            //console.log("Warning: lines are straight");
            return w_hat.clone();

        }

        // Points from j, k. helps prevents points cross overover most of the time

        p.copy( pt_j ).addSelf( v_hat );
        q.copy( pt_k ).addSelf( w_hat );

        v_dot_w_hat = v.dot( w_hat );
        q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );

        // We should not reach these conditions

        if ( v_dot_w_hat === 0 ) {

            console.log( "Either infinite or no solutions!" );

            if ( q_sub_p_dot_w_hat === 0 ) {

                console.log( "Its finite solutions." );

            } else {

                console.log( "Too bad, no solutions." );

            }

        }

        s = q_sub_p_dot_w_hat / v_dot_w_hat;

        if ( s < 0 ) {

            // in case of emergecy, revert to algorithm 1.

            return getBevelVec1( pt_i, pt_j, pt_k );

        }

        intersection = v.multiplyScalar( s ).addSelf( p );

        return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly

    }

    var contourMovements = [];

    for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {

        if ( j === il ) j = 0;
        if ( k === il ) k = 0;

        //  (j)---(i)---(k)
        // console.log('i,j,k', i, j , k)

        var pt_i = contour[ i ];
        var pt_j = contour[ j ];
        var pt_k = contour[ k ];

        contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );

    }

    var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();

    for ( h = 0, hl = holes.length; h < hl; h ++ ) {

        ahole = holes[ h ];

        oneHoleMovements = [];

        for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {

            if ( j === il ) j = 0;
            if ( k === il ) k = 0;

            //  (j)---(i)---(k)
            oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );

        }

        holesMovements.push( oneHoleMovements );
        verticesMovements = verticesMovements.concat( oneHoleMovements );

    }


    // Loop bevelSegments, 1 for the front, 1 for the back

    for ( b = 0; b < bevelSegments; b ++ ) {
    //for ( b = bevelSegments; b > 0; b -- ) {

        t = b / bevelSegments;
        z = bevelThickness * ( 1 - t );

        //z = bevelThickness * t;
        bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
        //bs = bevelSize * t ; // linear

        // contract shape

        for ( i = 0, il = contour.length; i < il; i ++ ) {

            vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
            //vert = scalePt( contour[ i ], contourCentroid, bs, false );
            v( vert.x, vert.y,  - z );

        }

        // expand holes

        for ( h = 0, hl = holes.length; h < hl; h++ ) {

            ahole = holes[ h ];
            oneHoleMovements = holesMovements[ h ];

            for ( i = 0, il = ahole.length; i < il; i++ ) {

                vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
                //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );

                v( vert.x, vert.y,  -z );

            }

        }

    }

    bs = bevelSize;

    // Back facing vertices

    for ( i = 0; i < vlen; i ++ ) {

        vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];

        if ( !extrudeByPath ) {

            v( vert.x, vert.y, 0 );

        } else {

            // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );

            normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
            binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);

            position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);

            v( position2.x, position2.y, position2.z );

        }

    }

    // Add stepped vertices...
    // Including front facing vertices

    var s;

    for ( s = 1; s <= steps; s ++ ) {

        for ( i = 0; i < vlen; i ++ ) {

            vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];

            if ( !extrudeByPath ) {

                v( vert.x, vert.y, amount / steps * s );

            } else {

                // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );

                normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
                binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );

                position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );

                v( position2.x, position2.y, position2.z );

            }

        }

    }


    // Add bevel segments planes

    //for ( b = 1; b <= bevelSegments; b ++ ) {
    for ( b = bevelSegments - 1; b >= 0; b -- ) {

        t = b / bevelSegments;
        z = bevelThickness * ( 1 - t );
        //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
        bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;

        // contract shape

        for ( i = 0, il = contour.length; i < il; i ++ ) {

            vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
            v( vert.x, vert.y,  amount + z );

        }

        // expand holes

        for ( h = 0, hl = holes.length; h < hl; h ++ ) {

            ahole = holes[ h ];
            oneHoleMovements = holesMovements[ h ];

            for ( i = 0, il = ahole.length; i < il; i ++ ) {

                vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );

                if ( !extrudeByPath ) {

                    v( vert.x, vert.y,  amount + z );

                } else {

                    v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );

                }

            }

        }

    }

    /* Faces */

    // Top and bottom faces

    buildLidFaces();

    // Sides faces

    buildSideFaces();


    /////  Internal functions

    function buildLidFaces() {

        if ( bevelEnabled ) {

            var layer = 0 ; // steps + 1
            var offset = vlen * layer;

            // Bottom faces

            for ( i = 0; i < flen; i ++ ) {

                face = faces[ i ];
                f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );

            }

            layer = steps + bevelSegments * 2;
            offset = vlen * layer;

            // Top faces

            for ( i = 0; i < flen; i ++ ) {

                face = faces[ i ];
                f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );

            }

        } else {

            // Bottom faces

            for ( i = 0; i < flen; i++ ) {

                face = faces[ i ];
                f3( face[ 2 ], face[ 1 ], face[ 0 ], true );

            }

            // Top faces

            for ( i = 0; i < flen; i ++ ) {

                face = faces[ i ];
                f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );

            }
        }

    }

    // Create faces for the z-sides of the shape

    function buildSideFaces() {

        var layeroffset = 0;
        sidewalls( contour, layeroffset );
        layeroffset += contour.length;

        for ( h = 0, hl = holes.length;  h < hl; h ++ ) {

            ahole = holes[ h ];
            sidewalls( ahole, layeroffset );

            //, true
            layeroffset += ahole.length;

        }

    }

    function sidewalls( contour, layeroffset ) {

        var j, k;
        i = contour.length;

        while ( --i >= 0 ) {

            j = i;
            k = i - 1;
            if ( k < 0 ) k = contour.length - 1;

            //console.log('b', i,j, i-1, k,vertices.length);

            var s = 0, sl = steps  + bevelSegments * 2;

            for ( s = 0; s < sl; s ++ ) {

                var slen1 = vlen * s;
                var slen2 = vlen * ( s + 1 );

                var a = layeroffset + j + slen1,
                    b = layeroffset + k + slen1,
                    c = layeroffset + k + slen2,
                    d = layeroffset + j + slen2;

                f4( a, b, c, d, contour, s, sl, j, k );

            }
        }

    }


    function v( x, y, z ) {

        scope.vertices.push( new THREE.Vector3( x, y, z ) );

    }

    function f3( a, b, c, isBottom ) {

        a += shapesOffset;
        b += shapesOffset;
        c += shapesOffset;

        // normal, color, material
        scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );

        var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );

         scope.faceVertexUvs[ 0 ].push( uvs );

    }

    function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {

        a += shapesOffset;
        b += shapesOffset;
        c += shapesOffset;
        d += shapesOffset;

         scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );

         var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
                                             stepIndex, stepsLength, contourIndex1, contourIndex2 );
         scope.faceVertexUvs[ 0 ].push( uvs );

    }

};

THREE.ExtrudeGeometry.WorldUVGenerator = {

    generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
        var ax = geometry.vertices[ indexA ].x,
            ay = geometry.vertices[ indexA ].y,

            bx = geometry.vertices[ indexB ].x,
            by = geometry.vertices[ indexB ].y,

            cx = geometry.vertices[ indexC ].x,
            cy = geometry.vertices[ indexC ].y;

        return [
            new THREE.UV( ax, ay ),
            new THREE.UV( bx, by ),
            new THREE.UV( cx, cy )
        ];

    },

    generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {

        return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );

    },

    generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
                                  indexA, indexB, indexC, indexD, stepIndex, stepsLength,
                                  contourIndex1, contourIndex2 ) {

        var ax = geometry.vertices[ indexA ].x,
            ay = geometry.vertices[ indexA ].y,
            az = geometry.vertices[ indexA ].z,

            bx = geometry.vertices[ indexB ].x,
            by = geometry.vertices[ indexB ].y,
            bz = geometry.vertices[ indexB ].z,

            cx = geometry.vertices[ indexC ].x,
            cy = geometry.vertices[ indexC ].y,
            cz = geometry.vertices[ indexC ].z,

            dx = geometry.vertices[ indexD ].x,
            dy = geometry.vertices[ indexD ].y,
            dz = geometry.vertices[ indexD ].z;

        if ( Math.abs( ay - by ) < 0.01 ) {
            return [
                new THREE.UV( ax, 1 - az ),
                new THREE.UV( bx, 1 - bz ),
                new THREE.UV( cx, 1 - cz ),
                new THREE.UV( dx, 1 - dz )
            ];
        } else {
            return [
                new THREE.UV( ay, 1 - az ),
                new THREE.UV( by, 1 - bz ),
                new THREE.UV( cy, 1 - cz ),
                new THREE.UV( dy, 1 - dz )
            ];
        }
    }
};

THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
/**
 * @author jonobr1 / http://jonobr1.com
 *
 * Creates a one-sided polygonal geometry from a path shape. Similar to
 * ExtrudeGeometry.
 *
 * parameters = {
 *
 *    curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
 *
 *    material: <int> // material index for front and back faces
 *    uvGenerator: <Object> // object that provides UV generator functions
 *
 * }
 **/

THREE.ShapeGeometry = function ( shapes, options ) {

    THREE.Geometry.call( this );

    if ( shapes instanceof Array === false ) shapes = [ shapes ];

    this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();

    this.addShapeList( shapes, options );

    this.computeCentroids();
    this.computeFaceNormals();

};

THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );

/**
 * Add an array of shapes to THREE.ShapeGeometry.
 */
THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {

    for ( var i = 0, l = shapes.length; i < l; i++ ) {

        this.addShape( shapes[ i ], options );

    }

    return this;

};

/**
 * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
 */
THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {

    if ( options === undefined ) options = {};

    var material = options.material;
    var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;

    var shapebb = this.shapebb;

    //

    var i, l, hole, s;

    var shapesOffset = this.vertices.length;
    var shapePoints = shape.extractPoints();

    var vertices = shapePoints.shape;
    var holes = shapePoints.holes;

    var reverse = !THREE.Shape.Utils.isClockWise( vertices );

    if ( reverse ) {

        vertices = vertices.reverse();

        // Maybe we should also check if holes are in the opposite direction, just to be safe...

        for ( i = 0, l = holes.length; i < l; i++ ) {

            hole = holes[ i ];

            if ( THREE.Shape.Utils.isClockWise( hole ) ) {

                holes[ i ] = hole.reverse();

            }

        }

        reverse = false;

    }

    var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );

    // Vertices

    var contour = vertices;

    for ( i = 0, l = holes.length; i < l; i++ ) {

        hole = holes[ i ];
        vertices = vertices.concat( hole );

    }

    //

    var vert, vlen = vertices.length;
    var face, flen = faces.length;
    var cont, clen = contour.length;

    for ( i = 0; i < vlen; i++ ) {

        vert = vertices[ i ];

        this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );

    }

    for ( i = 0; i < flen; i++ ) {

        face = faces[ i ];

        var a = face[ 2 ] + shapesOffset;
        var b = face[ 1 ] + shapesOffset;
        var c = face[ 0 ] + shapesOffset;

        this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
        this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );

    }

};
/**
 * @author astrodud / http://astrodud.isgreat.org/
 * @author zz85 / https://github.com/zz85
 */

THREE.LatheGeometry = function ( points, steps, angle ) {

    THREE.Geometry.call( this );

    var _steps = steps || 12;
    var _angle = angle || 2 * Math.PI;

    var _newV = [];
    var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );

    for ( var j = 0; j < points.length; j ++ ) {

        _newV[ j ] = points[ j ].clone();
        this.vertices.push( _newV[ j ] );

    }

    var i, il = _steps + 1;

    for ( i = 0; i < il; i ++ ) {

        for ( var j = 0; j < _newV.length; j ++ ) {

            _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
            this.vertices.push( _newV[ j ] );

        }

    }

    for ( i = 0; i < _steps; i ++ ) {

        for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {

            var a = i * kl + k;
            var b = ( ( i + 1 ) % il ) * kl + k;
            var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
            var d = i * kl + ( k + 1 ) % kl;

            this.faces.push( new THREE.Face4( a, b, c, d ) );

            this.faceVertexUvs[ 0 ].push( [

                new THREE.UV( 1 - i / _steps, k / kl ),
                new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
                new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
                new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )

            ] );

        }

    }

    this.computeCentroids();
    this.computeFaceNormals();
    this.computeVertexNormals();

};

THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
 */

THREE.PlaneGeometry = function ( width, height, segmentsWidth, segmentsheight ) {

    THREE.Geometry.call( this );

    var ix, iz,
    width_half = width / 2,
    height_half = height / 2,
    gridX = segmentsWidth || 1,
    gridZ = segmentsheight || 1,
    gridX1 = gridX + 1,
    gridZ1 = gridZ + 1,
    segment_width = width / gridX,
    segment_height = height / gridZ,
    normal = new THREE.Vector3( 0, 0, 1 );

    for ( iz = 0; iz < gridZ1; iz ++ ) {

        for ( ix = 0; ix < gridX1; ix ++ ) {

            var x = ix * segment_width - width_half;
            var y = iz * segment_height - height_half;

            this.vertices.push( new THREE.Vector3( x, - y, 0 ) );

        }

    }

    for ( iz = 0; iz < gridZ; iz ++ ) {

        for ( ix = 0; ix < gridX; ix ++ ) {

            var a = ix + gridX1 * iz;
            var b = ix + gridX1 * ( iz + 1 );
            var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
            var d = ( ix + 1 ) + gridX1 * iz;

            var face = new THREE.Face4( a, b, c, d );
            face.normal.copy( normal );
            face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );

            this.faces.push( face );
            this.faceVertexUvs[ 0 ].push( [
                new THREE.UV( ix / gridX, 1 - iz / gridZ ),
                new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
                new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
                new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
            ] );

        }

    }

    this.computeCentroids();

};

THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {

    THREE.Geometry.call( this );

    radius = radius || 50;

    phiStart = phiStart !== undefined ? phiStart : 0;
    phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;

    thetaStart = thetaStart !== undefined ? thetaStart : 0;
    thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;

    var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
    var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );

    var x, y, vertices = [], uvs = [];

    for ( y = 0; y <= segmentsY; y ++ ) {

        var verticesRow = [];
        var uvsRow = [];

        for ( x = 0; x <= segmentsX; x ++ ) {

            var u = x / segmentsX;
            var v = y / segmentsY;

            var vertex = new THREE.Vector3();
            vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
            vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
            vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );

            this.vertices.push( vertex );

            verticesRow.push( this.vertices.length - 1 );
            uvsRow.push( new THREE.UV( u, 1 - v ) );

        }

        vertices.push( verticesRow );
        uvs.push( uvsRow );

    }

    for ( y = 0; y < segmentsY; y ++ ) {

        for ( x = 0; x < segmentsX; x ++ ) {

            var v1 = vertices[ y ][ x + 1 ];
            var v2 = vertices[ y ][ x ];
            var v3 = vertices[ y + 1 ][ x ];
            var v4 = vertices[ y + 1 ][ x + 1 ];

            var n1 = this.vertices[ v1 ].clone().normalize();
            var n2 = this.vertices[ v2 ].clone().normalize();
            var n3 = this.vertices[ v3 ].clone().normalize();
            var n4 = this.vertices[ v4 ].clone().normalize();

            var uv1 = uvs[ y ][ x + 1 ].clone();
            var uv2 = uvs[ y ][ x ].clone();
            var uv3 = uvs[ y + 1 ][ x ].clone();
            var uv4 = uvs[ y + 1 ][ x + 1 ].clone();

            if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {

                this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
                this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );

            } else if ( Math.abs( this.vertices[ v3 ].y ) ==  radius ) {

                this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
                this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );

            } else {

                this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
                this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );

            }

        }

    }

    this.computeCentroids();
    this.computeFaceNormals();

    this.boundingSphere = { radius: radius };

};

THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author zz85 / http://www.lab4games.net/zz85/blog
 * @author alteredq / http://alteredqualia.com/
 *
 * For creating 3D text geometry in three.js
 *
 * Text = 3D Text
 *
 * parameters = {
 *  size:             <float>,     // size of the text
 *  height:         <float>,     // thickness to extrude text
 *  curveSegments:     <int>,        // number of points on the curves
 *
 *  font:             <string>,        // font name
 *  weight:         <string>,        // font weight (normal, bold)
 *  style:             <string>,        // font style  (normal, italics)
 *
 *  bevelEnabled:    <bool>,            // turn on bevel
 *  bevelThickness: <float>,         // how deep into text bevel goes
 *  bevelSize:        <float>,         // how far from text outline is bevel
 *  }
 *
 */

/*    Usage Examples

    // TextGeometry wrapper

    var text3d = new TextGeometry( text, options );

    // Complete manner

    var textShapes = THREE.FontUtils.generateShapes( text, options );
    var text3d = new ExtrudeGeometry( textShapes, options );

*/


THREE.TextGeometry = function ( text, parameters ) {

    var textShapes = THREE.FontUtils.generateShapes( text, parameters );

    // translate parameters to ExtrudeGeometry API

    parameters.amount = parameters.height !== undefined ? parameters.height : 50;

    // defaults

    if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
    if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
    if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;

    THREE.ExtrudeGeometry.call( this, textShapes, parameters );

};

THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
/**
 * @author oosmoxiecode
 * @author mrdoob / http://mrdoob.com/
 * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
 */

THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {

    THREE.Geometry.call( this );

    var scope = this;

    this.radius = radius || 100;
    this.tube = tube || 40;
    this.segmentsR = segmentsR || 8;
    this.segmentsT = segmentsT || 6;
    this.arc = arc || Math.PI * 2;

    var center = new THREE.Vector3(), uvs = [], normals = [];

    for ( var j = 0; j <= this.segmentsR; j ++ ) {

        for ( var i = 0; i <= this.segmentsT; i ++ ) {

            var u = i / this.segmentsT * this.arc;
            var v = j / this.segmentsR * Math.PI * 2;

            center.x = this.radius * Math.cos( u );
            center.y = this.radius * Math.sin( u );

            var vertex = new THREE.Vector3();
            vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
            vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
            vertex.z = this.tube * Math.sin( v );

            this.vertices.push( vertex );

            uvs.push( new THREE.UV( i / this.segmentsT, j / this.segmentsR ) );
            normals.push( vertex.clone().subSelf( center ).normalize() );

        }
    }


    for ( var j = 1; j <= this.segmentsR; j ++ ) {

        for ( var i = 1; i <= this.segmentsT; i ++ ) {

            var a = ( this.segmentsT + 1 ) * j + i - 1;
            var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
            var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
            var d = ( this.segmentsT + 1 ) * j + i;

            var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
            face.normal.addSelf( normals[ a ] );
            face.normal.addSelf( normals[ b ] );
            face.normal.addSelf( normals[ c ] );
            face.normal.addSelf( normals[ d ] );
            face.normal.normalize();

            this.faces.push( face );

            this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
        }

    }

    this.computeCentroids();

};

THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author oosmoxiecode
 * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
 */

THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {

    THREE.Geometry.call( this );

    var scope = this;

    this.radius = radius || 200;
    this.tube = tube || 40;
    this.segmentsR = segmentsR || 64;
    this.segmentsT = segmentsT || 8;
    this.p = p || 2;
    this.q = q || 3;
    this.heightScale = heightScale || 1;
    this.grid = new Array(this.segmentsR);

    var tang = new THREE.Vector3();
    var n = new THREE.Vector3();
    var bitan = new THREE.Vector3();

    for ( var i = 0; i < this.segmentsR; ++ i ) {

        this.grid[ i ] = new Array( this.segmentsT );

        for ( var j = 0; j < this.segmentsT; ++ j ) {

            var u = i / this.segmentsR * 2 * this.p * Math.PI;
            var v = j / this.segmentsT * 2 * Math.PI;
            var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
            var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
            var cx, cy;

            tang.sub( p2, p1 );
            n.add( p2, p1 );

            bitan.cross( tang, n );
            n.cross( bitan, tang );
            bitan.normalize();
            n.normalize();

            cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
            cy = this.tube * Math.sin( v );

            p1.x += cx * n.x + cy * bitan.x;
            p1.y += cx * n.y + cy * bitan.y;
            p1.z += cx * n.z + cy * bitan.z;

            this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );

        }

    }

    for ( var i = 0; i < this.segmentsR; ++ i ) {

        for ( var j = 0; j < this.segmentsT; ++ j ) {

            var ip = ( i + 1 ) % this.segmentsR;
            var jp = ( j + 1 ) % this.segmentsT;

            var a = this.grid[ i ][ j ];
            var b = this.grid[ ip ][ j ];
            var c = this.grid[ ip ][ jp ];
            var d = this.grid[ i ][ jp ];

            var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
            var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
            var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
            var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );

            this.faces.push( new THREE.Face4( a, b, c, d ) );
            this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );

        }
    }

    this.computeCentroids();
    this.computeFaceNormals();
    this.computeVertexNormals();

    function vert( x, y, z ) {

        return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;

    }

    function getPos( u, v, in_q, in_p, radius, heightScale ) {

        var cu = Math.cos( u );
        var cv = Math.cos( v );
        var su = Math.sin( u );
        var quOverP = in_q / in_p * u;
        var cs = Math.cos( quOverP );

        var tx = radius * ( 2 + cs ) * 0.5 * cu;
        var ty = radius * ( 2 + cs ) * su * 0.5;
        var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;

        return new THREE.Vector3( tx, ty, tz );

    }

};

THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author WestLangley / https://github.com/WestLangley
 * @author zz85 / https://github.com/zz85
 * @author miningold / https://github.com/miningold
 *
 * Modified from the TorusKnotGeometry by @oosmoxiecode
 *
 * Creates a tube which extrudes along a 3d spline
 *
 * Uses parallel transport frames as described in
 * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
 */

THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {

    THREE.Geometry.call( this );

    this.path = path;
    this.segments = segments || 64;
    this.radius = radius || 1;
    this.segmentsRadius = segmentsRadius || 8;
    this.closed = closed || false;
    if ( debug ) this.debug = new THREE.Object3D();

    this.grid = [];

    var scope = this,

        tangent,
        normal,
        binormal,

        numpoints = this.segments + 1,

        x, y, z,
        tx, ty, tz,
        u, v,

        cx, cy,
        pos, pos2 = new THREE.Vector3(),
        i, j,
        ip, jp,
        a, b, c, d,
        uva, uvb, uvc, uvd;

    var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
        tangents = frames.tangents,
        normals = frames.normals,
        binormals = frames.binormals;

    // proxy internals
    this.tangents = tangents;
    this.normals = normals;
    this.binormals = binormals;


    function vert( x, y, z ) {

        return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;

    }




    // consruct the grid

    for ( i = 0; i < numpoints; i++ ) {

        this.grid[ i ] = [];

        u = i / ( numpoints - 1 );

        pos = path.getPointAt( u );

        tangent = tangents[ i ];
        normal = normals[ i ];
        binormal = binormals[ i ];

        if ( this.debug ) {

            this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
            this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
            this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));

        }

        for ( j = 0; j < this.segmentsRadius; j++ ) {

            v = j / this.segmentsRadius * 2 * Math.PI;

            cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
            cy = this.radius * Math.sin( v );

            pos2.copy( pos );
            pos2.x += cx * normal.x + cy * binormal.x;
            pos2.y += cx * normal.y + cy * binormal.y;
            pos2.z += cx * normal.z + cy * binormal.z;

            this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );

        }
    }


    // construct the mesh

    for ( i = 0; i < this.segments; i++ ) {

        for ( j = 0; j < this.segmentsRadius; j++ ) {

            ip = ( closed ) ? (i + 1) % this.segments : i + 1;
            jp = (j + 1) % this.segmentsRadius;

            a = this.grid[ i ][ j ];        // *** NOT NECESSARILY PLANAR ! ***
            b = this.grid[ ip ][ j ];
            c = this.grid[ ip ][ jp ];
            d = this.grid[ i ][ jp ];

            uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
            uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
            uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
            uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );

            this.faces.push( new THREE.Face4( a, b, c, d ) );
            this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );

        }
    }

    this.computeCentroids();
    this.computeFaceNormals();
    this.computeVertexNormals();

};

THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );


// For computing of Frenet frames, exposing the tangents, normals and binormals the spline
THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {

    var
        tangent = new THREE.Vector3(),
        normal = new THREE.Vector3(),
        binormal = new THREE.Vector3(),

        tangents = [],
        normals = [],
        binormals = [],

        vec = new THREE.Vector3(),
        mat = new THREE.Matrix4(),

        numpoints = segments + 1,
        theta,
        epsilon = 0.0001,
        smallest,

        tx, ty, tz,
        i, u, v;


    // expose internals
    this.tangents = tangents;
    this.normals = normals;
    this.binormals = binormals;

    // compute the tangent vectors for each segment on the path

    for ( i = 0; i < numpoints; i++ ) {

        u = i / ( numpoints - 1 );

        tangents[ i ] = path.getTangentAt( u );
        tangents[ i ].normalize();

    }

    initialNormal3();

    function initialNormal1(lastBinormal) {
        // fixed start binormal. Has dangers of 0 vectors
        normals[ 0 ] = new THREE.Vector3();
        binormals[ 0 ] = new THREE.Vector3();
        if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
        normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
        binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
    }

    function initialNormal2() {

        // This uses the Frenet-Serret formula for deriving binormal
        var t2 = path.getTangentAt( epsilon );

        normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
        binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );

        normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
        binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();

    }

    function initialNormal3() {
        // select an initial normal vector perpenicular to the first tangent vector,
        // and in the direction of the smallest tangent xyz component

        normals[ 0 ] = new THREE.Vector3();
        binormals[ 0 ] = new THREE.Vector3();
        smallest = Number.MAX_VALUE;
        tx = Math.abs( tangents[ 0 ].x );
        ty = Math.abs( tangents[ 0 ].y );
        tz = Math.abs( tangents[ 0 ].z );

        if ( tx <= smallest ) {
            smallest = tx;
            normal.set( 1, 0, 0 );
        }

        if ( ty <= smallest ) {
            smallest = ty;
            normal.set( 0, 1, 0 );
        }

        if ( tz <= smallest ) {
            normal.set( 0, 0, 1 );
        }

        vec.cross( tangents[ 0 ], normal ).normalize();

        normals[ 0 ].cross( tangents[ 0 ], vec );
        binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
    }


    // compute the slowly-varying normal and binormal vectors for each segment on the path

    for ( i = 1; i < numpoints; i++ ) {

        normals[ i ] = normals[ i-1 ].clone();

        binormals[ i ] = binormals[ i-1 ].clone();

        vec.cross( tangents[ i-1 ], tangents[ i ] );

        if ( vec.length() > epsilon ) {

            vec.normalize();

            theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );

            mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );

        }

        binormals[ i ].cross( tangents[ i ], normals[ i ] );

    }


    // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same

    if ( closed ) {

        theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
        theta /= ( numpoints - 1 );

        if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {

            theta = -theta;

        }

        for ( i = 1; i < numpoints; i++ ) {

            // twist a little...
            mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
            binormals[ i ].cross( tangents[ i ], normals[ i ] );

        }

    }
};
/**
 * @author clockworkgeek / https://github.com/clockworkgeek
 * @author timothypratley / https://github.com/timothypratley
 */

THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {

    THREE.Geometry.call( this );

    radius = radius || 1;
    detail = detail || 0;

    var that = this;

    for ( var i = 0, l = vertices.length; i < l; i ++ ) {

        prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );

    }

    var midpoints = [], p = this.vertices;

    for ( var i = 0, l = faces.length; i < l; i ++ ) {

        make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );

    }

    this.mergeVertices();

    // Apply radius

    for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {

        this.vertices[ i ].multiplyScalar( radius );

    }


    // Project vector onto sphere's surface

    function prepare( vector ) {

        var vertex = vector.normalize().clone();
        vertex.index = that.vertices.push( vertex ) - 1;

        // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.

        var u = azimuth( vector ) / 2 / Math.PI + 0.5;
        var v = inclination( vector ) / Math.PI + 0.5;
        vertex.uv = new THREE.UV( u, 1 - v );

        return vertex;

    }


    // Approximate a curved face with recursively sub-divided triangles.

    function make( v1, v2, v3, detail ) {

        if ( detail < 1 ) {

            var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
            face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
            face.normal = face.centroid.clone().normalize();
            that.faces.push( face );

            var azi = azimuth( face.centroid );
            that.faceVertexUvs[ 0 ].push( [
                correctUV( v1.uv, v1, azi ),
                correctUV( v2.uv, v2, azi ),
                correctUV( v3.uv, v3, azi )
            ] );

        } else {

            detail -= 1;

            // split triangle into 4 smaller triangles

            make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
            make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
            make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
            make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant

        }

    }

    function midpoint( v1, v2 ) {

        if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
        if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];

        var mid = midpoints[ v1.index ][ v2.index ];

        if ( mid === undefined ) {

            // generate mean point and project to surface with prepare()

            midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
                new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
            );
        }

        return mid;

    }


    // Angle around the Y axis, counter-clockwise when looking from above.

    function azimuth( vector ) {

        return Math.atan2( vector.z, -vector.x );

    }


    // Angle above the XZ plane.

    function inclination( vector ) {

        return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );

    }


    // Texture fixing helper. Spheres have some odd behaviours.

    function correctUV( uv, vector, azimuth ) {

        if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
        if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
        return uv;

    }

    this.computeCentroids();

    this.boundingSphere = { radius: radius };

};

THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author timothypratley / https://github.com/timothypratley
 */

THREE.IcosahedronGeometry = function ( radius, detail ) {

    var t = ( 1 + Math.sqrt( 5 ) ) / 2;

    var vertices = [
        [ -1,  t,  0 ], [  1, t, 0 ], [ -1, -t,  0 ], [  1, -t,  0 ],
        [  0, -1,  t ], [  0, 1, t ], [  0, -1, -t ], [  0,  1, -t ],
        [  t,  0, -1 ], [  t, 0, 1 ], [ -t,  0, -1 ], [ -t,  0,  1 ]
    ];

    var faces = [
        [ 0, 11,  5 ], [ 0,  5,  1 ], [  0,  1,  7 ], [  0,  7, 10 ], [  0, 10, 11 ],
        [ 1,  5,  9 ], [ 5, 11,  4 ], [ 11, 10,  2 ], [ 10,  7,  6 ], [  7,  1,  8 ],
        [ 3,  9,  4 ], [ 3,  4,  2 ], [  3,  2,  6 ], [  3,  6,  8 ], [  3,  8,  9 ],
        [ 4,  9,  5 ], [ 2,  4, 11 ], [  6,  2, 10 ], [  8,  6,  7 ], [  9,  8,  1 ]
    ];

    THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );

};

THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author timothypratley / https://github.com/timothypratley
 */

THREE.OctahedronGeometry = function ( radius, detail ) {

    var vertices = [
        [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
    ];

    var faces = [
        [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
    ];

    THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
};

THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author timothypratley / https://github.com/timothypratley
 */

THREE.TetrahedronGeometry = function ( radius, detail ) {

    var vertices = [
        [ 1,  1,  1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
    ];

    var faces = [
        [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
    ];

    THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );

};

THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author zz85 / https://github.com/zz85
 * Parametric Surfaces Geometry
 * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
 *
 * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
 *
 */

THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {

    THREE.Geometry.call( this );

    var verts = this.vertices;
    var faces = this.faces;
    var uvs = this.faceVertexUvs[ 0 ];

    useTris = (useTris === undefined) ? false : useTris;

    var i, il, j, p;
    var u, v;

    var stackCount = stacks + 1;
    var sliceCount = slices + 1;

    for ( i = 0; i <= stacks; i ++ ) {

        v = i / stacks;

        for ( j = 0; j <= slices; j ++ ) {

            u = j / slices;

            p = func( u, v );
            verts.push( p );

        }
    }

    var a, b, c, d;
    var uva, uvb, uvc, uvd;

    for ( i = 0; i < stacks; i ++ ) {

        for ( j = 0; j < slices; j ++ ) {

            a = i * sliceCount + j;
            b = i * sliceCount + j + 1;
            c = (i + 1) * sliceCount + j;
            d = (i + 1) * sliceCount + j + 1;

            uva = new THREE.UV( j / slices, i / stacks );
            uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
            uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
            uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );

            if ( useTris ) {

                faces.push( new THREE.Face3( a, b, c ) );
                faces.push( new THREE.Face3( b, d, c ) );

                uvs.push( [ uva, uvb, uvc ] );
                uvs.push( [ uvb, uvd, uvc ] );

            } else {

                faces.push( new THREE.Face4( a, b, d, c ) );
                uvs.push( [ uva, uvb, uvd, uvc ] );

            }

        }

    }

    // console.log(this);

    // magic bullet
    // var diff = this.mergeVertices();
    // console.log('removed ', diff, ' vertices by merging');

    this.computeCentroids();
    this.computeFaceNormals();
    this.computeVertexNormals();

};

THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author qiao / https://github.com/qiao
 * @fileoverview This is a convex hull generator using the incremental method.
 * The complexity is O(n^2) where n is the number of vertices.
 * O(nlogn) algorithms do exist, but they are much more complicated.
 *
 * Benchmark:
 *
 *  Platform: CPU: P7350 @2.00GHz Engine: V8
 *
 *  Num Vertices    Time(ms)
 *
 *     10           1
 *     20           3
 *     30           19
 *     40           48
 *     50           107
 */

THREE.ConvexGeometry = function( vertices ) {

    THREE.Geometry.call( this );

    var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];

    for ( var i = 3; i < vertices.length; i++ ) {

        addPoint( i );

    }


    function addPoint( vertexId ) {

        var vertex = vertices[ vertexId ].clone();

        var mag = vertex.length();
        vertex.x += mag * randomOffset();
        vertex.y += mag * randomOffset();
        vertex.z += mag * randomOffset();

        var hole = [];

        for ( var f = 0; f < faces.length; ) {

            var face = faces[ f ];

            // for each face, if the vertex can see it,
            // then we try to add the face's edges into the hole.
            if ( visible( face, vertex ) ) {

                for ( var e = 0; e < 3; e++ ) {

                    var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
                    var boundary = true;

                    // remove duplicated edges.
                    for ( var h = 0; h < hole.length; h++ ) {

                        if ( equalEdge( hole[ h ], edge ) ) {

                            hole[ h ] = hole[ hole.length - 1 ];
                            hole.pop();
                            boundary = false;
                            break;

                        }

                    }

                    if ( boundary ) {

                        hole.push( edge );

                    }

                }

                // remove faces[ f ]
                faces[ f ] = faces[ faces.length - 1 ];
                faces.pop();

            } else { // not visible

                f++;

            }
        }

        // construct the new faces formed by the edges of the hole and the vertex
        for ( var h = 0; h < hole.length; h++ ) {

            faces.push( [
                hole[ h ][ 0 ],
                hole[ h ][ 1 ],
                vertexId
            ] );

        }
    }

    /**
     * Whether the face is visible from the vertex
     */
    function visible( face, vertex ) {

        var va = vertices[ face[ 0 ] ];
        var vb = vertices[ face[ 1 ] ];
        var vc = vertices[ face[ 2 ] ];

        var n = normal( va, vb, vc );

        // distance from face to origin
        var dist = n.dot( va );

        return n.dot( vertex ) >= dist;

    }

    /**
     * Face normal
     */
    function normal( va, vb, vc ) {

        var cb = new THREE.Vector3();
        var ab = new THREE.Vector3();

        cb.sub( vc, vb );
        ab.sub( va, vb );
        cb.crossSelf( ab );

        if ( !cb.isZero() ) {

            cb.normalize();

        }

        return cb;

    }

    /**
     * Detect whether two edges are equal.
     * Note that when constructing the convex hull, two same edges can only
     * be of the negative direction.
     */
    function equalEdge( ea, eb ) {

        return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];

    }

    /**
     * Create a random offset between -1e-6 and 1e-6.
     */
    function randomOffset() {

        return ( Math.random() - 0.5 ) * 2 * 1e-6;

    }


    /**
     * XXX: Not sure if this is the correct approach. Need someone to review.
     */
    function vertexUv( vertex ) {

        var mag = vertex.length();
        return new THREE.UV( vertex.x / mag, vertex.y / mag );

    }

    // Push vertices into `this.vertices`, skipping those inside the hull
    var id = 0;
    var newId = new Array( vertices.length ); // map from old vertex id to new id

    for ( var i = 0; i < faces.length; i++ ) {

         var face = faces[ i ];

         for ( var j = 0; j < 3; j++ ) {

                if ( newId[ face[ j ] ] === undefined ) {

                        newId[ face[ j ] ] = id++;
                        this.vertices.push( vertices[ face[ j ] ] );

                }

                face[ j ] = newId[ face[ j ] ];

         }

    }

    // Convert faces into instances of THREE.Face3
    for ( var i = 0; i < faces.length; i++ ) {

        this.faces.push( new THREE.Face3(
                faces[ i ][ 0 ],
                faces[ i ][ 1 ],
                faces[ i ][ 2 ]
        ) );

    }

    // Compute UVs
    for ( var i = 0; i < this.faces.length; i++ ) {

        var face = this.faces[ i ];

        this.faceVertexUvs[ 0 ].push( [
            vertexUv( this.vertices[ face.a ] ),
            vertexUv( this.vertices[ face.b ] ),
            vertexUv( this.vertices[ face.c ])
        ] );

    }


    this.computeCentroids();
    this.computeFaceNormals();
    this.computeVertexNormals();

};

THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
/**
 * @author sroucheray / http://sroucheray.org/
 * @author mrdoob / http://mrdoob.com/
 */

THREE.AxisHelper = function () {

    THREE.Object3D.call( this );

    var lineGeometry = new THREE.Geometry();
    lineGeometry.vertices.push( new THREE.Vector3() );
    lineGeometry.vertices.push( new THREE.Vector3( 0, 100, 0 ) );

    var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );

    var line, cone;

    // x

    line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
    line.rotation.z = - Math.PI / 2;
    this.add( line );

    cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
    cone.position.x = 100;
    cone.rotation.z = - Math.PI / 2;
    this.add( cone );

    // y

    line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
    this.add( line );

    cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
    cone.position.y = 100;
    this.add( cone );

    // z

    line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
    line.rotation.x = Math.PI / 2;
    this.add( line );

    cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
    cone.position.z = 100;
    cone.rotation.x = Math.PI / 2;
    this.add( cone );

};

THREE.AxisHelper.prototype = Object.create( THREE.Object3D.prototype );
/**
 * @author WestLangley / http://github.com/WestLangley
 * @author zz85 / https://github.com/zz85
 *
 * Creates an arrow for visualizing directions
 *
 * Parameters:
 *  dir - Vector3
 *  origin - Vector3
 *  length - Number
 *  hex - color in hex value
 */

THREE.ArrowHelper = function ( dir, origin, length, hex ) {

    THREE.Object3D.call( this );

    if ( hex === undefined ) hex = 0xffff00;
    if ( length === undefined ) length = 20;

    var lineGeometry = new THREE.Geometry();
    lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
    lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );

    this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
    this.add( this.line );

    var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );

    this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
    this.cone.position.set( 0, 1, 0 );
    this.add( this.cone );

    if ( origin instanceof THREE.Vector3 ) this.position = origin;

    this.setDirection( dir );
    this.setLength( length );

};

THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );

THREE.ArrowHelper.prototype.setDirection = function ( dir ) {

    var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );

    var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );

    this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );

    this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );

};

THREE.ArrowHelper.prototype.setLength = function ( length ) {

    this.scale.set( length, length, length );

};

THREE.ArrowHelper.prototype.setColor = function ( hex ) {

    this.line.material.color.setHex( hex );
    this.cone.material.color.setHex( hex );

};
/**
 * @author alteredq / http://alteredqualia.com/
 *
 *    - shows frustum, line of sight and up of the camera
 *    - suitable for fast updates
 *     - based on frustum visualization in lightgl.js shadowmap example
 *        http://evanw.github.com/lightgl.js/tests/shadowmap.html
 */

THREE.CameraHelper = function ( camera ) {

    THREE.Line.call( this );

    var scope = this;

    this.geometry = new THREE.Geometry();
    this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
    this.type = THREE.LinePieces;

    this.matrixWorld = camera.matrixWorld;
    this.matrixAutoUpdate = false;

    this.pointMap = {};

    // colors

    var hexFrustum = 0xffaa00;
    var hexCone = 0xff0000;
    var hexUp = 0x00aaff;
    var hexTarget = 0xffffff;
    var hexCross = 0x333333;

    // near

    addLine( "n1", "n2", hexFrustum );
    addLine( "n2", "n4", hexFrustum );
    addLine( "n4", "n3", hexFrustum );
    addLine( "n3", "n1", hexFrustum );

    // far

    addLine( "f1", "f2", hexFrustum );
    addLine( "f2", "f4", hexFrustum );
    addLine( "f4", "f3", hexFrustum );
    addLine( "f3", "f1", hexFrustum );

    // sides

    addLine( "n1", "f1", hexFrustum );
    addLine( "n2", "f2", hexFrustum );
    addLine( "n3", "f3", hexFrustum );
    addLine( "n4", "f4", hexFrustum );

    // cone

    addLine( "p", "n1", hexCone );
    addLine( "p", "n2", hexCone );
    addLine( "p", "n3", hexCone );
    addLine( "p", "n4", hexCone );

    // up

    addLine( "u1", "u2", hexUp );
    addLine( "u2", "u3", hexUp );
    addLine( "u3", "u1", hexUp );

    // target

    addLine( "c", "t", hexTarget );
    addLine( "p", "c", hexCross );

    // cross

    addLine( "cn1", "cn2", hexCross );
    addLine( "cn3", "cn4", hexCross );

    addLine( "cf1", "cf2", hexCross );
    addLine( "cf3", "cf4", hexCross );

    this.camera = camera;

    function addLine( a, b, hex ) {

        addPoint( a, hex );
        addPoint( b, hex );

    }

    function addPoint( id, hex ) {

        scope.geometry.vertices.push( new THREE.Vector3() );
        scope.geometry.colors.push( new THREE.Color( hex ) );

        if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];

        scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );

    }

    this.update( camera );

};

THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );

THREE.CameraHelper.prototype.update = function () {

    var scope = this;

    var w = 1, h = 1;

    // we need just camera projection matrix
    // world matrix must be identity

    THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );

    // center / target

    setPoint( "c", 0, 0, -1 );
    setPoint( "t", 0, 0,  1 );

    // near

    setPoint( "n1", -w, -h, -1 );
    setPoint( "n2",  w, -h, -1 );
    setPoint( "n3", -w,  h, -1 );
    setPoint( "n4",  w,  h, -1 );

    // far

    setPoint( "f1", -w, -h, 1 );
    setPoint( "f2",  w, -h, 1 );
    setPoint( "f3", -w,  h, 1 );
    setPoint( "f4",  w,  h, 1 );

    // up

    setPoint( "u1",  w * 0.7, h * 1.1, -1 );
    setPoint( "u2", -w * 0.7, h * 1.1, -1 );
    setPoint( "u3",        0, h * 2,   -1 );

    // cross

    setPoint( "cf1", -w,  0, 1 );
    setPoint( "cf2",  w,  0, 1 );
    setPoint( "cf3",  0, -h, 1 );
    setPoint( "cf4",  0,  h, 1 );

    setPoint( "cn1", -w,  0, -1 );
    setPoint( "cn2",  w,  0, -1 );
    setPoint( "cn3",  0, -h, -1 );
    setPoint( "cn4",  0,  h, -1 );

    function setPoint( point, x, y, z ) {

        THREE.CameraHelper.__v.set( x, y, z );
        THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );

        var points = scope.pointMap[ point ];

        if ( points !== undefined ) {

            for ( var i = 0, il = points.length; i < il; i ++ ) {

                scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );

            }

        }

    }

    this.geometry.verticesNeedUpdate = true;

};

THREE.CameraHelper.__projector = new THREE.Projector();
THREE.CameraHelper.__v = new THREE.Vector3();
THREE.CameraHelper.__c = new THREE.Camera();

/*
 *    @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
 *
 *    Subdivision Geometry Modifier
 *        using Catmull-Clark Subdivision Surfaces
 *        for creating smooth geometry meshes
 *
 *    Note: a modifier modifies vertices and faces of geometry,
 *        so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
 *
 *    Readings:
 *        http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
 *        http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
 *        http://xrt.wikidot.com/blog:31
 *        "Subdivision Surfaces in Character Animation"
 *
 *    Supports:
 *        Closed and Open geometries.
 *
 *    TODO:
 *        crease vertex and "semi-sharp" features
 *        selective subdivision
 */

THREE.SubdivisionModifier = function( subdivisions ) {

    this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;

    // Settings
    this.useOldVertexColors = false;
    this.supportUVs = true;
    this.debug = false;

};

// Applies the "modify" pattern
THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {

    var repeats = this.subdivisions;

    while ( repeats-- > 0 ) {
        this.smooth( geometry );
    }

};

// Performs an iteration of Catmull-Clark Subdivision
THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {

    //debug( 'running smooth' );

    // New set of vertices, faces and uvs
    var newVertices = [], newFaces = [], newUVs = [];

    function v( x, y, z ) {
        newVertices.push( new THREE.Vector3( x, y, z ) );
    }

    var scope = this;

    function debug() {
        if (scope.debug) console.log.apply(console, arguments);
    }

    function warn() {
        if (console)
        console.log.apply(console, arguments);
    }

    function f4( a, b, c, d, oldFace, orders, facei ) {

        // TODO move vertex selection over here!

        var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );

        if (scope.useOldVertexColors) {

            newFace.vertexColors = [];

            var color, tmpColor, order;
            for (var i=0;i<4;i++) {
                order = orders[i];

                color = new THREE.Color(),
                color.setRGB(0,0,0);

                for (var j=0, jl=0; j<order.length;j++) {
                    tmpColor = oldFace.vertexColors[order[j]-1];
                    color.r += tmpColor.r;
                    color.g += tmpColor.g;
                    color.b += tmpColor.b;
                }

                color.r /= order.length;
                color.g /= order.length;
                color.b /= order.length;

                newFace.vertexColors[i] = color;

            }

        }

        newFaces.push( newFace );

        if (scope.supportUVs) {

            var aUv = [
                getUV(a, ''),
                getUV(b, facei),
                getUV(c, facei),
                getUV(d, facei)
            ];

            if (!aUv[0]) debug('a :( ', a+':'+facei);
            else if (!aUv[1]) debug('b :( ', b+':'+facei);
            else if (!aUv[2]) debug('c :( ', c+':'+facei);
            else if (!aUv[3]) debug('d :( ', d+':'+facei);
            else
                newUVs.push( aUv );

        }
    }

    function edge_hash( a, b ) {

        return Math.min( a, b ) + "_" + Math.max( a, b );

    }

    function computeEdgeFaces( geometry ) {

        var i, il, v1, v2, j, k,
            face, faceIndices, faceIndex,
            edge,
            hash,
            edgeFaceMap = {};

        function mapEdgeHash( hash, i ) {

            if ( edgeFaceMap[ hash ] === undefined ) {

                edgeFaceMap[ hash ] = [];

            }

            edgeFaceMap[ hash ].push( i );
        }


        // construct vertex -> face map

        for( i = 0, il = geometry.faces.length; i < il; i ++ ) {

            face = geometry.faces[ i ];

            if ( face instanceof THREE.Face3 ) {

                hash = edge_hash( face.a, face.b );
                mapEdgeHash( hash, i );

                hash = edge_hash( face.b, face.c );
                mapEdgeHash( hash, i );

                hash = edge_hash( face.c, face.a );
                mapEdgeHash( hash, i );

            } else if ( face instanceof THREE.Face4 ) {

                hash = edge_hash( face.a, face.b );
                mapEdgeHash( hash, i );

                hash = edge_hash( face.b, face.c );
                mapEdgeHash( hash, i );

                hash = edge_hash( face.c, face.d );
                mapEdgeHash( hash, i );

                hash = edge_hash( face.d, face.a );
                mapEdgeHash( hash, i );

            }

        }

        // extract faces

        // var edges = [];
        //
        // var numOfEdges = 0;
        // for (i in edgeFaceMap) {
        //     numOfEdges++;
        //
        //     edge = edgeFaceMap[i];
        //     edges.push(edge);
        //
        // }

        //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);

        return edgeFaceMap;

    }

    var originalPoints = oldGeometry.vertices;
    var originalFaces = oldGeometry.faces;

    var newPoints = originalPoints.concat(); // Vertices

    var facePoints = [], edgePoints = {};

    var sharpEdges = {}, sharpVertices = [], sharpFaces = [];

    var uvForVertices = {}; // Stored in {vertex}:{old face} format

    var originalVerticesLength = originalPoints.length;

    function getUV(vertexNo, oldFaceNo) {
        var j,jl;

        var key = vertexNo+':'+oldFaceNo;
        var theUV = uvForVertices[key];

        if (!theUV) {
            if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
                debug('face pt');
            } else {
                debug('edge pt');
            }

            warn('warning, UV not found for', key);

            return null;
        }

        return theUV;

        // Original faces -> Vertex Nos.
        // new Facepoint -> Vertex Nos.
        // edge Points

    }

    function addUV(vertexNo, oldFaceNo, value) {

        var key = vertexNo+':'+oldFaceNo;
        if (!(key in uvForVertices)) {
            uvForVertices[key] = value;
        } else {
            warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
        }
    }

    // Step 1
    //    For each face, add a face point
    //    Set each face point to be the centroid of all original points for the respective face.
    // debug(oldGeometry);
    var i, il, j, jl, face;

    // For Uvs
    var uvs = oldGeometry.faceVertexUvs[0];
    var abcd = 'abcd', vertice;

    debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
    if (scope.supportUVs)
    for (i=0, il = uvs.length; i<il; i++ ) {
        for (j=0,jl=uvs[i].length;j<jl;j++) {
            vertice = originalFaces[i][abcd.charAt(j)];

            addUV(vertice, i, uvs[i][j]);

        }
    }

    if (uvs.length == 0) scope.supportUVs = false;

    // Additional UVs check, if we index original
    var uvCount = 0;
    for (var u in uvForVertices) {
        uvCount++;
    }
    if (!uvCount) {
        scope.supportUVs = false;
        debug('no uvs');
    }

    debug('-- Original Faces + Vertices UVs completed', uvForVertices, 'vs', uvs.length);

    var avgUv ;
    for (i=0, il = originalFaces.length; i<il ;i++) {
        face = originalFaces[ i ];
        facePoints.push( face.centroid );
        newPoints.push( face.centroid );


        if (!scope.supportUVs) continue;

        // Prepare subdivided uv

        avgUv = new THREE.UV();

        if ( face instanceof THREE.Face3 ) {
            avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
            avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
            avgUv.u /= 3;
            avgUv.v /= 3;

        } else if ( face instanceof THREE.Face4 ) {
            avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
            avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
            avgUv.u /= 4;
            avgUv.v /= 4;
        }

        addUV(originalVerticesLength + i, '', avgUv);

    }

    debug('-- added UVs for new Faces', uvForVertices);

    // Step 2
    //    For each edge, add an edge point.
    //    Set each edge point to be the average of the two neighbouring face points and its two original endpoints.

    var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index
    var edge, faceIndexA, faceIndexB, avg;

    // debug('edgeFaceMap', edgeFaceMap);

    var edgeCount = 0;

    var edgeVertex, edgeVertexA, edgeVertexB;

    ////

    var vertexEdgeMap = {}; // Gives edges connecting from each vertex
    var vertexFaceMap = {}; // Gives faces connecting from each vertex

    function addVertexEdgeMap(vertex, edge) {
        if (vertexEdgeMap[vertex]===undefined) {
            vertexEdgeMap[vertex] = [];
        }

        vertexEdgeMap[vertex].push(edge);
    }

    function addVertexFaceMap(vertex, face, edge) {
        if (vertexFaceMap[vertex]===undefined) {
            vertexFaceMap[vertex] = {};
        }

        vertexFaceMap[vertex][face] = edge;
        // vertexFaceMap[vertex][face] = null;
    }

    // Prepares vertexEdgeMap and vertexFaceMap
    for (i in edgeFaceMap) { // This is for every edge
        edge = edgeFaceMap[i];

        edgeVertex = i.split('_');
        edgeVertexA = edgeVertex[0];
        edgeVertexB = edgeVertex[1];

        // Maps an edgeVertex to connecting edges
        addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
        addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );


        for (j=0,jl=edge.length;j<jl;j++) {
            face = edge[j];

            addVertexFaceMap(edgeVertexA, face, i);
            addVertexFaceMap(edgeVertexB, face, i);
        }

        if (edge.length < 2) {
            // edge is "sharp";
            sharpEdges[i] = true;
            sharpVertices[edgeVertexA] = true;
            sharpVertices[edgeVertexB] = true;

        }

    }

    debug('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);


    for (i in edgeFaceMap) {
        edge = edgeFaceMap[i];

        faceIndexA = edge[0]; // face index a
        faceIndexB = edge[1]; // face index b

        edgeVertex = i.split('_');
        edgeVertexA = edgeVertex[0];
        edgeVertexB = edgeVertex[1];


        avg = new THREE.Vector3();

        //debug(i, faceIndexB,facePoints[faceIndexB]);

        if (sharpEdges[i]) {
            //debug('warning, ', i, 'edge has only 1 connecting face', edge);

            // For a sharp edge, average the edge end points.
            avg.addSelf(originalPoints[edgeVertexA]);
            avg.addSelf(originalPoints[edgeVertexB]);

            avg.multiplyScalar(0.5);

            sharpVertices[newPoints.length] = true;

        } else {

            avg.addSelf(facePoints[faceIndexA]);
            avg.addSelf(facePoints[faceIndexB]);

            avg.addSelf(originalPoints[edgeVertexA]);
            avg.addSelf(originalPoints[edgeVertexB]);

            avg.multiplyScalar(0.25);

        }

        edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;

        newPoints.push( avg );

        edgeCount ++;

        if (!scope.supportUVs) {
            continue;
        }

        // debug('faceIndexAB', faceIndexA, faceIndexB, sharpEdges[i]);

        // Prepare subdivided uv

        avgUv = new THREE.UV();

        avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
        avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
        avgUv.u /= 2;
        avgUv.v /= 2;

        addUV(edgePoints[i], faceIndexA, avgUv);

        if (!sharpEdges[i]) {
        avgUv = new THREE.UV();

        avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
        avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
        avgUv.u /= 2;
        avgUv.v /= 2;

        addUV(edgePoints[i], faceIndexB, avgUv);
        }

    }

    debug('-- Step 2 done');

    // Step 3
    //    For each face point, add an edge for every edge of the face,
    //    connecting the face point to each edge point for the face.


    var facePt, currentVerticeIndex;

    var hashAB, hashBC, hashCD, hashDA, hashCA;

    var abc123 = ['123', '12', '2', '23'];
    var bca123 = ['123', '23', '3', '31'];
    var cab123 = ['123', '31', '1', '12'];
    var abc1234 = ['1234', '12', '2', '23'];
    var bcd1234 = ['1234', '23', '3', '34'];
    var cda1234 = ['1234', '34', '4', '41'];
    var dab1234 = ['1234', '41', '1', '12'];


    for (i=0, il = facePoints.length; i<il ;i++) { // for every face
        facePt = facePoints[i];
        face = originalFaces[i];
        currentVerticeIndex = originalVerticesLength+ i;

        if ( face instanceof THREE.Face3 ) {

            // create 3 face4s

            hashAB = edge_hash( face.a, face.b );
            hashBC = edge_hash( face.b, face.c );
            hashCA = edge_hash( face.c, face.a );

            f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
            f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
            f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );

        } else if ( face instanceof THREE.Face4 ) {
            // create 4 face4s

            hashAB = edge_hash( face.a, face.b );
            hashBC = edge_hash( face.b, face.c );
            hashCD = edge_hash( face.c, face.d );
            hashDA = edge_hash( face.d, face.a );

            f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
            f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
            f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
            f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );


        } else {
            debug('face should be a face!', face);
        }
    }

    newVertices = newPoints;

    // debug('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
    // debug('new points', newPoints.length, 'faces', newFaces.length );

    // Step 4

    //    For each original point P,
    //        take the average F of all n face points for faces touching P,
    //        and take the average R of all n edge midpoints for edges touching P,
    //        where each edge midpoint is the average of its two endpoint vertices.
    //    Move each original point to the point


    var F = new THREE.Vector3();
    var R = new THREE.Vector3();

    var n;
    for (i=0, il = originalPoints.length; i<il; i++) {
        // (F + 2R + (n-3)P) / n

        if (vertexEdgeMap[i]===undefined) continue;

        F.set(0,0,0);
        R.set(0,0,0);
        var newPos =  new THREE.Vector3(0,0,0);

        var f =0;
        for (j in vertexFaceMap[i]) {
            F.addSelf(facePoints[j]);
            f++;
        }

        var sharpEdgeCount = 0;

        n = vertexEdgeMap[i].length;

        for (j=0;j<n;j++) {
            if (
                sharpEdges[
                    edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
                ]) {
                    sharpEdgeCount++;
                }
        }

        if ( sharpEdgeCount==2 ) {
            continue;
            // Do not move vertex if there's 2 connecting sharp edges.
        }

        /*
        if (sharpEdgeCount>2) {
            // TODO
        }
        */

        F.divideScalar(f);



        for (j=0; j<n;j++) {
            edge = vertexEdgeMap[i][j];
            var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
            R.addSelf(midPt);
            // R.addSelf(originalPoints[edge[0]]);
            // R.addSelf(originalPoints[edge[1]]);
        }

        R.divideScalar(n);

        newPos.addSelf(originalPoints[i]);
        newPos.multiplyScalar(n - 3);

        newPos.addSelf(F);
        newPos.addSelf(R.multiplyScalar(2));
        newPos.divideScalar(n);

        newVertices[i] = newPos;


    }

    var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P

    newGeometry.vertices = newVertices;
    newGeometry.faces = newFaces;
    newGeometry.faceVertexUvs[ 0 ] = newUVs;

    delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P

    newGeometry.computeCentroids();
    newGeometry.computeFaceNormals();
    newGeometry.computeVertexNormals();

};
/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.ImmediateRenderObject = function ( ) {

    THREE.Object3D.call( this );

    this.render = function ( renderCallback ) { };

};

THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.LensFlare = function ( texture, size, distance, blending, color ) {

    THREE.Object3D.call( this );

    this.lensFlares = [];

    this.positionScreen = new THREE.Vector3();
    this.customUpdateCallback = undefined;

    if( texture !== undefined ) {

        this.add( texture, size, distance, blending, color );

    }

};

THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );


/*
 * Add: adds another flare
 */

THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {

    if( size === undefined ) size = -1;
    if( distance === undefined ) distance = 0;
    if( opacity === undefined ) opacity = 1;
    if( color === undefined ) color = new THREE.Color( 0xffffff );
    if( blending === undefined ) blending = THREE.NormalBlending;

    distance = Math.min( distance, Math.max( 0, distance ) );

    this.lensFlares.push( { texture: texture,             // THREE.Texture
                            size: size,                 // size in pixels (-1 = use texture.width)
                            distance: distance,         // distance (0-1) from light source (0=at light source)
                            x: 0, y: 0, z: 0,            // screen position (-1 => 1) z = 0 is ontop z = 1 is back
                            scale: 1,                     // scale
                            rotation: 1,                 // rotation
                            opacity: opacity,            // opacity
                            color: color,                // color
                            blending: blending } );        // blending

};


/*
 * Update lens flares update positions on all flares based on the screen position
 * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
 */

THREE.LensFlare.prototype.updateLensFlares = function () {

    var f, fl = this.lensFlares.length;
    var flare;
    var vecX = -this.positionScreen.x * 2;
    var vecY = -this.positionScreen.y * 2;

    for( f = 0; f < fl; f ++ ) {

        flare = this.lensFlares[ f ];

        flare.x = this.positionScreen.x + vecX * flare.distance;
        flare.y = this.positionScreen.y + vecY * flare.distance;

        flare.wantedRotation = flare.x * Math.PI * 0.25;
        flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;

    }

};












/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.MorphBlendMesh = function( geometry, material ) {

    THREE.Mesh.call( this, geometry, material );

    this.animationsMap = {};
    this.animationsList = [];

    // prepare default animation
    // (all frames played together in 1 second)

    var numFrames = this.geometry.morphTargets.length;

    var name = "__default";

    var startFrame = 0;
    var endFrame = numFrames - 1;

    var fps = numFrames / 1;

    this.createAnimation( name, startFrame, endFrame, fps );
    this.setAnimationWeight( name, 1 );

};

THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );

THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {

    var animation = {

        startFrame: start,
        endFrame: end,

        length: end - start + 1,

        fps: fps,
        duration: ( end - start ) / fps,

        lastFrame: 0,
        currentFrame: 0,

        active: false,

        time: 0,
        direction: 1,
        weight: 1,

        directionBackwards: false,
        mirroredLoop: false

    };

    this.animationsMap[ name ] = animation;
    this.animationsList.push( animation );

};

THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {

    var pattern = /([a-z]+)(\d+)/;

    var firstAnimation, frameRanges = {};

    var geometry = this.geometry;

    for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {

        var morph = geometry.morphTargets[ i ];
        var chunks = morph.name.match( pattern );

        if ( chunks && chunks.length > 1 ) {

            var name = chunks[ 1 ];
            var num = chunks[ 2 ];

            if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };

            var range = frameRanges[ name ];

            if ( i < range.start ) range.start = i;
            if ( i > range.end ) range.end = i;

            if ( ! firstAnimation ) firstAnimation = name;

        }

    }

    for ( var name in frameRanges ) {

        var range = frameRanges[ name ];
        this.createAnimation( name, range.start, range.end, fps );

    }

    this.firstAnimation = firstAnimation;

};

THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        animation.direction = 1;
        animation.directionBackwards = false;

    }

};

THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        animation.direction = -1;
        animation.directionBackwards = true;

    }

};

THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        animation.fps = fps;
        animation.duration = ( animation.end - animation.start ) / animation.fps;

    }

};

THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        animation.duration = duration;
        animation.fps = ( animation.end - animation.start ) / animation.duration;

    }

};

THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        animation.weight = weight;

    }

};

THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        animation.time = time;

    }

};

THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {

    var time = 0;

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        time = animation.time;

    }

    return time;

};

THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {

    var duration = -1;

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        duration = animation.duration;

    }

    return duration;

};

THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        animation.time = 0;
        animation.active = true;

    } else {

        console.warn( "animation[" + name + "] undefined" );

    }

};

THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {

    var animation = this.animationsMap[ name ];

    if ( animation ) {

        animation.active = false;

    }

};

THREE.MorphBlendMesh.prototype.update = function ( delta ) {

    for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {

        var animation = this.animationsList[ i ];

        if ( ! animation.active ) continue;

        var frameTime = animation.duration / animation.length;

        animation.time += animation.direction * delta;

        if ( animation.mirroredLoop ) {

            if ( animation.time > animation.duration || animation.time < 0 ) {

                animation.direction *= -1;

                if ( animation.time > animation.duration ) {

                    animation.time = animation.duration;
                    animation.directionBackwards = true;

                }

                if ( animation.time < 0 ) {

                    animation.time = 0;
                    animation.directionBackwards = false;

                }

            }

        } else {

            animation.time = animation.time % animation.duration;

            if ( animation.time < 0 ) animation.time += animation.duration;

        }

        var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
        var weight = animation.weight;

        if ( keyframe !== animation.currentFrame ) {

            this.morphTargetInfluences[ animation.lastFrame ] = 0;
            this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;

            this.morphTargetInfluences[ keyframe ] = 0;

            animation.lastFrame = animation.currentFrame;
            animation.currentFrame = keyframe;

        }

        var mix = ( animation.time % frameTime ) / frameTime;

        if ( animation.directionBackwards ) mix = 1 - mix;

        this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
        this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;

    }

};
/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.LensFlarePlugin = function ( ) {

    var _gl, _renderer, _lensFlare = {};

    this.init = function ( renderer ) {

        _gl = renderer.context;
        _renderer = renderer;

        _lensFlare.vertices = new Float32Array( 8 + 8 );
        _lensFlare.faces = new Uint16Array( 6 );

        var i = 0;
        _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1;    // vertex
        _lensFlare.vertices[ i++ ] = 0;  _lensFlare.vertices[ i++ ] = 0;    // uv... etc.

        _lensFlare.vertices[ i++ ] = 1;  _lensFlare.vertices[ i++ ] = -1;
        _lensFlare.vertices[ i++ ] = 1;  _lensFlare.vertices[ i++ ] = 0;

        _lensFlare.vertices[ i++ ] = 1;  _lensFlare.vertices[ i++ ] = 1;
        _lensFlare.vertices[ i++ ] = 1;  _lensFlare.vertices[ i++ ] = 1;

        _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
        _lensFlare.vertices[ i++ ] = 0;  _lensFlare.vertices[ i++ ] = 1;

        i = 0;
        _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
        _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;

        // buffers

        _lensFlare.vertexBuffer     = _gl.createBuffer();
        _lensFlare.elementBuffer    = _gl.createBuffer();

        _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
        _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );

        _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
        _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );

        // textures

        _lensFlare.tempTexture      = _gl.createTexture();
        _lensFlare.occlusionTexture = _gl.createTexture();

        _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
        _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
        _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
        _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
        _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
        _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );

        _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
        _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
        _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
        _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
        _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
        _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );

        if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {

            _lensFlare.hasVertexTexture = false;
            _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );

        } else {

            _lensFlare.hasVertexTexture = true;
            _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );

        }

        _lensFlare.attributes = {};
        _lensFlare.uniforms = {};

        _lensFlare.attributes.vertex       = _gl.getAttribLocation ( _lensFlare.program, "position" );
        _lensFlare.attributes.uv           = _gl.getAttribLocation ( _lensFlare.program, "uv" );

        _lensFlare.uniforms.renderType     = _gl.getUniformLocation( _lensFlare.program, "renderType" );
        _lensFlare.uniforms.map            = _gl.getUniformLocation( _lensFlare.program, "map" );
        _lensFlare.uniforms.occlusionMap   = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
        _lensFlare.uniforms.opacity        = _gl.getUniformLocation( _lensFlare.program, "opacity" );
        _lensFlare.uniforms.color          = _gl.getUniformLocation( _lensFlare.program, "color" );
        _lensFlare.uniforms.scale          = _gl.getUniformLocation( _lensFlare.program, "scale" );
        _lensFlare.uniforms.rotation       = _gl.getUniformLocation( _lensFlare.program, "rotation" );
        _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );

        _lensFlare.attributesEnabled = false;

    };


    /*
     * Render lens flares
     * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
     *         reads these back and calculates occlusion.
     *         Then _lensFlare.update_lensFlares() is called to re-position and
     *         update transparency of flares. Then they are rendered.
     *
     */

    this.render = function ( scene, camera, viewportWidth, viewportHeight ) {

        var flares = scene.__webglFlares,
            nFlares = flares.length;

        if ( ! nFlares ) return;

        var tempPosition = new THREE.Vector3();

        var invAspect = viewportHeight / viewportWidth,
            halfViewportWidth = viewportWidth * 0.5,
            halfViewportHeight = viewportHeight * 0.5;

        var size = 16 / viewportHeight,
            scale = new THREE.Vector2( size * invAspect, size );

        var screenPosition = new THREE.Vector3( 1, 1, 0 ),
            screenPositionPixels = new THREE.Vector2( 1, 1 );

        var uniforms = _lensFlare.uniforms,
            attributes = _lensFlare.attributes;

        // set _lensFlare program and reset blending

        _gl.useProgram( _lensFlare.program );

        if ( ! _lensFlare.attributesEnabled ) {

            _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
            _gl.enableVertexAttribArray( _lensFlare.attributes.uv );

            _lensFlare.attributesEnabled = true;

        }

        // loop through all lens flares to update their occlusion and positions
        // setup gl and common used attribs/unforms

        _gl.uniform1i( uniforms.occlusionMap, 0 );
        _gl.uniform1i( uniforms.map, 1 );

        _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
        _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
        _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );

        _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );

        _gl.disable( _gl.CULL_FACE );
        _gl.depthMask( false );

        var i, j, jl, flare, sprite;

        for ( i = 0; i < nFlares; i ++ ) {

            size = 16 / viewportHeight;
            scale.set( size * invAspect, size );

            // calc object screen position

            flare = flares[ i ];

            tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );

            camera.matrixWorldInverse.multiplyVector3( tempPosition );
            camera.projectionMatrix.multiplyVector3( tempPosition );

            // setup arrays for gl programs

            screenPosition.copy( tempPosition )

            screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
            screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;

            // screen cull

            if ( _lensFlare.hasVertexTexture || (
                screenPositionPixels.x > 0 &&
                screenPositionPixels.x < viewportWidth &&
                screenPositionPixels.y > 0 &&
                screenPositionPixels.y < viewportHeight ) ) {

                // save current RGB to temp texture

                _gl.activeTexture( _gl.TEXTURE1 );
                _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
                _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );


                // render pink quad

                _gl.uniform1i( uniforms.renderType, 0 );
                _gl.uniform2f( uniforms.scale, scale.x, scale.y );
                _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );

                _gl.disable( _gl.BLEND );
                _gl.enable( _gl.DEPTH_TEST );

                _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );


                // copy result to occlusionMap

                _gl.activeTexture( _gl.TEXTURE0 );
                _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
                _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );


                // restore graphics

                _gl.uniform1i( uniforms.renderType, 1 );
                _gl.disable( _gl.DEPTH_TEST );

                _gl.activeTexture( _gl.TEXTURE1 );
                _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
                _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );


                // update object positions

                flare.positionScreen.copy( screenPosition )

                if ( flare.customUpdateCallback ) {

                    flare.customUpdateCallback( flare );

                } else {

                    flare.updateLensFlares();

                }

                // render flares

                _gl.uniform1i( uniforms.renderType, 2 );
                _gl.enable( _gl.BLEND );

                for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {

                    sprite = flare.lensFlares[ j ];

                    if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {

                        screenPosition.x = sprite.x;
                        screenPosition.y = sprite.y;
                        screenPosition.z = sprite.z;

                        size = sprite.size * sprite.scale / viewportHeight;

                        scale.x = size * invAspect;
                        scale.y = size;

                        _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
                        _gl.uniform2f( uniforms.scale, scale.x, scale.y );
                        _gl.uniform1f( uniforms.rotation, sprite.rotation );

                        _gl.uniform1f( uniforms.opacity, sprite.opacity );
                        _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );

                        _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
                        _renderer.setTexture( sprite.texture, 1 );

                        _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );

                    }

                }

            }

        }

        // restore gl

        _gl.enable( _gl.CULL_FACE );
        _gl.enable( _gl.DEPTH_TEST );
        _gl.depthMask( true );

    };

    function createProgram ( shader ) {

        var program = _gl.createProgram();

        var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
        var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );

        _gl.shaderSource( fragmentShader, shader.fragmentShader );
        _gl.shaderSource( vertexShader, shader.vertexShader );

        _gl.compileShader( fragmentShader );
        _gl.compileShader( vertexShader );

        _gl.attachShader( program, fragmentShader );
        _gl.attachShader( program, vertexShader );

        _gl.linkProgram( program );

        return program;

    };

};/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.ShadowMapPlugin = function ( ) {

    var _gl,
    _renderer,
    _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,

    _frustum = new THREE.Frustum(),
    _projScreenMatrix = new THREE.Matrix4(),

    _min = new THREE.Vector3(),
    _max = new THREE.Vector3();

    this.init = function ( renderer ) {

        _gl = renderer.context;
        _renderer = renderer;

        var depthShader = THREE.ShaderLib[ "depthRGBA" ];
        var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );

        _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
        _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
        _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
        _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );

        _depthMaterial._shadowPass = true;
        _depthMaterialMorph._shadowPass = true;
        _depthMaterialSkin._shadowPass = true;
        _depthMaterialMorphSkin._shadowPass = true;

    };

    this.render = function ( scene, camera ) {

        if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;

        this.update( scene, camera );

    };

    this.update = function ( scene, camera ) {

        var i, il, j, jl, n,

        shadowMap, shadowMatrix, shadowCamera,
        program, buffer, material,
        webglObject, object, light,
        renderList,

        lights = [],
        k = 0,

        fog = null;

        // set GL state for depth map

        _gl.clearColor( 1, 1, 1, 1 );
        _gl.disable( _gl.BLEND );

        _gl.enable( _gl.CULL_FACE );
        _gl.frontFace( _gl.CCW );

        if ( _renderer.shadowMapCullFrontFaces ) {

            _gl.cullFace( _gl.FRONT );

        } else {

            _gl.cullFace( _gl.BACK );

        }

        _renderer.setDepthTest( true );

        // preprocess lights
        //     - skip lights that are not casting shadows
        //    - create virtual lights for cascaded shadow maps

        for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {

            light = scene.__lights[ i ];

            if ( ! light.castShadow ) continue;

            if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {

                for ( n = 0; n < light.shadowCascadeCount; n ++ ) {

                    var virtualLight;

                    if ( ! light.shadowCascadeArray[ n ] ) {

                        virtualLight = createVirtualLight( light, n );
                        virtualLight.originalCamera = camera;

                        var gyro = new THREE.Gyroscope();
                        gyro.position = light.shadowCascadeOffset;

                        gyro.add( virtualLight );
                        gyro.add( virtualLight.target );

                        camera.add( gyro );

                        light.shadowCascadeArray[ n ] = virtualLight;

                        console.log( "Created virtualLight", virtualLight );

                    } else {

                        virtualLight = light.shadowCascadeArray[ n ];

                    }

                    updateVirtualLight( light, n );

                    lights[ k ] = virtualLight;
                    k ++;

                }

            } else {

                lights[ k ] = light;
                k ++;

            }

        }

        // render depth map

        for ( i = 0, il = lights.length; i < il; i ++ ) {

            light = lights[ i ];

            if ( ! light.shadowMap ) {

                var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };

                light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
                light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );

                light.shadowMatrix = new THREE.Matrix4();

            }

            if ( ! light.shadowCamera ) {

                if ( light instanceof THREE.SpotLight ) {

                    light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );

                } else if ( light instanceof THREE.DirectionalLight ) {

                    light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );

                } else {

                    console.error( "Unsupported light type for shadow" );
                    continue;

                }

                scene.add( light.shadowCamera );

                if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();

            }

            if ( light.shadowCameraVisible && ! light.cameraHelper ) {

                light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
                light.shadowCamera.add( light.cameraHelper );

            }

            if ( light.isVirtual && virtualLight.originalCamera == camera ) {

                updateShadowCamera( camera, light );

            }

            shadowMap = light.shadowMap;
            shadowMatrix = light.shadowMatrix;
            shadowCamera = light.shadowCamera;

            shadowCamera.position.copy( light.matrixWorld.getPosition() );
            shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
            shadowCamera.updateMatrixWorld();

            shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );

            if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
            if ( light.shadowCameraVisible ) light.cameraHelper.update();

            // compute shadow matrix

            shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
                              0.0, 0.5, 0.0, 0.5,
                              0.0, 0.0, 0.5, 0.5,
                              0.0, 0.0, 0.0, 1.0 );

            shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
            shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );

            // update camera matrices and frustum

            if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
            if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );

            shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
            shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );

            _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
            _frustum.setFromMatrix( _projScreenMatrix );

            // render shadow map

            _renderer.setRenderTarget( shadowMap );
            _renderer.clear();

            // set object matrices & frustum culling

            renderList = scene.__webglObjects;

            for ( j = 0, jl = renderList.length; j < jl; j ++ ) {

                webglObject = renderList[ j ];
                object = webglObject.object;

                webglObject.render = false;

                if ( object.visible && object.castShadow ) {

                    if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {

                        object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );

                        webglObject.render = true;

                    }

                }

            }

            // render regular objects

            for ( j = 0, jl = renderList.length; j < jl; j ++ ) {

                webglObject = renderList[ j ];

                if ( webglObject.render ) {

                    object = webglObject.object;
                    buffer = webglObject.buffer;

                    // culling is overriden globally for all objects
                    // while rendering depth map

                    if ( object.customDepthMaterial ) {

                        material = object.customDepthMaterial;

                    } else if ( object instanceof THREE.SkinnedMesh ) {

                        material = object.geometry.morphTargets.length ? _depthMaterialMorphSkin : _depthMaterialSkin;

                    } else if ( object.geometry.morphTargets.length ) {

                        material = _depthMaterialMorph;

                    } else {

                        material = _depthMaterial;

                    }

                    if ( buffer instanceof THREE.BufferGeometry ) {

                        _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );

                    } else {

                        _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );

                    }

                }

            }

            // set matrices and render immediate objects

            renderList = scene.__webglObjectsImmediate;

            for ( j = 0, jl = renderList.length; j < jl; j ++ ) {

                webglObject = renderList[ j ];
                object = webglObject.object;

                if ( object.visible && object.castShadow ) {

                    object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );

                    _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );

                }

            }

        }

        // restore GL state

        var clearColor = _renderer.getClearColor(),
        clearAlpha = _renderer.getClearAlpha();

        _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
        _gl.enable( _gl.BLEND );

        if ( _renderer.shadowMapCullFrontFaces ) {

            _gl.cullFace( _gl.BACK );

        }

    };

    function createVirtualLight( light, cascade ) {

        var virtualLight = new THREE.DirectionalLight();

        virtualLight.isVirtual = true;

        virtualLight.onlyShadow = true;
        virtualLight.castShadow = true;

        virtualLight.shadowCameraNear = light.shadowCameraNear;
        virtualLight.shadowCameraFar = light.shadowCameraFar;

        virtualLight.shadowCameraLeft = light.shadowCameraLeft;
        virtualLight.shadowCameraRight = light.shadowCameraRight;
        virtualLight.shadowCameraBottom = light.shadowCameraBottom;
        virtualLight.shadowCameraTop = light.shadowCameraTop;

        virtualLight.shadowCameraVisible = light.shadowCameraVisible;

        virtualLight.shadowDarkness = light.shadowDarkness;

        virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
        virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
        virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];

        virtualLight.pointsWorld = [];
        virtualLight.pointsFrustum = [];

        var pointsWorld = virtualLight.pointsWorld,
            pointsFrustum = virtualLight.pointsFrustum;

        for ( var i = 0; i < 8; i ++ ) {

            pointsWorld[ i ] = new THREE.Vector3();
            pointsFrustum[ i ] = new THREE.Vector3();

        }

        var nearZ = light.shadowCascadeNearZ[ cascade ];
        var farZ = light.shadowCascadeFarZ[ cascade ];

        pointsFrustum[ 0 ].set( -1, -1, nearZ );
        pointsFrustum[ 1 ].set(  1, -1, nearZ );
        pointsFrustum[ 2 ].set( -1,  1, nearZ );
        pointsFrustum[ 3 ].set(  1,  1, nearZ );

        pointsFrustum[ 4 ].set( -1, -1, farZ );
        pointsFrustum[ 5 ].set(  1, -1, farZ );
        pointsFrustum[ 6 ].set( -1,  1, farZ );
        pointsFrustum[ 7 ].set(  1,  1, farZ );

        return virtualLight;

    }

    // Synchronize virtual light with the original light

    function updateVirtualLight( light, cascade ) {

        var virtualLight = light.shadowCascadeArray[ cascade ];

        virtualLight.position.copy( light.position );
        virtualLight.target.position.copy( light.target.position );
        virtualLight.lookAt( virtualLight.target );

        virtualLight.shadowCameraVisible = light.shadowCameraVisible;
        virtualLight.shadowDarkness = light.shadowDarkness;

        virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];

        var nearZ = light.shadowCascadeNearZ[ cascade ];
        var farZ = light.shadowCascadeFarZ[ cascade ];

        var pointsFrustum = virtualLight.pointsFrustum;

        pointsFrustum[ 0 ].z = nearZ;
        pointsFrustum[ 1 ].z = nearZ;
        pointsFrustum[ 2 ].z = nearZ;
        pointsFrustum[ 3 ].z = nearZ;

        pointsFrustum[ 4 ].z = farZ;
        pointsFrustum[ 5 ].z = farZ;
        pointsFrustum[ 6 ].z = farZ;
        pointsFrustum[ 7 ].z = farZ;

    }

    // Fit shadow camera's ortho frustum to camera frustum

    function updateShadowCamera( camera, light ) {

        var shadowCamera = light.shadowCamera,
            pointsFrustum = light.pointsFrustum,
            pointsWorld = light.pointsWorld;

        _min.set( Infinity, Infinity, Infinity );
        _max.set( -Infinity, -Infinity, -Infinity );

        for ( var i = 0; i < 8; i ++ ) {

            var p = pointsWorld[ i ];

            p.copy( pointsFrustum[ i ] );
            THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );

            shadowCamera.matrixWorldInverse.multiplyVector3( p );

            if ( p.x < _min.x ) _min.x = p.x;
            if ( p.x > _max.x ) _max.x = p.x;

            if ( p.y < _min.y ) _min.y = p.y;
            if ( p.y > _max.y ) _max.y = p.y;

            if ( p.z < _min.z ) _min.z = p.z;
            if ( p.z > _max.z ) _max.z = p.z;

        }

        shadowCamera.left = _min.x;
        shadowCamera.right = _max.x;
        shadowCamera.top = _max.y;
        shadowCamera.bottom = _min.y;

        // can't really fit near/far
        //shadowCamera.near = _min.z;
        //shadowCamera.far = _max.z;

        shadowCamera.updateProjectionMatrix();

    }

};

THREE.ShadowMapPlugin.__projector = new THREE.Projector();
/**
 * @author mikael emtinger / http://gomo.se/
 * @author alteredq / http://alteredqualia.com/
 */

THREE.SpritePlugin = function ( ) {

    var _gl, _renderer, _sprite = {};

    this.init = function ( renderer ) {

        _gl = renderer.context;
        _renderer = renderer;

        _sprite.vertices = new Float32Array( 8 + 8 );
        _sprite.faces    = new Uint16Array( 6 );

        var i = 0;

        _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1;    // vertex 0
        _sprite.vertices[ i++ ] = 0;  _sprite.vertices[ i++ ] = 0;    // uv 0

        _sprite.vertices[ i++ ] = 1;  _sprite.vertices[ i++ ] = -1;    // vertex 1
        _sprite.vertices[ i++ ] = 1;  _sprite.vertices[ i++ ] = 0;    // uv 1

        _sprite.vertices[ i++ ] = 1;  _sprite.vertices[ i++ ] = 1;    // vertex 2
        _sprite.vertices[ i++ ] = 1;  _sprite.vertices[ i++ ] = 1;    // uv 2

        _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1;    // vertex 3
        _sprite.vertices[ i++ ] = 0;  _sprite.vertices[ i++ ] = 1;    // uv 3

        i = 0;

        _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
        _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;

        _sprite.vertexBuffer  = _gl.createBuffer();
        _sprite.elementBuffer = _gl.createBuffer();

        _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
        _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );

        _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
        _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );

        _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );

        _sprite.attributes = {};
        _sprite.uniforms = {};

        _sprite.attributes.position           = _gl.getAttribLocation ( _sprite.program, "position" );
        _sprite.attributes.uv                 = _gl.getAttribLocation ( _sprite.program, "uv" );

        _sprite.uniforms.uvOffset             = _gl.getUniformLocation( _sprite.program, "uvOffset" );
        _sprite.uniforms.uvScale              = _gl.getUniformLocation( _sprite.program, "uvScale" );

        _sprite.uniforms.rotation             = _gl.getUniformLocation( _sprite.program, "rotation" );
        _sprite.uniforms.scale                = _gl.getUniformLocation( _sprite.program, "scale" );
        _sprite.uniforms.alignment            = _gl.getUniformLocation( _sprite.program, "alignment" );

        _sprite.uniforms.color                = _gl.getUniformLocation( _sprite.program, "color" );
        _sprite.uniforms.map                  = _gl.getUniformLocation( _sprite.program, "map" );
        _sprite.uniforms.opacity              = _gl.getUniformLocation( _sprite.program, "opacity" );

        _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
        _sprite.uniforms.affectedByDistance   = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
        _sprite.uniforms.screenPosition          = _gl.getUniformLocation( _sprite.program, "screenPosition" );
        _sprite.uniforms.modelViewMatrix      = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
        _sprite.uniforms.projectionMatrix     = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );

        _sprite.attributesEnabled = false;

    };

    this.render = function ( scene, camera, viewportWidth, viewportHeight ) {

        var sprites = scene.__webglSprites,
            nSprites = sprites.length;

        if ( ! nSprites ) return;

        var attributes = _sprite.attributes,
            uniforms = _sprite.uniforms;

        var invAspect = viewportHeight / viewportWidth;

        var halfViewportWidth = viewportWidth * 0.5,
            halfViewportHeight = viewportHeight * 0.5;

        var mergeWith3D = true;

        // setup gl

        _gl.useProgram( _sprite.program );

        if ( ! _sprite.attributesEnabled ) {

            _gl.enableVertexAttribArray( attributes.position );
            _gl.enableVertexAttribArray( attributes.uv );

            _sprite.attributesEnabled = true;

        }

        _gl.disable( _gl.CULL_FACE );
        _gl.enable( _gl.BLEND );
        _gl.depthMask( true );

        _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
        _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
        _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );

        _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );

        _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );

        _gl.activeTexture( _gl.TEXTURE0 );
        _gl.uniform1i( uniforms.map, 0 );

        // update positions and sort

        var i, sprite, screenPosition, size, scale = [];

        for( i = 0; i < nSprites; i ++ ) {

            sprite = sprites[ i ];

            if ( ! sprite.visible || sprite.opacity === 0 ) continue;

            if( ! sprite.useScreenCoordinates ) {

                sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
                sprite.z = - sprite._modelViewMatrix.elements[14];

            } else {

                sprite.z = - sprite.position.z;

            }

        }

        sprites.sort( painterSort );

        // render all sprites

        for( i = 0; i < nSprites; i ++ ) {

            sprite = sprites[ i ];

            if ( ! sprite.visible || sprite.opacity === 0 ) continue;

            if ( sprite.map && sprite.map.image && sprite.map.image.width ) {

                if ( sprite.useScreenCoordinates ) {

                    _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
                    _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth  ) / halfViewportWidth,
                                                            ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
                                                              Math.max( 0, Math.min( 1, sprite.position.z ) ) );

                } else {

                    _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
                    _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
                    _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );

                }

                size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );

                scale[ 0 ] = size * invAspect * sprite.scale.x;
                scale[ 1 ] = size * sprite.scale.y;

                _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
                _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
                _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );

                _gl.uniform1f( uniforms.opacity, sprite.opacity );
                _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );

                _gl.uniform1f( uniforms.rotation, sprite.rotation );
                _gl.uniform2fv( uniforms.scale, scale );

                if ( sprite.mergeWith3D && !mergeWith3D ) {

                    _gl.enable( _gl.DEPTH_TEST );
                    mergeWith3D = true;

                } else if ( ! sprite.mergeWith3D && mergeWith3D ) {

                    _gl.disable( _gl.DEPTH_TEST );
                    mergeWith3D = false;

                }

                _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
                _renderer.setTexture( sprite.map, 0 );

                _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );

            }

        }

        // restore gl

        _gl.enable( _gl.CULL_FACE );
        _gl.enable( _gl.DEPTH_TEST );
        _gl.depthMask( true );

    };

    function createProgram ( shader ) {

        var program = _gl.createProgram();

        var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
        var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );

        _gl.shaderSource( fragmentShader, shader.fragmentShader );
        _gl.shaderSource( vertexShader, shader.vertexShader );

        _gl.compileShader( fragmentShader );
        _gl.compileShader( vertexShader );

        _gl.attachShader( program, fragmentShader );
        _gl.attachShader( program, vertexShader );

        _gl.linkProgram( program );

        return program;

    };

    function painterSort ( a, b ) {

        return b.z - a.z;

    };

};/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.DepthPassPlugin = function ( ) {

    this.enabled = false;
    this.renderTarget = null;

    var _gl,
    _renderer,
    _depthMaterial, _depthMaterialMorph,

    _frustum = new THREE.Frustum(),
    _projScreenMatrix = new THREE.Matrix4();

    this.init = function ( renderer ) {

        _gl = renderer.context;
        _renderer = renderer;

        var depthShader = THREE.ShaderLib[ "depthRGBA" ];
        var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );

        _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
        _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );

        _depthMaterial._shadowPass = true;
        _depthMaterialMorph._shadowPass = true;

    };

    this.render = function ( scene, camera ) {

        if ( ! this.enabled ) return;

        this.update( scene, camera );

    };

    this.update = function ( scene, camera ) {

        var i, il, j, jl, n,

        program, buffer, material,
        webglObject, object, light,
        renderList,

        fog = null;

        // set GL state for depth map

        _gl.clearColor( 1, 1, 1, 1 );
        _gl.disable( _gl.BLEND );

        _renderer.setDepthTest( true );

        // update scene

        if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();

        // update camera matrices and frustum

        if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
        if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );

        camera.matrixWorldInverse.getInverse( camera.matrixWorld );

        camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
        camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );

        _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
        _frustum.setFromMatrix( _projScreenMatrix );

        // render depth map

        _renderer.setRenderTarget( this.renderTarget );
        _renderer.clear();

        // set object matrices & frustum culling

        renderList = scene.__webglObjects;

        for ( j = 0, jl = renderList.length; j < jl; j ++ ) {

            webglObject = renderList[ j ];
            object = webglObject.object;

            webglObject.render = false;

            if ( object.visible ) {

                if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {

                    //object.matrixWorld.flattenToArray( object._modelMatrixArray );
                    object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);

                    webglObject.render = true;

                }

            }

        }

        // render regular objects

        for ( j = 0, jl = renderList.length; j < jl; j ++ ) {

            webglObject = renderList[ j ];

            if ( webglObject.render ) {

                object = webglObject.object;
                buffer = webglObject.buffer;

                if ( object.material ) _renderer.setMaterialFaces( object.material );

                if ( object.customDepthMaterial ) {

                    material = object.customDepthMaterial;

                } else if ( object.geometry.morphTargets.length ) {

                    material = _depthMaterialMorph;

                } else {

                    material = _depthMaterial;

                }

                if ( buffer instanceof THREE.BufferGeometry ) {

                    _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );

                } else {

                    _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );

                }

            }

        }

        // set matrices and render immediate objects

        renderList = scene.__webglObjectsImmediate;

        for ( j = 0, jl = renderList.length; j < jl; j ++ ) {

            webglObject = renderList[ j ];
            object = webglObject.object;

            if ( object.visible && object.castShadow ) {

                /*
                if ( object.matrixAutoUpdate ) {

                    object.matrixWorld.flattenToArray( object._modelMatrixArray );

                }
                */

                object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);

                _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );

            }

        }

        // restore GL state

        var clearColor = _renderer.getClearColor(),
        clearAlpha = _renderer.getClearAlpha();

        _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
        _gl.enable( _gl.BLEND );

    };

};

/**
 * @author mikael emtinger / http://gomo.se/
 *
 */

THREE.ShaderFlares = {

    'lensFlareVertexTexture': {

        vertexShader: [

            "uniform vec3 screenPosition;",
            "uniform vec2 scale;",
            "uniform float rotation;",
            "uniform int renderType;",

            "uniform sampler2D occlusionMap;",

            "attribute vec2 position;",
            "attribute vec2 uv;",

            "varying vec2 vUV;",
            "varying float vVisibility;",

            "void main() {",

                "vUV = uv;",

                "vec2 pos = position;",

                "if( renderType == 2 ) {",

                    "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
                                      "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
                                      "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
                                      "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
                                      "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
                                      "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
                                      "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
                                      "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
                                      "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",

                    "vVisibility = (       visibility.r / 9.0 ) *",
                                  "( 1.0 - visibility.g / 9.0 ) *",
                                  "(       visibility.b / 9.0 ) *",
                                  "( 1.0 - visibility.a / 9.0 );",

                    "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
                    "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",

                "}",

                "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",

            "}"

        ].join( "\n" ),

        fragmentShader: [

            "precision mediump float;",

            "uniform sampler2D map;",
            "uniform float opacity;",
            "uniform int renderType;",
            "uniform vec3 color;",

            "varying vec2 vUV;",
            "varying float vVisibility;",

            "void main() {",

                // pink square

                "if( renderType == 0 ) {",

                    "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",

                // restore

                "} else if( renderType == 1 ) {",

                    "gl_FragColor = texture2D( map, vUV );",

                // flare

                "} else {",

                    "vec4 texture = texture2D( map, vUV );",
                    "texture.a *= opacity * vVisibility;",
                    "gl_FragColor = texture;",
                    "gl_FragColor.rgb *= color;",

                "}",

            "}"
        ].join( "\n" )

    },


    'lensFlare': {

        vertexShader: [

            "uniform vec3 screenPosition;",
            "uniform vec2 scale;",
            "uniform float rotation;",
            "uniform int renderType;",

            "attribute vec2 position;",
            "attribute vec2 uv;",

            "varying vec2 vUV;",

            "void main() {",

                "vUV = uv;",

                "vec2 pos = position;",

                "if( renderType == 2 ) {",

                    "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
                    "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",

                "}",

                "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",

            "}"

        ].join( "\n" ),

        fragmentShader: [

            "precision mediump float;",

            "uniform sampler2D map;",
            "uniform sampler2D occlusionMap;",
            "uniform float opacity;",
            "uniform int renderType;",
            "uniform vec3 color;",

            "varying vec2 vUV;",

            "void main() {",

                // pink square

                "if( renderType == 0 ) {",

                    "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",

                // restore

                "} else if( renderType == 1 ) {",

                    "gl_FragColor = texture2D( map, vUV );",

                // flare

                "} else {",

                    "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
                                       "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
                                       "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
                                       "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",

                    "visibility = ( 1.0 - visibility / 4.0 );",

                    "vec4 texture = texture2D( map, vUV );",
                    "texture.a *= opacity * visibility;",
                    "gl_FragColor = texture;",
                    "gl_FragColor.rgb *= color;",

                "}",

            "}"

        ].join( "\n" )

    }

};
/**
 * @author mikael emtinger / http://gomo.se/
 *
 */

THREE.ShaderSprite = {

    'sprite': {

        vertexShader: [

            "uniform int useScreenCoordinates;",
            "uniform int affectedByDistance;",
            "uniform vec3 screenPosition;",
            "uniform mat4 modelViewMatrix;",
            "uniform mat4 projectionMatrix;",
            "uniform float rotation;",
            "uniform vec2 scale;",
            "uniform vec2 alignment;",
            "uniform vec2 uvOffset;",
            "uniform vec2 uvScale;",

            "attribute vec2 position;",
            "attribute vec2 uv;",

            "varying vec2 vUV;",

            "void main() {",

                "vUV = uvOffset + uv * uvScale;",

                "vec2 alignedPosition = position + alignment;",

                "vec2 rotatedPosition;",
                "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
                "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",

                "vec4 finalPosition;",

                "if( useScreenCoordinates != 0 ) {",

                    "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",

                "} else {",

                    "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
                    "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",

                "}",

                "gl_Position = finalPosition;",

            "}"

        ].join( "\n" ),

        fragmentShader: [

            "precision mediump float;",

            "uniform vec3 color;",
            "uniform sampler2D map;",
            "uniform float opacity;",

            "varying vec2 vUV;",

            "void main() {",

                "vec4 texture = texture2D( map, vUV );",
                "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",

            "}"

        ].join( "\n" )

    }

};
/**
 * @author alteredq / http://alteredqualia.com/
 *
 */


THREE.ShaderSkin = {

    /* ------------------------------------------------------------------------------------------
    //    Simple skin shader
    //        - per-pixel Blinn-Phong diffuse term mixed with half-Lambert wrap-around term (per color component)
    //        - physically based specular term (Kelemen/Szirmay-Kalos specular reflectance)
    //
    //        - diffuse map
    //        - bump map
    //        - specular map
    //        - point, directional and hemisphere lights (use with "lights: true" material option)
    //        - fog (use with "fog: true" material option)
    //        - shadow maps
    //
    // ------------------------------------------------------------------------------------------ */

    'skinSimple' : {

        uniforms: THREE.UniformsUtils.merge( [

            THREE.UniformsLib[ "fog" ],
            THREE.UniformsLib[ "lights" ],
            THREE.UniformsLib[ "shadowmap" ],

            {

            "enableBump"    : { type: "i", value: 0 },
            "enableSpecular": { type: "i", value: 0 },

            "tDiffuse"    : { type: "t", value: null },
            "tBeckmann"    : { type: "t", value: null },

            "uDiffuseColor":  { type: "c", value: new THREE.Color( 0xeeeeee ) },
            "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
            "uAmbientColor":  { type: "c", value: new THREE.Color( 0x050505 ) },
            "uOpacity":       { type: "f", value: 1 },

            "uRoughness":               { type: "f", value: 0.15 },
            "uSpecularBrightness":     { type: "f", value: 0.75 },

            "bumpMap"    : { type: "t", value: null },
            "bumpScale" : { type: "f", value: 1 },

            "specularMap" : { type: "t", value: null },

            "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },

            "uWrapRGB":    { type: "v3", value: new THREE.Vector3( 0.75, 0.375, 0.1875 ) }

            }

        ] ),

        fragmentShader: [

            "#define USE_BUMPMAP",
            "#extension GL_OES_standard_derivatives : enable",

            "uniform bool enableBump;",
            "uniform bool enableSpecular;",

            "uniform vec3 uAmbientColor;",
            "uniform vec3 uDiffuseColor;",
            "uniform vec3 uSpecularColor;",
            "uniform float uOpacity;",

            "uniform float uRoughness;",
            "uniform float uSpecularBrightness;",

            "uniform vec3 uWrapRGB;",

            "uniform sampler2D tDiffuse;",
            "uniform sampler2D tBeckmann;",

            "uniform sampler2D specularMap;",

            "varying vec3 vNormal;",
            "varying vec2 vUv;",

            "uniform vec3 ambientLightColor;",

            "#if MAX_DIR_LIGHTS > 0",

                "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
                "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",

            "#endif",

            "#if MAX_HEMI_LIGHTS > 0",

                "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
                "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
                "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",

            "#endif",

            "#if MAX_POINT_LIGHTS > 0",

                "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
                "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
                "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",

            "#endif",

            "varying vec3 vViewPosition;",

            THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
            THREE.ShaderChunk[ "fog_pars_fragment" ],
            THREE.ShaderChunk[ "bumpmap_pars_fragment" ],

            // Fresnel term

            "float fresnelReflectance( vec3 H, vec3 V, float F0 ) {",

                "float base = 1.0 - dot( V, H );",
                "float exponential = pow( base, 5.0 );",

                "return exponential + F0 * ( 1.0 - exponential );",

            "}",

            // Kelemen/Szirmay-Kalos specular BRDF

            "float KS_Skin_Specular( vec3 N,",         // Bumped surface normal
                                    "vec3 L,",         // Points to light
                                    "vec3 V,",         // Points to eye
                                    "float m,",      // Roughness
                                    "float rho_s",     // Specular brightness
                                    ") {",

                "float result = 0.0;",
                "float ndotl = dot( N, L );",

                "if( ndotl > 0.0 ) {",

                    "vec3 h = L + V;", // Unnormalized half-way vector
                    "vec3 H = normalize( h );",

                    "float ndoth = dot( N, H );",

                    "float PH = pow( 2.0 * texture2D( tBeckmann, vec2( ndoth, m ) ).x, 10.0 );",

                    "float F = fresnelReflectance( H, V, 0.028 );",
                    "float frSpec = max( PH * F / dot( h, h ), 0.0 );",

                    "result = ndotl * rho_s * frSpec;", // BRDF * dot(N,L) * rho_s

                "}",

                "return result;",

            "}",

            "void main() {",

                "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",

                "vec4 colDiffuse = texture2D( tDiffuse, vUv );",
                "colDiffuse.rgb *= colDiffuse.rgb;",

                "gl_FragColor = gl_FragColor * colDiffuse;",

                "vec3 normal = normalize( vNormal );",
                "vec3 viewPosition = normalize( vViewPosition );",

                "float specularStrength;",

                "if ( enableSpecular ) {",

                    "vec4 texelSpecular = texture2D( specularMap, vUv );",
                    "specularStrength = texelSpecular.r;",

                "} else {",

                    "specularStrength = 1.0;",

                "}",

                "#ifdef USE_BUMPMAP",

                    "if ( enableBump ) normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",

                "#endif",

                // point lights

                "vec3 specularTotal = vec3( 0.0 );",

                "#if MAX_POINT_LIGHTS > 0",

                    "vec3 pointTotal = vec3( 0.0 );",

                    "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",

                        "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",

                        "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",

                        "float lDistance = 1.0;",

                        "if ( pointLightDistance[ i ] > 0.0 )",
                            "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",

                        "lVector = normalize( lVector );",

                        "float pointDiffuseWeightFull = max( dot( normal, lVector ), 0.0 );",
                        "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, lVector ) + 0.5, 0.0 );",
                        "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), uWrapRGB );",

                        "float pointSpecularWeight = KS_Skin_Specular( normal, lVector, viewPosition, uRoughness, uSpecularBrightness );",

                        "pointTotal    += lDistance * uDiffuseColor * pointLightColor[ i ] * pointDiffuseWeight;",
                        "specularTotal += lDistance * uSpecularColor * pointLightColor[ i ] * pointSpecularWeight * specularStrength;",

                    "}",

                "#endif",

                // directional lights

                "#if MAX_DIR_LIGHTS > 0",

                    "vec3 dirTotal = vec3( 0.0 );",

                    "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",

                        "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",

                        "vec3 dirVector = normalize( lDirection.xyz );",

                        "float dirDiffuseWeightFull = max( dot( normal, dirVector ), 0.0 );",
                        "float dirDiffuseWeightHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
                        "vec3 dirDiffuseWeight = mix( vec3 ( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), uWrapRGB );",

                        "float dirSpecularWeight =  KS_Skin_Specular( normal, dirVector, viewPosition, uRoughness, uSpecularBrightness );",

                        "dirTotal        += uDiffuseColor * directionalLightColor[ i ] * dirDiffuseWeight;",
                        "specularTotal += uSpecularColor * directionalLightColor[ i ] * dirSpecularWeight * specularStrength;",

                    "}",

                "#endif",

                // hemisphere lights

                "#if MAX_HEMI_LIGHTS > 0",

                    "vec3 hemiTotal = vec3( 0.0 );",

                    "for ( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",

                        "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
                        "vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",

                        "float dotProduct = dot( normal, lVector );",
                        "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",

                        "hemiTotal += uDiffuseColor * mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",

                        // specular (sky light)

                        "float hemiSpecularWeight = 0.0;",
                        "hemiSpecularWeight += KS_Skin_Specular( normal, lVector, viewPosition, uRoughness, uSpecularBrightness );",

                        // specular (ground light)

                        "vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",
                        "hemiSpecularWeight += KS_Skin_Specular( normal, lVectorGround, viewPosition, uRoughness, uSpecularBrightness );",

                        "specularTotal += uSpecularColor * mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight ) * hemiSpecularWeight * specularStrength;",

                    "}",

                "#endif",

                // all lights contribution summation

                "vec3 totalLight = vec3( 0.0 );",

                "#if MAX_DIR_LIGHTS > 0",
                    "totalLight += dirTotal;",
                "#endif",

                "#if MAX_POINT_LIGHTS > 0",
                    "totalLight += pointTotal;",
                "#endif",

                "#if MAX_HEMI_LIGHTS > 0",
                    "totalLight += hemiTotal;",
                "#endif",

                "gl_FragColor.xyz = gl_FragColor.xyz * ( totalLight + ambientLightColor * uAmbientColor ) + specularTotal;",

                THREE.ShaderChunk[ "shadowmap_fragment" ],
                THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
                THREE.ShaderChunk[ "fog_fragment" ],

            "}"

        ].join("\n"),

        vertexShader: [

            "uniform vec4 offsetRepeat;",

            "varying vec3 vNormal;",
            "varying vec2 vUv;",

            "varying vec3 vViewPosition;",

            THREE.ShaderChunk[ "shadowmap_pars_vertex" ],

            "void main() {",

                "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
                "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",

                "vViewPosition = -mvPosition.xyz;",

                "vNormal = normalMatrix * normal;",

                "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",

                "gl_Position = projectionMatrix * mvPosition;",

                THREE.ShaderChunk[ "shadowmap_vertex" ],

            "}"

        ].join( "\n" )

    },

    /* ------------------------------------------------------------------------------------------
    //    Skin shader
    //        - Blinn-Phong diffuse term (using normal + diffuse maps)
    //        - subsurface scattering approximation by four blur layers
    //        - physically based specular term (Kelemen/Szirmay-Kalos specular reflectance)
    //
    //        - point and directional lights (use with "lights: true" material option)
    //
    //        - based on Nvidia Advanced Skin Rendering GDC 2007 presentation
    //          and GPU Gems 3 Chapter 14. Advanced Techniques for Realistic Real-Time Skin Rendering
    //
    //            http://developer.download.nvidia.com/presentations/2007/gdc/Advanced_Skin.pdf
    //            http://http.developer.nvidia.com/GPUGems3/gpugems3_ch14.html
    // ------------------------------------------------------------------------------------------ */

    'skin' : {

        uniforms: THREE.UniformsUtils.merge( [

            THREE.UniformsLib[ "fog" ],
            THREE.UniformsLib[ "lights" ],

            {

            "passID": { type: "i", value: 0 },

            "tDiffuse"    : { type: "t", value: null },
            "tNormal"    : { type: "t", value: null },

            "tBlur1"    : { type: "t", value: null },
            "tBlur2"    : { type: "t", value: null },
            "tBlur3"    : { type: "t", value: null },
            "tBlur4"    : { type: "t", value: null },

            "tBeckmann"    : { type: "t", value: null },

            "uNormalScale": { type: "f", value: 1.0 },

            "uDiffuseColor":  { type: "c", value: new THREE.Color( 0xeeeeee ) },
            "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
            "uAmbientColor":  { type: "c", value: new THREE.Color( 0x050505 ) },
            "uOpacity":       { type: "f", value: 1 },

            "uRoughness":               { type: "f", value: 0.15 },
            "uSpecularBrightness":     { type: "f", value: 0.75 }

            }

        ] ),

        fragmentShader: [

            "uniform vec3 uAmbientColor;",
            "uniform vec3 uDiffuseColor;",
            "uniform vec3 uSpecularColor;",
            "uniform float uOpacity;",

            "uniform float uRoughness;",
            "uniform float uSpecularBrightness;",

            "uniform int passID;",

            "uniform sampler2D tDiffuse;",
            "uniform sampler2D tNormal;",

            "uniform sampler2D tBlur1;",
            "uniform sampler2D tBlur2;",
            "uniform sampler2D tBlur3;",
            "uniform sampler2D tBlur4;",

            "uniform sampler2D tBeckmann;",

            "uniform float uNormalScale;",

            "varying vec3 vTangent;",
            "varying vec3 vBinormal;",
            "varying vec3 vNormal;",
            "varying vec2 vUv;",

            "uniform vec3 ambientLightColor;",

            "#if MAX_DIR_LIGHTS > 0",
                "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
                "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
            "#endif",

            "#if MAX_POINT_LIGHTS > 0",
                "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
                "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
            "#endif",

            "varying vec3 vViewPosition;",

            THREE.ShaderChunk[ "fog_pars_fragment" ],

            "float fresnelReflectance( vec3 H, vec3 V, float F0 ) {",

                "float base = 1.0 - dot( V, H );",
                "float exponential = pow( base, 5.0 );",

                "return exponential + F0 * ( 1.0 - exponential );",

            "}",

            // Kelemen/Szirmay-Kalos specular BRDF

            "float KS_Skin_Specular( vec3 N,",         // Bumped surface normal
                                    "vec3 L,",         // Points to light
                                    "vec3 V,",         // Points to eye
                                    "float m,",      // Roughness
                                    "float rho_s",     // Specular brightness
                                    ") {",

                "float result = 0.0;",
                "float ndotl = dot( N, L );",

                "if( ndotl > 0.0 ) {",

                    "vec3 h = L + V;", // Unnormalized half-way vector
                    "vec3 H = normalize( h );",

                    "float ndoth = dot( N, H );",

                    "float PH = pow( 2.0 * texture2D( tBeckmann, vec2( ndoth, m ) ).x, 10.0 );",
                    "float F = fresnelReflectance( H, V, 0.028 );",
                    "float frSpec = max( PH * F / dot( h, h ), 0.0 );",

                    "result = ndotl * rho_s * frSpec;", // BRDF * dot(N,L) * rho_s

                "}",

                "return result;",

            "}",

            "void main() {",

                "gl_FragColor = vec4( 1.0 );",

                "vec4 mColor = vec4( uDiffuseColor, uOpacity );",
                "vec4 mSpecular = vec4( uSpecularColor, uOpacity );",

                "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
                "normalTex.xy *= uNormalScale;",
                "normalTex = normalize( normalTex );",

                "vec4 colDiffuse = texture2D( tDiffuse, vUv );",
                "colDiffuse *= colDiffuse;",

                "gl_FragColor = gl_FragColor * colDiffuse;",

                "mat3 tsb = mat3( vTangent, vBinormal, vNormal );",
                "vec3 finalNormal = tsb * normalTex;",

                "vec3 normal = normalize( finalNormal );",
                "vec3 viewPosition = normalize( vViewPosition );",

                // point lights

                "vec3 specularTotal = vec3( 0.0 );",

                "#if MAX_POINT_LIGHTS > 0",

                    "vec4 pointTotal = vec4( vec3( 0.0 ), 1.0 );",

                    "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",

                        "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
                        "float pointDistance = vPointLight[ i ].w;",

                        "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",

                        "pointTotal  += pointDistance * vec4( pointLightColor[ i ], 1.0 ) * ( mColor * pointDiffuseWeight );",

                        "if ( passID == 1 )",
                            "specularTotal += pointDistance * mSpecular.xyz * pointLightColor[ i ] * KS_Skin_Specular( normal, pointVector, viewPosition, uRoughness, uSpecularBrightness );",

                    "}",

                "#endif",

                // directional lights

                "#if MAX_DIR_LIGHTS > 0",

                    "vec4 dirTotal = vec4( vec3( 0.0 ), 1.0 );",

                    "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",

                        "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",

                        "vec3 dirVector = normalize( lDirection.xyz );",

                        "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",

                        "dirTotal  += vec4( directionalLightColor[ i ], 1.0 ) * ( mColor * dirDiffuseWeight );",

                        "if ( passID == 1 )",
                            "specularTotal += mSpecular.xyz * directionalLightColor[ i ] * KS_Skin_Specular( normal, dirVector, viewPosition, uRoughness, uSpecularBrightness );",

                    "}",

                "#endif",

                // all lights contribution summation

                "vec4 totalLight = vec4( vec3( 0.0 ), uOpacity );",

                "#if MAX_DIR_LIGHTS > 0",
                    "totalLight += dirTotal;",
                "#endif",

                "#if MAX_POINT_LIGHTS > 0",
                    "totalLight += pointTotal;",
                "#endif",

                "gl_FragColor = gl_FragColor * totalLight;",

                "if ( passID == 0 ) {",

                    "gl_FragColor = vec4( sqrt( gl_FragColor.xyz ), gl_FragColor.w );",

                "} else if ( passID == 1 ) {",

                    //"#define VERSION1",

                    "#ifdef VERSION1",

                        "vec3 nonblurColor = sqrt( gl_FragColor.xyz );",

                    "#else",

                        "vec3 nonblurColor = gl_FragColor.xyz;",

                    "#endif",

                    "vec3 blur1Color = texture2D( tBlur1, vUv ).xyz;",
                    "vec3 blur2Color = texture2D( tBlur2, vUv ).xyz;",
                    "vec3 blur3Color = texture2D( tBlur3, vUv ).xyz;",
                    "vec3 blur4Color = texture2D( tBlur4, vUv ).xyz;",


                    //"gl_FragColor = vec4( blur1Color, gl_FragColor.w );",

                    //"gl_FragColor = vec4( vec3( 0.22, 0.5, 0.7 ) * nonblurColor + vec3( 0.2, 0.5, 0.3 ) * blur1Color + vec3( 0.58, 0.0, 0.0 ) * blur2Color, gl_FragColor.w );",

                    //"gl_FragColor = vec4( vec3( 0.25, 0.6, 0.8 ) * nonblurColor + vec3( 0.15, 0.25, 0.2 ) * blur1Color + vec3( 0.15, 0.15, 0.0 ) * blur2Color + vec3( 0.45, 0.0, 0.0 ) * blur3Color, gl_FragColor.w );",


                    "gl_FragColor = vec4( vec3( 0.22,  0.437, 0.635 ) * nonblurColor + ",
                                         "vec3( 0.101, 0.355, 0.365 ) * blur1Color + ",
                                         "vec3( 0.119, 0.208, 0.0 )   * blur2Color + ",
                                         "vec3( 0.114, 0.0,   0.0 )   * blur3Color + ",
                                         "vec3( 0.444, 0.0,   0.0 )   * blur4Color",
                                         ", gl_FragColor.w );",

                    "gl_FragColor.xyz *= pow( colDiffuse.xyz, vec3( 0.5 ) );",

                    "gl_FragColor.xyz += ambientLightColor * uAmbientColor * colDiffuse.xyz + specularTotal;",

                    "#ifndef VERSION1",

                        "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",

                    "#endif",

                "}",

                THREE.ShaderChunk[ "fog_fragment" ],

            "}"

        ].join("\n"),

        vertexShader: [

            "attribute vec4 tangent;",

            "#ifdef VERTEX_TEXTURES",

                "uniform sampler2D tDisplacement;",
                "uniform float uDisplacementScale;",
                "uniform float uDisplacementBias;",

            "#endif",

            "varying vec3 vTangent;",
            "varying vec3 vBinormal;",
            "varying vec3 vNormal;",
            "varying vec2 vUv;",

            "#if MAX_POINT_LIGHTS > 0",

                "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
                "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",

                "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",

            "#endif",

            "varying vec3 vViewPosition;",

            "void main() {",

                "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",

                "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",

                "vViewPosition = -mvPosition.xyz;",

                "vNormal = normalize( normalMatrix * normal );",

                // tangent and binormal vectors

                "vTangent = normalize( normalMatrix * tangent.xyz );",

                "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
                "vBinormal = normalize( vBinormal );",

                "vUv = uv;",

                // point lights

                "#if MAX_POINT_LIGHTS > 0",

                    "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",

                        "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",

                        "vec3 lVector = lPosition.xyz - mvPosition.xyz;",

                        "float lDistance = 1.0;",

                        "if ( pointLightDistance[ i ] > 0.0 )",
                            "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",

                        "lVector = normalize( lVector );",

                        "vPointLight[ i ] = vec4( lVector, lDistance );",

                    "}",

                "#endif",

                // displacement mapping

                "#ifdef VERTEX_TEXTURES",

                    "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
                    "float df = uDisplacementScale * dv.x + uDisplacementBias;",
                    "vec4 displacedPosition = vec4( vNormal.xyz * df, 0.0 ) + mvPosition;",
                    "gl_Position = projectionMatrix * displacedPosition;",

                "#else",

                    "gl_Position = projectionMatrix * mvPosition;",

                "#endif",

            "}"

        ].join("\n"),

        vertexShaderUV: [

            "attribute vec4 tangent;",

            "#ifdef VERTEX_TEXTURES",

                "uniform sampler2D tDisplacement;",
                "uniform float uDisplacementScale;",
                "uniform float uDisplacementBias;",

            "#endif",

            "varying vec3 vTangent;",
            "varying vec3 vBinormal;",
            "varying vec3 vNormal;",
            "varying vec2 vUv;",

            "#if MAX_POINT_LIGHTS > 0",

                "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
                "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",

                "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",

            "#endif",

            "varying vec3 vViewPosition;",

            "void main() {",

                "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",

                "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",

                "vViewPosition = -mvPosition.xyz;",

                "vNormal = normalize( normalMatrix * normal );",

                // tangent and binormal vectors

                "vTangent = normalize( normalMatrix * tangent.xyz );",

                "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
                "vBinormal = normalize( vBinormal );",

                "vUv = uv;",

                // point lights

                "#if MAX_POINT_LIGHTS > 0",

                    "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",

                        "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",

                        "vec3 lVector = lPosition.xyz - mvPosition.xyz;",

                        "float lDistance = 1.0;",

                        "if ( pointLightDistance[ i ] > 0.0 )",
                            "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",

                        "lVector = normalize( lVector );",

                        "vPointLight[ i ] = vec4( lVector, lDistance );",

                    "}",

                "#endif",

                "gl_Position = vec4( uv.x * 2.0 - 1.0, uv.y * 2.0 - 1.0, 0.0, 1.0 );",

            "}"

        ].join("\n")

    },

    /* ------------------------------------------------------------------------------------------
    // Beckmann distribution function
    //    - to be used in specular term of skin shader
    //    - render a screen-aligned quad to precompute a 512 x 512 texture
    //
    //        - from http://developer.nvidia.com/node/171
     ------------------------------------------------------------------------------------------ */

    "beckmann" : {

        uniforms: {},

        vertexShader: [

            "varying vec2 vUv;",

            "void main() {",

                "vUv = uv;",
                "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

            "}"

        ].join("\n"),

        fragmentShader: [

            "varying vec2 vUv;",

            "float PHBeckmann( float ndoth, float m ) {",

                "float alpha = acos( ndoth );",
                "float ta = tan( alpha );",

                "float val = 1.0 / ( m * m * pow( ndoth, 4.0 ) ) * exp( -( ta * ta ) / ( m * m ) );",
                "return val;",

            "}",

            "float KSTextureCompute( vec2 tex ) {",

                // Scale the value to fit within [0,1]  invert upon lookup.

                "return 0.5 * pow( PHBeckmann( tex.x, tex.y ), 0.1 );",

            "}",

            "void main() {",

                "float x = KSTextureCompute( vUv );",

                "gl_FragColor = vec4( x, x, x, 1.0 );",

            "}"

        ].join("\n")

    }

};
//////////////////////////////////////////////////////////////////////////////
//                                                                          //
// Wii Opera SDK - Drawing Class v2.6.16 2008-12-14                         //
// (c) 2007-2008 Daniel Gump. All Rights Reserved.                          //
// http://wiioperasdk.com, http://hullbreachonline.com                      //
// hullbreach@hullbreachonline.com                                          //
//                                                                          //
//  Wii is a trademark of Nintendo Co., Ltd.                                //
//  Opera is a trademark of Opera, ASA.                                     //
//  This software package is not associated with either company             //
//  but was created to support users of both.  Its alternative name         //
//  when supporting other products is the HULLBREACH SDK.                   //
//                                                                          //
//  Redistribution and use in source and binary forms, with or without      //
//  modification, are permitted provided that the following conditions      //
//  are met:                                                                //
//    * Redistributions of source code must retain the above copyright      //
//      notice, this list of conditions and the following disclaimer.       //
//    * Redistributions in binary form must reproduce the above copyright   //
//      notice, this list of conditions and the following disclaimer in     //
//      the documentation and/or other materials provided with the          //
//      distribution.                                                       //
//    * Neither the names HULLBREACH ONLINE nor WII OPERA SDK nor the names //
//      of its contributors may be used to endorse or promote products      //
//      derived from this software without specific prior written           //
//      permission.                                                         //
//    * If the explicit purpose of the software is not to support the       //
//      Nintendo Wii or the Opera Web browser, then the names of such must  //
//      not be used in any derived product. The name shall be the           //
//      HULLBREACH SDK with a reference link to http://hullbreachonline.    //
//                                                                          //
//  THIS SOFTWARE IS PROVIDED BY Daniel Gump ''AS IS'' AND ANY EXPRESS OR   //
//  IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED          //
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE  //
//  DISCLAIMED. IN NO EVENT SHALL Daniel Gump BE LIABLE FOR ANY DIRECT,     //
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES      //
//  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR      //
//  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)      //
//  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,     //
//  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING   //
//  IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE      //
//  POSSIBILITY OF SUCH DAMAGE.                                             //
//////////////////////////////////////////////////////////////////////////////

function Drawing(){
	this.WIREFRAME = 1; this.FILL = 2;
	ZOOM = 1;
	CANVAS = null;
	TEXTURES = null;
}
Drawing.prototype.initialize = function(canvas){
	CANVAS = canvas.getContext("2d");
	CANVAS.lineJoin = "round";
	CANVAS.lineWidth = 1;
}
Drawing.prototype.loadTextures = function(textures){ TEXTURES = textures; }
Drawing.prototype.setFillColor = function(r,g,b){ CANVAS.fillStyle = "rgb("+(r>255?255:(r<0?0:r|0))+", "+(g>255?255:(g<0?0:g|0))+", "+(b>255?255:(b<0?0:b|0))+")"; }
Drawing.prototype.setFillColorA = function(r,g,b,a){ CANVAS.fillStyle = "rgba("+(r>255?255:(r<0?0:r|0))+", "+(g>255?255:(g<0?0:g|0))+", "+(b>255?255:(b<0?0:b|0))+", "+(a>255?1:(a<0?0:a/255))+")"; }
Drawing.prototype.setLineColor = function(r,g,b){ CANVAS.strokeStyle = "rgb("+(r>255?255:(r<0?0:r|0))+", "+(g>255?255:(g<0?0:g|0))+", "+(b>255?255:(b<0?0:b|0))+")"; }
Drawing.prototype.setLineColorA = function(r,g,b,a){ CANVAS.strokeStyle = "rgba("+(r>255?255:(r<0?0:r|0))+", "+(g>255?255:(g<0?0:g|0))+", "+(b>255?255:(b<0?0:b|0))+", "+(a>255?1:(a<0?0:a/255))+")"; }
Drawing.prototype.clipCircle = function(centerx,centery,radius){ CANVAS.beginPath(); CANVAS.arc(centerx,centery,radius,0,6.28318531,false); CANVAS.clip(); }
Drawing.prototype.clipRectangle = function(x1,y1,x2,y2){ CANVAS.beginPath(); CANVAS.strokeRect(x1,y1,x2-x1,y2-y1); CANVAS.clip(); }
Drawing.prototype.drawCircle = function(centerx,centery,radius,style){
	CANVAS.beginPath();
	CANVAS.arc(centerx, centery, radius, 0, Math.PI*2, false);
	if(style & this.FILL) CANVAS.fill();
	if(style & this.WIREFRAME) CANVAS.stroke();
}
Drawing.prototype.drawImage = function(x1,y1,x2,y2,img,angle){
	if(img.complete){
		x1|=0;
		y1|=0;
		x2|=0;
		y2|=0;
		if(x2<x1) x2=x1+1;
		if(y2<y1) y2=y1+1;
		var centerx = (x1+x2)>>1;
		var centery = (y1+y2)>>1;

		CANVAS.save();
		CANVAS.translate(centerx, centery);
		if(angle) CANVAS.rotate(angle*0.01745329);
		CANVAS.drawImage(img, x1-centerx, y1-centery, x2-x1, y2-y1);
		CANVAS.restore();
	}
}
Drawing.prototype.drawLine = function(x1, y1, x2, y2){ CANVAS.beginPath(); CANVAS.moveTo(x1|0, y1|0); CANVAS.lineTo(x2|0, y2|0); CANVAS.stroke(); }
Drawing.prototype.drawRectangle = function(x1, y1, x2, y2, style, angle){
	x1|=0;
	y1|=0;
	x2|=0;
	y2|=0;
	
	if(!angle){
		if(style & this.FILL) CANVAS.fillRect(x1, y1, x2-x1, y2-y1);
		if(style & this.WIREFRAME) CANVAS.strokeRect(x1, y1, x2-x1, y2-y1);
	}else{
		var centerx = (x1+x2)>>1; var centery = (y1+y2)>>1;

		CANVAS.save();
		CANVAS.translate(centerx, centery);
		CANVAS.rotate(angle*DEGTORAD);
		if(style & this.FILL) CANVAS.fillRect(x1-centerx, y1-centery, x2-x1, y2-y1);
		if(style & this.WIREFRAME) CANVAS.strokeRect(x1-centerx, y1-centery, x2-x1, y2-y1);
		CANVAS.restore();
	}
}
Drawing.prototype.drawScene = function(array,style){
	var piOver2 = 1.570796326794897;
	var piOver4 = 0.785398163397448;
	var sqrt2half = 1.414213562373095;

	for(tri=array.length;--tri>=0;){
		var x1 = array[tri][0];
		var y1 = array[tri][1];
		var x2 = array[tri][2];
		var y2 = array[tri][3];
		var x3 = array[tri][4];
		var y3 = array[tri][5];
		shade=array[tri][10];

		if(TEXTURES && array[tri][9]>=0){
			CANVAS.save();

			var u = (x2-x3)*(x2-x3)+(y2-y3)*(y2-y3);
			var v = (x1-x3)*(x1-x3)+(y1-y3)*(y1-y3);
			var w = (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1);

			var canvasRot = 0.5*Math.acos((w+v-u)/(2*Math.sqrt(w*v)));
			var scale = Math.cos(canvasRot)*sqrt2half;

			CANVAS.translate(x1,y1);
			CANVAS.rotate(Math.atan2(y2-y1,x2-x1)-piOver2+canvasRot);
			CANVAS.scale(Math.tan(canvasRot),1);
			CANVAS.rotate(piOver4);
			CANVAS.scale(Math.sqrt(w)*scale,Math.sqrt(v)*scale);
			//CANVAS.transform(x2-x1,y2-y1,x3-x1,y3-y1, x1,y1);
			CANVAS.drawImage((canvasimg = TEXTURES[array[tri][9]]), 0,0, canvasimg.width,canvasimg.height, 0,0, 1,1);
			CANVAS.restore();

			if(shade!=0){
				CANVAS.beginPath();
				CANVAS.moveTo(x1,y1);
				CANVAS.lineTo(x2,y2);
				CANVAS.lineTo(x3,y3);
				CANVAS.lineTo(x1,y1);
				if(shade>0){
					if(shade>1) shade=1;
					CANVAS.fillStyle = "rgba(255,255,255,"+(shade)+")";
					CANVAS.strokeStyle = "rgba(255,255,255,"+(shade*.5)+")";
				}else if(shade<0){
					if(shade<-1) shade=-1;
					CANVAS.fillStyle = "rgba(0,0,0,"+(-shade)+")";
					CANVAS.strokeStyle = "rgba(0,0,0,"+(-shade*.5)+")";
				}
				if(style & this.FILL) CANVAS.fill();
				if(style & this.WIREFRAME) CANVAS.stroke();
			}
		}else{
			var red = array[tri][6];
			var green = array[tri][7];
			var blue = array[tri][8];
			if(shade!=0){
				red=(red*=++shade)>255?255:(red<0?0:red);
				green=(green*=shade)>255?255:(green<0?0:green);
				blue=(blue*=shade)>255?255:(blue<0?0:blue);
			}
			var color = "rgb("+(red|0)+","+(green|0)+","+(blue|0)+")";
			CANVAS.beginPath();
			CANVAS.moveTo(x1,y1);
			CANVAS.lineTo(x2,y2);
			CANVAS.lineTo(x3,y3);
			CANVAS.lineTo(x1,y1);
			if(style & this.FILL){ CANVAS.fillStyle = color; CANVAS.fill(); }
			if(style & this.WIREFRAME){ CANVAS.strokeStyle = color; CANVAS.stroke(); }
		}
	}
}

Drawing.prototype.drawFloor = function(x1,x2,y1,x3,x4,y2,img){
	if((x2|=0)==(x1|=0)) x2++;
	if((y2|=0)==(y1|=0)) y2++;
	if((x4|=0)==(x3|=0)) x4++;
	var absdy=(dy = y2-y1)<0?-dy:dy;

	var sourceD = img.width-1, sourceY = (img.height-1)*(dx2 = x4-x3)/dy;
	var destX = (x3-x1)/dy;
	var tempY = 0;
	var destW2 = (dx1 = x2-x1);

	var absscale = (fullscale = 1.5*(dy>>31?-1:1)+dy/img.height)>>31?-(fullscale-1):(fullscale+1);
	var destwfullscale = fullscale*(dx2-dx1+1)/dy;

	while(tempY<0?-tempY:tempY<=absdy){
		CANVAS.drawImage(img, 0, sourceY*tempY/destW2, sourceD, 1, x1+destX*tempY, tempY+y1, destW2, absscale);
		tempY+=fullscale;
		destW2+=destwfullscale;
	}	
}
Drawing.prototype.drawWall = function(x1,y1,y2,x2,y3,y4,img){
	if(x2==x1) x2++;
	if(y2==y1) y2++;
	if(y4==y3) y4++;
	var dx = x2-x1, dy1 = y2-y1, dy2 = y4-y3;
	var absdx=dx<0?-dx:dx;

	var sourceH = img.height-1, sourceX = (img.width-1)*dy2/dx;
	var destY = (y3-y1)/dx;
	var tempX = 0;

	var fullscale = 1.5*(dx<0?-1:1)+dx/img.width;
	var absscale = fullscale<0?(-fullscale-1):(fullscale+1);
	var desthfullscale = fullscale*(dy2-dy1+1)/dx;

	while(tempX<0?-tempX:tempX<=absdx){
		CANVAS.drawImage(img, sourceX*tempX/dy1, 0, 1, sourceH, tempX+x1, y1+destY*tempX, absscale, dy1);
		tempX+=fullscale;
		dy1+=desthfullscale;
	}	
}
Drawing.prototype.zoom = function(zoom,width,height){
	ZOOM = zoom;
	CANVAS.translate(width>>1, height>>1);
	CANVAS.scale(ZOOM, ZOOM);
	CANVAS.translate(-width>>1, -height>>1);
}
Drawing.prototype.unZoom = function(width,height){
	CANVAS.translate(width>>1, height>>1);
	CANVAS.scale(1/ZOOM, 1/ZOOM);
	CANVAS.translate(-width>>1, -height>>1);
	ZOOM = 1;
}
Drawing.prototype.clear = function(x1, y1, x2, y2){ CANVAS.clearRect(x1, y1, x2-x1, y2-y1); }

Draw = new Drawing();var jWorkflow=function(){return{order:function(h,j){var i=[],f,d=null,g=function(){var a=false;return{take:function(){a=true},pass:function(b){var c;a=false;if(f.length){c=f.shift();b=c.func.apply(c.context,[b,g]);a||g.pass(b)}else d.func&&d.func.apply(d.context,[])}}}(),e={andThen:function(a,b){if(typeof a!=="function")throw"expected function but was "+typeof a;i.push({func:a,context:b});return e},chill:function(a){return e.andThen(function(b,c){c.take();setTimeout(function(){c.pass(b)},a)})},start:function(a,
b){d={func:a,context:b};f=i.slice();g.pass()}};return h?e.andThen(h,j):e}}}();if(typeof module==="object"&&typeof require==="function")module.exports=jWorkflow;
/*
  OpenLayers.js -- OpenLayers Map Viewer Library

  Copyright 2005-2010 OpenLayers Contributors, released under the Clear BSD
  license. Full license text below taken from http://svn.openlayers.org/trunk/openlayers/license.txt

        Copyright 2005-2011 OpenLayers Contributors. All rights reserved. See
        authors.txt for full list.
         
        Redistribution and use in source and binary forms, with or without modification,
        are permitted provided that the following conditions are met:
         
        1. Redistributions of source code must retain the above copyright notice, this
        list of conditions and the following disclaimer.
         
        2. Redistributions in binary form must reproduce the above copyright notice,
        this list of conditions and the following disclaimer in the documentation and/or
        other materials provided with the distribution.
         
        THIS SOFTWARE IS PROVIDED BY OPENLAYERS CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
        OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
        MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
        SHALL COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
        INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
        LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
        PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
        LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
        OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
        ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
         
        The views and conclusions contained in the software and documentation are those
        of the authors and should not be interpreted as representing official policies,
        either expressed or implied, of OpenLayers Contributors.

  Includes compressed code under the following licenses:

  (For uncompressed versions of the code used please see the
  OpenLayers SVN repository: <http://openlayers.org/>)

*/

/**  
*  
*  Contains portions of Rico <http://openrico.org/>
* 
*  Copyright 2005 Sabre Airline Solutions  
*  
*  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. 
*
**/

/**
 * Contains XMLHttpRequest.js <http://code.google.com/p/xmlhttprequest/>
 * Copyright 2007 Sergey Ilinsky (http://www.ilinsky.com)
 *
 * 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
 */

/**
 * Contains portions of Gears <http://code.google.com/apis/gears/>
 *
 * Copyright 2007, Google Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *  3. Neither the name of Google Inc. nor the names of its contributors may be
 *     used to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Sets up google.gears.*, which is *the only* supported way to access Gears.
 *
 * Circumvent this file at your own risk!
 *
 * In the future, Gears may automatically define google.gears.* without this
 * file. Gears may use these objects to transparently fix bugs and compatibility
 * issues. Applications that use the code below will continue to work seamlessly
 * when that happens.
 */
var OpenLayers={singleFile:true};(function(){var singleFile=(typeof OpenLayers=="object"&&OpenLayers.singleFile);var scriptLocation;window.OpenLayers={_scriptName:(!singleFile)?"lib/OpenLayers.js":"OpenLayers.js",_getScriptLocation:function(){if(scriptLocation!=undefined){return scriptLocation;}
scriptLocation="";var isOL=new RegExp("(^|(.*?\\/))("+OpenLayers._scriptName+")(\\?|$)");var scripts=document.getElementsByTagName('script');for(var i=0,len=scripts.length;i<len;i++){var src=scripts[i].getAttribute('src');if(src){var match=src.match(isOL);if(match){scriptLocation=match[1];break;}}}
return scriptLocation;}};if(!singleFile){var jsfiles=new Array("OpenLayers/Util.js","OpenLayers/BaseTypes.js","OpenLayers/BaseTypes/Class.js","OpenLayers/BaseTypes/Bounds.js","OpenLayers/BaseTypes/Element.js","OpenLayers/BaseTypes/LonLat.js","OpenLayers/BaseTypes/Pixel.js","OpenLayers/BaseTypes/Size.js","OpenLayers/Console.js","OpenLayers/Tween.js","Rico/Corner.js","Rico/Color.js","OpenLayers/Ajax.js","OpenLayers/Events.js","OpenLayers/Request.js","OpenLayers/Request/XMLHttpRequest.js","OpenLayers/Projection.js","OpenLayers/Map.js","OpenLayers/Layer.js","OpenLayers/Icon.js","OpenLayers/Marker.js","OpenLayers/Marker/Box.js","OpenLayers/Popup.js","OpenLayers/Tile.js","OpenLayers/Tile/Image.js","OpenLayers/Tile/Image/IFrame.js","OpenLayers/Tile/WFS.js","OpenLayers/Layer/Image.js","OpenLayers/Layer/SphericalMercator.js","OpenLayers/Layer/EventPane.js","OpenLayers/Layer/FixedZoomLevels.js","OpenLayers/Layer/Google.js","OpenLayers/Layer/Google/v3.js","OpenLayers/Layer/VirtualEarth.js","OpenLayers/Layer/Yahoo.js","OpenLayers/Layer/HTTPRequest.js","OpenLayers/Layer/Grid.js","OpenLayers/Layer/MapGuide.js","OpenLayers/Layer/MapServer.js","OpenLayers/Layer/MapServer/Untiled.js","OpenLayers/Layer/KaMap.js","OpenLayers/Layer/KaMapCache.js","OpenLayers/Layer/MultiMap.js","OpenLayers/Layer/Markers.js","OpenLayers/Layer/Text.js","OpenLayers/Layer/WorldWind.js","OpenLayers/Layer/ArcGIS93Rest.js","OpenLayers/Layer/WMS.js","OpenLayers/Layer/WMS/Untiled.js","OpenLayers/Layer/WMS/Post.js","OpenLayers/Layer/WMTS.js","OpenLayers/Layer/ArcIMS.js","OpenLayers/Layer/GeoRSS.js","OpenLayers/Layer/Boxes.js","OpenLayers/Layer/XYZ.js","OpenLayers/Layer/TMS.js","OpenLayers/Layer/TileCache.js","OpenLayers/Layer/Zoomify.js","OpenLayers/Popup/Anchored.js","OpenLayers/Popup/AnchoredBubble.js","OpenLayers/Popup/Framed.js","OpenLayers/Popup/FramedCloud.js","OpenLayers/Feature.js","OpenLayers/Feature/Vector.js","OpenLayers/Feature/WFS.js","OpenLayers/Handler.js","OpenLayers/Handler/Click.js","OpenLayers/Handler/Hover.js","OpenLayers/Handler/Point.js","OpenLayers/Handler/Path.js","OpenLayers/Handler/Polygon.js","OpenLayers/Handler/Feature.js","OpenLayers/Handler/Drag.js","OpenLayers/Handler/RegularPolygon.js","OpenLayers/Handler/Box.js","OpenLayers/Handler/MouseWheel.js","OpenLayers/Handler/Keyboard.js","OpenLayers/Control.js","OpenLayers/Control/Attribution.js","OpenLayers/Control/Button.js","OpenLayers/Control/ZoomBox.js","OpenLayers/Control/ZoomToMaxExtent.js","OpenLayers/Control/DragPan.js","OpenLayers/Control/Navigation.js","OpenLayers/Control/MouseDefaults.js","OpenLayers/Control/MousePosition.js","OpenLayers/Control/OverviewMap.js","OpenLayers/Control/KeyboardDefaults.js","OpenLayers/Control/PanZoom.js","OpenLayers/Control/PanZoomBar.js","OpenLayers/Control/ArgParser.js","OpenLayers/Control/Permalink.js","OpenLayers/Control/Scale.js","OpenLayers/Control/ScaleLine.js","OpenLayers/Control/Snapping.js","OpenLayers/Control/Split.js","OpenLayers/Control/LayerSwitcher.js","OpenLayers/Control/DrawFeature.js","OpenLayers/Control/DragFeature.js","OpenLayers/Control/ModifyFeature.js","OpenLayers/Control/Panel.js","OpenLayers/Control/SelectFeature.js","OpenLayers/Control/NavigationHistory.js","OpenLayers/Control/Measure.js","OpenLayers/Control/WMSGetFeatureInfo.js","OpenLayers/Control/WMTSGetFeatureInfo.js","OpenLayers/Control/Graticule.js","OpenLayers/Control/TransformFeature.js","OpenLayers/Control/SLDSelect.js","OpenLayers/Geometry.js","OpenLayers/Geometry/Rectangle.js","OpenLayers/Geometry/Collection.js","OpenLayers/Geometry/Point.js","OpenLayers/Geometry/MultiPoint.js","OpenLayers/Geometry/Curve.js","OpenLayers/Geometry/LineString.js","OpenLayers/Geometry/LinearRing.js","OpenLayers/Geometry/Polygon.js","OpenLayers/Geometry/MultiLineString.js","OpenLayers/Geometry/MultiPolygon.js","OpenLayers/Geometry/Surface.js","OpenLayers/Renderer.js","OpenLayers/Renderer/Elements.js","OpenLayers/Renderer/SVG.js","OpenLayers/Renderer/Canvas.js","OpenLayers/Renderer/VML.js","OpenLayers/Layer/Vector.js","OpenLayers/Layer/Vector/RootContainer.js","OpenLayers/Strategy.js","OpenLayers/Strategy/Filter.js","OpenLayers/Strategy/Fixed.js","OpenLayers/Strategy/Cluster.js","OpenLayers/Strategy/Paging.js","OpenLayers/Strategy/BBOX.js","OpenLayers/Strategy/Save.js","OpenLayers/Strategy/Refresh.js","OpenLayers/Filter.js","OpenLayers/Filter/FeatureId.js","OpenLayers/Filter/Logical.js","OpenLayers/Filter/Comparison.js","OpenLayers/Filter/Spatial.js","OpenLayers/Protocol.js","OpenLayers/Protocol/HTTP.js","OpenLayers/Protocol/SQL.js","OpenLayers/Protocol/SQL/Gears.js","OpenLayers/Protocol/WFS.js","OpenLayers/Protocol/WFS/v1.js","OpenLayers/Protocol/WFS/v1_0_0.js","OpenLayers/Protocol/WFS/v1_1_0.js","OpenLayers/Protocol/SOS.js","OpenLayers/Protocol/SOS/v1_0_0.js","OpenLayers/Layer/PointTrack.js","OpenLayers/Layer/GML.js","OpenLayers/Style.js","OpenLayers/Style2.js","OpenLayers/StyleMap.js","OpenLayers/Rule.js","OpenLayers/Format.js","OpenLayers/Format/XML.js","OpenLayers/Format/Context.js","OpenLayers/Format/ArcXML.js","OpenLayers/Format/ArcXML/Features.js","OpenLayers/Format/GML.js","OpenLayers/Format/GML/Base.js","OpenLayers/Format/GML/v2.js","OpenLayers/Format/GML/v3.js","OpenLayers/Format/Atom.js","OpenLayers/Format/KML.js","OpenLayers/Format/GeoRSS.js","OpenLayers/Format/WFS.js","OpenLayers/Format/WFSCapabilities.js","OpenLayers/Format/WFSCapabilities/v1.js","OpenLayers/Format/WFSCapabilities/v1_0_0.js","OpenLayers/Format/WFSCapabilities/v1_1_0.js","OpenLayers/Format/WFSDescribeFeatureType.js","OpenLayers/Format/WMSDescribeLayer.js","OpenLayers/Format/WMSDescribeLayer/v1_1.js","OpenLayers/Format/WKT.js","OpenLayers/Format/OSM.js","OpenLayers/Format/GPX.js","OpenLayers/Format/Filter.js","OpenLayers/Format/Filter/v1.js","OpenLayers/Format/Filter/v1_0_0.js","OpenLayers/Format/Filter/v1_1_0.js","OpenLayers/Format/SLD.js","OpenLayers/Format/SLD/v1.js","OpenLayers/Format/SLD/v1_0_0.js","OpenLayers/Format/OWSCommon/v1.js","OpenLayers/Format/OWSCommon/v1_0_0.js","OpenLayers/Format/OWSCommon/v1_1_0.js","OpenLayers/Format/CSWGetDomain.js","OpenLayers/Format/CSWGetDomain/v2_0_2.js","OpenLayers/Format/CSWGetRecords.js","OpenLayers/Format/CSWGetRecords/v2_0_2.js","OpenLayers/Format/WFST.js","OpenLayers/Format/WFST/v1.js","OpenLayers/Format/WFST/v1_0_0.js","OpenLayers/Format/WFST/v1_1_0.js","OpenLayers/Format/Text.js","OpenLayers/Format/JSON.js","OpenLayers/Format/GeoJSON.js","OpenLayers/Format/WMC.js","OpenLayers/Format/WMC/v1.js","OpenLayers/Format/WMC/v1_0_0.js","OpenLayers/Format/WMC/v1_1_0.js","OpenLayers/Format/WMSCapabilities.js","OpenLayers/Format/WMSCapabilities/v1.js","OpenLayers/Format/WMSCapabilities/v1_1.js","OpenLayers/Format/WMSCapabilities/v1_1_0.js","OpenLayers/Format/WMSCapabilities/v1_1_1.js","OpenLayers/Format/WMSCapabilities/v1_3.js","OpenLayers/Format/WMSCapabilities/v1_3_0.js","OpenLayers/Format/WMSGetFeatureInfo.js","OpenLayers/Format/SOSCapabilities.js","OpenLayers/Format/SOSCapabilities/v1_0_0.js","OpenLayers/Format/SOSGetObservation.js","OpenLayers/Format/SOSGetFeatureOfInterest.js","OpenLayers/Format/OWSContext.js","OpenLayers/Format/OWSContext/v0_3_1.js","OpenLayers/Format/WMTSCapabilities.js","OpenLayers/Format/WMTSCapabilities/v1_0_0.js","OpenLayers/Layer/WFS.js","OpenLayers/Control/GetFeature.js","OpenLayers/Control/MouseToolbar.js","OpenLayers/Control/NavToolbar.js","OpenLayers/Control/PanPanel.js","OpenLayers/Control/Pan.js","OpenLayers/Control/ZoomIn.js","OpenLayers/Control/ZoomOut.js","OpenLayers/Control/ZoomPanel.js","OpenLayers/Control/EditingToolbar.js","OpenLayers/Symbolizer.js","OpenLayers/Symbolizer/Point.js","OpenLayers/Symbolizer/Line.js","OpenLayers/Symbolizer/Polygon.js","OpenLayers/Symbolizer/Text.js","OpenLayers/Symbolizer/Raster.js","OpenLayers/Lang.js","OpenLayers/Lang/en.js");var agent=navigator.userAgent;var docWrite=(agent.match("MSIE")||agent.match("Safari"));if(docWrite){var allScriptTags=new Array(jsfiles.length);}
var host=OpenLayers._getScriptLocation()+"lib/";for(var i=0,len=jsfiles.length;i<len;i++){if(docWrite){allScriptTags[i]="<script src='"+host+jsfiles[i]+"'></script>";}else{var s=document.createElement("script");s.src=host+jsfiles[i];var h=document.getElementsByTagName("head").length?document.getElementsByTagName("head")[0]:document.body;h.appendChild(s);}}
if(docWrite){document.write(allScriptTags.join(""));}}})();OpenLayers.VERSION_NUMBER="OpenLayers 2.10 -- $Revision: 10721 $";OpenLayers.String={startsWith:function(str,sub){return(str.indexOf(sub)==0);},contains:function(str,sub){return(str.indexOf(sub)!=-1);},trim:function(str){return str.replace(/^\s\s*/,'').replace(/\s\s*$/,'');},camelize:function(str){var oStringList=str.split('-');var camelizedString=oStringList[0];for(var i=1,len=oStringList.length;i<len;i++){var s=oStringList[i];camelizedString+=s.charAt(0).toUpperCase()+s.substring(1);}
return camelizedString;},format:function(template,context,args){if(!context){context=window;}
var replacer=function(str,match){var replacement;var subs=match.split(/\.+/);for(var i=0;i<subs.length;i++){if(i==0){replacement=context;}
replacement=replacement[subs[i]];}
if(typeof replacement=="function"){replacement=args?replacement.apply(null,args):replacement();}
if(typeof replacement=='undefined'){return'undefined';}else{return replacement;}};return template.replace(OpenLayers.String.tokenRegEx,replacer);},tokenRegEx:/\$\{([\w.]+?)\}/g,numberRegEx:/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/,isNumeric:function(value){return OpenLayers.String.numberRegEx.test(value);},numericIf:function(value){return OpenLayers.String.isNumeric(value)?parseFloat(value):value;}};if(!String.prototype.startsWith){String.prototype.startsWith=function(sStart){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.String.startsWith'}));return OpenLayers.String.startsWith(this,sStart);};}
if(!String.prototype.contains){String.prototype.contains=function(str){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.String.contains'}));return OpenLayers.String.contains(this,str);};}
if(!String.prototype.trim){String.prototype.trim=function(){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.String.trim'}));return OpenLayers.String.trim(this);};}
if(!String.prototype.camelize){String.prototype.camelize=function(){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.String.camelize'}));return OpenLayers.String.camelize(this);};}
OpenLayers.Number={decimalSeparator:".",thousandsSeparator:",",limitSigDigs:function(num,sig){var fig=0;if(sig>0){fig=parseFloat(num.toPrecision(sig));}
return fig;},format:function(num,dec,tsep,dsep){dec=(typeof dec!="undefined")?dec:0;tsep=(typeof tsep!="undefined")?tsep:OpenLayers.Number.thousandsSeparator;dsep=(typeof dsep!="undefined")?dsep:OpenLayers.Number.decimalSeparator;if(dec!=null){num=parseFloat(num.toFixed(dec));}
var parts=num.toString().split(".");if(parts.length==1&&dec==null){dec=0;}
var integer=parts[0];if(tsep){var thousands=/(-?[0-9]+)([0-9]{3})/;while(thousands.test(integer)){integer=integer.replace(thousands,"$1"+tsep+"$2");}}
var str;if(dec==0){str=integer;}else{var rem=parts.length>1?parts[1]:"0";if(dec!=null){rem=rem+new Array(dec-rem.length+1).join("0");}
str=integer+dsep+rem;}
return str;}};if(!Number.prototype.limitSigDigs){Number.prototype.limitSigDigs=function(sig){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.Number.limitSigDigs'}));return OpenLayers.Number.limitSigDigs(this,sig);};}
OpenLayers.Function={bind:function(func,object){var args=Array.prototype.slice.apply(arguments,[2]);return function(){var newArgs=args.concat(Array.prototype.slice.apply(arguments,[0]));return func.apply(object,newArgs);};},bindAsEventListener:function(func,object){return function(event){return func.call(object,event||window.event);};},False:function(){return false;},True:function(){return true;}};if(!Function.prototype.bind){Function.prototype.bind=function(){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.Function.bind'}));Array.prototype.unshift.apply(arguments,[this]);return OpenLayers.Function.bind.apply(null,arguments);};}
if(!Function.prototype.bindAsEventListener){Function.prototype.bindAsEventListener=function(object){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.Function.bindAsEventListener'}));return OpenLayers.Function.bindAsEventListener(this,object);};}
OpenLayers.Array={filter:function(array,callback,caller){var selected=[];if(Array.prototype.filter){selected=array.filter(callback,caller);}else{var len=array.length;if(typeof callback!="function"){throw new TypeError();}
for(var i=0;i<len;i++){if(i in array){var val=array[i];if(callback.call(caller,val,i,array)){selected.push(val);}}}}
return selected;}};OpenLayers.Date={toISOString:(function(){if("toISOString"in Date.prototype){return function(date){return date.toISOString();}}else{function pad(num,len){var str=num+"";while(str.length<len){str="0"+str;}
return str;}
return function(date){var str;if(isNaN(date.getTime())){str="Invalid Date";}else{str=date.getUTCFullYear()+"-"+
pad(date.getUTCMonth()+1,2)+"-"+
pad(date.getUTCDate(),2)+"T"+
pad(date.getUTCHours(),2)+":"+
pad(date.getUTCMinutes(),2)+":"+
pad(date.getUTCSeconds(),2)+"."+
pad(date.getUTCMilliseconds(),3)+"Z";}
return str;}}})(),parse:function(str){var date;var elapsed=Date.parse(str);if(!isNaN(elapsed)){date=new Date(elapsed);}else{var match=str.match(/^(?:(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?)?(?:T(\d{1,2}):(\d{2}):(\d{2}(?:\.\d+)?)(Z|(?:[+-]\d{1,2}(?::(\d{2}))?)))?$/);var date;if(match&&(match[1]||match[7])){var year=parseInt(match[1],10)||0;var month=(parseInt(match[2],10)-1)||0;var day=parseInt(match[3],10)||1;date=new Date(Date.UTC(year,month,day));var type=match[7];if(type){var hours=parseInt(match[4],10);var minutes=parseInt(match[5],10);var secFrac=parseFloat(match[6]);var seconds=secFrac|0;var milliseconds=Math.round(1000*(secFrac-seconds));date.setUTCHours(hours,minutes,seconds,milliseconds);if(type!=="Z"){var hoursOffset=parseInt(type,10);var minutesOffset=parseInt(match[8])||0;var offset=-1000*(60*(hoursOffset*60)+minutesOffset*60);date=new Date(date.getTime()+offset);}}}else{date=new Date("invalid");}}
return date;}};OpenLayers.Class=function(){var Class=function(){if(arguments&&arguments[0]!=OpenLayers.Class.isPrototype){this.initialize.apply(this,arguments);}};var extended={};var parent,initialize,Type;for(var i=0,len=arguments.length;i<len;++i){Type=arguments[i];if(typeof Type=="function"){if(i==0&&len>1){initialize=Type.prototype.initialize;Type.prototype.initialize=function(){};extended=new Type();if(initialize===undefined){delete Type.prototype.initialize;}else{Type.prototype.initialize=initialize;}}
parent=Type.prototype;}else{parent=Type;}
OpenLayers.Util.extend(extended,parent);}
Class.prototype=extended;return Class;};OpenLayers.Class.isPrototype=function(){};OpenLayers.Class.create=function(){return function(){if(arguments&&arguments[0]!=OpenLayers.Class.isPrototype){this.initialize.apply(this,arguments);}};};OpenLayers.Class.inherit=function(){var superClass=arguments[0];var proto=new superClass(OpenLayers.Class.isPrototype);for(var i=1,len=arguments.length;i<len;i++){if(typeof arguments[i]=="function"){var mixin=arguments[i];arguments[i]=new mixin(OpenLayers.Class.isPrototype);}
OpenLayers.Util.extend(proto,arguments[i]);}
return proto;};OpenLayers.Util={};OpenLayers.Util.getElement=function(){var elements=[];for(var i=0,len=arguments.length;i<len;i++){var element=arguments[i];if(typeof element=='string'){element=document.getElementById(element);}
if(arguments.length==1){return element;}
elements.push(element);}
return elements;};OpenLayers.Util.isElement=function(o){return!!(o&&o.nodeType===1);};if(typeof window.$==="undefined"){window.$=OpenLayers.Util.getElement;}
OpenLayers.Util.extend=function(destination,source){destination=destination||{};if(source){for(var property in source){var value=source[property];if(value!==undefined){destination[property]=value;}}
var sourceIsEvt=typeof window.Event=="function"&&source instanceof window.Event;if(!sourceIsEvt&&source.hasOwnProperty&&source.hasOwnProperty('toString')){destination.toString=source.toString;}}
return destination;};OpenLayers.Util.removeItem=function(array,item){for(var i=array.length-1;i>=0;i--){if(array[i]==item){array.splice(i,1);}}
return array;};OpenLayers.Util.clearArray=function(array){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'array = []'}));array.length=0;};OpenLayers.Util.indexOf=function(array,obj){if(typeof array.indexOf=="function"){return array.indexOf(obj);}else{for(var i=0,len=array.length;i<len;i++){if(array[i]==obj){return i;}}
return-1;}};OpenLayers.Util.modifyDOMElement=function(element,id,px,sz,position,border,overflow,opacity){if(id){element.id=id;}
if(px){element.style.left=px.x+"px";element.style.top=px.y+"px";}
if(sz){element.style.width=sz.w+"px";element.style.height=sz.h+"px";}
if(position){element.style.position=position;}
if(border){element.style.border=border;}
if(overflow){element.style.overflow=overflow;}
if(parseFloat(opacity)>=0.0&&parseFloat(opacity)<1.0){element.style.filter='alpha(opacity='+(opacity*100)+')';element.style.opacity=opacity;}else if(parseFloat(opacity)==1.0){element.style.filter='';element.style.opacity='';}};OpenLayers.Util.createDiv=function(id,px,sz,imgURL,position,border,overflow,opacity){var dom=document.createElement('div');if(imgURL){dom.style.backgroundImage='url('+imgURL+')';}
if(!id){id=OpenLayers.Util.createUniqueID("OpenLayersDiv");}
if(!position){position="absolute";}
OpenLayers.Util.modifyDOMElement(dom,id,px,sz,position,border,overflow,opacity);return dom;};OpenLayers.Util.createImage=function(id,px,sz,imgURL,position,border,opacity,delayDisplay){var image=document.createElement("img");if(!id){id=OpenLayers.Util.createUniqueID("OpenLayersDiv");}
if(!position){position="relative";}
OpenLayers.Util.modifyDOMElement(image,id,px,sz,position,border,null,opacity);if(delayDisplay){image.style.display="none";OpenLayers.Event.observe(image,"load",OpenLayers.Function.bind(OpenLayers.Util.onImageLoad,image));OpenLayers.Event.observe(image,"error",OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError,image));}
image.style.alt=id;image.galleryImg="no";if(imgURL){image.src=imgURL;}
return image;};OpenLayers.Util.setOpacity=function(element,opacity){OpenLayers.Util.modifyDOMElement(element,null,null,null,null,null,null,opacity);};OpenLayers.Util.onImageLoad=function(){if(!this.viewRequestID||(this.map&&this.viewRequestID==this.map.viewRequestID)){this.style.display="";}
OpenLayers.Element.removeClass(this,"olImageLoadError");};OpenLayers.IMAGE_RELOAD_ATTEMPTS=0;OpenLayers.Util.onImageLoadError=function(){this._attempts=(this._attempts)?(this._attempts+1):1;if(this._attempts<=OpenLayers.IMAGE_RELOAD_ATTEMPTS){var urls=this.urls;if(urls&&urls instanceof Array&&urls.length>1){var src=this.src.toString();var current_url,k;for(k=0;current_url=urls[k];k++){if(src.indexOf(current_url)!=-1){break;}}
var guess=Math.floor(urls.length*Math.random());var new_url=urls[guess];k=0;while(new_url==current_url&&k++<4){guess=Math.floor(urls.length*Math.random());new_url=urls[guess];}
this.src=src.replace(current_url,new_url);}else{this.src=this.src;}}else{OpenLayers.Element.addClass(this,"olImageLoadError");}
this.style.display="";};OpenLayers.Util.alphaHackNeeded=null;OpenLayers.Util.alphaHack=function(){if(OpenLayers.Util.alphaHackNeeded==null){var arVersion=navigator.appVersion.split("MSIE");var version=parseFloat(arVersion[1]);var filter=false;try{filter=!!(document.body.filters);}catch(e){}
OpenLayers.Util.alphaHackNeeded=(filter&&(version>=5.5)&&(version<7));}
return OpenLayers.Util.alphaHackNeeded;};OpenLayers.Util.modifyAlphaImageDiv=function(div,id,px,sz,imgURL,position,border,sizing,opacity){OpenLayers.Util.modifyDOMElement(div,id,px,sz,position,null,null,opacity);var img=div.childNodes[0];if(imgURL){img.src=imgURL;}
OpenLayers.Util.modifyDOMElement(img,div.id+"_innerImage",null,sz,"relative",border);if(OpenLayers.Util.alphaHack()){if(div.style.display!="none"){div.style.display="inline-block";}
if(sizing==null){sizing="scale";}
div.style.filter="progid:DXImageTransform.Microsoft"+".AlphaImageLoader(src='"+img.src+"', "+"sizingMethod='"+sizing+"')";if(parseFloat(div.style.opacity)>=0.0&&parseFloat(div.style.opacity)<1.0){div.style.filter+=" alpha(opacity="+div.style.opacity*100+")";}
img.style.filter="alpha(opacity=0)";}};OpenLayers.Util.createAlphaImageDiv=function(id,px,sz,imgURL,position,border,sizing,opacity,delayDisplay){var div=OpenLayers.Util.createDiv();var img=OpenLayers.Util.createImage(null,null,null,null,null,null,null,false);div.appendChild(img);if(delayDisplay){img.style.display="none";OpenLayers.Event.observe(img,"load",OpenLayers.Function.bind(OpenLayers.Util.onImageLoad,div));OpenLayers.Event.observe(img,"error",OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError,div));}
OpenLayers.Util.modifyAlphaImageDiv(div,id,px,sz,imgURL,position,border,sizing,opacity);return div;};OpenLayers.Util.upperCaseObject=function(object){var uObject={};for(var key in object){uObject[key.toUpperCase()]=object[key];}
return uObject;};OpenLayers.Util.applyDefaults=function(to,from){to=to||{};var fromIsEvt=typeof window.Event=="function"&&from instanceof window.Event;for(var key in from){if(to[key]===undefined||(!fromIsEvt&&from.hasOwnProperty&&from.hasOwnProperty(key)&&!to.hasOwnProperty(key))){to[key]=from[key];}}
if(!fromIsEvt&&from&&from.hasOwnProperty&&from.hasOwnProperty('toString')&&!to.hasOwnProperty('toString')){to.toString=from.toString;}
return to;};OpenLayers.Util.getParameterString=function(params){var paramsArray=[];for(var key in params){var value=params[key];if((value!=null)&&(typeof value!='function')){var encodedValue;if(typeof value=='object'&&value.constructor==Array){var encodedItemArray=[];var item;for(var itemIndex=0,len=value.length;itemIndex<len;itemIndex++){item=value[itemIndex];encodedItemArray.push(encodeURIComponent((item===null||item===undefined)?"":item));}
encodedValue=encodedItemArray.join(",");}
else{encodedValue=encodeURIComponent(value);}
paramsArray.push(encodeURIComponent(key)+"="+encodedValue);}}
return paramsArray.join("&");};OpenLayers.Util.urlAppend=function(url,paramStr){var newUrl=url;if(paramStr){var parts=(url+" ").split(/[?&]/);newUrl+=(parts.pop()===" "?paramStr:parts.length?"&"+paramStr:"?"+paramStr);}
return newUrl;};OpenLayers.ImgPath='';OpenLayers.Util.getImagesLocation=function(){return OpenLayers.ImgPath||(OpenLayers._getScriptLocation()+"img/");};OpenLayers.Util.Try=function(){var returnValue=null;for(var i=0,len=arguments.length;i<len;i++){var lambda=arguments[i];try{returnValue=lambda();break;}catch(e){}}
return returnValue;};OpenLayers.Util.getNodes=function(p,tagName){var nodes=OpenLayers.Util.Try(function(){return OpenLayers.Util._getNodes(p.documentElement.childNodes,tagName);},function(){return OpenLayers.Util._getNodes(p.childNodes,tagName);});return nodes;};OpenLayers.Util._getNodes=function(nodes,tagName){var retArray=[];for(var i=0,len=nodes.length;i<len;i++){if(nodes[i].nodeName==tagName){retArray.push(nodes[i]);}}
return retArray;};OpenLayers.Util.getTagText=function(parent,item,index){var result=OpenLayers.Util.getNodes(parent,item);if(result&&(result.length>0))
{if(!index){index=0;}
if(result[index].childNodes.length>1){return result.childNodes[1].nodeValue;}
else if(result[index].childNodes.length==1){return result[index].firstChild.nodeValue;}}else{return"";}};OpenLayers.Util.getXmlNodeValue=function(node){var val=null;OpenLayers.Util.Try(function(){val=node.text;if(!val){val=node.textContent;}
if(!val){val=node.firstChild.nodeValue;}},function(){val=node.textContent;});return val;};OpenLayers.Util.mouseLeft=function(evt,div){var target=(evt.relatedTarget)?evt.relatedTarget:evt.toElement;while(target!=div&&target!=null){target=target.parentNode;}
return(target!=div);};OpenLayers.Util.DEFAULT_PRECISION=14;OpenLayers.Util.toFloat=function(number,precision){if(precision==null){precision=OpenLayers.Util.DEFAULT_PRECISION;}
var number;if(precision==0){number=parseFloat(number);}else{number=parseFloat(parseFloat(number).toPrecision(precision));}
return number;};OpenLayers.Util.rad=function(x){return x*Math.PI/180;};OpenLayers.Util.deg=function(x){return x*180/Math.PI;};OpenLayers.Util.VincentyConstants={a:6378137,b:6356752.3142,f:1/298.257223563};OpenLayers.Util.distVincenty=function(p1,p2){var ct=OpenLayers.Util.VincentyConstants;var a=ct.a,b=ct.b,f=ct.f;var L=OpenLayers.Util.rad(p2.lon-p1.lon);var U1=Math.atan((1-f)*Math.tan(OpenLayers.Util.rad(p1.lat)));var U2=Math.atan((1-f)*Math.tan(OpenLayers.Util.rad(p2.lat)));var sinU1=Math.sin(U1),cosU1=Math.cos(U1);var sinU2=Math.sin(U2),cosU2=Math.cos(U2);var lambda=L,lambdaP=2*Math.PI;var iterLimit=20;while(Math.abs(lambda-lambdaP)>1e-12&&--iterLimit>0){var sinLambda=Math.sin(lambda),cosLambda=Math.cos(lambda);var sinSigma=Math.sqrt((cosU2*sinLambda)*(cosU2*sinLambda)+
(cosU1*sinU2-sinU1*cosU2*cosLambda)*(cosU1*sinU2-sinU1*cosU2*cosLambda));if(sinSigma==0){return 0;}
var cosSigma=sinU1*sinU2+cosU1*cosU2*cosLambda;var sigma=Math.atan2(sinSigma,cosSigma);var alpha=Math.asin(cosU1*cosU2*sinLambda/sinSigma);var cosSqAlpha=Math.cos(alpha)*Math.cos(alpha);var cos2SigmaM=cosSigma-2*sinU1*sinU2/cosSqAlpha;var C=f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));lambdaP=lambda;lambda=L+(1-C)*f*Math.sin(alpha)*(sigma+C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));}
if(iterLimit==0){return NaN;}
var uSq=cosSqAlpha*(a*a-b*b)/(b*b);var A=1+uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));var B=uSq/1024*(256+uSq*(-128+uSq*(74-47*uSq)));var deltaSigma=B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));var s=b*A*(sigma-deltaSigma);var d=s.toFixed(3)/1000;return d;};OpenLayers.Util.destinationVincenty=function(lonlat,brng,dist){var u=OpenLayers.Util;var ct=u.VincentyConstants;var a=ct.a,b=ct.b,f=ct.f;var lon1=lonlat.lon;var lat1=lonlat.lat;var s=dist;var alpha1=u.rad(brng);var sinAlpha1=Math.sin(alpha1);var cosAlpha1=Math.cos(alpha1);var tanU1=(1-f)*Math.tan(u.rad(lat1));var cosU1=1/Math.sqrt((1+tanU1*tanU1)),sinU1=tanU1*cosU1;var sigma1=Math.atan2(tanU1,cosAlpha1);var sinAlpha=cosU1*sinAlpha1;var cosSqAlpha=1-sinAlpha*sinAlpha;var uSq=cosSqAlpha*(a*a-b*b)/(b*b);var A=1+uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));var B=uSq/1024*(256+uSq*(-128+uSq*(74-47*uSq)));var sigma=s/(b*A),sigmaP=2*Math.PI;while(Math.abs(sigma-sigmaP)>1e-12){var cos2SigmaM=Math.cos(2*sigma1+sigma);var sinSigma=Math.sin(sigma);var cosSigma=Math.cos(sigma);var deltaSigma=B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));sigmaP=sigma;sigma=s/(b*A)+deltaSigma;}
var tmp=sinU1*sinSigma-cosU1*cosSigma*cosAlpha1;var lat2=Math.atan2(sinU1*cosSigma+cosU1*sinSigma*cosAlpha1,(1-f)*Math.sqrt(sinAlpha*sinAlpha+tmp*tmp));var lambda=Math.atan2(sinSigma*sinAlpha1,cosU1*cosSigma-sinU1*sinSigma*cosAlpha1);var C=f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));var L=lambda-(1-C)*f*sinAlpha*(sigma+C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));var revAz=Math.atan2(sinAlpha,-tmp);return new OpenLayers.LonLat(lon1+u.deg(L),u.deg(lat2));};OpenLayers.Util.getParameters=function(url){url=url||window.location.href;var paramsString="";if(OpenLayers.String.contains(url,'?')){var start=url.indexOf('?')+1;var end=OpenLayers.String.contains(url,"#")?url.indexOf('#'):url.length;paramsString=url.substring(start,end);}
var parameters={};var pairs=paramsString.split(/[&;]/);for(var i=0,len=pairs.length;i<len;++i){var keyValue=pairs[i].split('=');if(keyValue[0]){var key=decodeURIComponent(keyValue[0]);var value=keyValue[1]||'';value=decodeURIComponent(value.replace(/\+/g," ")).split(",");if(value.length==1){value=value[0];}
parameters[key]=value;}}
return parameters;};OpenLayers.Util.getArgs=function(url){OpenLayers.Console.warn(OpenLayers.i18n("methodDeprecated",{'newMethod':'OpenLayers.Util.getParameters'}));return OpenLayers.Util.getParameters(url);};OpenLayers.Util.lastSeqID=0;OpenLayers.Util.createUniqueID=function(prefix){if(prefix==null){prefix="id_";}
OpenLayers.Util.lastSeqID+=1;return prefix+OpenLayers.Util.lastSeqID;};OpenLayers.INCHES_PER_UNIT={'inches':1.0,'ft':12.0,'mi':63360.0,'m':39.3701,'km':39370.1,'dd':4374754,'yd':36};OpenLayers.INCHES_PER_UNIT["in"]=OpenLayers.INCHES_PER_UNIT.inches;OpenLayers.INCHES_PER_UNIT["degrees"]=OpenLayers.INCHES_PER_UNIT.dd;OpenLayers.INCHES_PER_UNIT["nmi"]=1852*OpenLayers.INCHES_PER_UNIT.m;OpenLayers.METERS_PER_INCH=0.02540005080010160020;OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT,{"Inch":OpenLayers.INCHES_PER_UNIT.inches,"Meter":1.0/OpenLayers.METERS_PER_INCH,"Foot":0.30480060960121920243/OpenLayers.METERS_PER_INCH,"IFoot":0.30480000000000000000/OpenLayers.METERS_PER_INCH,"ClarkeFoot":0.3047972651151/OpenLayers.METERS_PER_INCH,"SearsFoot":0.30479947153867624624/OpenLayers.METERS_PER_INCH,"GoldCoastFoot":0.30479971018150881758/OpenLayers.METERS_PER_INCH,"IInch":0.02540000000000000000/OpenLayers.METERS_PER_INCH,"MicroInch":0.00002540000000000000/OpenLayers.METERS_PER_INCH,"Mil":0.00000002540000000000/OpenLayers.METERS_PER_INCH,"Centimeter":0.01000000000000000000/OpenLayers.METERS_PER_INCH,"Kilometer":1000.00000000000000000000/OpenLayers.METERS_PER_INCH,"Yard":0.91440182880365760731/OpenLayers.METERS_PER_INCH,"SearsYard":0.914398414616029/OpenLayers.METERS_PER_INCH,"IndianYard":0.91439853074444079983/OpenLayers.METERS_PER_INCH,"IndianYd37":0.91439523/OpenLayers.METERS_PER_INCH,"IndianYd62":0.9143988/OpenLayers.METERS_PER_INCH,"IndianYd75":0.9143985/OpenLayers.METERS_PER_INCH,"IndianFoot":0.30479951/OpenLayers.METERS_PER_INCH,"IndianFt37":0.30479841/OpenLayers.METERS_PER_INCH,"IndianFt62":0.3047996/OpenLayers.METERS_PER_INCH,"IndianFt75":0.3047995/OpenLayers.METERS_PER_INCH,"Mile":1609.34721869443738887477/OpenLayers.METERS_PER_INCH,"IYard":0.91440000000000000000/OpenLayers.METERS_PER_INCH,"IMile":1609.34400000000000000000/OpenLayers.METERS_PER_INCH,"NautM":1852.00000000000000000000/OpenLayers.METERS_PER_INCH,"Lat-66":110943.316488932731/OpenLayers.METERS_PER_INCH,"Lat-83":110946.25736872234125/OpenLayers.METERS_PER_INCH,"Decimeter":0.10000000000000000000/OpenLayers.METERS_PER_INCH,"Millimeter":0.00100000000000000000/OpenLayers.METERS_PER_INCH,"Dekameter":10.00000000000000000000/OpenLayers.METERS_PER_INCH,"Decameter":10.00000000000000000000/OpenLayers.METERS_PER_INCH,"Hectometer":100.00000000000000000000/OpenLayers.METERS_PER_INCH,"GermanMeter":1.0000135965/OpenLayers.METERS_PER_INCH,"CaGrid":0.999738/OpenLayers.METERS_PER_INCH,"ClarkeChain":20.1166194976/OpenLayers.METERS_PER_INCH,"GunterChain":20.11684023368047/OpenLayers.METERS_PER_INCH,"BenoitChain":20.116782494375872/OpenLayers.METERS_PER_INCH,"SearsChain":20.11676512155/OpenLayers.METERS_PER_INCH,"ClarkeLink":0.201166194976/OpenLayers.METERS_PER_INCH,"GunterLink":0.2011684023368047/OpenLayers.METERS_PER_INCH,"BenoitLink":0.20116782494375872/OpenLayers.METERS_PER_INCH,"SearsLink":0.2011676512155/OpenLayers.METERS_PER_INCH,"Rod":5.02921005842012/OpenLayers.METERS_PER_INCH,"IntnlChain":20.1168/OpenLayers.METERS_PER_INCH,"IntnlLink":0.201168/OpenLayers.METERS_PER_INCH,"Perch":5.02921005842012/OpenLayers.METERS_PER_INCH,"Pole":5.02921005842012/OpenLayers.METERS_PER_INCH,"Furlong":201.1684023368046/OpenLayers.METERS_PER_INCH,"Rood":3.778266898/OpenLayers.METERS_PER_INCH,"CapeFoot":0.3047972615/OpenLayers.METERS_PER_INCH,"Brealey":375.00000000000000000000/OpenLayers.METERS_PER_INCH,"ModAmFt":0.304812252984505969011938/OpenLayers.METERS_PER_INCH,"Fathom":1.8288/OpenLayers.METERS_PER_INCH,"NautM-UK":1853.184/OpenLayers.METERS_PER_INCH,"50kilometers":50000.0/OpenLayers.METERS_PER_INCH,"150kilometers":150000.0/OpenLayers.METERS_PER_INCH});OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT,{"mm":OpenLayers.INCHES_PER_UNIT["Meter"]/1000.0,"cm":OpenLayers.INCHES_PER_UNIT["Meter"]/100.0,"dm":OpenLayers.INCHES_PER_UNIT["Meter"]*100.0,"km":OpenLayers.INCHES_PER_UNIT["Meter"]*1000.0,"kmi":OpenLayers.INCHES_PER_UNIT["nmi"],"fath":OpenLayers.INCHES_PER_UNIT["Fathom"],"ch":OpenLayers.INCHES_PER_UNIT["IntnlChain"],"link":OpenLayers.INCHES_PER_UNIT["IntnlLink"],"us-in":OpenLayers.INCHES_PER_UNIT["inches"],"us-ft":OpenLayers.INCHES_PER_UNIT["Foot"],"us-yd":OpenLayers.INCHES_PER_UNIT["Yard"],"us-ch":OpenLayers.INCHES_PER_UNIT["GunterChain"],"us-mi":OpenLayers.INCHES_PER_UNIT["Mile"],"ind-yd":OpenLayers.INCHES_PER_UNIT["IndianYd37"],"ind-ft":OpenLayers.INCHES_PER_UNIT["IndianFt37"],"ind-ch":20.11669506/OpenLayers.METERS_PER_INCH});OpenLayers.DOTS_PER_INCH=72;OpenLayers.Util.normalizeScale=function(scale){var normScale=(scale>1.0)?(1.0/scale):scale;return normScale;};OpenLayers.Util.getResolutionFromScale=function(scale,units){var resolution;if(scale){if(units==null){units="degrees";}
var normScale=OpenLayers.Util.normalizeScale(scale);resolution=1/(normScale*OpenLayers.INCHES_PER_UNIT[units]*OpenLayers.DOTS_PER_INCH);}
return resolution;};OpenLayers.Util.getScaleFromResolution=function(resolution,units){if(units==null){units="degrees";}
var scale=resolution*OpenLayers.INCHES_PER_UNIT[units]*OpenLayers.DOTS_PER_INCH;return scale;};OpenLayers.Util.safeStopPropagation=function(evt){OpenLayers.Event.stop(evt,true);};OpenLayers.Util.pagePosition=function(forElement){var valueT=0,valueL=0;var element=forElement;var child=forElement;while(element){if(element==document.body){if(OpenLayers.Element.getStyle(child,'position')=='absolute'){break;}}
valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;child=element;try{element=element.offsetParent;}catch(e){OpenLayers.Console.error(OpenLayers.i18n("pagePositionFailed",{'elemId':element.id}));break;}}
element=forElement;while(element){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;element=element.parentNode;}
return[valueL,valueT];};OpenLayers.Util.isEquivalentUrl=function(url1,url2,options){options=options||{};OpenLayers.Util.applyDefaults(options,{ignoreCase:true,ignorePort80:true,ignoreHash:true});var urlObj1=OpenLayers.Util.createUrlObject(url1,options);var urlObj2=OpenLayers.Util.createUrlObject(url2,options);for(var key in urlObj1){if(key!=="args"){if(urlObj1[key]!=urlObj2[key]){return false;}}}
for(var key in urlObj1.args){if(urlObj1.args[key]!=urlObj2.args[key]){return false;}
delete urlObj2.args[key];}
for(var key in urlObj2.args){return false;}
return true;};OpenLayers.Util.createUrlObject=function(url,options){options=options||{};if(!(/^\w+:\/\//).test(url)){var loc=window.location;var port=loc.port?":"+loc.port:"";var fullUrl=loc.protocol+"//"+loc.host.split(":").shift()+port;if(url.indexOf("/")===0){url=fullUrl+url;}else{var parts=loc.pathname.split("/");parts.pop();url=fullUrl+parts.join("/")+"/"+url;}}
if(options.ignoreCase){url=url.toLowerCase();}
var a=document.createElement('a');a.href=url;var urlObject={};urlObject.host=a.host.split(":").shift();urlObject.protocol=a.protocol;if(options.ignorePort80){urlObject.port=(a.port=="80"||a.port=="0")?"":a.port;}else{urlObject.port=(a.port==""||a.port=="0")?"80":a.port;}
urlObject.hash=(options.ignoreHash||a.hash==="#")?"":a.hash;var queryString=a.search;if(!queryString){var qMark=url.indexOf("?");queryString=(qMark!=-1)?url.substr(qMark):"";}
urlObject.args=OpenLayers.Util.getParameters(queryString);urlObject.pathname=(a.pathname.charAt(0)=="/")?a.pathname:"/"+a.pathname;return urlObject;};OpenLayers.Util.removeTail=function(url){var head=null;var qMark=url.indexOf("?");var hashMark=url.indexOf("#");if(qMark==-1){head=(hashMark!=-1)?url.substr(0,hashMark):url;}else{head=(hashMark!=-1)?url.substr(0,Math.min(qMark,hashMark)):url.substr(0,qMark);}
return head;};OpenLayers.Util.getBrowserName=function(){var browserName="";var ua=navigator.userAgent.toLowerCase();if(ua.indexOf("opera")!=-1){browserName="opera";}else if(ua.indexOf("msie")!=-1){browserName="msie";}else if(ua.indexOf("safari")!=-1){browserName="safari";}else if(ua.indexOf("mozilla")!=-1){if(ua.indexOf("firefox")!=-1){browserName="firefox";}else{browserName="mozilla";}}
return browserName;};OpenLayers.Util.getRenderedDimensions=function(contentHTML,size,options){var w,h;var container=document.createElement("div");container.style.visibility="hidden";var containerElement=(options&&options.containerElement)?options.containerElement:document.body;if(size){if(size.w){w=size.w;container.style.width=w+"px";}else if(size.h){h=size.h;container.style.height=h+"px";}}
if(options&&options.displayClass){container.className=options.displayClass;}
var content=document.createElement("div");content.innerHTML=contentHTML;content.style.overflow="visible";if(content.childNodes){for(var i=0,l=content.childNodes.length;i<l;i++){if(!content.childNodes[i].style)continue;content.childNodes[i].style.overflow="visible";}}
container.appendChild(content);containerElement.appendChild(container);var parentHasPositionAbsolute=false;var parent=container.parentNode;while(parent&&parent.tagName.toLowerCase()!="body"){var parentPosition=OpenLayers.Element.getStyle(parent,"position");if(parentPosition=="absolute"){parentHasPositionAbsolute=true;break;}else if(parentPosition&&parentPosition!="static"){break;}
parent=parent.parentNode;}
if(!parentHasPositionAbsolute){container.style.position="absolute";}
if(!w){w=parseInt(content.scrollWidth);container.style.width=w+"px";}
if(!h){h=parseInt(content.scrollHeight);}
container.removeChild(content);containerElement.removeChild(container);return new OpenLayers.Size(w,h);};OpenLayers.Util.getScrollbarWidth=function(){var scrollbarWidth=OpenLayers.Util._scrollbarWidth;if(scrollbarWidth==null){var scr=null;var inn=null;var wNoScroll=0;var wScroll=0;scr=document.createElement('div');scr.style.position='absolute';scr.style.top='-1000px';scr.style.left='-1000px';scr.style.width='100px';scr.style.height='50px';scr.style.overflow='hidden';inn=document.createElement('div');inn.style.width='100%';inn.style.height='200px';scr.appendChild(inn);document.body.appendChild(scr);wNoScroll=inn.offsetWidth;scr.style.overflow='scroll';wScroll=inn.offsetWidth;document.body.removeChild(document.body.lastChild);OpenLayers.Util._scrollbarWidth=(wNoScroll-wScroll);scrollbarWidth=OpenLayers.Util._scrollbarWidth;}
return scrollbarWidth;};OpenLayers.Util.getFormattedLonLat=function(coordinate,axis,dmsOption){if(!dmsOption){dmsOption='dms';}
var abscoordinate=Math.abs(coordinate)
var coordinatedegrees=Math.floor(abscoordinate);var coordinateminutes=(abscoordinate-coordinatedegrees)/(1/60);var tempcoordinateminutes=coordinateminutes;coordinateminutes=Math.floor(coordinateminutes);var coordinateseconds=(tempcoordinateminutes-coordinateminutes)/(1/60);coordinateseconds=Math.round(coordinateseconds*10);coordinateseconds/=10;if(coordinatedegrees<10){coordinatedegrees="0"+coordinatedegrees;}
var str=coordinatedegrees+"\u00B0";if(dmsOption.indexOf('dm')>=0){if(coordinateminutes<10){coordinateminutes="0"+coordinateminutes;}
str+=coordinateminutes+"'";if(dmsOption.indexOf('dms')>=0){if(coordinateseconds<10){coordinateseconds="0"+coordinateseconds;}
str+=coordinateseconds+'"';}}
if(axis=="lon"){str+=coordinate<0?OpenLayers.i18n("W"):OpenLayers.i18n("E");}else{str+=coordinate<0?OpenLayers.i18n("S"):OpenLayers.i18n("N");}
return str;};OpenLayers.Rico=new Object();OpenLayers.Rico.Corner={round:function(e,options){e=OpenLayers.Util.getElement(e);this._setOptions(options);var color=this.options.color;if(this.options.color=="fromElement"){color=this._background(e);}
var bgColor=this.options.bgColor;if(this.options.bgColor=="fromParent"){bgColor=this._background(e.offsetParent);}
this._roundCornersImpl(e,color,bgColor);},changeColor:function(theDiv,newColor){theDiv.style.backgroundColor=newColor;var spanElements=theDiv.parentNode.getElementsByTagName("span");for(var currIdx=0;currIdx<spanElements.length;currIdx++){spanElements[currIdx].style.backgroundColor=newColor;}},changeOpacity:function(theDiv,newOpacity){var mozillaOpacity=newOpacity;var ieOpacity='alpha(opacity='+newOpacity*100+')';theDiv.style.opacity=mozillaOpacity;theDiv.style.filter=ieOpacity;var spanElements=theDiv.parentNode.getElementsByTagName("span");for(var currIdx=0;currIdx<spanElements.length;currIdx++){spanElements[currIdx].style.opacity=mozillaOpacity;spanElements[currIdx].style.filter=ieOpacity;}},reRound:function(theDiv,options){var topRico=theDiv.parentNode.childNodes[0];var bottomRico=theDiv.parentNode.childNodes[2];theDiv.parentNode.removeChild(topRico);theDiv.parentNode.removeChild(bottomRico);this.round(theDiv.parentNode,options);},_roundCornersImpl:function(e,color,bgColor){if(this.options.border){this._renderBorder(e,bgColor);}
if(this._isTopRounded()){this._roundTopCorners(e,color,bgColor);}
if(this._isBottomRounded()){this._roundBottomCorners(e,color,bgColor);}},_renderBorder:function(el,bgColor){var borderValue="1px solid "+this._borderColor(bgColor);var borderL="border-left: "+borderValue;var borderR="border-right: "+borderValue;var style="style='"+borderL+";"+borderR+"'";el.innerHTML="<div "+style+">"+el.innerHTML+"</div>";},_roundTopCorners:function(el,color,bgColor){var corner=this._createCorner(bgColor);for(var i=0;i<this.options.numSlices;i++){corner.appendChild(this._createCornerSlice(color,bgColor,i,"top"));}
el.style.paddingTop=0;el.insertBefore(corner,el.firstChild);},_roundBottomCorners:function(el,color,bgColor){var corner=this._createCorner(bgColor);for(var i=(this.options.numSlices-1);i>=0;i--){corner.appendChild(this._createCornerSlice(color,bgColor,i,"bottom"));}
el.style.paddingBottom=0;el.appendChild(corner);},_createCorner:function(bgColor){var corner=document.createElement("div");corner.style.backgroundColor=(this._isTransparent()?"transparent":bgColor);return corner;},_createCornerSlice:function(color,bgColor,n,position){var slice=document.createElement("span");var inStyle=slice.style;inStyle.backgroundColor=color;inStyle.display="block";inStyle.height="1px";inStyle.overflow="hidden";inStyle.fontSize="1px";var borderColor=this._borderColor(color,bgColor);if(this.options.border&&n==0){inStyle.borderTopStyle="solid";inStyle.borderTopWidth="1px";inStyle.borderLeftWidth="0px";inStyle.borderRightWidth="0px";inStyle.borderBottomWidth="0px";inStyle.height="0px";inStyle.borderColor=borderColor;}
else if(borderColor){inStyle.borderColor=borderColor;inStyle.borderStyle="solid";inStyle.borderWidth="0px 1px";}
if(!this.options.compact&&(n==(this.options.numSlices-1))){inStyle.height="2px";}
this._setMargin(slice,n,position);this._setBorder(slice,n,position);return slice;},_setOptions:function(options){this.options={corners:"all",color:"fromElement",bgColor:"fromParent",blend:true,border:false,compact:false};OpenLayers.Util.extend(this.options,options||{});this.options.numSlices=this.options.compact?2:4;if(this._isTransparent()){this.options.blend=false;}},_whichSideTop:function(){if(this._hasString(this.options.corners,"all","top")){return"";}
if(this.options.corners.indexOf("tl")>=0&&this.options.corners.indexOf("tr")>=0){return"";}
if(this.options.corners.indexOf("tl")>=0){return"left";}else if(this.options.corners.indexOf("tr")>=0){return"right";}
return"";},_whichSideBottom:function(){if(this._hasString(this.options.corners,"all","bottom")){return"";}
if(this.options.corners.indexOf("bl")>=0&&this.options.corners.indexOf("br")>=0){return"";}
if(this.options.corners.indexOf("bl")>=0){return"left";}else if(this.options.corners.indexOf("br")>=0){return"right";}
return"";},_borderColor:function(color,bgColor){if(color=="transparent"){return bgColor;}else if(this.options.border){return this.options.border;}else if(this.options.blend){return this._blend(bgColor,color);}else{return"";}},_setMargin:function(el,n,corners){var marginSize=this._marginSize(n);var whichSide=corners=="top"?this._whichSideTop():this._whichSideBottom();if(whichSide=="left"){el.style.marginLeft=marginSize+"px";el.style.marginRight="0px";}
else if(whichSide=="right"){el.style.marginRight=marginSize+"px";el.style.marginLeft="0px";}
else{el.style.marginLeft=marginSize+"px";el.style.marginRight=marginSize+"px";}},_setBorder:function(el,n,corners){var borderSize=this._borderSize(n);var whichSide=corners=="top"?this._whichSideTop():this._whichSideBottom();if(whichSide=="left"){el.style.borderLeftWidth=borderSize+"px";el.style.borderRightWidth="0px";}
else if(whichSide=="right"){el.style.borderRightWidth=borderSize+"px";el.style.borderLeftWidth="0px";}
else{el.style.borderLeftWidth=borderSize+"px";el.style.borderRightWidth=borderSize+"px";}
if(this.options.border!=false){el.style.borderLeftWidth=borderSize+"px";el.style.borderRightWidth=borderSize+"px";}},_marginSize:function(n){if(this._isTransparent()){return 0;}
var marginSizes=[5,3,2,1];var blendedMarginSizes=[3,2,1,0];var compactMarginSizes=[2,1];var smBlendedMarginSizes=[1,0];if(this.options.compact&&this.options.blend){return smBlendedMarginSizes[n];}else if(this.options.compact){return compactMarginSizes[n];}else if(this.options.blend){return blendedMarginSizes[n];}else{return marginSizes[n];}},_borderSize:function(n){var transparentBorderSizes=[5,3,2,1];var blendedBorderSizes=[2,1,1,1];var compactBorderSizes=[1,0];var actualBorderSizes=[0,2,0,0];if(this.options.compact&&(this.options.blend||this._isTransparent())){return 1;}else if(this.options.compact){return compactBorderSizes[n];}else if(this.options.blend){return blendedBorderSizes[n];}else if(this.options.border){return actualBorderSizes[n];}else if(this._isTransparent()){return transparentBorderSizes[n];}
return 0;},_hasString:function(str){for(var i=1;i<arguments.length;i++)if(str.indexOf(arguments[i])>=0){return true;}return false;},_blend:function(c1,c2){var cc1=OpenLayers.Rico.Color.createFromHex(c1);cc1.blend(OpenLayers.Rico.Color.createFromHex(c2));return cc1;},_background:function(el){try{return OpenLayers.Rico.Color.createColorFromBackground(el).asHex();}catch(err){return"#ffffff";}},_isTransparent:function(){return this.options.color=="transparent";},_isTopRounded:function(){return this._hasString(this.options.corners,"all","top","tl","tr");},_isBottomRounded:function(){return this._hasString(this.options.corners,"all","bottom","bl","br");},_hasSingleTextChild:function(el){return el.childNodes.length==1&&el.childNodes[0].nodeType==3;}};(function(){if(window.google&&google.gears){return;}
var factory=null;if(typeof GearsFactory!='undefined'){factory=new GearsFactory();}else{try{factory=new ActiveXObject('Gears.Factory');if(factory.getBuildInfo().indexOf('ie_mobile')!=-1){factory.privateSetGlobalObject(this);}}catch(e){if((typeof navigator.mimeTypes!='undefined')&&navigator.mimeTypes["application/x-googlegears"]){factory=document.createElement("object");factory.style.display="none";factory.width=0;factory.height=0;factory.type="application/x-googlegears";document.documentElement.appendChild(factory);}}}
if(!factory){return;}
if(!window.google){google={};}
if(!google.gears){google.gears={factory:factory};}})();OpenLayers.Element={visible:function(element){return OpenLayers.Util.getElement(element).style.display!='none';},toggle:function(){for(var i=0,len=arguments.length;i<len;i++){var element=OpenLayers.Util.getElement(arguments[i]);var display=OpenLayers.Element.visible(element)?'hide':'show';OpenLayers.Element[display](element);}},hide:function(){for(var i=0,len=arguments.length;i<len;i++){var element=OpenLayers.Util.getElement(arguments[i]);if(element){element.style.display='none';}}},show:function(){for(var i=0,len=arguments.length;i<len;i++){var element=OpenLayers.Util.getElement(arguments[i]);if(element){element.style.display='';}}},remove:function(element){element=OpenLayers.Util.getElement(element);element.parentNode.removeChild(element);},getHeight:function(element){element=OpenLayers.Util.getElement(element);return element.offsetHeight;},getDimensions:function(element){element=OpenLayers.Util.getElement(element);if(OpenLayers.Element.getStyle(element,'display')!='none'){return{width:element.offsetWidth,height:element.offsetHeight};}
var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;els.visibility='hidden';els.position='absolute';els.display='';var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};},hasClass:function(element,name){var names=element.className;return(!!names&&new RegExp("(^|\\s)"+name+"(\\s|$)").test(names));},addClass:function(element,name){if(!OpenLayers.Element.hasClass(element,name)){element.className+=(element.className?" ":"")+name;}
return element;},removeClass:function(element,name){var names=element.className;if(names){element.className=OpenLayers.String.trim(names.replace(new RegExp("(^|\\s+)"+name+"(\\s+|$)")," "));}
return element;},toggleClass:function(element,name){if(OpenLayers.Element.hasClass(element,name)){OpenLayers.Element.removeClass(element,name);}else{OpenLayers.Element.addClass(element,name);}
return element;},getStyle:function(element,style){element=OpenLayers.Util.getElement(element);var value=null;if(element&&element.style){value=element.style[OpenLayers.String.camelize(style)];if(!value){if(document.defaultView&&document.defaultView.getComputedStyle){var css=document.defaultView.getComputedStyle(element,null);value=css?css.getPropertyValue(style):null;}else if(element.currentStyle){value=element.currentStyle[OpenLayers.String.camelize(style)];}}
var positions=['left','top','right','bottom'];if(window.opera&&(OpenLayers.Util.indexOf(positions,style)!=-1)&&(OpenLayers.Element.getStyle(element,'position')=='static')){value='auto';}}
return value=='auto'?null:value;}};OpenLayers.Size=OpenLayers.Class({w:0.0,h:0.0,initialize:function(w,h){this.w=parseFloat(w);this.h=parseFloat(h);},toString:function(){return("w="+this.w+",h="+this.h);},clone:function(){return new OpenLayers.Size(this.w,this.h);},equals:function(sz){var equals=false;if(sz!=null){equals=((this.w==sz.w&&this.h==sz.h)||(isNaN(this.w)&&isNaN(this.h)&&isNaN(sz.w)&&isNaN(sz.h)));}
return equals;},CLASS_NAME:"OpenLayers.Size"});OpenLayers.Console={log:function(){},debug:function(){},info:function(){},warn:function(){},error:function(){},userError:function(error){alert(error);},assert:function(){},dir:function(){},dirxml:function(){},trace:function(){},group:function(){},groupEnd:function(){},time:function(){},timeEnd:function(){},profile:function(){},profileEnd:function(){},count:function(){},CLASS_NAME:"OpenLayers.Console"};(function(){var scripts=document.getElementsByTagName("script");for(var i=0,len=scripts.length;i<len;++i){if(scripts[i].src.indexOf("firebug.js")!=-1){if(console){OpenLayers.Util.extend(OpenLayers.Console,console);break;}}}})();OpenLayers.Icon=OpenLayers.Class({url:null,size:null,offset:null,calculateOffset:null,imageDiv:null,px:null,initialize:function(url,size,offset,calculateOffset){this.url=url;this.size=(size)?size:new OpenLayers.Size(20,20);this.offset=offset?offset:new OpenLayers.Pixel(-(this.size.w/2),-(this.size.h/2));this.calculateOffset=calculateOffset;var id=OpenLayers.Util.createUniqueID("OL_Icon_");this.imageDiv=OpenLayers.Util.createAlphaImageDiv(id);},destroy:function(){this.erase();OpenLayers.Event.stopObservingElement(this.imageDiv.firstChild);this.imageDiv.innerHTML="";this.imageDiv=null;},clone:function(){return new OpenLayers.Icon(this.url,this.size,this.offset,this.calculateOffset);},setSize:function(size){if(size!=null){this.size=size;}
this.draw();},setUrl:function(url){if(url!=null){this.url=url;}
this.draw();},draw:function(px){OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,this.size,this.url,"absolute");this.moveTo(px);return this.imageDiv;},erase:function(){if(this.imageDiv!=null&&this.imageDiv.parentNode!=null){OpenLayers.Element.remove(this.imageDiv);}},setOpacity:function(opacity){OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,null,null,null,null,null,opacity);},moveTo:function(px){if(px!=null){this.px=px;}
if(this.imageDiv!=null){if(this.px==null){this.display(false);}else{if(this.calculateOffset){this.offset=this.calculateOffset(this.size);}
var offsetPx=this.px.offset(this.offset);OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,offsetPx);}}},display:function(display){this.imageDiv.style.display=(display)?"":"none";},isDrawn:function(){var isDrawn=(this.imageDiv&&this.imageDiv.parentNode&&(this.imageDiv.parentNode.nodeType!=11));return isDrawn;},CLASS_NAME:"OpenLayers.Icon"});OpenLayers.Popup=OpenLayers.Class({events:null,id:"",lonlat:null,div:null,contentSize:null,size:null,contentHTML:null,backgroundColor:"",opacity:"",border:"",contentDiv:null,groupDiv:null,closeDiv:null,autoSize:false,minSize:null,maxSize:null,displayClass:"olPopup",contentDisplayClass:"olPopupContent",padding:0,disableFirefoxOverflowHack:false,fixPadding:function(){if(typeof this.padding=="number"){this.padding=new OpenLayers.Bounds(this.padding,this.padding,this.padding,this.padding);}},panMapIfOutOfView:false,keepInMap:false,closeOnMove:false,map:null,initialize:function(id,lonlat,contentSize,contentHTML,closeBox,closeBoxCallback){if(id==null){id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");}
this.id=id;this.lonlat=lonlat;this.contentSize=(contentSize!=null)?contentSize:new OpenLayers.Size(OpenLayers.Popup.WIDTH,OpenLayers.Popup.HEIGHT);if(contentHTML!=null){this.contentHTML=contentHTML;}
this.backgroundColor=OpenLayers.Popup.COLOR;this.opacity=OpenLayers.Popup.OPACITY;this.border=OpenLayers.Popup.BORDER;this.div=OpenLayers.Util.createDiv(this.id,null,null,null,null,null,"hidden");this.div.className=this.displayClass;var groupDivId=this.id+"_GroupDiv";this.groupDiv=OpenLayers.Util.createDiv(groupDivId,null,null,null,"relative",null,"hidden");var id=this.div.id+"_contentDiv";this.contentDiv=OpenLayers.Util.createDiv(id,null,this.contentSize.clone(),null,"relative");this.contentDiv.className=this.contentDisplayClass;this.groupDiv.appendChild(this.contentDiv);this.div.appendChild(this.groupDiv);if(closeBox){this.addCloseBox(closeBoxCallback);}
this.registerEvents();},destroy:function(){this.id=null;this.lonlat=null;this.size=null;this.contentHTML=null;this.backgroundColor=null;this.opacity=null;this.border=null;if(this.closeOnMove&&this.map){this.map.events.unregister("movestart",this,this.hide);}
this.events.destroy();this.events=null;if(this.closeDiv){OpenLayers.Event.stopObservingElement(this.closeDiv);this.groupDiv.removeChild(this.closeDiv);}
this.closeDiv=null;this.div.removeChild(this.groupDiv);this.groupDiv=null;if(this.map!=null){this.map.removePopup(this);}
this.map=null;this.div=null;this.autoSize=null;this.minSize=null;this.maxSize=null;this.padding=null;this.panMapIfOutOfView=null;},draw:function(px){if(px==null){if((this.lonlat!=null)&&(this.map!=null)){px=this.map.getLayerPxFromLonLat(this.lonlat);}}
if(this.closeOnMove){this.map.events.register("movestart",this,this.hide);}
if(!this.disableFirefoxOverflowHack&&OpenLayers.Util.getBrowserName()=='firefox'){this.map.events.register("movestart",this,function(){var style=document.defaultView.getComputedStyle(this.contentDiv,null);var currentOverflow=style.getPropertyValue("overflow");if(currentOverflow!="hidden"){this.contentDiv._oldOverflow=currentOverflow;this.contentDiv.style.overflow="hidden";}});this.map.events.register("moveend",this,function(){var oldOverflow=this.contentDiv._oldOverflow;if(oldOverflow){this.contentDiv.style.overflow=oldOverflow;this.contentDiv._oldOverflow=null;}});}
this.moveTo(px);if(!this.autoSize&&!this.size){this.setSize(this.contentSize);}
this.setBackgroundColor();this.setOpacity();this.setBorder();this.setContentHTML();if(this.panMapIfOutOfView){this.panIntoView();}
return this.div;},updatePosition:function(){if((this.lonlat)&&(this.map)){var px=this.map.getLayerPxFromLonLat(this.lonlat);if(px){this.moveTo(px);}}},moveTo:function(px){if((px!=null)&&(this.div!=null)){this.div.style.left=px.x+"px";this.div.style.top=px.y+"px";}},visible:function(){return OpenLayers.Element.visible(this.div);},toggle:function(){if(this.visible()){this.hide();}else{this.show();}},show:function(){OpenLayers.Element.show(this.div);if(this.panMapIfOutOfView){this.panIntoView();}},hide:function(){OpenLayers.Element.hide(this.div);},setSize:function(contentSize){this.size=contentSize.clone();var contentDivPadding=this.getContentDivPadding();var wPadding=contentDivPadding.left+contentDivPadding.right;var hPadding=contentDivPadding.top+contentDivPadding.bottom;this.fixPadding();wPadding+=this.padding.left+this.padding.right;hPadding+=this.padding.top+this.padding.bottom;if(this.closeDiv){var closeDivWidth=parseInt(this.closeDiv.style.width);wPadding+=closeDivWidth+contentDivPadding.right;}
this.size.w+=wPadding;this.size.h+=hPadding;if(OpenLayers.Util.getBrowserName()=="msie"){this.contentSize.w+=contentDivPadding.left+contentDivPadding.right;this.contentSize.h+=contentDivPadding.bottom+contentDivPadding.top;}
if(this.div!=null){this.div.style.width=this.size.w+"px";this.div.style.height=this.size.h+"px";}
if(this.contentDiv!=null){this.contentDiv.style.width=contentSize.w+"px";this.contentDiv.style.height=contentSize.h+"px";}},updateSize:function(){var preparedHTML="<div class='"+this.contentDisplayClass+"'>"+
this.contentDiv.innerHTML+"</div>";var containerElement=(this.map)?this.map.layerContainerDiv:document.body;var realSize=OpenLayers.Util.getRenderedDimensions(preparedHTML,null,{displayClass:this.displayClass,containerElement:containerElement});var safeSize=this.getSafeContentSize(realSize);var newSize=null;if(safeSize.equals(realSize)){newSize=realSize;}else{var fixedSize=new OpenLayers.Size();fixedSize.w=(safeSize.w<realSize.w)?safeSize.w:null;fixedSize.h=(safeSize.h<realSize.h)?safeSize.h:null;if(fixedSize.w&&fixedSize.h){newSize=safeSize;}else{var clippedSize=OpenLayers.Util.getRenderedDimensions(preparedHTML,fixedSize,{displayClass:this.contentDisplayClass,containerElement:containerElement});var currentOverflow=OpenLayers.Element.getStyle(this.contentDiv,"overflow");if((currentOverflow!="hidden")&&(clippedSize.equals(safeSize))){var scrollBar=OpenLayers.Util.getScrollbarWidth();if(fixedSize.w){clippedSize.h+=scrollBar;}else{clippedSize.w+=scrollBar;}}
newSize=this.getSafeContentSize(clippedSize);}}
this.setSize(newSize);},setBackgroundColor:function(color){if(color!=undefined){this.backgroundColor=color;}
if(this.div!=null){this.div.style.backgroundColor=this.backgroundColor;}},setOpacity:function(opacity){if(opacity!=undefined){this.opacity=opacity;}
if(this.div!=null){this.div.style.opacity=this.opacity;this.div.style.filter='alpha(opacity='+this.opacity*100+')';}},setBorder:function(border){if(border!=undefined){this.border=border;}
if(this.div!=null){this.div.style.border=this.border;}},setContentHTML:function(contentHTML){if(contentHTML!=null){this.contentHTML=contentHTML;}
if((this.contentDiv!=null)&&(this.contentHTML!=null)&&(this.contentHTML!=this.contentDiv.innerHTML)){this.contentDiv.innerHTML=this.contentHTML;if(this.autoSize){this.registerImageListeners();this.updateSize();}}},registerImageListeners:function(){var onImgLoad=function(){this.popup.updateSize();if(this.popup.visible()&&this.popup.panMapIfOutOfView){this.popup.panIntoView();}
OpenLayers.Event.stopObserving(this.img,"load",this.img._onImageLoad);};var images=this.contentDiv.getElementsByTagName("img");for(var i=0,len=images.length;i<len;i++){var img=images[i];if(img.width==0||img.height==0){var context={'popup':this,'img':img};img._onImgLoad=OpenLayers.Function.bind(onImgLoad,context);OpenLayers.Event.observe(img,'load',img._onImgLoad);}}},getSafeContentSize:function(size){var safeContentSize=size.clone();var contentDivPadding=this.getContentDivPadding();var wPadding=contentDivPadding.left+contentDivPadding.right;var hPadding=contentDivPadding.top+contentDivPadding.bottom;this.fixPadding();wPadding+=this.padding.left+this.padding.right;hPadding+=this.padding.top+this.padding.bottom;if(this.closeDiv){var closeDivWidth=parseInt(this.closeDiv.style.width);wPadding+=closeDivWidth+contentDivPadding.right;}
if(this.minSize){safeContentSize.w=Math.max(safeContentSize.w,(this.minSize.w-wPadding));safeContentSize.h=Math.max(safeContentSize.h,(this.minSize.h-hPadding));}
if(this.maxSize){safeContentSize.w=Math.min(safeContentSize.w,(this.maxSize.w-wPadding));safeContentSize.h=Math.min(safeContentSize.h,(this.maxSize.h-hPadding));}
if(this.map&&this.map.size){var extraX=0,extraY=0;if(this.keepInMap&&!this.panMapIfOutOfView){var px=this.map.getPixelFromLonLat(this.lonlat);switch(this.relativePosition){case"tr":extraX=px.x;extraY=this.map.size.h-px.y;break;case"tl":extraX=this.map.size.w-px.x;extraY=this.map.size.h-px.y;break;case"bl":extraX=this.map.size.w-px.x;extraY=px.y;break;case"br":extraX=px.x;extraY=px.y;break;default:extraX=px.x;extraY=this.map.size.h-px.y;break;}}
var maxY=this.map.size.h-
this.map.paddingForPopups.top-
this.map.paddingForPopups.bottom-
hPadding-extraY;var maxX=this.map.size.w-
this.map.paddingForPopups.left-
this.map.paddingForPopups.right-
wPadding-extraX;safeContentSize.w=Math.min(safeContentSize.w,maxX);safeContentSize.h=Math.min(safeContentSize.h,maxY);}
return safeContentSize;},getContentDivPadding:function(){var contentDivPadding=this._contentDivPadding;if(!contentDivPadding){if(this.div.parentNode==null){this.div.style.display="none";document.body.appendChild(this.div);}
contentDivPadding=new OpenLayers.Bounds(OpenLayers.Element.getStyle(this.contentDiv,"padding-left"),OpenLayers.Element.getStyle(this.contentDiv,"padding-bottom"),OpenLayers.Element.getStyle(this.contentDiv,"padding-right"),OpenLayers.Element.getStyle(this.contentDiv,"padding-top"));this._contentDivPadding=contentDivPadding;if(this.div.parentNode==document.body){document.body.removeChild(this.div);this.div.style.display="";}}
return contentDivPadding;},addCloseBox:function(callback){this.closeDiv=OpenLayers.Util.createDiv(this.id+"_close",null,new OpenLayers.Size(17,17));this.closeDiv.className="olPopupCloseBox";var contentDivPadding=this.getContentDivPadding();this.closeDiv.style.right=contentDivPadding.right+"px";this.closeDiv.style.top=contentDivPadding.top+"px";this.groupDiv.appendChild(this.closeDiv);var closePopup=callback||function(e){this.hide();OpenLayers.Event.stop(e);};OpenLayers.Event.observe(this.closeDiv,"click",OpenLayers.Function.bindAsEventListener(closePopup,this));},panIntoView:function(){var mapSize=this.map.getSize();var origTL=this.map.getViewPortPxFromLayerPx(new OpenLayers.Pixel(parseInt(this.div.style.left),parseInt(this.div.style.top)));var newTL=origTL.clone();if(origTL.x<this.map.paddingForPopups.left){newTL.x=this.map.paddingForPopups.left;}else
if((origTL.x+this.size.w)>(mapSize.w-this.map.paddingForPopups.right)){newTL.x=mapSize.w-this.map.paddingForPopups.right-this.size.w;}
if(origTL.y<this.map.paddingForPopups.top){newTL.y=this.map.paddingForPopups.top;}else
if((origTL.y+this.size.h)>(mapSize.h-this.map.paddingForPopups.bottom)){newTL.y=mapSize.h-this.map.paddingForPopups.bottom-this.size.h;}
var dx=origTL.x-newTL.x;var dy=origTL.y-newTL.y;this.map.pan(dx,dy);},registerEvents:function(){this.events=new OpenLayers.Events(this,this.div,null,true);this.events.on({"mousedown":this.onmousedown,"mousemove":this.onmousemove,"mouseup":this.onmouseup,"click":this.onclick,"mouseout":this.onmouseout,"dblclick":this.ondblclick,scope:this});},onmousedown:function(evt){this.mousedown=true;OpenLayers.Event.stop(evt,true);},onmousemove:function(evt){if(this.mousedown){OpenLayers.Event.stop(evt,true);}},onmouseup:function(evt){if(this.mousedown){this.mousedown=false;OpenLayers.Event.stop(evt,true);}},onclick:function(evt){OpenLayers.Event.stop(evt,true);},onmouseout:function(evt){this.mousedown=false;},ondblclick:function(evt){OpenLayers.Event.stop(evt,true);},CLASS_NAME:"OpenLayers.Popup"});OpenLayers.Popup.WIDTH=200;OpenLayers.Popup.HEIGHT=200;OpenLayers.Popup.COLOR="white";OpenLayers.Popup.OPACITY=1;OpenLayers.Popup.BORDER="0px";OpenLayers.Protocol=OpenLayers.Class({format:null,options:null,autoDestroy:true,defaultFilter:null,initialize:function(options){options=options||{};OpenLayers.Util.extend(this,options);this.options=options;},mergeWithDefaultFilter:function(filter){var merged;if(filter&&this.defaultFilter){merged=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[this.defaultFilter,filter]});}else{merged=filter||this.defaultFilter||undefined;}
return merged;},destroy:function(){this.options=null;this.format=null;},read:function(options){options=options||{};options.filter=this.mergeWithDefaultFilter(options.filter);},create:function(){},update:function(){},"delete":function(){},commit:function(){},abort:function(response){},createCallback:function(method,response,options){return OpenLayers.Function.bind(function(){method.apply(this,[response,options]);},this);},CLASS_NAME:"OpenLayers.Protocol"});OpenLayers.Protocol.Response=OpenLayers.Class({code:null,requestType:null,last:true,features:null,reqFeatures:null,priv:null,initialize:function(options){OpenLayers.Util.extend(this,options);},success:function(){return this.code>0;},CLASS_NAME:"OpenLayers.Protocol.Response"});OpenLayers.Protocol.Response.SUCCESS=1;OpenLayers.Protocol.Response.FAILURE=0;OpenLayers.Renderer=OpenLayers.Class({container:null,root:null,extent:null,locked:false,size:null,resolution:null,map:null,initialize:function(containerID,options){this.container=OpenLayers.Util.getElement(containerID);},destroy:function(){this.container=null;this.extent=null;this.size=null;this.resolution=null;this.map=null;},supported:function(){return false;},setExtent:function(extent,resolutionChanged){this.extent=extent.clone();if(resolutionChanged){this.resolution=null;}},setSize:function(size){this.size=size.clone();this.resolution=null;},getResolution:function(){this.resolution=this.resolution||this.map.getResolution();return this.resolution;},drawFeature:function(feature,style){if(style==null){style=feature.style;}
if(feature.geometry){var bounds=feature.geometry.getBounds();if(bounds){if(!bounds.intersectsBounds(this.extent)){style={display:"none"};}
var rendered=this.drawGeometry(feature.geometry,style,feature.id);if(style.display!="none"&&style.label&&rendered!==false){var location=feature.geometry.getCentroid();if(style.labelXOffset||style.labelYOffset){xOffset=isNaN(style.labelXOffset)?0:style.labelXOffset;yOffset=isNaN(style.labelYOffset)?0:style.labelYOffset;var res=this.getResolution();location.move(xOffset*res,yOffset*res);}
this.drawText(feature.id,style,location);}else{this.removeText(feature.id);}
return rendered;}}},drawGeometry:function(geometry,style,featureId){},drawText:function(featureId,style,location){},removeText:function(featureId){},clear:function(){},getFeatureIdFromEvent:function(evt){},eraseFeatures:function(features){if(!(features instanceof Array)){features=[features];}
for(var i=0,len=features.length;i<len;++i){var feature=features[i];this.eraseGeometry(feature.geometry,feature.id);this.removeText(feature.id);}},eraseGeometry:function(geometry,featureId){},moveRoot:function(renderer){},getRenderLayerId:function(){return this.container.id;},applyDefaultSymbolizer:function(symbolizer){var result=OpenLayers.Util.extend({},OpenLayers.Renderer.defaultSymbolizer);if(symbolizer.stroke===false){delete result.strokeWidth;delete result.strokeColor;}
if(symbolizer.fill===false){delete result.fillColor;}
OpenLayers.Util.extend(result,symbolizer);return result;},CLASS_NAME:"OpenLayers.Renderer"});OpenLayers.Renderer.defaultSymbolizer={fillColor:"#000000",strokeColor:"#000000",strokeWidth:2,fillOpacity:1,strokeOpacity:1,pointRadius:0};OpenLayers.Strategy=OpenLayers.Class({layer:null,options:null,active:null,autoActivate:true,autoDestroy:true,initialize:function(options){OpenLayers.Util.extend(this,options);this.options=options;this.active=false;},destroy:function(){this.deactivate();this.layer=null;this.options=null;},setLayer:function(layer){this.layer=layer;},activate:function(){if(!this.active){this.active=true;return true;}
return false;},deactivate:function(){if(this.active){this.active=false;return true;}
return false;},CLASS_NAME:"OpenLayers.Strategy"});OpenLayers.Symbolizer=OpenLayers.Class({zIndex:0,initialize:function(config){OpenLayers.Util.extend(this,config);},clone:function(){var Type=eval(this.CLASS_NAME);return new Type(OpenLayers.Util.extend({},this));},CLASS_NAME:"OpenLayers.Symbolizer"});OpenLayers.Rico.Color=OpenLayers.Class({initialize:function(red,green,blue){this.rgb={r:red,g:green,b:blue};},setRed:function(r){this.rgb.r=r;},setGreen:function(g){this.rgb.g=g;},setBlue:function(b){this.rgb.b=b;},setHue:function(h){var hsb=this.asHSB();hsb.h=h;this.rgb=OpenLayers.Rico.Color.HSBtoRGB(hsb.h,hsb.s,hsb.b);},setSaturation:function(s){var hsb=this.asHSB();hsb.s=s;this.rgb=OpenLayers.Rico.Color.HSBtoRGB(hsb.h,hsb.s,hsb.b);},setBrightness:function(b){var hsb=this.asHSB();hsb.b=b;this.rgb=OpenLayers.Rico.Color.HSBtoRGB(hsb.h,hsb.s,hsb.b);},darken:function(percent){var hsb=this.asHSB();this.rgb=OpenLayers.Rico.Color.HSBtoRGB(hsb.h,hsb.s,Math.max(hsb.b-percent,0));},brighten:function(percent){var hsb=this.asHSB();this.rgb=OpenLayers.Rico.Color.HSBtoRGB(hsb.h,hsb.s,Math.min(hsb.b+percent,1));},blend:function(other){this.rgb.r=Math.floor((this.rgb.r+other.rgb.r)/2);this.rgb.g=Math.floor((this.rgb.g+other.rgb.g)/2);this.rgb.b=Math.floor((this.rgb.b+other.rgb.b)/2);},isBright:function(){var hsb=this.asHSB();return this.asHSB().b>0.5;},isDark:function(){return!this.isBright();},asRGB:function(){return"rgb("+this.rgb.r+","+this.rgb.g+","+this.rgb.b+")";},asHex:function(){return"#"+this.rgb.r.toColorPart()+this.rgb.g.toColorPart()+this.rgb.b.toColorPart();},asHSB:function(){return OpenLayers.Rico.Color.RGBtoHSB(this.rgb.r,this.rgb.g,this.rgb.b);},toString:function(){return this.asHex();}});OpenLayers.Rico.Color.createFromHex=function(hexCode){if(hexCode.length==4){var shortHexCode=hexCode;var hexCode='#';for(var i=1;i<4;i++){hexCode+=(shortHexCode.charAt(i)+
shortHexCode.charAt(i));}}
if(hexCode.indexOf('#')==0){hexCode=hexCode.substring(1);}
var red=hexCode.substring(0,2);var green=hexCode.substring(2,4);var blue=hexCode.substring(4,6);return new OpenLayers.Rico.Color(parseInt(red,16),parseInt(green,16),parseInt(blue,16));};OpenLayers.Rico.Color.createColorFromBackground=function(elem){var actualColor=RicoUtil.getElementsComputedStyle(OpenLayers.Util.getElement(elem),"backgroundColor","background-color");if(actualColor=="transparent"&&elem.parentNode){return OpenLayers.Rico.Color.createColorFromBackground(elem.parentNode);}
if(actualColor==null){return new OpenLayers.Rico.Color(255,255,255);}
if(actualColor.indexOf("rgb(")==0){var colors=actualColor.substring(4,actualColor.length-1);var colorArray=colors.split(",");return new OpenLayers.Rico.Color(parseInt(colorArray[0]),parseInt(colorArray[1]),parseInt(colorArray[2]));}
else if(actualColor.indexOf("#")==0){return OpenLayers.Rico.Color.createFromHex(actualColor);}
else{return new OpenLayers.Rico.Color(255,255,255);}};OpenLayers.Rico.Color.HSBtoRGB=function(hue,saturation,brightness){var red=0;var green=0;var blue=0;if(saturation==0){red=parseInt(brightness*255.0+0.5);green=red;blue=red;}
else{var h=(hue-Math.floor(hue))*6.0;var f=h-Math.floor(h);var p=brightness*(1.0-saturation);var q=brightness*(1.0-saturation*f);var t=brightness*(1.0-(saturation*(1.0-f)));switch(parseInt(h)){case 0:red=(brightness*255.0+0.5);green=(t*255.0+0.5);blue=(p*255.0+0.5);break;case 1:red=(q*255.0+0.5);green=(brightness*255.0+0.5);blue=(p*255.0+0.5);break;case 2:red=(p*255.0+0.5);green=(brightness*255.0+0.5);blue=(t*255.0+0.5);break;case 3:red=(p*255.0+0.5);green=(q*255.0+0.5);blue=(brightness*255.0+0.5);break;case 4:red=(t*255.0+0.5);green=(p*255.0+0.5);blue=(brightness*255.0+0.5);break;case 5:red=(brightness*255.0+0.5);green=(p*255.0+0.5);blue=(q*255.0+0.5);break;}}
return{r:parseInt(red),g:parseInt(green),b:parseInt(blue)};};OpenLayers.Rico.Color.RGBtoHSB=function(r,g,b){var hue;var saturation;var brightness;var cmax=(r>g)?r:g;if(b>cmax){cmax=b;}
var cmin=(r<g)?r:g;if(b<cmin){cmin=b;}
brightness=cmax/255.0;if(cmax!=0){saturation=(cmax-cmin)/cmax;}else{saturation=0;}
if(saturation==0){hue=0;}else{var redc=(cmax-r)/(cmax-cmin);var greenc=(cmax-g)/(cmax-cmin);var bluec=(cmax-b)/(cmax-cmin);if(r==cmax){hue=bluec-greenc;}else if(g==cmax){hue=2.0+redc-bluec;}else{hue=4.0+greenc-redc;}
hue=hue/6.0;if(hue<0){hue=hue+1.0;}}
return{h:hue,s:saturation,b:brightness};};OpenLayers.Bounds=OpenLayers.Class({left:null,bottom:null,right:null,top:null,centerLonLat:null,initialize:function(left,bottom,right,top){if(left!=null){this.left=OpenLayers.Util.toFloat(left);}
if(bottom!=null){this.bottom=OpenLayers.Util.toFloat(bottom);}
if(right!=null){this.right=OpenLayers.Util.toFloat(right);}
if(top!=null){this.top=OpenLayers.Util.toFloat(top);}},clone:function(){return new OpenLayers.Bounds(this.left,this.bottom,this.right,this.top);},equals:function(bounds){var equals=false;if(bounds!=null){equals=((this.left==bounds.left)&&(this.right==bounds.right)&&(this.top==bounds.top)&&(this.bottom==bounds.bottom));}
return equals;},toString:function(){return("left-bottom=("+this.left+","+this.bottom+")"
+" right-top=("+this.right+","+this.top+")");},toArray:function(reverseAxisOrder){if(reverseAxisOrder===true){return[this.bottom,this.left,this.top,this.right];}else{return[this.left,this.bottom,this.right,this.top];}},toBBOX:function(decimal,reverseAxisOrder){if(decimal==null){decimal=6;}
var mult=Math.pow(10,decimal);var xmin=Math.round(this.left*mult)/mult;var ymin=Math.round(this.bottom*mult)/mult;var xmax=Math.round(this.right*mult)/mult;var ymax=Math.round(this.top*mult)/mult;if(reverseAxisOrder===true){return ymin+","+xmin+","+ymax+","+xmax;}else{return xmin+","+ymin+","+xmax+","+ymax;}},toGeometry:function(){return new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing([new OpenLayers.Geometry.Point(this.left,this.bottom),new OpenLayers.Geometry.Point(this.right,this.bottom),new OpenLayers.Geometry.Point(this.right,this.top),new OpenLayers.Geometry.Point(this.left,this.top)])]);},getWidth:function(){return(this.right-this.left);},getHeight:function(){return(this.top-this.bottom);},getSize:function(){return new OpenLayers.Size(this.getWidth(),this.getHeight());},getCenterPixel:function(){return new OpenLayers.Pixel((this.left+this.right)/2,(this.bottom+this.top)/2);},getCenterLonLat:function(){if(!this.centerLonLat){this.centerLonLat=new OpenLayers.LonLat((this.left+this.right)/2,(this.bottom+this.top)/2);}
return this.centerLonLat;},scale:function(ratio,origin){if(origin==null){origin=this.getCenterLonLat();}
var origx,origy;if(origin.CLASS_NAME=="OpenLayers.LonLat"){origx=origin.lon;origy=origin.lat;}else{origx=origin.x;origy=origin.y;}
var left=(this.left-origx)*ratio+origx;var bottom=(this.bottom-origy)*ratio+origy;var right=(this.right-origx)*ratio+origx;var top=(this.top-origy)*ratio+origy;return new OpenLayers.Bounds(left,bottom,right,top);},add:function(x,y){if((x==null)||(y==null)){var msg=OpenLayers.i18n("boundsAddError");OpenLayers.Console.error(msg);return null;}
return new OpenLayers.Bounds(this.left+x,this.bottom+y,this.right+x,this.top+y);},extend:function(object){var bounds=null;if(object){switch(object.CLASS_NAME){case"OpenLayers.LonLat":bounds=new OpenLayers.Bounds(object.lon,object.lat,object.lon,object.lat);break;case"OpenLayers.Geometry.Point":bounds=new OpenLayers.Bounds(object.x,object.y,object.x,object.y);break;case"OpenLayers.Bounds":bounds=object;break;}
if(bounds){this.centerLonLat=null;if((this.left==null)||(bounds.left<this.left)){this.left=bounds.left;}
if((this.bottom==null)||(bounds.bottom<this.bottom)){this.bottom=bounds.bottom;}
if((this.right==null)||(bounds.right>this.right)){this.right=bounds.right;}
if((this.top==null)||(bounds.top>this.top)){this.top=bounds.top;}}}},containsLonLat:function(ll,inclusive){return this.contains(ll.lon,ll.lat,inclusive);},containsPixel:function(px,inclusive){return this.contains(px.x,px.y,inclusive);},contains:function(x,y,inclusive){if(inclusive==null){inclusive=true;}
if(x==null||y==null){return false;}
x=OpenLayers.Util.toFloat(x);y=OpenLayers.Util.toFloat(y);var contains=false;if(inclusive){contains=((x>=this.left)&&(x<=this.right)&&(y>=this.bottom)&&(y<=this.top));}else{contains=((x>this.left)&&(x<this.right)&&(y>this.bottom)&&(y<this.top));}
return contains;},intersectsBounds:function(bounds,inclusive){if(inclusive==null){inclusive=true;}
var intersects=false;var mightTouch=(this.left==bounds.right||this.right==bounds.left||this.top==bounds.bottom||this.bottom==bounds.top);if(inclusive||!mightTouch){var inBottom=(((bounds.bottom>=this.bottom)&&(bounds.bottom<=this.top))||((this.bottom>=bounds.bottom)&&(this.bottom<=bounds.top)));var inTop=(((bounds.top>=this.bottom)&&(bounds.top<=this.top))||((this.top>bounds.bottom)&&(this.top<bounds.top)));var inLeft=(((bounds.left>=this.left)&&(bounds.left<=this.right))||((this.left>=bounds.left)&&(this.left<=bounds.right)));var inRight=(((bounds.right>=this.left)&&(bounds.right<=this.right))||((this.right>=bounds.left)&&(this.right<=bounds.right)));intersects=((inBottom||inTop)&&(inLeft||inRight));}
return intersects;},containsBounds:function(bounds,partial,inclusive){if(partial==null){partial=false;}
if(inclusive==null){inclusive=true;}
var bottomLeft=this.contains(bounds.left,bounds.bottom,inclusive);var bottomRight=this.contains(bounds.right,bounds.bottom,inclusive);var topLeft=this.contains(bounds.left,bounds.top,inclusive);var topRight=this.contains(bounds.right,bounds.top,inclusive);return(partial)?(bottomLeft||bottomRight||topLeft||topRight):(bottomLeft&&bottomRight&&topLeft&&topRight);},determineQuadrant:function(lonlat){var quadrant="";var center=this.getCenterLonLat();quadrant+=(lonlat.lat<center.lat)?"b":"t";quadrant+=(lonlat.lon<center.lon)?"l":"r";return quadrant;},transform:function(source,dest){this.centerLonLat=null;var ll=OpenLayers.Projection.transform({'x':this.left,'y':this.bottom},source,dest);var lr=OpenLayers.Projection.transform({'x':this.right,'y':this.bottom},source,dest);var ul=OpenLayers.Projection.transform({'x':this.left,'y':this.top},source,dest);var ur=OpenLayers.Projection.transform({'x':this.right,'y':this.top},source,dest);this.left=Math.min(ll.x,ul.x);this.bottom=Math.min(ll.y,lr.y);this.right=Math.max(lr.x,ur.x);this.top=Math.max(ul.y,ur.y);return this;},wrapDateLine:function(maxExtent,options){options=options||{};var leftTolerance=options.leftTolerance||0;var rightTolerance=options.rightTolerance||0;var newBounds=this.clone();if(maxExtent){while(newBounds.left<maxExtent.left&&(newBounds.right-rightTolerance)<=maxExtent.left){newBounds=newBounds.add(maxExtent.getWidth(),0);}
while((newBounds.left+leftTolerance)>=maxExtent.right&&newBounds.right>maxExtent.right){newBounds=newBounds.add(-maxExtent.getWidth(),0);}}
return newBounds;},CLASS_NAME:"OpenLayers.Bounds"});OpenLayers.Bounds.fromString=function(str){var bounds=str.split(",");return OpenLayers.Bounds.fromArray(bounds);};OpenLayers.Bounds.fromArray=function(bbox){return new OpenLayers.Bounds(parseFloat(bbox[0]),parseFloat(bbox[1]),parseFloat(bbox[2]),parseFloat(bbox[3]));};OpenLayers.Bounds.fromSize=function(size){return new OpenLayers.Bounds(0,size.h,size.w,0);};OpenLayers.Bounds.oppositeQuadrant=function(quadrant){var opp="";opp+=(quadrant.charAt(0)=='t')?'b':'t';opp+=(quadrant.charAt(1)=='l')?'r':'l';return opp;};OpenLayers.LonLat=OpenLayers.Class({lon:0.0,lat:0.0,initialize:function(lon,lat){this.lon=OpenLayers.Util.toFloat(lon);this.lat=OpenLayers.Util.toFloat(lat);},toString:function(){return("lon="+this.lon+",lat="+this.lat);},toShortString:function(){return(this.lon+", "+this.lat);},clone:function(){return new OpenLayers.LonLat(this.lon,this.lat);},add:function(lon,lat){if((lon==null)||(lat==null)){var msg=OpenLayers.i18n("lonlatAddError");OpenLayers.Console.error(msg);return null;}
return new OpenLayers.LonLat(this.lon+OpenLayers.Util.toFloat(lon),this.lat+OpenLayers.Util.toFloat(lat));},equals:function(ll){var equals=false;if(ll!=null){equals=((this.lon==ll.lon&&this.lat==ll.lat)||(isNaN(this.lon)&&isNaN(this.lat)&&isNaN(ll.lon)&&isNaN(ll.lat)));}
return equals;},transform:function(source,dest){var point=OpenLayers.Projection.transform({'x':this.lon,'y':this.lat},source,dest);this.lon=point.x;this.lat=point.y;return this;},wrapDateLine:function(maxExtent){var newLonLat=this.clone();if(maxExtent){while(newLonLat.lon<maxExtent.left){newLonLat.lon+=maxExtent.getWidth();}
while(newLonLat.lon>maxExtent.right){newLonLat.lon-=maxExtent.getWidth();}}
return newLonLat;},CLASS_NAME:"OpenLayers.LonLat"});OpenLayers.LonLat.fromString=function(str){var pair=str.split(",");return new OpenLayers.LonLat(pair[0],pair[1]);};OpenLayers.Pixel=OpenLayers.Class({x:0.0,y:0.0,initialize:function(x,y){this.x=parseFloat(x);this.y=parseFloat(y);},toString:function(){return("x="+this.x+",y="+this.y);},clone:function(){return new OpenLayers.Pixel(this.x,this.y);},equals:function(px){var equals=false;if(px!=null){equals=((this.x==px.x&&this.y==px.y)||(isNaN(this.x)&&isNaN(this.y)&&isNaN(px.x)&&isNaN(px.y)));}
return equals;},add:function(x,y){if((x==null)||(y==null)){var msg=OpenLayers.i18n("pixelAddError");OpenLayers.Console.error(msg);return null;}
return new OpenLayers.Pixel(this.x+x,this.y+y);},offset:function(px){var newPx=this.clone();if(px){newPx=this.add(px.x,px.y);}
return newPx;},CLASS_NAME:"OpenLayers.Pixel"});OpenLayers.Control=OpenLayers.Class({id:null,map:null,div:null,type:null,allowSelection:false,displayClass:"",title:"",autoActivate:false,active:null,handler:null,eventListeners:null,events:null,EVENT_TYPES:["activate","deactivate"],initialize:function(options){this.displayClass=this.CLASS_NAME.replace("OpenLayers.","ol").replace(/\./g,"");OpenLayers.Util.extend(this,options);this.events=new OpenLayers.Events(this,null,this.EVENT_TYPES);if(this.eventListeners instanceof Object){this.events.on(this.eventListeners);}
if(this.id==null){this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");}},destroy:function(){if(this.events){if(this.eventListeners){this.events.un(this.eventListeners);}
this.events.destroy();this.events=null;}
this.eventListeners=null;if(this.handler){this.handler.destroy();this.handler=null;}
if(this.handlers){for(var key in this.handlers){if(this.handlers.hasOwnProperty(key)&&typeof this.handlers[key].destroy=="function"){this.handlers[key].destroy();}}
this.handlers=null;}
if(this.map){this.map.removeControl(this);this.map=null;}},setMap:function(map){this.map=map;if(this.handler){this.handler.setMap(map);}},draw:function(px){if(this.div==null){this.div=OpenLayers.Util.createDiv(this.id);this.div.className=this.displayClass;if(!this.allowSelection){this.div.className+=" olControlNoSelect";this.div.setAttribute("unselectable","on",0);this.div.onselectstart=OpenLayers.Function.False;}
if(this.title!=""){this.div.title=this.title;}}
if(px!=null){this.position=px.clone();}
this.moveTo(this.position);return this.div;},moveTo:function(px){if((px!=null)&&(this.div!=null)){this.div.style.left=px.x+"px";this.div.style.top=px.y+"px";}},activate:function(){if(this.active){return false;}
if(this.handler){this.handler.activate();}
this.active=true;if(this.map){OpenLayers.Element.addClass(this.map.viewPortDiv,this.displayClass.replace(/ /g,"")+"Active");}
this.events.triggerEvent("activate");return true;},deactivate:function(){if(this.active){if(this.handler){this.handler.deactivate();}
this.active=false;if(this.map){OpenLayers.Element.removeClass(this.map.viewPortDiv,this.displayClass.replace(/ /g,"")+"Active");}
this.events.triggerEvent("deactivate");return true;}
return false;},CLASS_NAME:"OpenLayers.Control"});OpenLayers.Control.TYPE_BUTTON=1;OpenLayers.Control.TYPE_TOGGLE=2;OpenLayers.Control.TYPE_TOOL=3;OpenLayers.Lang={code:null,defaultCode:"en",getCode:function(){if(!OpenLayers.Lang.code){OpenLayers.Lang.setCode();}
return OpenLayers.Lang.code;},setCode:function(code){var lang;if(!code){code=(OpenLayers.Util.getBrowserName()=="msie")?navigator.userLanguage:navigator.language;}
var parts=code.split('-');parts[0]=parts[0].toLowerCase();if(typeof OpenLayers.Lang[parts[0]]=="object"){lang=parts[0];}
if(parts[1]){var testLang=parts[0]+'-'+parts[1].toUpperCase();if(typeof OpenLayers.Lang[testLang]=="object"){lang=testLang;}}
if(!lang){OpenLayers.Console.warn('Failed to find OpenLayers.Lang.'+parts.join("-")+' dictionary, falling back to default language');lang=OpenLayers.Lang.defaultCode;}
OpenLayers.Lang.code=lang;},translate:function(key,context){var dictionary=OpenLayers.Lang[OpenLayers.Lang.getCode()];var message=dictionary[key];if(!message){message=key;}
if(context){message=OpenLayers.String.format(message,context);}
return message;}};OpenLayers.i18n=OpenLayers.Lang.translate;OpenLayers.Popup.Anchored=OpenLayers.Class(OpenLayers.Popup,{relativePosition:null,keepInMap:true,anchor:null,initialize:function(id,lonlat,contentSize,contentHTML,anchor,closeBox,closeBoxCallback){var newArguments=[id,lonlat,contentSize,contentHTML,closeBox,closeBoxCallback];OpenLayers.Popup.prototype.initialize.apply(this,newArguments);this.anchor=(anchor!=null)?anchor:{size:new OpenLayers.Size(0,0),offset:new OpenLayers.Pixel(0,0)};},destroy:function(){this.anchor=null;this.relativePosition=null;OpenLayers.Popup.prototype.destroy.apply(this,arguments);},show:function(){this.updatePosition();OpenLayers.Popup.prototype.show.apply(this,arguments);},moveTo:function(px){var oldRelativePosition=this.relativePosition;this.relativePosition=this.calculateRelativePosition(px);var newPx=this.calculateNewPx(px);var newArguments=new Array(newPx);OpenLayers.Popup.prototype.moveTo.apply(this,newArguments);if(this.relativePosition!=oldRelativePosition){this.updateRelativePosition();}},setSize:function(contentSize){OpenLayers.Popup.prototype.setSize.apply(this,arguments);if((this.lonlat)&&(this.map)){var px=this.map.getLayerPxFromLonLat(this.lonlat);this.moveTo(px);}},calculateRelativePosition:function(px){var lonlat=this.map.getLonLatFromLayerPx(px);var extent=this.map.getExtent();var quadrant=extent.determineQuadrant(lonlat);return OpenLayers.Bounds.oppositeQuadrant(quadrant);},updateRelativePosition:function(){},calculateNewPx:function(px){var newPx=px.offset(this.anchor.offset);var size=this.size||this.contentSize;var top=(this.relativePosition.charAt(0)=='t');newPx.y+=(top)?-(size.h+this.anchor.size.h):this.anchor.size.h;var left=(this.relativePosition.charAt(1)=='l');newPx.x+=(left)?-(size.w+this.anchor.size.w):this.anchor.size.w;return newPx;},CLASS_NAME:"OpenLayers.Popup.Anchored"});OpenLayers.Protocol.SOS=function(options){options=OpenLayers.Util.applyDefaults(options,OpenLayers.Protocol.SOS.DEFAULTS);var cls=OpenLayers.Protocol.SOS["v"+options.version.replace(/\./g,"_")];if(!cls){throw"Unsupported SOS version: "+options.version;}
return new cls(options);};OpenLayers.Protocol.SOS.DEFAULTS={"version":"1.0.0"};OpenLayers.Protocol.SQL=OpenLayers.Class(OpenLayers.Protocol,{databaseName:'ol',tableName:"ol_vector_features",postReadFiltering:true,initialize:function(options){OpenLayers.Protocol.prototype.initialize.apply(this,[options]);},destroy:function(){OpenLayers.Protocol.prototype.destroy.apply(this);},supported:function(){return false;},evaluateFilter:function(feature,filter){return filter&&this.postReadFiltering?filter.evaluate(feature):true;},CLASS_NAME:"OpenLayers.Protocol.SQL"});OpenLayers.Protocol.WFS=function(options){options=OpenLayers.Util.applyDefaults(options,OpenLayers.Protocol.WFS.DEFAULTS);var cls=OpenLayers.Protocol.WFS["v"+options.version.replace(/\./g,"_")];if(!cls){throw"Unsupported WFS version: "+options.version;}
return new cls(options);};OpenLayers.Protocol.WFS.fromWMSLayer=function(layer,options){var typeName,featurePrefix;var param=layer.params["LAYERS"];var parts=(param instanceof Array?param[0]:param).split(":");if(parts.length>1){featurePrefix=parts[0];}
typeName=parts.pop();var protocolOptions={url:layer.url,featureType:typeName,featurePrefix:featurePrefix,srsName:layer.projection&&layer.projection.getCode()||layer.map&&layer.map.getProjectionObject().getCode(),version:"1.1.0"};return new OpenLayers.Protocol.WFS(OpenLayers.Util.applyDefaults(options,protocolOptions));};OpenLayers.Protocol.WFS.DEFAULTS={"version":"1.0.0"};OpenLayers.Renderer.Canvas=OpenLayers.Class(OpenLayers.Renderer,{canvas:null,features:null,initialize:function(containerID){OpenLayers.Renderer.prototype.initialize.apply(this,arguments);this.root=document.createElement("canvas");this.container.appendChild(this.root);this.canvas=this.root.getContext("2d");this.features={};},eraseGeometry:function(geometry,featureId){this.eraseFeatures(this.features[featureId][0]);},supported:function(){var canvas=document.createElement("canvas");return!!canvas.getContext;},setExtent:function(extent){this.extent=extent.clone();this.resolution=null;this.redraw();},setSize:function(size){this.size=size.clone();this.root.style.width=size.w+"px";this.root.style.height=size.h+"px";this.root.width=size.w;this.root.height=size.h;this.resolution=null;},drawFeature:function(feature,style){style=style||feature.style;style=this.applyDefaultSymbolizer(style);this.features[feature.id]=[feature,style];this.redraw();},drawGeometry:function(geometry,style){var className=geometry.CLASS_NAME;if((className=="OpenLayers.Geometry.Collection")||(className=="OpenLayers.Geometry.MultiPoint")||(className=="OpenLayers.Geometry.MultiLineString")||(className=="OpenLayers.Geometry.MultiPolygon")){for(var i=0;i<geometry.components.length;i++){this.drawGeometry(geometry.components[i],style);}
return;}
switch(geometry.CLASS_NAME){case"OpenLayers.Geometry.Point":this.drawPoint(geometry,style);break;case"OpenLayers.Geometry.LineString":this.drawLineString(geometry,style);break;case"OpenLayers.Geometry.LinearRing":this.drawLinearRing(geometry,style);break;case"OpenLayers.Geometry.Polygon":this.drawPolygon(geometry,style);break;default:break;}},drawExternalGraphic:function(pt,style){var img=new Image();if(style.graphicTitle){img.title=style.graphicTitle;}
var width=style.graphicWidth||style.graphicHeight;var height=style.graphicHeight||style.graphicWidth;width=width?width:style.pointRadius*2;height=height?height:style.pointRadius*2;var xOffset=(style.graphicXOffset!=undefined)?style.graphicXOffset:-(0.5*width);var yOffset=(style.graphicYOffset!=undefined)?style.graphicYOffset:-(0.5*height);var context={img:img,x:(pt[0]+xOffset),y:(pt[1]+yOffset),width:width,height:height,opacity:style.graphicOpacity||style.fillOpacity,canvas:this.canvas};img.onload=OpenLayers.Function.bind(function(){this.canvas.globalAlpha=this.opacity;this.canvas.drawImage(this.img,this.x,this.y,this.width,this.height);},context);img.src=style.externalGraphic;},setCanvasStyle:function(type,style){if(type=="fill"){this.canvas.globalAlpha=style['fillOpacity'];this.canvas.fillStyle=style['fillColor'];}else if(type=="stroke"){this.canvas.globalAlpha=style['strokeOpacity'];this.canvas.strokeStyle=style['strokeColor'];this.canvas.lineWidth=style['strokeWidth'];}else{this.canvas.globalAlpha=0;this.canvas.lineWidth=1;}},drawPoint:function(geometry,style){if(style.graphic!==false){var pt=this.getLocalXY(geometry);if(style.externalGraphic){this.drawExternalGraphic(pt,style);}else{if(style.fill!==false){this.setCanvasStyle("fill",style);this.canvas.beginPath();this.canvas.arc(pt[0],pt[1],style.pointRadius,0,Math.PI*2,true);this.canvas.fill();}
if(style.stroke!==false){this.setCanvasStyle("stroke",style);this.canvas.beginPath();this.canvas.arc(pt[0],pt[1],style.pointRadius,0,Math.PI*2,true);this.canvas.stroke();this.setCanvasStyle("reset");}}}},drawLineString:function(geometry,style){if(style.stroke!==false){this.setCanvasStyle("stroke",style);this.canvas.beginPath();var start=this.getLocalXY(geometry.components[0]);this.canvas.moveTo(start[0],start[1]);for(var i=1;i<geometry.components.length;i++){var pt=this.getLocalXY(geometry.components[i]);this.canvas.lineTo(pt[0],pt[1]);}
this.canvas.stroke();}
this.setCanvasStyle("reset");},drawLinearRing:function(geometry,style){if(style.fill!==false){this.setCanvasStyle("fill",style);this.canvas.beginPath();var start=this.getLocalXY(geometry.components[0]);this.canvas.moveTo(start[0],start[1]);for(var i=1;i<geometry.components.length-1;i++){var pt=this.getLocalXY(geometry.components[i]);this.canvas.lineTo(pt[0],pt[1]);}
this.canvas.fill();}
if(style.stroke!==false){this.setCanvasStyle("stroke",style);this.canvas.beginPath();var start=this.getLocalXY(geometry.components[0]);this.canvas.moveTo(start[0],start[1]);for(var i=1;i<geometry.components.length;i++){var pt=this.getLocalXY(geometry.components[i]);this.canvas.lineTo(pt[0],pt[1]);}
this.canvas.stroke();}
this.setCanvasStyle("reset");},drawPolygon:function(geometry,style){this.drawLinearRing(geometry.components[0],style);for(var i=1;i<geometry.components.length;i++){this.drawLinearRing(geometry.components[i],{fillOpacity:0,strokeWidth:0,strokeOpacity:0,strokeColor:'#000000',fillColor:'#000000'});}},drawText:function(location,style){style=OpenLayers.Util.extend({fontColor:"#000000",labelAlign:"cm"},style);var pt=this.getLocalXY(location);this.setCanvasStyle("reset");this.canvas.fillStyle=style.fontColor;this.canvas.globalAlpha=style.fontOpacity||1.0;var fontStyle=style.fontWeight+" "+style.fontSize+" "+style.fontFamily;if(this.canvas.fillText){var labelAlign=OpenLayers.Renderer.Canvas.LABEL_ALIGN[style.labelAlign[0]]||"center";this.canvas.font=fontStyle;this.canvas.textAlign=labelAlign;this.canvas.fillText(style.label,pt[0],pt[1]);}else if(this.canvas.mozDrawText){this.canvas.mozTextStyle=fontStyle;var len=this.canvas.mozMeasureText(style.label);switch(style.labelAlign[0]){case"l":break;case"r":pt[0]-=len;break;case"c":default:pt[0]-=len/2;}
this.canvas.translate(pt[0],pt[1]);this.canvas.mozDrawText(style.label);this.canvas.translate(-1*pt[0],-1*pt[1]);}
this.setCanvasStyle("reset");},getLocalXY:function(point){var resolution=this.getResolution();var extent=this.extent;var x=(point.x/resolution+(-extent.left/resolution));var y=((extent.top/resolution)-point.y/resolution);return[x,y];},clear:function(){this.canvas.clearRect(0,0,this.root.width,this.root.height);this.features={};},getFeatureIdFromEvent:function(evt){var loc=this.map.getLonLatFromPixel(evt.xy);var resolution=this.getResolution();var bounds=new OpenLayers.Bounds(loc.lon-resolution*5,loc.lat-resolution*5,loc.lon+resolution*5,loc.lat+resolution*5);var geom=bounds.toGeometry();for(var feat in this.features){if(!this.features.hasOwnProperty(feat)){continue;}
if(this.features[feat][0].geometry.intersects(geom)){return feat;}}
return null;},eraseFeatures:function(features){if(!(features instanceof Array)){features=[features];}
for(var i=0;i<features.length;++i){delete this.features[features[i].id];}
this.redraw();},redraw:function(){if(!this.locked){this.canvas.clearRect(0,0,this.root.width,this.root.height);var labelMap=[];var feature,style;for(var id in this.features){if(!this.features.hasOwnProperty(id)){continue;}
feature=this.features[id][0];style=this.features[id][1];if(!feature.geometry){continue;}
this.drawGeometry(feature.geometry,style);if(style.label){labelMap.push([feature,style]);}}
var item;for(var i=0,len=labelMap.length;i<len;++i){item=labelMap[i];this.drawText(item[0].geometry.getCentroid(),item[1]);}}},CLASS_NAME:"OpenLayers.Renderer.Canvas"});OpenLayers.Renderer.Canvas.LABEL_ALIGN={"l":"left","r":"right"};OpenLayers.ElementsIndexer=OpenLayers.Class({maxZIndex:null,order:null,indices:null,compare:null,initialize:function(yOrdering){this.compare=yOrdering?OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER_Y_ORDER:OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER_DRAWING_ORDER;this.order=[];this.indices={};this.maxZIndex=0;},insert:function(newNode){if(this.exists(newNode)){this.remove(newNode);}
var nodeId=newNode.id;this.determineZIndex(newNode);var leftIndex=-1;var rightIndex=this.order.length;var middle;while(rightIndex-leftIndex>1){middle=parseInt((leftIndex+rightIndex)/2);var placement=this.compare(this,newNode,OpenLayers.Util.getElement(this.order[middle]));if(placement>0){leftIndex=middle;}else{rightIndex=middle;}}
this.order.splice(rightIndex,0,nodeId);this.indices[nodeId]=this.getZIndex(newNode);return this.getNextElement(rightIndex);},remove:function(node){var nodeId=node.id;var arrayIndex=OpenLayers.Util.indexOf(this.order,nodeId);if(arrayIndex>=0){this.order.splice(arrayIndex,1);delete this.indices[nodeId];if(this.order.length>0){var lastId=this.order[this.order.length-1];this.maxZIndex=this.indices[lastId];}else{this.maxZIndex=0;}}},clear:function(){this.order=[];this.indices={};this.maxZIndex=0;},exists:function(node){return(this.indices[node.id]!=null);},getZIndex:function(node){return node._style.graphicZIndex;},determineZIndex:function(node){var zIndex=node._style.graphicZIndex;if(zIndex==null){zIndex=this.maxZIndex;node._style.graphicZIndex=zIndex;}else if(zIndex>this.maxZIndex){this.maxZIndex=zIndex;}},getNextElement:function(index){var nextIndex=index+1;if(nextIndex<this.order.length){var nextElement=OpenLayers.Util.getElement(this.order[nextIndex]);if(nextElement==undefined){nextElement=this.getNextElement(nextIndex);}
return nextElement;}else{return null;}},CLASS_NAME:"OpenLayers.ElementsIndexer"});OpenLayers.ElementsIndexer.IndexingMethods={Z_ORDER:function(indexer,newNode,nextNode){var newZIndex=indexer.getZIndex(newNode);var returnVal=0;if(nextNode){var nextZIndex=indexer.getZIndex(nextNode);returnVal=newZIndex-nextZIndex;}
return returnVal;},Z_ORDER_DRAWING_ORDER:function(indexer,newNode,nextNode){var returnVal=OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER(indexer,newNode,nextNode);if(nextNode&&returnVal==0){returnVal=1;}
return returnVal;},Z_ORDER_Y_ORDER:function(indexer,newNode,nextNode){var returnVal=OpenLayers.ElementsIndexer.IndexingMethods.Z_ORDER(indexer,newNode,nextNode);if(nextNode&&returnVal===0){var result=nextNode._boundsBottom-newNode._boundsBottom;returnVal=(result===0)?1:result;}
return returnVal;}};OpenLayers.Renderer.Elements=OpenLayers.Class(OpenLayers.Renderer,{rendererRoot:null,root:null,vectorRoot:null,textRoot:null,xmlns:null,indexer:null,BACKGROUND_ID_SUFFIX:"_background",LABEL_ID_SUFFIX:"_label",initialize:function(containerID,options){OpenLayers.Renderer.prototype.initialize.apply(this,arguments);this.rendererRoot=this.createRenderRoot();this.root=this.createRoot("_root");this.vectorRoot=this.createRoot("_vroot");this.textRoot=this.createRoot("_troot");this.root.appendChild(this.vectorRoot);this.root.appendChild(this.textRoot);this.rendererRoot.appendChild(this.root);this.container.appendChild(this.rendererRoot);if(options&&(options.zIndexing||options.yOrdering)){this.indexer=new OpenLayers.ElementsIndexer(options.yOrdering);}},destroy:function(){this.clear();this.rendererRoot=null;this.root=null;this.xmlns=null;OpenLayers.Renderer.prototype.destroy.apply(this,arguments);},clear:function(){var child;var root=this.vectorRoot;if(root){while(child=root.firstChild){root.removeChild(child);}}
root=this.textRoot;if(root){while(child=root.firstChild){root.removeChild(child);}}
if(this.indexer){this.indexer.clear();}},getNodeType:function(geometry,style){},drawGeometry:function(geometry,style,featureId){var className=geometry.CLASS_NAME;var rendered=true;if((className=="OpenLayers.Geometry.Collection")||(className=="OpenLayers.Geometry.MultiPoint")||(className=="OpenLayers.Geometry.MultiLineString")||(className=="OpenLayers.Geometry.MultiPolygon")){for(var i=0,len=geometry.components.length;i<len;i++){rendered=this.drawGeometry(geometry.components[i],style,featureId)&&rendered;}
return rendered;};rendered=false;if(style.display!="none"){if(style.backgroundGraphic){this.redrawBackgroundNode(geometry.id,geometry,style,featureId);}
rendered=this.redrawNode(geometry.id,geometry,style,featureId);}
if(rendered==false){var node=document.getElementById(geometry.id);if(node){if(node._style.backgroundGraphic){node.parentNode.removeChild(document.getElementById(geometry.id+this.BACKGROUND_ID_SUFFIX));}
node.parentNode.removeChild(node);}}
return rendered;},redrawNode:function(id,geometry,style,featureId){style=this.applyDefaultSymbolizer(style);var node=this.nodeFactory(id,this.getNodeType(geometry,style));node._featureId=featureId;node._boundsBottom=geometry.getBounds().bottom;node._geometryClass=geometry.CLASS_NAME;node._style=style;var drawResult=this.drawGeometryNode(node,geometry,style);if(drawResult===false){return false;}
node=drawResult.node;if(this.indexer){var insert=this.indexer.insert(node);if(insert){this.vectorRoot.insertBefore(node,insert);}else{this.vectorRoot.appendChild(node);}}else{if(node.parentNode!==this.vectorRoot){this.vectorRoot.appendChild(node);}}
this.postDraw(node);return drawResult.complete;},redrawBackgroundNode:function(id,geometry,style,featureId){var backgroundStyle=OpenLayers.Util.extend({},style);backgroundStyle.externalGraphic=backgroundStyle.backgroundGraphic;backgroundStyle.graphicXOffset=backgroundStyle.backgroundXOffset;backgroundStyle.graphicYOffset=backgroundStyle.backgroundYOffset;backgroundStyle.graphicZIndex=backgroundStyle.backgroundGraphicZIndex;backgroundStyle.graphicWidth=backgroundStyle.backgroundWidth||backgroundStyle.graphicWidth;backgroundStyle.graphicHeight=backgroundStyle.backgroundHeight||backgroundStyle.graphicHeight;backgroundStyle.backgroundGraphic=null;backgroundStyle.backgroundXOffset=null;backgroundStyle.backgroundYOffset=null;backgroundStyle.backgroundGraphicZIndex=null;return this.redrawNode(id+this.BACKGROUND_ID_SUFFIX,geometry,backgroundStyle,null);},drawGeometryNode:function(node,geometry,style){style=style||node._style;var options={'isFilled':style.fill===undefined?true:style.fill,'isStroked':style.stroke===undefined?!!style.strokeWidth:style.stroke};var drawn;switch(geometry.CLASS_NAME){case"OpenLayers.Geometry.Point":if(style.graphic===false){options.isFilled=false;options.isStroked=false;}
drawn=this.drawPoint(node,geometry);break;case"OpenLayers.Geometry.LineString":options.isFilled=false;drawn=this.drawLineString(node,geometry);break;case"OpenLayers.Geometry.LinearRing":drawn=this.drawLinearRing(node,geometry);break;case"OpenLayers.Geometry.Polygon":drawn=this.drawPolygon(node,geometry);break;case"OpenLayers.Geometry.Surface":drawn=this.drawSurface(node,geometry);break;case"OpenLayers.Geometry.Rectangle":drawn=this.drawRectangle(node,geometry);break;default:break;}
node._options=options;if(drawn!=false){return{node:this.setStyle(node,style,options,geometry),complete:drawn};}else{return false;}},postDraw:function(node){},drawPoint:function(node,geometry){},drawLineString:function(node,geometry){},drawLinearRing:function(node,geometry){},drawPolygon:function(node,geometry){},drawRectangle:function(node,geometry){},drawCircle:function(node,geometry){},drawSurface:function(node,geometry){},removeText:function(featureId){var label=document.getElementById(featureId+this.LABEL_ID_SUFFIX);if(label){this.textRoot.removeChild(label);}},getFeatureIdFromEvent:function(evt){var target=evt.target;var useElement=target&&target.correspondingUseElement;var node=useElement?useElement:(target||evt.srcElement);var featureId=node._featureId;return featureId;},eraseGeometry:function(geometry,featureId){if((geometry.CLASS_NAME=="OpenLayers.Geometry.MultiPoint")||(geometry.CLASS_NAME=="OpenLayers.Geometry.MultiLineString")||(geometry.CLASS_NAME=="OpenLayers.Geometry.MultiPolygon")||(geometry.CLASS_NAME=="OpenLayers.Geometry.Collection")){for(var i=0,len=geometry.components.length;i<len;i++){this.eraseGeometry(geometry.components[i],featureId);}}else{var element=OpenLayers.Util.getElement(geometry.id);if(element&&element.parentNode){if(element.geometry){element.geometry.destroy();element.geometry=null;}
element.parentNode.removeChild(element);if(this.indexer){this.indexer.remove(element);}
if(element._style.backgroundGraphic){var backgroundId=geometry.id+this.BACKGROUND_ID_SUFFIX;var bElem=OpenLayers.Util.getElement(backgroundId);if(bElem&&bElem.parentNode){bElem.parentNode.removeChild(bElem);}}}}},nodeFactory:function(id,type){var node=OpenLayers.Util.getElement(id);if(node){if(!this.nodeTypeCompare(node,type)){node.parentNode.removeChild(node);node=this.nodeFactory(id,type);}}else{node=this.createNode(type,id);}
return node;},nodeTypeCompare:function(node,type){},createNode:function(type,id){},moveRoot:function(renderer){var root=this.root;if(renderer.root.parentNode==this.rendererRoot){root=renderer.root;}
root.parentNode.removeChild(root);renderer.rendererRoot.appendChild(root);},getRenderLayerId:function(){return this.root.parentNode.parentNode.id;},isComplexSymbol:function(graphicName){return(graphicName!="circle")&&!!graphicName;},CLASS_NAME:"OpenLayers.Renderer.Elements"});OpenLayers.Renderer.symbol={"star":[350,75,379,161,469,161,397,215,423,301,350,250,277,301,303,215,231,161,321,161,350,75],"cross":[4,0,6,0,6,4,10,4,10,6,6,6,6,10,4,10,4,6,0,6,0,4,4,4,4,0],"x":[0,0,25,0,50,35,75,0,100,0,65,50,100,100,75,100,50,65,25,100,0,100,35,50,0,0],"square":[0,0,0,1,1,1,1,0,0,0],"triangle":[0,10,10,10,5,0,0,10]};OpenLayers.Strategy.Cluster=OpenLayers.Class(OpenLayers.Strategy,{distance:20,threshold:null,features:null,clusters:null,clustering:false,resolution:null,initialize:function(options){OpenLayers.Strategy.prototype.initialize.apply(this,[options]);},activate:function(){var activated=OpenLayers.Strategy.prototype.activate.call(this);if(activated){this.layer.events.on({"beforefeaturesadded":this.cacheFeatures,"moveend":this.cluster,scope:this});}
return activated;},deactivate:function(){var deactivated=OpenLayers.Strategy.prototype.deactivate.call(this);if(deactivated){this.clearCache();this.layer.events.un({"beforefeaturesadded":this.cacheFeatures,"moveend":this.cluster,scope:this});}
return deactivated;},cacheFeatures:function(event){var propagate=true;if(!this.clustering){this.clearCache();this.features=event.features;this.cluster();propagate=false;}
return propagate;},clearCache:function(){this.features=null;},cluster:function(event){if((!event||event.zoomChanged)&&this.features){var resolution=this.layer.map.getResolution();if(resolution!=this.resolution||!this.clustersExist()){this.resolution=resolution;var clusters=[];var feature,clustered,cluster;for(var i=0;i<this.features.length;++i){feature=this.features[i];if(feature.geometry){clustered=false;for(var j=clusters.length-1;j>=0;--j){cluster=clusters[j];if(this.shouldCluster(cluster,feature)){this.addToCluster(cluster,feature);clustered=true;break;}}
if(!clustered){clusters.push(this.createCluster(this.features[i]));}}}
this.layer.removeAllFeatures();if(clusters.length>0){if(this.threshold>1){var clone=clusters.slice();clusters=[];var candidate;for(var i=0,len=clone.length;i<len;++i){candidate=clone[i];if(candidate.attributes.count<this.threshold){Array.prototype.push.apply(clusters,candidate.cluster);}else{clusters.push(candidate);}}}
this.clustering=true;this.layer.addFeatures(clusters);this.clustering=false;}
this.clusters=clusters;}}},clustersExist:function(){var exist=false;if(this.clusters&&this.clusters.length>0&&this.clusters.length==this.layer.features.length){exist=true;for(var i=0;i<this.clusters.length;++i){if(this.clusters[i]!=this.layer.features[i]){exist=false;break;}}}
return exist;},shouldCluster:function(cluster,feature){var cc=cluster.geometry.getBounds().getCenterLonLat();var fc=feature.geometry.getBounds().getCenterLonLat();var distance=(Math.sqrt(Math.pow((cc.lon-fc.lon),2)+Math.pow((cc.lat-fc.lat),2))/this.resolution);return(distance<=this.distance);},addToCluster:function(cluster,feature){cluster.cluster.push(feature);cluster.attributes.count+=1;},createCluster:function(feature){var center=feature.geometry.getBounds().getCenterLonLat();var cluster=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(center.lon,center.lat),{count:1});cluster.cluster=[feature];return cluster;},CLASS_NAME:"OpenLayers.Strategy.Cluster"});OpenLayers.Strategy.Fixed=OpenLayers.Class(OpenLayers.Strategy,{preload:false,initialize:function(options){OpenLayers.Strategy.prototype.initialize.apply(this,[options]);},destroy:function(){OpenLayers.Strategy.prototype.destroy.apply(this,arguments);},activate:function(){if(OpenLayers.Strategy.prototype.activate.apply(this,arguments)){this.layer.events.on({"refresh":this.load,scope:this});if(this.layer.visibility==true||this.preload){this.load();}else{this.layer.events.on({"visibilitychanged":this.load,scope:this});}
return true;}
return false;},deactivate:function(){var deactivated=OpenLayers.Strategy.prototype.deactivate.call(this);if(deactivated){this.layer.events.un({"refresh":this.load,"visibilitychanged":this.load,scope:this});}
return deactivated;},load:function(options){this.layer.events.triggerEvent("loadstart");this.layer.protocol.read(OpenLayers.Util.applyDefaults({callback:this.merge,filter:this.layer.filter,scope:this},options));this.layer.events.un({"visibilitychanged":this.load,scope:this});},merge:function(resp){this.layer.destroyFeatures();var features=resp.features;if(features&&features.length>0){var remote=this.layer.projection;var local=this.layer.map.getProjectionObject();if(!local.equals(remote)){var geom;for(var i=0,len=features.length;i<len;++i){geom=features[i].geometry;if(geom){geom.transform(remote,local);}}}
this.layer.addFeatures(features);}
this.layer.events.triggerEvent("loadend");},CLASS_NAME:"OpenLayers.Strategy.Fixed"});OpenLayers.Strategy.Paging=OpenLayers.Class(OpenLayers.Strategy,{features:null,length:10,num:null,paging:false,initialize:function(options){OpenLayers.Strategy.prototype.initialize.apply(this,[options]);},activate:function(){var activated=OpenLayers.Strategy.prototype.activate.call(this);if(activated){this.layer.events.on({"beforefeaturesadded":this.cacheFeatures,scope:this});}
return activated;},deactivate:function(){var deactivated=OpenLayers.Strategy.prototype.deactivate.call(this);if(deactivated){this.clearCache();this.layer.events.un({"beforefeaturesadded":this.cacheFeatures,scope:this});}
return deactivated;},cacheFeatures:function(event){if(!this.paging){this.clearCache();this.features=event.features;this.pageNext(event);}},clearCache:function(){if(this.features){for(var i=0;i<this.features.length;++i){this.features[i].destroy();}}
this.features=null;this.num=null;},pageCount:function(){var numFeatures=this.features?this.features.length:0;return Math.ceil(numFeatures/this.length);},pageNum:function(){return this.num;},pageLength:function(newLength){if(newLength&&newLength>0){this.length=newLength;}
return this.length;},pageNext:function(event){var changed=false;if(this.features){if(this.num===null){this.num=-1;}
var start=(this.num+1)*this.length;changed=this.page(start,event);}
return changed;},pagePrevious:function(){var changed=false;if(this.features){if(this.num===null){this.num=this.pageCount();}
var start=(this.num-1)*this.length;changed=this.page(start);}
return changed;},page:function(start,event){var changed=false;if(this.features){if(start>=0&&start<this.features.length){var num=Math.floor(start/this.length);if(num!=this.num){this.paging=true;var features=this.features.slice(start,start+this.length);this.layer.removeFeatures(this.layer.features);this.num=num;if(event&&event.features){event.features=features;}else{this.layer.addFeatures(features);}
this.paging=false;changed=true;}}}
return changed;},CLASS_NAME:"OpenLayers.Strategy.Paging"});OpenLayers.Strategy.Refresh=OpenLayers.Class(OpenLayers.Strategy,{force:false,interval:0,timer:null,initialize:function(options){OpenLayers.Strategy.prototype.initialize.apply(this,[options]);},activate:function(){var activated=OpenLayers.Strategy.prototype.activate.call(this);if(activated){if(this.layer.visibility===true){this.start();}
this.layer.events.on({"visibilitychanged":this.reset,scope:this});}
return activated;},deactivate:function(){var deactivated=OpenLayers.Strategy.prototype.deactivate.call(this);if(deactivated){this.stop();}
return deactivated;},reset:function(){if(this.layer.visibility===true){this.start();}else{this.stop();}},start:function(){if(this.interval&&typeof this.interval==="number"&&this.interval>0){this.timer=window.setInterval(OpenLayers.Function.bind(this.refresh,this),this.interval);}},refresh:function(){if(this.layer&&this.layer.refresh&&typeof this.layer.refresh=="function"){this.layer.refresh({force:this.force});}},stop:function(){if(this.timer!==null){window.clearInterval(this.timer);this.timer=null;}},CLASS_NAME:"OpenLayers.Strategy.Refresh"});OpenLayers.Strategy.Save=OpenLayers.Class(OpenLayers.Strategy,{EVENT_TYPES:["start","success","fail"],events:null,auto:false,timer:null,initialize:function(options){OpenLayers.Strategy.prototype.initialize.apply(this,[options]);this.events=new OpenLayers.Events(this,null,this.EVENT_TYPES);},activate:function(){var activated=OpenLayers.Strategy.prototype.activate.call(this);if(activated){if(this.auto){if(typeof this.auto==="number"){this.timer=window.setInterval(OpenLayers.Function.bind(this.save,this),this.auto*1000);}else{this.layer.events.on({"featureadded":this.triggerSave,"afterfeaturemodified":this.triggerSave,scope:this});}}}
return activated;},deactivate:function(){var deactivated=OpenLayers.Strategy.prototype.deactivate.call(this);if(deactivated){if(this.auto){if(typeof this.auto==="number"){window.clearInterval(this.timer);}else{this.layer.events.un({"featureadded":this.triggerSave,"afterfeaturemodified":this.triggerSave,scope:this});}}}
return deactivated;},triggerSave:function(event){var feature=event.feature;if(feature.state===OpenLayers.State.INSERT||feature.state===OpenLayers.State.UPDATE||feature.state===OpenLayers.State.DELETE){this.save([event.feature]);}},save:function(features){if(!features){features=this.layer.features;}
this.events.triggerEvent("start",{features:features});var remote=this.layer.projection;var local=this.layer.map.getProjectionObject();if(!local.equals(remote)){var len=features.length;var clones=new Array(len);var orig,clone;for(var i=0;i<len;++i){orig=features[i];clone=orig.clone();clone.fid=orig.fid;clone.state=orig.state;if(orig.url){clone.url=orig.url;}
clone._original=orig;clone.geometry.transform(local,remote);clones[i]=clone;}
features=clones;}
this.layer.protocol.commit(features,{callback:this.onCommit,scope:this});},onCommit:function(response){var evt={"response":response};if(response.success()){var features=response.reqFeatures;var state,feature;var destroys=[];var insertIds=response.insertIds||[];var j=0;for(var i=0,len=features.length;i<len;++i){feature=features[i];feature=feature._original||feature;state=feature.state;if(state){if(state==OpenLayers.State.DELETE){destroys.push(feature);}else if(state==OpenLayers.State.INSERT){feature.fid=insertIds[j];++j;}
feature.state=null;}}
if(destroys.length>0){this.layer.destroyFeatures(destroys);}
this.events.triggerEvent("success",evt);}else{this.events.triggerEvent("fail",evt);}},CLASS_NAME:"OpenLayers.Strategy.Save"});OpenLayers.Symbolizer.Line=OpenLayers.Class(OpenLayers.Symbolizer,{strokeColor:null,strokeOpacity:null,strokeWidth:null,strokeLinecap:null,strokeDashstyle:null,initialize:function(config){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments);},CLASS_NAME:"OpenLayers.Symbolizer.Line"});OpenLayers.Symbolizer.Point=OpenLayers.Class(OpenLayers.Symbolizer,{strokeColor:null,strokeOpacity:null,strokeWidth:null,strokeLinecap:null,strokeDashstyle:null,fillColor:null,fillOpacity:null,pointRadius:null,externalGraphic:null,graphicWidth:null,graphicHeight:null,graphicOpacity:null,graphicXOffset:null,graphicYOffset:null,rotation:null,graphicName:null,initialize:function(config){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments);},CLASS_NAME:"OpenLayers.Symbolizer.Point"});OpenLayers.Symbolizer.Polygon=OpenLayers.Class(OpenLayers.Symbolizer,{strokeColor:null,strokeOpacity:null,strokeWidth:null,strokeLinecap:null,strokeDashstyle:null,fillColor:null,fillOpacity:null,initialize:function(config){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments);},CLASS_NAME:"OpenLayers.Symbolizer.Polygon"});OpenLayers.Symbolizer.Raster=OpenLayers.Class(OpenLayers.Symbolizer,{initialize:function(config){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments);},CLASS_NAME:"OpenLayers.Symbolizer.Raster"});OpenLayers.Symbolizer.Text=OpenLayers.Class(OpenLayers.Symbolizer,{label:null,fontFamily:null,fontSize:null,fontWeight:null,fontStyle:null,initialize:function(config){OpenLayers.Symbolizer.prototype.initialize.apply(this,arguments);},CLASS_NAME:"OpenLayers.Symbolizer.Text"});OpenLayers.Tween=OpenLayers.Class({INTERVAL:10,easing:null,begin:null,finish:null,duration:null,callbacks:null,time:null,interval:null,playing:false,initialize:function(easing){this.easing=(easing)?easing:OpenLayers.Easing.Expo.easeOut;},start:function(begin,finish,duration,options){this.playing=true;this.begin=begin;this.finish=finish;this.duration=duration;this.callbacks=options.callbacks;this.time=0;if(this.interval){window.clearInterval(this.interval);this.interval=null;}
if(this.callbacks&&this.callbacks.start){this.callbacks.start.call(this,this.begin);}
this.interval=window.setInterval(OpenLayers.Function.bind(this.play,this),this.INTERVAL);},stop:function(){if(!this.playing){return;}
if(this.callbacks&&this.callbacks.done){this.callbacks.done.call(this,this.finish);}
window.clearInterval(this.interval);this.interval=null;this.playing=false;},play:function(){var value={};for(var i in this.begin){var b=this.begin[i];var f=this.finish[i];if(b==null||f==null||isNaN(b)||isNaN(f)){OpenLayers.Console.error('invalid value for Tween');}
var c=f-b;value[i]=this.easing.apply(this,[this.time,b,c,this.duration]);}
this.time++;if(this.callbacks&&this.callbacks.eachStep){this.callbacks.eachStep.call(this,value);}
if(this.time>this.duration){this.stop();}},CLASS_NAME:"OpenLayers.Tween"});OpenLayers.Easing={CLASS_NAME:"OpenLayers.Easing"};OpenLayers.Easing.Linear={easeIn:function(t,b,c,d){return c*t/d+b;},easeOut:function(t,b,c,d){return c*t/d+b;},easeInOut:function(t,b,c,d){return c*t/d+b;},CLASS_NAME:"OpenLayers.Easing.Linear"};OpenLayers.Easing.Expo={easeIn:function(t,b,c,d){return(t==0)?b:c*Math.pow(2,10*(t/d-1))+b;},easeOut:function(t,b,c,d){return(t==d)?b+c:c*(-Math.pow(2,-10*t/d)+1)+b;},easeInOut:function(t,b,c,d){if(t==0)return b;if(t==d)return b+c;if((t/=d/2)<1)return c/2*Math.pow(2,10*(t-1))+b;return c/2*(-Math.pow(2,-10*--t)+2)+b;},CLASS_NAME:"OpenLayers.Easing.Expo"};OpenLayers.Easing.Quad={easeIn:function(t,b,c,d){return c*(t/=d)*t+b;},easeOut:function(t,b,c,d){return-c*(t/=d)*(t-2)+b;},easeInOut:function(t,b,c,d){if((t/=d/2)<1)return c/2*t*t+b;return-c/2*((--t)*(t-2)-1)+b;},CLASS_NAME:"OpenLayers.Easing.Quad"};OpenLayers.Control.ArgParser=OpenLayers.Class(OpenLayers.Control,{center:null,zoom:null,layers:null,displayProjection:null,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);for(var i=0,len=this.map.controls.length;i<len;i++){var control=this.map.controls[i];if((control!=this)&&(control.CLASS_NAME=="OpenLayers.Control.ArgParser")){if(control.displayProjection!=this.displayProjection){this.displayProjection=control.displayProjection;}
break;}}
if(i==this.map.controls.length){var args=OpenLayers.Util.getParameters();if(args.layers){this.layers=args.layers;this.map.events.register('addlayer',this,this.configureLayers);this.configureLayers();}
if(args.lat&&args.lon){this.center=new OpenLayers.LonLat(parseFloat(args.lon),parseFloat(args.lat));if(args.zoom){this.zoom=parseInt(args.zoom);}
this.map.events.register('changebaselayer',this,this.setCenter);this.setCenter();}}},setCenter:function(){if(this.map.baseLayer){this.map.events.unregister('changebaselayer',this,this.setCenter);if(this.displayProjection){this.center.transform(this.displayProjection,this.map.getProjectionObject());}
this.map.setCenter(this.center,this.zoom);}},configureLayers:function(){if(this.layers.length==this.map.layers.length){this.map.events.unregister('addlayer',this,this.configureLayers);for(var i=0,len=this.layers.length;i<len;i++){var layer=this.map.layers[i];var c=this.layers.charAt(i);if(c=="B"){this.map.setBaseLayer(layer);}else if((c=="T")||(c=="F")){layer.setVisibility(c=="T");}}}},CLASS_NAME:"OpenLayers.Control.ArgParser"});OpenLayers.Control.Attribution=OpenLayers.Class(OpenLayers.Control,{separator:", ",initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){this.map.events.un({"removelayer":this.updateAttribution,"addlayer":this.updateAttribution,"changelayer":this.updateAttribution,"changebaselayer":this.updateAttribution,scope:this});OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.map.events.on({'changebaselayer':this.updateAttribution,'changelayer':this.updateAttribution,'addlayer':this.updateAttribution,'removelayer':this.updateAttribution,scope:this});this.updateAttribution();return this.div;},updateAttribution:function(){var attributions=[];if(this.map&&this.map.layers){for(var i=0,len=this.map.layers.length;i<len;i++){var layer=this.map.layers[i];if(layer.attribution&&layer.getVisibility()){if(OpenLayers.Util.indexOf(attributions,layer.attribution)===-1){attributions.push(layer.attribution);}}}
this.div.innerHTML=attributions.join(this.separator);}},CLASS_NAME:"OpenLayers.Control.Attribution"});OpenLayers.Control.Button=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_BUTTON,trigger:function(){},CLASS_NAME:"OpenLayers.Control.Button"});OpenLayers.Control.Graticule=OpenLayers.Class(OpenLayers.Control,{autoActivate:true,intervals:[45,30,20,10,5,2,1,0.5,0.2,0.1,0.05,0.01,0.005,0.002,0.001],displayInLayerSwitcher:true,visible:true,numPoints:50,targetSize:200,layerName:null,labelled:true,labelFormat:'dm',lineSymbolizer:{strokeColor:"#333",strokeWidth:1,strokeOpacity:0.5},labelSymbolizer:{},gratLayer:null,initialize:function(options){options=options||{};options.layerName=options.layerName||OpenLayers.i18n("graticule");OpenLayers.Control.prototype.initialize.apply(this,[options]);this.labelSymbolizer.stroke=false;this.labelSymbolizer.fill=false;this.labelSymbolizer.label="${label}";this.labelSymbolizer.labelAlign="${labelAlign}";this.labelSymbolizer.labelXOffset="${xOffset}";this.labelSymbolizer.labelYOffset="${yOffset}";},destroy:function(){this.deactivate();OpenLayers.Control.prototype.destroy.apply(this,arguments);if(this.gratLayer){this.gratLayer.destroy();this.gratLayer=null;}},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!this.gratLayer){var gratStyle=new OpenLayers.Style({},{rules:[new OpenLayers.Rule({'symbolizer':{"Point":this.labelSymbolizer,"Line":this.lineSymbolizer}})]});this.gratLayer=new OpenLayers.Layer.Vector(this.layerName,{styleMap:new OpenLayers.StyleMap({'default':gratStyle}),visibility:this.visible,displayInLayerSwitcher:this.displayInLayerSwitcher});}
return this.div;},activate:function(){if(OpenLayers.Control.prototype.activate.apply(this,arguments)){this.map.addLayer(this.gratLayer);this.map.events.register('moveend',this,this.update);this.update();return true;}else{return false;}},deactivate:function(){if(OpenLayers.Control.prototype.deactivate.apply(this,arguments)){this.map.events.unregister('moveend',this,this.update);this.map.removeLayer(this.gratLayer);return true;}else{return false;}},update:function(){var mapBounds=this.map.getExtent();if(!mapBounds){return;}
this.gratLayer.destroyFeatures();var llProj=new OpenLayers.Projection("EPSG:4326");var mapProj=this.map.getProjectionObject();var mapRes=this.map.getResolution();if(mapProj.proj&&mapProj.proj.projName=="longlat"){this.numPoints=1;}
var mapCenter=this.map.getCenter();var mapCenterLL=new OpenLayers.Pixel(mapCenter.lon,mapCenter.lat);OpenLayers.Projection.transform(mapCenterLL,mapProj,llProj);var testSq=this.targetSize*mapRes;testSq*=testSq;var llInterval;for(var i=0;i<this.intervals.length;++i){llInterval=this.intervals[i];var delta=llInterval/2;var p1=mapCenterLL.offset(new OpenLayers.Pixel(-delta,-delta));var p2=mapCenterLL.offset(new OpenLayers.Pixel(delta,delta));OpenLayers.Projection.transform(p1,llProj,mapProj);OpenLayers.Projection.transform(p2,llProj,mapProj);var distSq=(p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y);if(distSq<=testSq){break;}}
mapCenterLL.x=Math.floor(mapCenterLL.x/llInterval)*llInterval;mapCenterLL.y=Math.floor(mapCenterLL.y/llInterval)*llInterval;var iter=0;var centerLonPoints=[mapCenterLL.clone()];var newPoint=mapCenterLL.clone();var mapXY;do{newPoint=newPoint.offset(new OpenLayers.Pixel(0,llInterval));mapXY=OpenLayers.Projection.transform(newPoint.clone(),llProj,mapProj);centerLonPoints.unshift(newPoint);}while(mapBounds.containsPixel(mapXY)&&++iter<1000);newPoint=mapCenterLL.clone();do{newPoint=newPoint.offset(new OpenLayers.Pixel(0,-llInterval));mapXY=OpenLayers.Projection.transform(newPoint.clone(),llProj,mapProj);centerLonPoints.push(newPoint);}while(mapBounds.containsPixel(mapXY)&&++iter<1000);iter=0;var centerLatPoints=[mapCenterLL.clone()];newPoint=mapCenterLL.clone();do{newPoint=newPoint.offset(new OpenLayers.Pixel(-llInterval,0));mapXY=OpenLayers.Projection.transform(newPoint.clone(),llProj,mapProj);centerLatPoints.unshift(newPoint);}while(mapBounds.containsPixel(mapXY)&&++iter<1000);newPoint=mapCenterLL.clone();do{newPoint=newPoint.offset(new OpenLayers.Pixel(llInterval,0));mapXY=OpenLayers.Projection.transform(newPoint.clone(),llProj,mapProj);centerLatPoints.push(newPoint);}while(mapBounds.containsPixel(mapXY)&&++iter<1000);var lines=[];for(var i=0;i<centerLatPoints.length;++i){var lon=centerLatPoints[i].x;var pointList=[];var labelPoint=null;var latEnd=Math.min(centerLonPoints[0].y,90);var latStart=Math.max(centerLonPoints[centerLonPoints.length-1].y,-90);var latDelta=(latEnd-latStart)/this.numPoints;var lat=latStart;for(var j=0;j<=this.numPoints;++j){var gridPoint=new OpenLayers.Geometry.Point(lon,lat);gridPoint.transform(llProj,mapProj);pointList.push(gridPoint);lat+=latDelta;if(gridPoint.y>=mapBounds.bottom&&!labelPoint){labelPoint=gridPoint;}}
if(this.labelled){var labelPos=new OpenLayers.Geometry.Point(labelPoint.x,mapBounds.bottom);var labelAttrs={value:lon,label:this.labelled?OpenLayers.Util.getFormattedLonLat(lon,"lon",this.labelFormat):"",labelAlign:"cb",xOffset:0,yOffset:2};this.gratLayer.addFeatures(new OpenLayers.Feature.Vector(labelPos,labelAttrs));}
var geom=new OpenLayers.Geometry.LineString(pointList);lines.push(new OpenLayers.Feature.Vector(geom));}
for(var j=0;j<centerLonPoints.length;++j){lat=centerLonPoints[j].y;if(lat<-90||lat>90){continue;}
var pointList=[];var lonStart=centerLatPoints[0].x;var lonEnd=centerLatPoints[centerLatPoints.length-1].x;var lonDelta=(lonEnd-lonStart)/this.numPoints;var lon=lonStart;var labelPoint=null;for(var i=0;i<=this.numPoints;++i){var gridPoint=new OpenLayers.Geometry.Point(lon,lat);gridPoint.transform(llProj,mapProj);pointList.push(gridPoint);lon+=lonDelta;if(gridPoint.x<mapBounds.right){labelPoint=gridPoint;}}
if(this.labelled){var labelPos=new OpenLayers.Geometry.Point(mapBounds.right,labelPoint.y);var labelAttrs={value:lat,label:this.labelled?OpenLayers.Util.getFormattedLonLat(lat,"lat",this.labelFormat):"",labelAlign:"rb",xOffset:-2,yOffset:2};this.gratLayer.addFeatures(new OpenLayers.Feature.Vector(labelPos,labelAttrs));}
var geom=new OpenLayers.Geometry.LineString(pointList);lines.push(new OpenLayers.Feature.Vector(geom));}
this.gratLayer.addFeatures(lines);},CLASS_NAME:"OpenLayers.Control.Graticule"});OpenLayers.Control.LayerSwitcher=OpenLayers.Class(OpenLayers.Control,{roundedCorner:true,roundedCornerColor:"darkblue",layerStates:null,layersDiv:null,baseLayersDiv:null,baseLayers:null,dataLbl:null,dataLayersDiv:null,dataLayers:null,minimizeDiv:null,maximizeDiv:null,ascending:true,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.layerStates=[];},destroy:function(){OpenLayers.Event.stopObservingElement(this.div);OpenLayers.Event.stopObservingElement(this.minimizeDiv);OpenLayers.Event.stopObservingElement(this.maximizeDiv);this.clearLayersArray("base");this.clearLayersArray("data");this.map.events.un({"addlayer":this.redraw,"changelayer":this.redraw,"removelayer":this.redraw,"changebaselayer":this.redraw,scope:this});OpenLayers.Control.prototype.destroy.apply(this,arguments);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.map.events.on({"addlayer":this.redraw,"changelayer":this.redraw,"removelayer":this.redraw,"changebaselayer":this.redraw,scope:this});},draw:function(){OpenLayers.Control.prototype.draw.apply(this);this.loadContents();if(!this.outsideViewport){this.minimizeControl();}
this.redraw();return this.div;},clearLayersArray:function(layersType){var layers=this[layersType+"Layers"];if(layers){for(var i=0,len=layers.length;i<len;i++){var layer=layers[i];OpenLayers.Event.stopObservingElement(layer.inputElem);OpenLayers.Event.stopObservingElement(layer.labelSpan);}}
this[layersType+"LayersDiv"].innerHTML="";this[layersType+"Layers"]=[];},checkRedraw:function(){var redraw=false;if(!this.layerStates.length||(this.map.layers.length!=this.layerStates.length)){redraw=true;}else{for(var i=0,len=this.layerStates.length;i<len;i++){var layerState=this.layerStates[i];var layer=this.map.layers[i];if((layerState.name!=layer.name)||(layerState.inRange!=layer.inRange)||(layerState.id!=layer.id)||(layerState.visibility!=layer.visibility)){redraw=true;break;}}}
return redraw;},redraw:function(){if(!this.checkRedraw()){return this.div;}
this.clearLayersArray("base");this.clearLayersArray("data");var containsOverlays=false;var containsBaseLayers=false;var len=this.map.layers.length;this.layerStates=new Array(len);for(var i=0;i<len;i++){var layer=this.map.layers[i];this.layerStates[i]={'name':layer.name,'visibility':layer.visibility,'inRange':layer.inRange,'id':layer.id};}
var layers=this.map.layers.slice();if(!this.ascending){layers.reverse();}
for(var i=0,len=layers.length;i<len;i++){var layer=layers[i];var baseLayer=layer.isBaseLayer;if(layer.displayInLayerSwitcher){if(baseLayer){containsBaseLayers=true;}else{containsOverlays=true;}
var checked=(baseLayer)?(layer==this.map.baseLayer):layer.getVisibility();var inputElem=document.createElement("input");inputElem.id=this.id+"_input_"+layer.name;inputElem.name=(baseLayer)?this.id+"_baseLayers":layer.name;inputElem.type=(baseLayer)?"radio":"checkbox";inputElem.value=layer.name;inputElem.checked=checked;inputElem.defaultChecked=checked;if(!baseLayer&&!layer.inRange){inputElem.disabled=true;}
var context={'inputElem':inputElem,'layer':layer,'layerSwitcher':this};OpenLayers.Event.observe(inputElem,"mouseup",OpenLayers.Function.bindAsEventListener(this.onInputClick,context));var labelSpan=document.createElement("span");OpenLayers.Element.addClass(labelSpan,"labelSpan")
if(!baseLayer&&!layer.inRange){labelSpan.style.color="gray";}
labelSpan.innerHTML=layer.name;labelSpan.style.verticalAlign=(baseLayer)?"bottom":"baseline";OpenLayers.Event.observe(labelSpan,"click",OpenLayers.Function.bindAsEventListener(this.onInputClick,context));var br=document.createElement("br");var groupArray=(baseLayer)?this.baseLayers:this.dataLayers;groupArray.push({'layer':layer,'inputElem':inputElem,'labelSpan':labelSpan});var groupDiv=(baseLayer)?this.baseLayersDiv:this.dataLayersDiv;groupDiv.appendChild(inputElem);groupDiv.appendChild(labelSpan);groupDiv.appendChild(br);}}
this.dataLbl.style.display=(containsOverlays)?"":"none";this.baseLbl.style.display=(containsBaseLayers)?"":"none";return this.div;},onInputClick:function(e){if(!this.inputElem.disabled){if(this.inputElem.type=="radio"){this.inputElem.checked=true;this.layer.map.setBaseLayer(this.layer);}else{this.inputElem.checked=!this.inputElem.checked;this.layerSwitcher.updateMap();}}
OpenLayers.Event.stop(e);},onLayerClick:function(e){this.updateMap();},updateMap:function(){for(var i=0,len=this.baseLayers.length;i<len;i++){var layerEntry=this.baseLayers[i];if(layerEntry.inputElem.checked){this.map.setBaseLayer(layerEntry.layer,false);}}
for(var i=0,len=this.dataLayers.length;i<len;i++){var layerEntry=this.dataLayers[i];layerEntry.layer.setVisibility(layerEntry.inputElem.checked);}},maximizeControl:function(e){this.div.style.width="";this.div.style.height="";this.showControls(false);if(e!=null){OpenLayers.Event.stop(e);}},minimizeControl:function(e){this.div.style.width="0px";this.div.style.height="0px";this.showControls(true);if(e!=null){OpenLayers.Event.stop(e);}},showControls:function(minimize){this.maximizeDiv.style.display=minimize?"":"none";this.minimizeDiv.style.display=minimize?"none":"";this.layersDiv.style.display=minimize?"none":"";},loadContents:function(){OpenLayers.Event.observe(this.div,"mouseup",OpenLayers.Function.bindAsEventListener(this.mouseUp,this));OpenLayers.Event.observe(this.div,"click",this.ignoreEvent);OpenLayers.Event.observe(this.div,"mousedown",OpenLayers.Function.bindAsEventListener(this.mouseDown,this));OpenLayers.Event.observe(this.div,"dblclick",this.ignoreEvent);this.layersDiv=document.createElement("div");this.layersDiv.id=this.id+"_layersDiv";OpenLayers.Element.addClass(this.layersDiv,"layersDiv");this.baseLbl=document.createElement("div");this.baseLbl.innerHTML=OpenLayers.i18n("baseLayer");OpenLayers.Element.addClass(this.baseLbl,"baseLbl");this.baseLayersDiv=document.createElement("div");OpenLayers.Element.addClass(this.baseLayersDiv,"baseLayersDiv");this.dataLbl=document.createElement("div");this.dataLbl.innerHTML=OpenLayers.i18n("overlays");OpenLayers.Element.addClass(this.dataLbl,"dataLbl");this.dataLayersDiv=document.createElement("div");OpenLayers.Element.addClass(this.dataLayersDiv,"dataLayersDiv");if(this.ascending){this.layersDiv.appendChild(this.baseLbl);this.layersDiv.appendChild(this.baseLayersDiv);this.layersDiv.appendChild(this.dataLbl);this.layersDiv.appendChild(this.dataLayersDiv);}else{this.layersDiv.appendChild(this.dataLbl);this.layersDiv.appendChild(this.dataLayersDiv);this.layersDiv.appendChild(this.baseLbl);this.layersDiv.appendChild(this.baseLayersDiv);}
this.div.appendChild(this.layersDiv);if(this.roundedCorner){OpenLayers.Rico.Corner.round(this.div,{corners:"tl bl",bgColor:"transparent",color:this.roundedCornerColor,blend:false});OpenLayers.Rico.Corner.changeOpacity(this.layersDiv,0.75);}
var imgLocation=OpenLayers.Util.getImagesLocation();var sz=new OpenLayers.Size(18,18);var img=imgLocation+'layer-switcher-maximize.png';this.maximizeDiv=OpenLayers.Util.createAlphaImageDiv("OpenLayers_Control_MaximizeDiv",null,sz,img,"absolute");OpenLayers.Element.addClass(this.maximizeDiv,"maximizeDiv");this.maximizeDiv.style.display="none";OpenLayers.Event.observe(this.maximizeDiv,"click",OpenLayers.Function.bindAsEventListener(this.maximizeControl,this));this.div.appendChild(this.maximizeDiv);var img=imgLocation+'layer-switcher-minimize.png';var sz=new OpenLayers.Size(18,18);this.minimizeDiv=OpenLayers.Util.createAlphaImageDiv("OpenLayers_Control_MinimizeDiv",null,sz,img,"absolute");OpenLayers.Element.addClass(this.minimizeDiv,"minimizeDiv");this.minimizeDiv.style.display="none";OpenLayers.Event.observe(this.minimizeDiv,"click",OpenLayers.Function.bindAsEventListener(this.minimizeControl,this));this.div.appendChild(this.minimizeDiv);},ignoreEvent:function(evt){OpenLayers.Event.stop(evt);},mouseDown:function(evt){this.isMouseDown=true;this.ignoreEvent(evt);},mouseUp:function(evt){if(this.isMouseDown){this.isMouseDown=false;this.ignoreEvent(evt);}},CLASS_NAME:"OpenLayers.Control.LayerSwitcher"});OpenLayers.Control.MouseDefaults=OpenLayers.Class(OpenLayers.Control,{performedDrag:false,wheelObserver:null,initialize:function(){OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){if(this.handler){this.handler.destroy();}
this.handler=null;this.map.events.un({"click":this.defaultClick,"dblclick":this.defaultDblClick,"mousedown":this.defaultMouseDown,"mouseup":this.defaultMouseUp,"mousemove":this.defaultMouseMove,"mouseout":this.defaultMouseOut,scope:this});OpenLayers.Event.stopObserving(window,"DOMMouseScroll",this.wheelObserver);OpenLayers.Event.stopObserving(window,"mousewheel",this.wheelObserver);OpenLayers.Event.stopObserving(document,"mousewheel",this.wheelObserver);this.wheelObserver=null;OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){this.map.events.on({"click":this.defaultClick,"dblclick":this.defaultDblClick,"mousedown":this.defaultMouseDown,"mouseup":this.defaultMouseUp,"mousemove":this.defaultMouseMove,"mouseout":this.defaultMouseOut,scope:this});this.registerWheelEvents();},registerWheelEvents:function(){this.wheelObserver=OpenLayers.Function.bindAsEventListener(this.onWheelEvent,this);OpenLayers.Event.observe(window,"DOMMouseScroll",this.wheelObserver);OpenLayers.Event.observe(window,"mousewheel",this.wheelObserver);OpenLayers.Event.observe(document,"mousewheel",this.wheelObserver);},defaultClick:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
var notAfterDrag=!this.performedDrag;this.performedDrag=false;return notAfterDrag;},defaultDblClick:function(evt){var newCenter=this.map.getLonLatFromViewPortPx(evt.xy);this.map.setCenter(newCenter,this.map.zoom+1);OpenLayers.Event.stop(evt);return false;},defaultMouseDown:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
this.mouseDragStart=evt.xy.clone();this.performedDrag=false;if(evt.shiftKey){this.map.div.style.cursor="crosshair";this.zoomBox=OpenLayers.Util.createDiv('zoomBox',this.mouseDragStart,null,null,"absolute","2px solid red");this.zoomBox.style.backgroundColor="white";this.zoomBox.style.filter="alpha(opacity=50)";this.zoomBox.style.opacity="0.50";this.zoomBox.style.fontSize="1px";this.zoomBox.style.zIndex=this.map.Z_INDEX_BASE["Popup"]-1;this.map.viewPortDiv.appendChild(this.zoomBox);}
document.onselectstart=OpenLayers.Function.False;OpenLayers.Event.stop(evt);},defaultMouseMove:function(evt){this.mousePosition=evt.xy.clone();if(this.mouseDragStart!=null){if(this.zoomBox){var deltaX=Math.abs(this.mouseDragStart.x-evt.xy.x);var deltaY=Math.abs(this.mouseDragStart.y-evt.xy.y);this.zoomBox.style.width=Math.max(1,deltaX)+"px";this.zoomBox.style.height=Math.max(1,deltaY)+"px";if(evt.xy.x<this.mouseDragStart.x){this.zoomBox.style.left=evt.xy.x+"px";}
if(evt.xy.y<this.mouseDragStart.y){this.zoomBox.style.top=evt.xy.y+"px";}}else{var deltaX=this.mouseDragStart.x-evt.xy.x;var deltaY=this.mouseDragStart.y-evt.xy.y;var size=this.map.getSize();var newXY=new OpenLayers.Pixel(size.w/2+deltaX,size.h/2+deltaY);var newCenter=this.map.getLonLatFromViewPortPx(newXY);this.map.setCenter(newCenter,null,true);this.mouseDragStart=evt.xy.clone();this.map.div.style.cursor="move";}
this.performedDrag=true;}},defaultMouseUp:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
if(this.zoomBox){this.zoomBoxEnd(evt);}else{if(this.performedDrag){this.map.setCenter(this.map.center);}}
document.onselectstart=null;this.mouseDragStart=null;this.map.div.style.cursor="";},defaultMouseOut:function(evt){if(this.mouseDragStart!=null&&OpenLayers.Util.mouseLeft(evt,this.map.div)){if(this.zoomBox){this.removeZoomBox();}
this.mouseDragStart=null;}},defaultWheelUp:function(evt){if(this.map.getZoom()<=this.map.getNumZoomLevels()){this.map.setCenter(this.map.getLonLatFromPixel(evt.xy),this.map.getZoom()+1);}},defaultWheelDown:function(evt){if(this.map.getZoom()>0){this.map.setCenter(this.map.getLonLatFromPixel(evt.xy),this.map.getZoom()-1);}},zoomBoxEnd:function(evt){if(this.mouseDragStart!=null){if(Math.abs(this.mouseDragStart.x-evt.xy.x)>5||Math.abs(this.mouseDragStart.y-evt.xy.y)>5){var start=this.map.getLonLatFromViewPortPx(this.mouseDragStart);var end=this.map.getLonLatFromViewPortPx(evt.xy);var top=Math.max(start.lat,end.lat);var bottom=Math.min(start.lat,end.lat);var left=Math.min(start.lon,end.lon);var right=Math.max(start.lon,end.lon);var bounds=new OpenLayers.Bounds(left,bottom,right,top);this.map.zoomToExtent(bounds);}else{var end=this.map.getLonLatFromViewPortPx(evt.xy);this.map.setCenter(new OpenLayers.LonLat((end.lon),(end.lat)),this.map.getZoom()+1);}
this.removeZoomBox();}},removeZoomBox:function(){this.map.viewPortDiv.removeChild(this.zoomBox);this.zoomBox=null;},onWheelEvent:function(e){var inMap=false;var elem=OpenLayers.Event.element(e);while(elem!=null){if(this.map&&elem==this.map.div){inMap=true;break;}
elem=elem.parentNode;}
if(inMap){var delta=0;if(!e){e=window.event;}
if(e.wheelDelta){delta=e.wheelDelta/120;if(window.opera&&window.opera.version()<9.2){delta=-delta;}}else if(e.detail){delta=-e.detail/3;}
if(delta){e.xy=this.mousePosition;if(delta<0){this.defaultWheelDown(e);}else{this.defaultWheelUp(e);}}
OpenLayers.Event.stop(e);}},CLASS_NAME:"OpenLayers.Control.MouseDefaults"});OpenLayers.Control.MousePosition=OpenLayers.Class(OpenLayers.Control,{autoActivate:true,element:null,prefix:'',separator:', ',suffix:'',numDigits:5,granularity:10,emptyString:null,lastXy:null,displayProjection:null,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){this.deactivate();OpenLayers.Control.prototype.destroy.apply(this,arguments);},activate:function(){if(OpenLayers.Control.prototype.activate.apply(this,arguments)){this.map.events.register('mousemove',this,this.redraw);this.map.events.register('mouseout',this,this.reset);this.redraw();return true;}else{return false;}},deactivate:function(){if(OpenLayers.Control.prototype.deactivate.apply(this,arguments)){this.map.events.unregister('mousemove',this,this.redraw);this.map.events.unregister('mouseout',this,this.reset);this.element.innerHTML="";return true;}else{return false;}},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!this.element){this.div.left="";this.div.top="";this.element=this.div;}
return this.div;},redraw:function(evt){var lonLat;if(evt==null){this.reset();return;}else{if(this.lastXy==null||Math.abs(evt.xy.x-this.lastXy.x)>this.granularity||Math.abs(evt.xy.y-this.lastXy.y)>this.granularity)
{this.lastXy=evt.xy;return;}
lonLat=this.map.getLonLatFromPixel(evt.xy);if(!lonLat){return;}
if(this.displayProjection){lonLat.transform(this.map.getProjectionObject(),this.displayProjection);}
this.lastXy=evt.xy;}
var newHtml=this.formatOutput(lonLat);if(newHtml!=this.element.innerHTML){this.element.innerHTML=newHtml;}},reset:function(evt){if(this.emptyString!=null){this.element.innerHTML=this.emptyString;}},formatOutput:function(lonLat){var digits=parseInt(this.numDigits);var newHtml=this.prefix+
lonLat.lon.toFixed(digits)+
this.separator+
lonLat.lat.toFixed(digits)+
this.suffix;return newHtml;},CLASS_NAME:"OpenLayers.Control.MousePosition"});OpenLayers.Control.Pan=OpenLayers.Class(OpenLayers.Control,{slideFactor:50,direction:null,type:OpenLayers.Control.TYPE_BUTTON,initialize:function(direction,options){this.direction=direction;this.CLASS_NAME+=this.direction;OpenLayers.Control.prototype.initialize.apply(this,[options]);},trigger:function(){switch(this.direction){case OpenLayers.Control.Pan.NORTH:this.map.pan(0,-this.slideFactor);break;case OpenLayers.Control.Pan.SOUTH:this.map.pan(0,this.slideFactor);break;case OpenLayers.Control.Pan.WEST:this.map.pan(-this.slideFactor,0);break;case OpenLayers.Control.Pan.EAST:this.map.pan(this.slideFactor,0);break;}},CLASS_NAME:"OpenLayers.Control.Pan"});OpenLayers.Control.Pan.NORTH="North";OpenLayers.Control.Pan.SOUTH="South";OpenLayers.Control.Pan.EAST="East";OpenLayers.Control.Pan.WEST="West";OpenLayers.Control.PanZoom=OpenLayers.Class(OpenLayers.Control,{slideFactor:50,slideRatio:null,buttons:null,position:null,initialize:function(options){this.position=new OpenLayers.Pixel(OpenLayers.Control.PanZoom.X,OpenLayers.Control.PanZoom.Y);OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){OpenLayers.Control.prototype.destroy.apply(this,arguments);this.removeButtons();this.buttons=null;this.position=null;},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);px=this.position;this.buttons=[];var sz=new OpenLayers.Size(18,18);var centered=new OpenLayers.Pixel(px.x+sz.w/2,px.y);this._addButton("panup","north-mini.png",centered,sz);px.y=centered.y+sz.h;this._addButton("panleft","west-mini.png",px,sz);this._addButton("panright","east-mini.png",px.add(sz.w,0),sz);this._addButton("pandown","south-mini.png",centered.add(0,sz.h*2),sz);this._addButton("zoomin","zoom-plus-mini.png",centered.add(0,sz.h*3+5),sz);this._addButton("zoomworld","zoom-world-mini.png",centered.add(0,sz.h*4+5),sz);this._addButton("zoomout","zoom-minus-mini.png",centered.add(0,sz.h*5+5),sz);return this.div;},_addButton:function(id,img,xy,sz){var imgLocation=OpenLayers.Util.getImagesLocation()+img;var btn=OpenLayers.Util.createAlphaImageDiv(this.id+"_"+id,xy,sz,imgLocation,"absolute");this.div.appendChild(btn);OpenLayers.Event.observe(btn,"mousedown",OpenLayers.Function.bindAsEventListener(this.buttonDown,btn));OpenLayers.Event.observe(btn,"dblclick",OpenLayers.Function.bindAsEventListener(this.doubleClick,btn));OpenLayers.Event.observe(btn,"click",OpenLayers.Function.bindAsEventListener(this.doubleClick,btn));btn.action=id;btn.map=this.map;if(!this.slideRatio){var slideFactorPixels=this.slideFactor;var getSlideFactor=function(){return slideFactorPixels;};}else{var slideRatio=this.slideRatio;var getSlideFactor=function(dim){return this.map.getSize()[dim]*slideRatio;};}
btn.getSlideFactor=getSlideFactor;this.buttons.push(btn);return btn;},_removeButton:function(btn){OpenLayers.Event.stopObservingElement(btn);btn.map=null;btn.getSlideFactor=null;this.div.removeChild(btn);OpenLayers.Util.removeItem(this.buttons,btn);},removeButtons:function(){for(var i=this.buttons.length-1;i>=0;--i){this._removeButton(this.buttons[i]);}},doubleClick:function(evt){OpenLayers.Event.stop(evt);return false;},buttonDown:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
switch(this.action){case"panup":this.map.pan(0,-this.getSlideFactor("h"));break;case"pandown":this.map.pan(0,this.getSlideFactor("h"));break;case"panleft":this.map.pan(-this.getSlideFactor("w"),0);break;case"panright":this.map.pan(this.getSlideFactor("w"),0);break;case"zoomin":this.map.zoomIn();break;case"zoomout":this.map.zoomOut();break;case"zoomworld":this.map.zoomToMaxExtent();break;}
OpenLayers.Event.stop(evt);},CLASS_NAME:"OpenLayers.Control.PanZoom"});OpenLayers.Control.PanZoom.X=4;OpenLayers.Control.PanZoom.Y=4;OpenLayers.Control.Panel=OpenLayers.Class(OpenLayers.Control,{controls:null,autoActivate:true,defaultControl:null,saveState:false,activeState:null,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.controls=[];this.activeState={};},destroy:function(){OpenLayers.Control.prototype.destroy.apply(this,arguments);for(var i=this.controls.length-1;i>=0;i--){if(this.controls[i].events){this.controls[i].events.un({"activate":this.redraw,"deactivate":this.redraw,scope:this});}
OpenLayers.Event.stopObservingElement(this.controls[i].panel_div);this.controls[i].panel_div=null;}
this.activeState=null;},activate:function(){if(OpenLayers.Control.prototype.activate.apply(this,arguments)){var control;for(var i=0,len=this.controls.length;i<len;i++){control=this.controls[i];if(control===this.defaultControl||(this.saveState&&this.activeState[control.id])){control.activate();}}
if(this.saveState===true){this.defaultControl=null;}
this.redraw();return true;}else{return false;}},deactivate:function(){if(OpenLayers.Control.prototype.deactivate.apply(this,arguments)){var control;for(var i=0,len=this.controls.length;i<len;i++){control=this.controls[i];this.activeState[control.id]=control.deactivate();}
return true;}else{return false;}},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.addControlsToMap(this.controls);return this.div;},redraw:function(){if(this.div.children.length>0){for(var l=this.div.children.length,i=l-1;i>=0;i--){this.div.removeChild(this.div.children[i]);}}
this.div.innerHTML="";if(this.active){for(var i=0,len=this.controls.length;i<len;i++){var element=this.controls[i].panel_div;if(this.controls[i].active){element.className=this.controls[i].displayClass+"ItemActive";}else{element.className=this.controls[i].displayClass+"ItemInactive";}
this.div.appendChild(element);}}},activateControl:function(control){if(!this.active){return false;}
if(control.type==OpenLayers.Control.TYPE_BUTTON){control.trigger();this.redraw();return;}
if(control.type==OpenLayers.Control.TYPE_TOGGLE){if(control.active){control.deactivate();}else{control.activate();}
this.redraw();return;}
var c;for(var i=0,len=this.controls.length;i<len;i++){c=this.controls[i];if(c!=control&&(c.type===OpenLayers.Control.TYPE_TOOL||c.type==null)){c.deactivate();}}
control.activate();},addControls:function(controls){if(!(controls instanceof Array)){controls=[controls];}
this.controls=this.controls.concat(controls);for(var i=0,len=controls.length;i<len;i++){var element=document.createElement("div");controls[i].panel_div=element;if(controls[i].title!=""){controls[i].panel_div.title=controls[i].title;}
OpenLayers.Event.observe(controls[i].panel_div,"click",OpenLayers.Function.bind(this.onClick,this,controls[i]));OpenLayers.Event.observe(controls[i].panel_div,"dblclick",OpenLayers.Function.bind(this.onDoubleClick,this,controls[i]));OpenLayers.Event.observe(controls[i].panel_div,"mousedown",OpenLayers.Function.bindAsEventListener(OpenLayers.Event.stop));}
if(this.map){this.addControlsToMap(controls);this.redraw();}},addControlsToMap:function(controls){var control;for(var i=0,len=controls.length;i<len;i++){control=controls[i];if(control.autoActivate===true){control.autoActivate=false;this.map.addControl(control);control.autoActivate=true;}else{this.map.addControl(control);control.deactivate();}
control.events.on({"activate":this.redraw,"deactivate":this.redraw,scope:this});}},onClick:function(ctrl,evt){OpenLayers.Event.stop(evt?evt:window.event);this.activateControl(ctrl);},onDoubleClick:function(ctrl,evt){OpenLayers.Event.stop(evt?evt:window.event);},getControlsBy:function(property,match){var test=(typeof match.test=="function");var found=OpenLayers.Array.filter(this.controls,function(item){return item[property]==match||(test&&match.test(item[property]));});return found;},getControlsByName:function(match){return this.getControlsBy("name",match);},getControlsByClass:function(match){return this.getControlsBy("CLASS_NAME",match);},CLASS_NAME:"OpenLayers.Control.Panel"});OpenLayers.Control.Scale=OpenLayers.Class(OpenLayers.Control,{element:null,geodesic:false,initialize:function(element,options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.element=OpenLayers.Util.getElement(element);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!this.element){this.element=document.createElement("div");this.div.appendChild(this.element);}
this.map.events.register('moveend',this,this.updateScale);this.updateScale();return this.div;},updateScale:function(){var scale;if(this.geodesic===true){var units=this.map.getUnits();if(!units){return;}
var inches=OpenLayers.INCHES_PER_UNIT;scale=(this.map.getGeodesicPixelSize().w||0.000001)*inches["km"]*OpenLayers.DOTS_PER_INCH;}else{scale=this.map.getScale();}
if(!scale){return;}
if(scale>=9500&&scale<=950000){scale=Math.round(scale/1000)+"K";}else if(scale>=950000){scale=Math.round(scale/1000000)+"M";}else{scale=Math.round(scale);}
this.element.innerHTML=OpenLayers.i18n("scale",{'scaleDenom':scale});},CLASS_NAME:"OpenLayers.Control.Scale"});OpenLayers.Control.ScaleLine=OpenLayers.Class(OpenLayers.Control,{maxWidth:100,topOutUnits:"km",topInUnits:"m",bottomOutUnits:"mi",bottomInUnits:"ft",eTop:null,eBottom:null,geodesic:false,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,[options]);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!this.eTop){this.eTop=document.createElement("div");this.eTop.className=this.displayClass+"Top";var theLen=this.topInUnits.length;this.div.appendChild(this.eTop);if((this.topOutUnits=="")||(this.topInUnits=="")){this.eTop.style.visibility="hidden";}else{this.eTop.style.visibility="visible";}
this.eBottom=document.createElement("div");this.eBottom.className=this.displayClass+"Bottom";this.div.appendChild(this.eBottom);if((this.bottomOutUnits=="")||(this.bottomInUnits=="")){this.eBottom.style.visibility="hidden";}else{this.eBottom.style.visibility="visible";}}
this.map.events.register('moveend',this,this.update);this.update();return this.div;},getBarLen:function(maxLen){var digits=parseInt(Math.log(maxLen)/Math.log(10));var pow10=Math.pow(10,digits);var firstChar=parseInt(maxLen/pow10);var barLen;if(firstChar>5){barLen=5;}else if(firstChar>2){barLen=2;}else{barLen=1;}
return barLen*pow10;},update:function(){var res=this.map.getResolution();if(!res){return;}
var curMapUnits=this.map.getUnits();var inches=OpenLayers.INCHES_PER_UNIT;var maxSizeData=this.maxWidth*res*inches[curMapUnits];var geodesicRatio=1;if(this.geodesic===true){var maxSizeGeodesic=(this.map.getGeodesicPixelSize().w||0.000001)*this.maxWidth;var maxSizeKilometers=maxSizeData/inches["km"];geodesicRatio=maxSizeGeodesic/maxSizeKilometers;maxSizeData*=geodesicRatio;}
var topUnits;var bottomUnits;if(maxSizeData>100000){topUnits=this.topOutUnits;bottomUnits=this.bottomOutUnits;}else{topUnits=this.topInUnits;bottomUnits=this.bottomInUnits;}
var topMax=maxSizeData/inches[topUnits];var bottomMax=maxSizeData/inches[bottomUnits];var topRounded=this.getBarLen(topMax);var bottomRounded=this.getBarLen(bottomMax);topMax=topRounded/inches[curMapUnits]*inches[topUnits];bottomMax=bottomRounded/inches[curMapUnits]*inches[bottomUnits];var topPx=topMax/res/geodesicRatio;var bottomPx=bottomMax/res/geodesicRatio;if(this.eBottom.style.visibility=="visible"){this.eBottom.style.width=Math.round(bottomPx)+"px";this.eBottom.innerHTML=bottomRounded+" "+bottomUnits;}
if(this.eTop.style.visibility=="visible"){this.eTop.style.width=Math.round(topPx)+"px";this.eTop.innerHTML=topRounded+" "+topUnits;}},CLASS_NAME:"OpenLayers.Control.ScaleLine"});OpenLayers.Control.ZoomIn=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_BUTTON,trigger:function(){this.map.zoomIn();},CLASS_NAME:"OpenLayers.Control.ZoomIn"});OpenLayers.Control.ZoomOut=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_BUTTON,trigger:function(){this.map.zoomOut();},CLASS_NAME:"OpenLayers.Control.ZoomOut"});OpenLayers.Control.ZoomToMaxExtent=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_BUTTON,trigger:function(){if(this.map){this.map.zoomToMaxExtent();}},CLASS_NAME:"OpenLayers.Control.ZoomToMaxExtent"});OpenLayers.Event={observers:false,KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,element:function(event){return event.target||event.srcElement;},isLeftClick:function(event){return(((event.which)&&(event.which==1))||((event.button)&&(event.button==1)));},isRightClick:function(event){return(((event.which)&&(event.which==3))||((event.button)&&(event.button==2)));},stop:function(event,allowDefault){if(!allowDefault){if(event.preventDefault){event.preventDefault();}else{event.returnValue=false;}}
if(event.stopPropagation){event.stopPropagation();}else{event.cancelBubble=true;}},findElement:function(event,tagName){var element=OpenLayers.Event.element(event);while(element.parentNode&&(!element.tagName||(element.tagName.toUpperCase()!=tagName.toUpperCase()))){element=element.parentNode;}
return element;},observe:function(elementParam,name,observer,useCapture){var element=OpenLayers.Util.getElement(elementParam);useCapture=useCapture||false;if(name=='keypress'&&(navigator.appVersion.match(/Konqueror|Safari|KHTML/)||element.attachEvent)){name='keydown';}
if(!this.observers){this.observers={};}
if(!element._eventCacheID){var idPrefix="eventCacheID_";if(element.id){idPrefix=element.id+"_"+idPrefix;}
element._eventCacheID=OpenLayers.Util.createUniqueID(idPrefix);}
var cacheID=element._eventCacheID;if(!this.observers[cacheID]){this.observers[cacheID]=[];}
this.observers[cacheID].push({'element':element,'name':name,'observer':observer,'useCapture':useCapture});if(element.addEventListener){element.addEventListener(name,observer,useCapture);}else if(element.attachEvent){element.attachEvent('on'+name,observer);}},stopObservingElement:function(elementParam){var element=OpenLayers.Util.getElement(elementParam);var cacheID=element._eventCacheID;this._removeElementObservers(OpenLayers.Event.observers[cacheID]);},_removeElementObservers:function(elementObservers){if(elementObservers){for(var i=elementObservers.length-1;i>=0;i--){var entry=elementObservers[i];var args=new Array(entry.element,entry.name,entry.observer,entry.useCapture);var removed=OpenLayers.Event.stopObserving.apply(this,args);}}},stopObserving:function(elementParam,name,observer,useCapture){useCapture=useCapture||false;var element=OpenLayers.Util.getElement(elementParam);var cacheID=element._eventCacheID;if(name=='keypress'){if(navigator.appVersion.match(/Konqueror|Safari|KHTML/)||element.detachEvent){name='keydown';}}
var foundEntry=false;var elementObservers=OpenLayers.Event.observers[cacheID];if(elementObservers){var i=0;while(!foundEntry&&i<elementObservers.length){var cacheEntry=elementObservers[i];if((cacheEntry.name==name)&&(cacheEntry.observer==observer)&&(cacheEntry.useCapture==useCapture)){elementObservers.splice(i,1);if(elementObservers.length==0){delete OpenLayers.Event.observers[cacheID];}
foundEntry=true;break;}
i++;}}
if(foundEntry){if(element.removeEventListener){element.removeEventListener(name,observer,useCapture);}else if(element&&element.detachEvent){element.detachEvent('on'+name,observer);}}
return foundEntry;},unloadCache:function(){if(OpenLayers.Event&&OpenLayers.Event.observers){for(var cacheID in OpenLayers.Event.observers){var elementObservers=OpenLayers.Event.observers[cacheID];OpenLayers.Event._removeElementObservers.apply(this,[elementObservers]);}
OpenLayers.Event.observers=false;}},CLASS_NAME:"OpenLayers.Event"};OpenLayers.Event.observe(window,'unload',OpenLayers.Event.unloadCache,false);if(window.Event){OpenLayers.Util.applyDefaults(window.Event,OpenLayers.Event);}else{var Event=OpenLayers.Event;}
OpenLayers.Events=OpenLayers.Class({BROWSER_EVENTS:["mouseover","mouseout","mousedown","mouseup","mousemove","click","dblclick","rightclick","dblrightclick","resize","focus","blur"],listeners:null,object:null,element:null,eventTypes:null,eventHandler:null,fallThrough:null,includeXY:false,clearMouseListener:null,initialize:function(object,element,eventTypes,fallThrough,options){OpenLayers.Util.extend(this,options);this.object=object;this.fallThrough=fallThrough;this.listeners={};this.eventHandler=OpenLayers.Function.bindAsEventListener(this.handleBrowserEvent,this);this.clearMouseListener=OpenLayers.Function.bind(this.clearMouseCache,this);this.eventTypes=[];if(eventTypes!=null){for(var i=0,len=eventTypes.length;i<len;i++){this.addEventType(eventTypes[i]);}}
if(element!=null){this.attachToElement(element);}},destroy:function(){if(this.element){OpenLayers.Event.stopObservingElement(this.element);if(this.element.hasScrollEvent){OpenLayers.Event.stopObserving(window,"scroll",this.clearMouseListener);}}
this.element=null;this.listeners=null;this.object=null;this.eventTypes=null;this.fallThrough=null;this.eventHandler=null;},addEventType:function(eventName){if(!this.listeners[eventName]){this.eventTypes.push(eventName);this.listeners[eventName]=[];}},attachToElement:function(element){if(this.element){OpenLayers.Event.stopObservingElement(this.element);}
this.element=element;for(var i=0,len=this.BROWSER_EVENTS.length;i<len;i++){var eventType=this.BROWSER_EVENTS[i];this.addEventType(eventType);OpenLayers.Event.observe(element,eventType,this.eventHandler);}
OpenLayers.Event.observe(element,"dragstart",OpenLayers.Event.stop);},on:function(object){for(var type in object){if(type!="scope"){this.register(type,object.scope,object[type]);}}},register:function(type,obj,func){if((func!=null)&&(OpenLayers.Util.indexOf(this.eventTypes,type)!=-1)){if(obj==null){obj=this.object;}
var listeners=this.listeners[type];listeners.push({obj:obj,func:func});}},registerPriority:function(type,obj,func){if(func!=null){if(obj==null){obj=this.object;}
var listeners=this.listeners[type];if(listeners!=null){listeners.unshift({obj:obj,func:func});}}},un:function(object){for(var type in object){if(type!="scope"){this.unregister(type,object.scope,object[type]);}}},unregister:function(type,obj,func){if(obj==null){obj=this.object;}
var listeners=this.listeners[type];if(listeners!=null){for(var i=0,len=listeners.length;i<len;i++){if(listeners[i].obj==obj&&listeners[i].func==func){listeners.splice(i,1);break;}}}},remove:function(type){if(this.listeners[type]!=null){this.listeners[type]=[];}},triggerEvent:function(type,evt){var listeners=this.listeners[type];if(!listeners||listeners.length==0){return;}
if(evt==null){evt={};}
evt.object=this.object;evt.element=this.element;if(!evt.type){evt.type=type;}
var listeners=listeners.slice(),continueChain;for(var i=0,len=listeners.length;i<len;i++){var callback=listeners[i];continueChain=callback.func.apply(callback.obj,[evt]);if((continueChain!=undefined)&&(continueChain==false)){break;}}
if(!this.fallThrough){OpenLayers.Event.stop(evt,true);}
return continueChain;},handleBrowserEvent:function(evt){if(this.includeXY){evt.xy=this.getMousePosition(evt);}
this.triggerEvent(evt.type,evt);},clearMouseCache:function(){this.element.scrolls=null;this.element.lefttop=null;this.element.offsets=null;},getMousePosition:function(evt){if(!this.includeXY){this.clearMouseCache();}else if(!this.element.hasScrollEvent){OpenLayers.Event.observe(window,"scroll",this.clearMouseListener);this.element.hasScrollEvent=true;}
if(!this.element.scrolls){this.element.scrolls=[(document.documentElement.scrollLeft||document.body.scrollLeft),(document.documentElement.scrollTop||document.body.scrollTop)];}
if(!this.element.lefttop){this.element.lefttop=[(document.documentElement.clientLeft||0),(document.documentElement.clientTop||0)];}
if(!this.element.offsets){this.element.offsets=OpenLayers.Util.pagePosition(this.element);this.element.offsets[0]+=this.element.scrolls[0];this.element.offsets[1]+=this.element.scrolls[1];}
return new OpenLayers.Pixel((evt.clientX+this.element.scrolls[0])-this.element.offsets[0]
-this.element.lefttop[0],(evt.clientY+this.element.scrolls[1])-this.element.offsets[1]
-this.element.lefttop[1]);},CLASS_NAME:"OpenLayers.Events"});OpenLayers.Format=OpenLayers.Class({options:null,externalProjection:null,internalProjection:null,data:null,keepData:false,initialize:function(options){OpenLayers.Util.extend(this,options);this.options=options;},destroy:function(){},read:function(data){OpenLayers.Console.userError(OpenLayers.i18n("readNotImplemented"));},write:function(object){OpenLayers.Console.userError(OpenLayers.i18n("writeNotImplemented"));},CLASS_NAME:"OpenLayers.Format"});OpenLayers.Lang["ar"]=OpenLayers.Util.applyDefaults({'permalink':"وصلة دائمة",'baseLayer':"الطبقة الاساسية",'readNotImplemented':"القراءة غير محققة.",'writeNotImplemented':"الكتابة غير محققة",'errorLoadingGML':"خطأ عند تحميل الملف جي ام ال ${url}",'scale':"النسبة = 1 : ${scaleDenom}",'W':"غ",'E':"شر",'N':"شم",'S':"ج"});OpenLayers.Lang["be-tarask"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Неапрацаваны вынік запыту ${statusText}",'permalink':"Сталая спасылка",'overlays':"Слаі",'baseLayer':"Базавы слой",'sameProjection':"Аглядная мапа працуе толькі калі яна мае тую ж праекцыю, што і асноўная мапа",'readNotImplemented':"Функцыянальнасьць чытаньня ня створаная.",'writeNotImplemented':"Функцыянальнасьць запісу ня створаная.",'noFID':"Немагчыма абнавіць магчымасьць, для якога не існуе FID.",'errorLoadingGML':"Памылка загрузкі файла GML ${url}",'browserNotSupported':"Ваш браўзэр не падтрымлівае вэктарную графіку. У цяперашні момант падтрымліваюцца: ${renderers}",'componentShouldBe':"addFeatures : кампанэнт павінен быць ${geomType}",'getFeatureError':"getFeatureFromEvent выкліканы для слоя бяз рэндэру. Звычайна гэта азначае, што Вы зьнішчылі слой, але пакінулі зьвязаны зь ім апрацоўшчык.",'minZoomLevelError':"Уласьцівасьць minZoomLevel прызначана толькі для выкарыстаньня са слаямі вытворнымі ад FixedZoomLevels. Тое, што  гэты wfs-слой правяраецца на minZoomLevel — рэха прошлага. Але мы ня можам выдаліць гэтую магчымасьць, таму што ад яе залежаць некаторыя заснаваныя на OL дастасаваньні. Тым ня менш, праверка minZoomLevel будзе выдаленая ў вэрсіі 3.0. Калі ласка, выкарыстоўваеце замест яе ўстаноўкі мінімальнага/максымальнага памераў, як апісана тут: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"WFS-транзакцыя: ПОСЬПЕХ ${response}",'commitFailed':"WFS-транзакцыя: ПАМЫЛКА ${response}",'googleWarning':"Не атрымалася загрузіць слой Google. \x3cbr\x3e\x3cbr\x3eКаб пазбавіцца гэтага паведамленьня, выберыце новы базавы слой у сьпісе ў верхнім правым куце.\x3cbr\x3e\x3cbr\x3e Хутчэй за ўсё, прычына ў тым, што скрыпт бібліятэкі Google Maps ня быў уключаныя альбо не ўтрымлівае слушны API-ключ для Вашага сайта.\x3cbr\x3e\x3cbr\x3eРаспрацоўшчыкам: Для таго, каб даведацца як зрабіць так, каб усё працавала, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3eнацісьніце тут\x3c/a\x3e",'getLayerWarning':"Немагчыма загрузіць слой ${layerType}.\x3cbr\x3e\x3cbr\x3eКаб пазбавіцца гэтага паведамленьня, выберыце новы базавы слой у сьпісе ў верхнім правым куце.\x3cbr\x3e\x3cbr\x3eХутчэй за ўсё, прычына ў тым, што скрыпт бібліятэкі ${layerLib} ня быў слушна ўключаны.\x3cbr\x3e\x3cbr\x3eРаспрацоўшчыкам: Для таго, каб даведацца як зрабіць так, каб усё працавала, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3eнацісьніце тут\x3c/a\x3e",'scale':"Маштаб = 1 : ${scaleDenom}",'W':"З",'E':"У",'N':"Пн",'S':"Пд",'layerAlreadyAdded':"Вы паспрабавалі дадаць слой ${layerName} на мапу, але ён ужо дададзены",'reprojectDeprecated':"Вы выкарыстоўваеце ўстаноўку \'reproject\' для слоя ${layerName}. Гэтая ўстаноўка зьяўляецца састарэлай: яна выкарыстоўвалася для падтрымкі паказу зьвестак на камэрцыйных базавых мапах, але гэта функцыя цяпер рэалізаваная ў убудаванай падтрымцы сфэрычнай праекцыі Мэркатара. Дадатковая інфармацыя ёсьць на http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Гэты мэтад састарэлы і будзе выдалены ў вэрсіі 3.0. Калі ласка, замест яго выкарыстоўвайце ${newMethod}.",'boundsAddError':"Вам неабходна падаць абодва значэньні x і y для функцыі складаньня.",'lonlatAddError':"Вам неабходна падаць абодва значэньні lon і lat для функцыі складаньня.",'pixelAddError':"Вам неабходна падаць абодва значэньні x і y для функцыі складаньня.",'unsupportedGeometryType':"Тып геамэтрыі не падтрымліваецца: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition failed: верагодна элемэнт з ідэнтыфікатарам ${elemId} займае няслушнае месца.",'filterEvaluateNotImplemented':"evaluate не рэалізаваны для гэтага тыпу фільтру."});OpenLayers.Lang["bg"]=OpenLayers.Util.applyDefaults({'permalink':"Постоянна препратка",'baseLayer':"Основен слой",'errorLoadingGML':"Грешка при зареждане на GML файл ${url}",'scale':"Мащаб = 1 : ${scaleDenom}",'layerAlreadyAdded':"Опитахте да добавите слой ${layerName} в картата, но той вече е добавен",'methodDeprecated':"Този метод е остарял и ще бъде премахват в 3.0. Вместо него използвайте ${newMethod}."});OpenLayers.Lang["br"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Distro evel reked anveret ${statusText}",'permalink':"Peurliamm",'overlays':"Gwiskadoù",'baseLayer':"Gwiskad diazez",'sameProjection':"Ne\'z ar gartenn lec\'hiañ en-dro nemet pa vez heñvel ar banndres anezhi ha hini ar gartenn bennañ",'readNotImplemented':"N\'eo ket emplementet al lenn.",'writeNotImplemented':"N\'eo ket emplementet ar skrivañ.",'noFID':"N\'haller ket hizivaat un elfenn ma n\'eus ket a niverenn-anaout (FID) eviti.",'errorLoadingGML':"Fazi e-ser kargañ ar restr GML ${url}",'browserNotSupported':"N\'eo ket skoret an daskor vektorel gant ho merdeer. Setu aze an daskorerioù skoret evit ar poent :\n${renderers}",'componentShouldBe':"addFeatures : bez\' e tlefe ar parzh besañ eus ar seurt ${geomType}",'getFeatureError':"Galvet eo bet getFeatureFromEvent called war ur gwiskad hep daskorer. Kement-se a dalvez ez eus bet freuzet ur gwiskad hag hoc\'h eus miret un embreger bennak stag outañ.",'minZoomLevelError':"Ne zleer implijout ar perzh minZoomLevel nemet evit gwiskadoù FixedZoomLevels-descendent. Ar fed ma wiria ar gwiskad WHS-se hag-eñ ez eus eus minZoomLevel zo un aspadenn gozh. Koulskoude n\'omp ket evit e ziverkañ kuit da derriñ arloadoù diazezet war OL a c\'hallfe bezañ stag outañ. Setu perak eo dispredet -- Lamet kuit e vo ar gwiriañ minZoomLevel a-is er stumm 3.0. Ober gant an arventennoù bihanañ/brasañ evel deskrivet amañ e plas : http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Treuzgread WFS : MAT EO ${response}",'commitFailed':"Treuzgread WFS Transaction: C\'HWITET ${response}",'googleWarning':"N\'eus ket bet gallet kargañ ar gwiskad Google ent reizh.\x3cbr\x3e\x3cbr\x3eEvit en em zizober eus ar c\'hemenn-mañ, dibabit ur BaseLayer nevez en diuzer gwiskadoù er c\'horn dehoù el laez.\x3cbr\x3e\x3cbr\x3eSur a-walc\'h eo peogwir n\'eo ket bet ensoc\'het levraoueg Google Maps pe neuze ne glot ket an alc\'hwez API gant ho lec\'hienn.\x3cbr\x3e\x3cbr\x3eDiorroerien : Evit reizhañ an dra-se, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3eclick here\x3c/a\x3e",'getLayerWarning':"N\'haller ket kargañ ar gwiskad ${layerType} ent reizh.\x3cbr\x3e\x3cbr\x3eEvit en em zizober eus ar c\'hemenn-mañ, dibabit ur BaseLayer nevez en diuzer gwiskadoù er c\'horn dehoù el laez.\x3cbr\x3e\x3cbr\x3eSur a-walc\'h eo peogwir n\'eo ket bet ensoc\'het mat al levraoueg ${layerLib}.\x3cbr\x3e\x3cbr\x3eDiorroerien : Evit gouzout penaos reizhañ an dra-se, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3eclick here\x3c/a\x3e",'scale':"Skeul = 1 : ${scaleDenom}",'W':"K",'E':"R",'N':"N",'S':"S",'layerAlreadyAdded':"Klasket hoc\'h eus ouzhpennañ ar gwiskad : ${layerName} d\'ar gartenn, met ouzhpennet e oa bet c\'hoazh",'reprojectDeprecated':"Emaoc\'h oc\'h implijout an dibarzh \'reproject\' war ar gwiskad ${layerName}. Dispredet eo an dibarzh-mañ : bet eo hag e talveze da ziskwel roadennoù war-c\'horre kartennoù diazez kenwerzhel, un dra hag a c\'haller ober bremañ gant an arc\'hwel dre skor banndres boullek Mercator. Muioc\'h a ditouroù a c\'haller da gaout war http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Dispredet eo an daore-se ha tennet e vo kuit eus ar stumm 3.0. Grit gant ${newMethod} e plas.",'boundsAddError':"Rekis eo tremen an div dalvoudenn x ha y d\'an arc\'hwel add.",'lonlatAddError':"Rekis eo tremen an div dalvoudenn hedred ha ledred d\'an arc\'hwel add.",'pixelAddError':"Rekis eo tremen an div dalvoudenn x ha y d\'an arc\'hwel add.",'unsupportedGeometryType':"Seurt mentoniezh anskoret : ${geomType}",'pagePositionFailed':"C\'hwitet eo OpenLayers.Util.pagePosition : marteze emañ lec\'hiet fall an elfenn id ${elemId}.",'filterEvaluateNotImplemented':"N\'eo ket bet emplementet ar priziañ evit seurt siloù c\'hoazh."});OpenLayers.Lang["el"]=OpenLayers.Util.applyDefaults({'scale':"Κλίμακα ~ 1 : ${scaleDenom}"});OpenLayers.Lang.en={'unhandledRequest':"Unhandled request return ${statusText}",'permalink':"Permalink",'overlays':"Overlays",'baseLayer':"Base Layer",'sameProjection':"The overview map only works when it is in the same projection as the main map",'readNotImplemented':"Read not implemented.",'writeNotImplemented':"Write not implemented.",'noFID':"Can't update a feature for which there is no FID.",'errorLoadingGML':"Error in loading GML file ${url}",'browserNotSupported':"Your browser does not support vector rendering. Currently supported renderers are:\n${renderers}",'componentShouldBe':"addFeatures : component should be an ${geomType}",'getFeatureError':"getFeatureFromEvent called on layer with no renderer. This usually means you "+"destroyed a layer, but not some handler which is associated with it.",'minZoomLevelError':"The minZoomLevel property is only intended for use "+"with the FixedZoomLevels-descendent layers. That this "+"wfs layer checks for minZoomLevel is a relic of the"+"past. We cannot, however, remove it without possibly "+"breaking OL based applications that may depend on it."+" Therefore we are deprecating it -- the minZoomLevel "+"check below will be removed at 3.0. Please instead "+"use min/max resolution setting as described here: "+"http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"WFS Transaction: SUCCESS ${response}",'commitFailed':"WFS Transaction: FAILED ${response}",'googleWarning':"The Google Layer was unable to load correctly.<br><br>"+"To get rid of this message, select a new BaseLayer "+"in the layer switcher in the upper-right corner.<br><br>"+"Most likely, this is because the Google Maps library "+"script was either not included, or does not contain the "+"correct API key for your site.<br><br>"+"Developers: For help getting this working correctly, "+"<a href='http://trac.openlayers.org/wiki/Google' "+"target='_blank'>click here</a>",'getLayerWarning':"The ${layerType} Layer was unable to load correctly.<br><br>"+"To get rid of this message, select a new BaseLayer "+"in the layer switcher in the upper-right corner.<br><br>"+"Most likely, this is because the ${layerLib} library "+"script was not correctly included.<br><br>"+"Developers: For help getting this working correctly, "+"<a href='http://trac.openlayers.org/wiki/${layerLib}' "+"target='_blank'>click here</a>",'scale':"Scale = 1 : ${scaleDenom}",'W':'W','E':'E','N':'N','S':'S','graticule':'Graticule','layerAlreadyAdded':"You tried to add the layer: ${layerName} to the map, but it has already been added",'reprojectDeprecated':"You are using the 'reproject' option "+"on the ${layerName} layer. This option is deprecated: "+"its use was designed to support displaying data over commercial "+"basemaps, but that functionality should now be achieved by using "+"Spherical Mercator support. More information is available from "+"http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"This method has been deprecated and will be removed in 3.0. "+"Please use ${newMethod} instead.",'boundsAddError':"You must pass both x and y values to the add function.",'lonlatAddError':"You must pass both lon and lat values to the add function.",'pixelAddError':"You must pass both x and y values to the add function.",'unsupportedGeometryType':"Unsupported geometry type: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition failed: element with id ${elemId} may be misplaced.",'filterEvaluateNotImplemented':"evaluate is not implemented for this filter type.",'end':''};OpenLayers.Lang["fi"]=OpenLayers.Util.applyDefaults({'permalink':"Ikilinkki",'overlays':"Kerrokset",'baseLayer':"Peruskerros",'sameProjection':"Yleiskuvakarttaa voi käyttää vain, kun sillä on sama projektio kuin pääkartalla.",'W':"L",'E':"I",'N':"P",'S':"E"});OpenLayers.Lang["fur"]=OpenLayers.Util.applyDefaults({'permalink':"Leam Permanent",'overlays':"Livei parsore",'baseLayer':"Livel di base",'browserNotSupported':"Il to sgarfadôr nol supuarte la renderizazion vetoriâl. Al moment a son supuartâts:\n${renderers}",'scale':"Scjale = 1 : ${scaleDenom}",'W':"O",'E':"E",'N':"N",'S':"S"});OpenLayers.Lang["gl"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Solicitude non xerada; a resposta foi: ${statusText}",'permalink':"Ligazón permanente",'overlays':"Capas superpostas",'baseLayer':"Capa base",'sameProjection':"A vista xeral do mapa só funciona cando está na mesma proxección có mapa principal",'readNotImplemented':"Lectura non implementada.",'writeNotImplemented':"Escritura non implementada.",'noFID':"Non se pode actualizar a funcionalidade para a que non hai FID.",'errorLoadingGML':"Erro ao cargar o ficheiro GML ${url}",'browserNotSupported':"O seu navegador non soporta a renderización de vectores. Os renderizadores soportados actualmente son:\n${renderers}",'componentShouldBe':"addFeatures: o compoñente debera ser de tipo ${geomType}",'getFeatureError':"getFeatureFromEvent ten sido chamado a unha capa sen renderizador. Isto normalmente significa que destruíu unha capa, mais non o executador que está asociado con ela.",'minZoomLevelError':"A propiedade minZoomLevel é só para uso conxuntamente coas capas FixedZoomLevels-descendent. O feito de que esa capa wfs verifique o minZoomLevel é unha reliquia do pasado. Non podemos, con todo, eliminala sen a posibilidade de non romper as aplicacións baseadas en OL que poidan depender dela. Por iso a estamos deixando obsoleta (a comprobación minZoomLevel de embaixo será eliminada na versión 3.0). Por favor, no canto diso use o axuste de resolución mín/máx tal e como está descrito aquí: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Transacción WFS: ÉXITO ${response}",'commitFailed':"Transacción WFS: FALLIDA ${response}",'googleWarning':"A capa do Google non puido cargarse correctamente.\x3cbr\x3e\x3cbr\x3ePara evitar esta mensaxe, escolla unha nova capa base no seleccionador de capas na marxe superior dereita.\x3cbr\x3e\x3cbr\x3eProbablemente, isto acontece porque a escritura da libraría do Google Maps ou ben non foi incluída ou ben non contén a clave API correcta para o seu sitio.\x3cbr\x3e\x3cbr\x3eDesenvolvedores: para axudar a facer funcionar isto correctamente, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3epremede aquí\x3c/a\x3e",'getLayerWarning':"A capa ${layerType} foi incapaz de cargarse correctamente.\x3cbr\x3e\x3cbr\x3ePara evitar esta mensaxe, escolla unha nova capa base no seleccionador de capas na marxe superior dereita.\x3cbr\x3e\x3cbr\x3eProbablemente, isto acontece porque a escritura da libraría ${layerLib} non foi ben incluída.\x3cbr\x3e\x3cbr\x3eDesenvolvedores: para axudar a facer funcionar isto correctamente, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3epremede aquí\x3c/a\x3e",'scale':"Escala = 1 : ${scaleDenom}",'W':"O",'E':"L",'N':"N",'S':"S",'layerAlreadyAdded':"Intentou engadir a capa: ${layerName} ao mapa, pero xa fora engadida",'reprojectDeprecated':"Está usando a opción \"reproject\" na capa ${layerName}. Esta opción está obsoleta: o seu uso foi deseñado para a visualización de datos sobre mapas base comerciais, pero esta funcionalidade debera agora ser obtida utilizando a proxección Spherical Mercator. Hai dispoñible máis información en http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Este método está obsoleto e será eliminado na versión 3.0. Por favor, no canto deste use ${newMethod}.",'boundsAddError':"Debe achegar os valores x e y á función add.",'lonlatAddError':"Debe achegar tanto o valor lon coma o lat á función add.",'pixelAddError':"Debe achegar os valores x e y á función add.",'unsupportedGeometryType':"Tipo xeométrico non soportado: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition fallou: o elemento con id ${elemId} pode non estar na súa posición.",'filterEvaluateNotImplemented':"avaliar non está implementado para este tipo de filtro."});OpenLayers.Lang["gsw"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Nit behandleti Aafrogsruckmäldig ${statusText}",'permalink':"Permalink",'overlays':"Iberlagerige",'baseLayer':"Grundcharte",'sameProjection':"D Ibersichts-Charte funktioniert nume, wänn si di glych Projäktion brucht wie d Hauptcharte",'readNotImplemented':"Läse nit implementiert.",'writeNotImplemented':"Schrybe nit implementiert.",'noFID':"E Feature, wu s kei FID derfir git, cha nit aktualisiert wäre.",'errorLoadingGML':"Fähler bim Lade vu dr GML-Datei ${url}",'browserNotSupported':"Dyy Browser unterstitzt kei Vektordarstellig. Aktuäll unterstitzti Renderer:\n${renderers}",'componentShouldBe':"addFeatures : Komponänt sott dr Typ ${geomType} syy",'getFeatureError':"getFeatureFromEvent isch uf eme Layer ohni Renderer ufgruefe wore. Des heisst normalerwys, ass Du e Layer kaputt gmacht hesch, aber nit dr Handler, wu derzue ghert.",'minZoomLevelError':"D minZoomLevel-Eigeschaft isch nume dänk fir d Layer, wu vu dr FixedZoomLevels abstamme. Ass dää wfs-Layer minZoomLevel prieft, scih e Relikt us dr Vergangeheit. Mir chenne s aber nit ändere ohni OL_basierti Aawändige villicht kaputt gehn, wu dervu abhänge.  Us däm Grund het die Funktion d Eigeschaft \'deprecated\' iberchuu. D minZoomLevel-Priefig unte wird in dr Version 3.0 usegnuu. Bitte verwänd statt däm e min/max-Uflesig wie s do bschriben isch: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"WFS-Transaktion: ERFOLGRYCH ${response}",'commitFailed':"WFS-Transaktion: FÄHLGSCHLAA ${response}",'googleWarning':"Dr Google-Layer het nit korräkt chenne glade wäre.\x3cbr\x3e\x3cbr\x3eGo die Mäldig nimi z kriege, wehl e andere Hintergrundlayer us em LayerSwitcher im rächte obere Ecke.\x3cbr\x3e\x3cbr\x3eDää Fähler git s seli hyfig, wel s Skript vu dr Google-Maps-Bibliothek nit yybunde woren isch oder wel s kei giltige API-Schlissel fir Dyy URL din het.\x3cbr\x3e\x3cbr\x3eEntwickler: Fir Hilf zum korräkte Yybinde vum Google-Layer \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3edoo drucke\x3c/a\x3e",'getLayerWarning':"Dr ${layerType}-Layer het nit korräkt chenne glade wäre.\x3cbr\x3e\x3cbr\x3eGo die Mäldig nimi z kriege, wehl e andere Hintergrundlayer us em LayerSwitcher im rächte obere Ecke.\x3cbr\x3e\x3cbr\x3eDää Fähler git s seli hyfig, wel s Skript vu dr \'${layerLib}\'-Bibliothek nit yybunde woren isch oder wel s kei giltige API-Schlissel fir Dyy URL din het.\x3cbr\x3e\x3cbr\x3eEntwickler: Fir Hilf zum korräkte Yybinde vu Layer \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3edoo drucke\x3c/a\x3e",'scale':"Maßstab = 1 : ${scaleDenom}",'W':"W",'E':"O",'N':"N",'S':"S",'layerAlreadyAdded':"Du hesch versuecht dää Layer in d Charte yyzfiege: ${layerName}, aber är isch schoi yygfiegt",'reprojectDeprecated':"Du bruchsch d \'reproject\'-Option bim ${layerName}-Layer. Die Option isch nimi giltig: si isch aagleit wore go   Date iber kommerziälli Grundcharte lege, aber des sott mer jetz mache mit dr Unterstitzig vu Spherical Mercator. Meh Informatione git s uf http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Die Methode isch veraltet un wird us dr Version 3.0 usegnuu. Bitte verwäbnd statt däm ${newMethod}.",'boundsAddError':"Du muesch e x-Wärt un e y-Wärt yygee bi dr Zuefieg-Funktion",'lonlatAddError':"Du meusch e Lengi- un e Breiti-Grad yygee bi dr Zuefieg-Funktion.",'pixelAddError':"Du muesch x- un y-Wärt aagee bi dr Zuefieg-Funktion.",'unsupportedGeometryType':"Nit unterstitze Geometrii-Typ: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition fählgschlaa: Elemänt mit ID ${elemId} isch villicht falsch gsetzt.",'filterEvaluateNotImplemented':"evaluiere isch nit implemäntiert in däm Filtertyp."});OpenLayers.Lang["hr"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Nepodržani zahtjev ${statusText}",'permalink':"Permalink",'overlays':"Overlays",'baseLayer':"Osnovna karta",'sameProjection':"Pregledna karta radi jedino kao je u istoj projekciji kao i glava karta",'readNotImplemented':"Čitanje nije implementirano.",'writeNotImplemented':"Pisanje nije implementirano.",'noFID':"Ne mogu ažurirati značajku za koju ne postoji FID.",'errorLoadingGML':"Greška u učitavanju GML datoteke ${url}",'browserNotSupported':"Vaš preglednik ne podržava vektorsko renderiranje. Trenutno podržani rendereri su: ${renderers}",'componentShouldBe':"addFeatures : komponenta bi trebala biti ${geomType}",'getFeatureError':"getFeatureFromEvent je pozvao Layer bez renderera. Ovo obično znači da ste uništiili Layer, a ne neki Handler koji je povezan s njim.",'commitSuccess':"WFS Transakcija: USPJEŠNA ${response}",'commitFailed':"WFS Transakcija: NEUSPJEŠNA ${response}",'scale':"Mjerilo = 1 : ${scaleDenom}",'layerAlreadyAdded':"Pokušali ste dodati layer:  ${layerName} na kartu, ali je već dodan",'methodDeprecated':"Ova metoda nije odobrena i biti će maknuta u 3.0. Koristite ${newMethod}.",'boundsAddError':"Morate dati obje vrijednosti ,  x i y  da bi dodali funkciju.",'lonlatAddError':"Morate dati obje vrijednosti , (lon i lat) da bi dodali funkciju.",'pixelAddError':"Morate dati obje vrijednosti ,  x i y  da bi dodali funkciju.",'unsupportedGeometryType':"Nepodržani tip geometrije: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition nije uspjelo: element sa id ${elemId} može biti krivo smješten."});OpenLayers.Lang["hsb"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Wotmołwa njewobdźěłaneho naprašowanja ${statusText}",'permalink':"Trajny wotkaz",'overlays':"Naworštowanja",'baseLayer':"Zakładna runina",'sameProjection':"Přehladowa karta jenož funguje, hdyž je w samsnej projekciji kaž hłowna karta",'readNotImplemented':"Čitanje njeimplementowane.",'writeNotImplemented':"Pisanje njeimplementowane.",'noFID':"Funkcija, za kotruž FID njeje, njeda so aktualizować.",'errorLoadingGML':"Zmylk při začitowanju dataje ${url}",'browserNotSupported':"Twój wobhladowak wektorowe rysowanje njepodpěruje. Tuchwilu podpěrowane rysowaki su:\n${renderers}",'componentShouldBe':"addFeatures: komponenta měła ${geomType} być",'getFeatureError':"getFeatureFromEvent bu na woršće bjez rysowak zawołany. To zwjetša woznamjenja, zo sy worštu zničił, ale nic wobdźěłak, kotryž je z njej zwjazany.",'minZoomLevelError':"Kajkosć minZoomLevel je jenož za wužiwanje z worštami myslena, kotrež wot FixedZoomLevels pochadźeja. Zo tuta woršta wfs za minZoomLevel přepruwuje, je relikt zańdźenosće. Njemóžemy wšak ju wotstronić, bjeztoho zo aplikacije, kotrež na OpenLayers bazěruja a snano tutu kajkosć wužiwaja, hižo njefunguja. Tohodla smy ju jako zestarjenu woznamjenili -- přepruwowanje za minZoomLevel budu so we wersiji 3.0 wotstronjeć. Prošu wužij město toho nastajenje min/max, kaž je tu wopisane: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"WFS-Transakcija: WUSPĚŠNA ${response}",'commitFailed':"WFS-Transakcija: NJEPORADŹENA ${response}",'googleWarning':"Woršta Google njemóžeše so korektnje začitać.\x3cbr\x3e\x3cbr\x3eZo by tutu zdźělenku wotbył, wubjer nowy BaseLayer z wuběra worštow horjeka naprawo.\x3cbr\x3e\x3cbr\x3eNajskerje so to stawa, dokelž skript biblioteki Google Maps pak njebu zapřijaty pak njewobsahuje korektny kluč API za twoje sydło.\x3cbr\x3e\x3cbr\x3eWuwiwarjo: Za pomoc ke korektnemu fungowanju worštow\n\x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3etu kliknyć\x3c/a\x3e",'getLayerWarning':"Woršta ${layerType} njemóžeše so korektnje začitać.\x3cbr\x3e\x3cbr\x3eZo by tutu zdźělenku wotbył, wubjer nowy BaseLayer z wuběra worštow horjeka naprawo.\x3cbr\x3e\x3cbr\x3eNajskerje so to stawa, dokelž skript biblioteki ${layerLib} njebu korektnje zapřijaty.\x3cbr\x3e\x3cbr\x3eWuwiwarjo: Za pomoc ke korektnemu fungowanju worštow\n\x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3etu kliknyć\x3c/a\x3e",'scale':"Měritko = 1 : ${scaleDenom}",'W':"Z",'E':"W",'N':"S",'S':"J",'layerAlreadyAdded':"Sy spytał runinu ${layerName} karće dodać, ale je so hižo dodała",'reprojectDeprecated':"Wužiwaš opciju \"reproject\" wořšty ${layerName}. Tuta opcija je zestarjena: jeje wužiwanje bě myslene, zo by zwobraznjenje datow nad komercielnymi bazowymi kartami podpěrało, ale funkcionalnosć měła so nětko z pomocu Sperical Mercator docpěć. Dalše informacije steja na http://trac.openlayers.org/wiki/SphericalMercator k dispoziciji.",'methodDeprecated':"Tuta metoda je so njeschwaliła a budźe so w 3.0 wotstronjeć. Prošu wužij ${newMethod} město toho.",'boundsAddError':"Dyrbiš hódnotu x kaž tež y funkciji \"add\" přepodać.",'lonlatAddError':"Dyrbiš hódnotu lon kaž tež lat funkciji \"add\" přepodać.",'pixelAddError':"Dyrbiš hódnotu x kaž tež y funkciji \"add\" přepodać.",'unsupportedGeometryType':"Njepodpěrowany geometrijowy typ: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition je so njeporadźił: element z id ${elemId} bu snano wopak zaměstnjeny.",'filterEvaluateNotImplemented':"wuhódnoćenje njeje za tutón filtrowy typ implementowany."});OpenLayers.Lang["hu"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Nem kezelt kérés visszatérése ${statusText}",'permalink':"Permalink",'overlays':"Rávetítések",'baseLayer':"Alapréteg",'sameProjection':"Az áttekintő térkép csak abban az esetben működik, ha ugyanazon a vetületen van, mint a fő térkép.",'readNotImplemented':"Olvasás nincs végrehajtva.",'writeNotImplemented':"Írás nincs végrehajtva.",'noFID':"Nem frissíthető olyan jellemző, amely nem rendelkezik FID-del.",'errorLoadingGML':"Hiba GML-fájl betöltésekor ${url}",'browserNotSupported':"A böngészője nem támogatja a vektoros renderelést. A jelenleg támogatott renderelők:\n${renderers}",'componentShouldBe':"addFeatures : az összetevőnek ilyen típusúnak kell lennie: ${geomType}",'getFeatureError':"getFeatureFromEvent réteget hívott meg renderelő nélkül. Ez rendszerint azt jelenti, hogy megsemmisített egy fóliát, de néhány ahhoz társított kezelőt nem.",'minZoomLevelError':"A minZoomLevel tulajdonságot csak a következővel való használatra szánták: FixedZoomLevels-leszármazott fóliák. Ez azt jelenti, hogy a minZoomLevel wfs fólia jelölőnégyzetei már a múlté. Mi azonban nem távolíthatjuk el annak a veszélye nélkül, hogy az esetlegesen ettől függő OL alapú alkalmazásokat tönkretennénk. Ezért ezt érvénytelenítjük -- a minZoomLevel az alul levő jelölőnégyzet a 3.0-s verzióból el lesz távolítva. Kérjük, helyette használja a  min/max felbontás beállítást, amelyről az alábbi helyen talál leírást: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"WFS tranzakció: SIKERES ${response}",'commitFailed':"WFS tranzakció: SIKERTELEN ${response}",'googleWarning':"A Google fólia betöltése sikertelen.\x3cbr\x3e\x3cbr\x3eAhhoz, hogy ez az üzenet eltűnjön, válasszon egy új BaseLayer fóliát a jobb felső sarokban található fóliakapcsoló segítségével.\x3cbr\x3e\x3cbr\x3eNagy valószínűséggel ez azért van, mert a Google Maps könyvtár parancsfájlja nem található, vagy nem tartalmazza az Ön oldalához tartozó megfelelő API-kulcsot.\x3cbr\x3e\x3cbr\x3eFejlesztőknek: A helyes működtetésre vonatkozó segítség az alábbi helyen érhető el, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3ekattintson ide\x3c/a\x3e",'getLayerWarning':"A(z) ${layerType} fólia nem töltődött be helyesen.\x3cbr\x3e\x3cbr\x3eAhhoz, hogy ez az üzenet eltűnjön, válasszon egy új BaseLayer fóliát a jobb felső sarokban található fóliakapcsoló segítségével.\x3cbr\x3e\x3cbr\x3eNagy valószínűséggel ez azért van, mert a(z) ${layerLib} könyvtár parancsfájlja helytelen.\x3cbr\x3e\x3cbr\x3eFejlesztőknek: A helyes működtetésre vonatkozó segítség az alábbi helyen érhető el, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3ekattintson ide\x3c/a\x3e",'scale':"Lépték = 1 : ${scaleDenom}",'W':"Ny",'E':"K",'N':"É",'S':"D",'layerAlreadyAdded':"Megpróbálta hozzáadni a(z) ${layerName} fóliát a térképhez, de az már hozzá van adva",'reprojectDeprecated':"Ön a \'reproject\' beállítást használja a(z) ${layerName} fólián. Ez a beállítás érvénytelen: használata az üzleti alaptérképek fölötti adatok megjelenítésének támogatására szolgált, de ezt a funkció ezentúl a Gömbi Mercator használatával érhető el. További információ az alábbi helyen érhető el: http://trac.openlayers.org/wiki/SphericalMercator",'methodDeprecated':"Ez a módszer érvénytelenítve lett és a 3.0-s verzióból el lesz távolítva. Használja a(z) ${newMethod} módszert helyette.",'boundsAddError':"Az x és y értékeknek egyaránt meg kell felelnie, hogy a funkciót hozzáadhassa.",'lonlatAddError':"A hossz. és szél. értékeknek egyaránt meg kell felelnie, hogy a funkciót hozzáadhassa.",'pixelAddError':"Az x és y értékeknek egyaránt meg kell felelnie, hogy a funkciót hozzáadhassa.",'unsupportedGeometryType':"Nem támogatott geometriatípus: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition sikertelen: lehetséges, hogy a(z) ${elemId} azonosítójú elem téves helyre került.",'filterEvaluateNotImplemented':"ennél a szűrőtípusnál kiértékelés nem hajtódik végre."});OpenLayers.Lang["ia"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Le responsa a un requesta non esseva maneate: ${statusText}",'permalink':"Permaligamine",'overlays':"Superpositiones",'baseLayer':"Strato de base",'sameProjection':"Le mini-carta functiona solmente si illo es in le mesme projection que le carta principal",'readNotImplemented':"Lectura non implementate.",'writeNotImplemented':"Scriptura non implementate.",'noFID':"Non pote actualisar un elemento sin FID.",'errorLoadingGML':"Error al cargamento del file GML ${url}",'browserNotSupported':"Tu navigator non supporta le rendition de vectores. Le renditores actualmente supportate es:\n${renderers}",'componentShouldBe':"addFeatures: le componente debe esser del typo ${geomType}",'getFeatureError':"getFeatureFromEvent ha essite appellate in un strato sin renditor. Isto significa generalmente que tu ha destruite un strato, ma lassava un gestor associate con illo.",'minZoomLevelError':"Le proprietate minZoomLevel es solmente pro uso con le stratos descendente de FixedZoomLevels. Le facto que iste strato WFS verifica minZoomLevel es un reliquia del passato. Nonobstante, si nos lo remove immediatemente, nos pote rumper applicationes a base de OL que depende de illo. Ergo nos lo declara obsolete; le verification de minZoomLevel in basso essera removite in version 3.0. Per favor usa in su loco le configuration de resolutiones min/max como describite a: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Transaction WFS: SUCCESSO ${response}",'commitFailed':"Transaction WFS: FALLEVA ${response}",'googleWarning':"Le strato Google non poteva esser cargate correctemente.\x3cbr\x3e\x3cbr\x3ePro disfacer te de iste message, selige un nove BaseLayer in le selector de strato in alto a dextra.\x3cbr\x3e\x3cbr\x3eMulto probabilemente, isto es proque le script del libreria de Google Maps non esseva includite o non contine le clave API correcte pro tu sito.\x3cbr\x3e\x3cbr\x3eDisveloppatores: Pro adjuta de corriger isto, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3eclicca hic\x3c/a",'getLayerWarning':"Le strato ${layerType} non poteva esser cargate correctemente.\x3cbr\x3e\x3cbr\x3ePro disfacer te de iste message, selige un nove BaseLayer in le selector de strato in alto a dextra.\x3cbr\x3e\x3cbr\x3eMulto probabilemente, isto es proque le script del libreria de ${layerLib} non esseva correctemente includite.\x3cbr\x3e\x3cbr\x3eDisveloppatores: Pro adjuta de corriger isto, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3eclicca hic\x3c/a\x3e",'scale':"Scala = 1 : ${scaleDenom}",'W':"W",'E':"E",'N':"N",'S':"S",'layerAlreadyAdded':"Tu tentava adder le strato: ${layerName} al carta, ma illo es ja presente",'reprojectDeprecated':"Tu usa le option \'reproject\' in le strato ${layerName} layer. Iste option es obsolescente: illo esseva pro poter monstrar datos super cartas de base commercial, ma iste functionalitate pote ora esser attingite con le uso de Spherical Mercator. Ulterior information es disponibile a http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Iste methodo ha essite declarate obsolescente e essera removite in version 3.0. Per favor usa ${newMethod} in su loco.",'boundsAddError':"Tu debe passar le duo valores x e y al function add.",'lonlatAddError':"Tu debe passar le duo valores lon e lat al function add.",'pixelAddError':"Tu debe passar le duo valores x e y al function add.",'unsupportedGeometryType':"Typo de geometria non supportate: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition falleva: le elemento con id ${elemId} pote esser mal placiate.",'filterEvaluateNotImplemented':"\"evaluate\" non es implementate pro iste typo de filtro."});OpenLayers.Lang["id"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Permintaan yang tak tertangani menghasilkan ${statusText}",'permalink':"Pranala permanen",'overlays':"Hamparan",'baseLayer':"Lapisan Dasar",'sameProjection':"Peta tinjauan hanya bekerja bila dalam proyeksi yang sama dengan peta utama",'readNotImplemented':"Membaca tidak diterapkan.",'writeNotImplemented':"Menyimpan tidak diterapkan.",'noFID':"Tidak dapat memperbarui fitur yang tidak memiliki FID.",'errorLoadingGML':"Kesalahan dalam memuat berkas GML ${url}",'browserNotSupported':"Peramban Anda tidak mendukung penggambaran vektor. Penggambar yang didukung saat ini adalah:\n${renderers}",'componentShouldBe':"addFeatures : komponen harus berupa ${geomType}",'getFeatureError':"getFeatureFromEvent diterapkan pada lapisan tanpa penggambar. Ini biasanya berarti Anda menghapus sebuah lapisan, tetapi tidak menghapus penangan yang terkait dengannya.",'minZoomLevelError':"Properti minZoomLevel hanya ditujukan bekerja dengan lapisan FixedZoomLevels-descendent. Pengecekan minZoomLevel oleh lapisan wfs adalah peninggalan masa lalu. Kami tidak dapat menghapusnya tanpa kemungkinan merusak aplikasi berbasis OL yang mungkin bergantung padanya. Karenanya, kami menganggapnya tidak berlaku -- Cek minZoomLevel di bawah ini akan dihapus pada 3.0. Silakan gunakan penyetelan resolusi min/maks seperti dijabarkan di sini: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"WFS Transaksi: BERHASIL ${respon}",'commitFailed':"WFS Transaksi: GAGAL ${respon}",'googleWarning':"Lapisan Google tidak dapat dimuat dengan benar.\x3cbr\x3e\x3cbr\x3eUntuk menghilangkan pesan ini, pilih suatu BaseLayer baru melalui penukar lapisan (layer switcher) di ujung kanan atas.\x3cbr\x3e\x3cbr\x3eKemungkinan besar ini karena pustaka skrip Google Maps tidak disertakan atau tidak mengandung kunci API yang tepat untuk situs Anda.\x3cbr\x3e\x3cbr\x3ePengembang: Untuk bantuan mengatasi masalah ini, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3eklik di sini\x3c/a\x3e",'getLayerWarning':"Lapisan ${layerType} tidak dapat dimuat dengan benar.\x3cbr\x3e\x3cbr\x3eUntuk menghilangkan pesan ini, pilih suatu BaseLayer baru melalui penukar lapisan (layer switcher) di ujung kanan atas.\x3cbr\x3e\x3cbr\x3eKemungkinan besar ini karena pustaka skrip Google Maps tidak disertakan dengan benar.\x3cbr\x3e\x3cbr\x3ePengembang: Untuk bantuan mengatasi masalah ini, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3eklik di sini\x3c/a\x3e",'scale':"Sekala = 1 : ${scaleDenom}",'W':"B",'E':"T",'N':"U",'S':"S",'layerAlreadyAdded':"Anda mencoba menambahkan lapisan: ${layerName} ke dalam peta, tapi lapisan itu telah ditambahkan",'reprojectDeprecated':"Anda menggunakan opsi \'reproject\' pada lapisan ${layerName}. Opsi ini telah ditinggalkan: penggunaannya dirancang untuk mendukung tampilan data melalui peta dasar komersial, tapi fungsionalitas tersebut saat ini harus dilakukan dengan menggunakan dukungan Spherical Mercator. Informasi lebih lanjut tersedia di http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Metode ini telah usang dan akan dihapus di 3.0. Sebaliknya, harap gunakan ${newMethod}.",'boundsAddError':"Anda harus memberikan kedua nilai x dan y ke fungsi penambah.",'lonlatAddError':"Anda harus memberikan kedua nilai lon dan lat ke fungsi penambah.",'pixelAddError':"Anda harus memberikan kedua nilai x dan y ke fungsi penambah.",'unsupportedGeometryType':"Tipe geometri tak didukung: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition gagal: elemen dengan id ${elemId} mungkin salah tempat.",'filterEvaluateNotImplemented':"evaluasi tidak tersedia untuk tipe filter ini."});OpenLayers.Lang["io"]=OpenLayers.Util.applyDefaults({'scale':"Skalo = 1 : ${scaleDenom}"});OpenLayers.Lang["is"]=OpenLayers.Util.applyDefaults({'permalink':"Varanlegur tengill",'overlays':"Þekjur",'baseLayer':"Grunnlag",'sameProjection':"Yfirlitskortið virkar aðeins ef það er í sömu vörpun og aðalkortið",'readNotImplemented':"Skrifun er óútfærð.",'writeNotImplemented':"Lestur er óútfærður.",'errorLoadingGML':"Villa kom upp við að hlaða inn GML skránni ${url}",'scale':"Skali = 1 : ${scaleDenom}",'layerAlreadyAdded':"Þú reyndir að bæta laginu ${layerName} á kortið en það er þegar búið að bæta því við",'methodDeprecated':"Þetta fall hefur verið úrelt og verður fjarlægt í 3.0. Notaðu ${newMethod} í staðin."});OpenLayers.Lang["ja"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"未処理の要求は ${statusText} を返します",'permalink':"パーマリンク",'overlays':"オーバーレイ",'baseLayer':"基底レイヤー",'sameProjection':"概観地図はメインの地図と同じ投影法をとる場合のみ機能します",'readNotImplemented':"読み込みは実装されていません。",'writeNotImplemented':"書き込みは実装されていません。",'noFID':"FID のない地物は更新できません。",'errorLoadingGML':"GML ファイル ${url} の読み込みエラー",'browserNotSupported':"あなたのブラウザはベクターグラフィックスの描写に対応していません。現時点で対応しているソフトウェアは以下のものです。\n${renderers}",'componentShouldBe':"addFeatures: 要素は ${geomType} であるべきです",'getFeatureError':"getFeatureFromEvent がレンダラーのないレイヤーから呼ばれました。通常、これはあなたがレイヤーを、それに関連づけられたいくつかのハンドラを除いて、破壊してしまったことを意味します。",'minZoomLevelError':"minZoomLevel プロパティは FixedZoomLevels を継承するレイヤーでの使用のみを想定しています。この minZoomLevel に対する WFS レイヤーの検査は歴史的なものです。しかしながら、この検査を除去するとそれに依存する OpenLayers ベースのアプリケーションを破壊してしまう可能性があります。よって廃止が予定されており、この minZoomLevel 検査はバージョン3.0で除去されます。代わりに、http://trac.openlayers.org/wiki/SettingZoomLevels で解説されている、最小および最大解像度設定を使用してください。",'commitSuccess':"WFS トランザクション: 成功 ${response}",'commitFailed':"WFS トランザクション: 失敗 ${response}",'googleWarning':"Google レイヤーが正しく読み込みを行えませんでした。\x3cbr\x3e\x3cbr\x3eこのメッセージを消すには、右上の隅にあるレイヤー切り替え部分で新しい基底レイヤーを選んでください。\x3cbr\x3e\x3cbr\x3eおそらく、これは Google マップ用ライブラリのスクリプトが組み込まれていないか、あなたのサイトに対応する正しい API キーが設定されていないためです。\x3cbr\x3e\x3cbr\x3e開発者の方へ: 正しい動作をさせるために\x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3eこちらのウィキ\x3c/a\x3eを参照してください。",'getLayerWarning':"${layerType} レイヤーが正しく読み込みを行えませんでした。\x3cbr\x3e\x3cbr\x3eこのメッセージを消すには、右上の隅にあるレイヤー切り替え部分で新しい基底レイヤーを選んでください。\x3cbr\x3e\x3cbr\x3eおそらく、これは ${layerLib} ライブラリのスクリプトが正しく組み込まれていないためです。\x3cbr\x3e\x3cbr\x3e開発者の方へ: 正しい動作をさせるために\x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3eこちらのウィキ\x3c/a\x3eを参照してください。",'scale':"縮尺 = 1 : ${scaleDenom}",'W':"西",'E':"東",'N':"北",'S':"南",'layerAlreadyAdded':"あなたは「${layerName}」を地図に追加しようと試みましたが、そのレイヤーは既に追加されています",'reprojectDeprecated':"あなたは「${layerName}」レイヤーで reproject オプションを使っています。このオプションは商用の基底地図上に情報を表示する目的で設計されましたが、現在ではその機能は Spherical Mercator サポートを利用して実現されており、このオプションの使用は非推奨です。追加の情報は http://trac.openlayers.org/wiki/SphericalMercator で入手できます。",'methodDeprecated':"このメソッドは廃止が予定されており、バージョン3.0で除去されます。代わりに ${newMethod} を使用してください。",'boundsAddError':"x と y 両方の値を add 関数に渡さなければなりません。",'lonlatAddError':"lon と lat 両方の値を add 関数に渡さなければなりません。",'pixelAddError':"x と y の値両方を add 関数に渡さなければなりません。",'unsupportedGeometryType':"未対応の形状型: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition が失敗しました: id ${elemId} をもつ要素が誤った位置にある可能性があります。",'filterEvaluateNotImplemented':"このフィルター型について evaluate は実装されていません。"});OpenLayers.Lang["km"]=OpenLayers.Util.applyDefaults({'permalink':"តំណភ្ជាប់អចិន្ត្រៃយ៍",'baseLayer':"ស្រទាប់បាត​",'errorLoadingGML':"កំហុសកំឡុងពេលផ្ទុកឯកសារ GML ${url}",'scale':"មាត្រដ្ឋាន = ១ ៖ ${scaleDenom}"});OpenLayers.Lang["ksh"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Met dä Antwoot op en Aanfrooch ham_mer nix aanjefange: ${statusText}",'permalink':"Lengk op Duuer",'overlays':"Drövver jelaat",'baseLayer':"Jrund-Nivoh",'sameProjection':"De Övverseeschs_Kaat deiht et bloß, wann se de sälve Projäxjuhn bruche deiht, wi de Houp_Kaat",'readNotImplemented':"„\x3ccode lang=\"en\"\x3eread\x3c/code\x3e“ is em Projramm nit fürjesinn.",'writeNotImplemented':"„\x3ccode lang=\"en\"\x3ewrite\x3c/code\x3e“ is em Projramm nit fürjesinn.",'noFID':"En Saach, woh kein \x3ci lang=\"en\"\x3eFID\x3c/i\x3e för doh es, löht sesch nit ändere.",'errorLoadingGML':"Fähler beim \x3ci lang=\"en\"\x3eGML\x3c/i\x3e-Datei-Laade vun \x3ccode\x3e${url}\x3c/code\x3e",'browserNotSupported':"Dinge Brauser kann kein Väktore ußjävve. De Zoote Ußjaabe, di em Momang jon, sen:\n${renderers}",'componentShouldBe':"\x3ccode lang=\"en\"\x3eaddFeatures\x3c/code\x3e: dä Aandeil sullt vun dä Zoot „\x3ccode lang=\"en\"\x3e${geomType}\x3c/code\x3e“ sin.",'getFeatureError':"\x3ccode lang=\"en\"\x3egetFeatureFromEvent\x3c/code\x3e es vun enem Nivoh opjeroofe woode, woh et kei Projramm zom Ußjävve jit. Dat bedügg för jewöhnlesch, dat De e Nivoh kapott jemaat häs, ävver nit e Projramm för domet ömzejonn, wat domet verbonge es.",'minZoomLevelError':"De Eijeschaff „\x3ccode lang=\"en\"\x3eminZoomLevel\x3c/code\x3e“ es bloß doför jedaach, dat mer se met dä Nivvohß bruch, di vun \x3ccode lang=\"en\"\x3eFixedZoomLevels\x3c/code\x3e affhange don. Dat dat \x3ci lang=\"en\"\x3eWFS\x3c/i\x3e-Nivvoh övverhoup de Eijeschaff „\x3ccode lang=\"en\"\x3eminZoomLevel\x3c/code\x3e“ pröhfe deiht, es noch övveresch vun fröhjer. Mer künne dat ävver jez nit fott lohße, oohne dat mer Jevaa loufe, dat Aanwendunge vun OpenLayers nit mieh loufe, di sesch doh velleijsch noch drop am verlohße sin. Dröm sare mer, dat mer et nit mieh han welle, un de „\x3ccode lang=\"en\"\x3eminZoomLevel\x3c/code\x3e“-Eijeschaff weed hee vun de Version 3.0 af nit mieh jeprööf wäde. Nemm doför de Enstellung för de hühßte un de kleinßte Oplöhsung, esu wi et en http://trac.openlayers.org/wiki/SettingZoomLevels opjeschrevve es.",'commitSuccess':"Dä \x3ci lang=\"en\"\x3eWFS\x3c/i\x3e-Vörjang es joot jeloufe: ${response}",'commitFailed':"Dä \x3ci lang=\"en\"\x3eWFS\x3c/i\x3e-Vörjang es scheif jejange: ${response}",'googleWarning':"Dat Nivvoh \x3ccode lang=\"en\"\x3eGoogle\x3c/code\x3e kunnt nit reschtesch jelaade wääde.\x3cbr /\x3e\x3cbr /\x3eÖm hee di Nohreesch loß ze krijje, donn en ander Jrund-Nivvoh ußsöhke, rähß bovve en de Äk.\x3cbr /\x3e\x3cbr /\x3eWascheinlesch es dat wiel dat \x3ci lang=\"en\"\x3eGoogle-Maps\x3c/i\x3e-Skrepp entweeder nit reschtesch enjebonge wood, udder nit dä reschtejje \x3ci lang=\"en\"\x3eAPI\x3c/i\x3e-Schlößel för Ding Web-ßait scheke deiht.\x3cbr /\x3e\x3cbr /\x3eFör Projrammierer jidd_et Hölp do_drövver, \x3ca href=\"http://trac.openlayers.org/wiki/Google\" target=\"_blank\"\x3ewi mer dat aan et Loufe brengk\x3c/a\x3e.",'getLayerWarning':"Dat Nivvoh \x3ccode\x3e${layerType}\x3c/code\x3e kunnt nit reschtesch jelaade wääde.\x3cbr /\x3e\x3cbr /\x3eÖm hee di Nohreesch loß ze krijje, donn en ander Jrund-Nivvoh ußsöhkre, rähß bovve en de Äk.\x3cbr /\x3e\x3cbr /\x3eWascheinlesch es dat, wiel dat Skrepp \x3ccode\x3e${layerLib}\x3c/code\x3e nit reschtesch enjebonge wood.\x3cbr /\x3e\x3cbr /\x3eFör Projrammierer jidd_Et Hölp do_drövver, \x3ca href=\"http://trac.openlayers.org/wiki/${layerLib}\" target=\"_blank\"\x3ewi mer dat aan et Loufe brengk\x3c/a\x3e.",'scale':"Mohßshtaab = 1 : ${scaleDenom}",'W':"W",'E':"O",'N':"N",'S':"S",'layerAlreadyAdded':"Do häß versöhk, dat Nivvoh \x3ccode\x3e${layerName}\x3c/code\x3e en di Kaat eren ze bränge, et wohr ävver ald do dren.",'reprojectDeprecated':"Do bruchs de Ußwahl \x3ccode\x3ereproject\x3c/code\x3e op däm Nivvoh \x3ccode\x3e${layerName}\x3c/code\x3e. Di Ußwahl es nit mieh jähn jesinn. Se wohr doför jedaach, öm Date op jeschääfsmäßesch eruß jejovve Kaate bovve drop ze moole, wat ävver enzwesche besser met dä Öngershtözung för de ßfääresche Mäkaator Beldscher jeiht. Doh kanns De mieh drövver fenge op dä Sigg: http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Hee di Metood es nim_mih aktoäll un et weed se en dä Version 3.0 nit mieh jävve. Nemm \x3ccode\x3e${newMethod}\x3c/code\x3e doföör.",'boundsAddError':"Do moß beeds vun de \x3ccode\x3ex\x3c/code\x3e un \x3ccode\x3ey\x3c/code\x3e Wääte aan de Fungkßjohn \x3ccode\x3eadd\x3c/code\x3e jävve.",'lonlatAddError':"Do moß beeds \x3ccode\x3elon\x3c/code\x3e un \x3ccode\x3elat\x3c/code\x3e aan de Fungkßjohn \x3ccode\x3eadd\x3c/code\x3e jävve.",'pixelAddError':"Do moß beeds \x3ccode\x3ex\x3c/code\x3e un \x3ccode\x3ey\x3c/code\x3e aan de Fungkßjohn \x3ccode\x3eadd\x3c/code\x3e jävve.",'unsupportedGeometryType':"De Zoot Jommetrii dom_mer nit ongershtöze: \x3ccode\x3e${geomType}\x3c/code\x3e",'pagePositionFailed':"\x3ccode lang=\"en\"\x3eOpenLayers.Util.pagePosition\x3c/code\x3e es donevve jejange: dat Denge met dä Kännong \x3ccode\x3e${elemId}\x3c/code\x3e künnt am verkeehte Plaz sin.",'filterEvaluateNotImplemented':"„\x3ccode lang=\"en\"\x3eevaluate\x3c/code\x3e“ es för di Zoot Fellter nit enjereschdt."});OpenLayers.Lang["nds"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Unbehannelt Trüchmellels för de Anfraag ${statusText}",'permalink':"Permalink",'overlays':"Overlays",'baseLayer':"Achtergrundkoort",'sameProjection':"De Översichtskoort geiht blot, wenn de sülve Projekschoon as bi de Hööftkoort bruukt warrt",'readNotImplemented':"Lesen is nich inricht.",'writeNotImplemented':"Schrieven is nich inricht.",'noFID':"En Feature, dat keen FID hett, kann nich aktuell maakt warrn.",'errorLoadingGML':"Fehler bi’t Laden vun de GML-Datei ${url}",'browserNotSupported':"Dien Browser ünnerstütt keen Vektorbiller. Ünnerstütt Renderers:\n${renderers}",'componentShouldBe':"addFeatures : Kumponent schull man den Typ ${geomType} hebben",'getFeatureError':"getFeatureFromEvent is von en Laag ahn Render opropen worrn. Dat bedüüdt normalerwies, dat en Laag wegmaakt worrn is, aver nich de Handler, de dor op verwiest.",'commitSuccess':"WFS-Transakschoon: hett klappt ${response}",'commitFailed':"WFS-Transakschoon: hett nich klappt ${response}",'scale':"Skaal = 1 : ${scaleDenom}",'layerAlreadyAdded':"Du versöchst de Laag „${layerName}“ to de Koort totofögen, man de is al toföögt",'methodDeprecated':"Disse Methood is oold un schall dat in 3.0 nich mehr geven. Bruuk dor man beter ${newMethod} för.",'boundsAddError':"De Weert x un y, de mööt all beid an de add-Funkschoon övergeven warrn.",'lonlatAddError':"De Weert lon un lat, de mööt all beid an de add-Funkschoon övergeven warrn.",'pixelAddError':"De Weert x un y, de mööt all beid an de add-Funkschoon övergeven warrn.",'unsupportedGeometryType':"Nich ünnerstütt Geometrie-Typ: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition güng nich: Element mit de Id ${elemId} is villicht an’n verkehrten Platz."});OpenLayers.Lang["nn"]=OpenLayers.Util.applyDefaults({'scale':"Skala = 1 : ${scaleDenom}",'layerAlreadyAdded':"Du freista å leggja til laget «${layerName}» på kartet, men det har alt vorte lagt til.",'boundsAddError':"Du er nøydd til å gje både ein x- og ein y-verdi til «add»-funksjonen.",'lonlatAddError':"Du er nøydd til å gje både lon- og lat-verdiar til «add»-funksjonen.",'pixelAddError':"Du er nøydd til å gje både ein x- og ein y-verdi til «add»-funksjonen."});OpenLayers.Lang["oc"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Requèsta pas gerida, retorna ${statusText}",'permalink':"Permaligam",'overlays':"Calques",'baseLayer':"Calc de basa",'sameProjection':"La carta de situacion fonciona pas que quora sa projeccion es la meteissa que la de la carta principala",'readNotImplemented':"Lectura pas implementada.",'writeNotImplemented':"Escritura pas implementada.",'noFID':"Impossible de metre a jorn un objècte sens identificant (fid).",'errorLoadingGML':"Error al cargament del fichièr GML ${url}",'browserNotSupported':"Vòstre navegidor supòrta pas lo rendut vectorial. Los renderers actualament suportats son : \n${renderers}",'componentShouldBe':"addFeatures : lo compausant deuriá èsser de tipe ${geomType}",'getFeatureError':"getFeatureFromEvent es estat apelat sus un calc sens renderer. Aquò significa generalament qu\'avètz destruch aqueste jaç, mas qu\'avètz conservat un handler que li èra associat.",'minZoomLevelError':"La proprietat minZoomLevel deu èsser utilizada solament per de jaces FixedZoomLevels-descendent. Lo fach qu\'aqueste jaç WFS verifique la preséncia de minZoomLevel es una relica del passat. Çaquelà, la podèm suprimir sens copar d\'aplicacions que ne poirián dependre. Es per aquò que la depreciam -- la verificacion del minZoomLevel serà suprimida en version 3.0. A la plaça, mercés d\'utilizar los paramètres de resolucions min/max tal coma descrich sus : http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Transaccion WFS : SUCCES ${response}",'commitFailed':"Transaccion WFS : FRACAS ${response}",'googleWarning':"Lo jaç Google es pas estat en mesura de se cargar corrèctament.\x3cbr\x3e\x3cbr\x3ePer suprimir aqueste messatge, causissètz una BaseLayer novèla dins lo selector de jaç en naut a drecha.\x3cbr\x3e\x3cbr\x3eAquò es possiblament causat par la non-inclusion de la librariá Google Maps, o alara perque que la clau de l\'API correspond pas a vòstre site.\x3cbr\x3e\x3cbr\x3eDesvolopaires : per saber cossí corregir aquò, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3eclicatz aicí\x3c/a\x3e",'getLayerWarning':"Lo jaç ${layerType} es pas en mesura de se cargar corrèctament.\x3cbr\x3e\x3cbr\x3ePer suprimir aqueste messatge, causissètz una  BaseLayer novèla dins lo selector de jaç en naut a drecha.\x3cbr\x3e\x3cbr\x3eAquò es possiblament causat per la non-inclusion de la librariá ${layerLib}.\x3cbr\x3e\x3cbr\x3eDesvolopaires : per saber cossí corregir aquí, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3eclicatz aicí\x3c/a\x3e",'scale':"Escala ~ 1 : ${scaleDenom}",'W':"O",'E':"È",'N':"N",'S':"S",'layerAlreadyAdded':"Avètz ensajat d\'apondre a la carta lo calc : ${layerName}, mas ja es present",'reprojectDeprecated':"Utilizatz l\'opcion \'reproject\' sul jaç ${layerName}. Aquesta opcion es despreciada : Son usatge permetiá d\'afichar de donadas al dessús de jaces raster comercials. Aquesta foncionalitat ara es suportada en utilizant lo supòrt de la projeccion Mercator Esferica. Mai d\'informacion es disponibla sus http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Aqueste metòde es despreciada, e serà suprimida a la version 3.0. Mercés d\'utilizar ${newMethod} a la plaça.",'boundsAddError':"Vos cal passar las doas valors x e y a la foncion add.",'lonlatAddError':"Vos cal passar las doas valors lon e lat a la foncion add.",'pixelAddError':"Vos cal passar las doas valors x e y a la foncion add.",'unsupportedGeometryType':"Tipe de geometria pas suportat : ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition a fracassat : l\'element d\'id ${elemId} poiriá èsser mal posicionat.",'filterEvaluateNotImplemented':"evaluar es pas encara estat implementat per aqueste tipe de filtre."});OpenLayers.Lang["pt"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Servidor devolveu erro não contemplado ${statusText}",'permalink':"Ligação permanente",'overlays':"Sobreposições",'baseLayer':"Camada Base",'sameProjection':"O mapa panorâmico só funciona quando está na mesma projeção que o mapa principal",'readNotImplemented':"Leitura não implementada.",'writeNotImplemented':"Escrita não implementada.",'noFID':"Não é possível atualizar um elemento para a qual não há FID.",'errorLoadingGML':"Erro ao carregar ficheiro GML ${url}",'browserNotSupported':"O seu navegador não suporta renderização vetorial. Actualmente os renderizadores suportados são:\n${renderers}",'componentShouldBe':"addFeatures: componente deve ser um(a) ${geomType}",'getFeatureError':"getFeatureFromEvent foi chamado numa camada sem renderizador. Isto normalmente significa que destruiu uma camada, mas não um manipulador \'\'(handler)\'\' que lhe está associado.",'minZoomLevelError':"A propriedade minZoomLevel só deve ser usada com as camadas descendentes da FixedZoomLevels. A verificação da propriedade por esta camada wfs é uma relíquia do passado. No entanto, não podemos removê-la sem correr o risco de afectar aplicações OL que dependam dela. Portanto, estamos a torná-la obsoleta -- a verificação minZoomLevel será removida na versão 3.0. Em vez dela, por favor, use as opções de resolução min/max descritas aqui: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Transacção WFS: SUCESSO ${response}",'commitFailed':"Transacção WFS: FALHOU ${response}",'googleWarning':"A Camada Google não foi correctamente carregada.\x3cbr\x3e\x3cbr\x3ePara deixar de receber esta mensagem, seleccione uma nova Camada-Base no \'\'switcher\'\' de camadas no canto superior direito.\x3cbr\x3e\x3cbr\x3eProvavelmente, isto acontece porque o \'\'script\'\' da biblioteca do Google Maps não foi incluído ou não contém a chave API correcta para o seu sítio.\x3cbr\x3e\x3cbr\x3eProgramadores: Para ajuda sobre como solucionar o problema \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3eclique aqui\x3c/a\x3e .",'getLayerWarning':"A camada ${layerType} não foi correctamente carregada.\x3cbr\x3e\x3cbr\x3ePara desactivar esta mensagem, seleccione uma nova Camada-Base no \'\'switcher\'\' de camadas no canto superior direito.\x3cbr\x3e\x3cbr\x3eProvavelmente, isto acontece porque o \'\'script\'\' da biblioteca ${layerLib} não foi incluído correctamente.\x3cbr\x3e\x3cbr\x3eProgramadores: Para ajuda sobre como solucionar o problema \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3eclique aqui\x3c/a\x3e .",'scale':"Escala = 1 : ${scaleDenom}",'W':"O",'E':"E",'N':"N",'S':"S",'layerAlreadyAdded':"Você tentou adicionar a camada: ${layerName} ao mapa, mas ela já tinha sido adicionada antes",'reprojectDeprecated':"Está usando a opção \'reproject\' na camada ${layerName}. Esta opção é obsoleta: foi concebida para permitir a apresentação de dados sobre mapas-base comerciais, mas esta funcionalidade é agora suportada pelo Mercator Esférico. Mais informação está disponível em http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Este método foi declarado obsoleto e será removido na versão 3.0. Por favor, use ${newMethod} em vez disso.",'boundsAddError':"Você deve passar tanto o valor x como o y à função de adição.",'lonlatAddError':"Você deve passar tanto o valor lon como o lat à função de adição.",'pixelAddError':"Você deve passar tanto o valor x como o y à função de adição.",'unsupportedGeometryType':"Tipo de geometria não suportado: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition falhou: o elemento com o id ${elemId} poderá estar mal-posicionado.",'filterEvaluateNotImplemented':"avaliar não está implementado para este tipo de filtro."});OpenLayers.Lang["ru"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Необработанный запрос вернул ${statusText}",'permalink':"Постоянная ссылка",'overlays':"Слои",'baseLayer':"Основной слой",'sameProjection':"Обзорная карта работает только тогда, когда имеет ту же проекцию, что и основная",'readNotImplemented':"Чтение не реализовано.",'writeNotImplemented':"Запись не реализована.",'noFID':"Невозможно обновить объект, для которого нет FID.",'errorLoadingGML':"Ошибка при загрузке файла GML ${url}",'browserNotSupported':"Ваш браузер не поддерживает векторную графику. На данный момент поддерживаются:\n${renderers}",'componentShouldBe':"addFeatures: компонент должен быть ${geomType}",'getFeatureError':"getFeatureFromEvent вызван для слоя без рендерера. Обычно это говорит о том, что вы уничтожили слой, но оставили связанный с ним обработчик.",'minZoomLevelError':"Свойство minZoomLevel предназначено только для использования со слоями, являющимися потомками FixedZoomLevels. То, что этот WFS-слой проверяется на minZoomLevel — реликт прошлого. Однако мы не можем удалить эту функцию, так как, возможно, от неё зависят некоторые основанные на OpenLayers приложения. Функция объявлена устаревшей — проверка minZoomLevel будет удалена в 3.0. Пожалуйста, используйте вместо неё настройку мин/макс разрешения, описанную здесь: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Транзакция WFS: УСПЕШНО ${response}",'commitFailed':"Транзакция WFS: ОШИБКА ${response}",'googleWarning':"Слой Google не удалось нормально загрузить.\x3cbr\x3e\x3cbr\x3eЧтобы избавиться от этого сообщения, выбите другой основной слой в переключателе в правом верхнем углу.\x3cbr\x3e\x3cbr\x3eСкорее всего, причина в том, что библиотека Google Maps не была включена или не содержит корректного API-ключа для вашего сайта.\x3cbr\x3e\x3cbr\x3eРазработчикам: чтобы узнать, как сделать, чтобы всё заработало, \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3eщёлкните тут\x3c/a\x3e",'getLayerWarning':"Слой ${layerType} не удалось нормально загрузить. \x3cbr\x3e\x3cbr\x3eЧтобы избавиться от этого сообщения, выбите другой основной слой в переключателе в правом верхнем углу.\x3cbr\x3e\x3cbr\x3eСкорее всего, причина в том, что библиотека ${layerLib} не была включена или была включена некорректно.\x3cbr\x3e\x3cbr\x3eРазработчикам: чтобы узнать, как сделать, чтобы всё заработало, \x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3eщёлкните тут\x3c/a\x3e",'scale':"Масштаб = 1 : ${scaleDenom}",'W':"З",'E':"В",'N':"С",'S':"Ю",'layerAlreadyAdded':"Вы попытались добавить слой «${layerName}» на карту, но он уже был добавлен",'reprojectDeprecated':"Вы используете опцию \'reproject\' для слоя ${layerName}. Эта опция является устаревшей: ее использование предполагалось для поддержки показа данных поверх коммерческих базовых карт, но теперь этот функционал несёт встроенная поддержка сферической проекции Меркатора. Больше сведений доступно на http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Этот метод считается устаревшим и будет удалён в версии 3.0. Пожалуйста, пользуйтесь ${newMethod}.",'boundsAddError':"Функции add надо передавать оба значения, x и y.",'lonlatAddError':"Функции add надо передавать оба значения, lon и lat.",'pixelAddError':"Функции add надо передавать оба значения, x и y.",'unsupportedGeometryType':"Неподдерживаемый тип геометрии: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition failed: элемент с id ${elemId} может находиться не в нужном месте.",'filterEvaluateNotImplemented':"evaluate не реализовано для фильтра данного типа."});OpenLayers.Lang["sk"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Neobslúžené požiadavky vracajú ${statusText}",'permalink':"Trvalý odkaz",'overlays':"Prekrytia",'baseLayer':"Základná vrstva",'sameProjection':"Prehľadová mapka funguje iba vtedy, keď je v rovnakej projekcii ako hlavná mapa",'readNotImplemented':"Čítanie nie je implementované.",'writeNotImplemented':"Zápis nie je implementovaný.",'noFID':"Nie je možné aktualizovať vlastnosť, pre ktorú neexistuje FID.",'errorLoadingGML':"Chyba pri načítaní súboru GML ${url}",'browserNotSupported':"Váš prehliadač nepodporuje vykresľovanie vektorov. Momentálne podporované vykresľovače sú:\n${renderers}",'componentShouldBe':"addFeatures: komponent by mal byť ${geomType}",'getFeatureError':"getFeatureFromEvent bola zavolaná na vrstve bez vykresľovača. To zvyčajne znamená, že ste odstránili vrstvu, ale nie niektorú z obslúh, ktorá je s ňou asociovaná.",'minZoomLevelError':"Vlastnosť minZoomLevel je určený iba na použitie s vrstvami odvodenými od FixedZoomLevels. To, že táto wfs vrstva kontroluje minZoomLevel je pozostatok z minulosti. Nemôžeme ho však odstrániť, aby sme sa vyhli možnému porušeniu aplikácií založených na Open Layers, ktoré na tomto môže závisieť. Preto ho označujeme ako zavrhovaný - dolu uvedená kontrola minZoomLevel bude odstránená vo verzii 3.0. Použite prosím namiesto toho kontrolu min./max. rozlíšenia podľa tu uvedeného popisu: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Transakcia WFS: ÚSPEŠNÁ ${response}",'commitFailed':"Transakcia WFS: ZLYHALA ${response}",'googleWarning':"Vrstvu Google nebolo možné správne načítať.\x3cbr\x3e\x3cbr\x3eAby ste sa tejto správy zbavili vyberte novú BaseLayer v prepínači vrstiev v pravom hornom rohu.\x3cbr\x3e\x3cbr\x3eToto sa stalo pravdepodobne preto, že skript knižnice Google Maps buď nebol načítaný alebo neobsahuje správny kľúč API pre vašu lokalitu.\x3cbr\x3e\x3cbr\x3eVývojári: Tu môžete získať \x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3epomoc so sfunkčnením\x3c/a\x3e",'getLayerWarning':"Vrstvu ${layerType} nebolo možné správne načítať.\x3cbr\x3e\x3cbr\x3eAby ste sa tejto správy zbavili vyberte novú BaseLayer v prepínači vrstiev v pravom hornom rohu.\x3cbr\x3e\x3cbr\x3eToto sa stalo pravdepodobne preto, že skript knižnice ${layerType} buď nebol načítaný alebo neobsahuje správny kľúč API pre vašu lokalitu.\x3cbr\x3e\x3cbr\x3eVývojári: Tu môžete získať \x3ca href=\'http://trac.openlayers.org/wiki/${layerType}\' target=\'_blank\'\x3epomoc so sfunkčnením\x3c/a\x3e",'scale':"Mierka = 1 : ${scaleDenom}",'layerAlreadyAdded':"Pokúsili ste sa do mapy pridať vrstvu ${layerName}, ale tá už bola pridaná",'reprojectDeprecated':"Používate voľby „reproject“ vrstvy ${layerType}. Táto voľba je zzavrhovaná: jej použitie bolo navrhnuté na podporu zobrazovania údajov nad komerčnými základovými mapami, ale túto funkcionalitu je teraz možné dosiahnuť pomocou Spherical Mercator. Ďalšie informácie získate na stránke http://trac.openlayers.org/wiki/SphericalMercator.",'methodDeprecated':"Táto metóda je zavrhovaná a bude odstránená vo verzii 3.0. Použite prosím namiesto nej metódu ${newMethod}.",'boundsAddError':"Sčítacej funkcii musíte dať hodnoty x aj y.",'lonlatAddError':"Sčítacej funkcii musíte dať hodnoty lon (zem. dĺžka) aj lat (zem. šírka).",'pixelAddError':"Sčítacej funkcii musíte dať hodnoty x aj y.",'unsupportedGeometryType':"Nepodporovaný typ geometrie: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition zlyhalo: prvok s id ${elemId} môže byť zle umiestnený.",'filterEvaluateNotImplemented':"evaluate nie je implementovaný pre tento typ filtra"});OpenLayers.Lang["te"]=OpenLayers.Util.applyDefaults({'permalink':"స్థిరలింకు",'W':"ప",'E':"తూ",'N':"ఉ",'S':"ద"});OpenLayers.Lang["vi"]=OpenLayers.Util.applyDefaults({'unhandledRequest':"Không xử lý được phản hồi ${statusText} cho yêu cầu",'permalink':"Liên kết thường trực",'overlays':"Lấp bản đồ",'baseLayer':"Lớp nền",'sameProjection':"Bản đồ toàn cảnh chỉ hoạt động khi cùng phép chiếu với bản đồ chính",'readNotImplemented':"Chưa hỗ trợ chức năng đọc.",'writeNotImplemented':"Chưa hỗ trợ chức năng viết.",'noFID':"Không thể cập nhật tính năng thiếu FID.",'errorLoadingGML':"Lỗi tải tập tin GML tại ${url}",'browserNotSupported':"Trình duyệt của bạn không hỗ trợ chức năng vẽ bằng vectơ. Hiện hỗ trợ các bộ kết xuất:\n${renderers}",'componentShouldBe':"addFeatures: bộ phận cần phải là ${geomType}",'getFeatureError':"getFeatureFromEvent được gọi từ lớp không có bộ kết xuất. Thường thì có lẽ lớp bị xóa nhưng một phần xử lý của nó vẫn còn.",'minZoomLevelError':"Chỉ nên sử dụng thuộc tính minZoomLevel với các lớp FixedZoomLevels-descendent. Việc lớp wfs này tìm cho minZoomLevel là di tích còn lại từ xưa. Tuy nhiên, nếu chúng tôi dời nó thì sẽ vỡ các chương trình OpenLayers mà dựa trên nó. Bởi vậy chúng tôi phản đối sử dụng nó\x26nbsp;– bước tìm cho minZoomLevel sẽ được dời vào phiên bản 3.0. Xin sử dụng thiết lập độ phân tích tối thiểu / tối đa thay thế, theo hướng dẫn này: http://trac.openlayers.org/wiki/SettingZoomLevels",'commitSuccess':"Giao dịch WFS: THÀNH CÔNG ${response}",'commitFailed':"Giao dịch WFS: THẤT BẠI ${response}",'googleWarning':"Không thể tải lớp Google đúng đắn.\x3cbr\x3e\x3cbr\x3eĐể tránh thông báo này lần sau, hãy chọn BaseLayer mới dùng điều khiển chọn lớp ở góc trên phải.\x3cbr\x3e\x3cbr\x3eChắc script thư viện Google Maps hoặc không được bao gồm hoặc không chứa khóa API hợp với website của bạn.\x3cbr\x3e\x3cbr\x3e\x3ca href=\'http://trac.openlayers.org/wiki/Google\' target=\'_blank\'\x3eTrợ giúp về tính năng này\x3c/a\x3e cho người phát triển.",'getLayerWarning':"Không thể tải lớp ${layerType} đúng đắn.\x3cbr\x3e\x3cbr\x3eĐể tránh thông báo này lần sau, hãy chọn BaseLayer mới dùng điều khiển chọn lớp ở góc trên phải.\x3cbr\x3e\x3cbr\x3eChắc script thư viện ${layerLib} không được bao gồm đúng kiểu.\x3cbr\x3e\x3cbr\x3e\x3ca href=\'http://trac.openlayers.org/wiki/${layerLib}\' target=\'_blank\'\x3eTrợ giúp về tính năng này\x3c/a\x3e cho người phát triển.",'scale':"Tỷ lệ = 1 : ${scaleDenom}",'W':"T",'E':"Đ",'N':"B",'S':"N",'layerAlreadyAdded':"Bạn muốn thêm lớp ${layerName} vào bản đồ, nhưng lớp này đã được thêm",'reprojectDeprecated':"Bạn đang áp dụng chế độ “reproject” vào lớp ${layerName}. Chế độ này đã bị phản đối: nó có mục đích hỗ trợ lấp dữ liệu trên các nền bản đồ thương mại; nên thực hiện hiệu ứng đó dùng tính năng Mercator Hình cầu. Có sẵn thêm chi tiết tại http://trac.openlayers.org/wiki/SphericalMercator .",'methodDeprecated':"Phương thức này đã bị phản đối và sẽ bị dời vào phiên bản 3.0. Xin hãy sử dụng ${newMethod} thay thế.",'boundsAddError':"Cần phải cho cả giá trị x và y vào hàm add.",'lonlatAddError':"Cần phải cho cả giá trị lon và lat vào hàm add.",'pixelAddError':"Cần phải cho cả giá trị x và y vào hàm add.",'unsupportedGeometryType':"Không hỗ trợ kiểu địa lý: ${geomType}",'pagePositionFailed':"OpenLayers.Util.pagePosition bị thất bại: nguyên tố với ID ${elemId} có thể ở chỗ sai.",'filterEvaluateNotImplemented':"chưa hỗ trợ evaluate cho loại bộ lọc này."});OpenLayers.Popup.AnchoredBubble=OpenLayers.Class(OpenLayers.Popup.Anchored,{rounded:false,initialize:function(id,lonlat,contentSize,contentHTML,anchor,closeBox,closeBoxCallback){this.padding=new OpenLayers.Bounds(0,OpenLayers.Popup.AnchoredBubble.CORNER_SIZE,0,OpenLayers.Popup.AnchoredBubble.CORNER_SIZE);OpenLayers.Popup.Anchored.prototype.initialize.apply(this,arguments);},draw:function(px){OpenLayers.Popup.Anchored.prototype.draw.apply(this,arguments);this.setContentHTML();this.setBackgroundColor();this.setOpacity();return this.div;},updateRelativePosition:function(){this.setRicoCorners();},setSize:function(contentSize){OpenLayers.Popup.Anchored.prototype.setSize.apply(this,arguments);this.setRicoCorners();},setBackgroundColor:function(color){if(color!=undefined){this.backgroundColor=color;}
if(this.div!=null){if(this.contentDiv!=null){this.div.style.background="transparent";OpenLayers.Rico.Corner.changeColor(this.groupDiv,this.backgroundColor);}}},setOpacity:function(opacity){OpenLayers.Popup.Anchored.prototype.setOpacity.call(this,opacity);if(this.div!=null){if(this.groupDiv!=null){OpenLayers.Rico.Corner.changeOpacity(this.groupDiv,this.opacity);}}},setBorder:function(border){this.border=0;},setRicoCorners:function(){var corners=this.getCornersToRound(this.relativePosition);var options={corners:corners,color:this.backgroundColor,bgColor:"transparent",blend:false};if(!this.rounded){OpenLayers.Rico.Corner.round(this.div,options);this.rounded=true;}else{OpenLayers.Rico.Corner.reRound(this.groupDiv,options);this.setBackgroundColor();this.setOpacity();}},getCornersToRound:function(){var corners=['tl','tr','bl','br'];var corner=OpenLayers.Bounds.oppositeQuadrant(this.relativePosition);OpenLayers.Util.removeItem(corners,corner);return corners.join(" ");},CLASS_NAME:"OpenLayers.Popup.AnchoredBubble"});OpenLayers.Popup.AnchoredBubble.CORNER_SIZE=5;OpenLayers.Popup.Framed=OpenLayers.Class(OpenLayers.Popup.Anchored,{imageSrc:null,imageSize:null,isAlphaImage:false,positionBlocks:null,blocks:null,fixedRelativePosition:false,initialize:function(id,lonlat,contentSize,contentHTML,anchor,closeBox,closeBoxCallback){OpenLayers.Popup.Anchored.prototype.initialize.apply(this,arguments);if(this.fixedRelativePosition){this.updateRelativePosition();this.calculateRelativePosition=function(px){return this.relativePosition;};}
this.contentDiv.style.position="absolute";this.contentDiv.style.zIndex=1;if(closeBox){this.closeDiv.style.zIndex=1;}
this.groupDiv.style.position="absolute";this.groupDiv.style.top="0px";this.groupDiv.style.left="0px";this.groupDiv.style.height="100%";this.groupDiv.style.width="100%";},destroy:function(){this.imageSrc=null;this.imageSize=null;this.isAlphaImage=null;this.fixedRelativePosition=false;this.positionBlocks=null;for(var i=0;i<this.blocks.length;i++){var block=this.blocks[i];if(block.image){block.div.removeChild(block.image);}
block.image=null;if(block.div){this.groupDiv.removeChild(block.div);}
block.div=null;}
this.blocks=null;OpenLayers.Popup.Anchored.prototype.destroy.apply(this,arguments);},setBackgroundColor:function(color){},setBorder:function(){},setOpacity:function(opacity){},setSize:function(contentSize){OpenLayers.Popup.Anchored.prototype.setSize.apply(this,arguments);this.updateBlocks();},updateRelativePosition:function(){this.padding=this.positionBlocks[this.relativePosition].padding;if(this.closeDiv){var contentDivPadding=this.getContentDivPadding();this.closeDiv.style.right=contentDivPadding.right+
this.padding.right+"px";this.closeDiv.style.top=contentDivPadding.top+
this.padding.top+"px";}
this.updateBlocks();},calculateNewPx:function(px){var newPx=OpenLayers.Popup.Anchored.prototype.calculateNewPx.apply(this,arguments);newPx=newPx.offset(this.positionBlocks[this.relativePosition].offset);return newPx;},createBlocks:function(){this.blocks=[];var firstPosition=null;for(var key in this.positionBlocks){firstPosition=key;break;}
var position=this.positionBlocks[firstPosition];for(var i=0;i<position.blocks.length;i++){var block={};this.blocks.push(block);var divId=this.id+'_FrameDecorationDiv_'+i;block.div=OpenLayers.Util.createDiv(divId,null,null,null,"absolute",null,"hidden",null);var imgId=this.id+'_FrameDecorationImg_'+i;var imageCreator=(this.isAlphaImage)?OpenLayers.Util.createAlphaImageDiv:OpenLayers.Util.createImage;block.image=imageCreator(imgId,null,this.imageSize,this.imageSrc,"absolute",null,null,null);block.div.appendChild(block.image);this.groupDiv.appendChild(block.div);}},updateBlocks:function(){if(!this.blocks){this.createBlocks();}
if(this.size&&this.relativePosition){var position=this.positionBlocks[this.relativePosition];for(var i=0;i<position.blocks.length;i++){var positionBlock=position.blocks[i];var block=this.blocks[i];var l=positionBlock.anchor.left;var b=positionBlock.anchor.bottom;var r=positionBlock.anchor.right;var t=positionBlock.anchor.top;var w=(isNaN(positionBlock.size.w))?this.size.w-(r+l):positionBlock.size.w;var h=(isNaN(positionBlock.size.h))?this.size.h-(b+t):positionBlock.size.h;block.div.style.width=(w<0?0:w)+'px';block.div.style.height=(h<0?0:h)+'px';block.div.style.left=(l!=null)?l+'px':'';block.div.style.bottom=(b!=null)?b+'px':'';block.div.style.right=(r!=null)?r+'px':'';block.div.style.top=(t!=null)?t+'px':'';block.image.style.left=positionBlock.position.x+'px';block.image.style.top=positionBlock.position.y+'px';}
this.contentDiv.style.left=this.padding.left+"px";this.contentDiv.style.top=this.padding.top+"px";}},CLASS_NAME:"OpenLayers.Popup.Framed"});OpenLayers.Projection=OpenLayers.Class({proj:null,projCode:null,initialize:function(projCode,options){OpenLayers.Util.extend(this,options);this.projCode=projCode;if(window.Proj4js){this.proj=new Proj4js.Proj(projCode);}},getCode:function(){return this.proj?this.proj.srsCode:this.projCode;},getUnits:function(){return this.proj?this.proj.units:null;},toString:function(){return this.getCode();},equals:function(projection){if(projection&&projection.getCode){return this.getCode()==projection.getCode();}else{return false;}},destroy:function(){delete this.proj;delete this.projCode;},CLASS_NAME:"OpenLayers.Projection"});OpenLayers.Projection.transforms={};OpenLayers.Projection.addTransform=function(from,to,method){if(!OpenLayers.Projection.transforms[from]){OpenLayers.Projection.transforms[from]={};}
OpenLayers.Projection.transforms[from][to]=method;};OpenLayers.Projection.transform=function(point,source,dest){if(source.proj&&dest.proj){point=Proj4js.transform(source.proj,dest.proj,point);}else if(source&&dest&&OpenLayers.Projection.transforms[source.getCode()]&&OpenLayers.Projection.transforms[source.getCode()][dest.getCode()]){OpenLayers.Projection.transforms[source.getCode()][dest.getCode()](point);}
return point;};OpenLayers.Protocol.WFS.v1=OpenLayers.Class(OpenLayers.Protocol,{version:null,srsName:"EPSG:4326",featureType:null,featureNS:null,geometryName:"the_geom",schema:null,featurePrefix:"feature",formatOptions:null,readFormat:null,initialize:function(options){OpenLayers.Protocol.prototype.initialize.apply(this,[options]);if(!options.format){this.format=OpenLayers.Format.WFST(OpenLayers.Util.extend({version:this.version,featureType:this.featureType,featureNS:this.featureNS,featurePrefix:this.featurePrefix,geometryName:this.geometryName,srsName:this.srsName,schema:this.schema},this.formatOptions));}
if(!this.featureNS&&this.featurePrefix){var readNode=this.format.readNode;this.format.readNode=function(node,obj){if(!this.featureNS&&node.prefix==this.featurePrefix){this.featureNS=node.namespaceURI;this.setNamespace("feature",this.featureNS);}
return readNode.apply(this,arguments);};}},destroy:function(){if(this.options&&!this.options.format){this.format.destroy();}
this.format=null;OpenLayers.Protocol.prototype.destroy.apply(this);},read:function(options){OpenLayers.Protocol.prototype.read.apply(this,arguments);options=OpenLayers.Util.extend({},options);OpenLayers.Util.applyDefaults(options,this.options||{});var response=new OpenLayers.Protocol.Response({requestType:"read"});var data=OpenLayers.Format.XML.prototype.write.apply(this.format,[this.format.writeNode("wfs:GetFeature",options)]);response.priv=OpenLayers.Request.POST({url:options.url,callback:this.createCallback(this.handleRead,response,options),params:options.params,headers:options.headers,data:data});return response;},handleRead:function(response,options){if(options.callback){var request=response.priv;if(request.status>=200&&request.status<300){response.features=this.parseFeatures(request);response.code=OpenLayers.Protocol.Response.SUCCESS;}else{response.code=OpenLayers.Protocol.Response.FAILURE;}
options.callback.call(options.scope,response);}},parseFeatures:function(request){var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
if(!doc||doc.length<=0){return null;}
return(this.readFormat!==null)?this.readFormat.read(doc):this.format.read(doc);},commit:function(features,options){options=OpenLayers.Util.extend({},options);OpenLayers.Util.applyDefaults(options,this.options);var response=new OpenLayers.Protocol.Response({requestType:"commit",reqFeatures:features});response.priv=OpenLayers.Request.POST({url:options.url,data:this.format.write(features,options),callback:this.createCallback(this.handleCommit,response,options)});return response;},handleCommit:function(response,options){if(options.callback){var request=response.priv;var data=request.responseXML;if(!data||!data.documentElement){data=request.responseText;}
var obj=this.format.read(data)||{};response.insertIds=obj.insertIds||[];response.code=(obj.success)?OpenLayers.Protocol.Response.SUCCESS:OpenLayers.Protocol.Response.FAILURE;options.callback.call(options.scope,response);}},filterDelete:function(filter,options){options=OpenLayers.Util.extend({},options);OpenLayers.Util.applyDefaults(options,this.options);var response=new OpenLayers.Protocol.Response({requestType:"commit"});var root=this.format.createElementNSPlus("wfs:Transaction",{attributes:{service:"WFS",version:this.version}});var deleteNode=this.format.createElementNSPlus("wfs:Delete",{attributes:{typeName:(options.featureNS?this.featurePrefix+":":"")+
options.featureType}});if(options.featureNS){deleteNode.setAttribute("xmlns:"+this.featurePrefix,options.featureNS);}
var filterNode=this.format.writeNode("ogc:Filter",filter);deleteNode.appendChild(filterNode);root.appendChild(deleteNode);var data=OpenLayers.Format.XML.prototype.write.apply(this.format,[root]);return OpenLayers.Request.POST({url:this.url,callback:options.callback||function(){},data:data});},abort:function(response){if(response){response.priv.abort();}},CLASS_NAME:"OpenLayers.Protocol.WFS.v1"});OpenLayers.Renderer.SVG=OpenLayers.Class(OpenLayers.Renderer.Elements,{xmlns:"http://www.w3.org/2000/svg",xlinkns:"http://www.w3.org/1999/xlink",MAX_PIXEL:15000,translationParameters:null,symbolMetrics:null,isGecko:null,supportUse:null,initialize:function(containerID){if(!this.supported()){return;}
OpenLayers.Renderer.Elements.prototype.initialize.apply(this,arguments);this.translationParameters={x:0,y:0};this.supportUse=(navigator.userAgent.toLowerCase().indexOf("applewebkit/5")==-1);this.isGecko=(navigator.userAgent.toLowerCase().indexOf("gecko/")!=-1);this.symbolMetrics={};},destroy:function(){OpenLayers.Renderer.Elements.prototype.destroy.apply(this,arguments);},supported:function(){var svgFeature="http://www.w3.org/TR/SVG11/feature#";return(document.implementation&&(document.implementation.hasFeature("org.w3c.svg","1.0")||document.implementation.hasFeature(svgFeature+"SVG","1.1")||document.implementation.hasFeature(svgFeature+"BasicStructure","1.1")));},inValidRange:function(x,y,xyOnly){var left=x+(xyOnly?0:this.translationParameters.x);var top=y+(xyOnly?0:this.translationParameters.y);return(left>=-this.MAX_PIXEL&&left<=this.MAX_PIXEL&&top>=-this.MAX_PIXEL&&top<=this.MAX_PIXEL);},setExtent:function(extent,resolutionChanged){OpenLayers.Renderer.Elements.prototype.setExtent.apply(this,arguments);var resolution=this.getResolution();var left=-extent.left/resolution;var top=extent.top/resolution;if(resolutionChanged){this.left=left;this.top=top;var extentString="0 0 "+this.size.w+" "+this.size.h;this.rendererRoot.setAttributeNS(null,"viewBox",extentString);this.translate(0,0);return true;}else{var inRange=this.translate(left-this.left,top-this.top);if(!inRange){this.setExtent(extent,true);}
return inRange;}},translate:function(x,y){if(!this.inValidRange(x,y,true)){return false;}else{var transformString="";if(x||y){transformString="translate("+x+","+y+")";}
this.root.setAttributeNS(null,"transform",transformString);this.translationParameters={x:x,y:y};return true;}},setSize:function(size){OpenLayers.Renderer.prototype.setSize.apply(this,arguments);this.rendererRoot.setAttributeNS(null,"width",this.size.w);this.rendererRoot.setAttributeNS(null,"height",this.size.h);},getNodeType:function(geometry,style){var nodeType=null;switch(geometry.CLASS_NAME){case"OpenLayers.Geometry.Point":if(style.externalGraphic){nodeType="image";}else if(this.isComplexSymbol(style.graphicName)){nodeType=this.supportUse===false?"svg":"use";}else{nodeType="circle";}
break;case"OpenLayers.Geometry.Rectangle":nodeType="rect";break;case"OpenLayers.Geometry.LineString":nodeType="polyline";break;case"OpenLayers.Geometry.LinearRing":nodeType="polygon";break;case"OpenLayers.Geometry.Polygon":case"OpenLayers.Geometry.Curve":case"OpenLayers.Geometry.Surface":nodeType="path";break;default:break;}
return nodeType;},setStyle:function(node,style,options){style=style||node._style;options=options||node._options;var r=parseFloat(node.getAttributeNS(null,"r"));var widthFactor=1;var pos;if(node._geometryClass=="OpenLayers.Geometry.Point"&&r){node.style.visibility="";if(style.graphic===false){node.style.visibility="hidden";}else if(style.externalGraphic){pos=this.getPosition(node);if(style.graphicTitle){node.setAttributeNS(null,"title",style.graphicTitle);}
if(style.graphicWidth&&style.graphicHeight){node.setAttributeNS(null,"preserveAspectRatio","none");}
var width=style.graphicWidth||style.graphicHeight;var height=style.graphicHeight||style.graphicWidth;width=width?width:style.pointRadius*2;height=height?height:style.pointRadius*2;var xOffset=(style.graphicXOffset!=undefined)?style.graphicXOffset:-(0.5*width);var yOffset=(style.graphicYOffset!=undefined)?style.graphicYOffset:-(0.5*height);var opacity=style.graphicOpacity||style.fillOpacity;node.setAttributeNS(null,"x",(pos.x+xOffset).toFixed());node.setAttributeNS(null,"y",(pos.y+yOffset).toFixed());node.setAttributeNS(null,"width",width);node.setAttributeNS(null,"height",height);node.setAttributeNS(this.xlinkns,"href",style.externalGraphic);node.setAttributeNS(null,"style","opacity: "+opacity);}else if(this.isComplexSymbol(style.graphicName)){var offset=style.pointRadius*3;var size=offset*2;var id=this.importSymbol(style.graphicName);pos=this.getPosition(node);widthFactor=this.symbolMetrics[id][0]*3/size;var parent=node.parentNode;var nextSibling=node.nextSibling;if(parent){parent.removeChild(node);}
if(this.supportUse===false){var src=document.getElementById(id);node.firstChild&&node.removeChild(node.firstChild);node.appendChild(src.firstChild.cloneNode(true));node.setAttributeNS(null,"viewBox",src.getAttributeNS(null,"viewBox"));}else{node.setAttributeNS(this.xlinkns,"href","#"+id);}
node.setAttributeNS(null,"width",size);node.setAttributeNS(null,"height",size);node.setAttributeNS(null,"x",pos.x-offset);node.setAttributeNS(null,"y",pos.y-offset);if(nextSibling){parent.insertBefore(node,nextSibling);}else if(parent){parent.appendChild(node);}}else{node.setAttributeNS(null,"r",style.pointRadius);}
var rotation=style.rotation;if((rotation!==undefined||node._rotation!==undefined)&&pos){node._rotation=rotation;rotation|=0;if(node.nodeName!=="svg"){node.setAttributeNS(null,"transform","rotate("+rotation+" "+pos.x+" "+
pos.y+")");}else{var metrics=this.symbolMetrics[id];node.firstChild.setAttributeNS(null,"transform","rotate("+style.rotation+" "+metrics[1]+" "+metrics[2]+")");}}}
if(options.isFilled){node.setAttributeNS(null,"fill",style.fillColor);node.setAttributeNS(null,"fill-opacity",style.fillOpacity);}else{node.setAttributeNS(null,"fill","none");}
if(options.isStroked){node.setAttributeNS(null,"stroke",style.strokeColor);node.setAttributeNS(null,"stroke-opacity",style.strokeOpacity);node.setAttributeNS(null,"stroke-width",style.strokeWidth*widthFactor);node.setAttributeNS(null,"stroke-linecap",style.strokeLinecap||"round");node.setAttributeNS(null,"stroke-linejoin","round");style.strokeDashstyle&&node.setAttributeNS(null,"stroke-dasharray",this.dashStyle(style,widthFactor));}else{node.setAttributeNS(null,"stroke","none");}
if(style.pointerEvents){node.setAttributeNS(null,"pointer-events",style.pointerEvents);}
if(style.cursor!=null){node.setAttributeNS(null,"cursor",style.cursor);}
return node;},dashStyle:function(style,widthFactor){var w=style.strokeWidth*widthFactor;var str=style.strokeDashstyle;switch(str){case'solid':return'none';case'dot':return[1,4*w].join();case'dash':return[4*w,4*w].join();case'dashdot':return[4*w,4*w,1,4*w].join();case'longdash':return[8*w,4*w].join();case'longdashdot':return[8*w,4*w,1,4*w].join();default:return OpenLayers.String.trim(str).replace(/\s+/g,",");}},createNode:function(type,id){var node=document.createElementNS(this.xmlns,type);if(id){node.setAttributeNS(null,"id",id);}
return node;},nodeTypeCompare:function(node,type){return(type==node.nodeName);},createRenderRoot:function(){return this.nodeFactory(this.container.id+"_svgRoot","svg");},createRoot:function(suffix){return this.nodeFactory(this.container.id+suffix,"g");},createDefs:function(){var defs=this.nodeFactory(this.container.id+"_defs","defs");this.rendererRoot.appendChild(defs);return defs;},drawPoint:function(node,geometry){return this.drawCircle(node,geometry,1);},drawCircle:function(node,geometry,radius){var resolution=this.getResolution();var x=(geometry.x/resolution+this.left);var y=(this.top-geometry.y/resolution);if(this.inValidRange(x,y)){node.setAttributeNS(null,"cx",x);node.setAttributeNS(null,"cy",y);node.setAttributeNS(null,"r",radius);return node;}else{return false;}},drawLineString:function(node,geometry){var componentsResult=this.getComponentsString(geometry.components);if(componentsResult.path){node.setAttributeNS(null,"points",componentsResult.path);return(componentsResult.complete?node:null);}else{return false;}},drawLinearRing:function(node,geometry){var componentsResult=this.getComponentsString(geometry.components);if(componentsResult.path){node.setAttributeNS(null,"points",componentsResult.path);return(componentsResult.complete?node:null);}else{return false;}},drawPolygon:function(node,geometry){var d="";var draw=true;var complete=true;var linearRingResult,path;for(var j=0,len=geometry.components.length;j<len;j++){d+=" M";linearRingResult=this.getComponentsString(geometry.components[j].components," ");path=linearRingResult.path;if(path){d+=" "+path;complete=linearRingResult.complete&&complete;}else{draw=false;}}
d+=" z";if(draw){node.setAttributeNS(null,"d",d);node.setAttributeNS(null,"fill-rule","evenodd");return complete?node:null;}else{return false;}},drawRectangle:function(node,geometry){var resolution=this.getResolution();var x=(geometry.x/resolution+this.left);var y=(this.top-geometry.y/resolution);if(this.inValidRange(x,y)){node.setAttributeNS(null,"x",x);node.setAttributeNS(null,"y",y);node.setAttributeNS(null,"width",geometry.width/resolution);node.setAttributeNS(null,"height",geometry.height/resolution);return node;}else{return false;}},drawSurface:function(node,geometry){var d=null;var draw=true;for(var i=0,len=geometry.components.length;i<len;i++){if((i%3)==0&&(i/3)==0){var component=this.getShortString(geometry.components[i]);if(!component){draw=false;}
d="M "+component;}else if((i%3)==1){var component=this.getShortString(geometry.components[i]);if(!component){draw=false;}
d+=" C "+component;}else{var component=this.getShortString(geometry.components[i]);if(!component){draw=false;}
d+=" "+component;}}
d+=" Z";if(draw){node.setAttributeNS(null,"d",d);return node;}else{return false;}},drawText:function(featureId,style,location){var resolution=this.getResolution();var x=(location.x/resolution+this.left);var y=(location.y/resolution-this.top);var label=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX,"text");var tspan=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX+"_tspan","tspan");label.setAttributeNS(null,"x",x);label.setAttributeNS(null,"y",-y);if(style.fontColor){label.setAttributeNS(null,"fill",style.fontColor);}
if(style.fontOpacity){label.setAttributeNS(null,"opacity",style.fontOpacity);}
if(style.fontFamily){label.setAttributeNS(null,"font-family",style.fontFamily);}
if(style.fontSize){label.setAttributeNS(null,"font-size",style.fontSize);}
if(style.fontWeight){label.setAttributeNS(null,"font-weight",style.fontWeight);}
if(style.labelSelect===true){label.setAttributeNS(null,"pointer-events","visible");label._featureId=featureId;tspan._featureId=featureId;tspan._geometry=location;tspan._geometryClass=location.CLASS_NAME;}else{label.setAttributeNS(null,"pointer-events","none");}
var align=style.labelAlign||"cm";label.setAttributeNS(null,"text-anchor",OpenLayers.Renderer.SVG.LABEL_ALIGN[align[0]]||"middle");if(this.isGecko){label.setAttributeNS(null,"dominant-baseline",OpenLayers.Renderer.SVG.LABEL_ALIGN[align[1]]||"central");}else{tspan.setAttributeNS(null,"baseline-shift",OpenLayers.Renderer.SVG.LABEL_VSHIFT[align[1]]||"-35%");}
tspan.textContent=style.label;if(!label.parentNode){label.appendChild(tspan);this.textRoot.appendChild(label);}},getComponentsString:function(components,separator){var renderCmp=[];var complete=true;var len=components.length;var strings=[];var str,component;for(var i=0;i<len;i++){component=components[i];renderCmp.push(component);str=this.getShortString(component);if(str){strings.push(str);}else{if(i>0){if(this.getShortString(components[i-1])){strings.push(this.clipLine(components[i],components[i-1]));}}
if(i<len-1){if(this.getShortString(components[i+1])){strings.push(this.clipLine(components[i],components[i+1]));}}
complete=false;}}
return{path:strings.join(separator||","),complete:complete};},clipLine:function(badComponent,goodComponent){if(goodComponent.equals(badComponent)){return"";}
var resolution=this.getResolution();var maxX=this.MAX_PIXEL-this.translationParameters.x;var maxY=this.MAX_PIXEL-this.translationParameters.y;var x1=goodComponent.x/resolution+this.left;var y1=this.top-goodComponent.y/resolution;var x2=badComponent.x/resolution+this.left;var y2=this.top-badComponent.y/resolution;var k;if(x2<-maxX||x2>maxX){k=(y2-y1)/(x2-x1);x2=x2<0?-maxX:maxX;y2=y1+(x2-x1)*k;}
if(y2<-maxY||y2>maxY){k=(x2-x1)/(y2-y1);y2=y2<0?-maxY:maxY;x2=x1+(y2-y1)*k;}
return x2+","+y2;},getShortString:function(point){var resolution=this.getResolution();var x=(point.x/resolution+this.left);var y=(this.top-point.y/resolution);if(this.inValidRange(x,y)){return x+","+y;}else{return false;}},getPosition:function(node){return({x:parseFloat(node.getAttributeNS(null,"cx")),y:parseFloat(node.getAttributeNS(null,"cy"))});},importSymbol:function(graphicName){if(!this.defs){this.defs=this.createDefs();}
var id=this.container.id+"-"+graphicName;if(document.getElementById(id)!=null){return id;}
var symbol=OpenLayers.Renderer.symbol[graphicName];if(!symbol){throw new Error(graphicName+' is not a valid symbol name');}
var symbolNode=this.nodeFactory(id,"symbol");var node=this.nodeFactory(null,"polygon");symbolNode.appendChild(node);var symbolExtent=new OpenLayers.Bounds(Number.MAX_VALUE,Number.MAX_VALUE,0,0);var points=[];var x,y;for(var i=0;i<symbol.length;i=i+2){x=symbol[i];y=symbol[i+1];symbolExtent.left=Math.min(symbolExtent.left,x);symbolExtent.bottom=Math.min(symbolExtent.bottom,y);symbolExtent.right=Math.max(symbolExtent.right,x);symbolExtent.top=Math.max(symbolExtent.top,y);points.push(x,",",y);}
node.setAttributeNS(null,"points",points.join(" "));var width=symbolExtent.getWidth();var height=symbolExtent.getHeight();var viewBox=[symbolExtent.left-width,symbolExtent.bottom-height,width*3,height*3];symbolNode.setAttributeNS(null,"viewBox",viewBox.join(" "));this.symbolMetrics[id]=[Math.max(width,height),symbolExtent.getCenterLonLat().lon,symbolExtent.getCenterLonLat().lat];this.defs.appendChild(symbolNode);return symbolNode.id;},getFeatureIdFromEvent:function(evt){var featureId=OpenLayers.Renderer.Elements.prototype.getFeatureIdFromEvent.apply(this,arguments);if(this.supportUse===false&&!featureId){var target=evt.target;featureId=target.parentNode&&target!=this.rendererRoot&&target.parentNode._featureId;}
return featureId;},CLASS_NAME:"OpenLayers.Renderer.SVG"});OpenLayers.Renderer.SVG.LABEL_ALIGN={"l":"start","r":"end","b":"bottom","t":"hanging"};OpenLayers.Renderer.SVG.LABEL_VSHIFT={"t":"-70%","b":"0"};OpenLayers.Renderer.VML=OpenLayers.Class(OpenLayers.Renderer.Elements,{xmlns:"urn:schemas-microsoft-com:vml",symbolCache:{},offset:null,initialize:function(containerID){if(!this.supported()){return;}
if(!document.namespaces.olv){document.namespaces.add("olv",this.xmlns);var style=document.createStyleSheet();var shapes=['shape','rect','oval','fill','stroke','imagedata','group','textbox'];for(var i=0,len=shapes.length;i<len;i++){style.addRule('olv\\:'+shapes[i],"behavior: url(#default#VML); "+"position: absolute; display: inline-block;");}}
OpenLayers.Renderer.Elements.prototype.initialize.apply(this,arguments);},destroy:function(){OpenLayers.Renderer.Elements.prototype.destroy.apply(this,arguments);},supported:function(){return!!(document.namespaces);},setExtent:function(extent,resolutionChanged){OpenLayers.Renderer.Elements.prototype.setExtent.apply(this,arguments);var resolution=this.getResolution();var left=(extent.left/resolution)|0;var top=(extent.top/resolution-this.size.h)|0;if(resolutionChanged||!this.offset){this.offset={x:left,y:top};left=0;top=0;}else{left=left-this.offset.x;top=top-this.offset.y;}
var org=left+" "+top;this.root.coordorigin=org;var roots=[this.root,this.vectorRoot,this.textRoot];var root;for(var i=0,len=roots.length;i<len;++i){root=roots[i];var size=this.size.w+" "+this.size.h;root.coordsize=size;}
this.root.style.flip="y";return true;},setSize:function(size){OpenLayers.Renderer.prototype.setSize.apply(this,arguments);var roots=[this.rendererRoot,this.root,this.vectorRoot,this.textRoot];var w=this.size.w+"px";var h=this.size.h+"px";var root;for(var i=0,len=roots.length;i<len;++i){root=roots[i];root.style.width=w;root.style.height=h;}},getNodeType:function(geometry,style){var nodeType=null;switch(geometry.CLASS_NAME){case"OpenLayers.Geometry.Point":if(style.externalGraphic){nodeType="olv:rect";}else if(this.isComplexSymbol(style.graphicName)){nodeType="olv:shape";}else{nodeType="olv:oval";}
break;case"OpenLayers.Geometry.Rectangle":nodeType="olv:rect";break;case"OpenLayers.Geometry.LineString":case"OpenLayers.Geometry.LinearRing":case"OpenLayers.Geometry.Polygon":case"OpenLayers.Geometry.Curve":case"OpenLayers.Geometry.Surface":nodeType="olv:shape";break;default:break;}
return nodeType;},setStyle:function(node,style,options,geometry){style=style||node._style;options=options||node._options;var fillColor=style.fillColor;if(node._geometryClass==="OpenLayers.Geometry.Point"){if(style.externalGraphic){if(style.graphicTitle){node.title=style.graphicTitle;}
var width=style.graphicWidth||style.graphicHeight;var height=style.graphicHeight||style.graphicWidth;width=width?width:style.pointRadius*2;height=height?height:style.pointRadius*2;var resolution=this.getResolution();var xOffset=(style.graphicXOffset!=undefined)?style.graphicXOffset:-(0.5*width);var yOffset=(style.graphicYOffset!=undefined)?style.graphicYOffset:-(0.5*height);node.style.left=(((geometry.x/resolution-this.offset.x)+xOffset)|0)+"px";node.style.top=(((geometry.y/resolution-this.offset.y)-(yOffset+height))|0)+"px";node.style.width=width+"px";node.style.height=height+"px";node.style.flip="y";fillColor="none";options.isStroked=false;}else if(this.isComplexSymbol(style.graphicName)){var cache=this.importSymbol(style.graphicName);node.path=cache.path;node.coordorigin=cache.left+","+cache.bottom;var size=cache.size;node.coordsize=size+","+size;this.drawCircle(node,geometry,style.pointRadius);node.style.flip="y";}else{this.drawCircle(node,geometry,style.pointRadius);}}
if(options.isFilled){node.fillcolor=fillColor;}else{node.filled="false";}
var fills=node.getElementsByTagName("fill");var fill=(fills.length==0)?null:fills[0];if(!options.isFilled){if(fill){node.removeChild(fill);}}else{if(!fill){fill=this.createNode('olv:fill',node.id+"_fill");}
fill.opacity=style.fillOpacity;if(node._geometryClass==="OpenLayers.Geometry.Point"&&style.externalGraphic){if(style.graphicOpacity){fill.opacity=style.graphicOpacity;}
fill.src=style.externalGraphic;fill.type="frame";if(!(style.graphicWidth&&style.graphicHeight)){fill.aspect="atmost";}}
if(fill.parentNode!=node){node.appendChild(fill);}}
var rotation=style.rotation;if((rotation!==undefined||node._rotation!==undefined)){node._rotation=rotation;if(style.externalGraphic){this.graphicRotate(node,xOffset,yOffset,style);fill.opacity=0;}else if(node._geometryClass==="OpenLayers.Geometry.Point"){node.style.rotation=rotation||0;}}
var strokes=node.getElementsByTagName("stroke");var stroke=(strokes.length==0)?null:strokes[0];if(!options.isStroked){node.stroked=false;if(stroke){stroke.on=false;}}else{if(!stroke){stroke=this.createNode('olv:stroke',node.id+"_stroke");node.appendChild(stroke);}
stroke.on=true;stroke.color=style.strokeColor;stroke.weight=style.strokeWidth+"px";stroke.opacity=style.strokeOpacity;stroke.endcap=style.strokeLinecap=='butt'?'flat':(style.strokeLinecap||'round');if(style.strokeDashstyle){stroke.dashstyle=this.dashStyle(style);}}
if(style.cursor!="inherit"&&style.cursor!=null){node.style.cursor=style.cursor;}
return node;},graphicRotate:function(node,xOffset,yOffset,style){var style=style||node._style;var rotation=style.rotation||0;var aspectRatio,size;if(!(style.graphicWidth&&style.graphicHeight)){var img=new Image();img.onreadystatechange=OpenLayers.Function.bind(function(){if(img.readyState=="complete"||img.readyState=="interactive"){aspectRatio=img.width/img.height;size=Math.max(style.pointRadius*2,style.graphicWidth||0,style.graphicHeight||0);xOffset=xOffset*aspectRatio;style.graphicWidth=size*aspectRatio;style.graphicHeight=size;this.graphicRotate(node,xOffset,yOffset,style);}},this);img.src=style.externalGraphic;return;}else{size=Math.max(style.graphicWidth,style.graphicHeight);aspectRatio=style.graphicWidth/style.graphicHeight;}
var width=Math.round(style.graphicWidth||size*aspectRatio);var height=Math.round(style.graphicHeight||size);node.style.width=width+"px";node.style.height=height+"px";var image=document.getElementById(node.id+"_image");if(!image){image=this.createNode("olv:imagedata",node.id+"_image");node.appendChild(image);}
image.style.width=width+"px";image.style.height=height+"px";image.src=style.externalGraphic;image.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader("+"src='', sizingMethod='scale')";var rot=rotation*Math.PI/180;var sintheta=Math.sin(rot);var costheta=Math.cos(rot);var filter="progid:DXImageTransform.Microsoft.Matrix(M11="+costheta+",M12="+(-sintheta)+",M21="+sintheta+",M22="+costheta+",SizingMethod='auto expand')\n";var opacity=style.graphicOpacity||style.fillOpacity;if(opacity&&opacity!=1){filter+="progid:DXImageTransform.Microsoft.BasicImage(opacity="+
opacity+")\n";}
node.style.filter=filter;var centerPoint=new OpenLayers.Geometry.Point(-xOffset,-yOffset);var imgBox=new OpenLayers.Bounds(0,0,width,height).toGeometry();imgBox.rotate(style.rotation,centerPoint);var imgBounds=imgBox.getBounds();node.style.left=Math.round(parseInt(node.style.left)+imgBounds.left)+"px";node.style.top=Math.round(parseInt(node.style.top)-imgBounds.bottom)+"px";},postDraw:function(node){node.style.visibility="visible";var fillColor=node._style.fillColor;var strokeColor=node._style.strokeColor;if(fillColor=="none"&&node.fillcolor!=fillColor){node.fillcolor=fillColor;}
if(strokeColor=="none"&&node.strokecolor!=strokeColor){node.strokecolor=strokeColor;}},setNodeDimension:function(node,geometry){var bbox=geometry.getBounds();if(bbox){var resolution=this.getResolution();var scaledBox=new OpenLayers.Bounds((bbox.left/resolution-this.offset.x)|0,(bbox.bottom/resolution-this.offset.y)|0,(bbox.right/resolution-this.offset.x)|0,(bbox.top/resolution-this.offset.y)|0);node.style.left=scaledBox.left+"px";node.style.top=scaledBox.top+"px";node.style.width=scaledBox.getWidth()+"px";node.style.height=scaledBox.getHeight()+"px";node.coordorigin=scaledBox.left+" "+scaledBox.top;node.coordsize=scaledBox.getWidth()+" "+scaledBox.getHeight();}},dashStyle:function(style){var dash=style.strokeDashstyle;switch(dash){case'solid':case'dot':case'dash':case'dashdot':case'longdash':case'longdashdot':return dash;default:var parts=dash.split(/[ ,]/);if(parts.length==2){if(1*parts[0]>=2*parts[1]){return"longdash";}
return(parts[0]==1||parts[1]==1)?"dot":"dash";}else if(parts.length==4){return(1*parts[0]>=2*parts[1])?"longdashdot":"dashdot";}
return"solid";}},createNode:function(type,id){var node=document.createElement(type);if(id){node.id=id;}
node.unselectable='on';node.onselectstart=OpenLayers.Function.False;return node;},nodeTypeCompare:function(node,type){var subType=type;var splitIndex=subType.indexOf(":");if(splitIndex!=-1){subType=subType.substr(splitIndex+1);}
var nodeName=node.nodeName;splitIndex=nodeName.indexOf(":");if(splitIndex!=-1){nodeName=nodeName.substr(splitIndex+1);}
return(subType==nodeName);},createRenderRoot:function(){return this.nodeFactory(this.container.id+"_vmlRoot","div");},createRoot:function(suffix){return this.nodeFactory(this.container.id+suffix,"olv:group");},drawPoint:function(node,geometry){return this.drawCircle(node,geometry,1);},drawCircle:function(node,geometry,radius){if(!isNaN(geometry.x)&&!isNaN(geometry.y)){var resolution=this.getResolution();node.style.left=(((geometry.x/resolution-this.offset.x)|0)-radius)+"px";node.style.top=(((geometry.y/resolution-this.offset.y)|0)-radius)+"px";var diameter=radius*2;node.style.width=diameter+"px";node.style.height=diameter+"px";return node;}
return false;},drawLineString:function(node,geometry){return this.drawLine(node,geometry,false);},drawLinearRing:function(node,geometry){return this.drawLine(node,geometry,true);},drawLine:function(node,geometry,closeLine){this.setNodeDimension(node,geometry);var resolution=this.getResolution();var numComponents=geometry.components.length;var parts=new Array(numComponents);var comp,x,y;for(var i=0;i<numComponents;i++){comp=geometry.components[i];x=(comp.x/resolution-this.offset.x)|0;y=(comp.y/resolution-this.offset.y)|0;parts[i]=" "+x+","+y+" l ";}
var end=(closeLine)?" x e":" e";node.path="m"+parts.join("")+end;return node;},drawPolygon:function(node,geometry){this.setNodeDimension(node,geometry);var resolution=this.getResolution();var path=[];var linearRing,i,j,len,ilen,comp,x,y;for(j=0,len=geometry.components.length;j<len;j++){linearRing=geometry.components[j];path.push("m");for(i=0,ilen=linearRing.components.length;i<ilen;i++){comp=linearRing.components[i];x=(comp.x/resolution-this.offset.x)|0;y=(comp.y/resolution-this.offset.y)|0;path.push(" "+x+","+y);if(i==0){path.push(" l");}}
path.push(" x ");}
path.push("e");node.path=path.join("");return node;},drawRectangle:function(node,geometry){var resolution=this.getResolution();node.style.left=((geometry.x/resolution-this.offset.x)|0)+"px";node.style.top=((geometry.y/resolution-this.offset.y)|0)+"px";node.style.width=((geometry.width/resolution)|0)+"px";node.style.height=((geometry.height/resolution)|0)+"px";return node;},drawText:function(featureId,style,location){var label=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX,"olv:rect");var textbox=this.nodeFactory(featureId+this.LABEL_ID_SUFFIX+"_textbox","olv:textbox");var resolution=this.getResolution();label.style.left=((location.x/resolution-this.offset.x)|0)+"px";label.style.top=((location.y/resolution-this.offset.y)|0)+"px";label.style.flip="y";textbox.innerText=style.label;if(style.fontColor){textbox.style.color=style.fontColor;}
if(style.fontOpacity){textbox.style.filter='alpha(opacity='+(style.fontOpacity*100)+')';}
if(style.fontFamily){textbox.style.fontFamily=style.fontFamily;}
if(style.fontSize){textbox.style.fontSize=style.fontSize;}
if(style.fontWeight){textbox.style.fontWeight=style.fontWeight;}
if(style.labelSelect===true){label._featureId=featureId;textbox._featureId=featureId;textbox._geometry=location;textbox._geometryClass=location.CLASS_NAME;}
textbox.style.whiteSpace="nowrap";textbox.inset="1px,0px,0px,0px";if(!label.parentNode){label.appendChild(textbox);this.textRoot.appendChild(label);}
var align=style.labelAlign||"cm";if(align.length==1){align+="m";}
var xshift=textbox.clientWidth*(OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(0,1)]);var yshift=textbox.clientHeight*(OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(1,1)]);label.style.left=parseInt(label.style.left)-xshift-1+"px";label.style.top=parseInt(label.style.top)+yshift+"px";},drawSurface:function(node,geometry){this.setNodeDimension(node,geometry);var resolution=this.getResolution();var path=[];var comp,x,y;for(var i=0,len=geometry.components.length;i<len;i++){comp=geometry.components[i];x=(comp.x/resolution-this.offset.x)|0;y=(comp.y/resolution-this.offset.y)|0;if((i%3)==0&&(i/3)==0){path.push("m");}else if((i%3)==1){path.push(" c");}
path.push(" "+x+","+y);}
path.push(" x e");node.path=path.join("");return node;},moveRoot:function(renderer){var layer=this.map.getLayer(renderer.container.id);if(layer instanceof OpenLayers.Layer.Vector.RootContainer){layer=this.map.getLayer(this.container.id);}
layer&&layer.renderer.clear();OpenLayers.Renderer.Elements.prototype.moveRoot.apply(this,arguments);layer&&layer.redraw();},importSymbol:function(graphicName){var id=this.container.id+"-"+graphicName;var cache=this.symbolCache[id];if(cache){return cache;}
var symbol=OpenLayers.Renderer.symbol[graphicName];if(!symbol){throw new Error(graphicName+' is not a valid symbol name');}
var symbolExtent=new OpenLayers.Bounds(Number.MAX_VALUE,Number.MAX_VALUE,0,0);var pathitems=["m"];for(var i=0;i<symbol.length;i=i+2){var x=symbol[i];var y=symbol[i+1];symbolExtent.left=Math.min(symbolExtent.left,x);symbolExtent.bottom=Math.min(symbolExtent.bottom,y);symbolExtent.right=Math.max(symbolExtent.right,x);symbolExtent.top=Math.max(symbolExtent.top,y);pathitems.push(x);pathitems.push(y);if(i==0){pathitems.push("l");}}
pathitems.push("x e");var path=pathitems.join(" ");var diff=(symbolExtent.getWidth()-symbolExtent.getHeight())/2;if(diff>0){symbolExtent.bottom=symbolExtent.bottom-diff;symbolExtent.top=symbolExtent.top+diff;}else{symbolExtent.left=symbolExtent.left+diff;symbolExtent.right=symbolExtent.right-diff;}
cache={path:path,size:symbolExtent.getWidth(),left:symbolExtent.left,bottom:symbolExtent.bottom};this.symbolCache[id]=cache;return cache;},CLASS_NAME:"OpenLayers.Renderer.VML"});OpenLayers.Renderer.VML.LABEL_SHIFT={"l":0,"c":.5,"r":1,"t":0,"m":.5,"b":1};OpenLayers.Tile=OpenLayers.Class({EVENT_TYPES:["loadstart","loadend","reload","unload"],events:null,id:null,layer:null,url:null,bounds:null,size:null,position:null,isLoading:false,initialize:function(layer,position,bounds,url,size){this.layer=layer;this.position=position.clone();this.bounds=bounds.clone();this.url=url;this.size=size.clone();this.id=OpenLayers.Util.createUniqueID("Tile_");this.events=new OpenLayers.Events(this,null,this.EVENT_TYPES);},unload:function(){if(this.isLoading){this.isLoading=false;this.events.triggerEvent("unload");}},destroy:function(){this.layer=null;this.bounds=null;this.size=null;this.position=null;this.events.destroy();this.events=null;},clone:function(obj){if(obj==null){obj=new OpenLayers.Tile(this.layer,this.position,this.bounds,this.url,this.size);}
OpenLayers.Util.applyDefaults(obj,this);return obj;},draw:function(){var maxExtent=this.layer.maxExtent;var withinMaxExtent=(maxExtent&&this.bounds.intersectsBounds(maxExtent,false));this.shouldDraw=(withinMaxExtent||this.layer.displayOutsideMaxExtent);this.clear();return this.shouldDraw;},moveTo:function(bounds,position,redraw){if(redraw==null){redraw=true;}
this.bounds=bounds.clone();this.position=position.clone();if(redraw){this.draw();}},clear:function(){},getBoundsFromBaseLayer:function(position){var msg=OpenLayers.i18n('reprojectDeprecated',{'layerName':this.layer.name});OpenLayers.Console.warn(msg);var topLeft=this.layer.map.getLonLatFromLayerPx(position);var bottomRightPx=position.clone();bottomRightPx.x+=this.size.w;bottomRightPx.y+=this.size.h;var bottomRight=this.layer.map.getLonLatFromLayerPx(bottomRightPx);if(topLeft.lon>bottomRight.lon){if(topLeft.lon<0){topLeft.lon=-180-(topLeft.lon+180);}else{bottomRight.lon=180+bottomRight.lon+180;}}
var bounds=new OpenLayers.Bounds(topLeft.lon,bottomRight.lat,bottomRight.lon,topLeft.lat);return bounds;},showTile:function(){if(this.shouldDraw){this.show();}},show:function(){},hide:function(){},CLASS_NAME:"OpenLayers.Tile"});OpenLayers.Control.MouseToolbar=OpenLayers.Class(OpenLayers.Control.MouseDefaults,{mode:null,buttons:null,direction:"vertical",buttonClicked:null,initialize:function(position,direction){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.position=new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,OpenLayers.Control.MouseToolbar.Y);if(position){this.position=position;}
if(direction){this.direction=direction;}
this.measureDivs=[];},destroy:function(){for(var btnId in this.buttons){var btn=this.buttons[btnId];btn.map=null;btn.events.destroy();}
OpenLayers.Control.MouseDefaults.prototype.destroy.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);OpenLayers.Control.MouseDefaults.prototype.draw.apply(this,arguments);this.buttons={};var sz=new OpenLayers.Size(28,28);var centered=new OpenLayers.Pixel(OpenLayers.Control.MouseToolbar.X,0);this._addButton("zoombox","drag-rectangle-off.png","drag-rectangle-on.png",centered,sz,"Shift->Drag to zoom to area");centered=centered.add((this.direction=="vertical"?0:sz.w),(this.direction=="vertical"?sz.h:0));this._addButton("pan","panning-hand-off.png","panning-hand-on.png",centered,sz,"Drag the map to pan.");centered=centered.add((this.direction=="vertical"?0:sz.w),(this.direction=="vertical"?sz.h:0));this.switchModeTo("pan");return this.div;},_addButton:function(id,img,activeImg,xy,sz,title){var imgLocation=OpenLayers.Util.getImagesLocation()+img;var activeImgLocation=OpenLayers.Util.getImagesLocation()+activeImg;var btn=OpenLayers.Util.createAlphaImageDiv("OpenLayers_Control_MouseToolbar_"+id,xy,sz,imgLocation,"absolute");this.div.appendChild(btn);btn.imgLocation=imgLocation;btn.activeImgLocation=activeImgLocation;btn.events=new OpenLayers.Events(this,btn,null,true);btn.events.on({"mousedown":this.buttonDown,"mouseup":this.buttonUp,"dblclick":OpenLayers.Event.stop,scope:this});btn.action=id;btn.title=title;btn.alt=title;btn.map=this.map;this.buttons[id]=btn;return btn;},buttonDown:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
this.buttonClicked=evt.element.action;OpenLayers.Event.stop(evt);},buttonUp:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
if(this.buttonClicked!=null){if(this.buttonClicked==evt.element.action){this.switchModeTo(evt.element.action);}
OpenLayers.Event.stop(evt);this.buttonClicked=null;}},defaultDblClick:function(evt){this.switchModeTo("pan");this.performedDrag=false;var newCenter=this.map.getLonLatFromViewPortPx(evt.xy);this.map.setCenter(newCenter,this.map.zoom+1);OpenLayers.Event.stop(evt);return false;},defaultMouseDown:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
this.mouseDragStart=evt.xy.clone();this.performedDrag=false;this.startViaKeyboard=false;if(evt.shiftKey&&this.mode!="zoombox"){this.switchModeTo("zoombox");this.startViaKeyboard=true;}else if(evt.altKey&&this.mode!="measure"){this.switchModeTo("measure");}else if(!this.mode){this.switchModeTo("pan");}
switch(this.mode){case"zoombox":this.map.div.style.cursor="crosshair";this.zoomBox=OpenLayers.Util.createDiv('zoomBox',this.mouseDragStart,null,null,"absolute","2px solid red");this.zoomBox.style.backgroundColor="white";this.zoomBox.style.filter="alpha(opacity=50)";this.zoomBox.style.opacity="0.50";this.zoomBox.style.fontSize="1px";this.zoomBox.style.zIndex=this.map.Z_INDEX_BASE["Popup"]-1;this.map.viewPortDiv.appendChild(this.zoomBox);this.performedDrag=true;break;case"measure":var distance="";if(this.measureStart){var measureEnd=this.map.getLonLatFromViewPortPx(this.mouseDragStart);distance=OpenLayers.Util.distVincenty(this.measureStart,measureEnd);distance=Math.round(distance*100)/100;distance=distance+"km";this.measureStartBox=this.measureBox;}
this.measureStart=this.map.getLonLatFromViewPortPx(this.mouseDragStart);;this.measureBox=OpenLayers.Util.createDiv(null,this.mouseDragStart.add(-2-parseInt(this.map.layerContainerDiv.style.left),-2-parseInt(this.map.layerContainerDiv.style.top)),null,null,"absolute");this.measureBox.style.width="4px";this.measureBox.style.height="4px";this.measureBox.style.fontSize="1px";this.measureBox.style.backgroundColor="red";this.measureBox.style.zIndex=this.map.Z_INDEX_BASE["Popup"]-1;this.map.layerContainerDiv.appendChild(this.measureBox);if(distance){this.measureBoxDistance=OpenLayers.Util.createDiv(null,this.mouseDragStart.add(-2-parseInt(this.map.layerContainerDiv.style.left),2-parseInt(this.map.layerContainerDiv.style.top)),null,null,"absolute");this.measureBoxDistance.innerHTML=distance;this.measureBoxDistance.style.zIndex=this.map.Z_INDEX_BASE["Popup"]-1;this.map.layerContainerDiv.appendChild(this.measureBoxDistance);this.measureDivs.push(this.measureBoxDistance);}
this.measureBox.style.zIndex=this.map.Z_INDEX_BASE["Popup"]-1;this.map.layerContainerDiv.appendChild(this.measureBox);this.measureDivs.push(this.measureBox);break;default:this.map.div.style.cursor="move";break;}
document.onselectstart=OpenLayers.Function.False;OpenLayers.Event.stop(evt);},switchModeTo:function(mode){if(mode!=this.mode){if(this.mode&&this.buttons[this.mode]){OpenLayers.Util.modifyAlphaImageDiv(this.buttons[this.mode],null,null,null,this.buttons[this.mode].imgLocation);}
if(this.mode=="measure"&&mode!="measure"){for(var i=0,len=this.measureDivs.length;i<len;i++){if(this.measureDivs[i]){this.map.layerContainerDiv.removeChild(this.measureDivs[i]);}}
this.measureDivs=[];this.measureStart=null;}
this.mode=mode;if(this.buttons[mode]){OpenLayers.Util.modifyAlphaImageDiv(this.buttons[mode],null,null,null,this.buttons[mode].activeImgLocation);}
switch(this.mode){case"zoombox":this.map.div.style.cursor="crosshair";break;default:this.map.div.style.cursor="";break;}}},leaveMode:function(){this.switchModeTo("pan");},defaultMouseMove:function(evt){if(this.mouseDragStart!=null){switch(this.mode){case"zoombox":var deltaX=Math.abs(this.mouseDragStart.x-evt.xy.x);var deltaY=Math.abs(this.mouseDragStart.y-evt.xy.y);this.zoomBox.style.width=Math.max(1,deltaX)+"px";this.zoomBox.style.height=Math.max(1,deltaY)+"px";if(evt.xy.x<this.mouseDragStart.x){this.zoomBox.style.left=evt.xy.x+"px";}
if(evt.xy.y<this.mouseDragStart.y){this.zoomBox.style.top=evt.xy.y+"px";}
break;default:var deltaX=this.mouseDragStart.x-evt.xy.x;var deltaY=this.mouseDragStart.y-evt.xy.y;var size=this.map.getSize();var newXY=new OpenLayers.Pixel(size.w/2+deltaX,size.h/2+deltaY);var newCenter=this.map.getLonLatFromViewPortPx(newXY);this.map.setCenter(newCenter,null,true);this.mouseDragStart=evt.xy.clone();}
this.performedDrag=true;}},defaultMouseUp:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
switch(this.mode){case"zoombox":this.zoomBoxEnd(evt);if(this.startViaKeyboard){this.leaveMode();}
break;case"pan":if(this.performedDrag){this.map.setCenter(this.map.center);}}
document.onselectstart=null;this.mouseDragStart=null;this.map.div.style.cursor="default";},defaultMouseOut:function(evt){if(this.mouseDragStart!=null&&OpenLayers.Util.mouseLeft(evt,this.map.div)){if(this.zoomBox){this.removeZoomBox();if(this.startViaKeyboard){this.leaveMode();}}
this.mouseDragStart=null;this.map.div.style.cursor="default";}},defaultClick:function(evt){if(this.performedDrag){this.performedDrag=false;return false;}},CLASS_NAME:"OpenLayers.Control.MouseToolbar"});OpenLayers.Control.MouseToolbar.X=6;OpenLayers.Control.MouseToolbar.Y=300;OpenLayers.Control.NavigationHistory=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOGGLE,previous:null,previousOptions:null,next:null,nextOptions:null,limit:50,autoActivate:true,clearOnDeactivate:false,registry:null,nextStack:null,previousStack:null,listeners:null,restoring:false,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.registry=OpenLayers.Util.extend({"moveend":this.getState},this.registry);var previousOptions={trigger:OpenLayers.Function.bind(this.previousTrigger,this),displayClass:this.displayClass+" "+this.displayClass+"Previous"};OpenLayers.Util.extend(previousOptions,this.previousOptions);this.previous=new OpenLayers.Control.Button(previousOptions);var nextOptions={trigger:OpenLayers.Function.bind(this.nextTrigger,this),displayClass:this.displayClass+" "+this.displayClass+"Next"};OpenLayers.Util.extend(nextOptions,this.nextOptions);this.next=new OpenLayers.Control.Button(nextOptions);this.clear();},onPreviousChange:function(state,length){if(state&&!this.previous.active){this.previous.activate();}else if(!state&&this.previous.active){this.previous.deactivate();}},onNextChange:function(state,length){if(state&&!this.next.active){this.next.activate();}else if(!state&&this.next.active){this.next.deactivate();}},destroy:function(){OpenLayers.Control.prototype.destroy.apply(this);this.previous.destroy();this.next.destroy();this.deactivate();for(var prop in this){this[prop]=null;}},setMap:function(map){this.map=map;this.next.setMap(map);this.previous.setMap(map);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);this.next.draw();this.previous.draw();},previousTrigger:function(){var current=this.previousStack.shift();var state=this.previousStack.shift();if(state!=undefined){this.nextStack.unshift(current);this.previousStack.unshift(state);this.restoring=true;this.restore(state);this.restoring=false;this.onNextChange(this.nextStack[0],this.nextStack.length);this.onPreviousChange(this.previousStack[1],this.previousStack.length-1);}else{this.previousStack.unshift(current);}
return state;},nextTrigger:function(){var state=this.nextStack.shift();if(state!=undefined){this.previousStack.unshift(state);this.restoring=true;this.restore(state);this.restoring=false;this.onNextChange(this.nextStack[0],this.nextStack.length);this.onPreviousChange(this.previousStack[1],this.previousStack.length-1);}
return state;},clear:function(){this.previousStack=[];this.previous.deactivate();this.nextStack=[];this.next.deactivate();},getState:function(){return{center:this.map.getCenter(),resolution:this.map.getResolution(),projection:this.map.getProjectionObject(),units:this.map.getProjectionObject().getUnits()||this.map.units||this.map.baseLayer.units};},restore:function(state){var center,zoom;if(this.map.getProjectionObject()==state.projection){zoom=this.map.getZoomForResolution(state.resolution);center=state.center;}else{center=state.center.clone();center.transform(state.projection,this.map.getProjectionObject());var sourceUnits=state.units;var targetUnits=this.map.getProjectionObject().getUnits()||this.map.units||this.map.baseLayer.units;var resolutionFactor=sourceUnits&&targetUnits?OpenLayers.INCHES_PER_UNIT[sourceUnits]/OpenLayers.INCHES_PER_UNIT[targetUnits]:1;zoom=this.map.getZoomForResolution(resolutionFactor*state.resolution);}
this.map.setCenter(center,zoom);},setListeners:function(){this.listeners={};for(var type in this.registry){this.listeners[type]=OpenLayers.Function.bind(function(){if(!this.restoring){var state=this.registry[type].apply(this,arguments);this.previousStack.unshift(state);if(this.previousStack.length>1){this.onPreviousChange(this.previousStack[1],this.previousStack.length-1);}
if(this.previousStack.length>(this.limit+1)){this.previousStack.pop();}
if(this.nextStack.length>0){this.nextStack=[];this.onNextChange(null,0);}}
return true;},this);}},activate:function(){var activated=false;if(this.map){if(OpenLayers.Control.prototype.activate.apply(this)){if(this.listeners==null){this.setListeners();}
for(var type in this.listeners){this.map.events.register(type,this,this.listeners[type]);}
activated=true;if(this.previousStack.length==0){this.initStack();}}}
return activated;},initStack:function(){if(this.map.getCenter()){this.listeners.moveend();}},deactivate:function(){var deactivated=false;if(this.map){if(OpenLayers.Control.prototype.deactivate.apply(this)){for(var type in this.listeners){this.map.events.unregister(type,this,this.listeners[type]);}
if(this.clearOnDeactivate){this.clear();}
deactivated=true;}}
return deactivated;},CLASS_NAME:"OpenLayers.Control.NavigationHistory"});OpenLayers.Control.PanPanel=OpenLayers.Class(OpenLayers.Control.Panel,{slideFactor:50,initialize:function(options){OpenLayers.Control.Panel.prototype.initialize.apply(this,[options]);this.addControls([new OpenLayers.Control.Pan(OpenLayers.Control.Pan.NORTH,{slideFactor:this.slideFactor}),new OpenLayers.Control.Pan(OpenLayers.Control.Pan.SOUTH,{slideFactor:this.slideFactor}),new OpenLayers.Control.Pan(OpenLayers.Control.Pan.EAST,{slideFactor:this.slideFactor}),new OpenLayers.Control.Pan(OpenLayers.Control.Pan.WEST,{slideFactor:this.slideFactor})]);},CLASS_NAME:"OpenLayers.Control.PanPanel"});OpenLayers.Control.PanZoomBar=OpenLayers.Class(OpenLayers.Control.PanZoom,{zoomStopWidth:18,zoomStopHeight:11,slider:null,sliderEvents:null,zoombarDiv:null,divEvents:null,zoomWorldIcon:false,forceFixedZoomLevel:false,mouseDragStart:null,zoomStart:null,initialize:function(){OpenLayers.Control.PanZoom.prototype.initialize.apply(this,arguments);},destroy:function(){this._removeZoomBar();this.map.events.un({"changebaselayer":this.redraw,scope:this});OpenLayers.Control.PanZoom.prototype.destroy.apply(this,arguments);delete this.mouseDragStart;delete this.zoomStart;},setMap:function(map){OpenLayers.Control.PanZoom.prototype.setMap.apply(this,arguments);this.map.events.register("changebaselayer",this,this.redraw);},redraw:function(){if(this.div!=null){this.removeButtons();this._removeZoomBar();}
this.draw();},draw:function(px){OpenLayers.Control.prototype.draw.apply(this,arguments);px=this.position.clone();this.buttons=[];var sz=new OpenLayers.Size(18,18);var centered=new OpenLayers.Pixel(px.x+sz.w/2,px.y);var wposition=sz.w;if(this.zoomWorldIcon){centered=new OpenLayers.Pixel(px.x+sz.w,px.y);}
this._addButton("panup","north-mini.png",centered,sz);px.y=centered.y+sz.h;this._addButton("panleft","west-mini.png",px,sz);if(this.zoomWorldIcon){this._addButton("zoomworld","zoom-world-mini.png",px.add(sz.w,0),sz);wposition*=2;}
this._addButton("panright","east-mini.png",px.add(wposition,0),sz);this._addButton("pandown","south-mini.png",centered.add(0,sz.h*2),sz);this._addButton("zoomin","zoom-plus-mini.png",centered.add(0,sz.h*3+5),sz);centered=this._addZoomBar(centered.add(0,sz.h*4+5));this._addButton("zoomout","zoom-minus-mini.png",centered,sz);return this.div;},_addZoomBar:function(centered){var imgLocation=OpenLayers.Util.getImagesLocation();var id=this.id+"_"+this.map.id;var zoomsToEnd=this.map.getNumZoomLevels()-1-this.map.getZoom();var slider=OpenLayers.Util.createAlphaImageDiv(id,centered.add(-1,zoomsToEnd*this.zoomStopHeight),new OpenLayers.Size(20,9),imgLocation+"slider.png","absolute");this.slider=slider;this.sliderEvents=new OpenLayers.Events(this,slider,null,true,{includeXY:true});this.sliderEvents.on({"mousedown":this.zoomBarDown,"mousemove":this.zoomBarDrag,"mouseup":this.zoomBarUp,"dblclick":this.doubleClick,"click":this.doubleClick});var sz=new OpenLayers.Size();sz.h=this.zoomStopHeight*this.map.getNumZoomLevels();sz.w=this.zoomStopWidth;var div=null;if(OpenLayers.Util.alphaHack()){var id=this.id+"_"+this.map.id;div=OpenLayers.Util.createAlphaImageDiv(id,centered,new OpenLayers.Size(sz.w,this.zoomStopHeight),imgLocation+"zoombar.png","absolute",null,"crop");div.style.height=sz.h+"px";}else{div=OpenLayers.Util.createDiv('OpenLayers_Control_PanZoomBar_Zoombar'+this.map.id,centered,sz,imgLocation+"zoombar.png");}
this.zoombarDiv=div;this.divEvents=new OpenLayers.Events(this,div,null,true,{includeXY:true});this.divEvents.on({"mousedown":this.divClick,"mousemove":this.passEventToSlider,"dblclick":this.doubleClick,"click":this.doubleClick});this.div.appendChild(div);this.startTop=parseInt(div.style.top);this.div.appendChild(slider);this.map.events.register("zoomend",this,this.moveZoomBar);centered=centered.add(0,this.zoomStopHeight*this.map.getNumZoomLevels());return centered;},_removeZoomBar:function(){this.sliderEvents.un({"mousedown":this.zoomBarDown,"mousemove":this.zoomBarDrag,"mouseup":this.zoomBarUp,"dblclick":this.doubleClick,"click":this.doubleClick});this.sliderEvents.destroy();this.divEvents.un({"mousedown":this.divClick,"mousemove":this.passEventToSlider,"dblclick":this.doubleClick,"click":this.doubleClick});this.divEvents.destroy();this.div.removeChild(this.zoombarDiv);this.zoombarDiv=null;this.div.removeChild(this.slider);this.slider=null;this.map.events.unregister("zoomend",this,this.moveZoomBar);},passEventToSlider:function(evt){this.sliderEvents.handleBrowserEvent(evt);},divClick:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
var y=evt.xy.y;var top=OpenLayers.Util.pagePosition(evt.object)[1];var levels=(y-top)/this.zoomStopHeight;if(this.forceFixedZoomLevel||!this.map.fractionalZoom){levels=Math.floor(levels);}
var zoom=(this.map.getNumZoomLevels()-1)-levels;zoom=Math.min(Math.max(zoom,0),this.map.getNumZoomLevels()-1);this.map.zoomTo(zoom);OpenLayers.Event.stop(evt);},zoomBarDown:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
this.map.events.on({"mousemove":this.passEventToSlider,"mouseup":this.passEventToSlider,scope:this});this.mouseDragStart=evt.xy.clone();this.zoomStart=evt.xy.clone();this.div.style.cursor="move";this.zoombarDiv.offsets=null;OpenLayers.Event.stop(evt);},zoomBarDrag:function(evt){if(this.mouseDragStart!=null){var deltaY=this.mouseDragStart.y-evt.xy.y;var offsets=OpenLayers.Util.pagePosition(this.zoombarDiv);if((evt.clientY-offsets[1])>0&&(evt.clientY-offsets[1])<parseInt(this.zoombarDiv.style.height)-2){var newTop=parseInt(this.slider.style.top)-deltaY;this.slider.style.top=newTop+"px";this.mouseDragStart=evt.xy.clone();}
OpenLayers.Event.stop(evt);}},zoomBarUp:function(evt){if(!OpenLayers.Event.isLeftClick(evt)){return;}
if(this.mouseDragStart){this.div.style.cursor="";this.map.events.un({"mouseup":this.passEventToSlider,"mousemove":this.passEventToSlider,scope:this});var deltaY=this.zoomStart.y-evt.xy.y;var zoomLevel=this.map.zoom;if(!this.forceFixedZoomLevel&&this.map.fractionalZoom){zoomLevel+=deltaY/this.zoomStopHeight;zoomLevel=Math.min(Math.max(zoomLevel,0),this.map.getNumZoomLevels()-1);}else{zoomLevel+=Math.round(deltaY/this.zoomStopHeight);}
this.map.zoomTo(zoomLevel);this.mouseDragStart=null;this.zoomStart=null;OpenLayers.Event.stop(evt);}},moveZoomBar:function(){var newTop=((this.map.getNumZoomLevels()-1)-this.map.getZoom())*this.zoomStopHeight+this.startTop+1;this.slider.style.top=newTop+"px";},CLASS_NAME:"OpenLayers.Control.PanZoomBar"});OpenLayers.Control.Permalink=OpenLayers.Class(OpenLayers.Control,{argParserClass:OpenLayers.Control.ArgParser,element:null,base:'',displayProjection:null,initialize:function(element,base,options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.element=OpenLayers.Util.getElement(element);this.base=base||document.location.href;},destroy:function(){if(this.element.parentNode==this.div){this.div.removeChild(this.element);}
this.element=null;this.map.events.unregister('moveend',this,this.updateLink);OpenLayers.Control.prototype.destroy.apply(this,arguments);},setMap:function(map){OpenLayers.Control.prototype.setMap.apply(this,arguments);for(var i=0,len=this.map.controls.length;i<len;i++){var control=this.map.controls[i];if(control.CLASS_NAME==this.argParserClass.CLASS_NAME){if(control.displayProjection!=this.displayProjection){this.displayProjection=control.displayProjection;}
break;}}
if(i==this.map.controls.length){this.map.addControl(new this.argParserClass({'displayProjection':this.displayProjection}));}},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!this.element){this.div.className=this.displayClass;this.element=document.createElement("a");this.element.innerHTML=OpenLayers.i18n("permalink");this.element.href="";this.div.appendChild(this.element);}
this.map.events.on({'moveend':this.updateLink,'changelayer':this.updateLink,'changebaselayer':this.updateLink,scope:this});this.updateLink();return this.div;},updateLink:function(){var href=this.base;if(href.indexOf('?')!=-1){href=href.substring(0,href.indexOf('?'));}
href+='?'+OpenLayers.Util.getParameterString(this.createParams());this.element.href=href;},createParams:function(center,zoom,layers){center=center||this.map.getCenter();var params=OpenLayers.Util.getParameters(this.base);if(center){params.zoom=zoom||this.map.getZoom();var lat=center.lat;var lon=center.lon;if(this.displayProjection){var mapPosition=OpenLayers.Projection.transform({x:lon,y:lat},this.map.getProjectionObject(),this.displayProjection);lon=mapPosition.x;lat=mapPosition.y;}
params.lat=Math.round(lat*100000)/100000;params.lon=Math.round(lon*100000)/100000;layers=layers||this.map.layers;params.layers='';for(var i=0,len=layers.length;i<len;i++){var layer=layers[i];if(layer.isBaseLayer){params.layers+=(layer==this.map.baseLayer)?"B":"0";}else{params.layers+=(layer.getVisibility())?"T":"F";}}}
return params;},CLASS_NAME:"OpenLayers.Control.Permalink"});OpenLayers.Control.ZoomPanel=OpenLayers.Class(OpenLayers.Control.Panel,{initialize:function(options){OpenLayers.Control.Panel.prototype.initialize.apply(this,[options]);this.addControls([new OpenLayers.Control.ZoomIn(),new OpenLayers.Control.ZoomToMaxExtent(),new OpenLayers.Control.ZoomOut()]);},CLASS_NAME:"OpenLayers.Control.ZoomPanel"});OpenLayers.Format.CSWGetDomain=function(options){options=OpenLayers.Util.applyDefaults(options,OpenLayers.Format.CSWGetDomain.DEFAULTS);var cls=OpenLayers.Format.CSWGetDomain["v"+options.version.replace(/\./g,"_")];if(!cls){throw"Unsupported CSWGetDomain version: "+options.version;}
return new cls(options);};OpenLayers.Format.CSWGetDomain.DEFAULTS={"version":"2.0.2"};OpenLayers.Format.CSWGetRecords=function(options){options=OpenLayers.Util.applyDefaults(options,OpenLayers.Format.CSWGetRecords.DEFAULTS);var cls=OpenLayers.Format.CSWGetRecords["v"+options.version.replace(/\./g,"_")];if(!cls){throw"Unsupported CSWGetRecords version: "+options.version;}
return new cls(options);};OpenLayers.Format.CSWGetRecords.DEFAULTS={"version":"2.0.2"};OpenLayers.Format.JSON=OpenLayers.Class(OpenLayers.Format,{indent:"    ",space:" ",newline:"\n",level:0,pretty:false,initialize:function(options){OpenLayers.Format.prototype.initialize.apply(this,[options]);},read:function(json,filter){try{if(/^[\],:{}\s]*$/.test(json.replace(/\\["\\\/bfnrtu]/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){var object=eval('('+json+')');if(typeof filter==='function'){function walk(k,v){if(v&&typeof v==='object'){for(var i in v){if(v.hasOwnProperty(i)){v[i]=walk(i,v[i]);}}}
return filter(k,v);}
object=walk('',object);}
if(this.keepData){this.data=object;}
return object;}}catch(e){}
return null;},write:function(value,pretty){this.pretty=!!pretty;var json=null;var type=typeof value;if(this.serialize[type]){try{json=this.serialize[type].apply(this,[value]);}catch(err){OpenLayers.Console.error("Trouble serializing: "+err);}}
return json;},writeIndent:function(){var pieces=[];if(this.pretty){for(var i=0;i<this.level;++i){pieces.push(this.indent);}}
return pieces.join('');},writeNewline:function(){return(this.pretty)?this.newline:'';},writeSpace:function(){return(this.pretty)?this.space:'';},serialize:{'object':function(object){if(object==null){return"null";}
if(object.constructor==Date){return this.serialize.date.apply(this,[object]);}
if(object.constructor==Array){return this.serialize.array.apply(this,[object]);}
var pieces=['{'];this.level+=1;var key,keyJSON,valueJSON;var addComma=false;for(key in object){if(object.hasOwnProperty(key)){keyJSON=OpenLayers.Format.JSON.prototype.write.apply(this,[key,this.pretty]);valueJSON=OpenLayers.Format.JSON.prototype.write.apply(this,[object[key],this.pretty]);if(keyJSON!=null&&valueJSON!=null){if(addComma){pieces.push(',');}
pieces.push(this.writeNewline(),this.writeIndent(),keyJSON,':',this.writeSpace(),valueJSON);addComma=true;}}}
this.level-=1;pieces.push(this.writeNewline(),this.writeIndent(),'}');return pieces.join('');},'array':function(array){var json;var pieces=['['];this.level+=1;for(var i=0,len=array.length;i<len;++i){json=OpenLayers.Format.JSON.prototype.write.apply(this,[array[i],this.pretty]);if(json!=null){if(i>0){pieces.push(',');}
pieces.push(this.writeNewline(),this.writeIndent(),json);}}
this.level-=1;pieces.push(this.writeNewline(),this.writeIndent(),']');return pieces.join('');},'string':function(string){var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};if(/["\\\x00-\x1f]/.test(string)){return'"'+string.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=m[b];if(c){return c;}
c=b.charCodeAt();return'\\u00'+
Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"';}
return'"'+string+'"';},'number':function(number){return isFinite(number)?String(number):"null";},'boolean':function(bool){return String(bool);},'date':function(date){function format(number){return(number<10)?'0'+number:number;}
return'"'+date.getFullYear()+'-'+
format(date.getMonth()+1)+'-'+
format(date.getDate())+'T'+
format(date.getHours())+':'+
format(date.getMinutes())+':'+
format(date.getSeconds())+'"';}},CLASS_NAME:"OpenLayers.Format.JSON"});OpenLayers.Format.WFST=function(options){options=OpenLayers.Util.applyDefaults(options,OpenLayers.Format.WFST.DEFAULTS);var cls=OpenLayers.Format.WFST["v"+options.version.replace(/\./g,"_")];if(!cls){throw"Unsupported WFST version: "+options.version;}
return new cls(options);};OpenLayers.Format.WFST.DEFAULTS={"version":"1.0.0"};OpenLayers.Format.XML=OpenLayers.Class(OpenLayers.Format,{namespaces:null,namespaceAlias:null,defaultPrefix:null,readers:{},writers:{},xmldom:null,initialize:function(options){if(window.ActiveXObject){this.xmldom=new ActiveXObject("Microsoft.XMLDOM");}
OpenLayers.Format.prototype.initialize.apply(this,[options]);this.namespaces=OpenLayers.Util.extend({},this.namespaces);this.namespaceAlias={};for(var alias in this.namespaces){this.namespaceAlias[this.namespaces[alias]]=alias;}},destroy:function(){this.xmldom=null;OpenLayers.Format.prototype.destroy.apply(this,arguments);},setNamespace:function(alias,uri){this.namespaces[alias]=uri;this.namespaceAlias[uri]=alias;},read:function(text){var index=text.indexOf('<');if(index>0){text=text.substring(index);}
var node=OpenLayers.Util.Try(OpenLayers.Function.bind((function(){var xmldom;if(window.ActiveXObject&&!this.xmldom){xmldom=new ActiveXObject("Microsoft.XMLDOM");}else{xmldom=this.xmldom;}
xmldom.loadXML(text);return xmldom;}),this),function(){return new DOMParser().parseFromString(text,'text/xml');},function(){var req=new XMLHttpRequest();req.open("GET","data:"+"text/xml"+";charset=utf-8,"+encodeURIComponent(text),false);if(req.overrideMimeType){req.overrideMimeType("text/xml");}
req.send(null);return req.responseXML;});if(this.keepData){this.data=node;}
return node;},write:function(node){var data;if(this.xmldom){data=node.xml;}else{var serializer=new XMLSerializer();if(node.nodeType==1){var doc=document.implementation.createDocument("","",null);if(doc.importNode){node=doc.importNode(node,true);}
doc.appendChild(node);data=serializer.serializeToString(doc);}else{data=serializer.serializeToString(node);}}
return data;},createElementNS:function(uri,name){var element;if(this.xmldom){if(typeof uri=="string"){element=this.xmldom.createNode(1,name,uri);}else{element=this.xmldom.createNode(1,name,"");}}else{element=document.createElementNS(uri,name);}
return element;},createTextNode:function(text){var node;if(typeof text!=="string"){text=String(text);}
if(this.xmldom){node=this.xmldom.createTextNode(text);}else{node=document.createTextNode(text);}
return node;},getElementsByTagNameNS:function(node,uri,name){var elements=[];if(node.getElementsByTagNameNS){elements=node.getElementsByTagNameNS(uri,name);}else{var allNodes=node.getElementsByTagName("*");var potentialNode,fullName;for(var i=0,len=allNodes.length;i<len;++i){potentialNode=allNodes[i];fullName=(potentialNode.prefix)?(potentialNode.prefix+":"+name):name;if((name=="*")||(fullName==potentialNode.nodeName)){if((uri=="*")||(uri==potentialNode.namespaceURI)){elements.push(potentialNode);}}}}
return elements;},getAttributeNodeNS:function(node,uri,name){var attributeNode=null;if(node.getAttributeNodeNS){attributeNode=node.getAttributeNodeNS(uri,name);}else{var attributes=node.attributes;var potentialNode,fullName;for(var i=0,len=attributes.length;i<len;++i){potentialNode=attributes[i];if(potentialNode.namespaceURI==uri){fullName=(potentialNode.prefix)?(potentialNode.prefix+":"+name):name;if(fullName==potentialNode.nodeName){attributeNode=potentialNode;break;}}}}
return attributeNode;},getAttributeNS:function(node,uri,name){var attributeValue="";if(node.getAttributeNS){attributeValue=node.getAttributeNS(uri,name)||"";}else{var attributeNode=this.getAttributeNodeNS(node,uri,name);if(attributeNode){attributeValue=attributeNode.nodeValue;}}
return attributeValue;},getChildValue:function(node,def){var value=def||"";if(node){for(var child=node.firstChild;child;child=child.nextSibling){switch(child.nodeType){case 3:case 4:value+=child.nodeValue;}}}
return value;},concatChildValues:function(node,def){var value="";var child=node.firstChild;var childValue;while(child){childValue=child.nodeValue;if(childValue){value+=childValue;}
child=child.nextSibling;}
if(value==""&&def!=undefined){value=def;}
return value;},isSimpleContent:function(node){var simple=true;for(var child=node.firstChild;child;child=child.nextSibling){if(child.nodeType===1){simple=false;break;}}
return simple;},contentType:function(node){var simple=false,complex=false;var type=OpenLayers.Format.XML.CONTENT_TYPE.EMPTY;for(var child=node.firstChild;child;child=child.nextSibling){switch(child.nodeType){case 1:complex=true;break;case 8:break;default:simple=true;}
if(complex&&simple){break;}}
if(complex&&simple){type=OpenLayers.Format.XML.CONTENT_TYPE.MIXED;}else if(complex){return OpenLayers.Format.XML.CONTENT_TYPE.COMPLEX;}else if(simple){return OpenLayers.Format.XML.CONTENT_TYPE.SIMPLE;}
return type;},hasAttributeNS:function(node,uri,name){var found=false;if(node.hasAttributeNS){found=node.hasAttributeNS(uri,name);}else{found=!!this.getAttributeNodeNS(node,uri,name);}
return found;},setAttributeNS:function(node,uri,name,value){if(node.setAttributeNS){node.setAttributeNS(uri,name,value);}else{if(this.xmldom){if(uri){var attribute=node.ownerDocument.createNode(2,name,uri);attribute.nodeValue=value;node.setAttributeNode(attribute);}else{node.setAttribute(name,value);}}else{throw"setAttributeNS not implemented";}}},createElementNSPlus:function(name,options){options=options||{};var uri=options.uri||this.namespaces[options.prefix];if(!uri){var loc=name.indexOf(":");uri=this.namespaces[name.substring(0,loc)];}
if(!uri){uri=this.namespaces[this.defaultPrefix];}
var node=this.createElementNS(uri,name);if(options.attributes){this.setAttributes(node,options.attributes);}
var value=options.value;if(value!=null){node.appendChild(this.createTextNode(value));}
return node;},setAttributes:function(node,obj){var value,uri;for(var name in obj){if(obj[name]!=null&&obj[name].toString){value=obj[name].toString();uri=this.namespaces[name.substring(0,name.indexOf(":"))]||null;this.setAttributeNS(node,uri,name,value);}}},readNode:function(node,obj){if(!obj){obj={};}
var group=this.readers[node.namespaceURI?this.namespaceAlias[node.namespaceURI]:this.defaultPrefix];if(group){var local=node.localName||node.nodeName.split(":").pop();var reader=group[local]||group["*"];if(reader){reader.apply(this,[node,obj]);}}
return obj;},readChildNodes:function(node,obj){if(!obj){obj={};}
var children=node.childNodes;var child;for(var i=0,len=children.length;i<len;++i){child=children[i];if(child.nodeType==1){this.readNode(child,obj);}}
return obj;},writeNode:function(name,obj,parent){var prefix,local;var split=name.indexOf(":");if(split>0){prefix=name.substring(0,split);local=name.substring(split+1);}else{if(parent){prefix=this.namespaceAlias[parent.namespaceURI];}else{prefix=this.defaultPrefix;}
local=name;}
var child=this.writers[prefix][local].apply(this,[obj]);if(parent){parent.appendChild(child);}
return child;},getChildEl:function(node,name,uri){return node&&this.getThisOrNextEl(node.firstChild,name,uri);},getNextEl:function(node,name,uri){return node&&this.getThisOrNextEl(node.nextSibling,name,uri);},getThisOrNextEl:function(node,name,uri){outer:for(var sibling=node;sibling;sibling=sibling.nextSibling){switch(sibling.nodeType){case 1:if((!name||name===(sibling.localName||sibling.nodeName.split(":").pop()))&&(!uri||uri===sibling.namespaceURI)){break outer;}
sibling=null;break outer;case 3:if(/^\s*$/.test(sibling.nodeValue)){break;}
case 4:case 6:case 12:case 10:case 11:sibling=null;break outer;}}
return sibling||null;},lookupNamespaceURI:function(node,prefix){var uri=null;if(node){if(node.lookupNamespaceURI){uri=node.lookupNamespaceURI(prefix);}else{outer:switch(node.nodeType){case 1:if(node.namespaceURI!==null&&node.prefix===prefix){uri=node.namespaceURI;break outer;}
var len=node.attributes.length;if(len){var attr;for(var i=0;i<len;++i){attr=node.attributes[i];if(attr.prefix==="xmlns"&&attr.name==="xmlns:"+prefix){uri=attr.value||null;break outer;}else if(attr.name==="xmlns"&&prefix===null){uri=attr.value||null;break outer;}}}
uri=this.lookupNamespaceURI(node.parentNode,prefix);break outer;case 2:uri=this.lookupNamespaceURI(node.ownerElement,prefix);break outer;case 9:uri=this.lookupNamespaceURI(node.documentElement,prefix);break outer;case 6:case 12:case 10:case 11:break outer;default:uri=this.lookupNamespaceURI(node.parentNode,prefix);break outer;}}}
return uri;},CLASS_NAME:"OpenLayers.Format.XML"});OpenLayers.Format.XML.CONTENT_TYPE={EMPTY:0,SIMPLE:1,COMPLEX:2,MIXED:3};OpenLayers.Format.XML.lookupNamespaceURI=OpenLayers.Function.bind(OpenLayers.Format.XML.prototype.lookupNamespaceURI,OpenLayers.Format.XML.prototype);OpenLayers.Handler=OpenLayers.Class({id:null,control:null,map:null,keyMask:null,active:false,evt:null,initialize:function(control,callbacks,options){OpenLayers.Util.extend(this,options);this.control=control;this.callbacks=callbacks;var map=this.map||control.map;if(map){this.setMap(map);}
this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");},setMap:function(map){this.map=map;},checkModifiers:function(evt){if(this.keyMask==null){return true;}
var keyModifiers=(evt.shiftKey?OpenLayers.Handler.MOD_SHIFT:0)|(evt.ctrlKey?OpenLayers.Handler.MOD_CTRL:0)|(evt.altKey?OpenLayers.Handler.MOD_ALT:0);return(keyModifiers==this.keyMask);},activate:function(){if(this.active){return false;}
var events=OpenLayers.Events.prototype.BROWSER_EVENTS;for(var i=0,len=events.length;i<len;i++){if(this[events[i]]){this.register(events[i],this[events[i]]);}}
this.active=true;return true;},deactivate:function(){if(!this.active){return false;}
var events=OpenLayers.Events.prototype.BROWSER_EVENTS;for(var i=0,len=events.length;i<len;i++){if(this[events[i]]){this.unregister(events[i],this[events[i]]);}}
this.active=false;return true;},callback:function(name,args){if(name&&this.callbacks[name]){this.callbacks[name].apply(this.control,args);}},register:function(name,method){this.map.events.registerPriority(name,this,method);this.map.events.registerPriority(name,this,this.setEvent);},unregister:function(name,method){this.map.events.unregister(name,this,method);this.map.events.unregister(name,this,this.setEvent);},setEvent:function(evt){this.evt=evt;return true;},destroy:function(){this.deactivate();this.control=this.map=null;},CLASS_NAME:"OpenLayers.Handler"});OpenLayers.Handler.MOD_NONE=0;OpenLayers.Handler.MOD_SHIFT=1;OpenLayers.Handler.MOD_CTRL=2;OpenLayers.Handler.MOD_ALT=4;OpenLayers.Map=OpenLayers.Class({Z_INDEX_BASE:{BaseLayer:100,Overlay:325,Feature:725,Popup:750,Control:1000},EVENT_TYPES:["preaddlayer","addlayer","removelayer","changelayer","movestart","move","moveend","zoomend","popupopen","popupclose","addmarker","removemarker","clearmarkers","mouseover","mouseout","mousemove","dragstart","drag","dragend","changebaselayer"],id:null,fractionalZoom:false,events:null,allOverlays:false,div:null,dragging:false,size:null,viewPortDiv:null,layerContainerOrigin:null,layerContainerDiv:null,layers:null,controls:null,popups:null,baseLayer:null,center:null,resolution:null,zoom:0,panRatio:1.5,viewRequestID:0,tileSize:null,projection:"EPSG:4326",units:'degrees',resolutions:null,maxResolution:1.40625,minResolution:null,maxScale:null,minScale:null,maxExtent:null,minExtent:null,restrictedExtent:null,numZoomLevels:16,theme:null,displayProjection:null,fallThrough:true,panTween:null,eventListeners:null,panMethod:OpenLayers.Easing.Expo.easeOut,panDuration:50,paddingForPopups:null,initialize:function(div,options){if(arguments.length===1&&typeof div==="object"){options=div;div=options&&options.div;}
this.tileSize=new OpenLayers.Size(OpenLayers.Map.TILE_WIDTH,OpenLayers.Map.TILE_HEIGHT);this.maxExtent=new OpenLayers.Bounds(-180,-90,180,90);this.paddingForPopups=new OpenLayers.Bounds(15,15,15,15);this.theme=OpenLayers._getScriptLocation()?OpenLayers._getScriptLocation()+'theme/default/style.css':null;OpenLayers.Util.extend(this,options);this.layers=[];this.id=OpenLayers.Util.createUniqueID("OpenLayers.Map_");this.div=OpenLayers.Util.getElement(div);if(!this.div){this.div=document.createElement("div");this.div.style.height="1px";this.div.style.width="1px";}
OpenLayers.Element.addClass(this.div,'olMap');var id=this.id+"_OpenLayers_ViewPort";this.viewPortDiv=OpenLayers.Util.createDiv(id,null,null,null,"relative",null,"hidden");this.viewPortDiv.style.width="100%";this.viewPortDiv.style.height="100%";this.viewPortDiv.className="olMapViewport";this.div.appendChild(this.viewPortDiv);id=this.id+"_OpenLayers_Container";this.layerContainerDiv=OpenLayers.Util.createDiv(id);this.layerContainerDiv.style.zIndex=this.Z_INDEX_BASE['Popup']-1;this.viewPortDiv.appendChild(this.layerContainerDiv);this.events=new OpenLayers.Events(this,this.div,this.EVENT_TYPES,this.fallThrough,{includeXY:true});this.updateSize();if(this.eventListeners instanceof Object){this.events.on(this.eventListeners);}
this.events.register("movestart",this,this.updateSize);if(OpenLayers.String.contains(navigator.appName,"Microsoft")){this.events.register("resize",this,this.updateSize);}else{this.updateSizeDestroy=OpenLayers.Function.bind(this.updateSize,this);OpenLayers.Event.observe(window,'resize',this.updateSizeDestroy);}
if(this.theme){var addNode=true;var nodes=document.getElementsByTagName('link');for(var i=0,len=nodes.length;i<len;++i){if(OpenLayers.Util.isEquivalentUrl(nodes.item(i).href,this.theme)){addNode=false;break;}}
if(addNode){var cssNode=document.createElement('link');cssNode.setAttribute('rel','stylesheet');cssNode.setAttribute('type','text/css');cssNode.setAttribute('href',this.theme);document.getElementsByTagName('head')[0].appendChild(cssNode);}}
if(this.controls==null){if(OpenLayers.Control!=null){this.controls=[new OpenLayers.Control.Navigation(),new OpenLayers.Control.PanZoom(),new OpenLayers.Control.ArgParser(),new OpenLayers.Control.Attribution()];}else{this.controls=[];}}
for(var i=0,len=this.controls.length;i<len;i++){this.addControlToMap(this.controls[i]);}
this.popups=[];this.unloadDestroy=OpenLayers.Function.bind(this.destroy,this);OpenLayers.Event.observe(window,'unload',this.unloadDestroy);if(options&&options.layers){this.addLayers(options.layers);if(options.center){this.setCenter(options.center,options.zoom);}}},render:function(div){this.div=OpenLayers.Util.getElement(div);OpenLayers.Element.addClass(this.div,'olMap');this.events.attachToElement(this.div);this.viewPortDiv.parentNode.removeChild(this.viewPortDiv);this.div.appendChild(this.viewPortDiv);this.updateSize();},unloadDestroy:null,updateSizeDestroy:null,destroy:function(){if(!this.unloadDestroy){return false;}
if(this.panTween){this.panTween.stop();this.panTween=null;}
OpenLayers.Event.stopObserving(window,'unload',this.unloadDestroy);this.unloadDestroy=null;if(this.updateSizeDestroy){OpenLayers.Event.stopObserving(window,'resize',this.updateSizeDestroy);}else{this.events.unregister("resize",this,this.updateSize);}
this.paddingForPopups=null;if(this.controls!=null){for(var i=this.controls.length-1;i>=0;--i){this.controls[i].destroy();}
this.controls=null;}
if(this.layers!=null){for(var i=this.layers.length-1;i>=0;--i){this.layers[i].destroy(false);}
this.layers=null;}
if(this.viewPortDiv){this.div.removeChild(this.viewPortDiv);}
this.viewPortDiv=null;if(this.eventListeners){this.events.un(this.eventListeners);this.eventListeners=null;}
this.events.destroy();this.events=null;},setOptions:function(options){OpenLayers.Util.extend(this,options);},getTileSize:function(){return this.tileSize;},getBy:function(array,property,match){var test=(typeof match.test=="function");var found=OpenLayers.Array.filter(this[array],function(item){return item[property]==match||(test&&match.test(item[property]));});return found;},getLayersBy:function(property,match){return this.getBy("layers",property,match);},getLayersByName:function(match){return this.getLayersBy("name",match);},getLayersByClass:function(match){return this.getLayersBy("CLASS_NAME",match);},getControlsBy:function(property,match){return this.getBy("controls",property,match);},getControlsByClass:function(match){return this.getControlsBy("CLASS_NAME",match);},getLayer:function(id){var foundLayer=null;for(var i=0,len=this.layers.length;i<len;i++){var layer=this.layers[i];if(layer.id==id){foundLayer=layer;break;}}
return foundLayer;},setLayerZIndex:function(layer,zIdx){layer.setZIndex(this.Z_INDEX_BASE[layer.isBaseLayer?'BaseLayer':'Overlay']
+zIdx*5);},resetLayersZIndex:function(){for(var i=0,len=this.layers.length;i<len;i++){var layer=this.layers[i];this.setLayerZIndex(layer,i);}},addLayer:function(layer){for(var i=0,len=this.layers.length;i<len;i++){if(this.layers[i]==layer){var msg=OpenLayers.i18n('layerAlreadyAdded',{'layerName':layer.name});OpenLayers.Console.warn(msg);return false;}}
if(this.allOverlays){layer.isBaseLayer=false;}
if(this.events.triggerEvent("preaddlayer",{layer:layer})===false){return;}
layer.div.className="olLayerDiv";layer.div.style.overflow="";this.setLayerZIndex(layer,this.layers.length);if(layer.isFixed){this.viewPortDiv.appendChild(layer.div);}else{this.layerContainerDiv.appendChild(layer.div);}
this.layers.push(layer);layer.setMap(this);if(layer.isBaseLayer||(this.allOverlays&&!this.baseLayer)){if(this.baseLayer==null){this.setBaseLayer(layer);}else{layer.setVisibility(false);}}else{layer.redraw();}
this.events.triggerEvent("addlayer",{layer:layer});layer.afterAdd();},addLayers:function(layers){for(var i=0,len=layers.length;i<len;i++){this.addLayer(layers[i]);}},removeLayer:function(layer,setNewBaseLayer){if(setNewBaseLayer==null){setNewBaseLayer=true;}
if(layer.isFixed){this.viewPortDiv.removeChild(layer.div);}else{this.layerContainerDiv.removeChild(layer.div);}
OpenLayers.Util.removeItem(this.layers,layer);layer.removeMap(this);layer.map=null;if(this.baseLayer==layer){this.baseLayer=null;if(setNewBaseLayer){for(var i=0,len=this.layers.length;i<len;i++){var iLayer=this.layers[i];if(iLayer.isBaseLayer||this.allOverlays){this.setBaseLayer(iLayer);break;}}}}
this.resetLayersZIndex();this.events.triggerEvent("removelayer",{layer:layer});},getNumLayers:function(){return this.layers.length;},getLayerIndex:function(layer){return OpenLayers.Util.indexOf(this.layers,layer);},setLayerIndex:function(layer,idx){var base=this.getLayerIndex(layer);if(idx<0){idx=0;}else if(idx>this.layers.length){idx=this.layers.length;}
if(base!=idx){this.layers.splice(base,1);this.layers.splice(idx,0,layer);for(var i=0,len=this.layers.length;i<len;i++){this.setLayerZIndex(this.layers[i],i);}
this.events.triggerEvent("changelayer",{layer:layer,property:"order"});if(this.allOverlays){if(idx===0){this.setBaseLayer(layer);}else if(this.baseLayer!==this.layers[0]){this.setBaseLayer(this.layers[0]);}}}},raiseLayer:function(layer,delta){var idx=this.getLayerIndex(layer)+delta;this.setLayerIndex(layer,idx);},setBaseLayer:function(newBaseLayer){if(newBaseLayer!=this.baseLayer){if(OpenLayers.Util.indexOf(this.layers,newBaseLayer)!=-1){var center=this.getCenter();var newResolution=OpenLayers.Util.getResolutionFromScale(this.getScale(),newBaseLayer.units);if(this.baseLayer!=null&&!this.allOverlays){this.baseLayer.setVisibility(false);}
this.baseLayer=newBaseLayer;this.viewRequestID++;if(!this.allOverlays||this.baseLayer.visibility){this.baseLayer.setVisibility(true);}
if(center!=null){var newZoom=this.getZoomForResolution(newResolution||this.resolution,true);this.setCenter(center,newZoom,false,true);}
this.events.triggerEvent("changebaselayer",{layer:this.baseLayer});}}},addControl:function(control,px){this.controls.push(control);this.addControlToMap(control,px);},addControls:function(controls,pixels){var pxs=(arguments.length===1)?[]:pixels;for(var i=0,len=controls.length;i<len;i++){var ctrl=controls[i];var px=(pxs[i])?pxs[i]:null;this.addControl(ctrl,px);}},addControlToMap:function(control,px){control.outsideViewport=(control.div!=null);if(this.displayProjection&&!control.displayProjection){control.displayProjection=this.displayProjection;}
control.setMap(this);var div=control.draw(px);if(div){if(!control.outsideViewport){div.style.zIndex=this.Z_INDEX_BASE['Control']+
this.controls.length;this.viewPortDiv.appendChild(div);}}
if(control.autoActivate){control.activate();}},getControl:function(id){var returnControl=null;for(var i=0,len=this.controls.length;i<len;i++){var control=this.controls[i];if(control.id==id){returnControl=control;break;}}
return returnControl;},removeControl:function(control){if((control)&&(control==this.getControl(control.id))){if(control.div&&(control.div.parentNode==this.viewPortDiv)){this.viewPortDiv.removeChild(control.div);}
OpenLayers.Util.removeItem(this.controls,control);}},addPopup:function(popup,exclusive){if(exclusive){for(var i=this.popups.length-1;i>=0;--i){this.removePopup(this.popups[i]);}}
popup.map=this;this.popups.push(popup);var popupDiv=popup.draw();if(popupDiv){popupDiv.style.zIndex=this.Z_INDEX_BASE['Popup']+
this.popups.length;this.layerContainerDiv.appendChild(popupDiv);}},removePopup:function(popup){OpenLayers.Util.removeItem(this.popups,popup);if(popup.div){try{this.layerContainerDiv.removeChild(popup.div);}
catch(e){}}
popup.map=null;},getSize:function(){var size=null;if(this.size!=null){size=this.size.clone();}
return size;},updateSize:function(){var newSize=this.getCurrentSize();if(newSize&&!isNaN(newSize.h)&&!isNaN(newSize.w)){this.events.clearMouseCache();var oldSize=this.getSize();if(oldSize==null){this.size=oldSize=newSize;}
if(!newSize.equals(oldSize)){this.size=newSize;for(var i=0,len=this.layers.length;i<len;i++){this.layers[i].onMapResize();}
var center=this.getCenter();if(this.baseLayer!=null&&center!=null){var zoom=this.getZoom();this.zoom=null;this.setCenter(center,zoom);}}}},getCurrentSize:function(){var size=new OpenLayers.Size(this.div.clientWidth,this.div.clientHeight);if(size.w==0&&size.h==0||isNaN(size.w)&&isNaN(size.h)){size.w=this.div.offsetWidth;size.h=this.div.offsetHeight;}
if(size.w==0&&size.h==0||isNaN(size.w)&&isNaN(size.h)){size.w=parseInt(this.div.style.width);size.h=parseInt(this.div.style.height);}
return size;},calculateBounds:function(center,resolution){var extent=null;if(center==null){center=this.getCenter();}
if(resolution==null){resolution=this.getResolution();}
if((center!=null)&&(resolution!=null)){var size=this.getSize();var w_deg=size.w*resolution;var h_deg=size.h*resolution;extent=new OpenLayers.Bounds(center.lon-w_deg/2,center.lat-h_deg/2,center.lon+w_deg/2,center.lat+h_deg/2);}
return extent;},getCenter:function(){var center=null;if(this.center){center=this.center.clone();}
return center;},getZoom:function(){return this.zoom;},pan:function(dx,dy,options){options=OpenLayers.Util.applyDefaults(options,{animate:true,dragging:false});var centerPx=this.getViewPortPxFromLonLat(this.getCenter());var newCenterPx=centerPx.add(dx,dy);if(!options.dragging||!newCenterPx.equals(centerPx)){var newCenterLonLat=this.getLonLatFromViewPortPx(newCenterPx);if(options.animate){this.panTo(newCenterLonLat);}else{this.setCenter(newCenterLonLat,null,options.dragging);}}},panTo:function(lonlat){if(this.panMethod&&this.getExtent().scale(this.panRatio).containsLonLat(lonlat)){if(!this.panTween){this.panTween=new OpenLayers.Tween(this.panMethod);}
var center=this.getCenter();if(lonlat.lon==center.lon&&lonlat.lat==center.lat){return;}
var from={lon:center.lon,lat:center.lat};var to={lon:lonlat.lon,lat:lonlat.lat};this.panTween.start(from,to,this.panDuration,{callbacks:{start:OpenLayers.Function.bind(function(lonlat){this.events.triggerEvent("movestart");},this),eachStep:OpenLayers.Function.bind(function(lonlat){lonlat=new OpenLayers.LonLat(lonlat.lon,lonlat.lat);this.moveTo(lonlat,this.zoom,{'dragging':true,'noEvent':true});},this),done:OpenLayers.Function.bind(function(lonlat){lonlat=new OpenLayers.LonLat(lonlat.lon,lonlat.lat);this.moveTo(lonlat,this.zoom,{'noEvent':true});this.events.triggerEvent("moveend");},this)}});}else{this.setCenter(lonlat);}},setCenter:function(lonlat,zoom,dragging,forceZoomChange){this.moveTo(lonlat,zoom,{'dragging':dragging,'forceZoomChange':forceZoomChange,'caller':'setCenter'});},moveTo:function(lonlat,zoom,options){if(!options){options={};}
if(zoom!=null){zoom=parseFloat(zoom);if(!this.fractionalZoom){zoom=Math.round(zoom);}}
var dragging=options.dragging;var forceZoomChange=options.forceZoomChange;var noEvent=options.noEvent;if(this.panTween&&options.caller=="setCenter"){this.panTween.stop();}
if(!this.center&&!this.isValidLonLat(lonlat)){lonlat=this.maxExtent.getCenterLonLat();}
if(this.restrictedExtent!=null){if(lonlat==null){lonlat=this.getCenter();}
if(zoom==null){zoom=this.getZoom();}
var resolution=this.getResolutionForZoom(zoom);var extent=this.calculateBounds(lonlat,resolution);if(!this.restrictedExtent.containsBounds(extent)){var maxCenter=this.restrictedExtent.getCenterLonLat();if(extent.getWidth()>this.restrictedExtent.getWidth()){lonlat=new OpenLayers.LonLat(maxCenter.lon,lonlat.lat);}else if(extent.left<this.restrictedExtent.left){lonlat=lonlat.add(this.restrictedExtent.left-
extent.left,0);}else if(extent.right>this.restrictedExtent.right){lonlat=lonlat.add(this.restrictedExtent.right-
extent.right,0);}
if(extent.getHeight()>this.restrictedExtent.getHeight()){lonlat=new OpenLayers.LonLat(lonlat.lon,maxCenter.lat);}else if(extent.bottom<this.restrictedExtent.bottom){lonlat=lonlat.add(0,this.restrictedExtent.bottom-
extent.bottom);}
else if(extent.top>this.restrictedExtent.top){lonlat=lonlat.add(0,this.restrictedExtent.top-
extent.top);}}}
var zoomChanged=forceZoomChange||((this.isValidZoomLevel(zoom))&&(zoom!=this.getZoom()));var centerChanged=(this.isValidLonLat(lonlat))&&(!lonlat.equals(this.center));if(zoomChanged||centerChanged||!dragging){if(!this.dragging&&!noEvent){this.events.triggerEvent("movestart");}
if(centerChanged){if((!zoomChanged)&&(this.center)){this.centerLayerContainer(lonlat);}
this.center=lonlat.clone();}
if((zoomChanged)||(this.layerContainerOrigin==null)){this.layerContainerOrigin=this.center.clone();this.layerContainerDiv.style.left="0px";this.layerContainerDiv.style.top="0px";}
if(zoomChanged){this.zoom=zoom;this.resolution=this.getResolutionForZoom(zoom);this.viewRequestID++;}
var bounds=this.getExtent();if(this.baseLayer.visibility){this.baseLayer.moveTo(bounds,zoomChanged,dragging);if(dragging){this.baseLayer.events.triggerEvent("move");}else{this.baseLayer.events.triggerEvent("moveend",{"zoomChanged":zoomChanged});}}
bounds=this.baseLayer.getExtent();for(var i=0,len=this.layers.length;i<len;i++){var layer=this.layers[i];if(layer!==this.baseLayer&&!layer.isBaseLayer){var inRange=layer.calculateInRange();if(layer.inRange!=inRange){layer.inRange=inRange;if(!inRange){layer.display(false);}
this.events.triggerEvent("changelayer",{layer:layer,property:"visibility"});}
if(inRange&&layer.visibility){layer.moveTo(bounds,zoomChanged,dragging);if(dragging){layer.events.triggerEvent("move");}else{layer.events.triggerEvent("moveend",{"zoomChanged":zoomChanged});}}}}
if(zoomChanged){for(var i=0,len=this.popups.length;i<len;i++){this.popups[i].updatePosition();}}
this.events.triggerEvent("move");if(zoomChanged){this.events.triggerEvent("zoomend");}}
if(!dragging&&!noEvent){this.events.triggerEvent("moveend");}
this.dragging=!!dragging;},centerLayerContainer:function(lonlat){var originPx=this.getViewPortPxFromLonLat(this.layerContainerOrigin);var newPx=this.getViewPortPxFromLonLat(lonlat);if((originPx!=null)&&(newPx!=null)){this.layerContainerDiv.style.left=Math.round(originPx.x-newPx.x)+"px";this.layerContainerDiv.style.top=Math.round(originPx.y-newPx.y)+"px";}},isValidZoomLevel:function(zoomLevel){return((zoomLevel!=null)&&(zoomLevel>=0)&&(zoomLevel<this.getNumZoomLevels()));},isValidLonLat:function(lonlat){var valid=false;if(lonlat!=null){var maxExtent=this.getMaxExtent();valid=maxExtent.containsLonLat(lonlat);}
return valid;},getProjection:function(){var projection=this.getProjectionObject();return projection?projection.getCode():null;},getProjectionObject:function(){var projection=null;if(this.baseLayer!=null){projection=this.baseLayer.projection;}
return projection;},getMaxResolution:function(){var maxResolution=null;if(this.baseLayer!=null){maxResolution=this.baseLayer.maxResolution;}
return maxResolution;},getMaxExtent:function(options){var maxExtent=null;if(options&&options.restricted&&this.restrictedExtent){maxExtent=this.restrictedExtent;}else if(this.baseLayer!=null){maxExtent=this.baseLayer.maxExtent;}
return maxExtent;},getNumZoomLevels:function(){var numZoomLevels=null;if(this.baseLayer!=null){numZoomLevels=this.baseLayer.numZoomLevels;}
return numZoomLevels;},getExtent:function(){var extent=null;if(this.baseLayer!=null){extent=this.baseLayer.getExtent();}
return extent;},getResolution:function(){var resolution=null;if(this.baseLayer!=null){resolution=this.baseLayer.getResolution();}else if(this.allOverlays===true&&this.layers.length>0){resolution=this.layers[0].getResolution();}
return resolution;},getUnits:function(){var units=null;if(this.baseLayer!=null){units=this.baseLayer.units;}
return units;},getScale:function(){var scale=null;if(this.baseLayer!=null){var res=this.getResolution();var units=this.baseLayer.units;scale=OpenLayers.Util.getScaleFromResolution(res,units);}
return scale;},getZoomForExtent:function(bounds,closest){var zoom=null;if(this.baseLayer!=null){zoom=this.baseLayer.getZoomForExtent(bounds,closest);}
return zoom;},getResolutionForZoom:function(zoom){var resolution=null;if(this.baseLayer){resolution=this.baseLayer.getResolutionForZoom(zoom);}
return resolution;},getZoomForResolution:function(resolution,closest){var zoom=null;if(this.baseLayer!=null){zoom=this.baseLayer.getZoomForResolution(resolution,closest);}
return zoom;},zoomTo:function(zoom){if(this.isValidZoomLevel(zoom)){this.setCenter(null,zoom);}},zoomIn:function(){this.zoomTo(this.getZoom()+1);},zoomOut:function(){this.zoomTo(this.getZoom()-1);},zoomToExtent:function(bounds,closest){var center=bounds.getCenterLonLat();if(this.baseLayer.wrapDateLine){var maxExtent=this.getMaxExtent();bounds=bounds.clone();while(bounds.right<bounds.left){bounds.right+=maxExtent.getWidth();}
center=bounds.getCenterLonLat().wrapDateLine(maxExtent);}
this.setCenter(center,this.getZoomForExtent(bounds,closest));},zoomToMaxExtent:function(options){var restricted=(options)?options.restricted:true;var maxExtent=this.getMaxExtent({'restricted':restricted});this.zoomToExtent(maxExtent);},zoomToScale:function(scale,closest){var res=OpenLayers.Util.getResolutionFromScale(scale,this.baseLayer.units);var size=this.getSize();var w_deg=size.w*res;var h_deg=size.h*res;var center=this.getCenter();var extent=new OpenLayers.Bounds(center.lon-w_deg/2,center.lat-h_deg/2,center.lon+w_deg/2,center.lat+h_deg/2);this.zoomToExtent(extent,closest);},getLonLatFromViewPortPx:function(viewPortPx){var lonlat=null;if(this.baseLayer!=null){lonlat=this.baseLayer.getLonLatFromViewPortPx(viewPortPx);}
return lonlat;},getViewPortPxFromLonLat:function(lonlat){var px=null;if(this.baseLayer!=null){px=this.baseLayer.getViewPortPxFromLonLat(lonlat);}
return px;},getLonLatFromPixel:function(px){return this.getLonLatFromViewPortPx(px);},getPixelFromLonLat:function(lonlat){var px=this.getViewPortPxFromLonLat(lonlat);px.x=Math.round(px.x);px.y=Math.round(px.y);return px;},getGeodesicPixelSize:function(px){var lonlat=px?this.getLonLatFromPixel(px):(this.getCenter()||new OpenLayers.LonLat(0,0));var res=this.getResolution();var left=lonlat.add(-res/2,0);var right=lonlat.add(res/2,0);var bottom=lonlat.add(0,-res/2);var top=lonlat.add(0,res/2);var dest=new OpenLayers.Projection("EPSG:4326");var source=this.getProjectionObject()||dest;if(!source.equals(dest)){left.transform(source,dest);right.transform(source,dest);bottom.transform(source,dest);top.transform(source,dest);}
return new OpenLayers.Size(OpenLayers.Util.distVincenty(left,right),OpenLayers.Util.distVincenty(bottom,top));},getViewPortPxFromLayerPx:function(layerPx){var viewPortPx=null;if(layerPx!=null){var dX=parseInt(this.layerContainerDiv.style.left);var dY=parseInt(this.layerContainerDiv.style.top);viewPortPx=layerPx.add(dX,dY);}
return viewPortPx;},getLayerPxFromViewPortPx:function(viewPortPx){var layerPx=null;if(viewPortPx!=null){var dX=-parseInt(this.layerContainerDiv.style.left);var dY=-parseInt(this.layerContainerDiv.style.top);layerPx=viewPortPx.add(dX,dY);if(isNaN(layerPx.x)||isNaN(layerPx.y)){layerPx=null;}}
return layerPx;},getLonLatFromLayerPx:function(px){px=this.getViewPortPxFromLayerPx(px);return this.getLonLatFromViewPortPx(px);},getLayerPxFromLonLat:function(lonlat){var px=this.getPixelFromLonLat(lonlat);return this.getLayerPxFromViewPortPx(px);},CLASS_NAME:"OpenLayers.Map"});OpenLayers.Map.TILE_WIDTH=256;OpenLayers.Map.TILE_HEIGHT=256;OpenLayers.Marker=OpenLayers.Class({icon:null,lonlat:null,events:null,map:null,initialize:function(lonlat,icon){this.lonlat=lonlat;var newIcon=(icon)?icon:OpenLayers.Marker.defaultIcon();if(this.icon==null){this.icon=newIcon;}else{this.icon.url=newIcon.url;this.icon.size=newIcon.size;this.icon.offset=newIcon.offset;this.icon.calculateOffset=newIcon.calculateOffset;}
this.events=new OpenLayers.Events(this,this.icon.imageDiv,null);},destroy:function(){this.erase();this.map=null;this.events.destroy();this.events=null;if(this.icon!=null){this.icon.destroy();this.icon=null;}},draw:function(px){return this.icon.draw(px);},erase:function(){if(this.icon!=null){this.icon.erase();}},moveTo:function(px){if((px!=null)&&(this.icon!=null)){this.icon.moveTo(px);}
this.lonlat=this.map.getLonLatFromLayerPx(px);},isDrawn:function(){var isDrawn=(this.icon&&this.icon.isDrawn());return isDrawn;},onScreen:function(){var onScreen=false;if(this.map){var screenBounds=this.map.getExtent();onScreen=screenBounds.containsLonLat(this.lonlat);}
return onScreen;},inflate:function(inflate){if(this.icon){var newSize=new OpenLayers.Size(this.icon.size.w*inflate,this.icon.size.h*inflate);this.icon.setSize(newSize);}},setOpacity:function(opacity){this.icon.setOpacity(opacity);},setUrl:function(url){this.icon.setUrl(url);},display:function(display){this.icon.display(display);},CLASS_NAME:"OpenLayers.Marker"});OpenLayers.Marker.defaultIcon=function(){var url=OpenLayers.Util.getImagesLocation()+"marker.png";var size=new OpenLayers.Size(21,25);var calculateOffset=function(size){return new OpenLayers.Pixel(-(size.w/2),-size.h);};return new OpenLayers.Icon(url,size,null,calculateOffset);};OpenLayers.Popup.FramedCloud=OpenLayers.Class(OpenLayers.Popup.Framed,{contentDisplayClass:"olFramedCloudPopupContent",autoSize:true,panMapIfOutOfView:true,imageSize:new OpenLayers.Size(1276,736),isAlphaImage:false,fixedRelativePosition:false,positionBlocks:{"tl":{'offset':new OpenLayers.Pixel(44,0),'padding':new OpenLayers.Bounds(8,40,8,9),'blocks':[{size:new OpenLayers.Size('auto','auto'),anchor:new OpenLayers.Bounds(0,51,22,0),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,'auto'),anchor:new OpenLayers.Bounds(null,50,0,0),position:new OpenLayers.Pixel(-1238,0)},{size:new OpenLayers.Size('auto',19),anchor:new OpenLayers.Bounds(0,32,22,null),position:new OpenLayers.Pixel(0,-631)},{size:new OpenLayers.Size(22,18),anchor:new OpenLayers.Bounds(null,32,0,null),position:new OpenLayers.Pixel(-1238,-632)},{size:new OpenLayers.Size(81,35),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(0,-688)}]},"tr":{'offset':new OpenLayers.Pixel(-45,0),'padding':new OpenLayers.Bounds(8,40,8,9),'blocks':[{size:new OpenLayers.Size('auto','auto'),anchor:new OpenLayers.Bounds(0,51,22,0),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,'auto'),anchor:new OpenLayers.Bounds(null,50,0,0),position:new OpenLayers.Pixel(-1238,0)},{size:new OpenLayers.Size('auto',19),anchor:new OpenLayers.Bounds(0,32,22,null),position:new OpenLayers.Pixel(0,-631)},{size:new OpenLayers.Size(22,19),anchor:new OpenLayers.Bounds(null,32,0,null),position:new OpenLayers.Pixel(-1238,-631)},{size:new OpenLayers.Size(81,35),anchor:new OpenLayers.Bounds(0,0,null,null),position:new OpenLayers.Pixel(-215,-687)}]},"bl":{'offset':new OpenLayers.Pixel(45,0),'padding':new OpenLayers.Bounds(8,9,8,40),'blocks':[{size:new OpenLayers.Size('auto','auto'),anchor:new OpenLayers.Bounds(0,21,22,32),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,'auto'),anchor:new OpenLayers.Bounds(null,21,0,32),position:new OpenLayers.Pixel(-1238,0)},{size:new OpenLayers.Size('auto',21),anchor:new OpenLayers.Bounds(0,0,22,null),position:new OpenLayers.Pixel(0,-629)},{size:new OpenLayers.Size(22,21),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(-1238,-629)},{size:new OpenLayers.Size(81,33),anchor:new OpenLayers.Bounds(null,null,0,0),position:new OpenLayers.Pixel(-101,-674)}]},"br":{'offset':new OpenLayers.Pixel(-44,0),'padding':new OpenLayers.Bounds(8,9,8,40),'blocks':[{size:new OpenLayers.Size('auto','auto'),anchor:new OpenLayers.Bounds(0,21,22,32),position:new OpenLayers.Pixel(0,0)},{size:new OpenLayers.Size(22,'auto'),anchor:new OpenLayers.Bounds(null,21,0,32),position:new OpenLayers.Pixel(-1238,0)},{size:new OpenLayers.Size('auto',21),anchor:new OpenLayers.Bounds(0,0,22,null),position:new OpenLayers.Pixel(0,-629)},{size:new OpenLayers.Size(22,21),anchor:new OpenLayers.Bounds(null,0,0,null),position:new OpenLayers.Pixel(-1238,-629)},{size:new OpenLayers.Size(81,33),anchor:new OpenLayers.Bounds(0,null,null,0),position:new OpenLayers.Pixel(-311,-674)}]}},minSize:new OpenLayers.Size(105,10),maxSize:new OpenLayers.Size(1200,660),initialize:function(id,lonlat,contentSize,contentHTML,anchor,closeBox,closeBoxCallback){this.imageSrc=OpenLayers.Util.getImagesLocation()+'cloud-popup-relative.png';OpenLayers.Popup.Framed.prototype.initialize.apply(this,arguments);this.contentDiv.className=this.contentDisplayClass;},destroy:function(){OpenLayers.Popup.Framed.prototype.destroy.apply(this,arguments);},CLASS_NAME:"OpenLayers.Popup.FramedCloud"});OpenLayers.Request={DEFAULT_CONFIG:{method:"GET",url:window.location.href,async:true,user:undefined,password:undefined,params:null,proxy:OpenLayers.ProxyHost,headers:{},data:null,callback:function(){},success:null,failure:null,scope:null},events:new OpenLayers.Events(this,null,["complete","success","failure"]),issue:function(config){var defaultConfig=OpenLayers.Util.extend(this.DEFAULT_CONFIG,{proxy:OpenLayers.ProxyHost});config=OpenLayers.Util.applyDefaults(config,defaultConfig);var request=new OpenLayers.Request.XMLHttpRequest();var url=config.url;if(config.params){var paramString=OpenLayers.Util.getParameterString(config.params);if(paramString.length>0){var separator=(url.indexOf('?')>-1)?'&':'?';url+=separator+paramString;}}
if(config.proxy&&(url.indexOf("http")==0)){if(typeof config.proxy=="function"){url=config.proxy(url);}else{url=config.proxy+encodeURIComponent(url);}}
request.open(config.method,url,config.async,config.user,config.password);for(var header in config.headers){request.setRequestHeader(header,config.headers[header]);}
var events=this.events;var self=this;request.onreadystatechange=function(){if(request.readyState==OpenLayers.Request.XMLHttpRequest.DONE){var proceed=events.triggerEvent("complete",{request:request,config:config,requestUrl:url});if(proceed!==false){self.runCallbacks({request:request,config:config,requestUrl:url});}}};if(config.async===false){request.send(config.data);}else{window.setTimeout(function(){if(request._aborted!==true){request.send(config.data);}},0);}
return request;},runCallbacks:function(options){var request=options.request;var config=options.config;var complete=(config.scope)?OpenLayers.Function.bind(config.callback,config.scope):config.callback;var success;if(config.success){success=(config.scope)?OpenLayers.Function.bind(config.success,config.scope):config.success;}
var failure;if(config.failure){failure=(config.scope)?OpenLayers.Function.bind(config.failure,config.scope):config.failure;}
complete(request);if(!request.status||(request.status>=200&&request.status<300)){this.events.triggerEvent("success",options);if(success){success(request);}}
if(request.status&&(request.status<200||request.status>=300)){this.events.triggerEvent("failure",options);if(failure){failure(request);}}},GET:function(config){config=OpenLayers.Util.extend(config,{method:"GET"});return OpenLayers.Request.issue(config);},POST:function(config){config=OpenLayers.Util.extend(config,{method:"POST"});config.headers=config.headers?config.headers:{};if(!("CONTENT-TYPE"in OpenLayers.Util.upperCaseObject(config.headers))){config.headers["Content-Type"]="application/xml";}
return OpenLayers.Request.issue(config);},PUT:function(config){config=OpenLayers.Util.extend(config,{method:"PUT"});config.headers=config.headers?config.headers:{};if(!("CONTENT-TYPE"in OpenLayers.Util.upperCaseObject(config.headers))){config.headers["Content-Type"]="application/xml";}
return OpenLayers.Request.issue(config);},DELETE:function(config){config=OpenLayers.Util.extend(config,{method:"DELETE"});return OpenLayers.Request.issue(config);},HEAD:function(config){config=OpenLayers.Util.extend(config,{method:"HEAD"});return OpenLayers.Request.issue(config);},OPTIONS:function(config){config=OpenLayers.Util.extend(config,{method:"OPTIONS"});return OpenLayers.Request.issue(config);}};OpenLayers.Tile.Image=OpenLayers.Class(OpenLayers.Tile,{url:null,imgDiv:null,frame:null,layerAlphaHack:null,isBackBuffer:false,lastRatio:1,isFirstDraw:true,backBufferTile:null,initialize:function(layer,position,bounds,url,size){OpenLayers.Tile.prototype.initialize.apply(this,arguments);this.url=url;this.frame=document.createElement('div');this.frame.style.overflow='hidden';this.frame.style.position='absolute';this.layerAlphaHack=this.layer.alpha&&OpenLayers.Util.alphaHack();},destroy:function(){if(this.imgDiv!=null){if(this.layerAlphaHack){OpenLayers.Event.stopObservingElement(this.imgDiv.childNodes[0]);}
OpenLayers.Event.stopObservingElement(this.imgDiv);if(this.imgDiv.parentNode==this.frame){this.frame.removeChild(this.imgDiv);this.imgDiv.map=null;}
this.imgDiv.urls=null;this.imgDiv.src=OpenLayers.Util.getImagesLocation()+"blank.gif";}
this.imgDiv=null;if((this.frame!=null)&&(this.frame.parentNode==this.layer.div)){this.layer.div.removeChild(this.frame);}
this.frame=null;if(this.backBufferTile){this.backBufferTile.destroy();this.backBufferTile=null;}
this.layer.events.unregister("loadend",this,this.resetBackBuffer);OpenLayers.Tile.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Tile.Image(this.layer,this.position,this.bounds,this.url,this.size);}
obj=OpenLayers.Tile.prototype.clone.apply(this,[obj]);obj.imgDiv=null;return obj;},draw:function(){if(this.layer!=this.layer.map.baseLayer&&this.layer.reproject){this.bounds=this.getBoundsFromBaseLayer(this.position);}
var drawTile=OpenLayers.Tile.prototype.draw.apply(this,arguments);if((OpenLayers.Util.indexOf(this.layer.SUPPORTED_TRANSITIONS,this.layer.transitionEffect)!=-1)||this.layer.singleTile){if(drawTile){if(!this.backBufferTile){this.backBufferTile=this.clone();this.backBufferTile.hide();this.backBufferTile.isBackBuffer=true;this.events.register('loadend',this,this.resetBackBuffer);this.layer.events.register("loadend",this,this.resetBackBuffer);}
this.startTransition();}else{if(this.backBufferTile){this.backBufferTile.clear();}}}else{if(drawTile&&this.isFirstDraw){this.events.register('loadend',this,this.showTile);this.isFirstDraw=false;}}
if(!drawTile){return false;}
if(this.isLoading){this.events.triggerEvent("reload");}else{this.isLoading=true;this.events.triggerEvent("loadstart");}
return this.renderTile();},resetBackBuffer:function(){this.showTile();if(this.backBufferTile&&(this.isFirstDraw||!this.layer.numLoadingTiles)){this.isFirstDraw=false;var maxExtent=this.layer.maxExtent;var withinMaxExtent=(maxExtent&&this.bounds.intersectsBounds(maxExtent,false));if(withinMaxExtent){this.backBufferTile.position=this.position;this.backBufferTile.bounds=this.bounds;this.backBufferTile.size=this.size;this.backBufferTile.imageSize=this.layer.getImageSize(this.bounds)||this.size;this.backBufferTile.imageOffset=this.layer.imageOffset;this.backBufferTile.resolution=this.layer.getResolution();this.backBufferTile.renderTile();}
this.backBufferTile.hide();}},renderTile:function(){if(this.imgDiv==null){this.initImgDiv();}
this.imgDiv.viewRequestID=this.layer.map.viewRequestID;if(this.layer.async){this.layer.getURLasync(this.bounds,this,"url",this.positionImage);}else{if(this.layer.url instanceof Array){this.imgDiv.urls=this.layer.url.slice();}
this.url=this.layer.getURL(this.bounds);this.positionImage();}
return true;},positionImage:function(){if(this.layer===null){return;}
OpenLayers.Util.modifyDOMElement(this.frame,null,this.position,this.size);var imageSize=this.layer.getImageSize(this.bounds);if(this.layerAlphaHack){OpenLayers.Util.modifyAlphaImageDiv(this.imgDiv,null,null,imageSize,this.url);}else{OpenLayers.Util.modifyDOMElement(this.imgDiv,null,null,imageSize);this.imgDiv.src=this.url;}},clear:function(){if(this.imgDiv){this.hide();if(OpenLayers.Tile.Image.useBlankTile){this.imgDiv.src=OpenLayers.Util.getImagesLocation()+"blank.gif";}}},initImgDiv:function(){var offset=this.layer.imageOffset;var size=this.layer.getImageSize(this.bounds);if(this.layerAlphaHack){this.imgDiv=OpenLayers.Util.createAlphaImageDiv(null,offset,size,null,"relative",null,null,null,true);}else{this.imgDiv=OpenLayers.Util.createImage(null,offset,size,null,"relative",null,null,true);}
this.imgDiv.className='olTileImage';this.frame.style.zIndex=this.isBackBuffer?0:1;this.frame.appendChild(this.imgDiv);this.layer.div.appendChild(this.frame);if(this.layer.opacity!=null){OpenLayers.Util.modifyDOMElement(this.imgDiv,null,null,null,null,null,null,this.layer.opacity);}
this.imgDiv.map=this.layer.map;var onload=function(){if(this.isLoading){this.isLoading=false;this.events.triggerEvent("loadend");}};if(this.layerAlphaHack){OpenLayers.Event.observe(this.imgDiv.childNodes[0],'load',OpenLayers.Function.bind(onload,this));}else{OpenLayers.Event.observe(this.imgDiv,'load',OpenLayers.Function.bind(onload,this));}
var onerror=function(){if(this.imgDiv._attempts>OpenLayers.IMAGE_RELOAD_ATTEMPTS){onload.call(this);}};OpenLayers.Event.observe(this.imgDiv,"error",OpenLayers.Function.bind(onerror,this));},checkImgURL:function(){if(this.layer){var loaded=this.layerAlphaHack?this.imgDiv.firstChild.src:this.imgDiv.src;if(!OpenLayers.Util.isEquivalentUrl(loaded,this.url)){this.hide();}}},startTransition:function(){if(!this.backBufferTile||!this.backBufferTile.imgDiv){return;}
var ratio=1;if(this.backBufferTile.resolution){ratio=this.backBufferTile.resolution/this.layer.getResolution();}
if(ratio!=this.lastRatio){if(this.layer.transitionEffect=='resize'){var upperLeft=new OpenLayers.LonLat(this.backBufferTile.bounds.left,this.backBufferTile.bounds.top);var size=new OpenLayers.Size(this.backBufferTile.size.w*ratio,this.backBufferTile.size.h*ratio);var px=this.layer.map.getLayerPxFromLonLat(upperLeft);OpenLayers.Util.modifyDOMElement(this.backBufferTile.frame,null,px,size);var imageSize=this.backBufferTile.imageSize;imageSize=new OpenLayers.Size(imageSize.w*ratio,imageSize.h*ratio);var imageOffset=this.backBufferTile.imageOffset;if(imageOffset){imageOffset=new OpenLayers.Pixel(imageOffset.x*ratio,imageOffset.y*ratio);}
OpenLayers.Util.modifyDOMElement(this.backBufferTile.imgDiv,null,imageOffset,imageSize);this.backBufferTile.show();}}else{if(this.layer.singleTile){this.backBufferTile.show();}else{this.backBufferTile.hide();}}
this.lastRatio=ratio;},show:function(){this.frame.style.display='';if(OpenLayers.Util.indexOf(this.layer.SUPPORTED_TRANSITIONS,this.layer.transitionEffect)!=-1){if(navigator.userAgent.toLowerCase().indexOf("gecko")!=-1){this.frame.scrollLeft=this.frame.scrollLeft;}}},hide:function(){this.frame.style.display='none';},CLASS_NAME:"OpenLayers.Tile.Image"});OpenLayers.Tile.Image.useBlankTile=(OpenLayers.Util.getBrowserName()=="safari"||OpenLayers.Util.getBrowserName()=="opera");OpenLayers.Control.OverviewMap=OpenLayers.Class(OpenLayers.Control,{element:null,ovmap:null,size:new OpenLayers.Size(180,90),layers:null,minRectSize:15,minRectDisplayClass:"RectReplacement",minRatio:8,maxRatio:32,mapOptions:null,autoPan:false,handlers:null,resolutionFactor:1,maximized:false,initialize:function(options){this.layers=[];this.handlers={};OpenLayers.Control.prototype.initialize.apply(this,[options]);},destroy:function(){if(!this.mapDiv){return;}
if(this.handlers.click){this.handlers.click.destroy();}
if(this.handlers.drag){this.handlers.drag.destroy();}
this.mapDiv.removeChild(this.extentRectangle);this.extentRectangle=null;if(this.rectEvents){this.rectEvents.destroy();this.rectEvents=null;}
if(this.ovmap){this.ovmap.destroy();this.ovmap=null;}
this.element.removeChild(this.mapDiv);this.mapDiv=null;this.div.removeChild(this.element);this.element=null;if(this.maximizeDiv){OpenLayers.Event.stopObservingElement(this.maximizeDiv);this.div.removeChild(this.maximizeDiv);this.maximizeDiv=null;}
if(this.minimizeDiv){OpenLayers.Event.stopObservingElement(this.minimizeDiv);this.div.removeChild(this.minimizeDiv);this.minimizeDiv=null;}
this.map.events.un({"moveend":this.update,"changebaselayer":this.baseLayerDraw,scope:this});OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!(this.layers.length>0)){if(this.map.baseLayer){var layer=this.map.baseLayer.clone();this.layers=[layer];}else{this.map.events.register("changebaselayer",this,this.baseLayerDraw);return this.div;}}
this.element=document.createElement('div');this.element.className=this.displayClass+'Element';this.element.style.display='none';this.mapDiv=document.createElement('div');this.mapDiv.style.width=this.size.w+'px';this.mapDiv.style.height=this.size.h+'px';this.mapDiv.style.position='relative';this.mapDiv.style.overflow='hidden';this.mapDiv.id=OpenLayers.Util.createUniqueID('overviewMap');this.extentRectangle=document.createElement('div');this.extentRectangle.style.position='absolute';this.extentRectangle.style.zIndex=1000;this.extentRectangle.className=this.displayClass+'ExtentRectangle';this.mapDiv.appendChild(this.extentRectangle);this.element.appendChild(this.mapDiv);this.div.appendChild(this.element);if(!this.outsideViewport){this.div.className+=" "+this.displayClass+'Container';var imgLocation=OpenLayers.Util.getImagesLocation();var img=imgLocation+'layer-switcher-maximize.png';this.maximizeDiv=OpenLayers.Util.createAlphaImageDiv(this.displayClass+'MaximizeButton',null,new OpenLayers.Size(18,18),img,'absolute');this.maximizeDiv.style.display='none';this.maximizeDiv.className=this.displayClass+'MaximizeButton';OpenLayers.Event.observe(this.maximizeDiv,'click',OpenLayers.Function.bindAsEventListener(this.maximizeControl,this));this.div.appendChild(this.maximizeDiv);var img=imgLocation+'layer-switcher-minimize.png';this.minimizeDiv=OpenLayers.Util.createAlphaImageDiv('OpenLayers_Control_minimizeDiv',null,new OpenLayers.Size(18,18),img,'absolute');this.minimizeDiv.style.display='none';this.minimizeDiv.className=this.displayClass+'MinimizeButton';OpenLayers.Event.observe(this.minimizeDiv,'click',OpenLayers.Function.bindAsEventListener(this.minimizeControl,this));this.div.appendChild(this.minimizeDiv);var eventsToStop=['dblclick','mousedown'];for(var i=0,len=eventsToStop.length;i<len;i++){OpenLayers.Event.observe(this.maximizeDiv,eventsToStop[i],OpenLayers.Event.stop);OpenLayers.Event.observe(this.minimizeDiv,eventsToStop[i],OpenLayers.Event.stop);}
this.minimizeControl();}else{this.element.style.display='';}
if(this.map.getExtent()){this.update();}
this.map.events.register('moveend',this,this.update);if(this.maximized){this.maximizeControl();}
return this.div;},baseLayerDraw:function(){this.draw();this.map.events.unregister("changebaselayer",this,this.baseLayerDraw);},rectDrag:function(px){var deltaX=this.handlers.drag.last.x-px.x;var deltaY=this.handlers.drag.last.y-px.y;if(deltaX!=0||deltaY!=0){var rectTop=this.rectPxBounds.top;var rectLeft=this.rectPxBounds.left;var rectHeight=Math.abs(this.rectPxBounds.getHeight());var rectWidth=this.rectPxBounds.getWidth();var newTop=Math.max(0,(rectTop-deltaY));newTop=Math.min(newTop,this.ovmap.size.h-this.hComp-rectHeight);var newLeft=Math.max(0,(rectLeft-deltaX));newLeft=Math.min(newLeft,this.ovmap.size.w-this.wComp-rectWidth);this.setRectPxBounds(new OpenLayers.Bounds(newLeft,newTop+rectHeight,newLeft+rectWidth,newTop));}},mapDivClick:function(evt){var pxCenter=this.rectPxBounds.getCenterPixel();var deltaX=evt.xy.x-pxCenter.x;var deltaY=evt.xy.y-pxCenter.y;var top=this.rectPxBounds.top;var left=this.rectPxBounds.left;var height=Math.abs(this.rectPxBounds.getHeight());var width=this.rectPxBounds.getWidth();var newTop=Math.max(0,(top+deltaY));newTop=Math.min(newTop,this.ovmap.size.h-height);var newLeft=Math.max(0,(left+deltaX));newLeft=Math.min(newLeft,this.ovmap.size.w-width);this.setRectPxBounds(new OpenLayers.Bounds(newLeft,newTop+height,newLeft+width,newTop));this.updateMapToRect();},maximizeControl:function(e){this.element.style.display='';this.showToggle(false);if(e!=null){OpenLayers.Event.stop(e);}},minimizeControl:function(e){this.element.style.display='none';this.showToggle(true);if(e!=null){OpenLayers.Event.stop(e);}},showToggle:function(minimize){this.maximizeDiv.style.display=minimize?'':'none';this.minimizeDiv.style.display=minimize?'none':'';},update:function(){if(this.ovmap==null){this.createMap();}
if(this.autoPan||!this.isSuitableOverview()){this.updateOverview();}
this.updateRectToMap();},isSuitableOverview:function(){var mapExtent=this.map.getExtent();var maxExtent=this.map.maxExtent;var testExtent=new OpenLayers.Bounds(Math.max(mapExtent.left,maxExtent.left),Math.max(mapExtent.bottom,maxExtent.bottom),Math.min(mapExtent.right,maxExtent.right),Math.min(mapExtent.top,maxExtent.top));if(this.ovmap.getProjection()!=this.map.getProjection()){testExtent=testExtent.transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject());}
var resRatio=this.ovmap.getResolution()/this.map.getResolution();return((resRatio>this.minRatio)&&(resRatio<=this.maxRatio)&&(this.ovmap.getExtent().containsBounds(testExtent)));},updateOverview:function(){var mapRes=this.map.getResolution();var targetRes=this.ovmap.getResolution();var resRatio=targetRes/mapRes;if(resRatio>this.maxRatio){targetRes=this.minRatio*mapRes;}else if(resRatio<=this.minRatio){targetRes=this.maxRatio*mapRes;}
var center;if(this.ovmap.getProjection()!=this.map.getProjection()){center=this.map.center.clone();center.transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject());}else{center=this.map.center;}
this.ovmap.setCenter(center,this.ovmap.getZoomForResolution(targetRes*this.resolutionFactor));this.updateRectToMap();},createMap:function(){var options=OpenLayers.Util.extend({controls:[],maxResolution:'auto',fallThrough:false},this.mapOptions);this.ovmap=new OpenLayers.Map(this.mapDiv,options);OpenLayers.Event.stopObserving(window,'unload',this.ovmap.unloadDestroy);this.ovmap.addLayers(this.layers);this.ovmap.zoomToMaxExtent();this.wComp=parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-left-width'))+
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-right-width'));this.wComp=(this.wComp)?this.wComp:2;this.hComp=parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-top-width'))+
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-bottom-width'));this.hComp=(this.hComp)?this.hComp:2;this.handlers.drag=new OpenLayers.Handler.Drag(this,{move:this.rectDrag,done:this.updateMapToRect},{map:this.ovmap});this.handlers.click=new OpenLayers.Handler.Click(this,{"click":this.mapDivClick},{"single":true,"double":false,"stopSingle":true,"stopDouble":true,"pixelTolerance":1,map:this.ovmap});this.handlers.click.activate();this.rectEvents=new OpenLayers.Events(this,this.extentRectangle,null,true);this.rectEvents.register("mouseover",this,function(e){if(!this.handlers.drag.active&&!this.map.dragging){this.handlers.drag.activate();}});this.rectEvents.register("mouseout",this,function(e){if(!this.handlers.drag.dragging){this.handlers.drag.deactivate();}});if(this.ovmap.getProjection()!=this.map.getProjection()){var sourceUnits=this.map.getProjectionObject().getUnits()||this.map.units||this.map.baseLayer.units;var targetUnits=this.ovmap.getProjectionObject().getUnits()||this.ovmap.units||this.ovmap.baseLayer.units;this.resolutionFactor=sourceUnits&&targetUnits?OpenLayers.INCHES_PER_UNIT[sourceUnits]/OpenLayers.INCHES_PER_UNIT[targetUnits]:1;}},updateRectToMap:function(){var bounds;if(this.ovmap.getProjection()!=this.map.getProjection()){bounds=this.map.getExtent().transform(this.map.getProjectionObject(),this.ovmap.getProjectionObject());}else{bounds=this.map.getExtent();}
var pxBounds=this.getRectBoundsFromMapBounds(bounds);if(pxBounds){this.setRectPxBounds(pxBounds);}},updateMapToRect:function(){var lonLatBounds=this.getMapBoundsFromRectBounds(this.rectPxBounds);if(this.ovmap.getProjection()!=this.map.getProjection()){lonLatBounds=lonLatBounds.transform(this.ovmap.getProjectionObject(),this.map.getProjectionObject());}
this.map.panTo(lonLatBounds.getCenterLonLat());},setRectPxBounds:function(pxBounds){var top=Math.max(pxBounds.top,0);var left=Math.max(pxBounds.left,0);var bottom=Math.min(pxBounds.top+Math.abs(pxBounds.getHeight()),this.ovmap.size.h-this.hComp);var right=Math.min(pxBounds.left+pxBounds.getWidth(),this.ovmap.size.w-this.wComp);var width=Math.max(right-left,0);var height=Math.max(bottom-top,0);if(width<this.minRectSize||height<this.minRectSize){this.extentRectangle.className=this.displayClass+
this.minRectDisplayClass;var rLeft=left+(width/2)-(this.minRectSize/2);var rTop=top+(height/2)-(this.minRectSize/2);this.extentRectangle.style.top=Math.round(rTop)+'px';this.extentRectangle.style.left=Math.round(rLeft)+'px';this.extentRectangle.style.height=this.minRectSize+'px';this.extentRectangle.style.width=this.minRectSize+'px';}else{this.extentRectangle.className=this.displayClass+'ExtentRectangle';this.extentRectangle.style.top=Math.round(top)+'px';this.extentRectangle.style.left=Math.round(left)+'px';this.extentRectangle.style.height=Math.round(height)+'px';this.extentRectangle.style.width=Math.round(width)+'px';}
this.rectPxBounds=new OpenLayers.Bounds(Math.round(left),Math.round(bottom),Math.round(right),Math.round(top));},getRectBoundsFromMapBounds:function(lonLatBounds){var leftBottomLonLat=new OpenLayers.LonLat(lonLatBounds.left,lonLatBounds.bottom);var rightTopLonLat=new OpenLayers.LonLat(lonLatBounds.right,lonLatBounds.top);var leftBottomPx=this.getOverviewPxFromLonLat(leftBottomLonLat);var rightTopPx=this.getOverviewPxFromLonLat(rightTopLonLat);var bounds=null;if(leftBottomPx&&rightTopPx){bounds=new OpenLayers.Bounds(leftBottomPx.x,leftBottomPx.y,rightTopPx.x,rightTopPx.y);}
return bounds;},getMapBoundsFromRectBounds:function(pxBounds){var leftBottomPx=new OpenLayers.Pixel(pxBounds.left,pxBounds.bottom);var rightTopPx=new OpenLayers.Pixel(pxBounds.right,pxBounds.top);var leftBottomLonLat=this.getLonLatFromOverviewPx(leftBottomPx);var rightTopLonLat=this.getLonLatFromOverviewPx(rightTopPx);return new OpenLayers.Bounds(leftBottomLonLat.lon,leftBottomLonLat.lat,rightTopLonLat.lon,rightTopLonLat.lat);},getLonLatFromOverviewPx:function(overviewMapPx){var size=this.ovmap.size;var res=this.ovmap.getResolution();var center=this.ovmap.getExtent().getCenterLonLat();var delta_x=overviewMapPx.x-(size.w/2);var delta_y=overviewMapPx.y-(size.h/2);return new OpenLayers.LonLat(center.lon+delta_x*res,center.lat-delta_y*res);},getOverviewPxFromLonLat:function(lonlat){var res=this.ovmap.getResolution();var extent=this.ovmap.getExtent();var px=null;if(extent){px=new OpenLayers.Pixel(Math.round(1/res*(lonlat.lon-extent.left)),Math.round(1/res*(extent.top-lonlat.lat)));}
return px;},CLASS_NAME:'OpenLayers.Control.OverviewMap'});OpenLayers.Feature=OpenLayers.Class({layer:null,id:null,lonlat:null,data:null,marker:null,popupClass:OpenLayers.Popup.AnchoredBubble,popup:null,initialize:function(layer,lonlat,data){this.layer=layer;this.lonlat=lonlat;this.data=(data!=null)?data:{};this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");},destroy:function(){if((this.layer!=null)&&(this.layer.map!=null)){if(this.popup!=null){this.layer.map.removePopup(this.popup);}}
if(this.layer!=null&&this.marker!=null){this.layer.removeMarker(this.marker);}
this.layer=null;this.id=null;this.lonlat=null;this.data=null;if(this.marker!=null){this.destroyMarker(this.marker);this.marker=null;}
if(this.popup!=null){this.destroyPopup(this.popup);this.popup=null;}},onScreen:function(){var onScreen=false;if((this.layer!=null)&&(this.layer.map!=null)){var screenBounds=this.layer.map.getExtent();onScreen=screenBounds.containsLonLat(this.lonlat);}
return onScreen;},createMarker:function(){if(this.lonlat!=null){this.marker=new OpenLayers.Marker(this.lonlat,this.data.icon);}
return this.marker;},destroyMarker:function(){this.marker.destroy();},createPopup:function(closeBox){if(this.lonlat!=null){var id=this.id+"_popup";var anchor=(this.marker)?this.marker.icon:null;if(!this.popup){this.popup=new this.popupClass(id,this.lonlat,this.data.popupSize,this.data.popupContentHTML,anchor,closeBox);}
if(this.data.overflow!=null){this.popup.contentDiv.style.overflow=this.data.overflow;}
this.popup.feature=this;}
return this.popup;},destroyPopup:function(){if(this.popup){this.popup.feature=null;this.popup.destroy();this.popup=null;}},CLASS_NAME:"OpenLayers.Feature"});OpenLayers.Format.CSWGetDomain.v2_0_2=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",csw:"http://www.opengis.net/cat/csw/2.0.2"},defaultPrefix:"csw",version:"2.0.2",schemaLocation:"http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd",PropertyName:null,ParameterName:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var obj={};this.readNode(data,obj);return obj;},readers:{"csw":{"GetDomainResponse":function(node,obj){this.readChildNodes(node,obj);},"DomainValues":function(node,obj){if(!(obj.DomainValues instanceof Array)){obj.DomainValues=[];}
var attrs=node.attributes;var domainValue={};for(var i=0,len=attrs.length;i<len;++i){domainValue[attrs[i].name]=attrs[i].nodeValue;}
this.readChildNodes(node,domainValue);obj.DomainValues.push(domainValue);},"PropertyName":function(node,obj){obj.PropertyName=this.getChildValue(node);},"ParameterName":function(node,obj){obj.ParameterName=this.getChildValue(node);},"ListOfValues":function(node,obj){if(!(obj.ListOfValues instanceof Array)){obj.ListOfValues=[];}
this.readChildNodes(node,obj.ListOfValues);},"Value":function(node,obj){var attrs=node.attributes;var value={}
for(var i=0,len=attrs.length;i<len;++i){value[attrs[i].name]=attrs[i].nodeValue;}
value.value=this.getChildValue(node);obj.push({Value:value});},"ConceptualScheme":function(node,obj){obj.ConceptualScheme={};this.readChildNodes(node,obj.ConceptualScheme);},"Name":function(node,obj){obj.Name=this.getChildValue(node);},"Document":function(node,obj){obj.Document=this.getChildValue(node);},"Authority":function(node,obj){obj.Authority=this.getChildValue(node);},"RangeOfValues":function(node,obj){obj.RangeOfValues={};this.readChildNodes(node,obj.RangeOfValues);},"MinValue":function(node,obj){var attrs=node.attributes;var value={}
for(var i=0,len=attrs.length;i<len;++i){value[attrs[i].name]=attrs[i].nodeValue;}
value.value=this.getChildValue(node);obj.MinValue=value;},"MaxValue":function(node,obj){var attrs=node.attributes;var value={}
for(var i=0,len=attrs.length;i<len;++i){value[attrs[i].name]=attrs[i].nodeValue;}
value.value=this.getChildValue(node);obj.MaxValue=value;}}},write:function(options){var node=this.writeNode("csw:GetDomain",options);return OpenLayers.Format.XML.prototype.write.apply(this,[node]);},writers:{"csw":{"GetDomain":function(options){var node=this.createElementNSPlus("csw:GetDomain",{attributes:{service:"CSW",version:this.version}});if(options.PropertyName||this.PropertyName){this.writeNode("csw:PropertyName",options.PropertyName||this.PropertyName,node);}else if(options.ParameterName||this.ParameterName){this.writeNode("csw:ParameterName",options.ParameterName||this.ParameterName,node);}
this.readChildNodes(node,options);return node;},"PropertyName":function(value){var node=this.createElementNSPlus("csw:PropertyName",{value:value});return node;},"ParameterName":function(value){var node=this.createElementNSPlus("csw:ParameterName",{value:value});return node;}}},CLASS_NAME:"OpenLayers.Format.CSWGetDomain.v2_0_2"});OpenLayers.Format.Context=OpenLayers.Class({version:null,layerOptions:null,layerParams:null,parser:null,initialize:function(options){OpenLayers.Util.extend(this,options);this.options=options;},read:function(data,options){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;var version=this.version;if(!version){version=root.getAttribute("version");}
var parser=this.getParser(version);var context=parser.read(data,options);var map;if(options&&options.map){this.context=context;if(options.map instanceof OpenLayers.Map){map=this.mergeContextToMap(context,options.map);}else{var mapOptions=options.map;if(OpenLayers.Util.isElement(mapOptions)||typeof mapOptions=="string"){mapOptions={div:mapOptions};}
map=this.contextToMap(context,mapOptions);}}else{map=context;}
return map;},getLayerFromContext:function(layerContext){var i,len;var options={queryable:layerContext.queryable,visibility:layerContext.visibility,maxExtent:layerContext.maxExtent,metadata:OpenLayers.Util.applyDefaults(layerContext.metadata,{styles:layerContext.styles}),numZoomLevels:layerContext.numZoomLevels,units:layerContext.units,isBaseLayer:layerContext.isBaseLayer,opacity:layerContext.opacity,displayInLayerSwitcher:layerContext.displayInLayerSwitcher,singleTile:layerContext.singleTile,tileSize:(layerContext.tileSize)?new OpenLayers.Size(layerContext.tileSize.width,layerContext.tileSize.height):undefined,minScale:layerContext.minScale||layerContext.maxScaleDenominator,maxScale:layerContext.maxScale||layerContext.minScaleDenominator};if(this.layerOptions){OpenLayers.Util.applyDefaults(options,this.layerOptions);}
var params={layers:layerContext.name,transparent:layerContext.transparent,version:layerContext.version};if(layerContext.formats&&layerContext.formats.length>0){params.format=layerContext.formats[0].value;for(i=0,len=layerContext.formats.length;i<len;i++){var format=layerContext.formats[i];if(format.current==true){params.format=format.value;break;}}}
if(layerContext.styles&&layerContext.styles.length>0){for(i=0,len=layerContext.styles.length;i<len;i++){var style=layerContext.styles[i];if(style.current==true){if(style.href){params.sld=style.href;}else if(style.body){params.sld_body=style.body;}else{params.styles=style.name;}
break;}}}
if(this.layerParams){OpenLayers.Util.applyDefaults(params,this.layerParams);}
var layer=null;var service=layerContext.service;if(service==OpenLayers.Format.Context.serviceTypes.WFS){options.strategies=[new OpenLayers.Strategy.BBOX()];options.protocol=new OpenLayers.Protocol.WFS({url:layerContext.url,featurePrefix:layerContext.name.split(":")[0],featureType:layerContext.name.split(":").pop()});layer=new OpenLayers.Layer.Vector(layerContext.title||layerContext.name,options);}else if(service==OpenLayers.Format.Context.serviceTypes.KML){options.strategies=[new OpenLayers.Strategy.Fixed()];options.protocol=new OpenLayers.Protocol.HTTP({url:layerContext.url,format:new OpenLayers.Format.KML()});layer=new OpenLayers.Layer.Vector(layerContext.title||layerContext.name,options);}else if(service==OpenLayers.Format.Context.serviceTypes.GML){options.strategies=[new OpenLayers.Strategy.Fixed()];options.protocol=new OpenLayers.Protocol.HTTP({url:layerContext.url,format:new OpenLayers.Format.GML()});layer=new OpenLayers.Layer.Vector(layerContext.title||layerContext.name,options);}else if(layerContext.features){layer=new OpenLayers.Layer.Vector(layerContext.title||layerContext.name,options);layer.addFeatures(layerContext.features);}else if(layerContext.categoryLayer!==true){layer=new OpenLayers.Layer.WMS(layerContext.title||layerContext.name,layerContext.url,params,options);}
return layer;},getLayersFromContext:function(layersContext){var layers=[];for(var i=0,len=layersContext.length;i<len;i++){var layer=this.getLayerFromContext(layersContext[i]);if(layer!==null){layers.push(layer);}}
return layers;},contextToMap:function(context,options){options=OpenLayers.Util.applyDefaults({maxExtent:context.maxExtent,projection:context.projection},options);var map=new OpenLayers.Map(options);map.addLayers(this.getLayersFromContext(context.layersContext));map.setCenter(context.bounds.getCenterLonLat(),map.getZoomForExtent(context.bounds,true));return map;},mergeContextToMap:function(context,map){map.addLayers(this.getLayersFromContext(context.layersContext));return map;},write:function(obj,options){obj=this.toContext(obj);var version=options&&options.version;var parser=this.getParser(version);var context=parser.write(obj,options);return context;},CLASS_NAME:"OpenLayers.Format.Context"});OpenLayers.Format.Context.serviceTypes={"WMS":"urn:ogc:serviceType:WMS","WFS":"urn:ogc:serviceType:WFS","WCS":"urn:ogc:serviceType:WCS","GML":"urn:ogc:serviceType:GML","SLD":"urn:ogc:serviceType:SLD","FES":"urn:ogc:serviceType:FES","KML":"urn:ogc:serviceType:KML"};if(!OpenLayers.Format.OWSCommon){OpenLayers.Format.OWSCommon={};}
OpenLayers.Format.OWSCommon.v1=OpenLayers.Class(OpenLayers.Format.XML,{regExes:{trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)},readers:{"ows":{"ServiceIdentification":function(node,obj){obj.serviceIdentification={};this.readChildNodes(node,obj.serviceIdentification);},"Title":function(node,obj){obj.title=this.getChildValue(node);},"Abstract":function(node,serviceIdentification){serviceIdentification["abstract"]=this.getChildValue(node);},"Keywords":function(node,serviceIdentification){serviceIdentification.keywords={};this.readChildNodes(node,serviceIdentification.keywords);},"Keyword":function(node,keywords){keywords[this.getChildValue(node)]=true;},"ServiceType":function(node,serviceIdentification){serviceIdentification.serviceType={codeSpace:node.getAttribute('codeSpace'),value:this.getChildValue(node)};},"ServiceTypeVersion":function(node,serviceIdentification){serviceIdentification.serviceTypeVersion=this.getChildValue(node);},"Fees":function(node,serviceIdentification){serviceIdentification.fees=this.getChildValue(node);},"AccessConstraints":function(node,serviceIdentification){serviceIdentification.accessConstraints=this.getChildValue(node);},"ServiceProvider":function(node,obj){obj.serviceProvider={};this.readChildNodes(node,obj.serviceProvider);},"ProviderName":function(node,serviceProvider){serviceProvider.providerName=this.getChildValue(node);},"ProviderSite":function(node,serviceProvider){serviceProvider.providerSite=this.getAttributeNS(node,this.namespaces.xlink,"href");},"ServiceContact":function(node,serviceProvider){serviceProvider.serviceContact={};this.readChildNodes(node,serviceProvider.serviceContact);},"IndividualName":function(node,serviceContact){serviceContact.individualName=this.getChildValue(node);},"PositionName":function(node,serviceContact){serviceContact.positionName=this.getChildValue(node);},"ContactInfo":function(node,serviceContact){serviceContact.contactInfo={};this.readChildNodes(node,serviceContact.contactInfo);},"Phone":function(node,contactInfo){contactInfo.phone={};this.readChildNodes(node,contactInfo.phone);},"Voice":function(node,phone){phone.voice=this.getChildValue(node);},"Address":function(node,contactInfo){contactInfo.address={};this.readChildNodes(node,contactInfo.address);},"DeliveryPoint":function(node,address){address.deliveryPoint=this.getChildValue(node);},"City":function(node,address){address.city=this.getChildValue(node);},"AdministrativeArea":function(node,address){address.administrativeArea=this.getChildValue(node);},"PostalCode":function(node,address){address.postalCode=this.getChildValue(node);},"Country":function(node,address){address.country=this.getChildValue(node);},"ElectronicMailAddress":function(node,address){address.electronicMailAddress=this.getChildValue(node);},"Role":function(node,serviceContact){serviceContact.role=this.getChildValue(node);},"OperationsMetadata":function(node,obj){obj.operationsMetadata={};this.readChildNodes(node,obj.operationsMetadata);},"Operation":function(node,operationsMetadata){var name=node.getAttribute("name");operationsMetadata[name]={};this.readChildNodes(node,operationsMetadata[name]);},"DCP":function(node,operation){operation.dcp={};this.readChildNodes(node,operation.dcp);},"HTTP":function(node,dcp){dcp.http={};this.readChildNodes(node,dcp.http);},"Get":function(node,http){http.get=this.getAttributeNS(node,this.namespaces.xlink,"href");},"Post":function(node,http){http.post=this.getAttributeNS(node,this.namespaces.xlink,"href");},"Parameter":function(node,operation){if(!operation.parameters){operation.parameters={};}
var name=node.getAttribute("name");operation.parameters[name]={};this.readChildNodes(node,operation.parameters[name]);},"Value":function(node,allowedValues){allowedValues[this.getChildValue(node)]=true;},"OutputFormat":function(node,obj){obj.formats.push({value:this.getChildValue(node)});this.readChildNodes(node,obj);},"WGS84BoundingBox":function(node,obj){var boundingBox={};boundingBox.crs=node.getAttribute("crs");if(obj.BoundingBox){obj.BoundingBox.push(boundingBox);}else{obj.projection=boundingBox.crs;boundingBox=obj;}
this.readChildNodes(node,boundingBox);},"BoundingBox":function(node,obj){this.readers['ows']['WGS84BoundingBox'].apply(this,[node,obj]);},"LowerCorner":function(node,obj){var str=this.getChildValue(node).replace(this.regExes.trimSpace,"");str=str.replace(this.regExes.trimComma,",");var pointList=str.split(this.regExes.splitSpace);obj.left=pointList[0];obj.bottom=pointList[1];},"UpperCorner":function(node,obj){var str=this.getChildValue(node).replace(this.regExes.trimSpace,"");str=str.replace(this.regExes.trimComma,",");var pointList=str.split(this.regExes.splitSpace);obj.right=pointList[0];obj.top=pointList[1];obj.bounds=new OpenLayers.Bounds(obj.left,obj.bottom,obj.right,obj.top);delete obj.left;delete obj.bottom;delete obj.right;delete obj.top;}}},writers:{"ows":{"BoundingBox":function(options){var node=this.createElementNSPlus("ows:BoundingBox",{attributes:{crs:options.projection}});this.writeNode("ows:LowerCorner",options,node);this.writeNode("ows:UpperCorner",options,node);return node;},"LowerCorner":function(options){var node=this.createElementNSPlus("ows:LowerCorner",{value:options.bounds.left+" "+options.bounds.bottom});return node;},"UpperCorner":function(options){var node=this.createElementNSPlus("ows:UpperCorner",{value:options.bounds.right+" "+options.bounds.top});return node;},"Title":function(title){var node=this.createElementNSPlus("ows:Title",{value:title});return node;},"OutputFormat":function(format){var node=this.createElementNSPlus("ows:OutputFormat",{value:format});return node;}}},CLASS_NAME:"OpenLayers.Format.OWSCommon.v1"});OpenLayers.Format.SOSCapabilities=OpenLayers.Class(OpenLayers.Format.XML,{defaultVersion:"1.0.0",version:null,parser:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);this.options=options;},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;var version=this.version||root.getAttribute("version")||this.defaultVersion;if(!this.parser||this.parser.version!==version){var constr=OpenLayers.Format.SOSCapabilities["v"+version.replace(/\./g,"_")];if(!constr){throw"Can't find a SOS capabilities parser for version "+version;}
var parser=new constr(this.options);}
var capabilities=parser.read(data);capabilities.version=version;return capabilities;},CLASS_NAME:"OpenLayers.Format.SOSCapabilities"});OpenLayers.Format.WFSCapabilities=OpenLayers.Class(OpenLayers.Format.XML,{defaultVersion:"1.1.0",version:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);this.options=options;},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;var version=this.version;if(!version){version=root.getAttribute("version");if(!version){version=this.defaultVersion;}}
var constr=OpenLayers.Format.WFSCapabilities["v"+version.replace(/\./g,"_")];if(!constr){throw"Can't find a WFS capabilities parser for version "+version;}
var parser=new constr(this.options);var capabilities=parser.read(data);capabilities.version=version;return capabilities;},CLASS_NAME:"OpenLayers.Format.WFSCapabilities"});OpenLayers.Format.WFSDescribeFeatureType=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{xsd:"http://www.w3.org/2001/XMLSchema"},initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},readers:{"xsd":{"schema":function(node,obj){var complexTypes=[];var customTypes={};var schema={complexTypes:complexTypes,customTypes:customTypes};this.readChildNodes(node,schema);var attributes=node.attributes;var attr,name;for(var i=0,len=attributes.length;i<len;++i){attr=attributes[i];name=attr.name;if(name.indexOf("xmlns")==0){this.setNamespace(name.split(":")[1]||"",attr.value);}else{obj[name]=attr.value;}}
obj.featureTypes=complexTypes;obj.targetPrefix=this.namespaceAlias[obj.targetNamespace];var complexType,customType;for(var i=0,len=complexTypes.length;i<len;++i){complexType=complexTypes[i];customType=customTypes[complexType.typeName];if(customTypes[complexType.typeName]){complexType.typeName=customType.name;}}},"complexType":function(node,obj){var complexType={"typeName":node.getAttribute("name")};this.readChildNodes(node,complexType);obj.complexTypes.push(complexType);},"complexContent":function(node,obj){this.readChildNodes(node,obj);},"extension":function(node,obj){this.readChildNodes(node,obj);},"sequence":function(node,obj){var sequence={elements:[]};this.readChildNodes(node,sequence);obj.properties=sequence.elements;},"element":function(node,obj){if(obj.elements){var element={};var attributes=node.attributes;var attr;for(var i=0,len=attributes.length;i<len;++i){attr=attributes[i];element[attr.name]=attr.value;}
var type=element.type;if(!type){type={};this.readChildNodes(node,type);element.restriction=type;element.type=type.base;}
var fullType=type.base||type;element.localType=fullType.split(":").pop();obj.elements.push(element);}
if(obj.complexTypes){var type=node.getAttribute("type");var localType=type.split(":").pop();obj.customTypes[localType]={"name":node.getAttribute("name"),"type":type};}},"simpleType":function(node,obj){this.readChildNodes(node,obj);},"restriction":function(node,obj){obj.base=node.getAttribute("base");this.readRestriction(node,obj);}}},readRestriction:function(node,obj){var children=node.childNodes;var child,nodeName,value;for(var i=0,len=children.length;i<len;++i){child=children[i];if(child.nodeType==1){nodeName=child.nodeName.split(":").pop();value=child.getAttribute("value");if(!obj[nodeName]){obj[nodeName]=value;}else{if(typeof obj[nodeName]=="string"){obj[nodeName]=[obj[nodeName]];}
obj[nodeName].push(value);}}}},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var schema={};this.readNode(data,schema);return schema;},CLASS_NAME:"OpenLayers.Format.WFSDescribeFeatureType"});OpenLayers.Format.WFST.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",wfs:"http://www.opengis.net/wfs",gml:"http://www.opengis.net/gml",ogc:"http://www.opengis.net/ogc"},defaultPrefix:"wfs",version:null,schemaLocations:null,srsName:null,extractAttributes:true,xy:true,stateName:null,initialize:function(options){this.stateName={};this.stateName[OpenLayers.State.INSERT]="wfs:Insert";this.stateName[OpenLayers.State.UPDATE]="wfs:Update";this.stateName[OpenLayers.State.DELETE]="wfs:Delete";OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},getSrsName:function(feature,options){var srsName=options&&options.srsName;if(!srsName){if(feature&&feature.layer){srsName=feature.layer.projection.getCode();}else{srsName=this.srsName;}}
return srsName;},read:function(data,options){options=options||{};OpenLayers.Util.applyDefaults(options,{output:"features"});if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var obj={};if(data){this.readNode(data,obj);}
if(obj.features&&options.output==="features"){obj=obj.features;}
return obj;},readers:{"wfs":{"FeatureCollection":function(node,obj){obj.features=[];this.readChildNodes(node,obj);}}},write:function(features){var node=this.writeNode("wfs:Transaction",features);var value=this.schemaLocationAttr();if(value){this.setAttributeNS(node,this.namespaces["xsi"],"xsi:schemaLocation",value)}
return OpenLayers.Format.XML.prototype.write.apply(this,[node]);},writers:{"wfs":{"GetFeature":function(options){var node=this.createElementNSPlus("wfs:GetFeature",{attributes:{service:"WFS",version:this.version,outputFormat:options&&options.outputFormat,maxFeatures:options&&options.maxFeatures,"xsi:schemaLocation":this.schemaLocationAttr(options)}});if(typeof this.featureType=="string"){this.writeNode("Query",options,node);}else{for(var i=0,len=this.featureType.length;i<len;i++){options.featureType=this.featureType[i];this.writeNode("Query",options,node);}}
return node;},"Transaction":function(features){var node=this.createElementNSPlus("wfs:Transaction",{attributes:{service:"WFS",version:this.version}});if(features){var name,feature;for(var i=0,len=features.length;i<len;++i){feature=features[i];name=this.stateName[feature.state];if(name){this.writeNode(name,feature,node);}}}
return node;},"Insert":function(feature){var node=this.createElementNSPlus("wfs:Insert");this.srsName=this.getSrsName(feature);this.writeNode("feature:_typeName",feature,node);return node;},"Update":function(feature){var node=this.createElementNSPlus("wfs:Update",{attributes:{typeName:(this.featureNS?this.featurePrefix+":":"")+
this.featureType}});if(this.featureNS){node.setAttribute("xmlns:"+this.featurePrefix,this.featureNS);}
if(this.geometryName!==null){this.writeNode("Property",{name:this.geometryName,value:feature},node);}
for(var key in feature.attributes){if(feature.attributes[key]!==undefined){this.writeNode("Property",{name:key,value:feature.attributes[key]},node);}}
this.writeNode("ogc:Filter",new OpenLayers.Filter.FeatureId({fids:[feature.fid]}),node);return node;},"Property":function(obj){var node=this.createElementNSPlus("wfs:Property");this.writeNode("Name",obj.name,node);if(obj.value!==null){this.writeNode("Value",obj.value,node);}
return node;},"Name":function(name){return this.createElementNSPlus("wfs:Name",{value:name});},"Value":function(obj){var node;if(obj instanceof OpenLayers.Feature.Vector){node=this.createElementNSPlus("wfs:Value");this.srsName=this.getSrsName(obj);var geom=this.writeNode("feature:_geometry",obj.geometry).firstChild;node.appendChild(geom);}else{node=this.createElementNSPlus("wfs:Value",{value:obj});}
return node;},"Delete":function(feature){var node=this.createElementNSPlus("wfs:Delete",{attributes:{typeName:(this.featureNS?this.featurePrefix+":":"")+
this.featureType}});if(this.featureNS){node.setAttribute("xmlns:"+this.featurePrefix,this.featureNS);}
this.writeNode("ogc:Filter",new OpenLayers.Filter.FeatureId({fids:[feature.fid]}),node);return node;}}},schemaLocationAttr:function(options){options=OpenLayers.Util.extend({featurePrefix:this.featurePrefix,schema:this.schema},options);var schemaLocations=OpenLayers.Util.extend({},this.schemaLocations);if(options.schema){schemaLocations[options.featurePrefix]=options.schema;}
var parts=[];var uri;for(var key in schemaLocations){uri=this.namespaces[key];if(uri){parts.push(uri+" "+schemaLocations[key]);}}
var value=parts.join(" ")||undefined;return value;},setFilterProperty:function(filter){if(filter.filters){for(var i=0,len=filter.filters.length;i<len;++i){this.setFilterProperty(filter.filters[i]);}}else{if(filter instanceof OpenLayers.Filter.Spatial){filter.property=this.geometryName;}}},CLASS_NAME:"OpenLayers.Format.WFST.v1"});OpenLayers.Format.WMSCapabilities=OpenLayers.Class(OpenLayers.Format.XML,{defaultVersion:"1.1.1",version:null,parser:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);this.options=options;},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;var version=this.version||root.getAttribute("version")||this.defaultVersion;if(!this.parser||this.parser.version!==version){var constr=OpenLayers.Format.WMSCapabilities["v"+version.replace(/\./g,"_")];if(!constr){throw"Can't find a WMS capabilities parser for version "+version;}
this.parser=new constr(this.options);}
var capabilities=this.parser.read(data);capabilities.version=version;return capabilities;},CLASS_NAME:"OpenLayers.Format.WMSCapabilities"});OpenLayers.Format.WMSDescribeLayer=OpenLayers.Class(OpenLayers.Format.XML,{defaultVersion:"1.1.1",version:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);this.options=options;},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;var version=this.version;if(!version){version=root.getAttribute("version");if(!version){version=this.defaultVersion;}}
if(version=="1.1.1"||version=="1.1.0"){version="1.1";}
var constructor=OpenLayers.Format.WMSDescribeLayer["v"+version.replace(/\./g,"_")];if(!constructor){throw"Can't find a WMS DescribeLayer parser for version "+
version;}
var parser=new constructor(this.options);var describelayer=parser.read(data);describelayer.version=version;return describelayer;},CLASS_NAME:"OpenLayers.Format.WMSDescribeLayer"});OpenLayers.Format.WMSGetFeatureInfo=OpenLayers.Class(OpenLayers.Format.XML,{layerIdentifier:'_layer',featureIdentifier:'_feature',regExes:{trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)},gmlFormat:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,arguments);OpenLayers.Util.extend(this,options);this.options=options;},read:function(data){var result;if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;if(root){var scope=this;var read=this["read_"+root.nodeName];if(read){result=read.call(this,root);}else{result=new OpenLayers.Format.GML((this.options?this.options:{})).read(data);}}else{result=data;}
return result;},read_msGMLOutput:function(data){var response=[];var layerNodes=this.getSiblingNodesByTagCriteria(data,this.layerIdentifier);if(layerNodes){for(var i=0,len=layerNodes.length;i<len;++i){var node=layerNodes[i];var layerName=node.nodeName;if(node.prefix){layerName=layerName.split(':')[1];}
var layerName=layerName.replace(this.layerIdentifier,'');var featureNodes=this.getSiblingNodesByTagCriteria(node,this.featureIdentifier);if(featureNodes){for(var j=0;j<featureNodes.length;j++){var featureNode=featureNodes[j];var geomInfo=this.parseGeometry(featureNode);var attributes=this.parseAttributes(featureNode);var feature=new OpenLayers.Feature.Vector(geomInfo.geometry,attributes,null);feature.bounds=geomInfo.bounds;feature.type=layerName;response.push(feature);}}}}
return response;},read_FeatureInfoResponse:function(data){var response=[];var featureNodes=this.getElementsByTagNameNS(data,'*','FIELDS');for(var i=0,len=featureNodes.length;i<len;i++){var featureNode=featureNodes[i];var geom=null;var attributes={};for(var j=0,jlen=featureNode.attributes.length;j<jlen;j++){var attribute=featureNode.attributes[j];attributes[attribute.nodeName]=attribute.nodeValue;}
response.push(new OpenLayers.Feature.Vector(geom,attributes,null));}
return response;},getSiblingNodesByTagCriteria:function(node,criteria){var nodes=[];var children,tagName,n,matchNodes,child;if(node&&node.hasChildNodes()){children=node.childNodes;n=children.length;for(var k=0;k<n;k++){child=children[k];while(child&&child.nodeType!=1){child=child.nextSibling;k++;}
tagName=(child?child.nodeName:'');if(tagName.length>0&&tagName.indexOf(criteria)>-1){nodes.push(child);}else{matchNodes=this.getSiblingNodesByTagCriteria(child,criteria);if(matchNodes.length>0){(nodes.length==0)?nodes=matchNodes:nodes.push(matchNodes);}}}}
return nodes;},parseAttributes:function(node){var attributes={};if(node.nodeType==1){var children=node.childNodes;var n=children.length;for(var i=0;i<n;++i){var child=children[i];if(child.nodeType==1){var grandchildren=child.childNodes;if(grandchildren.length==1){var grandchild=grandchildren[0];if(grandchild.nodeType==3||grandchild.nodeType==4){var name=(child.prefix)?child.nodeName.split(":")[1]:child.nodeName;var value=grandchild.nodeValue.replace(this.regExes.trimSpace,"");attributes[name]=value;}}}}}
return attributes;},parseGeometry:function(node){if(!this.gmlFormat){this.gmlFormat=new OpenLayers.Format.GML();}
var feature=this.gmlFormat.parseFeature(node);var geometry,bounds=null;if(feature){geometry=feature.geometry&&feature.geometry.clone();bounds=feature.bounds&&feature.bounds.clone();feature.destroy();}
return{geometry:geometry,bounds:bounds};},CLASS_NAME:"OpenLayers.Format.WMSGetFeatureInfo"});OpenLayers.Format.WMTSCapabilities=OpenLayers.Class(OpenLayers.Format.XML,{defaultVersion:"1.0.0",version:null,parser:null,yx:{"urn:ogc:def:crs:EPSG::4326":true},initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);this.options=options;},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;var version=this.version||root.getAttribute("version")||this.defaultVersion;if(!this.parser||this.parser.version!==version){var constr=OpenLayers.Format.WMTSCapabilities["v"+version.replace(/\./g,"_")];if(!constr){throw new Error("Can't find a WMTS capabilities parser for version "+version);}
this.parser=new constr(this.options);}
return this.parser.read(data);},createLayer:function(capabilities,config){var layer;var required={layer:true,matrixSet:true};for(var prop in required){if(!(prop in config)){throw new Error("Missing property '"+prop+"' in layer configuration.");}}
var contents=capabilities.contents;var matrixSet=contents.tileMatrixSets[config.matrixSet];var layers=contents.layers;var layerDef;for(var i=0,ii=contents.layers.length;i<ii;++i){if(contents.layers[i].identifier===config.layer){layerDef=contents.layers[i];break;}}
if(layerDef&&matrixSet){var style;for(var i=0,ii=layerDef.styles.length;i<ii;++i){style=layerDef.styles[i];if(style.isDefault){break;}}
layer=new OpenLayers.Layer.WMTS(OpenLayers.Util.applyDefaults(config,{url:capabilities.operationsMetadata.GetTile.dcp.http.get,name:layerDef.title,style:style,matrixIds:matrixSet.matrixIds}));}
return layer;},CLASS_NAME:"OpenLayers.Format.WMTSCapabilities"});OpenLayers.Handler.Click=OpenLayers.Class(OpenLayers.Handler,{delay:300,single:true,'double':false,pixelTolerance:0,stopSingle:false,stopDouble:false,timerId:null,down:null,rightclickTimerId:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);if(this.pixelTolerance!=null){this.mousedown=function(evt){this.down=evt.xy;return true;};}},mousedown:null,mouseup:function(evt){var propagate=true;if(this.checkModifiers(evt)&&this.control.handleRightClicks&&OpenLayers.Event.isRightClick(evt)){propagate=this.rightclick(evt);}
return propagate;},rightclick:function(evt){if(this.passesTolerance(evt)){if(this.rightclickTimerId!=null){this.clearTimer();this.callback('dblrightclick',[evt]);return!this.stopDouble;}else{var clickEvent=this['double']?OpenLayers.Util.extend({},evt):this.callback('rightclick',[evt]);var delayedRightCall=OpenLayers.Function.bind(this.delayedRightCall,this,clickEvent);this.rightclickTimerId=window.setTimeout(delayedRightCall,this.delay);}}
return!this.stopSingle;},delayedRightCall:function(evt){this.rightclickTimerId=null;if(evt){this.callback('rightclick',[evt]);}
return!this.stopSingle;},dblclick:function(evt){if(this.passesTolerance(evt)){if(this["double"]){this.callback('dblclick',[evt]);}
this.clearTimer();}
return!this.stopDouble;},click:function(evt){if(this.passesTolerance(evt)){if(this.timerId!=null){this.clearTimer();}else{var clickEvent=this.single?OpenLayers.Util.extend({},evt):null;this.timerId=window.setTimeout(OpenLayers.Function.bind(this.delayedCall,this,clickEvent),this.delay);}}
return!this.stopSingle;},passesTolerance:function(evt){var passes=true;if(this.pixelTolerance!=null&&this.down){var dpx=Math.sqrt(Math.pow(this.down.x-evt.xy.x,2)+
Math.pow(this.down.y-evt.xy.y,2));if(dpx>this.pixelTolerance){passes=false;}}
return passes;},clearTimer:function(){if(this.timerId!=null){window.clearTimeout(this.timerId);this.timerId=null;}
if(this.rightclickTimerId!=null){window.clearTimeout(this.rightclickTimerId);this.rightclickTimerId=null;}},delayedCall:function(evt){this.timerId=null;if(evt){this.callback('click',[evt]);}},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.clearTimer();this.down=null;deactivated=true;}
return deactivated;},CLASS_NAME:"OpenLayers.Handler.Click"});OpenLayers.Handler.Drag=OpenLayers.Class(OpenLayers.Handler,{started:false,stopDown:true,dragging:false,last:null,start:null,oldOnselectstart:null,interval:0,timeoutId:null,documentDrag:false,documentEvents:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);},down:function(evt){},move:function(evt){},up:function(evt){},out:function(evt){},mousedown:function(evt){var propagate=true;this.dragging=false;if(this.checkModifiers(evt)&&OpenLayers.Event.isLeftClick(evt)){this.started=true;this.start=evt.xy;this.last=evt.xy;OpenLayers.Element.addClass(this.map.viewPortDiv,"olDragDown");this.down(evt);this.callback("down",[evt.xy]);OpenLayers.Event.stop(evt);if(!this.oldOnselectstart){this.oldOnselectstart=(document.onselectstart)?document.onselectstart:OpenLayers.Function.True;}
document.onselectstart=OpenLayers.Function.False;propagate=!this.stopDown;}else{this.started=false;this.start=null;this.last=null;}
return propagate;},mousemove:function(evt){if(this.started&&!this.timeoutId&&(evt.xy.x!=this.last.x||evt.xy.y!=this.last.y)){if(this.documentDrag===true&&this.documentEvents){if(evt.element===document){this.adjustXY(evt);this.setEvent(evt);}else{this.destroyDocumentEvents();}}
if(this.interval>0){this.timeoutId=setTimeout(OpenLayers.Function.bind(this.removeTimeout,this),this.interval);}
this.dragging=true;this.move(evt);this.callback("move",[evt.xy]);if(!this.oldOnselectstart){this.oldOnselectstart=document.onselectstart;document.onselectstart=OpenLayers.Function.False;}
this.last=this.evt.xy;}
return true;},removeTimeout:function(){this.timeoutId=null;},mouseup:function(evt){if(this.started){if(this.documentDrag===true&&this.documentEvents){this.adjustXY(evt);this.destroyDocumentEvents();}
var dragged=(this.start!=this.last);this.started=false;this.dragging=false;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDragDown");this.up(evt);this.callback("up",[evt.xy]);if(dragged){this.callback("done",[evt.xy]);}
document.onselectstart=this.oldOnselectstart;}
return true;},mouseout:function(evt){if(this.started&&OpenLayers.Util.mouseLeft(evt,this.map.div)){if(this.documentDrag===true){this.documentEvents=new OpenLayers.Events(this,document,null,null,{includeXY:true});this.documentEvents.on({mousemove:this.mousemove,mouseup:this.mouseup});OpenLayers.Element.addClass(document.body,"olDragDown");}else{var dragged=(this.start!=this.last);this.started=false;this.dragging=false;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDragDown");this.out(evt);this.callback("out",[]);if(dragged){this.callback("done",[evt.xy]);}
if(document.onselectstart){document.onselectstart=this.oldOnselectstart;}}}
return true;},click:function(evt){return(this.start==this.last);},activate:function(){var activated=false;if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.dragging=false;activated=true;}
return activated;},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.started=false;this.dragging=false;this.start=null;this.last=null;deactivated=true;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDragDown");}
return deactivated;},adjustXY:function(evt){var pos=OpenLayers.Util.pagePosition(this.map.div);evt.xy.x-=pos[0];evt.xy.y-=pos[1];},destroyDocumentEvents:function(){OpenLayers.Element.removeClass(document.body,"olDragDown");this.documentEvents.destroy();this.documentEvents=null;},CLASS_NAME:"OpenLayers.Handler.Drag"});OpenLayers.Handler.Feature=OpenLayers.Class(OpenLayers.Handler,{EVENTMAP:{'click':{'in':'click','out':'clickout'},'mousemove':{'in':'over','out':'out'},'dblclick':{'in':'dblclick','out':null},'mousedown':{'in':null,'out':null},'mouseup':{'in':null,'out':null}},feature:null,lastFeature:null,down:null,up:null,clickTolerance:4,geometryTypes:null,stopClick:true,stopDown:true,stopUp:false,initialize:function(control,layer,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,[control,callbacks,options]);this.layer=layer;},mousedown:function(evt){this.down=evt.xy;return this.handle(evt)?!this.stopDown:true;},mouseup:function(evt){this.up=evt.xy;return this.handle(evt)?!this.stopUp:true;},click:function(evt){return this.handle(evt)?!this.stopClick:true;},mousemove:function(evt){if(!this.callbacks['over']&&!this.callbacks['out']){return true;}
this.handle(evt);return true;},dblclick:function(evt){return!this.handle(evt);},geometryTypeMatches:function(feature){return this.geometryTypes==null||OpenLayers.Util.indexOf(this.geometryTypes,feature.geometry.CLASS_NAME)>-1;},handle:function(evt){if(this.feature&&!this.feature.layer){this.feature=null;}
var type=evt.type;var handled=false;var previouslyIn=!!(this.feature);var click=(type=="click"||type=="dblclick");this.feature=this.layer.getFeatureFromEvent(evt);if(this.feature&&!this.feature.layer){this.feature=null;}
if(this.lastFeature&&!this.lastFeature.layer){this.lastFeature=null;}
if(this.feature){var inNew=(this.feature!=this.lastFeature);if(this.geometryTypeMatches(this.feature)){if(previouslyIn&&inNew){if(this.lastFeature){this.triggerCallback(type,'out',[this.lastFeature]);}
this.triggerCallback(type,'in',[this.feature]);}else if(!previouslyIn||click){this.triggerCallback(type,'in',[this.feature]);}
this.lastFeature=this.feature;handled=true;}else{if(this.lastFeature&&(previouslyIn&&inNew||click)){this.triggerCallback(type,'out',[this.lastFeature]);}
this.feature=null;}}else{if(this.lastFeature&&(previouslyIn||click)){this.triggerCallback(type,'out',[this.lastFeature]);}}
return handled;},triggerCallback:function(type,mode,args){var key=this.EVENTMAP[type][mode];if(key){if(type=='click'&&this.up&&this.down){var dpx=Math.sqrt(Math.pow(this.up.x-this.down.x,2)+
Math.pow(this.up.y-this.down.y,2));if(dpx<=this.clickTolerance){this.callback(key,args);}}else{this.callback(key,args);}}},activate:function(){var activated=false;if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.moveLayerToTop();this.map.events.on({"removelayer":this.handleMapEvents,"changelayer":this.handleMapEvents,scope:this});activated=true;}
return activated;},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.moveLayerBack();this.feature=null;this.lastFeature=null;this.down=null;this.up=null;this.map.events.un({"removelayer":this.handleMapEvents,"changelayer":this.handleMapEvents,scope:this});deactivated=true;}
return deactivated;},handleMapEvents:function(evt){if(!evt.property||evt.property=="order"){this.moveLayerToTop();}},moveLayerToTop:function(){var index=Math.max(this.map.Z_INDEX_BASE['Feature']-1,this.layer.getZIndex())+1;this.layer.setZIndex(index);},moveLayerBack:function(){var index=this.layer.getZIndex()-1;if(index>=this.map.Z_INDEX_BASE['Feature']){this.layer.setZIndex(index);}else{this.map.setLayerZIndex(this.layer,this.map.getLayerIndex(this.layer));}},CLASS_NAME:"OpenLayers.Handler.Feature"});OpenLayers.Handler.Hover=OpenLayers.Class(OpenLayers.Handler,{delay:500,pixelTolerance:null,stopMove:false,px:null,timerId:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);},mousemove:function(evt){if(this.passesTolerance(evt.xy)){this.clearTimer();this.callback('move',[evt]);this.px=evt.xy;evt=OpenLayers.Util.extend({},evt);this.timerId=window.setTimeout(OpenLayers.Function.bind(this.delayedCall,this,evt),this.delay);}
return!this.stopMove;},mouseout:function(evt){if(OpenLayers.Util.mouseLeft(evt,this.map.div)){this.clearTimer();this.callback('move',[evt]);}
return true;},passesTolerance:function(px){var passes=true;if(this.pixelTolerance&&this.px){var dpx=Math.sqrt(Math.pow(this.px.x-px.x,2)+
Math.pow(this.px.y-px.y,2));if(dpx<this.pixelTolerance){passes=false;}}
return passes;},clearTimer:function(){if(this.timerId!=null){window.clearTimeout(this.timerId);this.timerId=null;}},delayedCall:function(evt){this.callback('pause',[evt]);},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.clearTimer();deactivated=true;}
return deactivated;},CLASS_NAME:"OpenLayers.Handler.Hover"});OpenLayers.Handler.Keyboard=OpenLayers.Class(OpenLayers.Handler,{KEY_EVENTS:["keydown","keyup"],eventListener:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);this.eventListener=OpenLayers.Function.bindAsEventListener(this.handleKeyEvent,this);},destroy:function(){this.deactivate();this.eventListener=null;OpenLayers.Handler.prototype.destroy.apply(this,arguments);},activate:function(){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){for(var i=0,len=this.KEY_EVENTS.length;i<len;i++){OpenLayers.Event.observe(document,this.KEY_EVENTS[i],this.eventListener);}
return true;}else{return false;}},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){for(var i=0,len=this.KEY_EVENTS.length;i<len;i++){OpenLayers.Event.stopObserving(document,this.KEY_EVENTS[i],this.eventListener);}
deactivated=true;}
return deactivated;},handleKeyEvent:function(evt){if(this.checkModifiers(evt)){this.callback(evt.type,[evt]);}},CLASS_NAME:"OpenLayers.Handler.Keyboard"});OpenLayers.Handler.MouseWheel=OpenLayers.Class(OpenLayers.Handler,{wheelListener:null,mousePosition:null,interval:0,delta:0,cumulative:true,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);this.wheelListener=OpenLayers.Function.bindAsEventListener(this.onWheelEvent,this);},destroy:function(){OpenLayers.Handler.prototype.destroy.apply(this,arguments);this.wheelListener=null;},onWheelEvent:function(e){if(!this.map||!this.checkModifiers(e)){return;}
var overScrollableDiv=false;var overLayerDiv=false;var overMapDiv=false;var elem=OpenLayers.Event.element(e);while((elem!=null)&&!overMapDiv&&!overScrollableDiv){if(!overScrollableDiv){try{if(elem.currentStyle){overflow=elem.currentStyle["overflow"];}else{var style=document.defaultView.getComputedStyle(elem,null);var overflow=style.getPropertyValue("overflow");}
overScrollableDiv=(overflow&&(overflow=="auto")||(overflow=="scroll"));}catch(err){}}
if(!overLayerDiv){for(var i=0,len=this.map.layers.length;i<len;i++){if(elem==this.map.layers[i].div||elem==this.map.layers[i].pane){overLayerDiv=true;break;}}}
overMapDiv=(elem==this.map.div);elem=elem.parentNode;}
if(!overScrollableDiv&&overMapDiv){if(overLayerDiv){var delta=0;if(!e){e=window.event;}
if(e.wheelDelta){delta=e.wheelDelta/120;if(window.opera&&window.opera.version()<9.2){delta=-delta;}}else if(e.detail){delta=-e.detail/3;}
this.delta=this.delta+delta;if(this.interval){window.clearTimeout(this._timeoutId);this._timeoutId=window.setTimeout(OpenLayers.Function.bind(function(){this.wheelZoom(e);},this),this.interval);}else{this.wheelZoom(e);}}
OpenLayers.Event.stop(e);}},wheelZoom:function(e){var delta=this.delta;this.delta=0;if(delta){if(this.mousePosition){e.xy=this.mousePosition;}
if(!e.xy){e.xy=this.map.getPixelFromLonLat(this.map.getCenter());}
if(delta<0){this.callback("down",[e,this.cumulative?delta:-1]);}else{this.callback("up",[e,this.cumulative?delta:1]);}}},mousemove:function(evt){this.mousePosition=evt.xy;},activate:function(evt){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){var wheelListener=this.wheelListener;OpenLayers.Event.observe(window,"DOMMouseScroll",wheelListener);OpenLayers.Event.observe(window,"mousewheel",wheelListener);OpenLayers.Event.observe(document,"mousewheel",wheelListener);return true;}else{return false;}},deactivate:function(evt){if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){var wheelListener=this.wheelListener;OpenLayers.Event.stopObserving(window,"DOMMouseScroll",wheelListener);OpenLayers.Event.stopObserving(window,"mousewheel",wheelListener);OpenLayers.Event.stopObserving(document,"mousewheel",wheelListener);return true;}else{return false;}},CLASS_NAME:"OpenLayers.Handler.MouseWheel"});OpenLayers.Layer=OpenLayers.Class({id:null,name:null,div:null,opacity:null,alwaysInRange:null,EVENT_TYPES:["loadstart","loadend","loadcancel","visibilitychanged","move","moveend"],RESOLUTION_PROPERTIES:['scales','resolutions','maxScale','minScale','maxResolution','minResolution','numZoomLevels','maxZoomLevel'],events:null,map:null,isBaseLayer:false,alpha:false,displayInLayerSwitcher:true,visibility:true,attribution:null,inRange:false,imageSize:null,imageOffset:null,options:null,eventListeners:null,gutter:0,projection:null,units:null,scales:null,resolutions:null,maxExtent:null,minExtent:null,maxResolution:null,minResolution:null,numZoomLevels:null,minScale:null,maxScale:null,displayOutsideMaxExtent:false,wrapDateLine:false,transitionEffect:null,SUPPORTED_TRANSITIONS:['resize'],metadata:{},initialize:function(name,options){this.addOptions(options);this.name=name;if(this.id==null){this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");this.div=OpenLayers.Util.createDiv(this.id);this.div.style.width="100%";this.div.style.height="100%";this.div.dir="ltr";this.events=new OpenLayers.Events(this,this.div,this.EVENT_TYPES);if(this.eventListeners instanceof Object){this.events.on(this.eventListeners);}}
if(this.wrapDateLine){this.displayOutsideMaxExtent=true;}},destroy:function(setNewBaseLayer){if(setNewBaseLayer==null){setNewBaseLayer=true;}
if(this.map!=null){this.map.removeLayer(this,setNewBaseLayer);}
this.projection=null;this.map=null;this.name=null;this.div=null;this.options=null;if(this.events){if(this.eventListeners){this.events.un(this.eventListeners);}
this.events.destroy();}
this.eventListeners=null;this.events=null;},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer(this.name,this.getOptions());}
OpenLayers.Util.applyDefaults(obj,this);obj.map=null;return obj;},getOptions:function(){var options={};for(var o in this.options){options[o]=this[o];}
return options;},setName:function(newName){if(newName!=this.name){this.name=newName;if(this.map!=null){this.map.events.triggerEvent("changelayer",{layer:this,property:"name"});}}},addOptions:function(newOptions){if(this.options==null){this.options={};}
OpenLayers.Util.extend(this.options,newOptions);OpenLayers.Util.extend(this,newOptions);if(typeof this.projection=="string"){this.projection=new OpenLayers.Projection(this.projection);}
if(this.projection&&this.projection.getUnits()){this.units=this.projection.getUnits();}
if(this.map){var properties=this.RESOLUTION_PROPERTIES.concat(["projection","units","minExtent","maxExtent"]);for(var o in newOptions){if(newOptions.hasOwnProperty(o)&&OpenLayers.Util.indexOf(properties,o)>=0){this.initResolutions();break;}}}},onMapResize:function(){},redraw:function(){var redrawn=false;if(this.map){this.inRange=this.calculateInRange();var extent=this.getExtent();if(extent&&this.inRange&&this.visibility){var zoomChanged=true;this.moveTo(extent,zoomChanged,false);this.events.triggerEvent("moveend",{"zoomChanged":zoomChanged});redrawn=true;}}
return redrawn;},moveTo:function(bounds,zoomChanged,dragging){var display=this.visibility;if(!this.isBaseLayer){display=display&&this.inRange;}
this.display(display);},setMap:function(map){if(this.map==null){this.map=map;this.maxExtent=this.maxExtent||this.map.maxExtent;this.minExtent=this.minExtent||this.map.minExtent;this.projection=this.projection||this.map.projection;if(typeof this.projection=="string"){this.projection=new OpenLayers.Projection(this.projection);}
this.units=this.projection.getUnits()||this.units||this.map.units;this.initResolutions();if(!this.isBaseLayer){this.inRange=this.calculateInRange();var show=((this.visibility)&&(this.inRange));this.div.style.display=show?"":"none";}
this.setTileSize();}},afterAdd:function(){},removeMap:function(map){},getImageSize:function(bounds){return(this.imageSize||this.tileSize);},setTileSize:function(size){var tileSize=(size)?size:((this.tileSize)?this.tileSize:this.map.getTileSize());this.tileSize=tileSize;if(this.gutter){this.imageOffset=new OpenLayers.Pixel(-this.gutter,-this.gutter);this.imageSize=new OpenLayers.Size(tileSize.w+(2*this.gutter),tileSize.h+(2*this.gutter));}},getVisibility:function(){return this.visibility;},setVisibility:function(visibility){if(visibility!=this.visibility){this.visibility=visibility;this.display(visibility);this.redraw();if(this.map!=null){this.map.events.triggerEvent("changelayer",{layer:this,property:"visibility"});}
this.events.triggerEvent("visibilitychanged");}},display:function(display){if(display!=(this.div.style.display!="none")){this.div.style.display=(display&&this.calculateInRange())?"block":"none";}},calculateInRange:function(){var inRange=false;if(this.alwaysInRange){inRange=true;}else{if(this.map){var resolution=this.map.getResolution();inRange=((resolution>=this.minResolution)&&(resolution<=this.maxResolution));}}
return inRange;},setIsBaseLayer:function(isBaseLayer){if(isBaseLayer!=this.isBaseLayer){this.isBaseLayer=isBaseLayer;if(this.map!=null){this.map.events.triggerEvent("changebaselayer",{layer:this});}}},initResolutions:function(){var i,len;var props={},alwaysInRange=true;for(i=0,len=this.RESOLUTION_PROPERTIES.length;i<len;i++){var p=this.RESOLUTION_PROPERTIES[i];props[p]=this.options[p];if(alwaysInRange&&this.options[p]){alwaysInRange=false;}}
if(this.alwaysInRange==null){this.alwaysInRange=alwaysInRange;}
if(props.resolutions==null){props.resolutions=this.resolutionsFromScales(props.scales);}
if(props.resolutions==null){props.resolutions=this.calculateResolutions(props);}
if(props.resolutions==null){for(i=0,len=this.RESOLUTION_PROPERTIES.length;i<len;i++){var p=this.RESOLUTION_PROPERTIES[i];props[p]=this.options[p]!=null?this.options[p]:this.map[p];}
if(props.resolutions==null){props.resolutions=this.resolutionsFromScales(props.scales);}
if(props.resolutions==null){props.resolutions=this.calculateResolutions(props);}}
var maxResolution;if(this.options.maxResolution&&this.options.maxResolution!=="auto"){maxResolution=this.options.maxResolution;}
if(this.options.minScale){maxResolution=OpenLayers.Util.getResolutionFromScale(this.options.minScale,this.units);}
var minResolution;if(this.options.minResolution&&this.options.minResolution!=="auto"){minResolution=this.options.minResolution;}
if(this.options.maxScale){minResolution=OpenLayers.Util.getResolutionFromScale(this.options.maxScale,this.units);}
if(props.resolutions){props.resolutions.sort(function(a,b){return(b-a);});if(!maxResolution){maxResolution=props.resolutions[0];}
if(!minResolution){var lastIdx=props.resolutions.length-1;minResolution=props.resolutions[lastIdx];}}
this.resolutions=props.resolutions;if(this.resolutions){len=this.resolutions.length;this.scales=new Array(len);for(i=0;i<len;i++){this.scales[i]=OpenLayers.Util.getScaleFromResolution(this.resolutions[i],this.units);}
this.numZoomLevels=len;}
this.minResolution=minResolution;if(minResolution){this.maxScale=OpenLayers.Util.getScaleFromResolution(minResolution,this.units);}
this.maxResolution=maxResolution;if(maxResolution){this.minScale=OpenLayers.Util.getScaleFromResolution(maxResolution,this.units);}},resolutionsFromScales:function(scales){if(scales==null){return;}
var resolutions,i,len;len=scales.length;resolutions=new Array(len);for(i=0;i<len;i++){resolutions[i]=OpenLayers.Util.getResolutionFromScale(scales[i],this.units);}
return resolutions;},calculateResolutions:function(props){var maxResolution=props.maxResolution;if(props.minScale!=null){maxResolution=OpenLayers.Util.getResolutionFromScale(props.minScale,this.units);}else if(maxResolution=="auto"&&this.maxExtent!=null){var viewSize=this.map.getSize();var wRes=this.maxExtent.getWidth()/viewSize.w;var hRes=this.maxExtent.getHeight()/viewSize.h;maxResolution=Math.max(wRes,hRes);}
var minResolution=props.minResolution;if(props.maxScale!=null){minResolution=OpenLayers.Util.getResolutionFromScale(props.maxScale,this.units);}else if(props.minResolution=="auto"&&this.minExtent!=null){var viewSize=this.map.getSize();var wRes=this.minExtent.getWidth()/viewSize.w;var hRes=this.minExtent.getHeight()/viewSize.h;minResolution=Math.max(wRes,hRes);}
var maxZoomLevel=props.maxZoomLevel;var numZoomLevels=props.numZoomLevels;if(typeof minResolution==="number"&&typeof maxResolution==="number"&&numZoomLevels===undefined){var ratio=maxResolution/minResolution;numZoomLevels=Math.floor(Math.log(ratio)/Math.log(2))+1;}else if(numZoomLevels===undefined&&maxZoomLevel!=null){numZoomLevels=maxZoomLevel+1;}
if(typeof numZoomLevels!=="number"||numZoomLevels<=0||(typeof maxResolution!=="number"&&typeof minResolution!=="number")){return;}
var resolutions=new Array(numZoomLevels);var base=2;if(typeof minResolution=="number"&&typeof maxResolution=="number"){base=Math.pow((maxResolution/minResolution),(1/(numZoomLevels-1)));}
var i;if(typeof maxResolution==="number"){for(i=0;i<numZoomLevels;i++){resolutions[i]=maxResolution/Math.pow(base,i);}}else{for(i=0;i<numZoomLevels;i++){resolutions[numZoomLevels-1-i]=minResolution*Math.pow(base,i);}}
return resolutions;},getResolution:function(){var zoom=this.map.getZoom();return this.getResolutionForZoom(zoom);},getExtent:function(){return this.map.calculateBounds();},getZoomForExtent:function(extent,closest){var viewSize=this.map.getSize();var idealResolution=Math.max(extent.getWidth()/viewSize.w,extent.getHeight()/viewSize.h);return this.getZoomForResolution(idealResolution,closest);},getDataExtent:function(){},getResolutionForZoom:function(zoom){zoom=Math.max(0,Math.min(zoom,this.resolutions.length-1));var resolution;if(this.map.fractionalZoom){var low=Math.floor(zoom);var high=Math.ceil(zoom);resolution=this.resolutions[low]-
((zoom-low)*(this.resolutions[low]-this.resolutions[high]));}else{resolution=this.resolutions[Math.round(zoom)];}
return resolution;},getZoomForResolution:function(resolution,closest){var zoom;if(this.map.fractionalZoom){var lowZoom=0;var highZoom=this.resolutions.length-1;var highRes=this.resolutions[lowZoom];var lowRes=this.resolutions[highZoom];var res;for(var i=0,len=this.resolutions.length;i<len;++i){res=this.resolutions[i];if(res>=resolution){highRes=res;lowZoom=i;}
if(res<=resolution){lowRes=res;highZoom=i;break;}}
var dRes=highRes-lowRes;if(dRes>0){zoom=lowZoom+((highRes-resolution)/dRes);}else{zoom=lowZoom;}}else{var diff;var minDiff=Number.POSITIVE_INFINITY;for(var i=0,len=this.resolutions.length;i<len;i++){if(closest){diff=Math.abs(this.resolutions[i]-resolution);if(diff>minDiff){break;}
minDiff=diff;}else{if(this.resolutions[i]<resolution){break;}}}
zoom=Math.max(0,i-1);}
return zoom;},getLonLatFromViewPortPx:function(viewPortPx){var lonlat=null;if(viewPortPx!=null){var size=this.map.getSize();var center=this.map.getCenter();if(center){var res=this.map.getResolution();var delta_x=viewPortPx.x-(size.w/2);var delta_y=viewPortPx.y-(size.h/2);lonlat=new OpenLayers.LonLat(center.lon+delta_x*res,center.lat-delta_y*res);if(this.wrapDateLine){lonlat=lonlat.wrapDateLine(this.maxExtent);}}}
return lonlat;},getViewPortPxFromLonLat:function(lonlat){var px=null;if(lonlat!=null){var resolution=this.map.getResolution();var extent=this.map.getExtent();px=new OpenLayers.Pixel((1/resolution*(lonlat.lon-extent.left)),(1/resolution*(extent.top-lonlat.lat)));}
return px;},setOpacity:function(opacity){if(opacity!=this.opacity){this.opacity=opacity;for(var i=0,len=this.div.childNodes.length;i<len;++i){var element=this.div.childNodes[i].firstChild;OpenLayers.Util.modifyDOMElement(element,null,null,null,null,null,null,opacity);}
if(this.map!=null){this.map.events.triggerEvent("changelayer",{layer:this,property:"opacity"});}}},getZIndex:function(){return this.div.style.zIndex;},setZIndex:function(zIndex){this.div.style.zIndex=zIndex;},adjustBounds:function(bounds){if(this.gutter){var mapGutter=this.gutter*this.map.getResolution();bounds=new OpenLayers.Bounds(bounds.left-mapGutter,bounds.bottom-mapGutter,bounds.right+mapGutter,bounds.top+mapGutter);}
if(this.wrapDateLine){var wrappingOptions={'rightTolerance':this.getResolution()};bounds=bounds.wrapDateLine(this.maxExtent,wrappingOptions);}
return bounds;},CLASS_NAME:"OpenLayers.Layer"});OpenLayers.Marker.Box=OpenLayers.Class(OpenLayers.Marker,{bounds:null,div:null,initialize:function(bounds,borderColor,borderWidth){this.bounds=bounds;this.div=OpenLayers.Util.createDiv();this.div.style.overflow='hidden';this.events=new OpenLayers.Events(this,this.div,null);this.setBorder(borderColor,borderWidth);},destroy:function(){this.bounds=null;this.div=null;OpenLayers.Marker.prototype.destroy.apply(this,arguments);},setBorder:function(color,width){if(!color){color="red";}
if(!width){width=2;}
this.div.style.border=width+"px solid "+color;},draw:function(px,sz){OpenLayers.Util.modifyDOMElement(this.div,null,px,sz);return this.div;},onScreen:function(){var onScreen=false;if(this.map){var screenBounds=this.map.getExtent();onScreen=screenBounds.containsBounds(this.bounds,true,true);}
return onScreen;},display:function(display){this.div.style.display=(display)?"":"none";},CLASS_NAME:"OpenLayers.Marker.Box"});(function(){var oXMLHttpRequest=window.XMLHttpRequest;var bGecko=!!window.controllers,bIE=window.document.all&&!window.opera,bIE7=bIE&&window.navigator.userAgent.match(/MSIE ([\.0-9]+)/)&&RegExp.$1==7;function cXMLHttpRequest(){this._object=oXMLHttpRequest&&!bIE7?new oXMLHttpRequest:new window.ActiveXObject("Microsoft.XMLHTTP");this._listeners=[];};if(bGecko&&oXMLHttpRequest.wrapped)
cXMLHttpRequest.wrapped=oXMLHttpRequest.wrapped;cXMLHttpRequest.UNSENT=0;cXMLHttpRequest.OPENED=1;cXMLHttpRequest.HEADERS_RECEIVED=2;cXMLHttpRequest.LOADING=3;cXMLHttpRequest.DONE=4;cXMLHttpRequest.prototype.readyState=cXMLHttpRequest.UNSENT;cXMLHttpRequest.prototype.responseText='';cXMLHttpRequest.prototype.responseXML=null;cXMLHttpRequest.prototype.status=0;cXMLHttpRequest.prototype.statusText='';cXMLHttpRequest.prototype.onreadystatechange=null;cXMLHttpRequest.onreadystatechange=null;cXMLHttpRequest.onopen=null;cXMLHttpRequest.onsend=null;cXMLHttpRequest.onabort=null;cXMLHttpRequest.prototype.open=function(sMethod,sUrl,bAsync,sUser,sPassword){delete this._headers;if(arguments.length<3)
bAsync=true;this._async=bAsync;var oRequest=this,nState=this.readyState,fOnUnload;if(bIE&&bAsync){fOnUnload=function(){if(nState!=cXMLHttpRequest.DONE){fCleanTransport(oRequest);oRequest.abort();}};window.attachEvent("onunload",fOnUnload);}
if(cXMLHttpRequest.onopen)
cXMLHttpRequest.onopen.apply(this,arguments);if(arguments.length>4)
this._object.open(sMethod,sUrl,bAsync,sUser,sPassword);else
if(arguments.length>3)
this._object.open(sMethod,sUrl,bAsync,sUser);else
this._object.open(sMethod,sUrl,bAsync);if(!bGecko&&!bIE){this.readyState=cXMLHttpRequest.OPENED;fReadyStateChange(this);}
this._object.onreadystatechange=function(){if(bGecko&&!bAsync)
return;oRequest.readyState=oRequest._object.readyState;fSynchronizeValues(oRequest);if(oRequest._aborted){oRequest.readyState=cXMLHttpRequest.UNSENT;return;}
if(oRequest.readyState==cXMLHttpRequest.DONE){fCleanTransport(oRequest);if(bIE&&bAsync)
window.detachEvent("onunload",fOnUnload);}
if(nState!=oRequest.readyState)
fReadyStateChange(oRequest);nState=oRequest.readyState;}};cXMLHttpRequest.prototype.send=function(vData){if(cXMLHttpRequest.onsend)
cXMLHttpRequest.onsend.apply(this,arguments);if(vData&&vData.nodeType){vData=window.XMLSerializer?new window.XMLSerializer().serializeToString(vData):vData.xml;if(!this._headers["Content-Type"])
this._object.setRequestHeader("Content-Type","application/xml");}
this._object.send(vData);if(bGecko&&!this._async){this.readyState=cXMLHttpRequest.OPENED;fSynchronizeValues(this);while(this.readyState<cXMLHttpRequest.DONE){this.readyState++;fReadyStateChange(this);if(this._aborted)
return;}}};cXMLHttpRequest.prototype.abort=function(){if(cXMLHttpRequest.onabort)
cXMLHttpRequest.onabort.apply(this,arguments);if(this.readyState>cXMLHttpRequest.UNSENT)
this._aborted=true;this._object.abort();fCleanTransport(this);};cXMLHttpRequest.prototype.getAllResponseHeaders=function(){return this._object.getAllResponseHeaders();};cXMLHttpRequest.prototype.getResponseHeader=function(sName){return this._object.getResponseHeader(sName);};cXMLHttpRequest.prototype.setRequestHeader=function(sName,sValue){if(!this._headers)
this._headers={};this._headers[sName]=sValue;return this._object.setRequestHeader(sName,sValue);};cXMLHttpRequest.prototype.addEventListener=function(sName,fHandler,bUseCapture){for(var nIndex=0,oListener;oListener=this._listeners[nIndex];nIndex++)
if(oListener[0]==sName&&oListener[1]==fHandler&&oListener[2]==bUseCapture)
return;this._listeners.push([sName,fHandler,bUseCapture]);};cXMLHttpRequest.prototype.removeEventListener=function(sName,fHandler,bUseCapture){for(var nIndex=0,oListener;oListener=this._listeners[nIndex];nIndex++)
if(oListener[0]==sName&&oListener[1]==fHandler&&oListener[2]==bUseCapture)
break;if(oListener)
this._listeners.splice(nIndex,1);};cXMLHttpRequest.prototype.dispatchEvent=function(oEvent){var oEventPseudo={'type':oEvent.type,'target':this,'currentTarget':this,'eventPhase':2,'bubbles':oEvent.bubbles,'cancelable':oEvent.cancelable,'timeStamp':oEvent.timeStamp,'stopPropagation':function(){},'preventDefault':function(){},'initEvent':function(){}};if(oEventPseudo.type=="readystatechange"&&this.onreadystatechange)
(this.onreadystatechange.handleEvent||this.onreadystatechange).apply(this,[oEventPseudo]);for(var nIndex=0,oListener;oListener=this._listeners[nIndex];nIndex++)
if(oListener[0]==oEventPseudo.type&&!oListener[2])
(oListener[1].handleEvent||oListener[1]).apply(this,[oEventPseudo]);};cXMLHttpRequest.prototype.toString=function(){return'['+"object"+' '+"XMLHttpRequest"+']';};cXMLHttpRequest.toString=function(){return'['+"XMLHttpRequest"+']';};function fReadyStateChange(oRequest){if(cXMLHttpRequest.onreadystatechange)
cXMLHttpRequest.onreadystatechange.apply(oRequest);oRequest.dispatchEvent({'type':"readystatechange",'bubbles':false,'cancelable':false,'timeStamp':new Date+0});};function fGetDocument(oRequest){var oDocument=oRequest.responseXML,sResponse=oRequest.responseText;if(bIE&&sResponse&&oDocument&&!oDocument.documentElement&&oRequest.getResponseHeader("Content-Type").match(/[^\/]+\/[^\+]+\+xml/)){oDocument=new window.ActiveXObject("Microsoft.XMLDOM");oDocument.async=false;oDocument.validateOnParse=false;oDocument.loadXML(sResponse);}
if(oDocument)
if((bIE&&oDocument.parseError!=0)||!oDocument.documentElement||(oDocument.documentElement&&oDocument.documentElement.tagName=="parsererror"))
return null;return oDocument;};function fSynchronizeValues(oRequest){try{oRequest.responseText=oRequest._object.responseText;}catch(e){}
try{oRequest.responseXML=fGetDocument(oRequest._object);}catch(e){}
try{oRequest.status=oRequest._object.status;}catch(e){}
try{oRequest.statusText=oRequest._object.statusText;}catch(e){}};function fCleanTransport(oRequest){oRequest._object.onreadystatechange=new window.Function;};if(!window.Function.prototype.apply){window.Function.prototype.apply=function(oRequest,oArguments){if(!oArguments)
oArguments=[];oRequest.__func=this;oRequest.__func(oArguments[0],oArguments[1],oArguments[2],oArguments[3],oArguments[4]);delete oRequest.__func;};};OpenLayers.Request.XMLHttpRequest=cXMLHttpRequest;})();OpenLayers.Tile.Image.IFrame=OpenLayers.Class(OpenLayers.Tile.Image,{initialize:function(layer,position,bounds,url,size){OpenLayers.Tile.Image.prototype.initialize.apply(this,arguments);this.layerAlphaHack=false;},destroy:function(){if(this.imgDiv!=null){OpenLayers.Event.stopObservingElement(this.imgDiv.firstChild);}
OpenLayers.Tile.Image.prototype.destroy.apply(this,arguments);},clear:function(){if(this.imgDiv){var iFrame=this.imgDiv.firstChild;OpenLayers.Event.stopObservingElement(iFrame);this.imgDiv.removeChild(iFrame);}},clone:function(obj){if(obj==null){obj=new OpenLayers.Tile.Image.IFrame(this.layer,this.position,this.bounds,this.url,this.size);}
obj=OpenLayers.Tile.Image.prototype.clone.apply(this,[obj]);return obj;},renderTile:function(){if(OpenLayers.Tile.Image.prototype.renderTile.apply(this,arguments)){var form=this.createRequestForm();this.imgDiv.appendChild(form);form.submit();this.imgDiv.removeChild(form);}},initImgDiv:function(){this.imgDiv=this.createImgDiv();OpenLayers.Util.modifyDOMElement(this.imgDiv,this.id,null,this.layer.getImageSize(),"relative");this.imgDiv.className='olTileImage';this.frame.appendChild(this.imgDiv);this.layer.div.appendChild(this.frame);if(this.layer.opacity!=null){OpenLayers.Util.modifyDOMElement(this.imgDiv,null,null,null,null,null,null,this.layer.opacity);}
this.imgDiv.map=this.layer.map;},createImgDiv:function(){var eventPane=document.createElement("div");if(OpenLayers.Util.getBrowserName()=="msie"){eventPane.style.backgroundColor='#FFFFFF';eventPane.style.filter='chroma(color=#FFFFFF)';}
OpenLayers.Util.modifyDOMElement(eventPane,null,new OpenLayers.Pixel(0,0),this.layer.getImageSize(),"absolute");var imgDiv=document.createElement("div");imgDiv.appendChild(eventPane);return imgDiv;},createIFrame:function(){var id=this.id+'_iFrame';var iframe;if(OpenLayers.Util.getBrowserName()=="msie"){iframe=document.createElement('<iframe name="'+id+'">');iframe.style.backgroundColor='#FFFFFF';iframe.style.filter='chroma(color=#FFFFFF)';}
else{iframe=document.createElement('iframe');iframe.style.backgroundColor='transparent';iframe.name=id;}
iframe.id=id;iframe.scrolling='no';iframe.marginWidth='0px';iframe.marginHeight='0px';iframe.frameBorder='0';OpenLayers.Util.modifyDOMElement(iframe,id,new OpenLayers.Pixel(0,0),this.layer.getImageSize(),"absolute");var onload=function(){this.show();if(this.isLoading){this.isLoading=false;this.events.triggerEvent("loadend");}};OpenLayers.Event.observe(iframe,'load',OpenLayers.Function.bind(onload,this));return iframe;},createRequestForm:function(){var form=document.createElement('form');form.method='POST';var cacheId=this.layer.params["_OLSALT"];cacheId=(cacheId?cacheId+"_":"")+this.bounds.toBBOX();form.action=OpenLayers.Util.urlAppend(this.layer.url,cacheId);this.imgDiv.insertBefore(this.createIFrame(),this.imgDiv.firstChild);form.target=this.id+'_iFrame';var imageSize=this.layer.getImageSize();var params=OpenLayers.Util.extend({"BBOX":this.encodeBBOX?this.bounds.toBBOX():this.bounds.toArray(),"WIDTH":imageSize.w,"HEIGHT":imageSize.h},this.layer.params);for(var par in params){var field=document.createElement('input');field.type='hidden';field.name=par;field.value=params[par];form.appendChild(field);}
return form;},CLASS_NAME:"OpenLayers.Tile.Image.IFrame"});OpenLayers.ProxyHost="";OpenLayers.nullHandler=function(request){OpenLayers.Console.userError(OpenLayers.i18n("unhandledRequest",{'statusText':request.statusText}));};OpenLayers.loadURL=function(uri,params,caller,onComplete,onFailure){if(typeof params=='string'){params=OpenLayers.Util.getParameters(params);}
var success=(onComplete)?onComplete:OpenLayers.nullHandler;var failure=(onFailure)?onFailure:OpenLayers.nullHandler;return OpenLayers.Request.GET({url:uri,params:params,success:success,failure:failure,scope:caller});};OpenLayers.parseXMLString=function(text){var index=text.indexOf('<');if(index>0){text=text.substring(index);}
var ajaxResponse=OpenLayers.Util.Try(function(){var xmldom=new ActiveXObject('Microsoft.XMLDOM');xmldom.loadXML(text);return xmldom;},function(){return new DOMParser().parseFromString(text,'text/xml');},function(){var req=new XMLHttpRequest();req.open("GET","data:"+"text/xml"+";charset=utf-8,"+encodeURIComponent(text),false);if(req.overrideMimeType){req.overrideMimeType("text/xml");}
req.send(null);return req.responseXML;});return ajaxResponse;};OpenLayers.Ajax={emptyFunction:function(){},getTransport:function(){return OpenLayers.Util.Try(function(){return new XMLHttpRequest();},function(){return new ActiveXObject('Msxml2.XMLHTTP');},function(){return new ActiveXObject('Microsoft.XMLHTTP');})||false;},activeRequestCount:0};OpenLayers.Ajax.Responders={responders:[],register:function(responderToAdd){for(var i=0;i<this.responders.length;i++){if(responderToAdd==this.responders[i]){return;}}
this.responders.push(responderToAdd);},unregister:function(responderToRemove){OpenLayers.Util.removeItem(this.reponders,responderToRemove);},dispatch:function(callback,request,transport){var responder;for(var i=0;i<this.responders.length;i++){responder=this.responders[i];if(responder[callback]&&typeof responder[callback]=='function'){try{responder[callback].apply(responder,[request,transport]);}catch(e){}}}}};OpenLayers.Ajax.Responders.register({onCreate:function(){OpenLayers.Ajax.activeRequestCount++;},onComplete:function(){OpenLayers.Ajax.activeRequestCount--;}});OpenLayers.Ajax.Base=OpenLayers.Class({initialize:function(options){this.options={method:'post',asynchronous:true,contentType:'application/xml',parameters:''};OpenLayers.Util.extend(this.options,options||{});this.options.method=this.options.method.toLowerCase();if(typeof this.options.parameters=='string'){this.options.parameters=OpenLayers.Util.getParameters(this.options.parameters);}}});OpenLayers.Ajax.Request=OpenLayers.Class(OpenLayers.Ajax.Base,{_complete:false,initialize:function(url,options){OpenLayers.Ajax.Base.prototype.initialize.apply(this,[options]);if(OpenLayers.ProxyHost&&OpenLayers.String.startsWith(url,"http")){url=OpenLayers.ProxyHost+encodeURIComponent(url);}
this.transport=OpenLayers.Ajax.getTransport();this.request(url);},request:function(url){this.url=url;this.method=this.options.method;var params=OpenLayers.Util.extend({},this.options.parameters);if(this.method!='get'&&this.method!='post'){params['_method']=this.method;this.method='post';}
this.parameters=params;if(params=OpenLayers.Util.getParameterString(params)){if(this.method=='get'){this.url+=((this.url.indexOf('?')>-1)?'&':'?')+params;}else if(/Konqueror|Safari|KHTML/.test(navigator.userAgent)){params+='&_=';}}
try{var response=new OpenLayers.Ajax.Response(this);if(this.options.onCreate){this.options.onCreate(response);}
OpenLayers.Ajax.Responders.dispatch('onCreate',this,response);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous){window.setTimeout(OpenLayers.Function.bind(this.respondToReadyState,this,1),10);}
this.transport.onreadystatechange=OpenLayers.Function.bind(this.onStateChange,this);this.setRequestHeaders();this.body=this.method=='post'?(this.options.postBody||params):null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType){this.onStateChange();}}catch(e){this.dispatchException(e);}},onStateChange:function(){var readyState=this.transport.readyState;if(readyState>1&&!((readyState==4)&&this._complete)){this.respondToReadyState(this.transport.readyState);}},setRequestHeaders:function(){var headers={'X-Requested-With':'XMLHttpRequest','Accept':'text/javascript, text/html, application/xml, text/xml, */*','OpenLayers':true};if(this.method=='post'){headers['Content-type']=this.options.contentType+
(this.options.encoding?'; charset='+this.options.encoding:'');if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005){headers['Connection']='close';}}
if(typeof this.options.requestHeaders=='object'){var extras=this.options.requestHeaders;if(typeof extras.push=='function'){for(var i=0,length=extras.length;i<length;i+=2){headers[extras[i]]=extras[i+1];}}else{for(var i in extras){headers[i]=extras[i];}}}
for(var name in headers){this.transport.setRequestHeader(name,headers[name]);}},success:function(){var status=this.getStatus();return!status||(status>=200&&status<300);},getStatus:function(){try{return this.transport.status||0;}catch(e){return 0;}},respondToReadyState:function(readyState){var state=OpenLayers.Ajax.Request.Events[readyState];var response=new OpenLayers.Ajax.Response(this);if(state=='Complete'){try{this._complete=true;(this.options['on'+response.status]||this.options['on'+(this.success()?'Success':'Failure')]||OpenLayers.Ajax.emptyFunction)(response);}catch(e){this.dispatchException(e);}
var contentType=response.getHeader('Content-type');}
try{(this.options['on'+state]||OpenLayers.Ajax.emptyFunction)(response);OpenLayers.Ajax.Responders.dispatch('on'+state,this,response);}catch(e){this.dispatchException(e);}
if(state=='Complete'){this.transport.onreadystatechange=OpenLayers.Ajax.emptyFunction;}},getHeader:function(name){try{return this.transport.getResponseHeader(name);}catch(e){return null;}},dispatchException:function(exception){var handler=this.options.onException;if(handler){handler(this,exception);OpenLayers.Ajax.Responders.dispatch('onException',this,exception);}else{var listener=false;var responders=OpenLayers.Ajax.Responders.responders;for(var i=0;i<responders.length;i++){if(responders[i].onException){listener=true;break;}}
if(listener){OpenLayers.Ajax.Responders.dispatch('onException',this,exception);}else{throw exception;}}}});OpenLayers.Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];OpenLayers.Ajax.Response=OpenLayers.Class({status:0,statusText:'',initialize:function(request){this.request=request;var transport=this.transport=request.transport,readyState=this.readyState=transport.readyState;if((readyState>2&&!(!!(window.attachEvent&&!window.opera)))||readyState==4){this.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=transport.responseText==null?'':String(transport.responseText);}
if(readyState==4){var xml=transport.responseXML;this.responseXML=xml===undefined?null:xml;}},getStatus:OpenLayers.Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||'';}catch(e){return'';}},getHeader:OpenLayers.Ajax.Request.prototype.getHeader,getResponseHeader:function(name){return this.transport.getResponseHeader(name);}});OpenLayers.Ajax.getElementsByTagNameNS=function(parentnode,nsuri,nsprefix,tagname){var elem=null;if(parentnode.getElementsByTagNameNS){elem=parentnode.getElementsByTagNameNS(nsuri,tagname);}else{elem=parentnode.getElementsByTagName(nsprefix+':'+tagname);}
return elem;};OpenLayers.Ajax.serializeXMLToString=function(xmldom){var serializer=new XMLSerializer();var data=serializer.serializeToString(xmldom);return data;};OpenLayers.Control.DragFeature=OpenLayers.Class(OpenLayers.Control,{geometryTypes:null,onStart:function(feature,pixel){},onDrag:function(feature,pixel){},onComplete:function(feature,pixel){},documentDrag:false,layer:null,feature:null,dragCallbacks:{},featureCallbacks:{},lastPixel:null,initialize:function(layer,options){OpenLayers.Control.prototype.initialize.apply(this,[options]);this.layer=layer;this.handlers={drag:new OpenLayers.Handler.Drag(this,OpenLayers.Util.extend({down:this.downFeature,move:this.moveFeature,up:this.upFeature,out:this.cancel,done:this.doneDragging},this.dragCallbacks),{documentDrag:this.documentDrag}),feature:new OpenLayers.Handler.Feature(this,this.layer,OpenLayers.Util.extend({over:this.overFeature,out:this.outFeature},this.featureCallbacks),{geometryTypes:this.geometryTypes})};},destroy:function(){this.layer=null;OpenLayers.Control.prototype.destroy.apply(this,[]);},activate:function(){return(this.handlers.feature.activate()&&OpenLayers.Control.prototype.activate.apply(this,arguments));},deactivate:function(){this.handlers.drag.deactivate();this.handlers.feature.deactivate();this.feature=null;this.dragging=false;this.lastPixel=null;OpenLayers.Element.removeClass(this.map.viewPortDiv,this.displayClass+"Over");return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},overFeature:function(feature){if(!this.handlers.drag.dragging){this.feature=feature;this.handlers.drag.activate();this.over=true;OpenLayers.Element.addClass(this.map.viewPortDiv,this.displayClass+"Over");}else{if(this.feature.id==feature.id){this.over=true;}else{this.over=false;}}},downFeature:function(pixel){this.lastPixel=pixel;this.onStart(this.feature,pixel);},moveFeature:function(pixel){var res=this.map.getResolution();this.feature.geometry.move(res*(pixel.x-this.lastPixel.x),res*(this.lastPixel.y-pixel.y));this.layer.drawFeature(this.feature);this.lastPixel=pixel;this.onDrag(this.feature,pixel);},upFeature:function(pixel){if(!this.over){this.handlers.drag.deactivate();}},doneDragging:function(pixel){this.onComplete(this.feature,pixel);},outFeature:function(feature){if(!this.handlers.drag.dragging){this.over=false;this.handlers.drag.deactivate();OpenLayers.Element.removeClass(this.map.viewPortDiv,this.displayClass+"Over");this.feature=null;}else{if(this.feature.id==feature.id){this.over=false;}}},cancel:function(){this.handlers.drag.deactivate();this.over=false;},setMap:function(map){this.handlers.drag.setMap(map);this.handlers.feature.setMap(map);OpenLayers.Control.prototype.setMap.apply(this,arguments);},CLASS_NAME:"OpenLayers.Control.DragFeature"});OpenLayers.Control.DragPan=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,panned:false,interval:25,documentDrag:false,draw:function(){this.handler=new OpenLayers.Handler.Drag(this,{"move":this.panMap,"done":this.panMapDone},{interval:this.interval,documentDrag:this.documentDrag});},panMap:function(xy){this.panned=true;this.map.pan(this.handler.last.x-xy.x,this.handler.last.y-xy.y,{dragging:this.handler.dragging,animate:false});},panMapDone:function(xy){if(this.panned){this.panMap(xy);this.panned=false;}},CLASS_NAME:"OpenLayers.Control.DragPan"});OpenLayers.Control.KeyboardDefaults=OpenLayers.Class(OpenLayers.Control,{autoActivate:true,slideFactor:75,initialize:function(){OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){if(this.handler){this.handler.destroy();}
this.handler=null;OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){this.handler=new OpenLayers.Handler.Keyboard(this,{"keydown":this.defaultKeyPress});},defaultKeyPress:function(evt){switch(evt.keyCode){case OpenLayers.Event.KEY_LEFT:this.map.pan(-this.slideFactor,0);break;case OpenLayers.Event.KEY_RIGHT:this.map.pan(this.slideFactor,0);break;case OpenLayers.Event.KEY_UP:this.map.pan(0,-this.slideFactor);break;case OpenLayers.Event.KEY_DOWN:this.map.pan(0,this.slideFactor);break;case 33:var size=this.map.getSize();this.map.pan(0,-0.75*size.h);break;case 34:var size=this.map.getSize();this.map.pan(0,0.75*size.h);break;case 35:var size=this.map.getSize();this.map.pan(0.75*size.w,0);break;case 36:var size=this.map.getSize();this.map.pan(-0.75*size.w,0);break;case 43:case 61:case 187:case 107:this.map.zoomIn();break;case 45:case 109:case 189:case 95:this.map.zoomOut();break;}},CLASS_NAME:"OpenLayers.Control.KeyboardDefaults"});OpenLayers.Control.WMSGetFeatureInfo=OpenLayers.Class(OpenLayers.Control,{hover:false,drillDown:false,maxFeatures:10,clickCallback:"click",layers:null,queryVisible:false,url:null,layerUrls:null,infoFormat:'text/html',vendorParams:{},format:null,formatOptions:null,handlerOptions:null,handler:null,hoverRequest:null,EVENT_TYPES:["beforegetfeatureinfo","nogetfeatureinfo","getfeatureinfo"],initialize:function(options){this.EVENT_TYPES=OpenLayers.Control.WMSGetFeatureInfo.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES);options=options||{};options.handlerOptions=options.handlerOptions||{};OpenLayers.Control.prototype.initialize.apply(this,[options]);if(!this.format){this.format=new OpenLayers.Format.WMSGetFeatureInfo(options.formatOptions);}
if(this.drillDown===true){this.hover=false;}
if(this.hover){this.handler=new OpenLayers.Handler.Hover(this,{'move':this.cancelHover,'pause':this.getInfoForHover},OpenLayers.Util.extend(this.handlerOptions.hover||{},{'delay':250}));}else{var callbacks={};callbacks[this.clickCallback]=this.getInfoForClick;this.handler=new OpenLayers.Handler.Click(this,callbacks,this.handlerOptions.click||{});}},activate:function(){if(!this.active){this.handler.activate();}
return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},getInfoForClick:function(evt){this.events.triggerEvent("beforegetfeatureinfo",{xy:evt.xy});OpenLayers.Element.addClass(this.map.viewPortDiv,"olCursorWait");this.request(evt.xy,{});},getInfoForHover:function(evt){this.events.triggerEvent("beforegetfeatureinfo",{xy:evt.xy});this.request(evt.xy,{hover:true});},cancelHover:function(){if(this.hoverRequest){this.hoverRequest.abort();this.hoverRequest=null;}},findLayers:function(){var candidates=this.layers||this.map.layers;var layers=[];var layer,url;for(var i=0,len=candidates.length;i<len;++i){layer=candidates[i];if(layer instanceof OpenLayers.Layer.WMS&&(!this.queryVisible||layer.getVisibility())){url=layer.url instanceof Array?layer.url[0]:layer.url;if(this.drillDown===false&&!this.url){this.url=url;}
if(this.drillDown===true||this.urlMatches(url)){layers.push(layer);}}}
return layers;},urlMatches:function(url){var matches=OpenLayers.Util.isEquivalentUrl(this.url,url);if(!matches&&this.layerUrls){for(var i=0,len=this.layerUrls.length;i<len;++i){if(OpenLayers.Util.isEquivalentUrl(this.layerUrls[i],url)){matches=true;break;}}}
return matches;},buildWMSOptions:function(url,layers,clickPosition,format){var layerNames=[],styleNames=[];for(var i=0,len=layers.length;i<len;i++){layerNames=layerNames.concat(layers[i].params.LAYERS);styleNames=styleNames.concat(this.getStyleNames(layers[i]));}
var params=OpenLayers.Util.extend({service:"WMS",version:layers[0].params.VERSION,request:"GetFeatureInfo",layers:layerNames,query_layers:layerNames,styles:styleNames,bbox:this.map.getExtent().toBBOX(null,layers[0].reverseAxisOrder()),feature_count:this.maxFeatures,height:this.map.getSize().h,width:this.map.getSize().w,format:format,info_format:this.infoFormat},(parseFloat(layers[0].params.VERSION)>=1.3)?{crs:this.map.getProjection(),i:clickPosition.x,j:clickPosition.y}:{srs:this.map.getProjection(),x:clickPosition.x,y:clickPosition.y});OpenLayers.Util.applyDefaults(params,this.vendorParams);return{url:url,params:OpenLayers.Util.upperCaseObject(params),callback:function(request){this.handleResponse(clickPosition,request);},scope:this};},getStyleNames:function(layer){var styleNames;if(layer.params.STYLES){styleNames=layer.params.STYLES;}else{if(layer.params.LAYERS instanceof Array){styleNames=new Array(layer.params.LAYERS.length);}else{styleNames=layer.params.LAYERS.replace(/[^,]/g,"");}}
return styleNames;},request:function(clickPosition,options){var layers=this.findLayers();if(layers.length==0){this.events.triggerEvent("nogetfeatureinfo");OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait");return;}
options=options||{};if(this.drillDown===false){var wmsOptions=this.buildWMSOptions(this.url,layers,clickPosition,layers[0].params.FORMAT);var request=OpenLayers.Request.GET(wmsOptions);if(options.hover===true){this.hoverRequest=request;}}else{this._requestCount=0;this._numRequests=0;this.features=[];var services={},url;for(var i=0,len=layers.length;i<len;i++){var layer=layers[i];var service,found=false;url=layer.url instanceof Array?layer.url[0]:layer.url;if(url in services){services[url].push(layer);}else{this._numRequests++;services[url]=[layer];}}
var layers;for(var url in services){layers=services[url];var wmsOptions=this.buildWMSOptions(url,layers,clickPosition,layers[0].params.FORMAT);OpenLayers.Request.GET(wmsOptions);}}},triggerGetFeatureInfo:function(request,xy,features){this.events.triggerEvent("getfeatureinfo",{text:request.responseText,features:features,request:request,xy:xy});OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait");},handleResponse:function(xy,request){var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
var features=this.format.read(doc);if(this.drillDown===false){this.triggerGetFeatureInfo(request,xy,features);}else{this._requestCount++;this._features=(this._features||[]).concat(features);if(this._requestCount===this._numRequests){this.triggerGetFeatureInfo(request,xy,this._features.concat());delete this._features;delete this._requestCount;delete this._numRequests;}}},CLASS_NAME:"OpenLayers.Control.WMSGetFeatureInfo"});OpenLayers.Control.WMTSGetFeatureInfo=OpenLayers.Class(OpenLayers.Control,{hover:false,requestEncoding:"KVP",drillDown:false,maxFeatures:10,clickCallback:"click",layers:null,queryVisible:true,infoFormat:'text/html',vendorParams:{},format:null,formatOptions:null,handlerOptions:null,handler:null,hoverRequest:null,EVENT_TYPES:["beforegetfeatureinfo","getfeatureinfo","exception"],pending:0,initialize:function(options){this.EVENT_TYPES=OpenLayers.Control.WMTSGetFeatureInfo.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES);options=options||{};options.handlerOptions=options.handlerOptions||{};OpenLayers.Control.prototype.initialize.apply(this,[options]);if(!this.format){this.format=new OpenLayers.Format.WMSGetFeatureInfo(options.formatOptions);}
if(this.drillDown===true){this.hover=false;}
if(this.hover){this.handler=new OpenLayers.Handler.Hover(this,{move:this.cancelHover,pause:this.getInfoForHover},OpenLayers.Util.extend(this.handlerOptions.hover||{},{delay:250}));}else{var callbacks={};callbacks[this.clickCallback]=this.getInfoForClick;this.handler=new OpenLayers.Handler.Click(this,callbacks,this.handlerOptions.click||{});}},activate:function(){if(!this.active){this.handler.activate();}
return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},getInfoForClick:function(evt){this.request(evt.xy,{});},getInfoForHover:function(evt){this.request(evt.xy,{hover:true});},cancelHover:function(){if(this.hoverRequest){--this.pending;if(this.pending<=0){OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait");this.pending=0;}
this.hoverRequest.abort();this.hoverRequest=null;}},findLayers:function(){var candidates=this.layers||this.map.layers;var layers=[];var layer;for(var i=candidates.length-1;i>=0;--i){layer=candidates[i];if(layer instanceof OpenLayers.Layer.WMTS&&layer.requestEncoding===this.requestEncoding&&(!this.queryVisible||layer.getVisibility())){layers.push(layer);if(!this.drillDown||this.hover){break;}}}
return layers;},buildRequestOptions:function(layer,xy){var loc=this.map.getLonLatFromPixel(xy);var getTileUrl=layer.getURL(new OpenLayers.Bounds(loc.lon,loc.lat,loc.lon,loc.lat));var params=OpenLayers.Util.getParameters(getTileUrl);var tileInfo=layer.getTileInfo(loc);OpenLayers.Util.extend(params,{service:"WMTS",version:layer.version,request:"GetFeatureInfo",infoFormat:this.infoFormat,i:tileInfo.i,j:tileInfo.j});OpenLayers.Util.applyDefaults(params,this.vendorParams);return{url:layer.url instanceof Array?layer.url[0]:layer.url,params:OpenLayers.Util.upperCaseObject(params),callback:function(request){this.handleResponse(xy,request,layer);},scope:this};},request:function(xy,options){options=options||{};var layers=this.findLayers();if(layers.length>0){var issue,layer;for(var i=0,len=layers.length;i<len;i++){layer=layers[i];issue=this.events.triggerEvent("beforegetfeatureinfo",{xy:xy,layer:layer});if(issue!==false){++this.pending;var requestOptions=this.buildRequestOptions(layer,xy);var request=OpenLayers.Request.GET(requestOptions);if(options.hover===true){this.hoverRequest=request;}}}
if(this.pending>0){OpenLayers.Element.addClass(this.map.viewPortDiv,"olCursorWait");}}},handleResponse:function(xy,request,layer){--this.pending;if(this.pending<=0){OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait");this.pending=0;}
if(request.status&&(request.status<200||request.status>=300)){this.events.triggerEvent("exception",{xy:xy,request:request,layer:layer});}else{var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
var features,except;try{features=this.format.read(doc);}catch(error){except=true;this.events.triggerEvent("exception",{xy:xy,request:request,error:error,layer:layer});}
if(!except){this.events.triggerEvent("getfeatureinfo",{text:request.responseText,features:features,request:request,xy:xy,layer:layer});}}},setMap:function(map){this.handler.setMap(map);OpenLayers.Control.prototype.setMap.apply(this,arguments);},CLASS_NAME:"OpenLayers.Control.WMTSGetFeatureInfo"});OpenLayers.State={UNKNOWN:'Unknown',INSERT:'Insert',UPDATE:'Update',DELETE:'Delete'};OpenLayers.Feature.Vector=OpenLayers.Class(OpenLayers.Feature,{fid:null,geometry:null,attributes:null,bounds:null,state:null,style:null,url:null,renderIntent:"default",initialize:function(geometry,attributes,style){OpenLayers.Feature.prototype.initialize.apply(this,[null,null,attributes]);this.lonlat=null;this.geometry=geometry?geometry:null;this.state=null;this.attributes={};if(attributes){this.attributes=OpenLayers.Util.extend(this.attributes,attributes);}
this.style=style?style:null;},destroy:function(){if(this.layer){this.layer.removeFeatures(this);this.layer=null;}
this.geometry=null;OpenLayers.Feature.prototype.destroy.apply(this,arguments);},clone:function(){return new OpenLayers.Feature.Vector(this.geometry?this.geometry.clone():null,this.attributes,this.style);},onScreen:function(boundsOnly){var onScreen=false;if(this.layer&&this.layer.map){var screenBounds=this.layer.map.getExtent();if(boundsOnly){var featureBounds=this.geometry.getBounds();onScreen=screenBounds.intersectsBounds(featureBounds);}else{var screenPoly=screenBounds.toGeometry();onScreen=screenPoly.intersects(this.geometry);}}
return onScreen;},getVisibility:function(){return!(this.style&&this.style.display=='none'||!this.layer||this.layer&&this.layer.styleMap&&this.layer.styleMap.createSymbolizer(this,this.renderIntent).display=='none'||this.layer&&!this.layer.getVisibility());},createMarker:function(){return null;},destroyMarker:function(){},createPopup:function(){return null;},atPoint:function(lonlat,toleranceLon,toleranceLat){var atPoint=false;if(this.geometry){atPoint=this.geometry.atPoint(lonlat,toleranceLon,toleranceLat);}
return atPoint;},destroyPopup:function(){},move:function(location){if(!this.layer||!this.geometry.move){return;}
var pixel;if(location.CLASS_NAME=="OpenLayers.LonLat"){pixel=this.layer.getViewPortPxFromLonLat(location);}else{pixel=location;}
var lastPixel=this.layer.getViewPortPxFromLonLat(this.geometry.getBounds().getCenterLonLat());var res=this.layer.map.getResolution();this.geometry.move(res*(pixel.x-lastPixel.x),res*(lastPixel.y-pixel.y));this.layer.drawFeature(this);return lastPixel;},toState:function(state){if(state==OpenLayers.State.UPDATE){switch(this.state){case OpenLayers.State.UNKNOWN:case OpenLayers.State.DELETE:this.state=state;break;case OpenLayers.State.UPDATE:case OpenLayers.State.INSERT:break;}}else if(state==OpenLayers.State.INSERT){switch(this.state){case OpenLayers.State.UNKNOWN:break;default:this.state=state;break;}}else if(state==OpenLayers.State.DELETE){switch(this.state){case OpenLayers.State.INSERT:break;case OpenLayers.State.DELETE:break;case OpenLayers.State.UNKNOWN:case OpenLayers.State.UPDATE:this.state=state;break;}}else if(state==OpenLayers.State.UNKNOWN){this.state=state;}},CLASS_NAME:"OpenLayers.Feature.Vector"});OpenLayers.Feature.Vector.style={'default':{fillColor:"#ee9900",fillOpacity:0.4,hoverFillColor:"white",hoverFillOpacity:0.8,strokeColor:"#ee9900",strokeOpacity:1,strokeWidth:1,strokeLinecap:"round",strokeDashstyle:"solid",hoverStrokeColor:"red",hoverStrokeOpacity:1,hoverStrokeWidth:0.2,pointRadius:6,hoverPointRadius:1,hoverPointUnit:"%",pointerEvents:"visiblePainted",cursor:"inherit"},'select':{fillColor:"blue",fillOpacity:0.4,hoverFillColor:"white",hoverFillOpacity:0.8,strokeColor:"blue",strokeOpacity:1,strokeWidth:2,strokeLinecap:"round",strokeDashstyle:"solid",hoverStrokeColor:"red",hoverStrokeOpacity:1,hoverStrokeWidth:0.2,pointRadius:6,hoverPointRadius:1,hoverPointUnit:"%",pointerEvents:"visiblePainted",cursor:"pointer"},'temporary':{fillColor:"#66cccc",fillOpacity:0.2,hoverFillColor:"white",hoverFillOpacity:0.8,strokeColor:"#66cccc",strokeOpacity:1,strokeLinecap:"round",strokeWidth:2,strokeDashstyle:"solid",hoverStrokeColor:"red",hoverStrokeOpacity:1,hoverStrokeWidth:0.2,pointRadius:6,hoverPointRadius:1,hoverPointUnit:"%",pointerEvents:"visiblePainted",cursor:"inherit"},'delete':{display:"none"}};OpenLayers.Feature.WFS=OpenLayers.Class(OpenLayers.Feature,{initialize:function(layer,xmlNode){var newArguments=arguments;var data=this.processXMLNode(xmlNode);newArguments=new Array(layer,data.lonlat,data);OpenLayers.Feature.prototype.initialize.apply(this,newArguments);this.createMarker();this.layer.addMarker(this.marker);},destroy:function(){if(this.marker!=null){this.layer.removeMarker(this.marker);}
OpenLayers.Feature.prototype.destroy.apply(this,arguments);},processXMLNode:function(xmlNode){var point=OpenLayers.Ajax.getElementsByTagNameNS(xmlNode,"http://www.opengis.net/gml","gml","Point");var text=OpenLayers.Util.getXmlNodeValue(OpenLayers.Ajax.getElementsByTagNameNS(point[0],"http://www.opengis.net/gml","gml","coordinates")[0]);var floats=text.split(",");return{lonlat:new OpenLayers.LonLat(parseFloat(floats[0]),parseFloat(floats[1])),id:null};},CLASS_NAME:"OpenLayers.Feature.WFS"});OpenLayers.Format.OWSCommon.v1_0_0=OpenLayers.Class(OpenLayers.Format.OWSCommon.v1,{namespaces:{ows:"http://www.opengis.net/ows/1.0",xlink:"http://www.w3.org/1999/xlink"},readers:{"ows":OpenLayers.Format.OWSCommon.v1.prototype.readers["ows"]},writers:{"ows":OpenLayers.Format.OWSCommon.v1.prototype.writers["ows"]},CLASS_NAME:"OpenLayers.Format.OWSCommon.v1_1_0"});OpenLayers.Format.OWSCommon.v1_1_0=OpenLayers.Class(OpenLayers.Format.OWSCommon.v1,{namespaces:{ows:"http://www.opengis.net/ows/1.1",xlink:"http://www.w3.org/1999/xlink"},readers:{"ows":OpenLayers.Util.applyDefaults({"AllowedValues":function(node,parameter){parameter.allowedValues={};this.readChildNodes(node,parameter.allowedValues);},"AnyValue":function(node,parameter){parameter.anyValue=true;},"Range":function(node,allowedValues){allowedValues.range={};this.readChildNodes(node,allowedValues.range);},"MinimumValue":function(node,range){range.minValue=this.getChildValue(node);},"MaximumValue":function(node,range){range.maxValue=this.getChildValue(node);},"Identifier":function(node,obj){obj.identifier=this.getChildValue(node);},"SupportedCRS":function(node,obj){obj.supportedCRS=this.getChildValue(node);}},OpenLayers.Format.OWSCommon.v1.prototype.readers["ows"])},CLASS_NAME:"OpenLayers.Format.OWSCommon.v1_1_0"});OpenLayers.Format.OWSContext=OpenLayers.Class(OpenLayers.Format.Context,{defaultVersion:"0.3.1",getParser:function(version){var v=version||this.version||this.defaultVersion;if(v==="0.3.0"){v=this.defaultVersion;}
if(!this.parser||this.parser.VERSION!=v){var format=OpenLayers.Format.OWSContext["v"+v.replace(/\./g,"_")];if(!format){throw"Can't find a OWSContext parser for version "+v;}
this.parser=new format(this.options);}
return this.parser;},toContext:function(obj){var context={};if(obj.CLASS_NAME=="OpenLayers.Map"){context.bounds=obj.getExtent();context.maxExtent=obj.maxExtent;context.projection=obj.projection;context.size=obj.getSize();context.layers=obj.layers;}
return context;},CLASS_NAME:"OpenLayers.Format.OWSContext"});OpenLayers.Format.WFSCapabilities.v1=OpenLayers.Class(OpenLayers.Format.WFSCapabilities,{initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);this.options=options;},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var capabilities={};var root=data.documentElement;this.runChildNodes(capabilities,root);return capabilities;},runChildNodes:function(obj,node){var children=node.childNodes;var childNode,processor;for(var i=0;i<children.length;++i){childNode=children[i];if(childNode.nodeType==1){processor=this["read_cap_"+childNode.nodeName];if(processor){processor.apply(this,[obj,childNode]);}}}},read_cap_FeatureTypeList:function(request,node){var featureTypeList={featureTypes:[]};this.runChildNodes(featureTypeList,node);request.featureTypeList=featureTypeList;},read_cap_FeatureType:function(featureTypeList,node,parentLayer){var featureType={};this.runChildNodes(featureType,node);featureTypeList.featureTypes.push(featureType);},read_cap_Name:function(obj,node){var name=this.getChildValue(node);if(name){var parts=name.split(":");obj.name=parts.pop();if(parts.length>0){obj.featureNS=this.lookupNamespaceURI(node,parts[0]);}}},read_cap_Title:function(obj,node){var title=this.getChildValue(node);if(title){obj.title=title;}},read_cap_Abstract:function(obj,node){var abst=this.getChildValue(node);if(abst){obj["abstract"]=abst;}},CLASS_NAME:"OpenLayers.Format.WFSCapabilities.v1"});OpenLayers.Format.WMC=OpenLayers.Class(OpenLayers.Format.Context,{defaultVersion:"1.1.0",getParser:function(version){var v=version||this.version||this.defaultVersion;if(!this.parser||this.parser.VERSION!=v){var format=OpenLayers.Format.WMC["v"+v.replace(/\./g,"_")];if(!format){throw"Can't find a WMC parser for version "+v;}
this.parser=new format(this.options);}
return this.parser;},layerToContext:function(layer){var parser=this.getParser();var layerContext={queryable:layer.queryable,visibility:layer.visibility,name:layer.params["LAYERS"],title:layer.name,metadataURL:layer.metadataURL,version:layer.params["VERSION"],url:layer.url,maxExtent:layer.maxExtent,transparent:layer.params["TRANSPARENT"],numZoomLevels:layer.numZoomLevels,units:layer.units,isBaseLayer:layer.isBaseLayer,opacity:layer.opacity,displayInLayerSwitcher:layer.displayInLayerSwitcher,singleTile:layer.singleTile,tileSize:(layer.singleTile||!layer.tileSize)?undefined:{width:layer.tileSize.w,height:layer.tileSize.h},minScale:(layer.options.resolutions||layer.options.scales||layer.options.maxResolution||layer.options.minScale)?layer.minScale:undefined,maxScale:(layer.options.resolutions||layer.options.scales||layer.options.minResolution||layer.options.maxScale)?layer.maxScale:undefined,formats:[{value:layer.params["FORMAT"],current:true}],styles:[{href:layer.params["SLD"],body:layer.params["SLD_BODY"],name:layer.params["STYLES"]||parser.defaultStyleName,title:parser.defaultStyleTitle,current:true}]};return layerContext;},toContext:function(obj){var context={};var layers=obj.layers;if(obj.CLASS_NAME=="OpenLayers.Map"){context.bounds=obj.getExtent();context.maxExtent=obj.maxExtent;context.projection=obj.projection;context.size=obj.getSize();}
else{OpenLayers.Util.applyDefaults(context,obj);if(context.layers!=undefined){delete(context.layers);}}
if(context.layersContext==undefined){context.layersContext=[];}
if(layers!=undefined&&layers instanceof Array){for(var i=0,len=layers.length;i<len;i++){var layer=layers[i];if(layer instanceof OpenLayers.Layer.WMS){context.layersContext.push(this.layerToContext(layer));}}}
return context;},CLASS_NAME:"OpenLayers.Format.WMC"});OpenLayers.Format.WMSCapabilities.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{wms:"http://www.opengis.net/wms",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},defaultPrefix:"wms",initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var capabilities={};this.readNode(data,capabilities);this.postProcessLayers(capabilities);return capabilities;},postProcessLayers:function(capabilities){if(capabilities.capability){capabilities.capability.layers=[];var layers=capabilities.capability.nestedLayers;for(var i=0,len=layers.length;i<len;++i){var layer=layers[i];this.processLayer(capabilities.capability,layer);}}},processLayer:function(capability,layer,parentLayer){if(layer.formats===undefined){layer.formats=capability.request.getmap.formats;}
if(parentLayer){layer.styles=layer.styles.concat(parentLayer.styles);var attributes=["queryable","cascaded","fixedWidth","fixedHeight","opaque","noSubsets","llbbox","minScale","maxScale","attribution"];var complexAttr=["srs","bbox","dimensions","authorityURLs"];var key;for(var j=0;j<attributes.length;j++){key=attributes[j];if(key in parentLayer){if(layer[key]==null){layer[key]=parentLayer[key];}
if(layer[key]==null){var intAttr=["cascaded","fixedWidth","fixedHeight"];var boolAttr=["queryable","opaque","noSubsets"];if(OpenLayers.Util.indexOf(intAttr,key)!=-1){layer[key]=0;}
if(OpenLayers.Util.indexOf(boolAttr,key)!=-1){layer[key]=false;}}}}
for(var j=0;j<complexAttr.length;j++){key=complexAttr[j];layer[key]=OpenLayers.Util.extend(layer[key],parentLayer[key]);}}
for(var i=0,len=layer.nestedLayers.length;i<len;i++){var childLayer=layer.nestedLayers[i];this.processLayer(capability,childLayer,layer);}
if(layer.name){capability.layers.push(layer);}},readers:{"wms":{"Service":function(node,obj){obj.service={};this.readChildNodes(node,obj.service);},"Name":function(node,obj){obj.name=this.getChildValue(node);},"Title":function(node,obj){obj.title=this.getChildValue(node);},"Abstract":function(node,obj){obj["abstract"]=this.getChildValue(node);},"BoundingBox":function(node,obj){var bbox={};bbox.bbox=[parseFloat(node.getAttribute("minx")),parseFloat(node.getAttribute("miny")),parseFloat(node.getAttribute("maxx")),parseFloat(node.getAttribute("maxy"))];var res={x:parseFloat(node.getAttribute("resx")),y:parseFloat(node.getAttribute("resy"))};if(!(isNaN(res.x)&&isNaN(res.y))){bbox.res=res;}
return bbox;},"OnlineResource":function(node,obj){obj.href=this.getAttributeNS(node,this.namespaces.xlink,"href");},"ContactInformation":function(node,obj){obj.contactInformation={};this.readChildNodes(node,obj.contactInformation);},"ContactPersonPrimary":function(node,obj){obj.personPrimary={};this.readChildNodes(node,obj.personPrimary);},"ContactPerson":function(node,obj){obj.person=this.getChildValue(node);},"ContactOrganization":function(node,obj){obj.organization=this.getChildValue(node);},"ContactPosition":function(node,obj){obj.position=this.getChildValue(node);},"ContactAddress":function(node,obj){obj.contactAddress={};this.readChildNodes(node,obj.contactAddress);},"AddressType":function(node,obj){obj.type=this.getChildValue(node);},"Address":function(node,obj){obj.address=this.getChildValue(node);},"City":function(node,obj){obj.city=this.getChildValue(node);},"StateOrProvince":function(node,obj){obj.stateOrProvince=this.getChildValue(node);},"PostCode":function(node,obj){obj.postcode=this.getChildValue(node);},"Country":function(node,obj){obj.country=this.getChildValue(node);},"ContactVoiceTelephone":function(node,obj){obj.phone=this.getChildValue(node);},"ContactFacsimileTelephone":function(node,obj){obj.fax=this.getChildValue(node);},"ContactElectronicMailAddress":function(node,obj){obj.email=this.getChildValue(node);},"Fees":function(node,obj){var fees=this.getChildValue(node);if(fees&&fees.toLowerCase()!="none"){obj.fees=fees;}},"AccessConstraints":function(node,obj){var constraints=this.getChildValue(node);if(constraints&&constraints.toLowerCase()!="none"){obj.accessConstraints=constraints;}},"Capability":function(node,obj){obj.capability={nestedLayers:[]};this.readChildNodes(node,obj.capability);},"Request":function(node,obj){obj.request={};this.readChildNodes(node,obj.request);},"GetCapabilities":function(node,obj){obj.getcapabilities={formats:[]};this.readChildNodes(node,obj.getcapabilities);},"Format":function(node,obj){if(obj.formats instanceof Array){obj.formats.push(this.getChildValue(node));}else{obj.format=this.getChildValue(node);}},"DCPType":function(node,obj){this.readChildNodes(node,obj);},"HTTP":function(node,obj){this.readChildNodes(node,obj);},"Get":function(node,obj){this.readChildNodes(node,obj);},"Post":function(node,obj){this.readChildNodes(node,obj);},"GetMap":function(node,obj){obj.getmap={formats:[]};this.readChildNodes(node,obj.getmap);},"GetFeatureInfo":function(node,obj){obj.getfeatureinfo={formats:[]};this.readChildNodes(node,obj.getfeatureinfo);},"Exception":function(node,obj){obj.exception={formats:[]};this.readChildNodes(node,obj.exception);},"Layer":function(node,obj){var attrNode=node.getAttributeNode("queryable");var queryable=(attrNode&&attrNode.specified)?node.getAttribute("queryable"):null;attrNode=node.getAttributeNode("cascaded");var cascaded=(attrNode&&attrNode.specified)?node.getAttribute("cascaded"):null;attrNode=node.getAttributeNode("opaque");var opaque=(attrNode&&attrNode.specified)?node.getAttribute('opaque'):null;var noSubsets=node.getAttribute('noSubsets');var fixedWidth=node.getAttribute('fixedWidth');var fixedHeight=node.getAttribute('fixedHeight');var layer={nestedLayers:[],styles:[],srs:{},metadataURLs:[],bbox:{},dimensions:{},authorityURLs:{},identifiers:{},keywords:[],queryable:(queryable&&queryable!=="")?(queryable==="1"||queryable==="true"):null,cascaded:(cascaded!==null)?parseInt(cascaded):null,opaque:opaque?(opaque==="1"||opaque==="true"):null,noSubsets:(noSubsets!==null)?(noSubsets==="1"||noSubsets==="true"):null,fixedWidth:(fixedWidth!=null)?parseInt(fixedWidth):null,fixedHeight:(fixedHeight!=null)?parseInt(fixedHeight):null};obj.nestedLayers.push(layer);this.readChildNodes(node,layer);if(layer.name){var parts=layer.name.split(":");if(parts.length>0){layer.prefix=parts[0];}}},"Attribution":function(node,obj){obj.attribution={};this.readChildNodes(node,obj.attribution);},"LogoURL":function(node,obj){obj.logo={width:node.getAttribute("width"),height:node.getAttribute("height")};this.readChildNodes(node,obj.logo);},"Style":function(node,obj){var style={};obj.styles.push(style);this.readChildNodes(node,style);},"LegendURL":function(node,obj){var legend={width:node.getAttribute("width"),height:node.getAttribute("height")};obj.legend=legend;this.readChildNodes(node,legend);},"MetadataURL":function(node,obj){var metadataURL={type:node.getAttribute("type")};obj.metadataURLs.push(metadataURL);this.readChildNodes(node,metadataURL);},"DataURL":function(node,obj){obj.dataURL={};this.readChildNodes(node,obj.dataURL);},"FeatureListURL":function(node,obj){obj.featureListURL={};this.readChildNodes(node,obj.featureListURL);},"AuthorityURL":function(node,obj){var name=node.getAttribute("name");var authority={};this.readChildNodes(node,authority);obj.authorityURLs[name]=authority.href;},"Identifier":function(node,obj){var authority=node.getAttribute("authority");obj.identifiers[authority]=this.getChildValue(node);},"KeywordList":function(node,obj){this.readChildNodes(node,obj);},"SRS":function(node,obj){obj.srs[this.getChildValue(node)]=true;}}},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1"});OpenLayers.Format.WMSDescribeLayer.v1_1=OpenLayers.Class(OpenLayers.Format.WMSDescribeLayer,{initialize:function(options){OpenLayers.Format.WMSDescribeLayer.prototype.initialize.apply(this,[options]);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;var children=root.childNodes;var describelayer=[];var childNode,nodeName;for(var i=0;i<children.length;++i){childNode=children[i];nodeName=childNode.nodeName;if(nodeName=='LayerDescription'){var layerName=childNode.getAttribute('name');var owsType='';var owsURL='';var typeName='';if(childNode.getAttribute('owsType')){owsType=childNode.getAttribute('owsType');owsURL=childNode.getAttribute('owsURL');}else{if(childNode.getAttribute('wfs')!=''){owsType='WFS';owsURL=childNode.getAttribute('wfs');}else if(childNode.getAttribute('wcs')!=''){owsType='WCS';owsURL=childNode.getAttribute('wcs');}}
var query=childNode.getElementsByTagName('Query');if(query.length>0){typeName=query[0].getAttribute('typeName');if(!typeName){typeName=query[0].getAttribute('typename');}}
describelayer.push({layerName:layerName,owsType:owsType,owsURL:owsURL,typeName:typeName});}}
return describelayer;},CLASS_NAME:"OpenLayers.Format.WMSDescribeLayer.v1_1"});OpenLayers.Handler.Box=OpenLayers.Class(OpenLayers.Handler,{dragHandler:null,boxDivClassName:'olHandlerBoxZoomBox',boxCharacteristics:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);var callbacks={"down":this.startBox,"move":this.moveBox,"out":this.removeBox,"up":this.endBox};this.dragHandler=new OpenLayers.Handler.Drag(this,callbacks,{keyMask:this.keyMask});},destroy:function(){if(this.dragHandler){this.dragHandler.destroy();this.dragHandler=null;}
OpenLayers.Handler.prototype.destroy.apply(this,arguments);},setMap:function(map){OpenLayers.Handler.prototype.setMap.apply(this,arguments);if(this.dragHandler){this.dragHandler.setMap(map);}},startBox:function(xy){this.zoomBox=OpenLayers.Util.createDiv('zoomBox',this.dragHandler.start);this.zoomBox.className=this.boxDivClassName;this.zoomBox.style.zIndex=this.map.Z_INDEX_BASE["Popup"]-1;this.map.viewPortDiv.appendChild(this.zoomBox);OpenLayers.Element.addClass(this.map.viewPortDiv,"olDrawBox");},moveBox:function(xy){var startX=this.dragHandler.start.x;var startY=this.dragHandler.start.y;var deltaX=Math.abs(startX-xy.x);var deltaY=Math.abs(startY-xy.y);this.zoomBox.style.width=Math.max(1,deltaX)+"px";this.zoomBox.style.height=Math.max(1,deltaY)+"px";this.zoomBox.style.left=xy.x<startX?xy.x+"px":startX+"px";this.zoomBox.style.top=xy.y<startY?xy.y+"px":startY+"px";var box=this.getBoxCharacteristics();if(box.newBoxModel){if(xy.x>startX){this.zoomBox.style.width=Math.max(1,deltaX-box.xOffset)+"px";}
if(xy.y>startY){this.zoomBox.style.height=Math.max(1,deltaY-box.yOffset)+"px";}}},endBox:function(end){var result;if(Math.abs(this.dragHandler.start.x-end.x)>5||Math.abs(this.dragHandler.start.y-end.y)>5){var start=this.dragHandler.start;var top=Math.min(start.y,end.y);var bottom=Math.max(start.y,end.y);var left=Math.min(start.x,end.x);var right=Math.max(start.x,end.x);result=new OpenLayers.Bounds(left,bottom,right,top);}else{result=this.dragHandler.start.clone();}
this.removeBox();this.callback("done",[result]);},removeBox:function(){this.map.viewPortDiv.removeChild(this.zoomBox);this.zoomBox=null;this.boxCharacteristics=null;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olDrawBox");},activate:function(){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.dragHandler.activate();return true;}else{return false;}},deactivate:function(){if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.dragHandler.deactivate();return true;}else{return false;}},getBoxCharacteristics:function(){if(!this.boxCharacteristics){var xOffset=parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-left-width"))+parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-right-width"))+1;var yOffset=parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-top-width"))+parseInt(OpenLayers.Element.getStyle(this.zoomBox,"border-bottom-width"))+1;var newBoxModel=OpenLayers.Util.getBrowserName()=="msie"?document.compatMode!="BackCompat":true;this.boxCharacteristics={xOffset:xOffset,yOffset:yOffset,newBoxModel:newBoxModel};}
return this.boxCharacteristics;},CLASS_NAME:"OpenLayers.Handler.Box"});OpenLayers.Handler.RegularPolygon=OpenLayers.Class(OpenLayers.Handler.Drag,{sides:4,radius:null,snapAngle:null,snapToggle:'shiftKey',layerOptions:null,persist:false,irregular:false,angle:null,fixedRadius:false,feature:null,layer:null,origin:null,initialize:function(control,callbacks,options){if(!(options&&options.layerOptions&&options.layerOptions.styleMap)){this.style=OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'],{});}
OpenLayers.Handler.prototype.initialize.apply(this,[control,callbacks,options]);this.options=(options)?options:{};},setOptions:function(newOptions){OpenLayers.Util.extend(this.options,newOptions);OpenLayers.Util.extend(this,newOptions);},activate:function(){var activated=false;if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){var options=OpenLayers.Util.extend({displayInLayerSwitcher:false,calculateInRange:OpenLayers.Function.True},this.layerOptions);this.layer=new OpenLayers.Layer.Vector(this.CLASS_NAME,options);this.map.addLayer(this.layer);activated=true;}
return activated;},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.Drag.prototype.deactivate.apply(this,arguments)){if(this.dragging){this.cancel();}
if(this.layer.map!=null){this.layer.destroy(false);if(this.feature){this.feature.destroy();}}
this.layer=null;this.feature=null;deactivated=true;}
return deactivated;},down:function(evt){this.fixedRadius=!!(this.radius);var maploc=this.map.getLonLatFromPixel(evt.xy);this.origin=new OpenLayers.Geometry.Point(maploc.lon,maploc.lat);if(!this.fixedRadius||this.irregular){this.radius=this.map.getResolution();}
if(this.persist){this.clear();}
this.feature=new OpenLayers.Feature.Vector();this.createGeometry();this.callback("create",[this.origin,this.feature]);this.layer.addFeatures([this.feature],{silent:true});this.layer.drawFeature(this.feature,this.style);},move:function(evt){var maploc=this.map.getLonLatFromPixel(evt.xy);var point=new OpenLayers.Geometry.Point(maploc.lon,maploc.lat);if(this.irregular){var ry=Math.sqrt(2)*Math.abs(point.y-this.origin.y)/2;this.radius=Math.max(this.map.getResolution()/2,ry);}else if(this.fixedRadius){this.origin=point;}else{this.calculateAngle(point,evt);this.radius=Math.max(this.map.getResolution()/2,point.distanceTo(this.origin));}
this.modifyGeometry();if(this.irregular){var dx=point.x-this.origin.x;var dy=point.y-this.origin.y;var ratio;if(dy==0){ratio=dx/(this.radius*Math.sqrt(2));}else{ratio=dx/dy;}
this.feature.geometry.resize(1,this.origin,ratio);this.feature.geometry.move(dx/2,dy/2);}
this.layer.drawFeature(this.feature,this.style);},up:function(evt){this.finalize();if(this.start==this.last){this.callback("done",[evt.xy]);}},out:function(evt){this.finalize();},createGeometry:function(){this.angle=Math.PI*((1/this.sides)-(1/2));if(this.snapAngle){this.angle+=this.snapAngle*(Math.PI/180);}
this.feature.geometry=OpenLayers.Geometry.Polygon.createRegularPolygon(this.origin,this.radius,this.sides,this.snapAngle);},modifyGeometry:function(){var angle,point;var ring=this.feature.geometry.components[0];if(ring.components.length!=(this.sides+1)){this.createGeometry();ring=this.feature.geometry.components[0];}
for(var i=0;i<this.sides;++i){point=ring.components[i];angle=this.angle+(i*2*Math.PI/this.sides);point.x=this.origin.x+(this.radius*Math.cos(angle));point.y=this.origin.y+(this.radius*Math.sin(angle));point.clearBounds();}},calculateAngle:function(point,evt){var alpha=Math.atan2(point.y-this.origin.y,point.x-this.origin.x);if(this.snapAngle&&(this.snapToggle&&!evt[this.snapToggle])){var snapAngleRad=(Math.PI/180)*this.snapAngle;this.angle=Math.round(alpha/snapAngleRad)*snapAngleRad;}else{this.angle=alpha;}},cancel:function(){this.callback("cancel",null);this.finalize();},finalize:function(){this.origin=null;this.radius=this.options.radius;},clear:function(){if(this.layer){this.layer.renderer.clear();this.layer.destroyFeatures();}},callback:function(name,args){if(this.callbacks[name]){this.callbacks[name].apply(this.control,[this.feature.geometry.clone()]);}
if(!this.persist&&(name=="done"||name=="cancel")){this.clear();}},CLASS_NAME:"OpenLayers.Handler.RegularPolygon"});OpenLayers.Layer.EventPane=OpenLayers.Class(OpenLayers.Layer,{smoothDragPan:true,isBaseLayer:true,isFixed:true,pane:null,mapObject:null,initialize:function(name,options){OpenLayers.Layer.prototype.initialize.apply(this,arguments);if(this.pane==null){this.pane=OpenLayers.Util.createDiv(this.div.id+"_EventPane");}},destroy:function(){this.mapObject=null;this.pane=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments);},setMap:function(map){OpenLayers.Layer.prototype.setMap.apply(this,arguments);this.pane.style.zIndex=parseInt(this.div.style.zIndex)+1;this.pane.style.display=this.div.style.display;this.pane.style.width="100%";this.pane.style.height="100%";if(OpenLayers.Util.getBrowserName()=="msie"){this.pane.style.background="url("+OpenLayers.Util.getImagesLocation()+"blank.gif)";}
if(this.isFixed){this.map.viewPortDiv.appendChild(this.pane);}else{this.map.layerContainerDiv.appendChild(this.pane);}
this.loadMapObject();if(this.mapObject==null){this.loadWarningMessage();}},removeMap:function(map){if(this.pane&&this.pane.parentNode){this.pane.parentNode.removeChild(this.pane);}
OpenLayers.Layer.prototype.removeMap.apply(this,arguments);},loadWarningMessage:function(){this.div.style.backgroundColor="darkblue";var viewSize=this.map.getSize();var msgW=Math.min(viewSize.w,300);var msgH=Math.min(viewSize.h,200);var size=new OpenLayers.Size(msgW,msgH);var centerPx=new OpenLayers.Pixel(viewSize.w/2,viewSize.h/2);var topLeft=centerPx.add(-size.w/2,-size.h/2);var div=OpenLayers.Util.createDiv(this.name+"_warning",topLeft,size,null,null,null,"auto");div.style.padding="7px";div.style.backgroundColor="yellow";div.innerHTML=this.getWarningHTML();this.div.appendChild(div);},getWarningHTML:function(){return"";},display:function(display){OpenLayers.Layer.prototype.display.apply(this,arguments);this.pane.style.display=this.div.style.display;},setZIndex:function(zIndex){OpenLayers.Layer.prototype.setZIndex.apply(this,arguments);this.pane.style.zIndex=parseInt(this.div.style.zIndex)+1;},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);if(this.mapObject!=null){var newCenter=this.map.getCenter();var newZoom=this.map.getZoom();if(newCenter!=null){var moOldCenter=this.getMapObjectCenter();var oldCenter=this.getOLLonLatFromMapObjectLonLat(moOldCenter);var moOldZoom=this.getMapObjectZoom();var oldZoom=this.getOLZoomFromMapObjectZoom(moOldZoom);if(!(newCenter.equals(oldCenter))||!(newZoom==oldZoom)){if(dragging&&this.dragPanMapObject&&this.smoothDragPan){var oldPx=this.map.getViewPortPxFromLonLat(oldCenter);var newPx=this.map.getViewPortPxFromLonLat(newCenter);this.dragPanMapObject(newPx.x-oldPx.x,oldPx.y-newPx.y);}else{var center=this.getMapObjectLonLatFromOLLonLat(newCenter);var zoom=this.getMapObjectZoomFromOLZoom(newZoom);this.setMapObjectCenter(center,zoom,dragging);}}}}},getLonLatFromViewPortPx:function(viewPortPx){var lonlat=null;if((this.mapObject!=null)&&(this.getMapObjectCenter()!=null)){var moPixel=this.getMapObjectPixelFromOLPixel(viewPortPx);var moLonLat=this.getMapObjectLonLatFromMapObjectPixel(moPixel);lonlat=this.getOLLonLatFromMapObjectLonLat(moLonLat);}
return lonlat;},getViewPortPxFromLonLat:function(lonlat){var viewPortPx=null;if((this.mapObject!=null)&&(this.getMapObjectCenter()!=null)){var moLonLat=this.getMapObjectLonLatFromOLLonLat(lonlat);var moPixel=this.getMapObjectPixelFromMapObjectLonLat(moLonLat);viewPortPx=this.getOLPixelFromMapObjectPixel(moPixel);}
return viewPortPx;},getOLLonLatFromMapObjectLonLat:function(moLonLat){var olLonLat=null;if(moLonLat!=null){var lon=this.getLongitudeFromMapObjectLonLat(moLonLat);var lat=this.getLatitudeFromMapObjectLonLat(moLonLat);olLonLat=new OpenLayers.LonLat(lon,lat);}
return olLonLat;},getMapObjectLonLatFromOLLonLat:function(olLonLat){var moLatLng=null;if(olLonLat!=null){moLatLng=this.getMapObjectLonLatFromLonLat(olLonLat.lon,olLonLat.lat);}
return moLatLng;},getOLPixelFromMapObjectPixel:function(moPixel){var olPixel=null;if(moPixel!=null){var x=this.getXFromMapObjectPixel(moPixel);var y=this.getYFromMapObjectPixel(moPixel);olPixel=new OpenLayers.Pixel(x,y);}
return olPixel;},getMapObjectPixelFromOLPixel:function(olPixel){var moPixel=null;if(olPixel!=null){moPixel=this.getMapObjectPixelFromXY(olPixel.x,olPixel.y);}
return moPixel;},CLASS_NAME:"OpenLayers.Layer.EventPane"});OpenLayers.Layer.FixedZoomLevels=OpenLayers.Class({initialize:function(){},initResolutions:function(){var props=new Array('minZoomLevel','maxZoomLevel','numZoomLevels');for(var i=0,len=props.length;i<len;i++){var property=props[i];this[property]=(this.options[property]!=null)?this.options[property]:this.map[property];}
if((this.minZoomLevel==null)||(this.minZoomLevel<this.MIN_ZOOM_LEVEL)){this.minZoomLevel=this.MIN_ZOOM_LEVEL;}
var desiredZoomLevels;var limitZoomLevels=this.MAX_ZOOM_LEVEL-this.minZoomLevel+1;if(((this.options.numZoomLevels==null)&&(this.options.maxZoomLevel!=null))||((this.numZoomLevels==null)&&(this.maxZoomLevel!=null))){desiredZoomLevels=this.maxZoomLevel-this.minZoomLevel+1;}else{desiredZoomLevels=this.numZoomLevels;}
if(desiredZoomLevels!=null){this.numZoomLevels=Math.min(desiredZoomLevels,limitZoomLevels);}else{this.numZoomLevels=limitZoomLevels;}
this.maxZoomLevel=this.minZoomLevel+this.numZoomLevels-1;if(this.RESOLUTIONS!=null){var resolutionsIndex=0;this.resolutions=[];for(var i=this.minZoomLevel;i<=this.maxZoomLevel;i++){this.resolutions[resolutionsIndex++]=this.RESOLUTIONS[i];}
this.maxResolution=this.resolutions[0];this.minResolution=this.resolutions[this.resolutions.length-1];}},getResolution:function(){if(this.resolutions!=null){return OpenLayers.Layer.prototype.getResolution.apply(this,arguments);}else{var resolution=null;var viewSize=this.map.getSize();var extent=this.getExtent();if((viewSize!=null)&&(extent!=null)){resolution=Math.max(extent.getWidth()/viewSize.w,extent.getHeight()/viewSize.h);}
return resolution;}},getExtent:function(){var extent=null;var size=this.map.getSize();var tlPx=new OpenLayers.Pixel(0,0);var tlLL=this.getLonLatFromViewPortPx(tlPx);var brPx=new OpenLayers.Pixel(size.w,size.h);var brLL=this.getLonLatFromViewPortPx(brPx);if((tlLL!=null)&&(brLL!=null)){extent=new OpenLayers.Bounds(tlLL.lon,brLL.lat,brLL.lon,tlLL.lat);}
return extent;},getZoomForResolution:function(resolution){if(this.resolutions!=null){return OpenLayers.Layer.prototype.getZoomForResolution.apply(this,arguments);}else{var extent=OpenLayers.Layer.prototype.getExtent.apply(this,[]);return this.getZoomForExtent(extent);}},getOLZoomFromMapObjectZoom:function(moZoom){var zoom=null;if(moZoom!=null){zoom=moZoom-this.minZoomLevel;}
return zoom;},getMapObjectZoomFromOLZoom:function(olZoom){var zoom=null;if(olZoom!=null){zoom=olZoom+this.minZoomLevel;}
return zoom;},CLASS_NAME:"OpenLayers.Layer.FixedZoomLevels"});OpenLayers.Layer.HTTPRequest=OpenLayers.Class(OpenLayers.Layer,{URL_HASH_FACTOR:(Math.sqrt(5)-1)/2,url:null,params:null,reproject:false,initialize:function(name,url,params,options){var newArguments=arguments;newArguments=[name,options];OpenLayers.Layer.prototype.initialize.apply(this,newArguments);this.url=url;this.params=OpenLayers.Util.extend({},params);},destroy:function(){this.url=null;this.params=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.HTTPRequest(this.name,this.url,this.params,this.getOptions());}
obj=OpenLayers.Layer.prototype.clone.apply(this,[obj]);return obj;},setUrl:function(newUrl){this.url=newUrl;},mergeNewParams:function(newParams){this.params=OpenLayers.Util.extend(this.params,newParams);var ret=this.redraw();if(this.map!=null){this.map.events.triggerEvent("changelayer",{layer:this,property:"params"});}
return ret;},redraw:function(force){if(force){return this.mergeNewParams({"_olSalt":Math.random()});}else{return OpenLayers.Layer.prototype.redraw.apply(this,[]);}},selectUrl:function(paramString,urls){var product=1;for(var i=0,len=paramString.length;i<len;i++){product*=paramString.charCodeAt(i)*this.URL_HASH_FACTOR;product-=Math.floor(product);}
return urls[Math.floor(product*urls.length)];},getFullRequestString:function(newParams,altUrl){var url=altUrl||this.url;var allParams=OpenLayers.Util.extend({},this.params);allParams=OpenLayers.Util.extend(allParams,newParams);var paramsString=OpenLayers.Util.getParameterString(allParams);if(url instanceof Array){url=this.selectUrl(paramsString,url);}
var urlParams=OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(url));for(var key in allParams){if(key.toUpperCase()in urlParams){delete allParams[key];}}
paramsString=OpenLayers.Util.getParameterString(allParams);return OpenLayers.Util.urlAppend(url,paramsString);},CLASS_NAME:"OpenLayers.Layer.HTTPRequest"});OpenLayers.Layer.Image=OpenLayers.Class(OpenLayers.Layer,{isBaseLayer:true,url:null,extent:null,size:null,tile:null,aspectRatio:null,initialize:function(name,url,extent,size,options){this.url=url;this.extent=extent;this.maxExtent=extent;this.size=size;OpenLayers.Layer.prototype.initialize.apply(this,[name,options]);this.aspectRatio=(this.extent.getHeight()/this.size.h)/(this.extent.getWidth()/this.size.w);},destroy:function(){if(this.tile){this.removeTileMonitoringHooks(this.tile);this.tile.destroy();this.tile=null;}
OpenLayers.Layer.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.Image(this.name,this.url,this.extent,this.size,this.getOptions());}
obj=OpenLayers.Layer.prototype.clone.apply(this,[obj]);return obj;},setMap:function(map){if(this.options.maxResolution==null){this.options.maxResolution=this.aspectRatio*this.extent.getWidth()/this.size.w;}
OpenLayers.Layer.prototype.setMap.apply(this,arguments);},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);var firstRendering=(this.tile==null);if(zoomChanged||firstRendering){this.setTileSize();var ul=new OpenLayers.LonLat(this.extent.left,this.extent.top);var ulPx=this.map.getLayerPxFromLonLat(ul);if(firstRendering){this.tile=new OpenLayers.Tile.Image(this,ulPx,this.extent,null,this.tileSize);this.addTileMonitoringHooks(this.tile);}else{this.tile.size=this.tileSize.clone();this.tile.position=ulPx.clone();}
this.tile.draw();}},setTileSize:function(){var tileWidth=this.extent.getWidth()/this.map.getResolution();var tileHeight=this.extent.getHeight()/this.map.getResolution();this.tileSize=new OpenLayers.Size(tileWidth,tileHeight);},addTileMonitoringHooks:function(tile){tile.onLoadStart=function(){this.events.triggerEvent("loadstart");};tile.events.register("loadstart",this,tile.onLoadStart);tile.onLoadEnd=function(){this.events.triggerEvent("loadend");};tile.events.register("loadend",this,tile.onLoadEnd);tile.events.register("unload",this,tile.onLoadEnd);},removeTileMonitoringHooks:function(tile){tile.unload();tile.events.un({"loadstart":tile.onLoadStart,"loadend":tile.onLoadEnd,"unload":tile.onLoadEnd,scope:this});},setUrl:function(newUrl){this.url=newUrl;this.tile.draw();},getURL:function(bounds){return this.url;},CLASS_NAME:"OpenLayers.Layer.Image"});OpenLayers.Layer.Markers=OpenLayers.Class(OpenLayers.Layer,{isBaseLayer:false,markers:null,drawn:false,initialize:function(name,options){OpenLayers.Layer.prototype.initialize.apply(this,arguments);this.markers=[];},destroy:function(){this.clearMarkers();this.markers=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments);},setOpacity:function(opacity){if(opacity!=this.opacity){this.opacity=opacity;for(var i=0,len=this.markers.length;i<len;i++){this.markers[i].setOpacity(this.opacity);}}},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);if(zoomChanged||!this.drawn){for(var i=0,len=this.markers.length;i<len;i++){this.drawMarker(this.markers[i]);}
this.drawn=true;}},addMarker:function(marker){this.markers.push(marker);if(this.opacity!=null){marker.setOpacity(this.opacity);}
if(this.map&&this.map.getExtent()){marker.map=this.map;this.drawMarker(marker);}},removeMarker:function(marker){if(this.markers&&this.markers.length){OpenLayers.Util.removeItem(this.markers,marker);marker.erase();}},clearMarkers:function(){if(this.markers!=null){while(this.markers.length>0){this.removeMarker(this.markers[0]);}}},drawMarker:function(marker){var px=this.map.getLayerPxFromLonLat(marker.lonlat);if(px==null){marker.display(false);}else{if(!marker.isDrawn()){var markerImg=marker.draw(px);this.div.appendChild(markerImg);}else if(marker.icon){marker.icon.moveTo(px);}}},getDataExtent:function(){var maxExtent=null;if(this.markers&&(this.markers.length>0)){var maxExtent=new OpenLayers.Bounds();for(var i=0,len=this.markers.length;i<len;i++){var marker=this.markers[i];maxExtent.extend(marker.lonlat);}}
return maxExtent;},CLASS_NAME:"OpenLayers.Layer.Markers"});OpenLayers.Layer.SphericalMercator={getExtent:function(){var extent=null;if(this.sphericalMercator){extent=this.map.calculateBounds();}else{extent=OpenLayers.Layer.FixedZoomLevels.prototype.getExtent.apply(this);}
return extent;},getLonLatFromViewPortPx:function(viewPortPx){return OpenLayers.Layer.prototype.getLonLatFromViewPortPx.apply(this,arguments);},getViewPortPxFromLonLat:function(lonlat){return OpenLayers.Layer.prototype.getViewPortPxFromLonLat.apply(this,arguments);},initMercatorParameters:function(){this.RESOLUTIONS=[];var maxResolution=156543.0339;for(var zoom=0;zoom<=this.MAX_ZOOM_LEVEL;++zoom){this.RESOLUTIONS[zoom]=maxResolution/Math.pow(2,zoom);}
this.units="m";this.projection=this.projection||"EPSG:900913";},forwardMercator:function(lon,lat){var x=lon*20037508.34/180;var y=Math.log(Math.tan((90+lat)*Math.PI/360))/(Math.PI/180);y=y*20037508.34/180;return new OpenLayers.LonLat(x,y);},inverseMercator:function(x,y){var lon=(x/20037508.34)*180;var lat=(y/20037508.34)*180;lat=180/Math.PI*(2*Math.atan(Math.exp(lat*Math.PI/180))-Math.PI/2);return new OpenLayers.LonLat(lon,lat);},projectForward:function(point){var lonlat=OpenLayers.Layer.SphericalMercator.forwardMercator(point.x,point.y);point.x=lonlat.lon;point.y=lonlat.lat;return point;},projectInverse:function(point){var lonlat=OpenLayers.Layer.SphericalMercator.inverseMercator(point.x,point.y);point.x=lonlat.lon;point.y=lonlat.lat;return point;}};OpenLayers.Projection.addTransform("EPSG:4326","EPSG:900913",OpenLayers.Layer.SphericalMercator.projectForward);OpenLayers.Projection.addTransform("EPSG:900913","EPSG:4326",OpenLayers.Layer.SphericalMercator.projectInverse);OpenLayers.Tile.WFS=OpenLayers.Class(OpenLayers.Tile,{features:null,url:null,request:null,initialize:function(layer,position,bounds,url,size){OpenLayers.Tile.prototype.initialize.apply(this,arguments);this.url=url;this.features=[];},destroy:function(){OpenLayers.Tile.prototype.destroy.apply(this,arguments);this.destroyAllFeatures();this.features=null;this.url=null;if(this.request){this.request.abort();this.request=null;}},clear:function(){this.destroyAllFeatures();},draw:function(){if(OpenLayers.Tile.prototype.draw.apply(this,arguments)){if(this.isLoading){this.events.triggerEvent("reload");}else{this.isLoading=true;this.events.triggerEvent("loadstart");}
this.loadFeaturesForRegion(this.requestSuccess);}},loadFeaturesForRegion:function(success,failure){if(this.request){this.request.abort();}
this.request=OpenLayers.Request.GET({url:this.url,success:success,failure:failure,scope:this});},requestSuccess:function(request){if(this.features){var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
if(this.layer.vectorMode){this.layer.addFeatures(this.layer.formatObject.read(doc));}else{var xml=new OpenLayers.Format.XML();if(typeof doc=="string"){doc=xml.read(doc);}
var resultFeatures=xml.getElementsByTagNameNS(doc,"http://www.opengis.net/gml","featureMember");this.addResults(resultFeatures);}}
if(this.events){this.events.triggerEvent("loadend");}
this.request=null;},addResults:function(results){for(var i=0;i<results.length;i++){var feature=new this.layer.featureClass(this.layer,results[i]);this.features.push(feature);}},destroyAllFeatures:function(){while(this.features.length>0){var feature=this.features.shift();feature.destroy();}},CLASS_NAME:"OpenLayers.Tile.WFS"});OpenLayers.Control.DrawFeature=OpenLayers.Class(OpenLayers.Control,{layer:null,callbacks:null,EVENT_TYPES:["featureadded"],multi:false,featureAdded:function(){},handlerOptions:null,initialize:function(layer,handler,options){this.EVENT_TYPES=OpenLayers.Control.DrawFeature.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES);OpenLayers.Control.prototype.initialize.apply(this,[options]);this.callbacks=OpenLayers.Util.extend({done:this.drawFeature,modify:function(vertex,feature){this.layer.events.triggerEvent("sketchmodified",{vertex:vertex,feature:feature});},create:function(vertex,feature){this.layer.events.triggerEvent("sketchstarted",{vertex:vertex,feature:feature});}},this.callbacks);this.layer=layer;this.handlerOptions=this.handlerOptions||{};if(!("multi"in this.handlerOptions)){this.handlerOptions.multi=this.multi;}
var sketchStyle=this.layer.styleMap&&this.layer.styleMap.styles.temporary;if(sketchStyle){this.handlerOptions.layerOptions=OpenLayers.Util.applyDefaults(this.handlerOptions.layerOptions,{styleMap:new OpenLayers.StyleMap({"default":sketchStyle})});}
this.handler=new handler(this,this.callbacks,this.handlerOptions);},drawFeature:function(geometry){var feature=new OpenLayers.Feature.Vector(geometry);var proceed=this.layer.events.triggerEvent("sketchcomplete",{feature:feature});if(proceed!==false){feature.state=OpenLayers.State.INSERT;this.layer.addFeatures([feature]);this.featureAdded(feature);this.events.triggerEvent("featureadded",{feature:feature});}},CLASS_NAME:"OpenLayers.Control.DrawFeature"});OpenLayers.Control.Measure=OpenLayers.Class(OpenLayers.Control,{EVENT_TYPES:['measure','measurepartial'],handlerOptions:null,callbacks:null,displaySystem:'metric',geodesic:false,displaySystemUnits:{geographic:['dd'],english:['mi','ft','in'],metric:['km','m']},partialDelay:300,delayedTrigger:null,persist:false,initialize:function(handler,options){this.EVENT_TYPES=OpenLayers.Control.Measure.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES);OpenLayers.Control.prototype.initialize.apply(this,[options]);this.callbacks=OpenLayers.Util.extend({done:this.measureComplete,point:this.measurePartial},this.callbacks);this.handlerOptions=OpenLayers.Util.extend({persist:this.persist},this.handlerOptions);this.handler=new handler(this,this.callbacks,this.handlerOptions);},cancel:function(){this.handler.cancel();},updateHandler:function(handler,options){var active=this.active;if(active){this.deactivate();}
this.handler=new handler(this,this.callbacks,options);if(active){this.activate();}},measureComplete:function(geometry){if(this.delayedTrigger){window.clearTimeout(this.delayedTrigger);}
this.measure(geometry,"measure");},measurePartial:function(point,geometry){if(geometry.getLength()>0){geometry=geometry.clone();this.delayedTrigger=window.setTimeout(OpenLayers.Function.bind(function(){this.measure(geometry,"measurepartial");},this),this.partialDelay);}},measure:function(geometry,eventType){var stat,order;if(geometry.CLASS_NAME.indexOf('LineString')>-1){stat=this.getBestLength(geometry);order=1;}else{stat=this.getBestArea(geometry);order=2;}
this.events.triggerEvent(eventType,{measure:stat[0],units:stat[1],order:order,geometry:geometry});},getBestArea:function(geometry){var units=this.displaySystemUnits[this.displaySystem];var unit,area;for(var i=0,len=units.length;i<len;++i){unit=units[i];area=this.getArea(geometry,unit);if(area>1){break;}}
return[area,unit];},getArea:function(geometry,units){var area,geomUnits;if(this.geodesic){area=geometry.getGeodesicArea(this.map.getProjectionObject());geomUnits="m";}else{area=geometry.getArea();geomUnits=this.map.getUnits();}
var inPerDisplayUnit=OpenLayers.INCHES_PER_UNIT[units];if(inPerDisplayUnit){var inPerMapUnit=OpenLayers.INCHES_PER_UNIT[geomUnits];area*=Math.pow((inPerMapUnit/inPerDisplayUnit),2);}
return area;},getBestLength:function(geometry){var units=this.displaySystemUnits[this.displaySystem];var unit,length;for(var i=0,len=units.length;i<len;++i){unit=units[i];length=this.getLength(geometry,unit);if(length>1){break;}}
return[length,unit];},getLength:function(geometry,units){var length,geomUnits;if(this.geodesic){length=geometry.getGeodesicLength(this.map.getProjectionObject());geomUnits="m";}else{length=geometry.getLength();geomUnits=this.map.getUnits();}
var inPerDisplayUnit=OpenLayers.INCHES_PER_UNIT[units];if(inPerDisplayUnit){var inPerMapUnit=OpenLayers.INCHES_PER_UNIT[geomUnits];length*=(inPerMapUnit/inPerDisplayUnit);}
return length;},CLASS_NAME:"OpenLayers.Control.Measure"});OpenLayers.Control.ZoomBox=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,out:false,alwaysZoom:false,draw:function(){this.handler=new OpenLayers.Handler.Box(this,{done:this.zoomBox},{keyMask:this.keyMask});},zoomBox:function(position){if(position instanceof OpenLayers.Bounds){var bounds;if(!this.out){var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.left,position.bottom));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.right,position.top));bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);}else{var pixWidth=Math.abs(position.right-position.left);var pixHeight=Math.abs(position.top-position.bottom);var zoomFactor=Math.min((this.map.size.h/pixHeight),(this.map.size.w/pixWidth));var extent=this.map.getExtent();var center=this.map.getLonLatFromPixel(position.getCenterPixel());var xmin=center.lon-(extent.getWidth()/2)*zoomFactor;var xmax=center.lon+(extent.getWidth()/2)*zoomFactor;var ymin=center.lat-(extent.getHeight()/2)*zoomFactor;var ymax=center.lat+(extent.getHeight()/2)*zoomFactor;bounds=new OpenLayers.Bounds(xmin,ymin,xmax,ymax);}
var lastZoom=this.map.getZoom();this.map.zoomToExtent(bounds);if(lastZoom==this.map.getZoom()&&this.alwaysZoom==true){this.map.zoomTo(lastZoom+(this.out?-1:1));}}else{if(!this.out){this.map.setCenter(this.map.getLonLatFromPixel(position),this.map.getZoom()+1);}else{this.map.setCenter(this.map.getLonLatFromPixel(position),this.map.getZoom()-1);}}},CLASS_NAME:"OpenLayers.Control.ZoomBox"});OpenLayers.Format.WFSCapabilities.v1_0_0=OpenLayers.Class(OpenLayers.Format.WFSCapabilities.v1,{initialize:function(options){OpenLayers.Format.WFSCapabilities.v1.prototype.initialize.apply(this,[options]);},read_cap_Service:function(capabilities,node){var service={};this.runChildNodes(service,node);capabilities.service=service;},read_cap_Fees:function(service,node){var fees=this.getChildValue(node);if(fees&&fees.toLowerCase()!="none"){service.fees=fees;}},read_cap_AccessConstraints:function(service,node){var constraints=this.getChildValue(node);if(constraints&&constraints.toLowerCase()!="none"){service.accessConstraints=constraints;}},read_cap_OnlineResource:function(service,node){var onlineResource=this.getChildValue(node);if(onlineResource&&onlineResource.toLowerCase()!="none"){service.onlineResource=onlineResource;}},read_cap_Keywords:function(service,node){var keywords=this.getChildValue(node);if(keywords&&keywords.toLowerCase()!="none"){service.keywords=keywords.split(', ');}},read_cap_Capability:function(capabilities,node){var capability={};this.runChildNodes(capability,node);capabilities.capability=capability;},read_cap_Request:function(obj,node){var request={};this.runChildNodes(request,node);obj.request=request;},read_cap_GetFeature:function(request,node){var getfeature={href:{},formats:[]};this.runChildNodes(getfeature,node);request.getfeature=getfeature;},read_cap_ResultFormat:function(obj,node){var children=node.childNodes;var childNode;for(var i=0;i<children.length;i++){childNode=children[i];if(childNode.nodeType==1){obj.formats.push(childNode.nodeName);}}},read_cap_DCPType:function(obj,node){this.runChildNodes(obj,node);},read_cap_HTTP:function(obj,node){this.runChildNodes(obj.href,node);},read_cap_Get:function(obj,node){obj.get=node.getAttribute("onlineResource");},read_cap_Post:function(obj,node){obj.post=node.getAttribute("onlineResource");},CLASS_NAME:"OpenLayers.Format.WFSCapabilities.v1_0_0"});OpenLayers.Format.WFSCapabilities.v1_1_0=OpenLayers.Class(OpenLayers.Format.WFSCapabilities.v1,{initialize:function(options){OpenLayers.Format.WFSCapabilities.v1.prototype.initialize.apply(this,[options]);},CLASS_NAME:"OpenLayers.Format.WFSCapabilities.v1_1_0"});OpenLayers.Format.WKT=OpenLayers.Class(OpenLayers.Format,{initialize:function(options){this.regExes={'typeStr':/^\s*(\w+)\s*\(\s*(.*)\s*\)\s*$/,'spaces':/\s+/,'parenComma':/\)\s*,\s*\(/,'doubleParenComma':/\)\s*\)\s*,\s*\(\s*\(/,'trimParens':/^\s*\(?(.*?)\)?\s*$/};OpenLayers.Format.prototype.initialize.apply(this,[options]);},read:function(wkt){var features,type,str;var matches=this.regExes.typeStr.exec(wkt);if(matches){type=matches[1].toLowerCase();str=matches[2];if(this.parse[type]){features=this.parse[type].apply(this,[str]);}
if(this.internalProjection&&this.externalProjection){if(features&&features.CLASS_NAME=="OpenLayers.Feature.Vector"){features.geometry.transform(this.externalProjection,this.internalProjection);}else if(features&&type!="geometrycollection"&&typeof features=="object"){for(var i=0,len=features.length;i<len;i++){var component=features[i];component.geometry.transform(this.externalProjection,this.internalProjection);}}}}
return features;},write:function(features){var collection,geometry,type,data,isCollection;if(features.constructor==Array){collection=features;isCollection=true;}else{collection=[features];isCollection=false;}
var pieces=[];if(isCollection){pieces.push('GEOMETRYCOLLECTION(');}
for(var i=0,len=collection.length;i<len;++i){if(isCollection&&i>0){pieces.push(',');}
geometry=collection[i].geometry;type=geometry.CLASS_NAME.split('.')[2].toLowerCase();if(!this.extract[type]){return null;}
if(this.internalProjection&&this.externalProjection){geometry=geometry.clone();geometry.transform(this.internalProjection,this.externalProjection);}
data=this.extract[type].apply(this,[geometry]);pieces.push(type.toUpperCase()+'('+data+')');}
if(isCollection){pieces.push(')');}
return pieces.join('');},extract:{'point':function(point){return point.x+' '+point.y;},'multipoint':function(multipoint){var array=[];for(var i=0,len=multipoint.components.length;i<len;++i){array.push('('+
this.extract.point.apply(this,[multipoint.components[i]])+')');}
return array.join(',');},'linestring':function(linestring){var array=[];for(var i=0,len=linestring.components.length;i<len;++i){array.push(this.extract.point.apply(this,[linestring.components[i]]));}
return array.join(',');},'multilinestring':function(multilinestring){var array=[];for(var i=0,len=multilinestring.components.length;i<len;++i){array.push('('+
this.extract.linestring.apply(this,[multilinestring.components[i]])+')');}
return array.join(',');},'polygon':function(polygon){var array=[];for(var i=0,len=polygon.components.length;i<len;++i){array.push('('+
this.extract.linestring.apply(this,[polygon.components[i]])+')');}
return array.join(',');},'multipolygon':function(multipolygon){var array=[];for(var i=0,len=multipolygon.components.length;i<len;++i){array.push('('+
this.extract.polygon.apply(this,[multipolygon.components[i]])+')');}
return array.join(',');}},parse:{'point':function(str){var coords=OpenLayers.String.trim(str).split(this.regExes.spaces);return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(coords[0],coords[1]));},'multipoint':function(str){var point;var points=OpenLayers.String.trim(str).split(this.regExes.parenComma);var components=[];for(var i=0,len=points.length;i<len;++i){point=points[i].replace(this.regExes.trimParens,'$1');components.push(this.parse.point.apply(this,[point]).geometry);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPoint(components));},'linestring':function(str){var points=OpenLayers.String.trim(str).split(',');var components=[];for(var i=0,len=points.length;i<len;++i){components.push(this.parse.point.apply(this,[points[i]]).geometry);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(components));},'multilinestring':function(str){var line;var lines=OpenLayers.String.trim(str).split(this.regExes.parenComma);var components=[];for(var i=0,len=lines.length;i<len;++i){line=lines[i].replace(this.regExes.trimParens,'$1');components.push(this.parse.linestring.apply(this,[line]).geometry);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiLineString(components));},'polygon':function(str){var ring,linestring,linearring;var rings=OpenLayers.String.trim(str).split(this.regExes.parenComma);var components=[];for(var i=0,len=rings.length;i<len;++i){ring=rings[i].replace(this.regExes.trimParens,'$1');linestring=this.parse.linestring.apply(this,[ring]).geometry;linearring=new OpenLayers.Geometry.LinearRing(linestring.components);components.push(linearring);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon(components));},'multipolygon':function(str){var polygon;var polygons=OpenLayers.String.trim(str).split(this.regExes.doubleParenComma);var components=[];for(var i=0,len=polygons.length;i<len;++i){polygon=polygons[i].replace(this.regExes.trimParens,'$1');components.push(this.parse.polygon.apply(this,[polygon]).geometry);}
return new OpenLayers.Feature.Vector(new OpenLayers.Geometry.MultiPolygon(components));},'geometrycollection':function(str){str=str.replace(/,\s*([A-Za-z])/g,'|$1');var wktArray=OpenLayers.String.trim(str).split('|');var components=[];for(var i=0,len=wktArray.length;i<len;++i){components.push(OpenLayers.Format.WKT.prototype.read.apply(this,[wktArray[i]]));}
return components;}},CLASS_NAME:"OpenLayers.Format.WKT"});OpenLayers.Format.WMC.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{ol:"http://openlayers.org/context",wmc:"http://www.opengis.net/context",sld:"http://www.opengis.net/sld",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},schemaLocation:"",getNamespacePrefix:function(uri){var prefix=null;if(uri==null){prefix=this.namespaces[this.defaultPrefix];}else{for(prefix in this.namespaces){if(this.namespaces[prefix]==uri){break;}}}
return prefix;},defaultPrefix:"wmc",rootPrefix:null,defaultStyleName:"",defaultStyleTitle:"Default",initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;this.rootPrefix=root.prefix;var context={version:root.getAttribute("version")};this.runChildNodes(context,root);return context;},runChildNodes:function(obj,node){var children=node.childNodes;var childNode,processor,prefix,local;for(var i=0,len=children.length;i<len;++i){childNode=children[i];if(childNode.nodeType==1){prefix=this.getNamespacePrefix(childNode.namespaceURI);local=childNode.nodeName.split(":").pop();processor=this["read_"+prefix+"_"+local];if(processor){processor.apply(this,[obj,childNode]);}}}},read_wmc_General:function(context,node){this.runChildNodes(context,node);},read_wmc_BoundingBox:function(context,node){context.projection=node.getAttribute("SRS");context.bounds=new OpenLayers.Bounds(parseFloat(node.getAttribute("minx")),parseFloat(node.getAttribute("miny")),parseFloat(node.getAttribute("maxx")),parseFloat(node.getAttribute("maxy")));},read_wmc_LayerList:function(context,node){context.layersContext=[];this.runChildNodes(context,node);},read_wmc_Layer:function(context,node){var layerContext={visibility:(node.getAttribute("hidden")!="1"),queryable:(node.getAttribute("queryable")=="1"),formats:[],styles:[]};this.runChildNodes(layerContext,node);context.layersContext.push(layerContext);},read_wmc_Extension:function(obj,node){this.runChildNodes(obj,node);},read_ol_units:function(layerContext,node){layerContext.units=this.getChildValue(node);},read_ol_maxExtent:function(obj,node){var bounds=new OpenLayers.Bounds(node.getAttribute("minx"),node.getAttribute("miny"),node.getAttribute("maxx"),node.getAttribute("maxy"));obj.maxExtent=bounds;},read_ol_transparent:function(layerContext,node){layerContext.transparent=this.getChildValue(node);},read_ol_numZoomLevels:function(layerContext,node){layerContext.numZoomLevels=parseInt(this.getChildValue(node));},read_ol_opacity:function(layerContext,node){layerContext.opacity=parseFloat(this.getChildValue(node));},read_ol_singleTile:function(layerContext,node){layerContext.singleTile=(this.getChildValue(node)=="true");},read_ol_tileSize:function(layerContext,node){var obj={"width":node.getAttribute("width"),"height":node.getAttribute("height")};layerContext.tileSize=obj;},read_ol_isBaseLayer:function(layerContext,node){layerContext.isBaseLayer=(this.getChildValue(node)=="true");},read_ol_displayInLayerSwitcher:function(layerContext,node){layerContext.displayInLayerSwitcher=(this.getChildValue(node)=="true");},read_wmc_Server:function(layerContext,node){layerContext.version=node.getAttribute("version");var server={};var links=node.getElementsByTagName("OnlineResource");if(links.length>0){this.read_wmc_OnlineResource(server,links[0]);}
layerContext.url=server.href;},read_wmc_FormatList:function(layerContext,node){this.runChildNodes(layerContext,node);},read_wmc_Format:function(layerContext,node){var format={value:this.getChildValue(node)};if(node.getAttribute("current")=="1"){format.current=true;}
layerContext.formats.push(format);},read_wmc_StyleList:function(layerContext,node){this.runChildNodes(layerContext,node);},read_wmc_Style:function(layerContext,node){var style={};this.runChildNodes(style,node);if(node.getAttribute("current")=="1"){style.current=true;}
layerContext.styles.push(style);},read_wmc_SLD:function(style,node){this.runChildNodes(style,node);},read_sld_StyledLayerDescriptor:function(sld,node){var xml=OpenLayers.Format.XML.prototype.write.apply(this,[node]);sld.body=xml;},read_wmc_OnlineResource:function(obj,node){obj.href=this.getAttributeNS(node,this.namespaces.xlink,"href");},read_wmc_Name:function(obj,node){var name=this.getChildValue(node);if(name){obj.name=name;}},read_wmc_Title:function(obj,node){var title=this.getChildValue(node);if(title){obj.title=title;}},read_wmc_MetadataURL:function(layerContext,node){var metadataURL={};var links=node.getElementsByTagName("OnlineResource");if(links.length>0){this.read_wmc_OnlineResource(metadataURL,links[0]);}
layerContext.metadataURL=metadataURL.href;},read_wmc_Abstract:function(obj,node){var abst=this.getChildValue(node);if(abst){obj["abstract"]=abst;}},read_wmc_LegendURL:function(style,node){var legend={width:node.getAttribute('width'),height:node.getAttribute('height')};var links=node.getElementsByTagName("OnlineResource");if(links.length>0){this.read_wmc_OnlineResource(legend,links[0]);}
style.legend=legend;},write:function(context,options){var root=this.createElementDefaultNS("ViewContext");this.setAttributes(root,{version:this.VERSION,id:(options&&typeof options.id=="string")?options.id:OpenLayers.Util.createUniqueID("OpenLayers_Context_")});this.setAttributeNS(root,this.namespaces.xsi,"xsi:schemaLocation",this.schemaLocation);root.appendChild(this.write_wmc_General(context));root.appendChild(this.write_wmc_LayerList(context));return OpenLayers.Format.XML.prototype.write.apply(this,[root]);},createElementDefaultNS:function(name,childValue,attributes){var node=this.createElementNS(this.namespaces[this.defaultPrefix],name);if(childValue){node.appendChild(this.createTextNode(childValue));}
if(attributes){this.setAttributes(node,attributes);}
return node;},setAttributes:function(node,obj){var value;for(var name in obj){value=obj[name].toString();if(value.match(/[A-Z]/)){this.setAttributeNS(node,null,name,value);}else{node.setAttribute(name,value);}}},write_wmc_General:function(context){var node=this.createElementDefaultNS("General");if(context.size){node.appendChild(this.createElementDefaultNS("Window",null,{width:context.size.w,height:context.size.h}));}
var bounds=context.bounds;node.appendChild(this.createElementDefaultNS("BoundingBox",null,{minx:bounds.left.toPrecision(18),miny:bounds.bottom.toPrecision(18),maxx:bounds.right.toPrecision(18),maxy:bounds.top.toPrecision(18),SRS:context.projection}));node.appendChild(this.createElementDefaultNS("Title",context.title));node.appendChild(this.write_ol_MapExtension(context));return node;},write_ol_MapExtension:function(context){var node=this.createElementDefaultNS("Extension");var bounds=context.maxExtent;if(bounds){var maxExtent=this.createElementNS(this.namespaces.ol,"ol:maxExtent");this.setAttributes(maxExtent,{minx:bounds.left.toPrecision(18),miny:bounds.bottom.toPrecision(18),maxx:bounds.right.toPrecision(18),maxy:bounds.top.toPrecision(18)});node.appendChild(maxExtent);}
return node;},write_wmc_LayerList:function(context){var list=this.createElementDefaultNS("LayerList");for(var i=0,len=context.layersContext.length;i<len;++i){list.appendChild(this.write_wmc_Layer(context.layersContext[i]));}
return list;},write_wmc_Layer:function(context){var node=this.createElementDefaultNS("Layer",null,{queryable:context.queryable?"1":"0",hidden:context.visibility?"0":"1"});node.appendChild(this.write_wmc_Server(context));node.appendChild(this.createElementDefaultNS("Name",context.name));node.appendChild(this.createElementDefaultNS("Title",context.title));if(context.metadataURL){node.appendChild(this.write_wmc_MetadataURL(context.metadataURL));}
return node;},write_wmc_LayerExtension:function(context){var node=this.createElementDefaultNS("Extension");var bounds=context.maxExtent;var maxExtent=this.createElementNS(this.namespaces.ol,"ol:maxExtent");this.setAttributes(maxExtent,{minx:bounds.left.toPrecision(18),miny:bounds.bottom.toPrecision(18),maxx:bounds.right.toPrecision(18),maxy:bounds.top.toPrecision(18)});node.appendChild(maxExtent);if(context.tileSize&&!context.singleTile){var size=this.createElementNS(this.namespaces.ol,"ol:tileSize");this.setAttributes(size,context.tileSize);node.appendChild(size);}
var properties=["transparent","numZoomLevels","units","isBaseLayer","opacity","displayInLayerSwitcher","singleTile"];var child;for(var i=0,len=properties.length;i<len;++i){child=this.createOLPropertyNode(context,properties[i]);if(child){node.appendChild(child);}}
return node;},createOLPropertyNode:function(obj,prop){var node=null;if(obj[prop]!=null){node=this.createElementNS(this.namespaces.ol,"ol:"+prop);node.appendChild(this.createTextNode(obj[prop].toString()));}
return node;},write_wmc_Server:function(context){var node=this.createElementDefaultNS("Server");this.setAttributes(node,{service:"OGC:WMS",version:context.version});node.appendChild(this.write_wmc_OnlineResource(context.url));return node;},write_wmc_MetadataURL:function(metadataURL){var node=this.createElementDefaultNS("MetadataURL");node.appendChild(this.write_wmc_OnlineResource(metadataURL));return node;},write_wmc_FormatList:function(context){var node=this.createElementDefaultNS("FormatList");for(var i=0,len=context.formats.length;i<len;i++){var format=context.formats[i];node.appendChild(this.createElementDefaultNS("Format",format.value,(format.current&&format.current==true)?{current:"1"}:null));}
return node;},write_wmc_StyleList:function(layer){var node=this.createElementDefaultNS("StyleList");var styles=layer.styles;if(styles&&styles instanceof Array){var sld;for(var i=0,len=styles.length;i<len;i++){var s=styles[i];var style=this.createElementDefaultNS("Style",null,(s.current&&s.current==true)?{current:"1"}:null);if(s.href){sld=this.createElementDefaultNS("SLD");var link=this.write_wmc_OnlineResource(s.href);sld.appendChild(link);sld.appendChild(this.createElementDefaultNS("Name",s.name));if(s.title){sld.appendChild(this.createElementDefaultNS("Title",s.title));}
style.appendChild(sld);}else if(s.body){sld=this.createElementDefaultNS("SLD");var doc=OpenLayers.Format.XML.prototype.read.apply(this,[s.body]);var imported=doc.documentElement;if(sld.ownerDocument&&sld.ownerDocument.importNode){imported=sld.ownerDocument.importNode(imported,true);}
sld.appendChild(imported);sld.appendChild(this.createElementDefaultNS("Name",s.name));if(s.title){sld.appendChild(this.createElementDefaultNS("Title",s.title));}
style.appendChild(sld);}else{style.appendChild(this.createElementDefaultNS("Name",s.name));style.appendChild(this.createElementDefaultNS("Title",s.title));if(s['abstract']){style.appendChild(this.createElementDefaultNS("Abstract",s['abstract']));}}
node.appendChild(style);}}
return node;},write_wmc_OnlineResource:function(href){var node=this.createElementDefaultNS("OnlineResource");this.setAttributeNS(node,this.namespaces.xlink,"xlink:type","simple");this.setAttributeNS(node,this.namespaces.xlink,"xlink:href",href);return node;},CLASS_NAME:"OpenLayers.Format.WMC.v1"});OpenLayers.Format.WMSCapabilities.v1_1=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1,{readers:{"wms":OpenLayers.Util.applyDefaults({"WMT_MS_Capabilities":function(node,obj){this.readChildNodes(node,obj);},"Keyword":function(node,obj){if(obj.keywords){obj.keywords.push(this.getChildValue(node));}},"DescribeLayer":function(node,obj){obj.describelayer={formats:[]};this.readChildNodes(node,obj.describelayer);},"GetLegendGraphic":function(node,obj){obj.getlegendgraphic={formats:[]};this.readChildNodes(node,obj.getlegendgraphic);},"GetStyles":function(node,obj){obj.getstyles={formats:[]};this.readChildNodes(node,obj.getstyles);},"PutStyles":function(node,obj){obj.putstyles={formats:[]};this.readChildNodes(node,obj.putstyles);},"UserDefinedSymbolization":function(node,obj){var userSymbols={supportSLD:parseInt(node.getAttribute("SupportSLD"))==1,userLayer:parseInt(node.getAttribute("UserLayer"))==1,userStyle:parseInt(node.getAttribute("UserStyle"))==1,remoteWFS:parseInt(node.getAttribute("RemoteWFS"))==1};obj.userSymbols=userSymbols;},"LatLonBoundingBox":function(node,obj){obj.llbbox=[parseFloat(node.getAttribute("minx")),parseFloat(node.getAttribute("miny")),parseFloat(node.getAttribute("maxx")),parseFloat(node.getAttribute("maxy"))];},"BoundingBox":function(node,obj){var bbox=OpenLayers.Format.WMSCapabilities.v1.prototype.readers["wms"].BoundingBox.apply(this,[node,obj]);bbox.srs=node.getAttribute("SRS");obj.bbox[bbox.srs]=bbox;},"ScaleHint":function(node,obj){var min=node.getAttribute("min");var max=node.getAttribute("max");var rad2=Math.pow(2,0.5);var ipm=OpenLayers.INCHES_PER_UNIT["m"];obj.maxScale=parseFloat(((min/rad2)*ipm*OpenLayers.DOTS_PER_INCH).toPrecision(13));obj.minScale=parseFloat(((max/rad2)*ipm*OpenLayers.DOTS_PER_INCH).toPrecision(13));},"Dimension":function(node,obj){var name=node.getAttribute("name").toLowerCase();var dim={name:name,units:node.getAttribute("units"),unitsymbol:node.getAttribute("unitSymbol")};obj.dimensions[dim.name]=dim;},"Extent":function(node,obj){var name=node.getAttribute("name").toLowerCase();if(name in obj["dimensions"]){var extent=obj.dimensions[name];extent.nearestVal=node.getAttribute("nearestValue")==="1";extent.multipleVal=node.getAttribute("multipleValues")==="1";extent.current=node.getAttribute("current")==="1";extent["default"]=node.getAttribute("default")||"";var values=this.getChildValue(node);extent.values=values.split(",");}}},OpenLayers.Format.WMSCapabilities.v1.prototype.readers["wms"])},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_1"});OpenLayers.Format.WMSCapabilities.v1_3=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1,{readers:{"wms":OpenLayers.Util.applyDefaults({"WMS_Capabilities":function(node,obj){this.readChildNodes(node,obj);},"LayerLimit":function(node,obj){obj.layerLimit=parseInt(this.getChildValue(node));},"MaxWidth":function(node,obj){obj.maxWidth=parseInt(this.getChildValue(node));},"MaxHeight":function(node,obj){obj.maxHeight=parseInt(this.getChildValue(node));},"BoundingBox":function(node,obj){var bbox=OpenLayers.Format.WMSCapabilities.v1.prototype.readers["wms"].BoundingBox.apply(this,[node,obj]);bbox.srs=node.getAttribute("CRS");obj.bbox[bbox.srs]=bbox;},"CRS":function(node,obj){this.readers.wms.SRS.apply(this,[node,obj]);},"EX_GeographicBoundingBox":function(node,obj){obj.llbbox=[];this.readChildNodes(node,obj.llbbox);},"westBoundLongitude":function(node,obj){obj[0]=this.getChildValue(node);},"eastBoundLongitude":function(node,obj){obj[2]=this.getChildValue(node);},"southBoundLatitude":function(node,obj){obj[1]=this.getChildValue(node);},"northBoundLatitude":function(node,obj){obj[3]=this.getChildValue(node);},"MinScaleDenominator":function(node,obj){obj.maxScale=parseFloat(this.getChildValue(node)).toPrecision(16);},"MaxScaleDenominator":function(node,obj){obj.minScale=parseFloat(this.getChildValue(node)).toPrecision(16);},"Dimension":function(node,obj){var name=node.getAttribute("name").toLowerCase();var dim={name:name,units:node.getAttribute("units"),unitsymbol:node.getAttribute("unitSymbol"),nearestVal:node.getAttribute("nearestValue")==="1",multipleVal:node.getAttribute("multipleValues")==="1","default":node.getAttribute("default")||"",current:node.getAttribute("current")==="1",values:this.getChildValue(node).split(",")};obj.dimensions[dim.name]=dim;},"Keyword":function(node,obj){var keyword={value:this.getChildValue(node),vocabulary:node.getAttribute("vocabulary")};if(obj.keywords){obj.keywords.push(keyword);}}},OpenLayers.Format.WMSCapabilities.v1.prototype.readers["wms"]),"sld":{"UserDefinedSymbolization":function(node,obj){this.readers.wms.UserDefinedSymbolization.apply(this,[node,obj]);obj.userSymbols.inlineFeature=parseInt(node.getAttribute("InlineFeature"))==1;obj.userSymbols.remoteWCS=parseInt(node.getAttribute("RemoteWCS"))==1;},"DescribeLayer":function(node,obj){this.readers.wms.DescribeLayer.apply(this,[node,obj]);},"GetLegendGraphic":function(node,obj){this.readers.wms.GetLegendGraphic.apply(this,[node,obj]);}}},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_3"});OpenLayers.Format.WMTSCapabilities.v1_0_0=OpenLayers.Class(OpenLayers.Format.OWSCommon.v1_1_0,{version:"1.0.0",namespaces:{ows:"http://www.opengis.net/ows/1.1",wmts:"http://www.opengis.net/wmts/1.0",xlink:"http://www.w3.org/1999/xlink"},yx:null,defaultPrefix:"wmts",initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);this.options=options;var yx=OpenLayers.Util.extend({},OpenLayers.Format.WMTSCapabilities.prototype.yx);this.yx=OpenLayers.Util.extend(yx,this.yx);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var capabilities={};this.readNode(data,capabilities);capabilities.version=this.version;return capabilities;},readers:{"wmts":{"Capabilities":function(node,obj){this.readChildNodes(node,obj);},"Contents":function(node,obj){obj.contents={};obj.contents.layers=[];obj.contents.tileMatrixSets={};this.readChildNodes(node,obj.contents);},"Layer":function(node,obj){var layer={styles:[],formats:[],tileMatrixSetLinks:[]};layer.layers=[];this.readChildNodes(node,layer);obj.layers.push(layer);},"Style":function(node,obj){var style={};style.isDefault=(node.getAttribute("isDefault")==="true");this.readChildNodes(node,style);obj.styles.push(style);},"Format":function(node,obj){obj.formats.push(this.getChildValue(node));},"TileMatrixSetLink":function(node,obj){var tileMatrixSetLink={};this.readChildNodes(node,tileMatrixSetLink);obj.tileMatrixSetLinks.push(tileMatrixSetLink);},"TileMatrixSet":function(node,obj){if(obj.layers){var tileMatrixSet={matrixIds:[]};this.readChildNodes(node,tileMatrixSet);obj.tileMatrixSets[tileMatrixSet.identifier]=tileMatrixSet;}else{obj.tileMatrixSet=this.getChildValue(node);}},"TileMatrix":function(node,obj){var tileMatrix={supportedCRS:obj.supportedCRS};this.readChildNodes(node,tileMatrix);obj.matrixIds.push(tileMatrix);},"ScaleDenominator":function(node,obj){obj.scaleDenominator=parseFloat(this.getChildValue(node));},"TopLeftCorner":function(node,obj){var topLeftCorner=this.getChildValue(node);var coords=topLeftCorner.split(" ");var yx;if(obj.supportedCRS){var crs=obj.supportedCRS.replace(/urn:ogc:def:crs:(\w+):.+:(\w+)$/,"urn:ogc:def:crs:$1::$2");yx=!!this.yx[crs];}
if(yx){obj.topLeftCorner=new OpenLayers.LonLat(coords[1],coords[0]);}else{obj.topLeftCorner=new OpenLayers.LonLat(coords[0],coords[1]);}},"TileWidth":function(node,obj){obj.tileWidth=parseInt(this.getChildValue(node));},"TileHeight":function(node,obj){obj.tileHeight=parseInt(this.getChildValue(node));},"MatrixWidth":function(node,obj){obj.matrixWidth=parseInt(this.getChildValue(node));},"MatrixHeight":function(node,obj){obj.matrixHeight=parseInt(this.getChildValue(node));},"WSDL":function(node,obj){obj.wsdl={};obj.wsdl.href=node.getAttribute("xlink:href");},"ServiceMetadataURL":function(node,obj){obj.serviceMetadataUrl={};obj.serviceMetadataUrl.href=node.getAttribute("xlink:href");}},"ows":OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers["ows"]},CLASS_NAME:"OpenLayers.Format.WMTSCapabilities.v1_0_0"});OpenLayers.Layer.Boxes=OpenLayers.Class(OpenLayers.Layer.Markers,{initialize:function(name,options){OpenLayers.Layer.Markers.prototype.initialize.apply(this,arguments);},drawMarker:function(marker){var bounds=marker.bounds;var topleft=this.map.getLayerPxFromLonLat(new OpenLayers.LonLat(bounds.left,bounds.top));var botright=this.map.getLayerPxFromLonLat(new OpenLayers.LonLat(bounds.right,bounds.bottom));if(botright==null||topleft==null){marker.display(false);}else{var sz=new OpenLayers.Size(Math.max(1,botright.x-topleft.x),Math.max(1,botright.y-topleft.y));var markerDiv=marker.draw(topleft,sz);if(!marker.drawn){this.div.appendChild(markerDiv);marker.drawn=true;}}},removeMarker:function(marker){OpenLayers.Util.removeItem(this.markers,marker);if((marker.div!=null)&&(marker.div.parentNode==this.div)){this.div.removeChild(marker.div);}},CLASS_NAME:"OpenLayers.Layer.Boxes"});OpenLayers.Layer.GeoRSS=OpenLayers.Class(OpenLayers.Layer.Markers,{location:null,features:null,formatOptions:null,selectedFeature:null,icon:null,popupSize:null,useFeedTitle:true,initialize:function(name,location,options){OpenLayers.Layer.Markers.prototype.initialize.apply(this,[name,options]);this.location=location;this.features=[];},destroy:function(){OpenLayers.Layer.Markers.prototype.destroy.apply(this,arguments);this.clearFeatures();this.features=null;},loadRSS:function(){if(!this.loaded){this.events.triggerEvent("loadstart");OpenLayers.Request.GET({url:this.location,success:this.parseData,scope:this});this.loaded=true;}},moveTo:function(bounds,zoomChanged,minor){OpenLayers.Layer.Markers.prototype.moveTo.apply(this,arguments);if(this.visibility&&!this.loaded){this.loadRSS();}},parseData:function(ajaxRequest){var doc=ajaxRequest.responseXML;if(!doc||!doc.documentElement){doc=OpenLayers.Format.XML.prototype.read(ajaxRequest.responseText);}
if(this.useFeedTitle){var name=null;try{name=doc.getElementsByTagNameNS('*','title')[0].firstChild.nodeValue;}
catch(e){name=doc.getElementsByTagName('title')[0].firstChild.nodeValue;}
if(name){this.setName(name);}}
var options={};OpenLayers.Util.extend(options,this.formatOptions);if(this.map&&!this.projection.equals(this.map.getProjectionObject())){options.externalProjection=this.projection;options.internalProjection=this.map.getProjectionObject();}
var format=new OpenLayers.Format.GeoRSS(options);var features=format.read(doc);for(var i=0,len=features.length;i<len;i++){var data={};var feature=features[i];if(!feature.geometry){continue;}
var title=feature.attributes.title?feature.attributes.title:"Untitled";var description=feature.attributes.description?feature.attributes.description:"No description.";var link=feature.attributes.link?feature.attributes.link:"";var location=feature.geometry.getBounds().getCenterLonLat();data.icon=this.icon==null?OpenLayers.Marker.defaultIcon():this.icon.clone();data.popupSize=this.popupSize?this.popupSize.clone():new OpenLayers.Size(250,120);if(title||description){data.title=title;data.description=description;var contentHTML='<div class="olLayerGeoRSSClose">[x]</div>';contentHTML+='<div class="olLayerGeoRSSTitle">';if(link){contentHTML+='<a class="link" href="'+link+'" target="_blank">';}
contentHTML+=title;if(link){contentHTML+='</a>';}
contentHTML+='</div>';contentHTML+='<div style="" class="olLayerGeoRSSDescription">';contentHTML+=description;contentHTML+='</div>';data['popupContentHTML']=contentHTML;}
var feature=new OpenLayers.Feature(this,location,data);this.features.push(feature);var marker=feature.createMarker();marker.events.register('click',feature,this.markerClick);this.addMarker(marker);}
this.events.triggerEvent("loadend");},markerClick:function(evt){var sameMarkerClicked=(this==this.layer.selectedFeature);this.layer.selectedFeature=(!sameMarkerClicked)?this:null;for(var i=0,len=this.layer.map.popups.length;i<len;i++){this.layer.map.removePopup(this.layer.map.popups[i]);}
if(!sameMarkerClicked){var popup=this.createPopup();OpenLayers.Event.observe(popup.div,"click",OpenLayers.Function.bind(function(){for(var i=0,len=this.layer.map.popups.length;i<len;i++){this.layer.map.removePopup(this.layer.map.popups[i]);}},this));this.layer.map.addPopup(popup);}
OpenLayers.Event.stop(evt);},clearFeatures:function(){if(this.features!=null){while(this.features.length>0){var feature=this.features[0];OpenLayers.Util.removeItem(this.features,feature);feature.destroy();}}},CLASS_NAME:"OpenLayers.Layer.GeoRSS"});OpenLayers.Layer.Google=OpenLayers.Class(OpenLayers.Layer.EventPane,OpenLayers.Layer.FixedZoomLevels,{MIN_ZOOM_LEVEL:0,MAX_ZOOM_LEVEL:21,RESOLUTIONS:[1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125,0.00002145767211914062,0.00001072883605957031,0.00000536441802978515,0.00000268220901489257,0.0000013411045074462891,0.00000067055225372314453],type:null,wrapDateLine:true,sphericalMercator:false,version:null,initialize:function(name,options){options=options||{};if(!options.version){options.version=typeof GMap2==="function"?"2":"3";}
var mixin=OpenLayers.Layer.Google["v"+
options.version.replace(/\./g,"_")];if(mixin){OpenLayers.Util.applyDefaults(options,mixin);}else{throw"Unsupported Google Maps API version: "+options.version;}
OpenLayers.Util.applyDefaults(options,mixin.DEFAULTS);if(options.maxExtent){options.maxExtent=options.maxExtent.clone();}
OpenLayers.Layer.EventPane.prototype.initialize.apply(this,[name,options]);OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this,[name,options]);if(this.sphericalMercator){OpenLayers.Util.extend(this,OpenLayers.Layer.SphericalMercator);this.initMercatorParameters();}},clone:function(){return new OpenLayers.Layer.Google(this.name,this.getOptions());},setVisibility:function(visible){var opacity=this.opacity==null?1:this.opacity;OpenLayers.Layer.EventPane.prototype.setVisibility.apply(this,arguments);this.setOpacity(opacity);},display:function(visible){if(!this._dragging){this.setGMapVisibility(visible);}
OpenLayers.Layer.EventPane.prototype.display.apply(this,arguments);},moveTo:function(bounds,zoomChanged,dragging){this._dragging=dragging;OpenLayers.Layer.EventPane.prototype.moveTo.apply(this,arguments);delete this._dragging;},setOpacity:function(opacity){if(opacity!==this.opacity){if(this.map!=null){this.map.events.triggerEvent("changelayer",{layer:this,property:"opacity"});}
this.opacity=opacity;}
if(this.getVisibility()){var container=this.getMapContainer();OpenLayers.Util.modifyDOMElement(container,null,null,null,null,null,null,opacity);}},destroy:function(){if(this.map){this.setGMapVisibility(false);var cache=OpenLayers.Layer.Google.cache[this.map.id];if(cache&&cache.count<=1){this.removeGMapElements();}}
OpenLayers.Layer.EventPane.prototype.destroy.apply(this,arguments);},removeGMapElements:function(){var cache=OpenLayers.Layer.Google.cache[this.map.id];if(cache){var container=this.mapObject&&this.getMapContainer();if(container&&container.parentNode){container.parentNode.removeChild(container);}
var termsOfUse=cache.termsOfUse;if(termsOfUse&&termsOfUse.parentNode){termsOfUse.parentNode.removeChild(termsOfUse);}
var poweredBy=cache.poweredBy;if(poweredBy&&poweredBy.parentNode){poweredBy.parentNode.removeChild(poweredBy);}}},removeMap:function(map){if(this.visibility&&this.mapObject){this.setGMapVisibility(false);}
var cache=OpenLayers.Layer.Google.cache[map.id];if(cache){if(cache.count<=1){this.removeGMapElements();delete OpenLayers.Layer.Google.cache[map.id];}else{--cache.count;}}
delete this.termsOfUse;delete this.poweredBy;delete this.mapObject;delete this.dragObject;OpenLayers.Layer.EventPane.prototype.removeMap.apply(this,arguments);},getOLBoundsFromMapObjectBounds:function(moBounds){var olBounds=null;if(moBounds!=null){var sw=moBounds.getSouthWest();var ne=moBounds.getNorthEast();if(this.sphericalMercator){sw=this.forwardMercator(sw.lng(),sw.lat());ne=this.forwardMercator(ne.lng(),ne.lat());}else{sw=new OpenLayers.LonLat(sw.lng(),sw.lat());ne=new OpenLayers.LonLat(ne.lng(),ne.lat());}
olBounds=new OpenLayers.Bounds(sw.lon,sw.lat,ne.lon,ne.lat);}
return olBounds;},getWarningHTML:function(){return OpenLayers.i18n("googleWarning");},getMapObjectCenter:function(){return this.mapObject.getCenter();},getMapObjectZoom:function(){return this.mapObject.getZoom();},getLongitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.lng(),moLonLat.lat()).lon:moLonLat.lng();},getLatitudeFromMapObjectLonLat:function(moLonLat){var lat=this.sphericalMercator?this.forwardMercator(moLonLat.lng(),moLonLat.lat()).lat:moLonLat.lat();return lat;},getXFromMapObjectPixel:function(moPixel){return moPixel.x;},getYFromMapObjectPixel:function(moPixel){return moPixel.y;},CLASS_NAME:"OpenLayers.Layer.Google"});OpenLayers.Layer.Google.cache={};OpenLayers.Layer.Google.v2={termsOfUse:null,poweredBy:null,dragObject:null,loadMapObject:function(){if(!this.type){this.type=G_NORMAL_MAP;}
var mapObject,termsOfUse,poweredBy;var cache=OpenLayers.Layer.Google.cache[this.map.id];if(cache){mapObject=cache.mapObject;termsOfUse=cache.termsOfUse;poweredBy=cache.poweredBy;++cache.count;}else{var container=this.map.viewPortDiv;var div=document.createElement("div");div.id=this.map.id+"_GMap2Container";div.style.position="absolute";div.style.width="100%";div.style.height="100%";container.appendChild(div);try{mapObject=new GMap2(div);termsOfUse=div.lastChild;container.appendChild(termsOfUse);termsOfUse.style.zIndex="1100";termsOfUse.style.right="";termsOfUse.style.bottom="";termsOfUse.className="olLayerGoogleCopyright";poweredBy=div.lastChild;container.appendChild(poweredBy);poweredBy.style.zIndex="1100";poweredBy.style.right="";poweredBy.style.bottom="";poweredBy.className="olLayerGooglePoweredBy gmnoprint";}catch(e){throw(e);}
OpenLayers.Layer.Google.cache[this.map.id]={mapObject:mapObject,termsOfUse:termsOfUse,poweredBy:poweredBy,count:1};}
this.mapObject=mapObject;this.termsOfUse=termsOfUse;this.poweredBy=poweredBy;if(OpenLayers.Util.indexOf(this.mapObject.getMapTypes(),this.type)===-1){this.mapObject.addMapType(this.type);}
if(typeof mapObject.getDragObject=="function"){this.dragObject=mapObject.getDragObject();}else{this.dragPanMapObject=null;}
if(this.isBaseLayer===false){this.setGMapVisibility(this.div.style.display!=="none");}},onMapResize:function(){if(this.visibility&&this.mapObject.isLoaded()){this.mapObject.checkResize();}else{if(!this._resized){var layer=this;var handle=GEvent.addListener(this.mapObject,"load",function(){GEvent.removeListener(handle);delete layer._resized;layer.mapObject.checkResize();layer.moveTo(layer.map.getCenter(),layer.map.getZoom());});}
this._resized=true;}},setGMapVisibility:function(visible){var cache=OpenLayers.Layer.Google.cache[this.map.id];if(cache){var container=this.mapObject.getContainer();if(visible===true){this.mapObject.setMapType(this.type);container.style.display="";this.termsOfUse.style.left="";this.termsOfUse.style.display="";this.poweredBy.style.display="";cache.displayed=this.id;}else{if(cache.displayed===this.id){delete cache.displayed;}
if(!cache.displayed){container.style.display="none";this.termsOfUse.style.display="none";this.termsOfUse.style.left="-9999px";this.poweredBy.style.display="none";}}}},getMapContainer:function(){return this.mapObject.getContainer();},getMapObjectBoundsFromOLBounds:function(olBounds){var moBounds=null;if(olBounds!=null){var sw=this.sphericalMercator?this.inverseMercator(olBounds.bottom,olBounds.left):new OpenLayers.LonLat(olBounds.bottom,olBounds.left);var ne=this.sphericalMercator?this.inverseMercator(olBounds.top,olBounds.right):new OpenLayers.LonLat(olBounds.top,olBounds.right);moBounds=new GLatLngBounds(new GLatLng(sw.lat,sw.lon),new GLatLng(ne.lat,ne.lon));}
return moBounds;},setMapObjectCenter:function(center,zoom){this.mapObject.setCenter(center,zoom);},dragPanMapObject:function(dX,dY){this.dragObject.moveBy(new GSize(-dX,dY));},getMapObjectLonLatFromMapObjectPixel:function(moPixel){return this.mapObject.fromContainerPixelToLatLng(moPixel);},getMapObjectPixelFromMapObjectLonLat:function(moLonLat){return this.mapObject.fromLatLngToContainerPixel(moLonLat);},getMapObjectZoomFromMapObjectBounds:function(moBounds){return this.mapObject.getBoundsZoomLevel(moBounds);},getMapObjectLonLatFromLonLat:function(lon,lat){var gLatLng;if(this.sphericalMercator){var lonlat=this.inverseMercator(lon,lat);gLatLng=new GLatLng(lonlat.lat,lonlat.lon);}else{gLatLng=new GLatLng(lat,lon);}
return gLatLng;},getMapObjectPixelFromXY:function(x,y){return new GPoint(x,y);}};OpenLayers.Layer.Grid=OpenLayers.Class(OpenLayers.Layer.HTTPRequest,{tileSize:null,grid:null,singleTile:false,ratio:1.5,buffer:2,numLoadingTiles:0,initialize:function(name,url,params,options){OpenLayers.Layer.HTTPRequest.prototype.initialize.apply(this,arguments);this.events.addEventType("tileloaded");this.grid=[];},destroy:function(){this.clearGrid();this.grid=null;this.tileSize=null;OpenLayers.Layer.HTTPRequest.prototype.destroy.apply(this,arguments);},clearGrid:function(){if(this.grid){for(var iRow=0,len=this.grid.length;iRow<len;iRow++){var row=this.grid[iRow];for(var iCol=0,clen=row.length;iCol<clen;iCol++){var tile=row[iCol];this.removeTileMonitoringHooks(tile);tile.destroy();}}
this.grid=[];}},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.Grid(this.name,this.url,this.params,this.getOptions());}
obj=OpenLayers.Layer.HTTPRequest.prototype.clone.apply(this,[obj]);if(this.tileSize!=null){obj.tileSize=this.tileSize.clone();}
obj.grid=[];return obj;},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.HTTPRequest.prototype.moveTo.apply(this,arguments);bounds=bounds||this.map.getExtent();if(bounds!=null){var forceReTile=!this.grid.length||zoomChanged;var tilesBounds=this.getTilesBounds();if(this.singleTile){if(forceReTile||(!dragging&&!tilesBounds.containsBounds(bounds))){this.initSingleTile(bounds);}}else{if(forceReTile||!tilesBounds.containsBounds(bounds,true)){this.initGriddedTiles(bounds);}else{this.moveGriddedTiles(bounds);}}}},setTileSize:function(size){if(this.singleTile){size=this.map.getSize();size.h=parseInt(size.h*this.ratio);size.w=parseInt(size.w*this.ratio);}
OpenLayers.Layer.HTTPRequest.prototype.setTileSize.apply(this,[size]);},getGridBounds:function(){var msg="The getGridBounds() function is deprecated. It will be "+"removed in 3.0. Please use getTilesBounds() instead.";OpenLayers.Console.warn(msg);return this.getTilesBounds();},getTilesBounds:function(){var bounds=null;if(this.grid.length){var bottom=this.grid.length-1;var bottomLeftTile=this.grid[bottom][0];var right=this.grid[0].length-1;var topRightTile=this.grid[0][right];bounds=new OpenLayers.Bounds(bottomLeftTile.bounds.left,bottomLeftTile.bounds.bottom,topRightTile.bounds.right,topRightTile.bounds.top);}
return bounds;},initSingleTile:function(bounds){var center=bounds.getCenterLonLat();var tileWidth=bounds.getWidth()*this.ratio;var tileHeight=bounds.getHeight()*this.ratio;var tileBounds=new OpenLayers.Bounds(center.lon-(tileWidth/2),center.lat-(tileHeight/2),center.lon+(tileWidth/2),center.lat+(tileHeight/2));var ul=new OpenLayers.LonLat(tileBounds.left,tileBounds.top);var px=this.map.getLayerPxFromLonLat(ul);if(!this.grid.length){this.grid[0]=[];}
var tile=this.grid[0][0];if(!tile){tile=this.addTile(tileBounds,px);this.addTileMonitoringHooks(tile);tile.draw();this.grid[0][0]=tile;}else{tile.moveTo(tileBounds,px);}
this.removeExcessTiles(1,1);},calculateGridLayout:function(bounds,extent,resolution){var tilelon=resolution*this.tileSize.w;var tilelat=resolution*this.tileSize.h;var offsetlon=bounds.left-extent.left;var tilecol=Math.floor(offsetlon/tilelon)-this.buffer;var tilecolremain=offsetlon/tilelon-tilecol;var tileoffsetx=-tilecolremain*this.tileSize.w;var tileoffsetlon=extent.left+tilecol*tilelon;var offsetlat=bounds.top-(extent.bottom+tilelat);var tilerow=Math.ceil(offsetlat/tilelat)+this.buffer;var tilerowremain=tilerow-offsetlat/tilelat;var tileoffsety=-tilerowremain*this.tileSize.h;var tileoffsetlat=extent.bottom+tilerow*tilelat;return{tilelon:tilelon,tilelat:tilelat,tileoffsetlon:tileoffsetlon,tileoffsetlat:tileoffsetlat,tileoffsetx:tileoffsetx,tileoffsety:tileoffsety};},initGriddedTiles:function(bounds){var viewSize=this.map.getSize();var minRows=Math.ceil(viewSize.h/this.tileSize.h)+
Math.max(1,2*this.buffer);var minCols=Math.ceil(viewSize.w/this.tileSize.w)+
Math.max(1,2*this.buffer);var extent=this.getMaxExtent();var resolution=this.map.getResolution();var tileLayout=this.calculateGridLayout(bounds,extent,resolution);var tileoffsetx=Math.round(tileLayout.tileoffsetx);var tileoffsety=Math.round(tileLayout.tileoffsety);var tileoffsetlon=tileLayout.tileoffsetlon;var tileoffsetlat=tileLayout.tileoffsetlat;var tilelon=tileLayout.tilelon;var tilelat=tileLayout.tilelat;this.origin=new OpenLayers.Pixel(tileoffsetx,tileoffsety);var startX=tileoffsetx;var startLon=tileoffsetlon;var rowidx=0;var layerContainerDivLeft=parseInt(this.map.layerContainerDiv.style.left);var layerContainerDivTop=parseInt(this.map.layerContainerDiv.style.top);do{var row=this.grid[rowidx++];if(!row){row=[];this.grid.push(row);}
tileoffsetlon=startLon;tileoffsetx=startX;var colidx=0;do{var tileBounds=new OpenLayers.Bounds(tileoffsetlon,tileoffsetlat,tileoffsetlon+tilelon,tileoffsetlat+tilelat);var x=tileoffsetx;x-=layerContainerDivLeft;var y=tileoffsety;y-=layerContainerDivTop;var px=new OpenLayers.Pixel(x,y);var tile=row[colidx++];if(!tile){tile=this.addTile(tileBounds,px);this.addTileMonitoringHooks(tile);row.push(tile);}else{tile.moveTo(tileBounds,px,false);}
tileoffsetlon+=tilelon;tileoffsetx+=this.tileSize.w;}while((tileoffsetlon<=bounds.right+tilelon*this.buffer)||colidx<minCols);tileoffsetlat-=tilelat;tileoffsety+=this.tileSize.h;}while((tileoffsetlat>=bounds.bottom-tilelat*this.buffer)||rowidx<minRows);this.removeExcessTiles(rowidx,colidx);this.spiralTileLoad();},getMaxExtent:function(){return this.maxExtent;},spiralTileLoad:function(){var tileQueue=[];var directions=["right","down","left","up"];var iRow=0;var iCell=-1;var direction=OpenLayers.Util.indexOf(directions,"right");var directionsTried=0;while(directionsTried<directions.length){var testRow=iRow;var testCell=iCell;switch(directions[direction]){case"right":testCell++;break;case"down":testRow++;break;case"left":testCell--;break;case"up":testRow--;break;}
var tile=null;if((testRow<this.grid.length)&&(testRow>=0)&&(testCell<this.grid[0].length)&&(testCell>=0)){tile=this.grid[testRow][testCell];}
if((tile!=null)&&(!tile.queued)){tileQueue.unshift(tile);tile.queued=true;directionsTried=0;iRow=testRow;iCell=testCell;}else{direction=(direction+1)%4;directionsTried++;}}
for(var i=0,len=tileQueue.length;i<len;i++){var tile=tileQueue[i];tile.draw();tile.queued=false;}},addTile:function(bounds,position){},addTileMonitoringHooks:function(tile){tile.onLoadStart=function(){if(this.numLoadingTiles==0){this.events.triggerEvent("loadstart");}
this.numLoadingTiles++;};tile.events.register("loadstart",this,tile.onLoadStart);tile.onLoadEnd=function(){this.numLoadingTiles--;this.events.triggerEvent("tileloaded");if(this.numLoadingTiles==0){this.events.triggerEvent("loadend");}};tile.events.register("loadend",this,tile.onLoadEnd);tile.events.register("unload",this,tile.onLoadEnd);},removeTileMonitoringHooks:function(tile){tile.unload();tile.events.un({"loadstart":tile.onLoadStart,"loadend":tile.onLoadEnd,"unload":tile.onLoadEnd,scope:this});},moveGriddedTiles:function(bounds){var buffer=this.buffer||1;while(true){var tlLayer=this.grid[0][0].position;var tlViewPort=this.map.getViewPortPxFromLayerPx(tlLayer);if(tlViewPort.x>-this.tileSize.w*(buffer-1)){this.shiftColumn(true);}else if(tlViewPort.x<-this.tileSize.w*buffer){this.shiftColumn(false);}else if(tlViewPort.y>-this.tileSize.h*(buffer-1)){this.shiftRow(true);}else if(tlViewPort.y<-this.tileSize.h*buffer){this.shiftRow(false);}else{break;}};},shiftRow:function(prepend){var modelRowIndex=(prepend)?0:(this.grid.length-1);var grid=this.grid;var modelRow=grid[modelRowIndex];var resolution=this.map.getResolution();var deltaY=(prepend)?-this.tileSize.h:this.tileSize.h;var deltaLat=resolution*-deltaY;var row=(prepend)?grid.pop():grid.shift();for(var i=0,len=modelRow.length;i<len;i++){var modelTile=modelRow[i];var bounds=modelTile.bounds.clone();var position=modelTile.position.clone();bounds.bottom=bounds.bottom+deltaLat;bounds.top=bounds.top+deltaLat;position.y=position.y+deltaY;row[i].moveTo(bounds,position);}
if(prepend){grid.unshift(row);}else{grid.push(row);}},shiftColumn:function(prepend){var deltaX=(prepend)?-this.tileSize.w:this.tileSize.w;var resolution=this.map.getResolution();var deltaLon=resolution*deltaX;for(var i=0,len=this.grid.length;i<len;i++){var row=this.grid[i];var modelTileIndex=(prepend)?0:(row.length-1);var modelTile=row[modelTileIndex];var bounds=modelTile.bounds.clone();var position=modelTile.position.clone();bounds.left=bounds.left+deltaLon;bounds.right=bounds.right+deltaLon;position.x=position.x+deltaX;var tile=prepend?this.grid[i].pop():this.grid[i].shift();tile.moveTo(bounds,position);if(prepend){row.unshift(tile);}else{row.push(tile);}}},removeExcessTiles:function(rows,columns){while(this.grid.length>rows){var row=this.grid.pop();for(var i=0,l=row.length;i<l;i++){var tile=row[i];this.removeTileMonitoringHooks(tile);tile.destroy();}}
while(this.grid[0].length>columns){for(var i=0,l=this.grid.length;i<l;i++){var row=this.grid[i];var tile=row.pop();this.removeTileMonitoringHooks(tile);tile.destroy();}}},onMapResize:function(){if(this.singleTile){this.clearGrid();this.setTileSize();}},getTileBounds:function(viewPortPx){var maxExtent=this.maxExtent;var resolution=this.getResolution();var tileMapWidth=resolution*this.tileSize.w;var tileMapHeight=resolution*this.tileSize.h;var mapPoint=this.getLonLatFromViewPortPx(viewPortPx);var tileLeft=maxExtent.left+(tileMapWidth*Math.floor((mapPoint.lon-
maxExtent.left)/tileMapWidth));var tileBottom=maxExtent.bottom+(tileMapHeight*Math.floor((mapPoint.lat-
maxExtent.bottom)/tileMapHeight));return new OpenLayers.Bounds(tileLeft,tileBottom,tileLeft+tileMapWidth,tileBottom+tileMapHeight);},CLASS_NAME:"OpenLayers.Layer.Grid"});OpenLayers.Layer.MultiMap=OpenLayers.Class(OpenLayers.Layer.EventPane,OpenLayers.Layer.FixedZoomLevels,{MIN_ZOOM_LEVEL:1,MAX_ZOOM_LEVEL:17,RESOLUTIONS:[9,1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125],type:null,initialize:function(name,options){OpenLayers.Layer.EventPane.prototype.initialize.apply(this,arguments);OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this,arguments);if(this.sphericalMercator){OpenLayers.Util.extend(this,OpenLayers.Layer.SphericalMercator);this.initMercatorParameters();this.RESOLUTIONS.unshift(10);}},loadMapObject:function(){try{this.mapObject=new MultimapViewer(this.div);}catch(e){}},getWarningHTML:function(){return OpenLayers.i18n("getLayerWarning",{'layerType':"MM",'layerLib':"MultiMap"});},setMapObjectCenter:function(center,zoom){this.mapObject.goToPosition(center,zoom);},getMapObjectCenter:function(){return this.mapObject.getCurrentPosition();},getMapObjectZoom:function(){return this.mapObject.getZoomFactor();},getMapObjectLonLatFromMapObjectPixel:function(moPixel){moPixel.x=moPixel.x-(this.map.getSize().w/2);moPixel.y=moPixel.y-(this.map.getSize().h/2);return this.mapObject.getMapPositionAt(moPixel);},getMapObjectPixelFromMapObjectLonLat:function(moLonLat){return this.mapObject.geoPosToContainerPixels(moLonLat);},getLongitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.lon,moLonLat.lat).lon:moLonLat.lon;},getLatitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.lon,moLonLat.lat).lat:moLonLat.lat;},getMapObjectLonLatFromLonLat:function(lon,lat){var mmLatLon;if(this.sphericalMercator){var lonlat=this.inverseMercator(lon,lat);mmLatLon=new MMLatLon(lonlat.lat,lonlat.lon);}else{mmLatLon=new MMLatLon(lat,lon);}
return mmLatLon;},getXFromMapObjectPixel:function(moPixel){return moPixel.x;},getYFromMapObjectPixel:function(moPixel){return moPixel.y;},getMapObjectPixelFromXY:function(x,y){return new MMPoint(x,y);},CLASS_NAME:"OpenLayers.Layer.MultiMap"});OpenLayers.Layer.VirtualEarth=OpenLayers.Class(OpenLayers.Layer.EventPane,OpenLayers.Layer.FixedZoomLevels,{MIN_ZOOM_LEVEL:1,MAX_ZOOM_LEVEL:19,RESOLUTIONS:[1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125,0.00002145767211914062,0.00001072883605957031,0.00000536441802978515],type:null,wrapDateLine:true,sphericalMercator:false,animationEnabled:true,initialize:function(name,options){OpenLayers.Layer.EventPane.prototype.initialize.apply(this,arguments);OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this,arguments);if(this.sphericalMercator){OpenLayers.Util.extend(this,OpenLayers.Layer.SphericalMercator);this.initMercatorParameters();}},loadMapObject:function(){var veDiv=OpenLayers.Util.createDiv(this.name);var sz=this.map.getSize();veDiv.style.width=sz.w+"px";veDiv.style.height=sz.h+"px";this.div.appendChild(veDiv);try{this.mapObject=new VEMap(this.name);}catch(e){}
if(this.mapObject!=null){try{this.mapObject.LoadMap(null,null,this.type,true);this.mapObject.AttachEvent("onmousedown",OpenLayers.Function.True);}catch(e){}
this.mapObject.HideDashboard();if(typeof this.mapObject.SetAnimationEnabled=="function"){this.mapObject.SetAnimationEnabled(this.animationEnabled);}}
if(!this.mapObject||!this.mapObject.vemapcontrol||!this.mapObject.vemapcontrol.PanMap||(typeof this.mapObject.vemapcontrol.PanMap!="function")){this.dragPanMapObject=null;}},onMapResize:function(){this.mapObject.Resize(this.map.size.w,this.map.size.h);},getWarningHTML:function(){return OpenLayers.i18n("getLayerWarning",{'layerType':'VE','layerLib':'VirtualEarth'});},setMapObjectCenter:function(center,zoom){this.mapObject.SetCenterAndZoom(center,zoom);},getMapObjectCenter:function(){return this.mapObject.GetCenter();},dragPanMapObject:function(dX,dY){this.mapObject.vemapcontrol.PanMap(dX,-dY);},getMapObjectZoom:function(){return this.mapObject.GetZoomLevel();},getMapObjectLonLatFromMapObjectPixel:function(moPixel){return(typeof VEPixel!='undefined')?this.mapObject.PixelToLatLong(moPixel):this.mapObject.PixelToLatLong(moPixel.x,moPixel.y);},getMapObjectPixelFromMapObjectLonLat:function(moLonLat){return this.mapObject.LatLongToPixel(moLonLat);},getLongitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.Longitude,moLonLat.Latitude).lon:moLonLat.Longitude;},getLatitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.Longitude,moLonLat.Latitude).lat:moLonLat.Latitude;},getMapObjectLonLatFromLonLat:function(lon,lat){var veLatLong;if(this.sphericalMercator){var lonlat=this.inverseMercator(lon,lat);veLatLong=new VELatLong(lonlat.lat,lonlat.lon);}else{veLatLong=new VELatLong(lat,lon);}
return veLatLong;},getXFromMapObjectPixel:function(moPixel){return moPixel.x;},getYFromMapObjectPixel:function(moPixel){return moPixel.y;},getMapObjectPixelFromXY:function(x,y){return(typeof VEPixel!='undefined')?new VEPixel(x,y):new Msn.VE.Pixel(x,y);},CLASS_NAME:"OpenLayers.Layer.VirtualEarth"});OpenLayers.Layer.Yahoo=OpenLayers.Class(OpenLayers.Layer.EventPane,OpenLayers.Layer.FixedZoomLevels,{MIN_ZOOM_LEVEL:0,MAX_ZOOM_LEVEL:17,RESOLUTIONS:[1.40625,0.703125,0.3515625,0.17578125,0.087890625,0.0439453125,0.02197265625,0.010986328125,0.0054931640625,0.00274658203125,0.001373291015625,0.0006866455078125,0.00034332275390625,0.000171661376953125,0.0000858306884765625,0.00004291534423828125,0.00002145767211914062,0.00001072883605957031],type:null,wrapDateLine:true,sphericalMercator:false,initialize:function(name,options){OpenLayers.Layer.EventPane.prototype.initialize.apply(this,arguments);OpenLayers.Layer.FixedZoomLevels.prototype.initialize.apply(this,arguments);if(this.sphericalMercator){OpenLayers.Util.extend(this,OpenLayers.Layer.SphericalMercator);this.initMercatorParameters();}},loadMapObject:function(){try{var size=this.getMapObjectSizeFromOLSize(this.map.getSize());this.mapObject=new YMap(this.div,this.type,size);this.mapObject.disableKeyControls();this.mapObject.disableDragMap();if(!this.mapObject.moveByXY||(typeof this.mapObject.moveByXY!="function")){this.dragPanMapObject=null;}}catch(e){}},onMapResize:function(){try{var size=this.getMapObjectSizeFromOLSize(this.map.getSize());this.mapObject.resizeTo(size);}catch(e){}},setMap:function(map){OpenLayers.Layer.EventPane.prototype.setMap.apply(this,arguments);this.map.events.register("moveend",this,this.fixYahooEventPane);},fixYahooEventPane:function(){var yahooEventPane=OpenLayers.Util.getElement("ygddfdiv");if(yahooEventPane!=null){if(yahooEventPane.parentNode!=null){yahooEventPane.parentNode.removeChild(yahooEventPane);}
this.map.events.unregister("moveend",this,this.fixYahooEventPane);}},getWarningHTML:function(){return OpenLayers.i18n("getLayerWarning",{'layerType':'Yahoo','layerLib':'Yahoo'});},getOLZoomFromMapObjectZoom:function(moZoom){var zoom=null;if(moZoom!=null){zoom=OpenLayers.Layer.FixedZoomLevels.prototype.getOLZoomFromMapObjectZoom.apply(this,[moZoom]);zoom=18-zoom;}
return zoom;},getMapObjectZoomFromOLZoom:function(olZoom){var zoom=null;if(olZoom!=null){zoom=OpenLayers.Layer.FixedZoomLevels.prototype.getMapObjectZoomFromOLZoom.apply(this,[olZoom]);zoom=18-zoom;}
return zoom;},setMapObjectCenter:function(center,zoom){this.mapObject.drawZoomAndCenter(center,zoom);},getMapObjectCenter:function(){return this.mapObject.getCenterLatLon();},dragPanMapObject:function(dX,dY){this.mapObject.moveByXY({'x':-dX,'y':dY});},getMapObjectZoom:function(){return this.mapObject.getZoomLevel();},getMapObjectLonLatFromMapObjectPixel:function(moPixel){return this.mapObject.convertXYLatLon(moPixel);},getMapObjectPixelFromMapObjectLonLat:function(moLonLat){return this.mapObject.convertLatLonXY(moLonLat);},getLongitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.Lon,moLonLat.Lat).lon:moLonLat.Lon;},getLatitudeFromMapObjectLonLat:function(moLonLat){return this.sphericalMercator?this.forwardMercator(moLonLat.Lon,moLonLat.Lat).lat:moLonLat.Lat;},getMapObjectLonLatFromLonLat:function(lon,lat){var yLatLong;if(this.sphericalMercator){var lonlat=this.inverseMercator(lon,lat);yLatLong=new YGeoPoint(lonlat.lat,lonlat.lon);}else{yLatLong=new YGeoPoint(lat,lon);}
return yLatLong;},getXFromMapObjectPixel:function(moPixel){return moPixel.x;},getYFromMapObjectPixel:function(moPixel){return moPixel.y;},getMapObjectPixelFromXY:function(x,y){return new YCoordPoint(x,y);},getMapObjectSizeFromOLSize:function(olSize){return new YSize(olSize.w,olSize.h);},CLASS_NAME:"OpenLayers.Layer.Yahoo"});OpenLayers.Style=OpenLayers.Class({id:null,name:null,title:null,description:null,layerName:null,isDefault:false,rules:null,context:null,defaultStyle:null,defaultsPerSymbolizer:false,propertyStyles:null,initialize:function(style,options){OpenLayers.Util.extend(this,options);this.rules=[];if(options&&options.rules){this.addRules(options.rules);}
this.setDefaultStyle(style||OpenLayers.Feature.Vector.style["default"]);this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");},destroy:function(){for(var i=0,len=this.rules.length;i<len;i++){this.rules[i].destroy();this.rules[i]=null;}
this.rules=null;this.defaultStyle=null;},createSymbolizer:function(feature){var style=this.defaultsPerSymbolizer?{}:this.createLiterals(OpenLayers.Util.extend({},this.defaultStyle),feature);var rules=this.rules;var rule,context;var elseRules=[];var appliedRules=false;for(var i=0,len=rules.length;i<len;i++){rule=rules[i];var applies=rule.evaluate(feature);if(applies){if(rule instanceof OpenLayers.Rule&&rule.elseFilter){elseRules.push(rule);}else{appliedRules=true;this.applySymbolizer(rule,style,feature);}}}
if(appliedRules==false&&elseRules.length>0){appliedRules=true;for(var i=0,len=elseRules.length;i<len;i++){this.applySymbolizer(elseRules[i],style,feature);}}
if(rules.length>0&&appliedRules==false){style.display="none";}
return style;},applySymbolizer:function(rule,style,feature){var symbolizerPrefix=feature.geometry?this.getSymbolizerPrefix(feature.geometry):OpenLayers.Style.SYMBOLIZER_PREFIXES[0];var symbolizer=rule.symbolizer[symbolizerPrefix]||rule.symbolizer;if(this.defaultsPerSymbolizer===true){var defaults=this.defaultStyle;OpenLayers.Util.applyDefaults(symbolizer,{pointRadius:defaults.pointRadius});if(symbolizer.stroke===true||symbolizer.graphic===true){OpenLayers.Util.applyDefaults(symbolizer,{strokeWidth:defaults.strokeWidth,strokeColor:defaults.strokeColor,strokeOpacity:defaults.strokeOpacity,strokeDashstyle:defaults.strokeDashstyle,strokeLinecap:defaults.strokeLinecap});}
if(symbolizer.fill===true||symbolizer.graphic===true){OpenLayers.Util.applyDefaults(symbolizer,{fillColor:defaults.fillColor,fillOpacity:defaults.fillOpacity});}
if(symbolizer.graphic===true){OpenLayers.Util.applyDefaults(symbolizer,{pointRadius:this.defaultStyle.pointRadius,externalGraphic:this.defaultStyle.externalGraphic,graphicName:this.defaultStyle.graphicName,graphicOpacity:this.defaultStyle.graphicOpacity,graphicWidth:this.defaultStyle.graphicWidth,graphicHeight:this.defaultStyle.graphicHeight,graphicXOffset:this.defaultStyle.graphicXOffset,graphicYOffset:this.defaultStyle.graphicYOffset});}}
return this.createLiterals(OpenLayers.Util.extend(style,symbolizer),feature);},createLiterals:function(style,feature){var context=OpenLayers.Util.extend({},feature.attributes||feature.data);OpenLayers.Util.extend(context,this.context);for(var i in this.propertyStyles){style[i]=OpenLayers.Style.createLiteral(style[i],context,feature,i);}
return style;},findPropertyStyles:function(){var propertyStyles={};var style=this.defaultStyle;this.addPropertyStyles(propertyStyles,style);var rules=this.rules;var symbolizer,value;for(var i=0,len=rules.length;i<len;i++){symbolizer=rules[i].symbolizer;for(var key in symbolizer){value=symbolizer[key];if(typeof value=="object"){this.addPropertyStyles(propertyStyles,value);}else{this.addPropertyStyles(propertyStyles,symbolizer);break;}}}
return propertyStyles;},addPropertyStyles:function(propertyStyles,symbolizer){var property;for(var key in symbolizer){property=symbolizer[key];if(typeof property=="string"&&property.match(/\$\{\w+\}/)){propertyStyles[key]=true;}}
return propertyStyles;},addRules:function(rules){Array.prototype.push.apply(this.rules,rules);this.propertyStyles=this.findPropertyStyles();},setDefaultStyle:function(style){this.defaultStyle=style;this.propertyStyles=this.findPropertyStyles();},getSymbolizerPrefix:function(geometry){var prefixes=OpenLayers.Style.SYMBOLIZER_PREFIXES;for(var i=0,len=prefixes.length;i<len;i++){if(geometry.CLASS_NAME.indexOf(prefixes[i])!=-1){return prefixes[i];}}},clone:function(){var options=OpenLayers.Util.extend({},this);if(this.rules){options.rules=[];for(var i=0,len=this.rules.length;i<len;++i){options.rules.push(this.rules[i].clone());}}
options.context=this.context&&OpenLayers.Util.extend({},this.context);var defaultStyle=OpenLayers.Util.extend({},this.defaultStyle);return new OpenLayers.Style(defaultStyle,options);},CLASS_NAME:"OpenLayers.Style"});OpenLayers.Style.createLiteral=function(value,context,feature,property){if(typeof value=="string"&&value.indexOf("${")!=-1){value=OpenLayers.String.format(value,context,[feature,property]);value=(isNaN(value)||!value)?value:parseFloat(value);}
return value;};OpenLayers.Style.SYMBOLIZER_PREFIXES=['Point','Line','Polygon','Text','Raster'];OpenLayers.Control.Navigation=OpenLayers.Class(OpenLayers.Control,{dragPan:null,dragPanOptions:null,documentDrag:false,zoomBox:null,zoomBoxEnabled:true,zoomWheelEnabled:true,mouseWheelOptions:null,handleRightClicks:false,zoomBoxKeyMask:OpenLayers.Handler.MOD_SHIFT,autoActivate:true,initialize:function(options){this.handlers={};OpenLayers.Control.prototype.initialize.apply(this,arguments);},destroy:function(){this.deactivate();if(this.dragPan){this.dragPan.destroy();}
this.dragPan=null;if(this.zoomBox){this.zoomBox.destroy();}
this.zoomBox=null;OpenLayers.Control.prototype.destroy.apply(this,arguments);},activate:function(){this.dragPan.activate();if(this.zoomWheelEnabled){this.handlers.wheel.activate();}
this.handlers.click.activate();if(this.zoomBoxEnabled){this.zoomBox.activate();}
return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){this.zoomBox.deactivate();this.dragPan.deactivate();this.handlers.click.deactivate();this.handlers.wheel.deactivate();return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},draw:function(){if(this.handleRightClicks){this.map.viewPortDiv.oncontextmenu=OpenLayers.Function.False;}
var clickCallbacks={'dblclick':this.defaultDblClick,'dblrightclick':this.defaultDblRightClick};var clickOptions={'double':true,'stopDouble':true};this.handlers.click=new OpenLayers.Handler.Click(this,clickCallbacks,clickOptions);this.dragPan=new OpenLayers.Control.DragPan(OpenLayers.Util.extend({map:this.map,documentDrag:this.documentDrag},this.dragPanOptions));this.zoomBox=new OpenLayers.Control.ZoomBox({map:this.map,keyMask:this.zoomBoxKeyMask});this.dragPan.draw();this.zoomBox.draw();this.handlers.wheel=new OpenLayers.Handler.MouseWheel(this,{"up":this.wheelUp,"down":this.wheelDown},this.mouseWheelOptions);},defaultDblClick:function(evt){var newCenter=this.map.getLonLatFromViewPortPx(evt.xy);this.map.setCenter(newCenter,this.map.zoom+1);},defaultDblRightClick:function(evt){var newCenter=this.map.getLonLatFromViewPortPx(evt.xy);this.map.setCenter(newCenter,this.map.zoom-1);},wheelChange:function(evt,deltaZ){var currentZoom=this.map.getZoom();var newZoom=this.map.getZoom()+Math.round(deltaZ);newZoom=Math.max(newZoom,0);newZoom=Math.min(newZoom,this.map.getNumZoomLevels());if(newZoom===currentZoom){return;}
var size=this.map.getSize();var deltaX=size.w/2-evt.xy.x;var deltaY=evt.xy.y-size.h/2;var newRes=this.map.baseLayer.getResolutionForZoom(newZoom);var zoomPoint=this.map.getLonLatFromPixel(evt.xy);var newCenter=new OpenLayers.LonLat(zoomPoint.lon+deltaX*newRes,zoomPoint.lat+deltaY*newRes);this.map.setCenter(newCenter,newZoom);},wheelUp:function(evt,delta){this.wheelChange(evt,delta||1);},wheelDown:function(evt,delta){this.wheelChange(evt,delta||-1);},disableZoomBox:function(){this.zoomBoxEnabled=false;this.zoomBox.deactivate();},enableZoomBox:function(){this.zoomBoxEnabled=true;if(this.active){this.zoomBox.activate();}},disableZoomWheel:function(){this.zoomWheelEnabled=false;this.handlers.wheel.deactivate();},enableZoomWheel:function(){this.zoomWheelEnabled=true;if(this.active){this.handlers.wheel.activate();}},CLASS_NAME:"OpenLayers.Control.Navigation"});OpenLayers.Filter=OpenLayers.Class({initialize:function(options){OpenLayers.Util.extend(this,options);},destroy:function(){},evaluate:function(context){return true;},clone:function(){return null;},CLASS_NAME:"OpenLayers.Filter"});OpenLayers.Format.WMC.v1_0_0=OpenLayers.Class(OpenLayers.Format.WMC.v1,{VERSION:"1.0.0",schemaLocation:"http://www.opengis.net/context http://schemas.opengis.net/context/1.0.0/context.xsd",initialize:function(options){OpenLayers.Format.WMC.v1.prototype.initialize.apply(this,[options]);},write_wmc_Layer:function(context){var node=OpenLayers.Format.WMC.v1.prototype.write_wmc_Layer.apply(this,[context]);node.appendChild(this.write_wmc_FormatList(context));node.appendChild(this.write_wmc_StyleList(context));node.appendChild(this.write_wmc_LayerExtension(context));},CLASS_NAME:"OpenLayers.Format.WMC.v1_0_0"});OpenLayers.Format.WMC.v1_1_0=OpenLayers.Class(OpenLayers.Format.WMC.v1,{VERSION:"1.1.0",schemaLocation:"http://www.opengis.net/context http://schemas.opengis.net/context/1.1.0/context.xsd",initialize:function(options){OpenLayers.Format.WMC.v1.prototype.initialize.apply(this,[options]);},read_sld_MinScaleDenominator:function(layerContext,node){var minScaleDenominator=parseFloat(this.getChildValue(node));if(minScaleDenominator>0){layerContext.maxScale=minScaleDenominator;}},read_sld_MaxScaleDenominator:function(layerContext,node){layerContext.minScale=parseFloat(this.getChildValue(node));},write_wmc_Layer:function(context){var node=OpenLayers.Format.WMC.v1.prototype.write_wmc_Layer.apply(this,[context]);if(context.maxScale){var minSD=this.createElementNS(this.namespaces.sld,"sld:MinScaleDenominator");minSD.appendChild(this.createTextNode(context.maxScale.toPrecision(16)));node.appendChild(minSD);}
if(context.minScale){var maxSD=this.createElementNS(this.namespaces.sld,"sld:MaxScaleDenominator");maxSD.appendChild(this.createTextNode(context.minScale.toPrecision(16)));node.appendChild(maxSD);}
node.appendChild(this.write_wmc_FormatList(context));node.appendChild(this.write_wmc_StyleList(context));node.appendChild(this.write_wmc_LayerExtension(context));return node;},CLASS_NAME:"OpenLayers.Format.WMC.v1_1_0"});OpenLayers.Format.WMSCapabilities.v1_1_0=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1_1,{version:"1.1.0",initialize:function(options){OpenLayers.Format.WMSCapabilities.v1_1.prototype.initialize.apply(this,[options]);},readers:{"wms":OpenLayers.Util.applyDefaults({"SRS":function(node,obj){var srs=this.getChildValue(node);var values=srs.split(/ +/);for(var i=0,len=values.length;i<len;i++){obj.srs[values[i]]=true;}}},OpenLayers.Format.WMSCapabilities.v1_1.prototype.readers["wms"])},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_1_0"});OpenLayers.Format.WMSCapabilities.v1_1_1=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1_1,{version:"1.1.1",initialize:function(options){OpenLayers.Format.WMSCapabilities.v1_1.prototype.initialize.apply(this,[options]);},readers:{"wms":OpenLayers.Util.applyDefaults({"SRS":function(node,obj){obj.srs[this.getChildValue(node)]=true;}},OpenLayers.Format.WMSCapabilities.v1_1.prototype.readers["wms"])},CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_1_1"});OpenLayers.Format.WMSCapabilities.v1_3_0=OpenLayers.Class(OpenLayers.Format.WMSCapabilities.v1_3,{version:"1.3.0",CLASS_NAME:"OpenLayers.Format.WMSCapabilities.v1_3_0"});OpenLayers.Geometry=OpenLayers.Class({id:null,parent:null,bounds:null,initialize:function(){this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");},destroy:function(){this.id=null;this.bounds=null;},clone:function(){return new OpenLayers.Geometry();},setBounds:function(bounds){if(bounds){this.bounds=bounds.clone();}},clearBounds:function(){this.bounds=null;if(this.parent){this.parent.clearBounds();}},extendBounds:function(newBounds){var bounds=this.getBounds();if(!bounds){this.setBounds(newBounds);}else{this.bounds.extend(newBounds);}},getBounds:function(){if(this.bounds==null){this.calculateBounds();}
return this.bounds;},calculateBounds:function(){},distanceTo:function(geometry,options){},getVertices:function(nodes){},atPoint:function(lonlat,toleranceLon,toleranceLat){var atPoint=false;var bounds=this.getBounds();if((bounds!=null)&&(lonlat!=null)){var dX=(toleranceLon!=null)?toleranceLon:0;var dY=(toleranceLat!=null)?toleranceLat:0;var toleranceBounds=new OpenLayers.Bounds(this.bounds.left-dX,this.bounds.bottom-dY,this.bounds.right+dX,this.bounds.top+dY);atPoint=toleranceBounds.containsLonLat(lonlat);}
return atPoint;},getLength:function(){return 0.0;},getArea:function(){return 0.0;},getCentroid:function(){return null;},toString:function(){return OpenLayers.Format.WKT.prototype.write(new OpenLayers.Feature.Vector(this));},CLASS_NAME:"OpenLayers.Geometry"});OpenLayers.Geometry.fromWKT=function(wkt){var format=arguments.callee.format;if(!format){format=new OpenLayers.Format.WKT();arguments.callee.format=format;}
var geom;var result=format.read(wkt);if(result instanceof OpenLayers.Feature.Vector){geom=result.geometry;}else if(result instanceof Array){var len=result.length;var components=new Array(len);for(var i=0;i<len;++i){components[i]=result[i].geometry;}
geom=new OpenLayers.Geometry.Collection(components);}
return geom;};OpenLayers.Geometry.segmentsIntersect=function(seg1,seg2,options){var point=options&&options.point;var tolerance=options&&options.tolerance;var intersection=false;var x11_21=seg1.x1-seg2.x1;var y11_21=seg1.y1-seg2.y1;var x12_11=seg1.x2-seg1.x1;var y12_11=seg1.y2-seg1.y1;var y22_21=seg2.y2-seg2.y1;var x22_21=seg2.x2-seg2.x1;var d=(y22_21*x12_11)-(x22_21*y12_11);var n1=(x22_21*y11_21)-(y22_21*x11_21);var n2=(x12_11*y11_21)-(y12_11*x11_21);if(d==0){if(n1==0&&n2==0){intersection=true;}}else{var along1=n1/d;var along2=n2/d;if(along1>=0&&along1<=1&&along2>=0&&along2<=1){if(!point){intersection=true;}else{var x=seg1.x1+(along1*x12_11);var y=seg1.y1+(along1*y12_11);intersection=new OpenLayers.Geometry.Point(x,y);}}}
if(tolerance){var dist;if(intersection){if(point){var segs=[seg1,seg2];var seg,x,y;outer:for(var i=0;i<2;++i){seg=segs[i];for(var j=1;j<3;++j){x=seg["x"+j];y=seg["y"+j];dist=Math.sqrt(Math.pow(x-intersection.x,2)+
Math.pow(y-intersection.y,2));if(dist<tolerance){intersection.x=x;intersection.y=y;break outer;}}}}}else{var segs=[seg1,seg2];var source,target,x,y,p,result;outer:for(var i=0;i<2;++i){source=segs[i];target=segs[(i+1)%2];for(var j=1;j<3;++j){p={x:source["x"+j],y:source["y"+j]};result=OpenLayers.Geometry.distanceToSegment(p,target);if(result.distance<tolerance){if(point){intersection=new OpenLayers.Geometry.Point(p.x,p.y);}else{intersection=true;}
break outer;}}}}}
return intersection;};OpenLayers.Geometry.distanceToSegment=function(point,segment){var x0=point.x;var y0=point.y;var x1=segment.x1;var y1=segment.y1;var x2=segment.x2;var y2=segment.y2;var dx=x2-x1;var dy=y2-y1;var along=((dx*(x0-x1))+(dy*(y0-y1)))/(Math.pow(dx,2)+Math.pow(dy,2));var x,y;if(along<=0.0){x=x1;y=y1;}else if(along>=1.0){x=x2;y=y2;}else{x=x1+along*dx;y=y1+along*dy;}
return{distance:Math.sqrt(Math.pow(x-x0,2)+Math.pow(y-y0,2)),x:x,y:y};};OpenLayers.Layer.ArcGIS93Rest=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{format:"png"},isBaseLayer:true,initialize:function(name,url,params,options){var newArguments=[];params=OpenLayers.Util.upperCaseObject(params);newArguments.push(name,url,params,options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);OpenLayers.Util.applyDefaults(this.params,OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS));if(this.params.TRANSPARENT&&this.params.TRANSPARENT.toString().toLowerCase()=="true"){if((options==null)||(!options.isBaseLayer)){this.isBaseLayer=false;}
if(this.params.FORMAT=="jpg"){this.params.FORMAT=OpenLayers.Util.alphaHack()?"gif":"png";}}},destroy:function(){OpenLayers.Layer.Grid.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.ArcGIS93Rest(this.name,this.url,this.params,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},getURL:function(bounds){bounds=this.adjustBounds(bounds);var projWords=this.projection.getCode().split(":");var srid=projWords[projWords.length-1];var imageSize=this.getImageSize();var newParams={'BBOX':bounds.toBBOX(),'SIZE':imageSize.w+","+imageSize.h,'F':"image",'BBOXSR':srid,'IMAGESR':srid};if(this.layerDefs){var layerDefStrList=[];var layerID;for(layerID in this.layerDefs){if(this.layerDefs.hasOwnProperty(layerID)){if(this.layerDefs[layerID]){layerDefStrList.push(layerID);layerDefStrList.push(":");layerDefStrList.push(this.layerDefs[layerID]);layerDefStrList.push(";");}}}
if(layerDefStrList.length>0){newParams['LAYERDEFS']=layerDefStrList.join("");}}
var requestString=this.getFullRequestString(newParams);return requestString;},setLayerFilter:function(id,queryDef){if(!this.layerDefs){this.layerDefs={};}
if(queryDef){this.layerDefs[id]=queryDef;}else{delete this.layerDefs[id];}},clearLayerFilter:function(id){if(id){delete this.layerDefs[id];}else{delete this.layerDefs;}},mergeNewParams:function(newParams){var upperParams=OpenLayers.Util.upperCaseObject(newParams);var newArguments=[upperParams];return OpenLayers.Layer.Grid.prototype.mergeNewParams.apply(this,newArguments);},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},CLASS_NAME:"OpenLayers.Layer.ArcGIS93Rest"});OpenLayers.Layer.Google.v3={DEFAULTS:{maxExtent:new OpenLayers.Bounds(-128*156543.0339,-128*156543.0339,128*156543.0339,128*156543.0339),sphericalMercator:true,maxResolution:156543.0339,units:"m",projection:"EPSG:900913"},loadMapObject:function(){if(!this.type){this.type=google.maps.MapTypeId.ROADMAP;}
var mapObject;var cache=OpenLayers.Layer.Google.cache[this.map.id];if(cache){mapObject=cache.mapObject;++cache.count;}else{var container=this.map.viewPortDiv;var div=document.createElement("div");div.id=this.map.id+"_GMapContainer";div.style.position="absolute";div.style.width="100%";div.style.height="100%";container.appendChild(div);var center=this.map.getCenter();mapObject=new google.maps.Map(div,{center:center?new google.maps.LatLng(center.lat,center.lon):new google.maps.LatLng(0,0),zoom:this.map.getZoom()||0,mapTypeId:this.type,disableDefaultUI:true,keyboardShortcuts:false,draggable:false,disableDoubleClickZoom:true,scrollwheel:false});cache={mapObject:mapObject,count:1};OpenLayers.Layer.Google.cache[this.map.id]=cache;this.repositionListener=google.maps.event.addListenerOnce(mapObject,"center_changed",OpenLayers.Function.bind(this.repositionMapElements,this));}
this.mapObject=mapObject;this.setGMapVisibility(this.visibility);},repositionMapElements:function(){google.maps.event.trigger(this.mapObject,"resize");var div=this.mapObject.getDiv().firstChild;if(!div||div.childNodes.length<3){this.repositionTimer=window.setTimeout(OpenLayers.Function.bind(this.repositionMapElements,this),250);return false;}
var cache=OpenLayers.Layer.Google.cache[this.map.id];var container=this.map.viewPortDiv;var termsOfUse=div.lastChild;container.appendChild(termsOfUse);termsOfUse.style.zIndex="1100";termsOfUse.style.bottom="";termsOfUse.className="olLayerGoogleCopyright olLayerGoogleV3";termsOfUse.style.display="";cache.termsOfUse=termsOfUse;var poweredBy=div.lastChild;container.appendChild(poweredBy);poweredBy.style.zIndex="1100";poweredBy.style.bottom="";poweredBy.className="olLayerGooglePoweredBy olLayerGoogleV3 gmnoprint";poweredBy.style.display="";cache.poweredBy=poweredBy;this.setGMapVisibility(this.visibility);},onMapResize:function(){if(this.visibility){google.maps.event.trigger(this.mapObject,"resize");}else{if(!this._resized){var layer=this;google.maps.event.addListenerOnce(this.mapObject,"tilesloaded",function(){delete layer._resized;google.maps.event.trigger(layer.mapObject,"resize");layer.moveTo(layer.map.getCenter(),layer.map.getZoom());});}
this._resized=true;}},setGMapVisibility:function(visible){var cache=OpenLayers.Layer.Google.cache[this.map.id];if(cache){var type=this.type;var layers=this.map.layers;var layer;for(var i=layers.length-1;i>=0;--i){layer=layers[i];if(layer instanceof OpenLayers.Layer.Google&&layer.visibility===true&&layer.inRange===true){type=layer.type;visible=true;break;}}
var container=this.mapObject.getDiv();if(visible===true){this.mapObject.setMapTypeId(type);container.style.left="";if(cache.termsOfUse&&cache.termsOfUse.style){cache.termsOfUse.style.left="";cache.termsOfUse.style.display="";cache.poweredBy.style.display="";}
cache.displayed=this.id;}else{delete cache.displayed;container.style.left="-9999px";if(cache.termsOfUse&&cache.termsOfUse.style){cache.termsOfUse.style.display="none";cache.termsOfUse.style.left="-9999px";cache.poweredBy.style.display="none";}}}},getMapContainer:function(){return this.mapObject.getDiv();},getMapObjectBoundsFromOLBounds:function(olBounds){var moBounds=null;if(olBounds!=null){var sw=this.sphericalMercator?this.inverseMercator(olBounds.bottom,olBounds.left):new OpenLayers.LonLat(olBounds.bottom,olBounds.left);var ne=this.sphericalMercator?this.inverseMercator(olBounds.top,olBounds.right):new OpenLayers.LonLat(olBounds.top,olBounds.right);moBounds=new google.maps.LatLngBounds(new google.maps.LatLng(sw.lat,sw.lon),new google.maps.LatLng(ne.lat,ne.lon));}
return moBounds;},getMapObjectLonLatFromMapObjectPixel:function(moPixel){var size=this.map.getSize();var lon=this.getLongitudeFromMapObjectLonLat(this.mapObject.center);var lat=this.getLatitudeFromMapObjectLonLat(this.mapObject.center);var res=this.map.getResolution();var delta_x=moPixel.x-(size.w/2);var delta_y=moPixel.y-(size.h/2);var lonlat=new OpenLayers.LonLat(lon+delta_x*res,lat-delta_y*res);if(this.wrapDateLine){lonlat=lonlat.wrapDateLine(this.maxExtent);}
return this.getMapObjectLonLatFromLonLat(lonlat.lon,lonlat.lat);},getMapObjectPixelFromMapObjectLonLat:function(moLonLat){var lon=this.getLongitudeFromMapObjectLonLat(moLonLat);var lat=this.getLatitudeFromMapObjectLonLat(moLonLat);var res=this.map.getResolution();var extent=this.map.getExtent();var px=new OpenLayers.Pixel((1/res*(lon-extent.left)),(1/res*(extent.top-lat)));return this.getMapObjectPixelFromXY(px.x,px.y);},setMapObjectCenter:function(center,zoom){this.mapObject.setOptions({center:center,zoom:zoom});},getMapObjectZoomFromMapObjectBounds:function(moBounds){return this.mapObject.getBoundsZoomLevel(moBounds);},getMapObjectLonLatFromLonLat:function(lon,lat){var gLatLng;if(this.sphericalMercator){var lonlat=this.inverseMercator(lon,lat);gLatLng=new google.maps.LatLng(lonlat.lat,lonlat.lon);}else{gLatLng=new google.maps.LatLng(lat,lon);}
return gLatLng;},getMapObjectPixelFromXY:function(x,y){return new google.maps.Point(x,y);},destroy:function(){if(this.repositionListener){google.maps.event.removeListener(this.repositionListener);}
if(this.repositionTimer){window.clearTimeout(this.repositionTimer);}
OpenLayers.Layer.Google.prototype.destroy.apply(this,arguments);}};OpenLayers.Layer.KaMap=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:true,units:null,resolution:OpenLayers.DOTS_PER_INCH,DEFAULT_PARAMS:{i:'jpeg',map:''},initialize:function(name,url,params,options){var newArguments=[];newArguments.push(name,url,params,options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);this.params=OpenLayers.Util.applyDefaults(this.params,this.DEFAULT_PARAMS);},getURL:function(bounds){bounds=this.adjustBounds(bounds);var mapRes=this.map.getResolution();var scale=Math.round((this.map.getScale()*10000))/10000;var pX=Math.round(bounds.left/mapRes);var pY=-Math.round(bounds.top/mapRes);return this.getFullRequestString({t:pY,l:pX,s:scale});},addTile:function(bounds,position){var url=this.getURL(bounds);return new OpenLayers.Tile.Image(this,position,bounds,url,this.tileSize);},calculateGridLayout:function(bounds,extent,resolution){var tilelon=resolution*this.tileSize.w;var tilelat=resolution*this.tileSize.h;var offsetlon=bounds.left;var tilecol=Math.floor(offsetlon/tilelon)-this.buffer;var tilecolremain=offsetlon/tilelon-tilecol;var tileoffsetx=-tilecolremain*this.tileSize.w;var tileoffsetlon=tilecol*tilelon;var offsetlat=bounds.top;var tilerow=Math.ceil(offsetlat/tilelat)+this.buffer;var tilerowremain=tilerow-offsetlat/tilelat;var tileoffsety=-(tilerowremain+1)*this.tileSize.h;var tileoffsetlat=tilerow*tilelat;return{tilelon:tilelon,tilelat:tilelat,tileoffsetlon:tileoffsetlon,tileoffsetlat:tileoffsetlat,tileoffsetx:tileoffsetx,tileoffsety:tileoffsety};},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.KaMap(this.name,this.url,this.params,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);if(this.tileSize!=null){obj.tileSize=this.tileSize.clone();}
obj.grid=[];return obj;},getTileBounds:function(viewPortPx){var resolution=this.getResolution();var tileMapWidth=resolution*this.tileSize.w;var tileMapHeight=resolution*this.tileSize.h;var mapPoint=this.getLonLatFromViewPortPx(viewPortPx);var tileLeft=tileMapWidth*Math.floor(mapPoint.lon/tileMapWidth);var tileBottom=tileMapHeight*Math.floor(mapPoint.lat/tileMapHeight);return new OpenLayers.Bounds(tileLeft,tileBottom,tileLeft+tileMapWidth,tileBottom+tileMapHeight);},CLASS_NAME:"OpenLayers.Layer.KaMap"});OpenLayers.Layer.MapGuide=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:true,useHttpTile:false,singleTile:false,useOverlay:false,useAsyncOverlay:true,TILE_PARAMS:{operation:'GETTILEIMAGE',version:'1.2.0'},SINGLE_TILE_PARAMS:{operation:'GETMAPIMAGE',format:'PNG',locale:'en',clip:'1',version:'1.0.0'},OVERLAY_PARAMS:{operation:'GETDYNAMICMAPOVERLAYIMAGE',format:'PNG',locale:'en',clip:'1',version:'2.0.0'},FOLDER_PARAMS:{tileColumnsPerFolder:30,tileRowsPerFolder:30,format:'png',querystring:null},defaultSize:new OpenLayers.Size(300,300),initialize:function(name,url,params,options){OpenLayers.Layer.Grid.prototype.initialize.apply(this,arguments);if(options==null||options.isBaseLayer==null){this.isBaseLayer=((this.transparent!="true")&&(this.transparent!=true));}
if(options&&options.useOverlay!=null){this.useOverlay=options.useOverlay;}
if(this.singleTile){if(this.useOverlay){OpenLayers.Util.applyDefaults(this.params,this.OVERLAY_PARAMS);if(!this.useAsyncOverlay){this.params.version="1.0.0";}}else{OpenLayers.Util.applyDefaults(this.params,this.SINGLE_TILE_PARAMS);}}else{if(this.useHttpTile){OpenLayers.Util.applyDefaults(this.params,this.FOLDER_PARAMS);}else{OpenLayers.Util.applyDefaults(this.params,this.TILE_PARAMS);}
this.setTileSize(this.defaultSize);}},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.MapGuide(this.name,this.url,this.params,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},getURL:function(bounds){var url;var center=bounds.getCenterLonLat();var mapSize=this.map.getSize();if(this.singleTile){var params={setdisplaydpi:OpenLayers.DOTS_PER_INCH,setdisplayheight:mapSize.h*this.ratio,setdisplaywidth:mapSize.w*this.ratio,setviewcenterx:center.lon,setviewcentery:center.lat,setviewscale:this.map.getScale()};if(this.useOverlay&&!this.useAsyncOverlay){var getVisParams={};getVisParams=OpenLayers.Util.extend(getVisParams,params);getVisParams.operation="GETVISIBLEMAPEXTENT";getVisParams.version="1.0.0";getVisParams.session=this.params.session;getVisParams.mapName=this.params.mapName;getVisParams.format='text/xml';url=this.getFullRequestString(getVisParams);OpenLayers.Request.GET({url:url,async:false});}
url=this.getFullRequestString(params);}else{var currentRes=this.map.getResolution();var colidx=Math.floor((bounds.left-this.maxExtent.left)/currentRes);colidx=Math.round(colidx/this.tileSize.w);var rowidx=Math.floor((this.maxExtent.top-bounds.top)/currentRes);rowidx=Math.round(rowidx/this.tileSize.h);if(this.useHttpTile){url=this.getImageFilePath({tilecol:colidx,tilerow:rowidx,scaleindex:this.resolutions.length-this.map.zoom-1});}else{url=this.getFullRequestString({tilecol:colidx,tilerow:rowidx,scaleindex:this.resolutions.length-this.map.zoom-1});}}
return url;},getFullRequestString:function(newParams,altUrl){var url=(altUrl==null)?this.url:altUrl;if(typeof url=="object"){url=url[Math.floor(Math.random()*url.length)];}
var requestString=url;var allParams=OpenLayers.Util.extend({},this.params);allParams=OpenLayers.Util.extend(allParams,newParams);var urlParams=OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(url));for(var key in allParams){if(key.toUpperCase()in urlParams){delete allParams[key];}}
var paramsString=OpenLayers.Util.getParameterString(allParams);paramsString=paramsString.replace(/,/g,"+");if(paramsString!=""){var lastServerChar=url.charAt(url.length-1);if((lastServerChar=="&")||(lastServerChar=="?")){requestString+=paramsString;}else{if(url.indexOf('?')==-1){requestString+='?'+paramsString;}else{requestString+='&'+paramsString;}}}
return requestString;},getImageFilePath:function(newParams,altUrl){var url=(altUrl==null)?this.url:altUrl;if(typeof url=="object"){url=url[Math.floor(Math.random()*url.length)];}
var requestString=url;var tileRowGroup="";var tileColGroup="";if(newParams.tilerow<0){tileRowGroup='-';}
if(newParams.tilerow==0){tileRowGroup+='0';}else{tileRowGroup+=Math.floor(Math.abs(newParams.tilerow/this.params.tileRowsPerFolder))*this.params.tileRowsPerFolder;}
if(newParams.tilecol<0){tileColGroup='-';}
if(newParams.tilecol==0){tileColGroup+='0';}else{tileColGroup+=Math.floor(Math.abs(newParams.tilecol/this.params.tileColumnsPerFolder))*this.params.tileColumnsPerFolder;}
var tilePath='/S'+Math.floor(newParams.scaleindex)
+'/'+this.params.basemaplayergroupname
+'/R'+tileRowGroup
+'/C'+tileColGroup
+'/'+(newParams.tilerow%this.params.tileRowsPerFolder)
+'_'+(newParams.tilecol%this.params.tileColumnsPerFolder)
+'.'+this.params.format;if(this.params.querystring){tilePath+="?"+this.params.querystring;}
requestString+=tilePath;return requestString;},calculateGridLayout:function(bounds,extent,resolution){var tilelon=resolution*this.tileSize.w;var tilelat=resolution*this.tileSize.h;var offsetlon=bounds.left-extent.left;var tilecol=Math.floor(offsetlon/tilelon)-this.buffer;var tilecolremain=offsetlon/tilelon-tilecol;var tileoffsetx=-tilecolremain*this.tileSize.w;var tileoffsetlon=extent.left+tilecol*tilelon;var offsetlat=extent.top-bounds.top+tilelat;var tilerow=Math.floor(offsetlat/tilelat)-this.buffer;var tilerowremain=tilerow-offsetlat/tilelat;var tileoffsety=tilerowremain*this.tileSize.h;var tileoffsetlat=extent.top-tilelat*tilerow;return{tilelon:tilelon,tilelat:tilelat,tileoffsetlon:tileoffsetlon,tileoffsetlat:tileoffsetlat,tileoffsetx:tileoffsetx,tileoffsety:tileoffsety};},CLASS_NAME:"OpenLayers.Layer.MapGuide"});OpenLayers.Layer.MapServer=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{mode:"map",map_imagetype:"png"},initialize:function(name,url,params,options){var newArguments=[];newArguments.push(name,url,params,options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);this.params=OpenLayers.Util.applyDefaults(this.params,this.DEFAULT_PARAMS);if(options==null||options.isBaseLayer==null){this.isBaseLayer=((this.params.transparent!="true")&&(this.params.transparent!=true));}},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.MapServer(this.name,this.url,this.params,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},getURL:function(bounds){bounds=this.adjustBounds(bounds);var extent=[bounds.left,bounds.bottom,bounds.right,bounds.top];var imageSize=this.getImageSize();var url=this.getFullRequestString({mapext:extent,imgext:extent,map_size:[imageSize.w,imageSize.h],imgx:imageSize.w/2,imgy:imageSize.h/2,imgxy:[imageSize.w,imageSize.h]});return url;},getFullRequestString:function(newParams,altUrl){var url=(altUrl==null)?this.url:altUrl;var allParams=OpenLayers.Util.extend({},this.params);allParams=OpenLayers.Util.extend(allParams,newParams);var paramsString=OpenLayers.Util.getParameterString(allParams);if(url instanceof Array){url=this.selectUrl(paramsString,url);}
var urlParams=OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(url));for(var key in allParams){if(key.toUpperCase()in urlParams){delete allParams[key];}}
paramsString=OpenLayers.Util.getParameterString(allParams);var requestString=url;paramsString=paramsString.replace(/,/g,"+");if(paramsString!=""){var lastServerChar=url.charAt(url.length-1);if((lastServerChar=="&")||(lastServerChar=="?")){requestString+=paramsString;}else{if(url.indexOf('?')==-1){requestString+='?'+paramsString;}else{requestString+='&'+paramsString;}}}
return requestString;},CLASS_NAME:"OpenLayers.Layer.MapServer"});OpenLayers.Layer.TMS=OpenLayers.Class(OpenLayers.Layer.Grid,{serviceVersion:"1.0.0",isBaseLayer:true,tileOrigin:null,serverResolutions:null,zoomOffset:0,initialize:function(name,url,options){var newArguments=[];newArguments.push(name,url,{},options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);},destroy:function(){OpenLayers.Layer.Grid.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.TMS(this.name,this.url,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},getURL:function(bounds){bounds=this.adjustBounds(bounds);var res=this.map.getResolution();var x=Math.round((bounds.left-this.tileOrigin.lon)/(res*this.tileSize.w));var y=Math.round((bounds.bottom-this.tileOrigin.lat)/(res*this.tileSize.h));var z=this.serverResolutions!=null?OpenLayers.Util.indexOf(this.serverResolutions,res):this.map.getZoom()+this.zoomOffset;var path=this.serviceVersion+"/"+this.layername+"/"+z+"/"+x+"/"+y+"."+this.type;var url=this.url;if(url instanceof Array){url=this.selectUrl(path,url);}
return url+path;},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},setMap:function(map){OpenLayers.Layer.Grid.prototype.setMap.apply(this,arguments);if(!this.tileOrigin){this.tileOrigin=new OpenLayers.LonLat(this.map.maxExtent.left,this.map.maxExtent.bottom);}},CLASS_NAME:"OpenLayers.Layer.TMS"});OpenLayers.Layer.TileCache=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:true,format:'image/png',serverResolutions:null,initialize:function(name,url,layername,options){this.layername=layername;OpenLayers.Layer.Grid.prototype.initialize.apply(this,[name,url,{},options]);this.extension=this.format.split('/')[1].toLowerCase();this.extension=(this.extension=='jpg')?'jpeg':this.extension;},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.TileCache(this.name,this.url,this.layername,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},getURL:function(bounds){var res=this.map.getResolution();var bbox=this.maxExtent;var size=this.tileSize;var tileX=Math.round((bounds.left-bbox.left)/(res*size.w));var tileY=Math.round((bounds.bottom-bbox.bottom)/(res*size.h));var tileZ=this.serverResolutions!=null?OpenLayers.Util.indexOf(this.serverResolutions,res):this.map.getZoom();function zeroPad(number,length){number=String(number);var zeros=[];for(var i=0;i<length;++i){zeros.push('0');}
return zeros.join('').substring(0,length-number.length)+number;}
var components=[this.layername,zeroPad(tileZ,2),zeroPad(parseInt(tileX/1000000),3),zeroPad((parseInt(tileX/1000)%1000),3),zeroPad((parseInt(tileX)%1000),3),zeroPad(parseInt(tileY/1000000),3),zeroPad((parseInt(tileY/1000)%1000),3),zeroPad((parseInt(tileY)%1000),3)+'.'+this.extension];var path=components.join('/');var url=this.url;if(url instanceof Array){url=this.selectUrl(path,url);}
url=(url.charAt(url.length-1)=='/')?url:url+'/';return url+path;},addTile:function(bounds,position){var url=this.getURL(bounds);return new OpenLayers.Tile.Image(this,position,bounds,url,this.tileSize);},CLASS_NAME:"OpenLayers.Layer.TileCache"});OpenLayers.Layer.WMS=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{service:"WMS",version:"1.1.1",request:"GetMap",styles:"",exceptions:"application/vnd.ogc.se_inimage",format:"image/jpeg"},reproject:false,isBaseLayer:true,encodeBBOX:false,noMagic:false,yx:{'EPSG:4326':true},initialize:function(name,url,params,options){var newArguments=[];params=OpenLayers.Util.upperCaseObject(params);if(parseFloat(params.VERSION)>=1.3&&!params.EXCEPTIONS){params.EXCEPTIONS="INIMAGE";}
newArguments.push(name,url,params,options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);OpenLayers.Util.applyDefaults(this.params,OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS));if(!this.noMagic&&this.params.TRANSPARENT&&this.params.TRANSPARENT.toString().toLowerCase()=="true"){if((options==null)||(!options.isBaseLayer)){this.isBaseLayer=false;}
if(this.params.FORMAT=="image/jpeg"){this.params.FORMAT=OpenLayers.Util.alphaHack()?"image/gif":"image/png";}}},destroy:function(){OpenLayers.Layer.Grid.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.WMS(this.name,this.url,this.params,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},reverseAxisOrder:function(){return(parseFloat(this.params.VERSION)>=1.3&&!!this.yx[this.map.getProjectionObject().getCode()]);},getURL:function(bounds){bounds=this.adjustBounds(bounds);var imageSize=this.getImageSize();var newParams={};var reverseAxisOrder=this.reverseAxisOrder();newParams.BBOX=this.encodeBBOX?bounds.toBBOX(null,reverseAxisOrder):bounds.toArray(reverseAxisOrder);newParams.WIDTH=imageSize.w;newParams.HEIGHT=imageSize.h;var requestString=this.getFullRequestString(newParams);return requestString;},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},mergeNewParams:function(newParams){var upperParams=OpenLayers.Util.upperCaseObject(newParams);var newArguments=[upperParams];return OpenLayers.Layer.Grid.prototype.mergeNewParams.apply(this,newArguments);},getFullRequestString:function(newParams,altUrl){var projectionCode=this.map.getProjection();var value=(projectionCode=="none")?null:projectionCode
if(parseFloat(this.params.VERSION)>=1.3){this.params.CRS=value;}else{this.params.SRS=value;}
return OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(this,arguments);},CLASS_NAME:"OpenLayers.Layer.WMS"});OpenLayers.Layer.WMTS=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:true,version:"1.0.0",requestEncoding:"KVP",url:null,layer:null,matrixSet:null,style:null,format:"image/jpeg",tileOrigin:null,tileFullExtent:null,formatSuffix:null,matrixIds:null,dimensions:null,params:null,zoomOffset:0,formatSuffixMap:{"image/png":"png","image/png8":"png","image/png24":"png","image/png32":"png","png":"png","image/jpeg":"jpg","image/jpg":"jpg","jpeg":"jpg","jpg":"jpg"},matrix:null,initialize:function(config){var required={url:true,layer:true,style:true,matrixSet:true};for(var prop in required){if(!(prop in config)){throw new Error("Missing property '"+prop+"' in layer configuration.");}}
config.params=OpenLayers.Util.upperCaseObject(config.params);var args=[config.name,config.url,config.params,config];OpenLayers.Layer.Grid.prototype.initialize.apply(this,args);if(!this.formatSuffix){this.formatSuffix=this.formatSuffixMap[this.format]||this.format.split("/").pop();}
if(this.matrixIds){var len=this.matrixIds.length;if(len&&typeof this.matrixIds[0]==="string"){var ids=this.matrixIds;this.matrixIds=new Array(len);for(var i=0;i<len;++i){this.matrixIds[i]={identifier:ids[i]};}}}},setMap:function(){OpenLayers.Layer.Grid.prototype.setMap.apply(this,arguments);this.updateMatrixProperties();},updateMatrixProperties:function(){this.matrix=this.getMatrix();if(this.matrix){if(this.matrix.topLeftCorner){this.tileOrigin=this.matrix.topLeftCorner;}
if(this.matrix.tileWidth&&this.matrix.tileHeight){this.tileSize=new OpenLayers.Size(this.matrix.tileWidth,this.matrix.tileHeight);}
if(!this.tileOrigin){this.tileOrigin=new OpenLayers.LonLat(this.maxExtent.left,this.maxExtent.top);}
if(!this.tileFullExtent){this.tileFullExtent=this.maxExtent;}}},moveTo:function(bounds,zoomChanged,dragging){if(zoomChanged||!this.matrix){this.updateMatrixProperties();}
return OpenLayers.Layer.Grid.prototype.moveTo.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.WMTS(this.options);}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},getMatrix:function(){var matrix;if(!this.matrixIds||this.matrixIds.length===0){matrix={identifier:this.map.getZoom()+this.zoomOffset};}else{if("scaleDenominator"in this.matrixIds[0]){var denom=OpenLayers.METERS_PER_INCH*OpenLayers.INCHES_PER_UNIT[this.units]*this.map.getResolution()/0.28E-3;var diff=Number.POSITIVE_INFINITY;var delta;for(var i=0,ii=this.matrixIds.length;i<ii;++i){delta=Math.abs(1-(this.matrixIds[i].scaleDenominator/denom));if(delta<diff){diff=delta;matrix=this.matrixIds[i];}}}else{matrix=this.matrixIds[this.map.getZoom()+this.zoomOffset];}}
return matrix;},getTileInfo:function(loc){var res=this.map.getResolution();var fx=(loc.lon-this.tileOrigin.lon)/(res*this.tileSize.w);var fy=(this.tileOrigin.lat-loc.lat)/(res*this.tileSize.h);var col=Math.floor(fx);var row=Math.floor(fy);return{col:col,row:row,i:Math.floor((fx-col)*this.tileSize.w),j:Math.floor((fy-row)*this.tileSize.h)};},getURL:function(bounds){bounds=this.adjustBounds(bounds);var url="";if(!this.tileFullExtent||this.tileFullExtent.intersectsBounds(bounds)){var center=bounds.getCenterLonLat();var info=this.getTileInfo(center);var matrixId=this.matrix.identifier;if(this.requestEncoding.toUpperCase()==="REST"){var path=this.version+"/"+this.layer+"/"+this.style+"/";if(this.dimensions){for(var i=0;i<this.dimensions.length;i++){if(this.params[this.dimensions[i]]){path=path+this.params[this.dimensions[i]]+"/";}}}
path=path+this.matrixSet+"/"+this.matrix.identifier+"/"+info.row+"/"+info.col+"."+this.formatSuffix;if(this.url instanceof Array){url=this.selectUrl(path,this.url);}else{url=this.url;}
if(!url.match(/\/$/)){url=url+"/";}
url=url+path;}else if(this.requestEncoding.toUpperCase()==="KVP"){var params={SERVICE:"WMTS",REQUEST:"GetTile",VERSION:this.version,LAYER:this.layer,STYLE:this.style,TILEMATRIXSET:this.matrixSet,TILEMATRIX:this.matrix.identifier,TILEROW:info.row,TILECOL:info.col,FORMAT:this.format};url=OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(this,[params]);}}
return url;},mergeNewParams:function(newParams){if(this.requestEncoding.toUpperCase()==="KVP"){return OpenLayers.Layer.Grid.prototype.mergeNewParams.apply(this,[OpenLayers.Util.upperCaseObject(newParams)]);}},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},CLASS_NAME:"OpenLayers.Layer.WMTS"});OpenLayers.Layer.WorldWind=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{},isBaseLayer:true,lzd:null,zoomLevels:null,initialize:function(name,url,lzd,zoomLevels,params,options){this.lzd=lzd;this.zoomLevels=zoomLevels;var newArguments=[];newArguments.push(name,url,params,options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);this.params=OpenLayers.Util.applyDefaults(this.params,this.DEFAULT_PARAMS);},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},getZoom:function(){var zoom=this.map.getZoom();var extent=this.map.getMaxExtent();zoom=zoom-Math.log(this.maxResolution/(this.lzd/512))/Math.log(2);return zoom;},getURL:function(bounds){bounds=this.adjustBounds(bounds);var zoom=this.getZoom();var extent=this.map.getMaxExtent();var deg=this.lzd/Math.pow(2,this.getZoom());var x=Math.floor((bounds.left-extent.left)/deg);var y=Math.floor((bounds.bottom-extent.bottom)/deg);if(this.map.getResolution()<=(this.lzd/512)&&this.getZoom()<=this.zoomLevels){return this.getFullRequestString({L:zoom,X:x,Y:y});}else{return OpenLayers.Util.getImagesLocation()+"blank.gif";}},CLASS_NAME:"OpenLayers.Layer.WorldWind"});OpenLayers.Layer.XYZ=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:true,sphericalMercator:false,zoomOffset:0,initialize:function(name,url,options){if(options&&options.sphericalMercator||this.sphericalMercator){options=OpenLayers.Util.extend({maxExtent:new OpenLayers.Bounds(-128*156543.0339,-128*156543.0339,128*156543.0339,128*156543.0339),maxResolution:156543.0339,numZoomLevels:19,units:"m",projection:"EPSG:900913"},options);}
url=url||this.url;name=name||this.name;var newArguments=[name,url,{},options];OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.XYZ(this.name,this.url,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},getURL:function(bounds){var res=this.map.getResolution();var x=Math.round((bounds.left-this.maxExtent.left)/(res*this.tileSize.w));var y=Math.round((this.maxExtent.top-bounds.top)/(res*this.tileSize.h));var z=this.map.getZoom()+this.zoomOffset;var url=this.url;var s=''+x+y+z;if(url instanceof Array)
{url=this.selectUrl(s,url);}
var path=OpenLayers.String.format(url,{'x':x,'y':y,'z':z});return path;},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},setMap:function(map){OpenLayers.Layer.Grid.prototype.setMap.apply(this,arguments);if(!this.tileOrigin){this.tileOrigin=new OpenLayers.LonLat(this.maxExtent.left,this.maxExtent.bottom);}},CLASS_NAME:"OpenLayers.Layer.XYZ"});OpenLayers.Layer.OSM=OpenLayers.Class(OpenLayers.Layer.XYZ,{name:"OpenStreetMap",attribution:"Data CC-By-SA by <a href='http://openstreetmap.org/'>OpenStreetMap</a>",sphericalMercator:true,url:'http://tile.openstreetmap.org/${z}/${x}/${y}.png',clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.OSM(this.name,this.url,this.getOptions());}
obj=OpenLayers.Layer.XYZ.prototype.clone.apply(this,[obj]);return obj;},CLASS_NAME:"OpenLayers.Layer.OSM"});OpenLayers.Layer.Zoomify=OpenLayers.Class(OpenLayers.Layer.Grid,{url:null,size:null,isBaseLayer:true,standardTileSize:256,numberOfTiers:0,tileCountUpToTier:new Array(),tierSizeInTiles:new Array(),tierImageSize:new Array(),initialize:function(name,url,size,options){this.initializeZoomify(size);var newArguments=[];newArguments.push(name,url,size,{},options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);},initializeZoomify:function(size){var imageSize=size.clone()
var tiles=new OpenLayers.Size(Math.ceil(imageSize.w/this.standardTileSize),Math.ceil(imageSize.h/this.standardTileSize));this.tierSizeInTiles.push(tiles);this.tierImageSize.push(imageSize);while(imageSize.w>this.standardTileSize||imageSize.h>this.standardTileSize){imageSize=new OpenLayers.Size(Math.floor(imageSize.w/2),Math.floor(imageSize.h/2));tiles=new OpenLayers.Size(Math.ceil(imageSize.w/this.standardTileSize),Math.ceil(imageSize.h/this.standardTileSize));this.tierSizeInTiles.push(tiles);this.tierImageSize.push(imageSize);}
this.tierSizeInTiles.reverse();this.tierImageSize.reverse();this.numberOfTiers=this.tierSizeInTiles.length;this.tileCountUpToTier[0]=0;for(var i=1;i<this.numberOfTiers;i++){this.tileCountUpToTier.push(this.tierSizeInTiles[i-1].w*this.tierSizeInTiles[i-1].h+
this.tileCountUpToTier[i-1]);}},destroy:function(){OpenLayers.Layer.Grid.prototype.destroy.apply(this,arguments);this.tileCountUpToTier.length=0
this.tierSizeInTiles.length=0
this.tierImageSize.length=0},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.Zoomify(this.name,this.url,this.size,this.options);}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},getURL:function(bounds){bounds=this.adjustBounds(bounds);var res=this.map.getResolution();var x=Math.round((bounds.left-this.tileOrigin.lon)/(res*this.tileSize.w));var y=Math.round((this.tileOrigin.lat-bounds.top)/(res*this.tileSize.h));var z=this.map.getZoom();var tileIndex=x+y*this.tierSizeInTiles[z].w+this.tileCountUpToTier[z];var path="TileGroup"+Math.floor((tileIndex)/256)+"/"+z+"-"+x+"-"+y+".jpg";var url=this.url;if(url instanceof Array){url=this.selectUrl(path,url);}
return url+path;},getImageSize:function(){if(arguments.length>0){bounds=this.adjustBounds(arguments[0]);var res=this.map.getResolution();var x=Math.round((bounds.left-this.tileOrigin.lon)/(res*this.tileSize.w));var y=Math.round((this.tileOrigin.lat-bounds.top)/(res*this.tileSize.h));var z=this.map.getZoom();var w=this.standardTileSize;var h=this.standardTileSize;if(x==this.tierSizeInTiles[z].w-1){var w=this.tierImageSize[z].w%this.standardTileSize;};if(y==this.tierSizeInTiles[z].h-1){var h=this.tierImageSize[z].h%this.standardTileSize;};return(new OpenLayers.Size(w,h));}else{return this.tileSize;}},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},setMap:function(map){OpenLayers.Layer.Grid.prototype.setMap.apply(this,arguments);this.tileOrigin=new OpenLayers.LonLat(this.map.maxExtent.left,this.map.maxExtent.top);},calculateGridLayout:function(bounds,extent,resolution){var tilelon=resolution*this.tileSize.w;var tilelat=resolution*this.tileSize.h;var offsetlon=bounds.left-extent.left;var tilecol=Math.floor(offsetlon/tilelon)-this.buffer;var tilecolremain=offsetlon/tilelon-tilecol;var tileoffsetx=-tilecolremain*this.tileSize.w;var tileoffsetlon=extent.left+tilecol*tilelon;var offsetlat=extent.top-bounds.top+tilelat;var tilerow=Math.floor(offsetlat/tilelat)-this.buffer;var tilerowremain=tilerow-offsetlat/tilelat;var tileoffsety=tilerowremain*this.tileSize.h;var tileoffsetlat=extent.top-tilelat*tilerow;return{tilelon:tilelon,tilelat:tilelat,tileoffsetlon:tileoffsetlon,tileoffsetlat:tileoffsetlat,tileoffsetx:tileoffsetx,tileoffsety:tileoffsety};},CLASS_NAME:"OpenLayers.Layer.Zoomify"});OpenLayers.Protocol.SQL.Gears=OpenLayers.Class(OpenLayers.Protocol.SQL,{FID_PREFIX:'__gears_fid__',NULL_GEOMETRY:'__gears_null_geometry__',NULL_FEATURE_STATE:'__gears_null_feature_state__',jsonParser:null,wktParser:null,fidRegExp:null,saveFeatureState:true,typeOfFid:"string",db:null,initialize:function(options){if(!this.supported()){return;}
OpenLayers.Protocol.SQL.prototype.initialize.apply(this,[options]);this.jsonParser=new OpenLayers.Format.JSON();this.wktParser=new OpenLayers.Format.WKT();this.fidRegExp=new RegExp('^'+this.FID_PREFIX);this.initializeDatabase();},initializeDatabase:function(){this.db=google.gears.factory.create('beta.database');this.db.open(this.databaseName);this.db.execute("CREATE TABLE IF NOT EXISTS "+this.tableName+" (fid TEXT UNIQUE, geometry TEXT, properties TEXT,"+"  state TEXT)");},destroy:function(){this.db.close();this.db=null;this.jsonParser=null;this.wktParser=null;OpenLayers.Protocol.SQL.prototype.destroy.apply(this);},supported:function(){return!!(window.google&&google.gears);},read:function(options){OpenLayers.Protocol.prototype.read.apply(this,arguments);options=OpenLayers.Util.applyDefaults(options,this.options);var feature,features=[];var rs=this.db.execute("SELECT * FROM "+this.tableName);while(rs.isValidRow()){feature=this.unfreezeFeature(rs);if(this.evaluateFilter(feature,options.filter)){if(!options.noFeatureStateReset){feature.state=null;}
features.push(feature);}
rs.next();}
rs.close();var resp=new OpenLayers.Protocol.Response({code:OpenLayers.Protocol.Response.SUCCESS,requestType:"read",features:features});if(options&&options.callback){options.callback.call(options.scope,resp);}
return resp;},unfreezeFeature:function(row){var feature;var wkt=row.fieldByName('geometry');if(wkt==this.NULL_GEOMETRY){feature=new OpenLayers.Feature.Vector();}else{feature=this.wktParser.read(wkt);}
feature.attributes=this.jsonParser.read(row.fieldByName('properties'));feature.fid=this.extractFidFromField(row.fieldByName('fid'));var state=row.fieldByName('state');if(state==this.NULL_FEATURE_STATE){state=null;}
feature.state=state;return feature;},extractFidFromField:function(field){if(!field.match(this.fidRegExp)&&this.typeOfFid=="number"){field=parseFloat(field);}
return field;},create:function(features,options){options=OpenLayers.Util.applyDefaults(options,this.options);var resp=this.createOrUpdate(features);resp.requestType="create";if(options&&options.callback){options.callback.call(options.scope,resp);}
return resp;},update:function(features,options){options=OpenLayers.Util.applyDefaults(options,this.options);var resp=this.createOrUpdate(features);resp.requestType="update";if(options&&options.callback){options.callback.call(options.scope,resp);}
return resp;},createOrUpdate:function(features){if(!(features instanceof Array)){features=[features];}
var i,len=features.length,feature;var insertedFeatures=new Array(len);for(i=0;i<len;i++){feature=features[i];var params=this.freezeFeature(feature);this.db.execute("REPLACE INTO "+this.tableName+" (fid, geometry, properties, state)"+" VALUES (?, ?, ?, ?)",params);var clone=feature.clone();clone.fid=this.extractFidFromField(params[0]);insertedFeatures[i]=clone;}
return new OpenLayers.Protocol.Response({code:OpenLayers.Protocol.Response.SUCCESS,features:insertedFeatures,reqFeatures:features});},freezeFeature:function(feature){feature.fid=feature.fid!=null?""+feature.fid:OpenLayers.Util.createUniqueID(this.FID_PREFIX);var geometry=feature.geometry!=null?feature.geometry.toString():this.NULL_GEOMETRY;var properties=this.jsonParser.write(feature.attributes);var state=this.getFeatureStateForFreeze(feature);return[feature.fid,geometry,properties,state];},getFeatureStateForFreeze:function(feature){var state;if(!this.saveFeatureState){state=this.NULL_FEATURE_STATE;}else if(this.createdOffline(feature)){state=OpenLayers.State.INSERT;}else{state=feature.state;}
return state;},"delete":function(features,options){if(!(features instanceof Array)){features=[features];}
options=OpenLayers.Util.applyDefaults(options,this.options);var i,len,feature;for(i=0,len=features.length;i<len;i++){feature=features[i];if(this.saveFeatureState&&!this.createdOffline(feature)){var toDelete=feature.clone();toDelete.fid=feature.fid;if(toDelete.geometry){toDelete.geometry.destroy();toDelete.geometry=null;}
toDelete.state=feature.state;this.createOrUpdate(toDelete);}else{this.db.execute("DELETE FROM "+this.tableName+" WHERE fid = ?",[feature.fid]);}}
var resp=new OpenLayers.Protocol.Response({code:OpenLayers.Protocol.Response.SUCCESS,requestType:"delete",reqFeatures:features});if(options&&options.callback){options.callback.call(options.scope,resp);}
return resp;},createdOffline:function(feature){return(typeof feature.fid=="string"&&!!(feature.fid.match(this.fidRegExp)));},commit:function(features,options){var opt,resp=[],nRequests=0,nResponses=0;function callback(resp){if(++nResponses<nRequests){resp.last=false;}
this.callUserCallback(options,resp);}
var feature,toCreate=[],toUpdate=[],toDelete=[];for(var i=features.length-1;i>=0;i--){feature=features[i];switch(feature.state){case OpenLayers.State.INSERT:toCreate.push(feature);break;case OpenLayers.State.UPDATE:toUpdate.push(feature);break;case OpenLayers.State.DELETE:toDelete.push(feature);break;}}
if(toCreate.length>0){nRequests++;opt=OpenLayers.Util.applyDefaults({"callback":callback,"scope":this},options.create);resp.push(this.create(toCreate,opt));}
if(toUpdate.length>0){nRequests++;opt=OpenLayers.Util.applyDefaults({"callback":callback,"scope":this},options.update);resp.push(this.update(toUpdate,opt));}
if(toDelete.length>0){nRequests++;opt=OpenLayers.Util.applyDefaults({"callback":callback,"scope":this},options["delete"]);resp.push(this["delete"](toDelete,opt));}
return resp;},clear:function(){this.db.execute("DELETE FROM "+this.tableName);},callUserCallback:function(options,resp){var opt=options[resp.requestType];if(opt&&opt.callback){opt.callback.call(opt.scope,resp);}
if(resp.last&&options.callback){options.callback.call(options.scope);}},CLASS_NAME:"OpenLayers.Protocol.SQL.Gears"});OpenLayers.Rule=OpenLayers.Class({id:null,name:null,title:null,description:null,context:null,filter:null,elseFilter:false,symbolizer:null,symbolizers:null,minScaleDenominator:null,maxScaleDenominator:null,initialize:function(options){this.symbolizer={};OpenLayers.Util.extend(this,options);if(this.symbolizers){delete this.symbolizer;}
this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");},destroy:function(){for(var i in this.symbolizer){this.symbolizer[i]=null;}
this.symbolizer=null;delete this.symbolizers;},evaluate:function(feature){var context=this.getContext(feature);var applies=true;if(this.minScaleDenominator||this.maxScaleDenominator){var scale=feature.layer.map.getScale();}
if(this.minScaleDenominator){applies=scale>=OpenLayers.Style.createLiteral(this.minScaleDenominator,context);}
if(applies&&this.maxScaleDenominator){applies=scale<OpenLayers.Style.createLiteral(this.maxScaleDenominator,context);}
if(applies&&this.filter){if(this.filter.CLASS_NAME=="OpenLayers.Filter.FeatureId"){applies=this.filter.evaluate(feature);}else{applies=this.filter.evaluate(context);}}
return applies;},getContext:function(feature){var context=this.context;if(!context){context=feature.attributes||feature.data;}
if(typeof this.context=="function"){context=this.context(feature);}
return context;},clone:function(){var options=OpenLayers.Util.extend({},this);if(this.symbolizers){var len=this.symbolizers.length;options.symbolizers=new Array(len);for(var i=0;i<len;++i){options.symbolizers[i]=this.symbolizers[i].clone();}}else{options.symbolizer={};var value,type;for(var key in this.symbolizer){value=this.symbolizer[key];type=typeof value;if(type==="object"){options.symbolizer[key]=OpenLayers.Util.extend({},value);}else if(type==="string"){options.symbolizer[key]=value;}}}
options.filter=this.filter&&this.filter.clone();options.context=this.context&&OpenLayers.Util.extend({},this.context);return new OpenLayers.Rule(options);},CLASS_NAME:"OpenLayers.Rule"});OpenLayers.StyleMap=OpenLayers.Class({styles:null,extendDefault:true,initialize:function(style,options){this.styles={"default":new OpenLayers.Style(OpenLayers.Feature.Vector.style["default"]),"select":new OpenLayers.Style(OpenLayers.Feature.Vector.style["select"]),"temporary":new OpenLayers.Style(OpenLayers.Feature.Vector.style["temporary"]),"delete":new OpenLayers.Style(OpenLayers.Feature.Vector.style["delete"])};if(style instanceof OpenLayers.Style){this.styles["default"]=style;this.styles["select"]=style;this.styles["temporary"]=style;this.styles["delete"]=style;}else if(typeof style=="object"){for(var key in style){if(style[key]instanceof OpenLayers.Style){this.styles[key]=style[key];}else if(typeof style[key]=="object"){this.styles[key]=new OpenLayers.Style(style[key]);}else{this.styles["default"]=new OpenLayers.Style(style);this.styles["select"]=new OpenLayers.Style(style);this.styles["temporary"]=new OpenLayers.Style(style);this.styles["delete"]=new OpenLayers.Style(style);break;}}}
OpenLayers.Util.extend(this,options);},destroy:function(){for(var key in this.styles){this.styles[key].destroy();}
this.styles=null;},createSymbolizer:function(feature,intent){if(!feature){feature=new OpenLayers.Feature.Vector();}
if(!this.styles[intent]){intent="default";}
feature.renderIntent=intent;var defaultSymbolizer={};if(this.extendDefault&&intent!="default"){defaultSymbolizer=this.styles["default"].createSymbolizer(feature);}
return OpenLayers.Util.extend(defaultSymbolizer,this.styles[intent].createSymbolizer(feature));},addUniqueValueRules:function(renderIntent,property,symbolizers,context){var rules=[];for(var value in symbolizers){rules.push(new OpenLayers.Rule({symbolizer:symbolizers[value],context:context,filter:new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO,property:property,value:value})}));}
this.styles[renderIntent].addRules(rules);},CLASS_NAME:"OpenLayers.StyleMap"});OpenLayers.Control.NavToolbar=OpenLayers.Class(OpenLayers.Control.Panel,{initialize:function(options){OpenLayers.Control.Panel.prototype.initialize.apply(this,[options]);this.addControls([new OpenLayers.Control.Navigation(),new OpenLayers.Control.ZoomBox()]);},draw:function(){var div=OpenLayers.Control.Panel.prototype.draw.apply(this,arguments);this.activateControl(this.controls[0]);return div;},CLASS_NAME:"OpenLayers.Control.NavToolbar"});OpenLayers.Filter.Comparison=OpenLayers.Class(OpenLayers.Filter,{type:null,property:null,value:null,matchCase:true,lowerBoundary:null,upperBoundary:null,initialize:function(options){OpenLayers.Filter.prototype.initialize.apply(this,[options]);},evaluate:function(context){if(context instanceof OpenLayers.Feature.Vector){context=context.attributes;}
var result=false;var got=context[this.property];switch(this.type){case OpenLayers.Filter.Comparison.EQUAL_TO:var exp=this.value;if(!this.matchCase&&typeof got=="string"&&typeof exp=="string"){result=(got.toUpperCase()==exp.toUpperCase());}else{result=(got==exp);}
break;case OpenLayers.Filter.Comparison.NOT_EQUAL_TO:var exp=this.value;if(!this.matchCase&&typeof got=="string"&&typeof exp=="string"){result=(got.toUpperCase()!=exp.toUpperCase());}else{result=(got!=exp);}
break;case OpenLayers.Filter.Comparison.LESS_THAN:result=got<this.value;break;case OpenLayers.Filter.Comparison.GREATER_THAN:result=got>this.value;break;case OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO:result=got<=this.value;break;case OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO:result=got>=this.value;break;case OpenLayers.Filter.Comparison.BETWEEN:result=(got>=this.lowerBoundary)&&(got<=this.upperBoundary);break;case OpenLayers.Filter.Comparison.LIKE:var regexp=new RegExp(this.value,"gi");result=regexp.test(got);break;}
return result;},value2regex:function(wildCard,singleChar,escapeChar){if(wildCard=="."){var msg="'.' is an unsupported wildCard character for "+"OpenLayers.Filter.Comparison";OpenLayers.Console.error(msg);return null;}
wildCard=wildCard?wildCard:"*";singleChar=singleChar?singleChar:".";escapeChar=escapeChar?escapeChar:"!";this.value=this.value.replace(new RegExp("\\"+escapeChar+"(.|$)","g"),"\\$1");this.value=this.value.replace(new RegExp("\\"+singleChar,"g"),".");this.value=this.value.replace(new RegExp("\\"+wildCard,"g"),".*");this.value=this.value.replace(new RegExp("\\\\.\\*","g"),"\\"+wildCard);this.value=this.value.replace(new RegExp("\\\\\\.","g"),"\\"+singleChar);return this.value;},regex2value:function(){var value=this.value;value=value.replace(/!/g,"!!");value=value.replace(/(\\)?\\\./g,function($0,$1){return $1?$0:"!.";});value=value.replace(/(\\)?\\\*/g,function($0,$1){return $1?$0:"!*";});value=value.replace(/\\\\/g,"\\");value=value.replace(/\.\*/g,"*");return value;},clone:function(){return OpenLayers.Util.extend(new OpenLayers.Filter.Comparison(),this);},CLASS_NAME:"OpenLayers.Filter.Comparison"});OpenLayers.Filter.Comparison.EQUAL_TO="==";OpenLayers.Filter.Comparison.NOT_EQUAL_TO="!=";OpenLayers.Filter.Comparison.LESS_THAN="<";OpenLayers.Filter.Comparison.GREATER_THAN=">";OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO="<=";OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO=">=";OpenLayers.Filter.Comparison.BETWEEN="..";OpenLayers.Filter.Comparison.LIKE="~";OpenLayers.Filter.FeatureId=OpenLayers.Class(OpenLayers.Filter,{fids:null,initialize:function(options){this.fids=[];OpenLayers.Filter.prototype.initialize.apply(this,[options]);},evaluate:function(feature){for(var i=0,len=this.fids.length;i<len;i++){var fid=feature.fid||feature.id;if(fid==this.fids[i]){return true;}}
return false;},clone:function(){var filter=new OpenLayers.Filter.FeatureId();OpenLayers.Util.extend(filter,this);filter.fids=this.fids.slice();return filter;},CLASS_NAME:"OpenLayers.Filter.FeatureId"});OpenLayers.Filter.Logical=OpenLayers.Class(OpenLayers.Filter,{filters:null,type:null,initialize:function(options){this.filters=[];OpenLayers.Filter.prototype.initialize.apply(this,[options]);},destroy:function(){this.filters=null;OpenLayers.Filter.prototype.destroy.apply(this);},evaluate:function(context){switch(this.type){case OpenLayers.Filter.Logical.AND:for(var i=0,len=this.filters.length;i<len;i++){if(this.filters[i].evaluate(context)==false){return false;}}
return true;case OpenLayers.Filter.Logical.OR:for(var i=0,len=this.filters.length;i<len;i++){if(this.filters[i].evaluate(context)==true){return true;}}
return false;case OpenLayers.Filter.Logical.NOT:return(!this.filters[0].evaluate(context));}},clone:function(){var filters=[];for(var i=0,len=this.filters.length;i<len;++i){filters.push(this.filters[i].clone());}
return new OpenLayers.Filter.Logical({type:this.type,filters:filters});},CLASS_NAME:"OpenLayers.Filter.Logical"});OpenLayers.Filter.Logical.AND="&&";OpenLayers.Filter.Logical.OR="||";OpenLayers.Filter.Logical.NOT="!";OpenLayers.Filter.Spatial=OpenLayers.Class(OpenLayers.Filter,{type:null,property:null,value:null,distance:null,distanceUnits:null,initialize:function(options){OpenLayers.Filter.prototype.initialize.apply(this,[options]);},evaluate:function(feature){var intersect=false;switch(this.type){case OpenLayers.Filter.Spatial.BBOX:case OpenLayers.Filter.Spatial.INTERSECTS:if(feature.geometry){var geom=this.value;if(this.value.CLASS_NAME=="OpenLayers.Bounds"){geom=this.value.toGeometry();}
if(feature.geometry.intersects(geom)){intersect=true;}}
break;default:OpenLayers.Console.error(OpenLayers.i18n("filterEvaluateNotImplemented"));break;}
return intersect;},clone:function(){var options=OpenLayers.Util.applyDefaults({value:this.value&&this.value.clone&&this.value.clone()},this);return new OpenLayers.Filter.Spatial(options);},CLASS_NAME:"OpenLayers.Filter.Spatial"});OpenLayers.Filter.Spatial.BBOX="BBOX";OpenLayers.Filter.Spatial.INTERSECTS="INTERSECTS";OpenLayers.Filter.Spatial.DWITHIN="DWITHIN";OpenLayers.Filter.Spatial.WITHIN="WITHIN";OpenLayers.Filter.Spatial.CONTAINS="CONTAINS";OpenLayers.Geometry.Collection=OpenLayers.Class(OpenLayers.Geometry,{components:null,componentTypes:null,initialize:function(components){OpenLayers.Geometry.prototype.initialize.apply(this,arguments);this.components=[];if(components!=null){this.addComponents(components);}},destroy:function(){this.components.length=0;this.components=null;OpenLayers.Geometry.prototype.destroy.apply(this,arguments);},clone:function(){var geometry=eval("new "+this.CLASS_NAME+"()");for(var i=0,len=this.components.length;i<len;i++){geometry.addComponent(this.components[i].clone());}
OpenLayers.Util.applyDefaults(geometry,this);return geometry;},getComponentsString:function(){var strings=[];for(var i=0,len=this.components.length;i<len;i++){strings.push(this.components[i].toShortString());}
return strings.join(",");},calculateBounds:function(){this.bounds=null;if(this.components&&this.components.length>0){this.setBounds(this.components[0].getBounds());for(var i=1,len=this.components.length;i<len;i++){this.extendBounds(this.components[i].getBounds());}}},addComponents:function(components){if(!(components instanceof Array)){components=[components];}
for(var i=0,len=components.length;i<len;i++){this.addComponent(components[i]);}},addComponent:function(component,index){var added=false;if(component){if(this.componentTypes==null||(OpenLayers.Util.indexOf(this.componentTypes,component.CLASS_NAME)>-1)){if(index!=null&&(index<this.components.length)){var components1=this.components.slice(0,index);var components2=this.components.slice(index,this.components.length);components1.push(component);this.components=components1.concat(components2);}else{this.components.push(component);}
component.parent=this;this.clearBounds();added=true;}}
return added;},removeComponents:function(components){if(!(components instanceof Array)){components=[components];}
for(var i=components.length-1;i>=0;--i){this.removeComponent(components[i]);}},removeComponent:function(component){OpenLayers.Util.removeItem(this.components,component);this.clearBounds();},getLength:function(){var length=0.0;for(var i=0,len=this.components.length;i<len;i++){length+=this.components[i].getLength();}
return length;},getArea:function(){var area=0.0;for(var i=0,len=this.components.length;i<len;i++){area+=this.components[i].getArea();}
return area;},getGeodesicArea:function(projection){var area=0.0;for(var i=0,len=this.components.length;i<len;i++){area+=this.components[i].getGeodesicArea(projection);}
return area;},getCentroid:function(weighted){if(!weighted){return this.components.length&&this.components[0].getCentroid();}
var len=this.components.length;if(!len){return false;}
var areas=[];var centroids=[];var areaSum=0;var minArea=Number.MAX_VALUE;var component;for(var i=0;i<len;++i){component=this.components[i];var area=component.getArea();var centroid=component.getCentroid(true);if(isNaN(area)||isNaN(centroid.x)||isNaN(centroid.y)){continue;}
areas.push(area);areaSum+=area;minArea=(area<minArea&&area>0)?area:minArea;centroids.push(centroid);}
len=areas.length;if(areaSum===0){for(var i=0;i<len;++i){areas[i]=1;}
areaSum=areas.length;}else{for(var i=0;i<len;++i){areas[i]/=minArea;}
areaSum/=minArea;}
var xSum=0,ySum=0,centroid,area;for(var i=0;i<len;++i){centroid=centroids[i];area=areas[i];xSum+=centroid.x*area;ySum+=centroid.y*area;}
return new OpenLayers.Geometry.Point(xSum/areaSum,ySum/areaSum);},getGeodesicLength:function(projection){var length=0.0;for(var i=0,len=this.components.length;i<len;i++){length+=this.components[i].getGeodesicLength(projection);}
return length;},move:function(x,y){for(var i=0,len=this.components.length;i<len;i++){this.components[i].move(x,y);}},rotate:function(angle,origin){for(var i=0,len=this.components.length;i<len;++i){this.components[i].rotate(angle,origin);}},resize:function(scale,origin,ratio){for(var i=0;i<this.components.length;++i){this.components[i].resize(scale,origin,ratio);}
return this;},distanceTo:function(geometry,options){var edge=!(options&&options.edge===false);var details=edge&&options&&options.details;var result,best,distance;var min=Number.POSITIVE_INFINITY;for(var i=0,len=this.components.length;i<len;++i){result=this.components[i].distanceTo(geometry,options);distance=details?result.distance:result;if(distance<min){min=distance;best=result;if(min==0){break;}}}
return best;},equals:function(geometry){var equivalent=true;if(!geometry||!geometry.CLASS_NAME||(this.CLASS_NAME!=geometry.CLASS_NAME)){equivalent=false;}else if(!(geometry.components instanceof Array)||(geometry.components.length!=this.components.length)){equivalent=false;}else{for(var i=0,len=this.components.length;i<len;++i){if(!this.components[i].equals(geometry.components[i])){equivalent=false;break;}}}
return equivalent;},transform:function(source,dest){if(source&&dest){for(var i=0,len=this.components.length;i<len;i++){var component=this.components[i];component.transform(source,dest);}
this.bounds=null;}
return this;},intersects:function(geometry){var intersect=false;for(var i=0,len=this.components.length;i<len;++i){intersect=geometry.intersects(this.components[i]);if(intersect){break;}}
return intersect;},getVertices:function(nodes){var vertices=[];for(var i=0,len=this.components.length;i<len;++i){Array.prototype.push.apply(vertices,this.components[i].getVertices(nodes));}
return vertices;},CLASS_NAME:"OpenLayers.Geometry.Collection"});OpenLayers.Geometry.Point=OpenLayers.Class(OpenLayers.Geometry,{x:null,y:null,initialize:function(x,y){OpenLayers.Geometry.prototype.initialize.apply(this,arguments);this.x=parseFloat(x);this.y=parseFloat(y);},clone:function(obj){if(obj==null){obj=new OpenLayers.Geometry.Point(this.x,this.y);}
OpenLayers.Util.applyDefaults(obj,this);return obj;},calculateBounds:function(){this.bounds=new OpenLayers.Bounds(this.x,this.y,this.x,this.y);},distanceTo:function(geometry,options){var edge=!(options&&options.edge===false);var details=edge&&options&&options.details;var distance,x0,y0,x1,y1,result;if(geometry instanceof OpenLayers.Geometry.Point){x0=this.x;y0=this.y;x1=geometry.x;y1=geometry.y;distance=Math.sqrt(Math.pow(x0-x1,2)+Math.pow(y0-y1,2));result=!details?distance:{x0:x0,y0:y0,x1:x1,y1:y1,distance:distance};}else{result=geometry.distanceTo(this,options);if(details){result={x0:result.x1,y0:result.y1,x1:result.x0,y1:result.y0,distance:result.distance};}}
return result;},equals:function(geom){var equals=false;if(geom!=null){equals=((this.x==geom.x&&this.y==geom.y)||(isNaN(this.x)&&isNaN(this.y)&&isNaN(geom.x)&&isNaN(geom.y)));}
return equals;},toShortString:function(){return(this.x+", "+this.y);},move:function(x,y){this.x=this.x+x;this.y=this.y+y;this.clearBounds();},rotate:function(angle,origin){angle*=Math.PI/180;var radius=this.distanceTo(origin);var theta=angle+Math.atan2(this.y-origin.y,this.x-origin.x);this.x=origin.x+(radius*Math.cos(theta));this.y=origin.y+(radius*Math.sin(theta));this.clearBounds();},getCentroid:function(){return new OpenLayers.Geometry.Point(this.x,this.y);},resize:function(scale,origin,ratio){ratio=(ratio==undefined)?1:ratio;this.x=origin.x+(scale*ratio*(this.x-origin.x));this.y=origin.y+(scale*(this.y-origin.y));this.clearBounds();return this;},intersects:function(geometry){var intersect=false;if(geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){intersect=this.equals(geometry);}else{intersect=geometry.intersects(this);}
return intersect;},transform:function(source,dest){if((source&&dest)){OpenLayers.Projection.transform(this,source,dest);this.bounds=null;}
return this;},getVertices:function(nodes){return[this];},CLASS_NAME:"OpenLayers.Geometry.Point"});OpenLayers.Geometry.Rectangle=OpenLayers.Class(OpenLayers.Geometry,{x:null,y:null,width:null,height:null,initialize:function(x,y,width,height){OpenLayers.Geometry.prototype.initialize.apply(this,arguments);this.x=x;this.y=y;this.width=width;this.height=height;},calculateBounds:function(){this.bounds=new OpenLayers.Bounds(this.x,this.y,this.x+this.width,this.y+this.height);},getLength:function(){var length=(2*this.width)+(2*this.height);return length;},getArea:function(){var area=this.width*this.height;return area;},CLASS_NAME:"OpenLayers.Geometry.Rectangle"});OpenLayers.Geometry.Surface=OpenLayers.Class(OpenLayers.Geometry,{initialize:function(){OpenLayers.Geometry.prototype.initialize.apply(this,arguments);},CLASS_NAME:"OpenLayers.Geometry.Surface"});OpenLayers.Layer.KaMapCache=OpenLayers.Class(OpenLayers.Layer.KaMap,{IMAGE_EXTENSIONS:{'jpeg':'jpg','gif':'gif','png':'png','png8':'png','png24':'png','dithered':'png'},DEFAULT_FORMAT:'jpeg',initialize:function(name,url,params,options){OpenLayers.Layer.KaMap.prototype.initialize.apply(this,arguments);this.extension=this.IMAGE_EXTENSIONS[this.params.i.toLowerCase()||DEFAULT_FORMAT];},getURL:function(bounds){bounds=this.adjustBounds(bounds);var mapRes=this.map.getResolution();var scale=Math.round((this.map.getScale()*10000))/10000;var pX=Math.round(bounds.left/mapRes);var pY=-Math.round(bounds.top/mapRes);var metaX=Math.floor(pX/this.tileSize.w/this.params.metaTileSize.w)*this.tileSize.w*this.params.metaTileSize.w;var metaY=Math.floor(pY/this.tileSize.h/this.params.metaTileSize.h)*this.tileSize.h*this.params.metaTileSize.h;var url=this.url;if(url instanceof Array){url=this.selectUrl(paramsString,url);}
var components=[url,"/",this.params.map,"/",scale,"/",this.params.g.replace(/\s/g,'_'),"/def/t",metaY,"/l",metaX,"/t",pY,"l",pX,".",this.extension];return components.join("");},CLASS_NAME:"OpenLayers.Layer.KaMapCache"});OpenLayers.Layer.MapServer.Untiled=OpenLayers.Class(OpenLayers.Layer.MapServer,{singleTile:true,initialize:function(name,url,params,options){OpenLayers.Layer.MapServer.prototype.initialize.apply(this,arguments);var msg="The OpenLayers.Layer.MapServer.Untiled class is deprecated and "+"will be removed in 3.0. Instead, you should use the "+"normal OpenLayers.Layer.MapServer class, passing it the option "+"'singleTile' as true.";OpenLayers.Console.warn(msg);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.MapServer.Untiled(this.name,this.url,this.params,this.getOptions());}
obj=OpenLayers.Layer.MapServer.prototype.clone.apply(this,[obj]);return obj;},CLASS_NAME:"OpenLayers.Layer.MapServer.Untiled"});OpenLayers.Layer.Vector=OpenLayers.Class(OpenLayers.Layer,{EVENT_TYPES:["beforefeatureadded","beforefeaturesadded","featureadded","featuresadded","beforefeatureremoved","beforefeaturesremoved","featureremoved","featuresremoved","beforefeatureselected","featureselected","featureunselected","beforefeaturemodified","featuremodified","afterfeaturemodified","vertexmodified","sketchstarted","sketchmodified","sketchcomplete","refresh"],isBaseLayer:false,isFixed:false,isVector:true,features:null,filter:null,selectedFeatures:null,unrenderedFeatures:null,reportError:true,style:null,styleMap:null,strategies:null,protocol:null,renderers:['SVG','VML','Canvas'],renderer:null,rendererOptions:null,geometryType:null,drawn:false,initialize:function(name,options){this.EVENT_TYPES=OpenLayers.Layer.Vector.prototype.EVENT_TYPES.concat(OpenLayers.Layer.prototype.EVENT_TYPES);OpenLayers.Layer.prototype.initialize.apply(this,arguments);if(!this.renderer||!this.renderer.supported()){this.assignRenderer();}
if(!this.renderer||!this.renderer.supported()){this.renderer=null;this.displayError();}
if(!this.styleMap){this.styleMap=new OpenLayers.StyleMap();}
this.features=[];this.selectedFeatures=[];this.unrenderedFeatures={};if(this.strategies){for(var i=0,len=this.strategies.length;i<len;i++){this.strategies[i].setLayer(this);}}},destroy:function(){if(this.strategies){var strategy,i,len;for(i=0,len=this.strategies.length;i<len;i++){strategy=this.strategies[i];if(strategy.autoDestroy){strategy.destroy();}}
this.strategies=null;}
if(this.protocol){if(this.protocol.autoDestroy){this.protocol.destroy();}
this.protocol=null;}
this.destroyFeatures();this.features=null;this.selectedFeatures=null;this.unrenderedFeatures=null;if(this.renderer){this.renderer.destroy();}
this.renderer=null;this.geometryType=null;this.drawn=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.Vector(this.name,this.getOptions());}
obj=OpenLayers.Layer.prototype.clone.apply(this,[obj]);var features=this.features;var len=features.length;var clonedFeatures=new Array(len);for(var i=0;i<len;++i){clonedFeatures[i]=features[i].clone();}
obj.features=clonedFeatures;return obj;},refresh:function(obj){if(this.calculateInRange()&&this.visibility){this.events.triggerEvent("refresh",obj);}},assignRenderer:function(){for(var i=0,len=this.renderers.length;i<len;i++){var rendererClass=this.renderers[i];var renderer=(typeof rendererClass=="function")?rendererClass:OpenLayers.Renderer[rendererClass];if(renderer&&renderer.prototype.supported()){this.renderer=new renderer(this.div,this.rendererOptions);break;}}},displayError:function(){if(this.reportError){OpenLayers.Console.userError(OpenLayers.i18n("browserNotSupported",{'renderers':this.renderers.join("\n")}));}},setMap:function(map){OpenLayers.Layer.prototype.setMap.apply(this,arguments);if(!this.renderer){this.map.removeLayer(this);}else{this.renderer.map=this.map;this.renderer.setSize(this.map.getSize());}},afterAdd:function(){if(this.strategies){var strategy,i,len;for(i=0,len=this.strategies.length;i<len;i++){strategy=this.strategies[i];if(strategy.autoActivate){strategy.activate();}}}},removeMap:function(map){this.drawn=false;if(this.strategies){var strategy,i,len;for(i=0,len=this.strategies.length;i<len;i++){strategy=this.strategies[i];if(strategy.autoActivate){strategy.deactivate();}}}},onMapResize:function(){OpenLayers.Layer.prototype.onMapResize.apply(this,arguments);this.renderer.setSize(this.map.getSize());},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);var coordSysUnchanged=true;if(!dragging){this.renderer.root.style.visibility="hidden";this.div.style.left=-parseInt(this.map.layerContainerDiv.style.left)+"px";this.div.style.top=-parseInt(this.map.layerContainerDiv.style.top)+"px";var extent=this.map.getExtent();coordSysUnchanged=this.renderer.setExtent(extent,zoomChanged);this.renderer.root.style.visibility="visible";if(navigator.userAgent.toLowerCase().indexOf("gecko")!=-1){this.div.scrollLeft=this.div.scrollLeft;}
if(!zoomChanged&&coordSysUnchanged){for(var i in this.unrenderedFeatures){var feature=this.unrenderedFeatures[i];this.drawFeature(feature);}}}
if(!this.drawn||zoomChanged||!coordSysUnchanged){this.drawn=true;var feature;for(var i=0,len=this.features.length;i<len;i++){this.renderer.locked=(i!==(len-1));feature=this.features[i];this.drawFeature(feature);}}},display:function(display){OpenLayers.Layer.prototype.display.apply(this,arguments);var currentDisplay=this.div.style.display;if(currentDisplay!=this.renderer.root.style.display){this.renderer.root.style.display=currentDisplay;}},addFeatures:function(features,options){if(!(features instanceof Array)){features=[features];}
var notify=!options||!options.silent;if(notify){var event={features:features};var ret=this.events.triggerEvent("beforefeaturesadded",event);if(ret===false){return;}
features=event.features;}
var featuresAdded=[];for(var i=0,len=features.length;i<len;i++){if(i!=(features.length-1)){this.renderer.locked=true;}else{this.renderer.locked=false;}
var feature=features[i];if(this.geometryType&&!(feature.geometry instanceof this.geometryType)){var throwStr=OpenLayers.i18n('componentShouldBe',{'geomType':this.geometryType.prototype.CLASS_NAME});throw throwStr;}
feature.layer=this;if(!feature.style&&this.style){feature.style=OpenLayers.Util.extend({},this.style);}
if(notify){if(this.events.triggerEvent("beforefeatureadded",{feature:feature})===false){continue;};this.preFeatureInsert(feature);}
featuresAdded.push(feature);this.features.push(feature);this.drawFeature(feature);if(notify){this.events.triggerEvent("featureadded",{feature:feature});this.onFeatureInsert(feature);}}
if(notify){this.events.triggerEvent("featuresadded",{features:featuresAdded});}},removeFeatures:function(features,options){if(!features||features.length===0){return;}
if(features===this.features){return this.removeAllFeatures(options);}
if(!(features instanceof Array)){features=[features];}
if(features===this.selectedFeatures){features=features.slice();}
var notify=!options||!options.silent;if(notify){this.events.triggerEvent("beforefeaturesremoved",{features:features});}
for(var i=features.length-1;i>=0;i--){if(i!=0&&features[i-1].geometry){this.renderer.locked=true;}else{this.renderer.locked=false;}
var feature=features[i];delete this.unrenderedFeatures[feature.id];if(notify){this.events.triggerEvent("beforefeatureremoved",{feature:feature});}
this.features=OpenLayers.Util.removeItem(this.features,feature);feature.layer=null;if(feature.geometry){this.renderer.eraseFeatures(feature);}
if(OpenLayers.Util.indexOf(this.selectedFeatures,feature)!=-1){OpenLayers.Util.removeItem(this.selectedFeatures,feature);}
if(notify){this.events.triggerEvent("featureremoved",{feature:feature});}}
if(notify){this.events.triggerEvent("featuresremoved",{features:features});}},removeAllFeatures:function(options){var notify=!options||!options.silent;var features=this.features;if(notify){this.events.triggerEvent("beforefeaturesremoved",{features:features});}
var feature;for(var i=features.length-1;i>=0;i--){feature=features[i];if(notify){this.events.triggerEvent("beforefeatureremoved",{feature:feature});}
feature.layer=null;if(notify){this.events.triggerEvent("featureremoved",{feature:feature});}}
this.renderer.clear();this.features=[];this.unrenderedFeatures={};this.selectedFeatures=[];if(notify){this.events.triggerEvent("featuresremoved",{features:features});}},destroyFeatures:function(features,options){var all=(features==undefined);if(all){features=this.features;}
if(features){this.removeFeatures(features,options);for(var i=features.length-1;i>=0;i--){features[i].destroy();}}},drawFeature:function(feature,style){if(!this.drawn){return}
if(typeof style!="object"){if(!style&&feature.state===OpenLayers.State.DELETE){style="delete";}
var renderIntent=style||feature.renderIntent;style=feature.style||this.style;if(!style){style=this.styleMap.createSymbolizer(feature,renderIntent);}}
if(!this.renderer.drawFeature(feature,style)){this.unrenderedFeatures[feature.id]=feature;}else{delete this.unrenderedFeatures[feature.id];};},eraseFeatures:function(features){this.renderer.eraseFeatures(features);},getFeatureFromEvent:function(evt){if(!this.renderer){OpenLayers.Console.error(OpenLayers.i18n("getFeatureError"));return null;}
var featureId=this.renderer.getFeatureIdFromEvent(evt);return this.getFeatureById(featureId);},getFeatureBy:function(property,value){var feature=null;for(var i=0,len=this.features.length;i<len;++i){if(this.features[i][property]==value){feature=this.features[i];break;}}
return feature;},getFeatureById:function(featureId){return this.getFeatureBy('id',featureId);},getFeatureByFid:function(featureFid){return this.getFeatureBy('fid',featureFid);},onFeatureInsert:function(feature){},preFeatureInsert:function(feature){},getDataExtent:function(){var maxExtent=null;var features=this.features;if(features&&(features.length>0)){maxExtent=new OpenLayers.Bounds();var geometry=null;for(var i=0,len=features.length;i<len;i++){geometry=features[i].geometry;if(geometry){maxExtent.extend(geometry.getBounds());}}}
return maxExtent;},CLASS_NAME:"OpenLayers.Layer.Vector"});OpenLayers.Layer.WMS.Post=OpenLayers.Class(OpenLayers.Layer.WMS,{tileClass:null,unsupportedBrowsers:["mozilla","firefox","opera"],SUPPORTED_TRANSITIONS:[],initialize:function(name,url,params,options){var newArguments=[];newArguments.push(name,url,params,options);OpenLayers.Layer.WMS.prototype.initialize.apply(this,newArguments);this.tileClass=OpenLayers.Util.indexOf(this.unsupportedBrowsers,OpenLayers.Util.getBrowserName())!=-1?OpenLayers.Tile.Image:OpenLayers.Tile.Image.IFrame;},addTile:function(bounds,position){return new this.tileClass(this,position,bounds,null,this.tileSize);},CLASS_NAME:'OpenLayers.Layer.WMS.Post'});OpenLayers.Layer.WMS.Untiled=OpenLayers.Class(OpenLayers.Layer.WMS,{singleTile:true,initialize:function(name,url,params,options){OpenLayers.Layer.WMS.prototype.initialize.apply(this,arguments);var msg="The OpenLayers.Layer.WMS.Untiled class is deprecated and "+"will be removed in 3.0. Instead, you should use the "+"normal OpenLayers.Layer.WMS class, passing it the option "+"'singleTile' as true.";OpenLayers.Console.warn(msg);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.WMS.Untiled(this.name,this.url,this.params,this.getOptions());}
obj=OpenLayers.Layer.WMS.prototype.clone.apply(this,[obj]);return obj;},CLASS_NAME:"OpenLayers.Layer.WMS.Untiled"});OpenLayers.Strategy.Filter=OpenLayers.Class(OpenLayers.Strategy,{filter:null,cache:null,caching:false,initialize:function(options){OpenLayers.Strategy.prototype.initialize.apply(this,[options]);if(!this.filter||!(this.filter instanceof OpenLayers.Filter)){throw new Error("Filter strategy must be constructed with a filter");}},activate:function(){var activated=OpenLayers.Strategy.prototype.activate.apply(this,arguments);if(activated){this.cache=[];this.layer.events.on({"beforefeaturesadded":this.handleAdd,"beforefeaturesremoved":this.handleRemove,scope:this});}
return activated;},deactivate:function(){this.cache=null;if(this.layer&&this.layer.events){this.layer.events.un({"beforefeaturesadded":this.handleAdd,"beforefeaturesremoved":this.handleRemove,scope:this});}
return OpenLayers.Strategy.prototype.deactivate.apply(this,arguments);},handleAdd:function(event){if(!this.caching){var features=event.features;event.features=[];var feature;for(var i=0,ii=features.length;i<ii;++i){feature=features[i];if(this.filter.evaluate(feature)){event.features.push(feature);}else{this.cache.push(feature);}}}},handleRemove:function(event){if(!this.caching){this.cache=[];}},setFilter:function(filter){this.filter=filter;var previousCache=this.cache;this.cache=[];this.handleAdd({features:this.layer.features});if(this.cache.length>0){this.caching=true;this.layer.removeFeatures(this.cache.slice(),{silent:true});this.caching=false;}
if(previousCache.length>0){var event={features:previousCache};this.handleAdd(event);this.caching=true;this.layer.addFeatures(event.features,{silent:true});this.caching=false;}},CLASS_NAME:"OpenLayers.Strategy.Filter"});OpenLayers.Style2=OpenLayers.Class({id:null,name:null,title:null,description:null,layerName:null,isDefault:false,rules:null,initialize:function(config){OpenLayers.Util.extend(this,config);this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");},destroy:function(){for(var i=0,len=this.rules.length;i<len;i++){this.rules[i].destroy();}
delete this.rules;},clone:function(){var config=OpenLayers.Util.extend({},this);if(this.rules){config.rules=[];for(var i=0,len=this.rules.length;i<len;++i){config.rules.push(this.rules[i].clone());}}
return new OpenLayers.Style2(config);},CLASS_NAME:"OpenLayers.Style2"});OpenLayers.Control.GetFeature=OpenLayers.Class(OpenLayers.Control,{protocol:null,multipleKey:null,toggleKey:null,modifiers:null,multiple:false,click:true,single:true,clickout:true,toggle:false,clickTolerance:5,hover:false,box:false,maxFeatures:10,features:null,hoverFeature:null,handlerOptions:null,handlers:null,hoverResponse:null,filterType:OpenLayers.Filter.Spatial.BBOX,EVENT_TYPES:["featureselected","featuresselected","featureunselected","clickout","beforefeatureselected","beforefeaturesselected","hoverfeature","outfeature"],initialize:function(options){this.EVENT_TYPES=OpenLayers.Control.GetFeature.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES);options.handlerOptions=options.handlerOptions||{};OpenLayers.Control.prototype.initialize.apply(this,[options]);this.features={};this.handlers={};if(this.click){this.handlers.click=new OpenLayers.Handler.Click(this,{click:this.selectClick},this.handlerOptions.click||{});}
if(this.box){this.handlers.box=new OpenLayers.Handler.Box(this,{done:this.selectBox},OpenLayers.Util.extend(this.handlerOptions.box,{boxDivClassName:"olHandlerBoxSelectFeature"}));}
if(this.hover){this.handlers.hover=new OpenLayers.Handler.Hover(this,{'move':this.cancelHover,'pause':this.selectHover},OpenLayers.Util.extend(this.handlerOptions.hover,{'delay':250}));}},activate:function(){if(!this.active){for(var i in this.handlers){this.handlers[i].activate();}}
return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){if(this.active){for(var i in this.handlers){this.handlers[i].deactivate();}}
return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},selectClick:function(evt){var bounds=this.pixelToBounds(evt.xy);this.setModifiers(evt);this.request(bounds,{single:this.single});},selectBox:function(position){var bounds;if(position instanceof OpenLayers.Bounds){var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.left,position.bottom));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.right,position.top));bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);}else{if(this.click){return;}
bounds=this.pixelToBounds(position);}
this.setModifiers(this.handlers.box.dragHandler.evt);this.request(bounds);},selectHover:function(evt){var bounds=this.pixelToBounds(evt.xy);this.request(bounds,{single:true,hover:true});},cancelHover:function(){if(this.hoverResponse){this.protocol.abort(this.hoverResponse);this.hoverResponse=null;OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait");}},request:function(bounds,options){options=options||{};var filter=new OpenLayers.Filter.Spatial({type:this.filterType,value:bounds});OpenLayers.Element.addClass(this.map.viewPortDiv,"olCursorWait");var response=this.protocol.read({maxFeatures:options.single==true?this.maxFeatures:undefined,filter:filter,callback:function(result){if(result.success()){if(result.features.length){if(options.single==true){this.selectBestFeature(result.features,bounds.getCenterLonLat(),options);}else{this.select(result.features);}}else if(options.hover){this.hoverSelect();}else{this.events.triggerEvent("clickout");if(this.clickout){this.unselectAll();}}}
OpenLayers.Element.removeClass(this.map.viewPortDiv,"olCursorWait");},scope:this});if(options.hover==true){this.hoverResponse=response;}},selectBestFeature:function(features,clickPosition,options){options=options||{};if(features.length){var point=new OpenLayers.Geometry.Point(clickPosition.lon,clickPosition.lat);var feature,resultFeature,dist;var minDist=Number.MAX_VALUE;for(var i=0;i<features.length;++i){feature=features[i];if(feature.geometry){dist=point.distanceTo(feature.geometry,{edge:false});if(dist<minDist){minDist=dist;resultFeature=feature;if(minDist==0){break;}}}}
if(options.hover==true){this.hoverSelect(resultFeature);}else{this.select(resultFeature||features);}}},setModifiers:function(evt){this.modifiers={multiple:this.multiple||(this.multipleKey&&evt[this.multipleKey]),toggle:this.toggle||(this.toggleKey&&evt[this.toggleKey])};},select:function(features){if(!this.modifiers.multiple&&!this.modifiers.toggle){this.unselectAll();}
if(!(features instanceof Array)){features=[features];}
var cont=this.events.triggerEvent("beforefeaturesselected",{features:features});if(cont!==false){var selectedFeatures=[];var feature;for(var i=0,len=features.length;i<len;++i){feature=features[i];if(this.features[feature.fid||feature.id]){if(this.modifiers.toggle){this.unselect(this.features[feature.fid||feature.id]);}}else{cont=this.events.triggerEvent("beforefeatureselected",{feature:feature});if(cont!==false){this.features[feature.fid||feature.id]=feature;selectedFeatures.push(feature);this.events.triggerEvent("featureselected",{feature:feature});}}}
this.events.triggerEvent("featuresselected",{features:selectedFeatures});}},hoverSelect:function(feature){var fid=feature?feature.fid||feature.id:null;var hfid=this.hoverFeature?this.hoverFeature.fid||this.hoverFeature.id:null;if(hfid&&hfid!=fid){this.events.triggerEvent("outfeature",{feature:this.hoverFeature});this.hoverFeature=null;}
if(fid&&fid!=hfid){this.events.triggerEvent("hoverfeature",{feature:feature});this.hoverFeature=feature;}},unselect:function(feature){delete this.features[feature.fid||feature.id];this.events.triggerEvent("featureunselected",{feature:feature});},unselectAll:function(){for(var fid in this.features){this.unselect(this.features[fid]);}},setMap:function(map){for(var i in this.handlers){this.handlers[i].setMap(map);}
OpenLayers.Control.prototype.setMap.apply(this,arguments);},pixelToBounds:function(pixel){var llPx=pixel.add(-this.clickTolerance/2,this.clickTolerance/2);var urPx=pixel.add(this.clickTolerance/2,-this.clickTolerance/2);var ll=this.map.getLonLatFromPixel(llPx);var ur=this.map.getLonLatFromPixel(urPx);return new OpenLayers.Bounds(ll.lon,ll.lat,ur.lon,ur.lat);},CLASS_NAME:"OpenLayers.Control.GetFeature"});OpenLayers.Control.Snapping=OpenLayers.Class(OpenLayers.Control,{EVENT_TYPES:["beforesnap","snap","unsnap"],DEFAULTS:{tolerance:10,node:true,edge:true,vertex:true},greedy:true,precedence:["node","vertex","edge"],resolution:null,geoToleranceCache:null,layer:null,feature:null,point:null,initialize:function(options){Array.prototype.push.apply(this.EVENT_TYPES,OpenLayers.Control.prototype.EVENT_TYPES);OpenLayers.Control.prototype.initialize.apply(this,[options]);this.options=options||{};if(this.options.layer){this.setLayer(this.options.layer);}
var defaults=OpenLayers.Util.extend({},this.options.defaults);this.defaults=OpenLayers.Util.applyDefaults(defaults,this.DEFAULTS);this.setTargets(this.options.targets);if(this.targets.length===0&&this.layer){this.addTargetLayer(this.layer);}
this.geoToleranceCache={};},setLayer:function(layer){if(this.active){this.deactivate();this.layer=layer;this.activate();}else{this.layer=layer;}},setTargets:function(targets){this.targets=[];if(targets&&targets.length){var target;for(var i=0,len=targets.length;i<len;++i){target=targets[i];if(target instanceof OpenLayers.Layer.Vector){this.addTargetLayer(target);}else{this.addTarget(target);}}}},addTargetLayer:function(layer){this.addTarget({layer:layer});},addTarget:function(target){target=OpenLayers.Util.applyDefaults(target,this.defaults);target.nodeTolerance=target.nodeTolerance||target.tolerance;target.vertexTolerance=target.vertexTolerance||target.tolerance;target.edgeTolerance=target.edgeTolerance||target.tolerance;this.targets.push(target);},removeTargetLayer:function(layer){var target;for(var i=this.targets.length-1;i>=0;--i){target=this.targets[i];if(target.layer===layer){this.removeTarget(target);}}},removeTarget:function(target){return OpenLayers.Util.removeItem(this.targets,target);},activate:function(){var activated=OpenLayers.Control.prototype.activate.call(this);if(activated){if(this.layer&&this.layer.events){this.layer.events.on({sketchstarted:this.onSketchModified,sketchmodified:this.onSketchModified,vertexmodified:this.onVertexModified,scope:this});}}
return activated;},deactivate:function(){var deactivated=OpenLayers.Control.prototype.deactivate.call(this);if(deactivated){if(this.layer&&this.layer.events){this.layer.events.un({sketchstarted:this.onSketchModified,sketchmodified:this.onSketchModified,vertexmodified:this.onVertexModified,scope:this});}}
this.feature=null;this.point=null;return deactivated;},onSketchModified:function(event){this.feature=event.feature;this.considerSnapping(event.vertex,event.vertex);},onVertexModified:function(event){this.feature=event.feature;var loc=this.layer.map.getLonLatFromViewPortPx(event.pixel);this.considerSnapping(event.vertex,new OpenLayers.Geometry.Point(loc.lon,loc.lat));},considerSnapping:function(point,loc){var best={rank:Number.POSITIVE_INFINITY,dist:Number.POSITIVE_INFINITY,x:null,y:null};var snapped=false;var result,target;for(var i=0,len=this.targets.length;i<len;++i){target=this.targets[i];result=this.testTarget(target,loc);if(result){if(this.greedy){best=result;best.target=target;snapped=true;break;}else{if((result.rank<best.rank)||(result.rank===best.rank&&result.dist<best.dist)){best=result;best.target=target;snapped=true;}}}}
if(snapped){var proceed=this.events.triggerEvent("beforesnap",{point:point,x:best.x,y:best.y,distance:best.dist,layer:best.target.layer,snapType:this.precedence[best.rank]});if(proceed!==false){point.x=best.x;point.y=best.y;this.point=point;this.events.triggerEvent("snap",{point:point,snapType:this.precedence[best.rank],layer:best.target.layer,distance:best.dist});}else{snapped=false;}}
if(this.point&&!snapped){point.x=loc.x;point.y=loc.y;this.point=null;this.events.triggerEvent("unsnap",{point:point});}},testTarget:function(target,loc){var tolerance={node:this.getGeoTolerance(target.nodeTolerance),vertex:this.getGeoTolerance(target.vertexTolerance),edge:this.getGeoTolerance(target.edgeTolerance)};var maxTolerance=Math.max(tolerance.node,tolerance.vertex,tolerance.edge);var result={rank:Number.POSITIVE_INFINITY,dist:Number.POSITIVE_INFINITY};var eligible=false;var features=target.layer.features;var feature,type,vertices,vertex,closest,dist,found;var numTypes=this.precedence.length;var ll=new OpenLayers.LonLat(loc.x,loc.y);for(var i=0,len=features.length;i<len;++i){feature=features[i];if(feature!==this.feature&&!feature._sketch&&feature.state!==OpenLayers.State.DELETE&&(!target.filter||target.filter.evaluate(feature.attributes))){if(feature.atPoint(ll,maxTolerance,maxTolerance)){for(var j=0,stop=Math.min(result.rank+1,numTypes);j<stop;++j){type=this.precedence[j];if(target[type]){if(type==="edge"){closest=feature.geometry.distanceTo(loc,{details:true});dist=closest.distance;if(dist<=tolerance[type]&&dist<result.dist){result={rank:j,dist:dist,x:closest.x0,y:closest.y0};eligible=true;break;}}else{vertices=feature.geometry.getVertices(type==="node");found=false;for(var k=0,klen=vertices.length;k<klen;++k){vertex=vertices[k];dist=vertex.distanceTo(loc);if(dist<=tolerance[type]&&(j<result.rank||(j===result.rank&&dist<result.dist))){result={rank:j,dist:dist,x:vertex.x,y:vertex.y};eligible=true;found=true;}}
if(found){break;}}}}}}}
return eligible?result:null;},getGeoTolerance:function(tolerance){var resolution=this.layer.map.getResolution();if(resolution!==this.resolution){this.resolution=resolution;this.geoToleranceCache={};}
var geoTolerance=this.geoToleranceCache[tolerance];if(geoTolerance===undefined){geoTolerance=tolerance*resolution;this.geoToleranceCache[tolerance]=geoTolerance;}
return geoTolerance;},destroy:function(){if(this.active){this.deactivate();}
delete this.layer;delete this.targets;OpenLayers.Control.prototype.destroy.call(this);},CLASS_NAME:"OpenLayers.Control.Snapping"});OpenLayers.Format.Filter=OpenLayers.Class(OpenLayers.Format.XML,{defaultVersion:"1.0.0",version:null,parser:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},write:function(filter,options){var version=(options&&options.version)||this.version||this.defaultVersion;if(!this.parser||this.parser.VERSION!=version){var format=OpenLayers.Format.Filter["v"+version.replace(/\./g,"_")];if(!format){throw"Can't find a Filter parser for version "+
version;}
this.parser=new format(this.options);}
return this.parser.write(filter);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var version=this.version;if(!version){version=this.defaultVersion;}
if(!this.parser||this.parser.VERSION!=version){var format=OpenLayers.Format.Filter["v"+version.replace(/\./g,"_")];if(!format){throw"Can't find a Filter parser for version "+
version;}
this.parser=new format(this.options);}
var filter=this.parser.read(data);return filter;},CLASS_NAME:"OpenLayers.Format.Filter"});OpenLayers.Format.SLD=OpenLayers.Class(OpenLayers.Format.XML,{defaultVersion:"1.0.0",version:null,namedLayersAsArray:false,parser:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},write:function(sld,options){var version=(options&&options.version)||this.version||this.defaultVersion;if(!this.parser||this.parser.VERSION!=version){var format=OpenLayers.Format.SLD["v"+version.replace(/\./g,"_")];if(!format){throw"Can't find a SLD parser for version "+
version;}
this.parser=new format(this.options);}
var root=this.parser.write(sld);return OpenLayers.Format.XML.prototype.write.apply(this,[root]);},read:function(data,options){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var root=data.documentElement;var version=this.version;if(!version){version=root.getAttribute("version");if(!version){version=this.defaultVersion;}}
if(!this.parser||this.parser.VERSION!=version){var format=OpenLayers.Format.SLD["v"+version.replace(/\./g,"_")];if(!format){throw"Can't find a SLD parser for version "+
version;}
this.parser=new format(this.options);}
var sld=this.parser.read(data,options);return sld;},CLASS_NAME:"OpenLayers.Format.SLD"});OpenLayers.Format.Text=OpenLayers.Class(OpenLayers.Format,{defaultStyle:null,extractStyles:true,initialize:function(options){options=options||{};if(options.extractStyles!==false){options.defaultStyle={'externalGraphic':OpenLayers.Util.getImagesLocation()+"marker.png",'graphicWidth':21,'graphicHeight':25,'graphicXOffset':-10.5,'graphicYOffset':-12.5};}
OpenLayers.Format.prototype.initialize.apply(this,[options]);},read:function(text){var lines=text.split('\n');var columns;var features=[];for(var lcv=0;lcv<(lines.length-1);lcv++){var currLine=lines[lcv].replace(/^\s*/,'').replace(/\s*$/,'');if(currLine.charAt(0)!='#'){if(!columns){columns=currLine.split('\t');}else{var vals=currLine.split('\t');var geometry=new OpenLayers.Geometry.Point(0,0);var attributes={};var style=this.defaultStyle?OpenLayers.Util.applyDefaults({},this.defaultStyle):null;var icon,iconSize,iconOffset,overflow;var set=false;for(var valIndex=0;valIndex<vals.length;valIndex++){if(vals[valIndex]){if(columns[valIndex]=='point'){var coords=vals[valIndex].split(',');geometry.y=parseFloat(coords[0]);geometry.x=parseFloat(coords[1]);set=true;}else if(columns[valIndex]=='lat'){geometry.y=parseFloat(vals[valIndex]);set=true;}else if(columns[valIndex]=='lon'){geometry.x=parseFloat(vals[valIndex]);set=true;}else if(columns[valIndex]=='title')
attributes['title']=vals[valIndex];else if(columns[valIndex]=='image'||columns[valIndex]=='icon'&&style){style['externalGraphic']=vals[valIndex];}else if(columns[valIndex]=='iconSize'&&style){var size=vals[valIndex].split(',');style['graphicWidth']=parseFloat(size[0]);style['graphicHeight']=parseFloat(size[1]);}else if(columns[valIndex]=='iconOffset'&&style){var offset=vals[valIndex].split(',');style['graphicXOffset']=parseFloat(offset[0]);style['graphicYOffset']=parseFloat(offset[1]);}else if(columns[valIndex]=='description'){attributes['description']=vals[valIndex];}else if(columns[valIndex]=='overflow'){attributes['overflow']=vals[valIndex];}else{attributes[columns[valIndex]]=vals[valIndex];}}}
if(set){if(this.internalProjection&&this.externalProjection){geometry.transform(this.externalProjection,this.internalProjection);}
var feature=new OpenLayers.Feature.Vector(geometry,attributes,style);features.push(feature);}}}}
return features;},CLASS_NAME:"OpenLayers.Format.Text"});OpenLayers.Geometry.MultiPoint=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.Point"],initialize:function(components){OpenLayers.Geometry.Collection.prototype.initialize.apply(this,arguments);},addPoint:function(point,index){this.addComponent(point,index);},removePoint:function(point){this.removeComponent(point);},CLASS_NAME:"OpenLayers.Geometry.MultiPoint"});OpenLayers.Handler.Point=OpenLayers.Class(OpenLayers.Handler,{point:null,layer:null,multi:false,drawing:false,mouseDown:false,lastDown:null,lastUp:null,persist:false,layerOptions:null,initialize:function(control,callbacks,options){if(!(options&&options.layerOptions&&options.layerOptions.styleMap)){this.style=OpenLayers.Util.extend(OpenLayers.Feature.Vector.style['default'],{});}
OpenLayers.Handler.prototype.initialize.apply(this,arguments);},activate:function(){if(!OpenLayers.Handler.prototype.activate.apply(this,arguments)){return false;}
var options=OpenLayers.Util.extend({displayInLayerSwitcher:false,calculateInRange:OpenLayers.Function.True},this.layerOptions);this.layer=new OpenLayers.Layer.Vector(this.CLASS_NAME,options);this.map.addLayer(this.layer);return true;},createFeature:function(pixel){var lonlat=this.map.getLonLatFromPixel(pixel);this.point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));this.callback("create",[this.point.geometry,this.point]);this.point.geometry.clearBounds();this.layer.addFeatures([this.point],{silent:true});},deactivate:function(){if(!OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){return false;}
if(this.drawing){this.cancel();}
this.destroyFeature();if(this.layer.map!=null){this.layer.destroy(false);}
this.layer=null;return true;},destroyFeature:function(){if(this.layer){this.layer.destroyFeatures();}
this.point=null;},finalize:function(cancel){var key=cancel?"cancel":"done";this.drawing=false;this.mouseDown=false;this.lastDown=null;this.lastUp=null;this.callback(key,[this.geometryClone()]);if(cancel||!this.persist){this.destroyFeature();}},cancel:function(){this.finalize(true);},click:function(evt){OpenLayers.Event.stop(evt);return false;},dblclick:function(evt){OpenLayers.Event.stop(evt);return false;},modifyFeature:function(pixel){var lonlat=this.map.getLonLatFromPixel(pixel);this.point.geometry.x=lonlat.lon;this.point.geometry.y=lonlat.lat;this.callback("modify",[this.point.geometry,this.point]);this.point.geometry.clearBounds();this.drawFeature();},drawFeature:function(){this.layer.drawFeature(this.point,this.style);},getGeometry:function(){var geometry=this.point&&this.point.geometry;if(geometry&&this.multi){geometry=new OpenLayers.Geometry.MultiPoint([geometry]);}
return geometry;},geometryClone:function(){var geom=this.getGeometry();return geom&&geom.clone();},mousedown:function(evt){if(!this.checkModifiers(evt)){return true;}
if(this.lastDown&&this.lastDown.equals(evt.xy)){return true;}
this.drawing=true;if(this.lastDown==null){if(this.persist){this.destroyFeature();}
this.createFeature(evt.xy);}else{this.modifyFeature(evt.xy);}
this.lastDown=evt.xy;return false;},mousemove:function(evt){if(this.drawing){this.modifyFeature(evt.xy);}
return true;},mouseup:function(evt){if(this.drawing){this.finalize();return false;}else{return true;}},CLASS_NAME:"OpenLayers.Handler.Point"});OpenLayers.Layer.GML=OpenLayers.Class(OpenLayers.Layer.Vector,{loaded:false,format:null,formatOptions:null,initialize:function(name,url,options){var newArguments=[];newArguments.push(name,options);OpenLayers.Layer.Vector.prototype.initialize.apply(this,newArguments);this.url=url;},setVisibility:function(visibility,noEvent){OpenLayers.Layer.Vector.prototype.setVisibility.apply(this,arguments);if(this.visibility&&!this.loaded){this.loadGML();}},moveTo:function(bounds,zoomChanged,minor){OpenLayers.Layer.Vector.prototype.moveTo.apply(this,arguments);if(this.visibility&&!this.loaded){this.loadGML();}},loadGML:function(){if(!this.loaded){this.events.triggerEvent("loadstart");OpenLayers.Request.GET({url:this.url,success:this.requestSuccess,failure:this.requestFailure,scope:this});this.loaded=true;}},setUrl:function(url){this.url=url;this.destroyFeatures();this.loaded=false;this.loadGML();},requestSuccess:function(request){var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
var options={};OpenLayers.Util.extend(options,this.formatOptions);if(this.map&&!this.projection.equals(this.map.getProjectionObject())){options.externalProjection=this.projection;options.internalProjection=this.map.getProjectionObject();}
var gml=this.format?new this.format(options):new OpenLayers.Format.GML(options);this.addFeatures(gml.read(doc));this.events.triggerEvent("loadend");},requestFailure:function(request){OpenLayers.Console.userError(OpenLayers.i18n("errorLoadingGML",{'url':this.url}));this.events.triggerEvent("loadend");},CLASS_NAME:"OpenLayers.Layer.GML"});OpenLayers.Layer.PointTrack=OpenLayers.Class(OpenLayers.Layer.Vector,{dataFrom:null,initialize:function(name,options){OpenLayers.Layer.Vector.prototype.initialize.apply(this,arguments);},addNodes:function(pointFeatures){if(pointFeatures.length<2){OpenLayers.Console.error("At least two point features have to be added to create"+"a line from");return;}
var lines=new Array(pointFeatures.length-1);var pointFeature,startPoint,endPoint;for(var i=0,len=pointFeatures.length;i<len;i++){pointFeature=pointFeatures[i];endPoint=pointFeature.geometry;if(!endPoint){var lonlat=pointFeature.lonlat;endPoint=new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat);}else if(endPoint.CLASS_NAME!="OpenLayers.Geometry.Point"){OpenLayers.Console.error("Only features with point geometries are supported.");return;}
if(i>0){var attributes=(this.dataFrom!=null)?(pointFeatures[i+this.dataFrom].data||pointFeatures[i+this.dataFrom].attributes):null;var line=new OpenLayers.Geometry.LineString([startPoint,endPoint]);lines[i-1]=new OpenLayers.Feature.Vector(line,attributes);}
startPoint=endPoint;}
this.addFeatures(lines);},CLASS_NAME:"OpenLayers.Layer.PointTrack"});OpenLayers.Layer.PointTrack.dataFrom={'SOURCE_NODE':-1,'TARGET_NODE':0};OpenLayers.Layer.Vector.RootContainer=OpenLayers.Class(OpenLayers.Layer.Vector,{displayInLayerSwitcher:false,layers:null,initialize:function(name,options){OpenLayers.Layer.Vector.prototype.initialize.apply(this,arguments);},display:function(){},getFeatureFromEvent:function(evt){var layers=this.layers;var feature;for(var i=0;i<layers.length;i++){feature=layers[i].getFeatureFromEvent(evt);if(feature){return feature;}}},setMap:function(map){OpenLayers.Layer.Vector.prototype.setMap.apply(this,arguments);this.collectRoots();map.events.register("changelayer",this,this.handleChangeLayer);},removeMap:function(map){map.events.unregister("changelayer",this,this.handleChangeLayer);this.resetRoots();OpenLayers.Layer.Vector.prototype.removeMap.apply(this,arguments);},collectRoots:function(){var layer;for(var i=0;i<this.map.layers.length;++i){layer=this.map.layers[i];if(OpenLayers.Util.indexOf(this.layers,layer)!=-1){layer.renderer.moveRoot(this.renderer);}}},resetRoots:function(){var layer;for(var i=0;i<this.layers.length;++i){layer=this.layers[i];if(this.renderer&&layer.renderer.getRenderLayerId()==this.id){this.renderer.moveRoot(layer.renderer);}}},handleChangeLayer:function(evt){var layer=evt.layer;if(evt.property=="order"&&OpenLayers.Util.indexOf(this.layers,layer)!=-1){this.resetRoots();this.collectRoots();}},CLASS_NAME:"OpenLayers.Layer.Vector.RootContainer"});OpenLayers.Layer.WFS=OpenLayers.Class(OpenLayers.Layer.Vector,OpenLayers.Layer.Markers,{isBaseLayer:false,tile:null,ratio:2,DEFAULT_PARAMS:{service:"WFS",version:"1.0.0",request:"GetFeature"},featureClass:null,format:null,formatObject:null,formatOptions:null,vectorMode:true,encodeBBOX:false,extractAttributes:false,initialize:function(name,url,params,options){if(options==undefined){options={};}
if(options.featureClass||!OpenLayers.Layer.Vector||!OpenLayers.Feature.Vector){this.vectorMode=false;}
params=OpenLayers.Util.upperCaseObject(params);OpenLayers.Util.extend(options,{'reportError':false});var newArguments=[];newArguments.push(name,options);OpenLayers.Layer.Vector.prototype.initialize.apply(this,newArguments);if(!this.renderer||!this.vectorMode){this.vectorMode=false;if(!options.featureClass){options.featureClass=OpenLayers.Feature.WFS;}
OpenLayers.Layer.Markers.prototype.initialize.apply(this,newArguments);}
if(this.params&&this.params.typename&&!this.options.typename){this.options.typename=this.params.typename;}
if(!this.options.geometry_column){this.options.geometry_column="the_geom";}
this.params=OpenLayers.Util.applyDefaults(params,OpenLayers.Util.upperCaseObject(this.DEFAULT_PARAMS));this.url=url;},destroy:function(){if(this.vectorMode){OpenLayers.Layer.Vector.prototype.destroy.apply(this,arguments);}else{OpenLayers.Layer.Markers.prototype.destroy.apply(this,arguments);}
if(this.tile){this.tile.destroy();}
this.tile=null;this.ratio=null;this.featureClass=null;this.format=null;if(this.formatObject&&this.formatObject.destroy){this.formatObject.destroy();}
this.formatObject=null;this.formatOptions=null;this.vectorMode=null;this.encodeBBOX=null;this.extractAttributes=null;},setMap:function(map){if(this.vectorMode){OpenLayers.Layer.Vector.prototype.setMap.apply(this,arguments);var options={'extractAttributes':this.extractAttributes};OpenLayers.Util.extend(options,this.formatOptions);if(this.map&&!this.projection.equals(this.map.getProjectionObject())){options.externalProjection=this.projection;options.internalProjection=this.map.getProjectionObject();}
this.formatObject=this.format?new this.format(options):new OpenLayers.Format.GML(options);}else{OpenLayers.Layer.Markers.prototype.setMap.apply(this,arguments);}},moveTo:function(bounds,zoomChanged,dragging){if(this.vectorMode){OpenLayers.Layer.Vector.prototype.moveTo.apply(this,arguments);}else{OpenLayers.Layer.Markers.prototype.moveTo.apply(this,arguments);}
if(dragging){return false;}
if(zoomChanged){if(this.vectorMode){this.renderer.clear();}}
if(this.options.minZoomLevel){OpenLayers.Console.warn(OpenLayers.i18n('minZoomLevelError'));if(this.map.getZoom()<this.options.minZoomLevel){return null;}}
if(bounds==null){bounds=this.map.getExtent();}
var firstRendering=(this.tile==null);var outOfBounds=(!firstRendering&&!this.tile.bounds.containsBounds(bounds));if(zoomChanged||firstRendering||(!dragging&&outOfBounds)){var center=bounds.getCenterLonLat();var tileWidth=bounds.getWidth()*this.ratio;var tileHeight=bounds.getHeight()*this.ratio;var tileBounds=new OpenLayers.Bounds(center.lon-(tileWidth/2),center.lat-(tileHeight/2),center.lon+(tileWidth/2),center.lat+(tileHeight/2));var tileSize=this.map.getSize();tileSize.w=tileSize.w*this.ratio;tileSize.h=tileSize.h*this.ratio;var ul=new OpenLayers.LonLat(tileBounds.left,tileBounds.top);var pos=this.map.getLayerPxFromLonLat(ul);var url=this.getFullRequestString();var params=null;var filter=this.params.filter||this.params.FILTER;if(filter){params={FILTER:filter};}
else{params={BBOX:this.encodeBBOX?tileBounds.toBBOX():tileBounds.toArray()};}
if(this.map&&!this.projection.equals(this.map.getProjectionObject())){var projectedBounds=tileBounds.clone();projectedBounds.transform(this.map.getProjectionObject(),this.projection);if(!filter){params.BBOX=this.encodeBBOX?projectedBounds.toBBOX():projectedBounds.toArray();}}
url+="&"+OpenLayers.Util.getParameterString(params);if(!this.tile){this.tile=new OpenLayers.Tile.WFS(this,pos,tileBounds,url,tileSize);this.addTileMonitoringHooks(this.tile);this.tile.draw();}else{if(this.vectorMode){this.destroyFeatures();this.renderer.clear();}else{this.clearMarkers();}
this.removeTileMonitoringHooks(this.tile);this.tile.destroy();this.tile=null;this.tile=new OpenLayers.Tile.WFS(this,pos,tileBounds,url,tileSize);this.addTileMonitoringHooks(this.tile);this.tile.draw();}}},addTileMonitoringHooks:function(tile){tile.onLoadStart=function(){if(this==this.layer.tile){this.layer.events.triggerEvent("loadstart");}};tile.events.register("loadstart",tile,tile.onLoadStart);tile.onLoadEnd=function(){if(this==this.layer.tile){this.layer.events.triggerEvent("tileloaded");this.layer.events.triggerEvent("loadend");}};tile.events.register("loadend",tile,tile.onLoadEnd);tile.events.register("unload",tile,tile.onLoadEnd);},removeTileMonitoringHooks:function(tile){tile.unload();tile.events.un({"loadstart":tile.onLoadStart,"loadend":tile.onLoadEnd,"unload":tile.onLoadEnd,scope:tile});},onMapResize:function(){if(this.vectorMode){OpenLayers.Layer.Vector.prototype.onMapResize.apply(this,arguments);}else{OpenLayers.Layer.Markers.prototype.onMapResize.apply(this,arguments);}},display:function(){if(this.vectorMode){OpenLayers.Layer.Vector.prototype.display.apply(this,arguments);}else{OpenLayers.Layer.Markers.prototype.display.apply(this,arguments);}},mergeNewParams:function(newParams){var upperParams=OpenLayers.Util.upperCaseObject(newParams);var newArguments=[upperParams];return OpenLayers.Layer.HTTPRequest.prototype.mergeNewParams.apply(this,newArguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.WFS(this.name,this.url,this.params,this.getOptions());}
if(this.vectorMode){obj=OpenLayers.Layer.Vector.prototype.clone.apply(this,[obj]);}else{obj=OpenLayers.Layer.Markers.prototype.clone.apply(this,[obj]);}
return obj;},getFullRequestString:function(newParams,altUrl){var projectionCode=this.projection.getCode()||this.map.getProjection();this.params.SRS=(projectionCode=="none")?null:projectionCode;return OpenLayers.Layer.Grid.prototype.getFullRequestString.apply(this,arguments);},commit:function(){if(!this.writer){var options={};if(this.map&&!this.projection.equals(this.map.getProjectionObject())){options.externalProjection=this.projection;options.internalProjection=this.map.getProjectionObject();}
this.writer=new OpenLayers.Format.WFS(options,this);}
var data=this.writer.write(this.features);OpenLayers.Request.POST({url:this.url,data:data,success:this.commitSuccess,failure:this.commitFailure,scope:this});},commitSuccess:function(request){var response=request.responseText;if(response.indexOf('SUCCESS')!=-1){this.commitReport(OpenLayers.i18n("commitSuccess",{'response':response}));for(var i=0;i<this.features.length;i++){this.features[i].state=null;}}else if(response.indexOf('FAILED')!=-1||response.indexOf('Exception')!=-1){this.commitReport(OpenLayers.i18n("commitFailed",{'response':response}));}},commitFailure:function(request){},commitReport:function(string,response){OpenLayers.Console.userError(string);},refresh:function(){if(this.tile){if(this.vectorMode){this.renderer.clear();this.features.length=0;}else{this.clearMarkers();this.markers.length=0;}
this.tile.draw();}},getDataExtent:function(){var extent;if(this.vectorMode){extent=OpenLayers.Layer.Vector.prototype.getDataExtent.apply(this);}else{extent=OpenLayers.Layer.Markers.prototype.getDataExtent.apply(this);}
return extent;},setOpacity:function(opacity){if(this.vectorMode){OpenLayers.Layer.Vector.prototype.setOpacity.apply(this,[opacity]);}else{OpenLayers.Layer.Markers.prototype.setOpacity.apply(this,[opacity]);}},CLASS_NAME:"OpenLayers.Layer.WFS"});OpenLayers.Protocol.HTTP=OpenLayers.Class(OpenLayers.Protocol,{url:null,headers:null,params:null,callback:null,scope:null,readWithPOST:false,wildcarded:false,initialize:function(options){options=options||{};this.params={};this.headers={};OpenLayers.Protocol.prototype.initialize.apply(this,arguments);},destroy:function(){this.params=null;this.headers=null;OpenLayers.Protocol.prototype.destroy.apply(this);},read:function(options){OpenLayers.Protocol.prototype.read.apply(this,arguments);options=OpenLayers.Util.applyDefaults(options,this.options);options.params=OpenLayers.Util.applyDefaults(options.params,this.options.params);if(options.filter){options.params=this.filterToParams(options.filter,options.params);}
var readWithPOST=(options.readWithPOST!==undefined)?options.readWithPOST:this.readWithPOST;var resp=new OpenLayers.Protocol.Response({requestType:"read"});if(readWithPOST){resp.priv=OpenLayers.Request.POST({url:options.url,callback:this.createCallback(this.handleRead,resp,options),data:OpenLayers.Util.getParameterString(options.params),headers:{"Content-Type":"application/x-www-form-urlencoded"}});}else{resp.priv=OpenLayers.Request.GET({url:options.url,callback:this.createCallback(this.handleRead,resp,options),params:options.params,headers:options.headers});}
return resp;},handleRead:function(resp,options){this.handleResponse(resp,options);},filterToParams:function(filter,params){params=params||{};var className=filter.CLASS_NAME;var filterType=className.substring(className.lastIndexOf(".")+1);switch(filterType){case"Spatial":switch(filter.type){case OpenLayers.Filter.Spatial.BBOX:params.bbox=filter.value.toArray();break;case OpenLayers.Filter.Spatial.DWITHIN:params.tolerance=filter.distance;case OpenLayers.Filter.Spatial.WITHIN:params.lon=filter.value.x;params.lat=filter.value.y;break;default:OpenLayers.Console.warn("Unknown spatial filter type "+filter.type);}
break;case"Comparison":var op=OpenLayers.Protocol.HTTP.COMP_TYPE_TO_OP_STR[filter.type];if(op!==undefined){var value=filter.value;if(filter.type==OpenLayers.Filter.Comparison.LIKE){value=this.regex2value(value);if(this.wildcarded){value="%"+value+"%";}}
params[filter.property+"__"+op]=value;params.queryable=params.queryable||[];params.queryable.push(filter.property);}else{OpenLayers.Console.warn("Unknown comparison filter type "+filter.type);}
break;case"Logical":if(filter.type===OpenLayers.Filter.Logical.AND){for(var i=0,len=filter.filters.length;i<len;i++){params=this.filterToParams(filter.filters[i],params);}}else{OpenLayers.Console.warn("Unsupported logical filter type "+filter.type);}
break;default:OpenLayers.Console.warn("Unknown filter type "+filterType);}
return params;},regex2value:function(value){value=value.replace(/%/g,"\\%");value=value.replace(/\\\\\.(\*)?/g,function($0,$1){return $1?$0:"\\\\_";});value=value.replace(/\\\\\.\*/g,"\\\\%");value=value.replace(/(\\)?\.(\*)?/g,function($0,$1,$2){return $1||$2?$0:"_";});value=value.replace(/(\\)?\.\*/g,function($0,$1){return $1?$0:"%";});value=value.replace(/\\\./g,".");value=value.replace(/(\\)?\\\*/g,function($0,$1){return $1?$0:"*";});return value;},create:function(features,options){options=OpenLayers.Util.applyDefaults(options,this.options);var resp=new OpenLayers.Protocol.Response({reqFeatures:features,requestType:"create"});resp.priv=OpenLayers.Request.POST({url:options.url,callback:this.createCallback(this.handleCreate,resp,options),headers:options.headers,data:this.format.write(features)});return resp;},handleCreate:function(resp,options){this.handleResponse(resp,options);},update:function(feature,options){options=options||{};var url=options.url||feature.url||this.options.url+"/"+feature.fid;options=OpenLayers.Util.applyDefaults(options,this.options);var resp=new OpenLayers.Protocol.Response({reqFeatures:feature,requestType:"update"});resp.priv=OpenLayers.Request.PUT({url:url,callback:this.createCallback(this.handleUpdate,resp,options),headers:options.headers,data:this.format.write(feature)});return resp;},handleUpdate:function(resp,options){this.handleResponse(resp,options);},"delete":function(feature,options){options=options||{};var url=options.url||feature.url||this.options.url+"/"+feature.fid;options=OpenLayers.Util.applyDefaults(options,this.options);var resp=new OpenLayers.Protocol.Response({reqFeatures:feature,requestType:"delete"});resp.priv=OpenLayers.Request.DELETE({url:url,callback:this.createCallback(this.handleDelete,resp,options),headers:options.headers});return resp;},handleDelete:function(resp,options){this.handleResponse(resp,options);},handleResponse:function(resp,options){var request=resp.priv;if(options.callback){if(request.status>=200&&request.status<300){if(resp.requestType!="delete"){resp.features=this.parseFeatures(request);}
resp.code=OpenLayers.Protocol.Response.SUCCESS;}else{resp.code=OpenLayers.Protocol.Response.FAILURE;}
options.callback.call(options.scope,resp);}},parseFeatures:function(request){var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
if(!doc||doc.length<=0){return null;}
return this.format.read(doc);},commit:function(features,options){options=OpenLayers.Util.applyDefaults(options,this.options);var resp=[],nResponses=0;var types={};types[OpenLayers.State.INSERT]=[];types[OpenLayers.State.UPDATE]=[];types[OpenLayers.State.DELETE]=[];var feature,list,requestFeatures=[];for(var i=0,len=features.length;i<len;++i){feature=features[i];list=types[feature.state];if(list){list.push(feature);requestFeatures.push(feature);}}
var nRequests=(types[OpenLayers.State.INSERT].length>0?1:0)+
types[OpenLayers.State.UPDATE].length+
types[OpenLayers.State.DELETE].length;var success=true;var finalResponse=new OpenLayers.Protocol.Response({reqFeatures:requestFeatures});function insertCallback(response){var len=response.features?response.features.length:0;var fids=new Array(len);for(var i=0;i<len;++i){fids[i]=response.features[i].fid;}
finalResponse.insertIds=fids;callback.apply(this,[response]);}
function callback(response){this.callUserCallback(response,options);success=success&&response.success();nResponses++;if(nResponses>=nRequests){if(options.callback){finalResponse.code=success?OpenLayers.Protocol.Response.SUCCESS:OpenLayers.Protocol.Response.FAILURE;options.callback.apply(options.scope,[finalResponse]);}}}
var queue=types[OpenLayers.State.INSERT];if(queue.length>0){resp.push(this.create(queue,OpenLayers.Util.applyDefaults({callback:insertCallback,scope:this},options.create)));}
queue=types[OpenLayers.State.UPDATE];for(var i=queue.length-1;i>=0;--i){resp.push(this.update(queue[i],OpenLayers.Util.applyDefaults({callback:callback,scope:this},options.update)));}
queue=types[OpenLayers.State.DELETE];for(var i=queue.length-1;i>=0;--i){resp.push(this["delete"](queue[i],OpenLayers.Util.applyDefaults({callback:callback,scope:this},options["delete"])));}
return resp;},abort:function(response){if(response){response.priv.abort();}},callUserCallback:function(resp,options){var opt=options[resp.requestType];if(opt&&opt.callback){opt.callback.call(opt.scope,resp);}},CLASS_NAME:"OpenLayers.Protocol.HTTP"});(function(){var o=OpenLayers.Protocol.HTTP.COMP_TYPE_TO_OP_STR={};o[OpenLayers.Filter.Comparison.EQUAL_TO]="eq";o[OpenLayers.Filter.Comparison.NOT_EQUAL_TO]="ne";o[OpenLayers.Filter.Comparison.LESS_THAN]="lt";o[OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO]="lte";o[OpenLayers.Filter.Comparison.GREATER_THAN]="gt";o[OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO]="gte";o[OpenLayers.Filter.Comparison.LIKE]="ilike";})();OpenLayers.Strategy.BBOX=OpenLayers.Class(OpenLayers.Strategy,{bounds:null,resolution:null,ratio:2,resFactor:null,response:null,initialize:function(options){OpenLayers.Strategy.prototype.initialize.apply(this,[options]);},activate:function(){var activated=OpenLayers.Strategy.prototype.activate.call(this);if(activated){this.layer.events.on({"moveend":this.update,scope:this});this.layer.events.on({"refresh":this.update,scope:this});}
return activated;},deactivate:function(){var deactivated=OpenLayers.Strategy.prototype.deactivate.call(this);if(deactivated){this.layer.events.un({"moveend":this.update,scope:this});this.layer.events.un({"refresh":this.update,scope:this});}
return deactivated;},update:function(options){var mapBounds=this.getMapBounds();if((options&&options.force)||this.invalidBounds(mapBounds)){this.calculateBounds(mapBounds);this.resolution=this.layer.map.getResolution();this.triggerRead();}},getMapBounds:function(){var bounds=this.layer.map.getExtent();if(!this.layer.projection.equals(this.layer.map.getProjectionObject())){bounds=bounds.clone().transform(this.layer.map.getProjectionObject(),this.layer.projection);}
return bounds;},invalidBounds:function(mapBounds){if(!mapBounds){mapBounds=this.getMapBounds();}
var invalid=!this.bounds||!this.bounds.containsBounds(mapBounds);if(!invalid&&this.resFactor){var ratio=this.resolution/this.layer.map.getResolution();invalid=(ratio>=this.resFactor||ratio<=(1/this.resFactor));}
return invalid;},calculateBounds:function(mapBounds){if(!mapBounds){mapBounds=this.getMapBounds();}
var center=mapBounds.getCenterLonLat();var dataWidth=mapBounds.getWidth()*this.ratio;var dataHeight=mapBounds.getHeight()*this.ratio;this.bounds=new OpenLayers.Bounds(center.lon-(dataWidth/2),center.lat-(dataHeight/2),center.lon+(dataWidth/2),center.lat+(dataHeight/2));},triggerRead:function(){if(this.response){this.layer.protocol.abort(this.response);this.layer.events.triggerEvent("loadend");}
this.layer.events.triggerEvent("loadstart");this.response=this.layer.protocol.read({filter:this.createFilter(),callback:this.merge,scope:this});},createFilter:function(){var filter=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.BBOX,value:this.bounds,projection:this.layer.projection});if(this.layer.filter){filter=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND,filters:[this.layer.filter,filter]});}
return filter;},merge:function(resp){this.layer.destroyFeatures();var features=resp.features;if(features&&features.length>0){var remote=this.layer.projection;var local=this.layer.map.getProjectionObject();if(!local.equals(remote)){var geom;for(var i=0,len=features.length;i<len;++i){geom=features[i].geometry;if(geom){geom.transform(remote,local);}}}
this.layer.addFeatures(features);}
this.response=null;this.layer.events.triggerEvent("loadend");},CLASS_NAME:"OpenLayers.Strategy.BBOX"});OpenLayers.Control.SelectFeature=OpenLayers.Class(OpenLayers.Control,{EVENT_TYPES:["beforefeaturehighlighted","featurehighlighted","featureunhighlighted"],multipleKey:null,toggleKey:null,multiple:false,clickout:true,toggle:false,hover:false,highlightOnly:false,box:false,onBeforeSelect:function(){},onSelect:function(){},onUnselect:function(){},scope:null,geometryTypes:null,layer:null,layers:null,callbacks:null,selectStyle:null,renderIntent:"select",handlers:null,initialize:function(layers,options){this.EVENT_TYPES=OpenLayers.Control.SelectFeature.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES);OpenLayers.Control.prototype.initialize.apply(this,[options]);if(this.scope===null){this.scope=this;}
this.initLayer(layers);var callbacks={click:this.clickFeature,clickout:this.clickoutFeature};if(this.hover){callbacks.over=this.overFeature;callbacks.out=this.outFeature;}
this.callbacks=OpenLayers.Util.extend(callbacks,this.callbacks);this.handlers={feature:new OpenLayers.Handler.Feature(this,this.layer,this.callbacks,{geometryTypes:this.geometryTypes})};if(this.box){this.handlers.box=new OpenLayers.Handler.Box(this,{done:this.selectBox},{boxDivClassName:"olHandlerBoxSelectFeature"});}},initLayer:function(layers){if(layers instanceof Array){this.layers=layers;this.layer=new OpenLayers.Layer.Vector.RootContainer(this.id+"_container",{layers:layers});}else{this.layer=layers;}},destroy:function(){if(this.active&&this.layers){this.map.removeLayer(this.layer);}
OpenLayers.Control.prototype.destroy.apply(this,arguments);if(this.layers){this.layer.destroy();}},activate:function(){if(!this.active){if(this.layers){this.map.addLayer(this.layer);}
this.handlers.feature.activate();if(this.box&&this.handlers.box){this.handlers.box.activate();}}
return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){if(this.active){this.handlers.feature.deactivate();if(this.handlers.box){this.handlers.box.deactivate();}
if(this.layers){this.map.removeLayer(this.layer);}}
return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},unselectAll:function(options){var layers=this.layers||[this.layer];var layer,feature;for(var l=0;l<layers.length;++l){layer=layers[l];for(var i=layer.selectedFeatures.length-1;i>=0;--i){feature=layer.selectedFeatures[i];if(!options||options.except!=feature){this.unselect(feature);}}}},clickFeature:function(feature){if(!this.hover){var selected=(OpenLayers.Util.indexOf(feature.layer.selectedFeatures,feature)>-1);if(selected){if(this.toggleSelect()){this.unselect(feature);}else if(!this.multipleSelect()){this.unselectAll({except:feature});}}else{if(!this.multipleSelect()){this.unselectAll({except:feature});}
this.select(feature);}}},multipleSelect:function(){return this.multiple||(this.handlers.feature.evt&&this.handlers.feature.evt[this.multipleKey]);},toggleSelect:function(){return this.toggle||(this.handlers.feature.evt&&this.handlers.feature.evt[this.toggleKey]);},clickoutFeature:function(feature){if(!this.hover&&this.clickout){this.unselectAll();}},overFeature:function(feature){var layer=feature.layer;if(this.hover){if(this.highlightOnly){this.highlight(feature);}else if(OpenLayers.Util.indexOf(layer.selectedFeatures,feature)==-1){this.select(feature);}}},outFeature:function(feature){if(this.hover){if(this.highlightOnly){if(feature._lastHighlighter==this.id){if(feature._prevHighlighter&&feature._prevHighlighter!=this.id){delete feature._lastHighlighter;var control=this.map.getControl(feature._prevHighlighter);if(control){control.highlight(feature);}}else{this.unhighlight(feature);}}}else{this.unselect(feature);}}},highlight:function(feature){var layer=feature.layer;var cont=this.events.triggerEvent("beforefeaturehighlighted",{feature:feature});if(cont!==false){feature._prevHighlighter=feature._lastHighlighter;feature._lastHighlighter=this.id;var style=this.selectStyle||this.renderIntent;layer.drawFeature(feature,style);this.events.triggerEvent("featurehighlighted",{feature:feature});}},unhighlight:function(feature){var layer=feature.layer;feature._lastHighlighter=feature._prevHighlighter;delete feature._prevHighlighter;layer.drawFeature(feature,feature.style||feature.layer.style||"default");this.events.triggerEvent("featureunhighlighted",{feature:feature});},select:function(feature){var cont=this.onBeforeSelect.call(this.scope,feature);var layer=feature.layer;if(cont!==false){cont=layer.events.triggerEvent("beforefeatureselected",{feature:feature});if(cont!==false){layer.selectedFeatures.push(feature);this.highlight(feature);if(!this.handlers.feature.lastFeature){this.handlers.feature.lastFeature=layer.selectedFeatures[0];}
layer.events.triggerEvent("featureselected",{feature:feature});this.onSelect.call(this.scope,feature);}}},unselect:function(feature){var layer=feature.layer;this.unhighlight(feature);OpenLayers.Util.removeItem(layer.selectedFeatures,feature);layer.events.triggerEvent("featureunselected",{feature:feature});this.onUnselect.call(this.scope,feature);},selectBox:function(position){if(position instanceof OpenLayers.Bounds){var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.left,position.bottom));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.right,position.top));var bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);if(!this.multipleSelect()){this.unselectAll();}
var prevMultiple=this.multiple;this.multiple=true;var layers=this.layers||[this.layer];var layer;for(var l=0;l<layers.length;++l){layer=layers[l];for(var i=0,len=layer.features.length;i<len;++i){var feature=layer.features[i];if(!feature.getVisibility()){continue;}
if(this.geometryTypes==null||OpenLayers.Util.indexOf(this.geometryTypes,feature.geometry.CLASS_NAME)>-1){if(bounds.toGeometry().intersects(feature.geometry)){if(OpenLayers.Util.indexOf(layer.selectedFeatures,feature)==-1){this.select(feature);}}}}}
this.multiple=prevMultiple;}},setMap:function(map){this.handlers.feature.setMap(map);if(this.box){this.handlers.box.setMap(map);}
OpenLayers.Control.prototype.setMap.apply(this,arguments);},setLayer:function(layers){var isActive=this.active;this.unselectAll();this.deactivate();if(this.layers){this.layer.destroy();this.layers=null;}
this.initLayer(layers);this.handlers.feature.layer=this.layer;if(isActive){this.activate();}},CLASS_NAME:"OpenLayers.Control.SelectFeature"});OpenLayers.Format.Filter.v1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{ogc:"http://www.opengis.net/ogc",gml:"http://www.opengis.net/gml",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},defaultPrefix:"ogc",schemaLocation:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){var obj={};this.readers.ogc["Filter"].apply(this,[data,obj]);return obj.filter;},readers:{"ogc":{"Filter":function(node,parent){var obj={fids:[],filters:[]};this.readChildNodes(node,obj);if(obj.fids.length>0){parent.filter=new OpenLayers.Filter.FeatureId({fids:obj.fids});}else if(obj.filters.length>0){parent.filter=obj.filters[0];}},"FeatureId":function(node,obj){var fid=node.getAttribute("fid");if(fid){obj.fids.push(fid);}},"And":function(node,obj){var filter=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.AND});this.readChildNodes(node,filter);obj.filters.push(filter);},"Or":function(node,obj){var filter=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.OR});this.readChildNodes(node,filter);obj.filters.push(filter);},"Not":function(node,obj){var filter=new OpenLayers.Filter.Logical({type:OpenLayers.Filter.Logical.NOT});this.readChildNodes(node,filter);obj.filters.push(filter);},"PropertyIsLessThan":function(node,obj){var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LESS_THAN});this.readChildNodes(node,filter);obj.filters.push(filter);},"PropertyIsGreaterThan":function(node,obj){var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.GREATER_THAN});this.readChildNodes(node,filter);obj.filters.push(filter);},"PropertyIsLessThanOrEqualTo":function(node,obj){var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LESS_THAN_OR_EQUAL_TO});this.readChildNodes(node,filter);obj.filters.push(filter);},"PropertyIsGreaterThanOrEqualTo":function(node,obj){var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.GREATER_THAN_OR_EQUAL_TO});this.readChildNodes(node,filter);obj.filters.push(filter);},"PropertyIsBetween":function(node,obj){var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.BETWEEN});this.readChildNodes(node,filter);obj.filters.push(filter);},"Literal":function(node,obj){obj.value=OpenLayers.String.numericIf(this.getChildValue(node));},"PropertyName":function(node,filter){filter.property=this.getChildValue(node);},"LowerBoundary":function(node,filter){filter.lowerBoundary=OpenLayers.String.numericIf(this.readOgcExpression(node));},"UpperBoundary":function(node,filter){filter.upperBoundary=OpenLayers.String.numericIf(this.readOgcExpression(node));},"Intersects":function(node,obj){this.readSpatial(node,obj,OpenLayers.Filter.Spatial.INTERSECTS);},"Within":function(node,obj){this.readSpatial(node,obj,OpenLayers.Filter.Spatial.WITHIN);},"Contains":function(node,obj){this.readSpatial(node,obj,OpenLayers.Filter.Spatial.CONTAINS);},"DWithin":function(node,obj){this.readSpatial(node,obj,OpenLayers.Filter.Spatial.DWITHIN);},"Distance":function(node,obj){obj.distance=parseInt(this.getChildValue(node));obj.distanceUnits=node.getAttribute("units");}}},readSpatial:function(node,obj,type){var filter=new OpenLayers.Filter.Spatial({type:type});this.readChildNodes(node,filter);filter.value=filter.components[0];delete filter.components;obj.filters.push(filter);},readOgcExpression:function(node){var obj={};this.readChildNodes(node,obj);var value=obj.value;if(value===undefined){value=this.getChildValue(node);}
return value;},write:function(filter){return this.writers.ogc["Filter"].apply(this,[filter]);},writers:{"ogc":{"Filter":function(filter){var node=this.createElementNSPlus("ogc:Filter");var sub=filter.CLASS_NAME.split(".").pop();if(sub=="FeatureId"){for(var i=0;i<filter.fids.length;++i){this.writeNode("FeatureId",filter.fids[i],node);}}else{this.writeNode(this.getFilterType(filter),filter,node);}
return node;},"FeatureId":function(fid){return this.createElementNSPlus("ogc:FeatureId",{attributes:{fid:fid}});},"And":function(filter){var node=this.createElementNSPlus("ogc:And");var childFilter;for(var i=0;i<filter.filters.length;++i){childFilter=filter.filters[i];this.writeNode(this.getFilterType(childFilter),childFilter,node);}
return node;},"Or":function(filter){var node=this.createElementNSPlus("ogc:Or");var childFilter;for(var i=0;i<filter.filters.length;++i){childFilter=filter.filters[i];this.writeNode(this.getFilterType(childFilter),childFilter,node);}
return node;},"Not":function(filter){var node=this.createElementNSPlus("ogc:Not");var childFilter=filter.filters[0];this.writeNode(this.getFilterType(childFilter),childFilter,node);return node;},"PropertyIsLessThan":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsLessThan");this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.value,node);return node;},"PropertyIsGreaterThan":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsGreaterThan");this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.value,node);return node;},"PropertyIsLessThanOrEqualTo":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsLessThanOrEqualTo");this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.value,node);return node;},"PropertyIsGreaterThanOrEqualTo":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsGreaterThanOrEqualTo");this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.value,node);return node;},"PropertyIsBetween":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsBetween");this.writeNode("PropertyName",filter,node);this.writeNode("LowerBoundary",filter,node);this.writeNode("UpperBoundary",filter,node);return node;},"PropertyName":function(filter){return this.createElementNSPlus("ogc:PropertyName",{value:filter.property});},"Literal":function(value){return this.createElementNSPlus("ogc:Literal",{value:value});},"LowerBoundary":function(filter){var node=this.createElementNSPlus("ogc:LowerBoundary");this.writeNode("Literal",filter.lowerBoundary,node);return node;},"UpperBoundary":function(filter){var node=this.createElementNSPlus("ogc:UpperBoundary");this.writeNode("Literal",filter.upperBoundary,node);return node;},"INTERSECTS":function(filter){return this.writeSpatial(filter,"Intersects");},"WITHIN":function(filter){return this.writeSpatial(filter,"Within");},"CONTAINS":function(filter){return this.writeSpatial(filter,"Contains");},"DWITHIN":function(filter){var node=this.writeSpatial(filter,"DWithin");this.writeNode("Distance",filter,node);return node;},"Distance":function(filter){return this.createElementNSPlus("ogc:Distance",{attributes:{units:filter.distanceUnits},value:filter.distance});}}},getFilterType:function(filter){var filterType=this.filterMap[filter.type];if(!filterType){throw"Filter writing not supported for rule type: "+filter.type;}
return filterType;},filterMap:{"&&":"And","||":"Or","!":"Not","==":"PropertyIsEqualTo","!=":"PropertyIsNotEqualTo","<":"PropertyIsLessThan",">":"PropertyIsGreaterThan","<=":"PropertyIsLessThanOrEqualTo",">=":"PropertyIsGreaterThanOrEqualTo","..":"PropertyIsBetween","~":"PropertyIsLike","BBOX":"BBOX","DWITHIN":"DWITHIN","WITHIN":"WITHIN","CONTAINS":"CONTAINS","INTERSECTS":"INTERSECTS"},CLASS_NAME:"OpenLayers.Format.Filter.v1"});OpenLayers.Geometry.Curve=OpenLayers.Class(OpenLayers.Geometry.MultiPoint,{componentTypes:["OpenLayers.Geometry.Point"],initialize:function(points){OpenLayers.Geometry.MultiPoint.prototype.initialize.apply(this,arguments);},getLength:function(){var length=0.0;if(this.components&&(this.components.length>1)){for(var i=1,len=this.components.length;i<len;i++){length+=this.components[i-1].distanceTo(this.components[i]);}}
return length;},getGeodesicLength:function(projection){var geom=this;if(projection){var gg=new OpenLayers.Projection("EPSG:4326");if(!gg.equals(projection)){geom=this.clone().transform(projection,gg);}}
var length=0.0;if(geom.components&&(geom.components.length>1)){var p1,p2;for(var i=1,len=geom.components.length;i<len;i++){p1=geom.components[i-1];p2=geom.components[i];length+=OpenLayers.Util.distVincenty({lon:p1.x,lat:p1.y},{lon:p2.x,lat:p2.y});}}
return length*1000;},CLASS_NAME:"OpenLayers.Geometry.Curve"});OpenLayers.Layer.Text=OpenLayers.Class(OpenLayers.Layer.Markers,{location:null,features:null,formatOptions:null,selectedFeature:null,initialize:function(name,options){OpenLayers.Layer.Markers.prototype.initialize.apply(this,arguments);this.features=new Array();},destroy:function(){OpenLayers.Layer.Markers.prototype.destroy.apply(this,arguments);this.clearFeatures();this.features=null;},loadText:function(){if(!this.loaded){if(this.location!=null){var onFail=function(e){this.events.triggerEvent("loadend");};this.events.triggerEvent("loadstart");OpenLayers.Request.GET({url:this.location,success:this.parseData,failure:onFail,scope:this});this.loaded=true;}}},moveTo:function(bounds,zoomChanged,minor){OpenLayers.Layer.Markers.prototype.moveTo.apply(this,arguments);if(this.visibility&&!this.loaded){this.loadText();}},parseData:function(ajaxRequest){var text=ajaxRequest.responseText;var options={};OpenLayers.Util.extend(options,this.formatOptions);if(this.map&&!this.projection.equals(this.map.getProjectionObject())){options.externalProjection=this.projection;options.internalProjection=this.map.getProjectionObject();}
var parser=new OpenLayers.Format.Text(options);var features=parser.read(text);for(var i=0,len=features.length;i<len;i++){var data={};var feature=features[i];var location;var iconSize,iconOffset;location=new OpenLayers.LonLat(feature.geometry.x,feature.geometry.y);if(feature.style.graphicWidth&&feature.style.graphicHeight){iconSize=new OpenLayers.Size(feature.style.graphicWidth,feature.style.graphicHeight);}
if(feature.style.graphicXOffset!==undefined&&feature.style.graphicYOffset!==undefined){iconOffset=new OpenLayers.Pixel(feature.style.graphicXOffset,feature.style.graphicYOffset);}
if(feature.style.externalGraphic!=null){data.icon=new OpenLayers.Icon(feature.style.externalGraphic,iconSize,iconOffset);}else{data.icon=OpenLayers.Marker.defaultIcon();if(iconSize!=null){data.icon.setSize(iconSize);}}
if((feature.attributes.title!=null)&&(feature.attributes.description!=null)){data['popupContentHTML']='<h2>'+feature.attributes.title+'</h2>'+'<p>'+feature.attributes.description+'</p>';}
data['overflow']=feature.attributes.overflow||"auto";var markerFeature=new OpenLayers.Feature(this,location,data);this.features.push(markerFeature);var marker=markerFeature.createMarker();if((feature.attributes.title!=null)&&(feature.attributes.description!=null)){marker.events.register('click',markerFeature,this.markerClick);}
this.addMarker(marker);}
this.events.triggerEvent("loadend");},markerClick:function(evt){var sameMarkerClicked=(this==this.layer.selectedFeature);this.layer.selectedFeature=(!sameMarkerClicked)?this:null;for(var i=0,len=this.layer.map.popups.length;i<len;i++){this.layer.map.removePopup(this.layer.map.popups[i]);}
if(!sameMarkerClicked){this.layer.map.addPopup(this.createPopup());}
OpenLayers.Event.stop(evt);},clearFeatures:function(){if(this.features!=null){while(this.features.length>0){var feature=this.features[0];OpenLayers.Util.removeItem(this.features,feature);feature.destroy();}}},CLASS_NAME:"OpenLayers.Layer.Text"});OpenLayers.Control.ModifyFeature=OpenLayers.Class(OpenLayers.Control,{geometryTypes:null,clickout:true,toggle:true,standalone:false,layer:null,feature:null,vertices:null,virtualVertices:null,selectControl:null,dragControl:null,handlers:null,deleteCodes:null,virtualStyle:null,mode:null,modified:false,radiusHandle:null,dragHandle:null,onModificationStart:function(){},onModification:function(){},onModificationEnd:function(){},initialize:function(layer,options){this.layer=layer;this.vertices=[];this.virtualVertices=[];this.virtualStyle=OpenLayers.Util.extend({},this.layer.style||this.layer.styleMap.createSymbolizer());this.virtualStyle.fillOpacity=0.3;this.virtualStyle.strokeOpacity=0.3;this.deleteCodes=[46,68];this.mode=OpenLayers.Control.ModifyFeature.RESHAPE;OpenLayers.Control.prototype.initialize.apply(this,[options]);if(!(this.deleteCodes instanceof Array)){this.deleteCodes=[this.deleteCodes];}
var control=this;var selectOptions={geometryTypes:this.geometryTypes,clickout:this.clickout,toggle:this.toggle,onBeforeSelect:this.beforeSelectFeature,onSelect:this.selectFeature,onUnselect:this.unselectFeature,scope:this};if(this.standalone===false){this.selectControl=new OpenLayers.Control.SelectFeature(layer,selectOptions);}
var dragOptions={geometryTypes:["OpenLayers.Geometry.Point"],snappingOptions:this.snappingOptions,onStart:function(feature,pixel){control.dragStart.apply(control,[feature,pixel]);},onDrag:function(feature,pixel){control.dragVertex.apply(control,[feature,pixel]);},onComplete:function(feature){control.dragComplete.apply(control,[feature]);},featureCallbacks:{over:function(feature){if(control.standalone!==true||feature._sketch||control.feature===feature){control.dragControl.overFeature.apply(control.dragControl,[feature]);}}}};this.dragControl=new OpenLayers.Control.DragFeature(layer,dragOptions);var keyboardOptions={keydown:this.handleKeypress};this.handlers={keyboard:new OpenLayers.Handler.Keyboard(this,keyboardOptions)};},destroy:function(){this.layer=null;this.standalone||this.selectControl.destroy();this.dragControl.destroy();OpenLayers.Control.prototype.destroy.apply(this,[]);},activate:function(){return((this.standalone||this.selectControl.activate())&&this.handlers.keyboard.activate()&&OpenLayers.Control.prototype.activate.apply(this,arguments));},deactivate:function(){var deactivated=false;if(OpenLayers.Control.prototype.deactivate.apply(this,arguments)){this.layer.removeFeatures(this.vertices,{silent:true});this.layer.removeFeatures(this.virtualVertices,{silent:true});this.vertices=[];this.dragControl.deactivate();var feature=this.feature;var valid=feature&&feature.geometry&&feature.layer;if(this.standalone===false){if(valid){this.selectControl.unselect.apply(this.selectControl,[feature]);}
this.selectControl.deactivate();}else{if(valid){this.unselectFeature(feature);}}
this.handlers.keyboard.deactivate();deactivated=true;}
return deactivated;},beforeSelectFeature:function(feature){return this.layer.events.triggerEvent("beforefeaturemodified",{feature:feature});},selectFeature:function(feature){this.feature=feature;this.modified=false;this.resetVertices();this.dragControl.activate();this.onModificationStart(this.feature);},unselectFeature:function(feature){this.layer.removeFeatures(this.vertices,{silent:true});this.vertices=[];this.layer.destroyFeatures(this.virtualVertices,{silent:true});this.virtualVertices=[];if(this.dragHandle){this.layer.destroyFeatures([this.dragHandle],{silent:true});delete this.dragHandle;}
if(this.radiusHandle){this.layer.destroyFeatures([this.radiusHandle],{silent:true});delete this.radiusHandle;}
this.feature=null;this.dragControl.deactivate();this.onModificationEnd(feature);this.layer.events.triggerEvent("afterfeaturemodified",{feature:feature,modified:this.modified});this.modified=false;},dragStart:function(feature,pixel){if(feature!=this.feature&&!feature.geometry.parent&&feature!=this.dragHandle&&feature!=this.radiusHandle){if(this.standalone===false&&this.feature){this.selectControl.clickFeature.apply(this.selectControl,[this.feature]);}
if(this.geometryTypes==null||OpenLayers.Util.indexOf(this.geometryTypes,feature.geometry.CLASS_NAME)!=-1){this.standalone||this.selectControl.clickFeature.apply(this.selectControl,[feature]);this.dragControl.overFeature.apply(this.dragControl,[feature]);this.dragControl.lastPixel=pixel;this.dragControl.handlers.drag.started=true;this.dragControl.handlers.drag.start=pixel;this.dragControl.handlers.drag.last=pixel;}}},dragVertex:function(vertex,pixel){this.modified=true;if(this.feature.geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){if(this.feature!=vertex){this.feature=vertex;}
this.layer.events.triggerEvent("vertexmodified",{vertex:vertex.geometry,feature:this.feature,pixel:pixel});}else{if(vertex._index){vertex.geometry.parent.addComponent(vertex.geometry,vertex._index);delete vertex._index;OpenLayers.Util.removeItem(this.virtualVertices,vertex);this.vertices.push(vertex);}else if(vertex==this.dragHandle){this.layer.removeFeatures(this.vertices,{silent:true});this.vertices=[];if(this.radiusHandle){this.layer.destroyFeatures([this.radiusHandle],{silent:true});this.radiusHandle=null;}}else if(vertex!==this.radiusHandle){this.layer.events.triggerEvent("vertexmodified",{vertex:vertex.geometry,feature:this.feature,pixel:pixel});}
if(this.virtualVertices.length>0){this.layer.destroyFeatures(this.virtualVertices,{silent:true});this.virtualVertices=[];}
this.layer.drawFeature(this.feature,this.standalone?undefined:this.selectControl.renderIntent);}
this.layer.drawFeature(vertex);},dragComplete:function(vertex){this.resetVertices();this.setFeatureState();this.onModification(this.feature);this.layer.events.triggerEvent("featuremodified",{feature:this.feature});},setFeatureState:function(){if(this.feature.state!=OpenLayers.State.INSERT&&this.feature.state!=OpenLayers.State.DELETE){this.feature.state=OpenLayers.State.UPDATE;}},resetVertices:function(){if(this.dragControl.feature){this.dragControl.outFeature(this.dragControl.feature);}
if(this.vertices.length>0){this.layer.removeFeatures(this.vertices,{silent:true});this.vertices=[];}
if(this.virtualVertices.length>0){this.layer.removeFeatures(this.virtualVertices,{silent:true});this.virtualVertices=[];}
if(this.dragHandle){this.layer.destroyFeatures([this.dragHandle],{silent:true});this.dragHandle=null;}
if(this.radiusHandle){this.layer.destroyFeatures([this.radiusHandle],{silent:true});this.radiusHandle=null;}
if(this.feature&&this.feature.geometry.CLASS_NAME!="OpenLayers.Geometry.Point"){if((this.mode&OpenLayers.Control.ModifyFeature.DRAG)){this.collectDragHandle();}
if((this.mode&(OpenLayers.Control.ModifyFeature.ROTATE|OpenLayers.Control.ModifyFeature.RESIZE))){this.collectRadiusHandle();}
if(this.mode&OpenLayers.Control.ModifyFeature.RESHAPE){if(!(this.mode&OpenLayers.Control.ModifyFeature.RESIZE)){this.collectVertices();}}}},handleKeypress:function(evt){var code=evt.keyCode;if(this.feature&&OpenLayers.Util.indexOf(this.deleteCodes,code)!=-1){var vertex=this.dragControl.feature;if(vertex&&OpenLayers.Util.indexOf(this.vertices,vertex)!=-1&&!this.dragControl.handlers.drag.dragging&&vertex.geometry.parent){vertex.geometry.parent.removeComponent(vertex.geometry);this.layer.drawFeature(this.feature,this.standalone?undefined:this.selectControl.renderIntent);this.resetVertices();this.setFeatureState();this.onModification(this.feature);this.layer.events.triggerEvent("featuremodified",{feature:this.feature});}}},collectVertices:function(){this.vertices=[];this.virtualVertices=[];var control=this;function collectComponentVertices(geometry){var i,vertex,component,len;if(geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){vertex=new OpenLayers.Feature.Vector(geometry);vertex._sketch=true;control.vertices.push(vertex);}else{var numVert=geometry.components.length;if(geometry.CLASS_NAME=="OpenLayers.Geometry.LinearRing"){numVert-=1;}
for(i=0;i<numVert;++i){component=geometry.components[i];if(component.CLASS_NAME=="OpenLayers.Geometry.Point"){vertex=new OpenLayers.Feature.Vector(component);vertex._sketch=true;control.vertices.push(vertex);}else{collectComponentVertices(component);}}
if(geometry.CLASS_NAME!="OpenLayers.Geometry.MultiPoint"){for(i=0,len=geometry.components.length;i<len-1;++i){var prevVertex=geometry.components[i];var nextVertex=geometry.components[i+1];if(prevVertex.CLASS_NAME=="OpenLayers.Geometry.Point"&&nextVertex.CLASS_NAME=="OpenLayers.Geometry.Point"){var x=(prevVertex.x+nextVertex.x)/2;var y=(prevVertex.y+nextVertex.y)/2;var point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(x,y),null,control.virtualStyle);point.geometry.parent=geometry;point._index=i+1;point._sketch=true;control.virtualVertices.push(point);}}}}}
collectComponentVertices.call(this,this.feature.geometry);this.layer.addFeatures(this.virtualVertices,{silent:true});this.layer.addFeatures(this.vertices,{silent:true});},collectDragHandle:function(){var geometry=this.feature.geometry;var center=geometry.getBounds().getCenterLonLat();var originGeometry=new OpenLayers.Geometry.Point(center.lon,center.lat);var origin=new OpenLayers.Feature.Vector(originGeometry);originGeometry.move=function(x,y){OpenLayers.Geometry.Point.prototype.move.call(this,x,y);geometry.move(x,y);};origin._sketch=true;this.dragHandle=origin;this.layer.addFeatures([this.dragHandle],{silent:true});},collectRadiusHandle:function(){var geometry=this.feature.geometry;var bounds=geometry.getBounds();var center=bounds.getCenterLonLat();var originGeometry=new OpenLayers.Geometry.Point(center.lon,center.lat);var radiusGeometry=new OpenLayers.Geometry.Point(bounds.right,bounds.bottom);var radius=new OpenLayers.Feature.Vector(radiusGeometry);var resize=(this.mode&OpenLayers.Control.ModifyFeature.RESIZE);var reshape=(this.mode&OpenLayers.Control.ModifyFeature.RESHAPE);var rotate=(this.mode&OpenLayers.Control.ModifyFeature.ROTATE);radiusGeometry.move=function(x,y){OpenLayers.Geometry.Point.prototype.move.call(this,x,y);var dx1=this.x-originGeometry.x;var dy1=this.y-originGeometry.y;var dx0=dx1-x;var dy0=dy1-y;if(rotate){var a0=Math.atan2(dy0,dx0);var a1=Math.atan2(dy1,dx1);var angle=a1-a0;angle*=180/Math.PI;geometry.rotate(angle,originGeometry);}
if(resize){var scale,ratio;if(reshape){scale=dy1/dy0;ratio=(dx1/dx0)/scale;}else{var l0=Math.sqrt((dx0*dx0)+(dy0*dy0));var l1=Math.sqrt((dx1*dx1)+(dy1*dy1));scale=l1/l0;}
geometry.resize(scale,originGeometry,ratio);}};radius._sketch=true;this.radiusHandle=radius;this.layer.addFeatures([this.radiusHandle],{silent:true});},setMap:function(map){this.standalone||this.selectControl.setMap(map);this.dragControl.setMap(map);OpenLayers.Control.prototype.setMap.apply(this,arguments);},CLASS_NAME:"OpenLayers.Control.ModifyFeature"});OpenLayers.Control.ModifyFeature.RESHAPE=1;OpenLayers.Control.ModifyFeature.RESIZE=2;OpenLayers.Control.ModifyFeature.ROTATE=4;OpenLayers.Control.ModifyFeature.DRAG=8;OpenLayers.Geometry.LineString=OpenLayers.Class(OpenLayers.Geometry.Curve,{initialize:function(points){OpenLayers.Geometry.Curve.prototype.initialize.apply(this,arguments);},removeComponent:function(point){if(this.components&&(this.components.length>2)){OpenLayers.Geometry.Collection.prototype.removeComponent.apply(this,arguments);}},intersects:function(geometry){var intersect=false;var type=geometry.CLASS_NAME;if(type=="OpenLayers.Geometry.LineString"||type=="OpenLayers.Geometry.LinearRing"||type=="OpenLayers.Geometry.Point"){var segs1=this.getSortedSegments();var segs2;if(type=="OpenLayers.Geometry.Point"){segs2=[{x1:geometry.x,y1:geometry.y,x2:geometry.x,y2:geometry.y}];}else{segs2=geometry.getSortedSegments();}
var seg1,seg1x1,seg1x2,seg1y1,seg1y2,seg2,seg2y1,seg2y2;outer:for(var i=0,len=segs1.length;i<len;++i){seg1=segs1[i];seg1x1=seg1.x1;seg1x2=seg1.x2;seg1y1=seg1.y1;seg1y2=seg1.y2;inner:for(var j=0,jlen=segs2.length;j<jlen;++j){seg2=segs2[j];if(seg2.x1>seg1x2){break;}
if(seg2.x2<seg1x1){continue;}
seg2y1=seg2.y1;seg2y2=seg2.y2;if(Math.min(seg2y1,seg2y2)>Math.max(seg1y1,seg1y2)){continue;}
if(Math.max(seg2y1,seg2y2)<Math.min(seg1y1,seg1y2)){continue;}
if(OpenLayers.Geometry.segmentsIntersect(seg1,seg2)){intersect=true;break outer;}}}}else{intersect=geometry.intersects(this);}
return intersect;},getSortedSegments:function(){var numSeg=this.components.length-1;var segments=new Array(numSeg),point1,point2;for(var i=0;i<numSeg;++i){point1=this.components[i];point2=this.components[i+1];if(point1.x<point2.x){segments[i]={x1:point1.x,y1:point1.y,x2:point2.x,y2:point2.y};}else{segments[i]={x1:point2.x,y1:point2.y,x2:point1.x,y2:point1.y};}}
function byX1(seg1,seg2){return seg1.x1-seg2.x1;}
return segments.sort(byX1);},splitWithSegment:function(seg,options){var edge=!(options&&options.edge===false);var tolerance=options&&options.tolerance;var lines=[];var verts=this.getVertices();var points=[];var intersections=[];var split=false;var vert1,vert2,point;var node,vertex,target;var interOptions={point:true,tolerance:tolerance};var result=null;for(var i=0,stop=verts.length-2;i<=stop;++i){vert1=verts[i];points.push(vert1.clone());vert2=verts[i+1];target={x1:vert1.x,y1:vert1.y,x2:vert2.x,y2:vert2.y};point=OpenLayers.Geometry.segmentsIntersect(seg,target,interOptions);if(point instanceof OpenLayers.Geometry.Point){if((point.x===seg.x1&&point.y===seg.y1)||(point.x===seg.x2&&point.y===seg.y2)||point.equals(vert1)||point.equals(vert2)){vertex=true;}else{vertex=false;}
if(vertex||edge){if(!point.equals(intersections[intersections.length-1])){intersections.push(point.clone());}
if(i===0){if(point.equals(vert1)){continue;}}
if(point.equals(vert2)){continue;}
split=true;if(!point.equals(vert1)){points.push(point);}
lines.push(new OpenLayers.Geometry.LineString(points));points=[point.clone()];}}}
if(split){points.push(vert2.clone());lines.push(new OpenLayers.Geometry.LineString(points));}
if(intersections.length>0){var xDir=seg.x1<seg.x2?1:-1;var yDir=seg.y1<seg.y2?1:-1;result={lines:lines,points:intersections.sort(function(p1,p2){return(xDir*p1.x-xDir*p2.x)||(yDir*p1.y-yDir*p2.y);})};}
return result;},split:function(target,options){var results=null;var mutual=options&&options.mutual;var sourceSplit,targetSplit,sourceParts,targetParts;if(target instanceof OpenLayers.Geometry.LineString){var verts=this.getVertices();var vert1,vert2,seg,splits,lines,point;var points=[];sourceParts=[];for(var i=0,stop=verts.length-2;i<=stop;++i){vert1=verts[i];vert2=verts[i+1];seg={x1:vert1.x,y1:vert1.y,x2:vert2.x,y2:vert2.y};targetParts=targetParts||[target];if(mutual){points.push(vert1.clone());}
for(var j=0;j<targetParts.length;++j){splits=targetParts[j].splitWithSegment(seg,options);if(splits){lines=splits.lines;if(lines.length>0){lines.unshift(j,1);Array.prototype.splice.apply(targetParts,lines);j+=lines.length-2;}
if(mutual){for(var k=0,len=splits.points.length;k<len;++k){point=splits.points[k];if(!point.equals(vert1)){points.push(point);sourceParts.push(new OpenLayers.Geometry.LineString(points));if(point.equals(vert2)){points=[];}else{points=[point.clone()];}}}}}}}
if(mutual&&sourceParts.length>0&&points.length>0){points.push(vert2.clone());sourceParts.push(new OpenLayers.Geometry.LineString(points));}}else{results=target.splitWith(this,options);}
if(targetParts&&targetParts.length>1){targetSplit=true;}else{targetParts=[];}
if(sourceParts&&sourceParts.length>1){sourceSplit=true;}else{sourceParts=[];}
if(targetSplit||sourceSplit){if(mutual){results=[sourceParts,targetParts];}else{results=targetParts;}}
return results;},splitWith:function(geometry,options){return geometry.split(this,options);},getVertices:function(nodes){var vertices;if(nodes===true){vertices=[this.components[0],this.components[this.components.length-1]];}else if(nodes===false){vertices=this.components.slice(1,this.components.length-1);}else{vertices=this.components.slice();}
return vertices;},distanceTo:function(geometry,options){var edge=!(options&&options.edge===false);var details=edge&&options&&options.details;var result,best={};var min=Number.POSITIVE_INFINITY;if(geometry instanceof OpenLayers.Geometry.Point){var segs=this.getSortedSegments();var x=geometry.x;var y=geometry.y;var seg;for(var i=0,len=segs.length;i<len;++i){seg=segs[i];result=OpenLayers.Geometry.distanceToSegment(geometry,seg);if(result.distance<min){min=result.distance;best=result;if(min===0){break;}}else{if(seg.x2>x&&((y>seg.y1&&y<seg.y2)||(y<seg.y1&&y>seg.y2))){break;}}}
if(details){best={distance:best.distance,x0:best.x,y0:best.y,x1:x,y1:y};}else{best=best.distance;}}else if(geometry instanceof OpenLayers.Geometry.LineString){var segs0=this.getSortedSegments();var segs1=geometry.getSortedSegments();var seg0,seg1,intersection,x0,y0;var len1=segs1.length;var interOptions={point:true};outer:for(var i=0,len=segs0.length;i<len;++i){seg0=segs0[i];x0=seg0.x1;y0=seg0.y1;for(var j=0;j<len1;++j){seg1=segs1[j];intersection=OpenLayers.Geometry.segmentsIntersect(seg0,seg1,interOptions);if(intersection){min=0;best={distance:0,x0:intersection.x,y0:intersection.y,x1:intersection.x,y1:intersection.y};break outer;}else{result=OpenLayers.Geometry.distanceToSegment({x:x0,y:y0},seg1);if(result.distance<min){min=result.distance;best={distance:min,x0:x0,y0:y0,x1:result.x,y1:result.y};}}}}
if(!details){best=best.distance;}
if(min!==0){if(seg0){result=geometry.distanceTo(new OpenLayers.Geometry.Point(seg0.x2,seg0.y2),options);var dist=details?result.distance:result;if(dist<min){if(details){best={distance:min,x0:result.x1,y0:result.y1,x1:result.x0,y1:result.y0};}else{best=dist;}}}}}else{best=geometry.distanceTo(this,options);if(details){best={distance:best.distance,x0:best.x1,y0:best.y1,x1:best.x0,y1:best.y0};}}
return best;},CLASS_NAME:"OpenLayers.Geometry.LineString"});OpenLayers.Control.TransformFeature=OpenLayers.Class(OpenLayers.Control,{EVENT_TYPES:["beforesetfeature","setfeature","beforetransform","transform","transformcomplete"],geometryTypes:null,layer:null,preserveAspectRatio:false,rotate:true,feature:null,renderIntent:"temporary",rotationHandleSymbolizer:null,box:null,center:null,scale:1,ratio:1,rotation:0,handles:null,rotationHandles:null,dragControl:null,initialize:function(layer,options){this.EVENT_TYPES=OpenLayers.Control.TransformFeature.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES);OpenLayers.Control.prototype.initialize.apply(this,[options]);this.layer=layer;if(!this.rotationHandleSymbolizer){this.rotationHandleSymbolizer={stroke:false,pointRadius:10,fillOpacity:0,cursor:"pointer"};}
this.createBox();this.createControl();},activate:function(){var activated=false;if(OpenLayers.Control.prototype.activate.apply(this,arguments)){this.dragControl.activate();this.layer.addFeatures([this.box]);this.rotate&&this.layer.addFeatures(this.rotationHandles);this.layer.addFeatures(this.handles);activated=true;}
return activated;},deactivate:function(){var deactivated=false;if(OpenLayers.Control.prototype.deactivate.apply(this,arguments)){this.layer.removeFeatures(this.handles);this.rotate&&this.layer.removeFeatures(this.rotationHandles);this.layer.removeFeatures([this.box]);this.dragControl.deactivate();deactivated=true;}
return deactivated;},setMap:function(map){this.dragControl.setMap(map);OpenLayers.Control.prototype.setMap.apply(this,arguments);},setFeature:function(feature,initialParams){initialParams=OpenLayers.Util.applyDefaults(initialParams,{rotation:0,scale:1,ratio:1});var evt={feature:feature};var oldRotation=this.rotation;var oldCenter=this.center;OpenLayers.Util.extend(this,initialParams);if(this.events.triggerEvent("beforesetfeature",evt)===false){return;}
this.feature=feature;this.activate();this._setfeature=true;var featureBounds=this.feature.geometry.getBounds();this.box.move(featureBounds.getCenterLonLat());this.box.geometry.rotate(-oldRotation,oldCenter);this._angle=0;var ll;if(this.rotation){var geom=feature.geometry.clone();geom.rotate(-this.rotation,this.center);var box=new OpenLayers.Feature.Vector(geom.getBounds().toGeometry());box.geometry.rotate(this.rotation,this.center);this.box.geometry.rotate(this.rotation,this.center);this.box.move(box.geometry.getBounds().getCenterLonLat());var llGeom=box.geometry.components[0].components[0];ll=llGeom.getBounds().getCenterLonLat();}else{ll=new OpenLayers.LonLat(featureBounds.left,featureBounds.bottom);}
this.handles[0].move(ll);delete this._setfeature;this.events.triggerEvent("setfeature",evt);},createBox:function(){var control=this;this.center=new OpenLayers.Geometry.Point(0,0);var box=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString([new OpenLayers.Geometry.Point(-1,-1),new OpenLayers.Geometry.Point(0,-1),new OpenLayers.Geometry.Point(1,-1),new OpenLayers.Geometry.Point(1,0),new OpenLayers.Geometry.Point(1,1),new OpenLayers.Geometry.Point(0,1),new OpenLayers.Geometry.Point(-1,1),new OpenLayers.Geometry.Point(-1,0),new OpenLayers.Geometry.Point(-1,-1)]),null,typeof this.renderIntent=="string"?null:this.renderIntent);box.geometry.move=function(x,y){control._moving=true;OpenLayers.Geometry.LineString.prototype.move.apply(this,arguments);control.center.move(x,y);delete control._moving;};var vertexMoveFn=function(x,y){OpenLayers.Geometry.Point.prototype.move.apply(this,arguments);this._rotationHandle&&this._rotationHandle.geometry.move(x,y);this._handle.geometry.move(x,y);};var vertexResizeFn=function(scale,center,ratio){OpenLayers.Geometry.Point.prototype.resize.apply(this,arguments);this._rotationHandle&&this._rotationHandle.geometry.resize(scale,center,ratio);this._handle.geometry.resize(scale,center,ratio);};var vertexRotateFn=function(angle,center){OpenLayers.Geometry.Point.prototype.rotate.apply(this,arguments);this._rotationHandle&&this._rotationHandle.geometry.rotate(angle,center);this._handle.geometry.rotate(angle,center);};var handleMoveFn=function(x,y){var oldX=this.x,oldY=this.y;OpenLayers.Geometry.Point.prototype.move.call(this,x,y);if(control._moving){return;}
var evt=control.dragControl.handlers.drag.evt;var preserveAspectRatio=!control._setfeature&&control.preserveAspectRatio;var reshape=!preserveAspectRatio&&!(evt&&evt.shiftKey);var oldGeom=new OpenLayers.Geometry.Point(oldX,oldY);var centerGeometry=control.center;this.rotate(-control.rotation,centerGeometry);oldGeom.rotate(-control.rotation,centerGeometry);var dx1=this.x-centerGeometry.x;var dy1=this.y-centerGeometry.y;var dx0=dx1-(this.x-oldGeom.x);var dy0=dy1-(this.y-oldGeom.y);this.x=oldX;this.y=oldY;var scale,ratio=1;if(reshape){scale=Math.abs(dy0)<0.00001?1:dy1/dy0;ratio=(Math.abs(dx0)<0.00001?1:(dx1/dx0))/scale;}else{var l0=Math.sqrt((dx0*dx0)+(dy0*dy0));var l1=Math.sqrt((dx1*dx1)+(dy1*dy1));scale=l1/l0;}
control._moving=true;control.box.geometry.rotate(-control.rotation,centerGeometry);delete control._moving;control.box.geometry.resize(scale,centerGeometry,ratio);control.box.geometry.rotate(control.rotation,centerGeometry);control.transformFeature({scale:scale,ratio:ratio});};var rotationHandleMoveFn=function(x,y){var oldX=this.x,oldY=this.y;OpenLayers.Geometry.Point.prototype.move.call(this,x,y);if(control._moving){return;}
var evt=control.dragControl.handlers.drag.evt;var constrain=(evt&&evt.shiftKey)?45:1;var centerGeometry=control.center;var dx1=this.x-centerGeometry.x;var dy1=this.y-centerGeometry.y;var dx0=dx1-x;var dy0=dy1-y;this.x=oldX;this.y=oldY;var a0=Math.atan2(dy0,dx0);var a1=Math.atan2(dy1,dx1);var angle=a1-a0;angle*=180/Math.PI;control._angle=(control._angle+angle)%360;var diff=control.rotation%constrain;if(Math.abs(control._angle)>=constrain||diff!==0){angle=Math.round(control._angle/constrain)*constrain-
diff;control._angle=0;control.box.geometry.rotate(angle,centerGeometry);control.transformFeature({rotation:angle});}};var handles=new Array(8);var rotationHandles=new Array(4);var geom,handle,rotationHandle;for(var i=0;i<8;++i){geom=box.geometry.components[i];handle=new OpenLayers.Feature.Vector(geom.clone(),null,typeof this.renderIntent=="string"?null:this.renderIntent);if(i%2==0){rotationHandle=new OpenLayers.Feature.Vector(geom.clone(),null,typeof this.rotationHandleSymbolizer=="string"?null:this.rotationHandleSymbolizer);rotationHandle.geometry.move=rotationHandleMoveFn;geom._rotationHandle=rotationHandle;rotationHandles[i/2]=rotationHandle;}
geom.move=vertexMoveFn;geom.resize=vertexResizeFn;geom.rotate=vertexRotateFn;handle.geometry.move=handleMoveFn;geom._handle=handle;handles[i]=handle;}
this.box=box;this.rotationHandles=rotationHandles;this.handles=handles;},createControl:function(){var control=this;this.dragControl=new OpenLayers.Control.DragFeature(this.layer,{documentDrag:true,moveFeature:function(pixel){if(this.feature===control.feature){this.feature=control.box;}
OpenLayers.Control.DragFeature.prototype.moveFeature.apply(this,arguments);},onDrag:function(feature,pixel){if(feature===control.box){control.transformFeature({center:control.center});control.drawHandles();}},onStart:function(feature,pixel){var eligible=!control.geometryTypes||OpenLayers.Util.indexOf(control.geometryTypes,feature.geometry.CLASS_NAME)!==-1;var i=OpenLayers.Util.indexOf(control.handles,feature);i+=OpenLayers.Util.indexOf(control.rotationHandles,feature);if(feature!==control.feature&&feature!==control.box&&i==-2&&eligible){control.setFeature(feature);}},onComplete:function(feature,pixel){control.events.triggerEvent("transformcomplete",{feature:control.feature});}});},drawHandles:function(){var layer=this.layer;for(var i=0;i<8;++i){if(this.rotate&&i%2===0){layer.drawFeature(this.rotationHandles[i/2],this.rotationHandleSymbolizer);}
layer.drawFeature(this.handles[i],this.renderIntent);}},transformFeature:function(mods){if(!this._setfeature){this.scale*=(mods.scale||1);this.ratio*=(mods.ratio||1);var oldRotation=this.rotation;this.rotation=(this.rotation+(mods.rotation||0))%360;if(this.events.triggerEvent("beforetransform",mods)!==false){var feature=this.feature;var geom=feature.geometry;var center=this.center;geom.rotate(-oldRotation,center);if(mods.scale||mods.ratio){geom.resize(mods.scale,center,mods.ratio);}else if(mods.center){feature.move(mods.center.getBounds().getCenterLonLat());}
geom.rotate(this.rotation,center);this.layer.drawFeature(feature);feature.toState(OpenLayers.State.UPDATE);this.events.triggerEvent("transform",mods);}}
this.layer.drawFeature(this.box,this.renderIntent);this.drawHandles();},destroy:function(){var geom;for(var i=0;i<8;++i){geom=this.box.geometry.components[i];geom._handle.destroy();geom._handle=null;geom._rotationHandle&&geom._rotationHandle.destroy();geom._rotationHandle=null;}
this.box.destroy();this.box=null;this.layer=null;this.dragControl.destroy();OpenLayers.Control.prototype.destroy.apply(this,arguments);},CLASS_NAME:"OpenLayers.Control.TransformFeature"});OpenLayers.Format.GPX=OpenLayers.Class(OpenLayers.Format.XML,{extractWaypoints:true,extractTracks:true,extractRoutes:true,extractAttributes:true,initialize:function(options){this.externalProjection=new OpenLayers.Projection("EPSG:4326");OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(doc){if(typeof doc=="string"){doc=OpenLayers.Format.XML.prototype.read.apply(this,[doc]);}
var features=[];if(this.extractTracks){var tracks=doc.getElementsByTagName("trk");for(var i=0,len=tracks.length;i<len;i++){var attrs={};if(this.extractAttributes){attrs=this.parseAttributes(tracks[i]);}
var segs=this.getElementsByTagNameNS(tracks[i],tracks[i].namespaceURI,"trkseg");for(var j=0,seglen=segs.length;j<seglen;j++){var track=this.extractSegment(segs[j],"trkpt");features.push(new OpenLayers.Feature.Vector(track,attrs));}}}
if(this.extractRoutes){var routes=doc.getElementsByTagName("rte");for(var k=0,klen=routes.length;k<klen;k++){var attrs={};if(this.extractAttributes){attrs=this.parseAttributes(routes[k]);}
var route=this.extractSegment(routes[k],"rtept");features.push(new OpenLayers.Feature.Vector(route,attrs));}}
if(this.extractWaypoints){var waypoints=doc.getElementsByTagName("wpt");for(var l=0,len=waypoints.length;l<len;l++){var attrs={};if(this.extractAttributes){attrs=this.parseAttributes(waypoints[l]);}
var wpt=new OpenLayers.Geometry.Point(waypoints[l].getAttribute("lon"),waypoints[l].getAttribute("lat"));features.push(new OpenLayers.Feature.Vector(wpt,attrs));}}
if(this.internalProjection&&this.externalProjection){for(var g=0,featLength=features.length;g<featLength;g++){features[g].geometry.transform(this.externalProjection,this.internalProjection);}}
return features;},extractSegment:function(segment,segmentType){var points=this.getElementsByTagNameNS(segment,segment.namespaceURI,segmentType);var point_features=[];for(var i=0,len=points.length;i<len;i++){point_features.push(new OpenLayers.Geometry.Point(points[i].getAttribute("lon"),points[i].getAttribute("lat")));}
return new OpenLayers.Geometry.LineString(point_features);},parseAttributes:function(node){var attributes={};var attrNode=node.firstChild;while(attrNode){if(attrNode.nodeType==1){var value=attrNode.firstChild;if(value.nodeType==3||value.nodeType==4){name=(attrNode.prefix)?attrNode.nodeName.split(":")[1]:attrNode.nodeName;if(name!="trkseg"&&name!="rtept"){attributes[name]=value.nodeValue;}}}
attrNode=attrNode.nextSibling;}
return attributes;},CLASS_NAME:"OpenLayers.Format.GPX"});OpenLayers.Geometry.LinearRing=OpenLayers.Class(OpenLayers.Geometry.LineString,{componentTypes:["OpenLayers.Geometry.Point"],initialize:function(points){OpenLayers.Geometry.LineString.prototype.initialize.apply(this,arguments);},addComponent:function(point,index){var added=false;var lastPoint=this.components.pop();if(index!=null||!point.equals(lastPoint)){added=OpenLayers.Geometry.Collection.prototype.addComponent.apply(this,arguments);}
var firstPoint=this.components[0];OpenLayers.Geometry.Collection.prototype.addComponent.apply(this,[firstPoint]);return added;},removeComponent:function(point){if(this.components.length>4){this.components.pop();OpenLayers.Geometry.Collection.prototype.removeComponent.apply(this,arguments);var firstPoint=this.components[0];OpenLayers.Geometry.Collection.prototype.addComponent.apply(this,[firstPoint]);}},move:function(x,y){for(var i=0,len=this.components.length;i<len-1;i++){this.components[i].move(x,y);}},rotate:function(angle,origin){for(var i=0,len=this.components.length;i<len-1;++i){this.components[i].rotate(angle,origin);}},resize:function(scale,origin,ratio){for(var i=0,len=this.components.length;i<len-1;++i){this.components[i].resize(scale,origin,ratio);}
return this;},transform:function(source,dest){if(source&&dest){for(var i=0,len=this.components.length;i<len-1;i++){var component=this.components[i];component.transform(source,dest);}
this.bounds=null;}
return this;},getCentroid:function(){if(this.components&&(this.components.length>2)){var sumX=0.0;var sumY=0.0;for(var i=0;i<this.components.length-1;i++){var b=this.components[i];var c=this.components[i+1];sumX+=(b.x+c.x)*(b.x*c.y-c.x*b.y);sumY+=(b.y+c.y)*(b.x*c.y-c.x*b.y);}
var area=-1*this.getArea();var x=sumX/(6*area);var y=sumY/(6*area);return new OpenLayers.Geometry.Point(x,y);}else{return null;}},getArea:function(){var area=0.0;if(this.components&&(this.components.length>2)){var sum=0.0;for(var i=0,len=this.components.length;i<len-1;i++){var b=this.components[i];var c=this.components[i+1];sum+=(b.x+c.x)*(c.y-b.y);}
area=-sum/2.0;}
return area;},getGeodesicArea:function(projection){var ring=this;if(projection){var gg=new OpenLayers.Projection("EPSG:4326");if(!gg.equals(projection)){ring=this.clone().transform(projection,gg);}}
var area=0.0;var len=ring.components&&ring.components.length;if(len>2){var p1,p2;for(var i=0;i<len-1;i++){p1=ring.components[i];p2=ring.components[i+1];area+=OpenLayers.Util.rad(p2.x-p1.x)*(2+Math.sin(OpenLayers.Util.rad(p1.y))+
Math.sin(OpenLayers.Util.rad(p2.y)));}
area=area*6378137.0*6378137.0/2.0;}
return area;},containsPoint:function(point){var approx=OpenLayers.Number.limitSigDigs;var digs=14;var px=approx(point.x,digs);var py=approx(point.y,digs);function getX(y,x1,y1,x2,y2){return(((x1-x2)*y)+((x2*y1)-(x1*y2)))/(y1-y2);}
var numSeg=this.components.length-1;var start,end,x1,y1,x2,y2,cx,cy;var crosses=0;for(var i=0;i<numSeg;++i){start=this.components[i];x1=approx(start.x,digs);y1=approx(start.y,digs);end=this.components[i+1];x2=approx(end.x,digs);y2=approx(end.y,digs);if(y1==y2){if(py==y1){if(x1<=x2&&(px>=x1&&px<=x2)||x1>=x2&&(px<=x1&&px>=x2)){crosses=-1;break;}}
continue;}
cx=approx(getX(py,x1,y1,x2,y2),digs);if(cx==px){if(y1<y2&&(py>=y1&&py<=y2)||y1>y2&&(py<=y1&&py>=y2)){crosses=-1;break;}}
if(cx<=px){continue;}
if(x1!=x2&&(cx<Math.min(x1,x2)||cx>Math.max(x1,x2))){continue;}
if(y1<y2&&(py>=y1&&py<y2)||y1>y2&&(py<y1&&py>=y2)){++crosses;}}
var contained=(crosses==-1)?1:!!(crosses&1);return contained;},intersects:function(geometry){var intersect=false;if(geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){intersect=this.containsPoint(geometry);}else if(geometry.CLASS_NAME=="OpenLayers.Geometry.LineString"){intersect=geometry.intersects(this);}else if(geometry.CLASS_NAME=="OpenLayers.Geometry.LinearRing"){intersect=OpenLayers.Geometry.LineString.prototype.intersects.apply(this,[geometry]);}else{for(var i=0,len=geometry.components.length;i<len;++i){intersect=geometry.components[i].intersects(this);if(intersect){break;}}}
return intersect;},getVertices:function(nodes){return(nodes===true)?[]:this.components.slice(0,this.components.length-1);},CLASS_NAME:"OpenLayers.Geometry.LinearRing"});OpenLayers.Geometry.MultiLineString=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.LineString"],initialize:function(components){OpenLayers.Geometry.Collection.prototype.initialize.apply(this,arguments);},split:function(geometry,options){var results=null;var mutual=options&&options.mutual;var splits,sourceLine,sourceLines,sourceSplit,targetSplit;var sourceParts=[];var targetParts=[geometry];for(var i=0,len=this.components.length;i<len;++i){sourceLine=this.components[i];sourceSplit=false;for(var j=0;j<targetParts.length;++j){splits=sourceLine.split(targetParts[j],options);if(splits){if(mutual){sourceLines=splits[0];for(var k=0,klen=sourceLines.length;k<klen;++k){if(k===0&&sourceParts.length){sourceParts[sourceParts.length-1].addComponent(sourceLines[k]);}else{sourceParts.push(new OpenLayers.Geometry.MultiLineString([sourceLines[k]]));}}
sourceSplit=true;splits=splits[1];}
if(splits.length){splits.unshift(j,1);Array.prototype.splice.apply(targetParts,splits);break;}}}
if(!sourceSplit){if(sourceParts.length){sourceParts[sourceParts.length-1].addComponent(sourceLine.clone());}else{sourceParts=[new OpenLayers.Geometry.MultiLineString(sourceLine.clone())];}}}
if(sourceParts&&sourceParts.length>1){sourceSplit=true;}else{sourceParts=[];}
if(targetParts&&targetParts.length>1){targetSplit=true;}else{targetParts=[];}
if(sourceSplit||targetSplit){if(mutual){results=[sourceParts,targetParts];}else{results=targetParts;}}
return results;},splitWith:function(geometry,options){var results=null;var mutual=options&&options.mutual;var splits,targetLine,sourceLines,sourceSplit,targetSplit,sourceParts,targetParts;if(geometry instanceof OpenLayers.Geometry.LineString){targetParts=[];sourceParts=[geometry];for(var i=0,len=this.components.length;i<len;++i){targetSplit=false;targetLine=this.components[i];for(var j=0;j<sourceParts.length;++j){splits=sourceParts[j].split(targetLine,options);if(splits){if(mutual){sourceLines=splits[0];if(sourceLines.length){sourceLines.unshift(j,1);Array.prototype.splice.apply(sourceParts,sourceLines);j+=sourceLines.length-2;}
splits=splits[1];if(splits.length===0){splits=[targetLine.clone()];}}
for(var k=0,klen=splits.length;k<klen;++k){if(k===0&&targetParts.length){targetParts[targetParts.length-1].addComponent(splits[k]);}else{targetParts.push(new OpenLayers.Geometry.MultiLineString([splits[k]]));}}
targetSplit=true;}}
if(!targetSplit){if(targetParts.length){targetParts[targetParts.length-1].addComponent(targetLine.clone());}else{targetParts=[new OpenLayers.Geometry.MultiLineString([targetLine.clone()])];}}}}else{results=geometry.split(this);}
if(sourceParts&&sourceParts.length>1){sourceSplit=true;}else{sourceParts=[];}
if(targetParts&&targetParts.length>1){targetSplit=true;}else{targetParts=[];}
if(sourceSplit||targetSplit){if(mutual){results=[sourceParts,targetParts];}else{results=targetParts;}}
return results;},CLASS_NAME:"OpenLayers.Geometry.MultiLineString"});OpenLayers.Handler.Path=OpenLayers.Class(OpenLayers.Handler.Point,{line:null,freehand:false,freehandToggle:'shiftKey',initialize:function(control,callbacks,options){OpenLayers.Handler.Point.prototype.initialize.apply(this,arguments);},createFeature:function(pixel){var lonlat=this.control.map.getLonLatFromPixel(pixel);this.point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));this.line=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString([this.point.geometry]));this.callback("create",[this.point.geometry,this.getSketch()]);this.point.geometry.clearBounds();this.layer.addFeatures([this.line,this.point],{silent:true});},destroyFeature:function(){OpenLayers.Handler.Point.prototype.destroyFeature.apply(this);this.line=null;},removePoint:function(){if(this.point){this.layer.removeFeatures([this.point]);}},addPoint:function(pixel){this.layer.removeFeatures([this.point]);var lonlat=this.control.map.getLonLatFromPixel(pixel);this.point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));this.line.geometry.addComponent(this.point.geometry,this.line.geometry.components.length);this.callback("point",[this.point.geometry,this.getGeometry()]);this.callback("modify",[this.point.geometry,this.getSketch()]);this.drawFeature();},freehandMode:function(evt){return(this.freehandToggle&&evt[this.freehandToggle])?!this.freehand:this.freehand;},modifyFeature:function(pixel){var lonlat=this.control.map.getLonLatFromPixel(pixel);this.point.geometry.x=lonlat.lon;this.point.geometry.y=lonlat.lat;this.callback("modify",[this.point.geometry,this.getSketch()]);this.point.geometry.clearBounds();this.drawFeature();},drawFeature:function(){this.layer.drawFeature(this.line,this.style);this.layer.drawFeature(this.point,this.style);},getSketch:function(){return this.line;},getGeometry:function(){var geometry=this.line&&this.line.geometry;if(geometry&&this.multi){geometry=new OpenLayers.Geometry.MultiLineString([geometry]);}
return geometry;},mousedown:function(evt){if(this.lastDown&&this.lastDown.equals(evt.xy)){return false;}
if(this.lastDown==null){if(this.persist){this.destroyFeature();}
this.createFeature(evt.xy);}else if((this.lastUp==null)||!this.lastUp.equals(evt.xy)){this.addPoint(evt.xy);}
this.mouseDown=true;this.lastDown=evt.xy;this.drawing=true;return false;},mousemove:function(evt){if(this.drawing){if(this.mouseDown&&this.freehandMode(evt)){this.addPoint(evt.xy);}else{this.modifyFeature(evt.xy);}}
return true;},mouseup:function(evt){this.mouseDown=false;if(this.drawing){if(this.freehandMode(evt)){this.removePoint();this.finalize();}else{if(this.lastUp==null){this.addPoint(evt.xy);}
this.lastUp=evt.xy;}
return false;}
return true;},dblclick:function(evt){if(!this.freehandMode(evt)){var index=this.line.geometry.components.length-1;this.line.geometry.removeComponent(this.line.geometry.components[index]);this.removePoint();this.finalize();}
return false;},CLASS_NAME:"OpenLayers.Handler.Path"});OpenLayers.Control.Split=OpenLayers.Class(OpenLayers.Control,{EVENT_TYPES:["beforesplit","split","aftersplit"],layer:null,source:null,sourceOptions:null,tolerance:null,edge:true,deferDelete:false,mutual:true,targetFilter:null,sourceFilter:null,handler:null,initialize:function(options){Array.prototype.push.apply(this.EVENT_TYPES,OpenLayers.Control.prototype.EVENT_TYPES);OpenLayers.Control.prototype.initialize.apply(this,[options]);this.options=options||{};if(this.options.source){this.setSource(this.options.source);}},setSource:function(layer){if(this.active){this.deactivate();if(this.handler){this.handler.destroy();delete this.handler;}
this.source=layer;this.activate();}else{this.source=layer;}},activate:function(){var activated=OpenLayers.Control.prototype.activate.call(this);if(activated){if(!this.source){if(!this.handler){this.handler=new OpenLayers.Handler.Path(this,{done:function(geometry){this.onSketchComplete({feature:new OpenLayers.Feature.Vector(geometry)});}},{layerOptions:this.sourceOptions});}
this.handler.activate();}else if(this.source.events){this.source.events.on({sketchcomplete:this.onSketchComplete,afterfeaturemodified:this.afterFeatureModified,scope:this});}}
return activated;},deactivate:function(){var deactivated=OpenLayers.Control.prototype.deactivate.call(this);if(deactivated){if(this.source&&this.source.events){this.layer.events.un({sketchcomplete:this.onSketchComplete,afterfeaturemodified:this.afterFeatureModified,scope:this});}}
return deactivated;},onSketchComplete:function(event){this.feature=null;return!this.considerSplit(event.feature);},afterFeatureModified:function(event){if(event.modified){var feature=event.feature;if(feature.geometry instanceof OpenLayers.Geometry.LineString||feature.geometry instanceof OpenLayers.Geometry.MultiLineString){this.feature=event.feature;this.considerSplit(event.feature);}}},removeByGeometry:function(features,geometry){for(var i=0,len=features.length;i<len;++i){if(features[i].geometry===geometry){features.splice(i,1);break;}}},isEligible:function(target){return(target.state!==OpenLayers.State.DELETE)&&(target.geometry instanceof OpenLayers.Geometry.LineString||target.geometry instanceof OpenLayers.Geometry.MultiLineString)&&(this.feature!==target)&&(!this.targetFilter||this.targetFilter.evaluate(target.attributes));},considerSplit:function(feature){var sourceSplit=false;var targetSplit=false;if(!this.sourceFilter||this.sourceFilter.evaluate(feature.attributes)){var features=this.layer&&this.layer.features||[];var target,results,proceed;var additions=[],removals=[];var mutual=(this.layer===this.source)&&this.mutual;var options={edge:this.edge,tolerance:this.tolerance,mutual:mutual};var sourceParts=[feature.geometry];var targetFeature,targetParts;var source,parts;for(var i=0,len=features.length;i<len;++i){targetFeature=features[i];if(this.isEligible(targetFeature)){targetParts=[targetFeature.geometry];for(var j=0;j<sourceParts.length;++j){source=sourceParts[j];for(var k=0;k<targetParts.length;++k){target=targetParts[k];if(source.getBounds().intersectsBounds(target.getBounds())){results=source.split(target,options);if(results){proceed=this.events.triggerEvent("beforesplit",{source:feature,target:targetFeature});if(proceed!==false){if(mutual){parts=results[0];if(parts.length>1){parts.unshift(j,1);Array.prototype.splice.apply(sourceParts,parts);j+=parts.length-3;}
results=results[1];}
if(results.length>1){results.unshift(k,1);Array.prototype.splice.apply(targetParts,results);k+=results.length-3;}}}}}}
if(targetParts&&targetParts.length>1){this.geomsToFeatures(targetFeature,targetParts);this.events.triggerEvent("split",{original:targetFeature,features:targetParts});Array.prototype.push.apply(additions,targetParts);removals.push(targetFeature);targetSplit=true;}}}
if(sourceParts&&sourceParts.length>1){this.geomsToFeatures(feature,sourceParts);this.events.triggerEvent("split",{original:feature,features:sourceParts});Array.prototype.push.apply(additions,sourceParts);removals.push(feature);sourceSplit=true;}
if(sourceSplit||targetSplit){if(this.deferDelete){var feat,destroys=[];for(var i=0,len=removals.length;i<len;++i){feat=removals[i];if(feat.state===OpenLayers.State.INSERT){destroys.push(feat);}else{feat.state=OpenLayers.State.DELETE;this.layer.drawFeature(feat);}}
this.layer.destroyFeatures(destroys,{silent:true});for(var i=0,len=additions.length;i<len;++i){additions[i].state=OpenLayers.State.INSERT;}}else{this.layer.destroyFeatures(removals,{silent:true});}
this.layer.addFeatures(additions,{silent:true});this.events.triggerEvent("aftersplit",{source:feature,features:additions});}}
return sourceSplit;},geomsToFeatures:function(feature,geoms){var clone=feature.clone();delete clone.geometry;var newFeature;for(var i=0,len=geoms.length;i<len;++i){newFeature=clone.clone();newFeature.geometry=geoms[i];newFeature.state=OpenLayers.State.INSERT;geoms[i]=newFeature;}},destroy:function(){if(this.active){this.deactivate();}
OpenLayers.Control.prototype.destroy.call(this);},CLASS_NAME:"OpenLayers.Control.Split"});OpenLayers.Geometry.Polygon=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.LinearRing"],initialize:function(components){OpenLayers.Geometry.Collection.prototype.initialize.apply(this,arguments);},getArea:function(){var area=0.0;if(this.components&&(this.components.length>0)){area+=Math.abs(this.components[0].getArea());for(var i=1,len=this.components.length;i<len;i++){area-=Math.abs(this.components[i].getArea());}}
return area;},getGeodesicArea:function(projection){var area=0.0;if(this.components&&(this.components.length>0)){area+=Math.abs(this.components[0].getGeodesicArea(projection));for(var i=1,len=this.components.length;i<len;i++){area-=Math.abs(this.components[i].getGeodesicArea(projection));}}
return area;},containsPoint:function(point){var numRings=this.components.length;var contained=false;if(numRings>0){contained=this.components[0].containsPoint(point);if(contained!==1){if(contained&&numRings>1){var hole;for(var i=1;i<numRings;++i){hole=this.components[i].containsPoint(point);if(hole){if(hole===1){contained=1;}else{contained=false;}
break;}}}}}
return contained;},intersects:function(geometry){var intersect=false;var i,len;if(geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){intersect=this.containsPoint(geometry);}else if(geometry.CLASS_NAME=="OpenLayers.Geometry.LineString"||geometry.CLASS_NAME=="OpenLayers.Geometry.LinearRing"){for(i=0,len=this.components.length;i<len;++i){intersect=geometry.intersects(this.components[i]);if(intersect){break;}}
if(!intersect){for(i=0,len=geometry.components.length;i<len;++i){intersect=this.containsPoint(geometry.components[i]);if(intersect){break;}}}}else{for(i=0,len=geometry.components.length;i<len;++i){intersect=this.intersects(geometry.components[i]);if(intersect){break;}}}
if(!intersect&&geometry.CLASS_NAME=="OpenLayers.Geometry.Polygon"){var ring=this.components[0];for(i=0,len=ring.components.length;i<len;++i){intersect=geometry.containsPoint(ring.components[i]);if(intersect){break;}}}
return intersect;},distanceTo:function(geometry,options){var edge=!(options&&options.edge===false);var result;if(!edge&&this.intersects(geometry)){result=0;}else{result=OpenLayers.Geometry.Collection.prototype.distanceTo.apply(this,[geometry,options]);}
return result;},CLASS_NAME:"OpenLayers.Geometry.Polygon"});OpenLayers.Geometry.Polygon.createRegularPolygon=function(origin,radius,sides,rotation){var angle=Math.PI*((1/sides)-(1/2));if(rotation){angle+=(rotation/180)*Math.PI;}
var rotatedAngle,x,y;var points=[];for(var i=0;i<sides;++i){rotatedAngle=angle+(i*2*Math.PI/sides);x=origin.x+(radius*Math.cos(rotatedAngle));y=origin.y+(radius*Math.sin(rotatedAngle));points.push(new OpenLayers.Geometry.Point(x,y));}
var ring=new OpenLayers.Geometry.LinearRing(points);return new OpenLayers.Geometry.Polygon([ring]);};OpenLayers.Format.GeoRSS=OpenLayers.Class(OpenLayers.Format.XML,{rssns:"http://backend.userland.com/rss2",featureNS:"http://mapserver.gis.umn.edu/mapserver",georssns:"http://www.georss.org/georss",geons:"http://www.w3.org/2003/01/geo/wgs84_pos#",featureTitle:"Untitled",featureDescription:"No Description",gmlParser:null,xy:false,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},createGeometryFromItem:function(item){var point=this.getElementsByTagNameNS(item,this.georssns,"point");var lat=this.getElementsByTagNameNS(item,this.geons,'lat');var lon=this.getElementsByTagNameNS(item,this.geons,'long');var line=this.getElementsByTagNameNS(item,this.georssns,"line");var polygon=this.getElementsByTagNameNS(item,this.georssns,"polygon");var where=this.getElementsByTagNameNS(item,this.georssns,"where");var box=this.getElementsByTagNameNS(item,this.georssns,"box");if(point.length>0||(lat.length>0&&lon.length>0)){var location;if(point.length>0){location=OpenLayers.String.trim(point[0].firstChild.nodeValue).split(/\s+/);if(location.length!=2){location=OpenLayers.String.trim(point[0].firstChild.nodeValue).split(/\s*,\s*/);}}else{location=[parseFloat(lat[0].firstChild.nodeValue),parseFloat(lon[0].firstChild.nodeValue)];}
var geometry=new OpenLayers.Geometry.Point(parseFloat(location[1]),parseFloat(location[0]));}else if(line.length>0){var coords=OpenLayers.String.trim(this.concatChildValues(line[0])).split(/\s+/);var components=[];var point;for(var i=0,len=coords.length;i<len;i+=2){point=new OpenLayers.Geometry.Point(parseFloat(coords[i+1]),parseFloat(coords[i]));components.push(point);}
geometry=new OpenLayers.Geometry.LineString(components);}else if(polygon.length>0){var coords=OpenLayers.String.trim(this.concatChildValues(polygon[0])).split(/\s+/);var components=[];var point;for(var i=0,len=coords.length;i<len;i+=2){point=new OpenLayers.Geometry.Point(parseFloat(coords[i+1]),parseFloat(coords[i]));components.push(point);}
geometry=new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing(components)]);}else if(where.length>0){if(!this.gmlParser){this.gmlParser=new OpenLayers.Format.GML({'xy':this.xy});}
var feature=this.gmlParser.parseFeature(where[0]);geometry=feature.geometry;}else if(box.length>0){var coords=OpenLayers.String.trim(box[0].firstChild.nodeValue).split(/\s+/);var components=[];var point;if(coords.length>3){point=new OpenLayers.Geometry.Point(parseFloat(coords[1]),parseFloat(coords[0]));components.push(point);point=new OpenLayers.Geometry.Point(parseFloat(coords[1]),parseFloat(coords[2]));components.push(point);point=new OpenLayers.Geometry.Point(parseFloat(coords[3]),parseFloat(coords[2]));components.push(point);point=new OpenLayers.Geometry.Point(parseFloat(coords[3]),parseFloat(coords[0]));components.push(point);point=new OpenLayers.Geometry.Point(parseFloat(coords[1]),parseFloat(coords[0]));components.push(point);}
geometry=new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing(components)]);}
if(geometry&&this.internalProjection&&this.externalProjection){geometry.transform(this.externalProjection,this.internalProjection);}
return geometry;},createFeatureFromItem:function(item){var geometry=this.createGeometryFromItem(item);var title=this.getChildValue(item,"*","title",this.featureTitle);var description=this.getChildValue(item,"*","description",this.getChildValue(item,"*","content",this.getChildValue(item,"*","summary",this.featureDescription)));var link=this.getChildValue(item,"*","link");if(!link){try{link=this.getElementsByTagNameNS(item,"*","link")[0].getAttribute("href");}catch(e){link=null;}}
var id=this.getChildValue(item,"*","id",null);var data={"title":title,"description":description,"link":link};var feature=new OpenLayers.Feature.Vector(geometry,data);feature.fid=id;return feature;},getChildValue:function(node,nsuri,name,def){var value;var eles=this.getElementsByTagNameNS(node,nsuri,name);if(eles&&eles[0]&&eles[0].firstChild&&eles[0].firstChild.nodeValue){value=eles[0].firstChild.nodeValue;}else{value=(def==undefined)?"":def;}
return value;},read:function(doc){if(typeof doc=="string"){doc=OpenLayers.Format.XML.prototype.read.apply(this,[doc]);}
var itemlist=null;itemlist=this.getElementsByTagNameNS(doc,'*','item');if(itemlist.length==0){itemlist=this.getElementsByTagNameNS(doc,'*','entry');}
var numItems=itemlist.length;var features=new Array(numItems);for(var i=0;i<numItems;i++){features[i]=this.createFeatureFromItem(itemlist[i]);}
return features;},write:function(features){var georss;if(features instanceof Array){georss=this.createElementNS(this.rssns,"rss");for(var i=0,len=features.length;i<len;i++){georss.appendChild(this.createFeatureXML(features[i]));}}else{georss=this.createFeatureXML(features);}
return OpenLayers.Format.XML.prototype.write.apply(this,[georss]);},createFeatureXML:function(feature){var geometryNode=this.buildGeometryNode(feature.geometry);var featureNode=this.createElementNS(this.rssns,"item");var titleNode=this.createElementNS(this.rssns,"title");titleNode.appendChild(this.createTextNode(feature.attributes.title?feature.attributes.title:""));var descNode=this.createElementNS(this.rssns,"description");descNode.appendChild(this.createTextNode(feature.attributes.description?feature.attributes.description:""));featureNode.appendChild(titleNode);featureNode.appendChild(descNode);if(feature.attributes.link){var linkNode=this.createElementNS(this.rssns,"link");linkNode.appendChild(this.createTextNode(feature.attributes.link));featureNode.appendChild(linkNode);}
for(var attr in feature.attributes){if(attr=="link"||attr=="title"||attr=="description"){continue;}
var attrText=this.createTextNode(feature.attributes[attr]);var nodename=attr;if(attr.search(":")!=-1){nodename=attr.split(":")[1];}
var attrContainer=this.createElementNS(this.featureNS,"feature:"+nodename);attrContainer.appendChild(attrText);featureNode.appendChild(attrContainer);}
featureNode.appendChild(geometryNode);return featureNode;},buildGeometryNode:function(geometry){if(this.internalProjection&&this.externalProjection){geometry=geometry.clone();geometry.transform(this.internalProjection,this.externalProjection);}
var node;if(geometry.CLASS_NAME=="OpenLayers.Geometry.Polygon"){node=this.createElementNS(this.georssns,'georss:polygon');node.appendChild(this.buildCoordinatesNode(geometry.components[0]));}
else if(geometry.CLASS_NAME=="OpenLayers.Geometry.LineString"){node=this.createElementNS(this.georssns,'georss:line');node.appendChild(this.buildCoordinatesNode(geometry));}
else if(geometry.CLASS_NAME=="OpenLayers.Geometry.Point"){node=this.createElementNS(this.georssns,'georss:point');node.appendChild(this.buildCoordinatesNode(geometry));}else{throw"Couldn't parse "+geometry.CLASS_NAME;}
return node;},buildCoordinatesNode:function(geometry){var points=null;if(geometry.components){points=geometry.components;}
var path;if(points){var numPoints=points.length;var parts=new Array(numPoints);for(var i=0;i<numPoints;i++){parts[i]=points[i].y+" "+points[i].x;}
path=parts.join(" ");}else{path=geometry.y+" "+geometry.x;}
return this.createTextNode(path);},CLASS_NAME:"OpenLayers.Format.GeoRSS"});OpenLayers.Format.KML=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{kml:"http://www.opengis.net/kml/2.2",gx:"http://www.google.com/kml/ext/2.2"},kmlns:"http://earth.google.com/kml/2.0",placemarksDesc:"No description available",foldersName:"OpenLayers export",foldersDesc:"Exported on "+new Date(),extractAttributes:true,extractStyles:false,extractTracks:false,trackAttributes:null,internalns:null,features:null,styles:null,styleBaseUrl:"",fetched:null,maxDepth:0,initialize:function(options){this.regExes={trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g),kmlColor:(/(\w{2})(\w{2})(\w{2})(\w{2})/),kmlIconPalette:(/root:\/\/icons\/palette-(\d+)(\.\w+)/),straightBracket:(/\$\[(.*?)\]/g)};this.externalProjection=new OpenLayers.Projection("EPSG:4326");OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){this.features=[];this.styles={};this.fetched={};var options={depth:0,styleBaseUrl:this.styleBaseUrl};return this.parseData(data,options);},parseData:function(data,options){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var types=["Link","NetworkLink","Style","StyleMap","Placemark"];for(var i=0,len=types.length;i<len;++i){var type=types[i];var nodes=this.getElementsByTagNameNS(data,"*",type);if(nodes.length==0){continue;}
switch(type.toLowerCase()){case"link":case"networklink":this.parseLinks(nodes,options);break;case"style":if(this.extractStyles){this.parseStyles(nodes,options);}
break;case"stylemap":if(this.extractStyles){this.parseStyleMaps(nodes,options);}
break;case"placemark":this.parseFeatures(nodes,options);break;}}
return this.features;},parseLinks:function(nodes,options){if(options.depth>=this.maxDepth){return false;}
var newOptions=OpenLayers.Util.extend({},options);newOptions.depth++;for(var i=0,len=nodes.length;i<len;i++){var href=this.parseProperty(nodes[i],"*","href");if(href&&!this.fetched[href]){this.fetched[href]=true;var data=this.fetchLink(href);if(data){this.parseData(data,newOptions);}}}},fetchLink:function(href){var request=OpenLayers.Request.GET({url:href,async:false});if(request){return request.responseText;}},parseStyles:function(nodes,options){for(var i=0,len=nodes.length;i<len;i++){var style=this.parseStyle(nodes[i]);if(style){var styleName=(options.styleBaseUrl||"")+"#"+style.id;this.styles[styleName]=style;}}},parseKmlColor:function(kmlColor){var color=null;if(kmlColor){var matches=kmlColor.match(this.regExes.kmlColor);if(matches){color={color:'#'+matches[4]+matches[3]+matches[2],opacity:parseInt(matches[1],16)/255};}}
return color;},parseStyle:function(node){var style={};var types=["LineStyle","PolyStyle","IconStyle","BalloonStyle","LabelStyle"];var type,nodeList,geometry,parser;for(var i=0,len=types.length;i<len;++i){type=types[i];styleTypeNode=this.getElementsByTagNameNS(node,"*",type)[0];if(!styleTypeNode){continue;}
switch(type.toLowerCase()){case"linestyle":var kmlColor=this.parseProperty(styleTypeNode,"*","color");var color=this.parseKmlColor(kmlColor);if(color){style["strokeColor"]=color.color;style["strokeOpacity"]=color.opacity;}
var width=this.parseProperty(styleTypeNode,"*","width");if(width){style["strokeWidth"]=width;}
break;case"polystyle":var kmlColor=this.parseProperty(styleTypeNode,"*","color");var color=this.parseKmlColor(kmlColor);if(color){style["fillOpacity"]=color.opacity;style["fillColor"]=color.color;}
var fill=this.parseProperty(styleTypeNode,"*","fill");if(fill=="0"){style["fillColor"]="none";}
var outline=this.parseProperty(styleTypeNode,"*","outline");if(outline=="0"){style["strokeWidth"]="0";}
break;case"iconstyle":var scale=parseFloat(this.parseProperty(styleTypeNode,"*","scale")||1);var width=32*scale;var height=32*scale;var iconNode=this.getElementsByTagNameNS(styleTypeNode,"*","Icon")[0];if(iconNode){var href=this.parseProperty(iconNode,"*","href");if(href){var w=this.parseProperty(iconNode,"*","w");var h=this.parseProperty(iconNode,"*","h");var google="http://maps.google.com/mapfiles/kml";if(OpenLayers.String.startsWith(href,google)&&!w&&!h){w=64;h=64;scale=scale/2;}
w=w||h;h=h||w;if(w){width=parseInt(w)*scale;}
if(h){height=parseInt(h)*scale;}
var matches=href.match(this.regExes.kmlIconPalette);if(matches){var palette=matches[1];var file_extension=matches[2];var x=this.parseProperty(iconNode,"*","x");var y=this.parseProperty(iconNode,"*","y");var posX=x?x/32:0;var posY=y?(7-y/32):7;var pos=posY*8+posX;href="http://maps.google.com/mapfiles/kml/pal"
+palette+"/icon"+pos+file_extension;}
style["graphicOpacity"]=1;style["externalGraphic"]=href;}}
var hotSpotNode=this.getElementsByTagNameNS(styleTypeNode,"*","hotSpot")[0];if(hotSpotNode){var x=parseFloat(hotSpotNode.getAttribute("x"));var y=parseFloat(hotSpotNode.getAttribute("y"));var xUnits=hotSpotNode.getAttribute("xunits");if(xUnits=="pixels"){style["graphicXOffset"]=-x*scale;}
else if(xUnits=="insetPixels"){style["graphicXOffset"]=-width+(x*scale);}
else if(xUnits=="fraction"){style["graphicXOffset"]=-width*x;}
var yUnits=hotSpotNode.getAttribute("yunits");if(yUnits=="pixels"){style["graphicYOffset"]=-height+(y*scale)+1;}
else if(yUnits=="insetPixels"){style["graphicYOffset"]=-(y*scale)+1;}
else if(yUnits=="fraction"){style["graphicYOffset"]=-height*(1-y)+1;}}
style["graphicWidth"]=width;style["graphicHeight"]=height;break;case"balloonstyle":var balloonStyle=OpenLayers.Util.getXmlNodeValue(styleTypeNode);if(balloonStyle){style["balloonStyle"]=balloonStyle.replace(this.regExes.straightBracket,"${$1}");}
break;case"labelstyle":var kmlColor=this.parseProperty(styleTypeNode,"*","color");var color=this.parseKmlColor(kmlColor);if(color){style["fontColor"]=color.color;style["fontOpacity"]=color.opacity;}
break;default:}}
if(!style["strokeColor"]&&style["fillColor"]){style["strokeColor"]=style["fillColor"];}
var id=node.getAttribute("id");if(id&&style){style.id=id;}
return style;},parseStyleMaps:function(nodes,options){for(var i=0,len=nodes.length;i<len;i++){var node=nodes[i];var pairs=this.getElementsByTagNameNS(node,"*","Pair");var id=node.getAttribute("id");for(var j=0,jlen=pairs.length;j<jlen;j++){var pair=pairs[j];var key=this.parseProperty(pair,"*","key");var styleUrl=this.parseProperty(pair,"*","styleUrl");if(styleUrl&&key=="normal"){this.styles[(options.styleBaseUrl||"")+"#"+id]=this.styles[(options.styleBaseUrl||"")+styleUrl];}
if(styleUrl&&key=="highlight"){}}}},parseFeatures:function(nodes,options){var features=[];for(var i=0,len=nodes.length;i<len;i++){var featureNode=nodes[i];var feature=this.parseFeature.apply(this,[featureNode]);if(feature){if(this.extractStyles&&feature.attributes&&feature.attributes.styleUrl){feature.style=this.getStyle(feature.attributes.styleUrl,options);}
if(this.extractStyles){var inlineStyleNode=this.getElementsByTagNameNS(featureNode,"*","Style")[0];if(inlineStyleNode){var inlineStyle=this.parseStyle(inlineStyleNode);if(inlineStyle){feature.style=OpenLayers.Util.extend(feature.style,inlineStyle);}}}
if(this.extractTracks){var tracks=this.getElementsByTagNameNS(featureNode,this.namespaces.gx,"Track");if(tracks&&tracks.length>0){var track=tracks[0];var container={features:[],feature:feature};this.readNode(track,container);if(container.features.length>0){features.push.apply(features,container.features);}}}else{features.push(feature);}}else{throw"Bad Placemark: "+i;}}
this.features=this.features.concat(features);},readers:{"kml":{"when":function(node,container){container.whens.push(OpenLayers.Date.parse(this.getChildValue(node)));},"_trackPointAttribute":function(node,container){var name=node.nodeName.split(":").pop();container.attributes[name].push(this.getChildValue(node));}},"gx":{"Track":function(node,container){var obj={whens:[],points:[],angles:[]};if(this.trackAttributes){var name;obj.attributes={};for(var i=0,ii=this.trackAttributes.length;i<ii;++i){name=this.trackAttributes[i];obj.attributes[name]=[];if(!(name in this.readers.kml)){this.readers.kml[name]=this.readers.kml._trackPointAttribute;}}}
this.readChildNodes(node,obj);if(obj.whens.length!==obj.points.length){throw new Error("gx:Track with unequal number of when ("+obj.whens.length+") and gx:coord ("+obj.points.length+") elements.");}
var hasAngles=obj.angles.length>0;if(hasAngles&&obj.whens.length!==obj.angles.length){throw new Error("gx:Track with unequal number of when ("+obj.whens.length+") and gx:angles ("+obj.angles.length+") elements.");}
var feature,point,angles;for(var i=0,ii=obj.whens.length;i<ii;++i){feature=container.feature.clone();feature.fid=container.feature.fid||container.feature.id;point=obj.points[i];feature.geometry=point;if("z"in point){feature.attributes.altitude=point.z;}
if(this.internalProjection&&this.externalProjection){feature.geometry.transform(this.externalProjection,this.internalProjection);}
if(this.trackAttributes){for(var j=0,jj=this.trackAttributes.length;j<jj;++j){feature.attributes[name]=obj.attributes[this.trackAttributes[j]][i];}}
feature.attributes.when=obj.whens[i];feature.attributes.trackId=container.feature.id;if(hasAngles){angles=obj.angles[i];feature.attributes.heading=parseFloat(angles[0]);feature.attributes.tilt=parseFloat(angles[1]);feature.attributes.roll=parseFloat(angles[2]);}
container.features.push(feature);}},"coord":function(node,container){var str=this.getChildValue(node);var coords=str.replace(this.regExes.trimSpace,"").split(/\s+/);var point=new OpenLayers.Geometry.Point(coords[0],coords[1]);if(coords.length>2){point.z=parseFloat(coords[2]);}
container.points.push(point);},"angles":function(node,container){var str=this.getChildValue(node);var parts=str.replace(this.regExes.trimSpace,"").split(/\s+/);container.angles.push(parts);}}},parseFeature:function(node){var order=["MultiGeometry","Polygon","LineString","Point"];var type,nodeList,geometry,parser;for(var i=0,len=order.length;i<len;++i){type=order[i];this.internalns=node.namespaceURI?node.namespaceURI:this.kmlns;nodeList=this.getElementsByTagNameNS(node,this.internalns,type);if(nodeList.length>0){var parser=this.parseGeometry[type.toLowerCase()];if(parser){geometry=parser.apply(this,[nodeList[0]]);if(this.internalProjection&&this.externalProjection){geometry.transform(this.externalProjection,this.internalProjection);}}else{OpenLayers.Console.error(OpenLayers.i18n("unsupportedGeometryType",{'geomType':type}));}
break;}}
var attributes;if(this.extractAttributes){attributes=this.parseAttributes(node);}
var feature=new OpenLayers.Feature.Vector(geometry,attributes);var fid=node.getAttribute("id")||node.getAttribute("name");if(fid!=null){feature.fid=fid;}
return feature;},getStyle:function(styleUrl,options){var styleBaseUrl=OpenLayers.Util.removeTail(styleUrl);var newOptions=OpenLayers.Util.extend({},options);newOptions.depth++;newOptions.styleBaseUrl=styleBaseUrl;if(!this.styles[styleUrl]&&!OpenLayers.String.startsWith(styleUrl,"#")&&newOptions.depth<=this.maxDepth&&!this.fetched[styleBaseUrl]){var data=this.fetchLink(styleBaseUrl);if(data){this.parseData(data,newOptions);}}
var style=OpenLayers.Util.extend({},this.styles[styleUrl]);return style;},parseGeometry:{point:function(node){var nodeList=this.getElementsByTagNameNS(node,this.internalns,"coordinates");var coords=[];if(nodeList.length>0){var coordString=nodeList[0].firstChild.nodeValue;coordString=coordString.replace(this.regExes.removeSpace,"");coords=coordString.split(",");}
var point=null;if(coords.length>1){if(coords.length==2){coords[2]=null;}
point=new OpenLayers.Geometry.Point(coords[0],coords[1],coords[2]);}else{throw"Bad coordinate string: "+coordString;}
return point;},linestring:function(node,ring){var nodeList=this.getElementsByTagNameNS(node,this.internalns,"coordinates");var line=null;if(nodeList.length>0){var coordString=this.getChildValue(nodeList[0]);coordString=coordString.replace(this.regExes.trimSpace,"");coordString=coordString.replace(this.regExes.trimComma,",");var pointList=coordString.split(this.regExes.splitSpace);var numPoints=pointList.length;var points=new Array(numPoints);var coords,numCoords;for(var i=0;i<numPoints;++i){coords=pointList[i].split(",");numCoords=coords.length;if(numCoords>1){if(coords.length==2){coords[2]=null;}
points[i]=new OpenLayers.Geometry.Point(coords[0],coords[1],coords[2]);}else{throw"Bad LineString point coordinates: "+
pointList[i];}}
if(numPoints){if(ring){line=new OpenLayers.Geometry.LinearRing(points);}else{line=new OpenLayers.Geometry.LineString(points);}}else{throw"Bad LineString coordinates: "+coordString;}}
return line;},polygon:function(node){var nodeList=this.getElementsByTagNameNS(node,this.internalns,"LinearRing");var numRings=nodeList.length;var components=new Array(numRings);if(numRings>0){var ring;for(var i=0,len=nodeList.length;i<len;++i){ring=this.parseGeometry.linestring.apply(this,[nodeList[i],true]);if(ring){components[i]=ring;}else{throw"Bad LinearRing geometry: "+i;}}}
return new OpenLayers.Geometry.Polygon(components);},multigeometry:function(node){var child,parser;var parts=[];var children=node.childNodes;for(var i=0,len=children.length;i<len;++i){child=children[i];if(child.nodeType==1){var type=(child.prefix)?child.nodeName.split(":")[1]:child.nodeName;var parser=this.parseGeometry[type.toLowerCase()];if(parser){parts.push(parser.apply(this,[child]));}}}
return new OpenLayers.Geometry.Collection(parts);}},parseAttributes:function(node){var attributes={};var edNodes=node.getElementsByTagName("ExtendedData");if(edNodes.length){attributes=this.parseExtendedData(edNodes[0]);}
var child,grandchildren,grandchild;var children=node.childNodes;for(var i=0,len=children.length;i<len;++i){child=children[i];if(child.nodeType==1){grandchildren=child.childNodes;if(grandchildren.length>=1&&grandchildren.length<=3){var grandchild;switch(grandchildren.length){case 1:grandchild=grandchildren[0];break;case 2:var c1=grandchildren[0];var c2=grandchildren[1];grandchild=(c1.nodeType==3||c1.nodeType==4)?c1:c2;break;case 3:default:grandchild=grandchildren[1];break;}
if(grandchild.nodeType==3||grandchild.nodeType==4){var name=(child.prefix)?child.nodeName.split(":")[1]:child.nodeName;var value=OpenLayers.Util.getXmlNodeValue(grandchild);if(value){value=value.replace(this.regExes.trimSpace,"");attributes[name]=value;}}}}}
return attributes;},parseExtendedData:function(node){var attributes={};var i,len,data,key;var dataNodes=node.getElementsByTagName("Data");for(i=0,len=dataNodes.length;i<len;i++){data=dataNodes[i];key=data.getAttribute("name");var ed={};var valueNode=data.getElementsByTagName("value");if(valueNode.length){ed['value']=this.getChildValue(valueNode[0]);}
var nameNode=data.getElementsByTagName("displayName");if(nameNode.length){ed['displayName']=this.getChildValue(nameNode[0]);}
attributes[key]=ed;}
var simpleDataNodes=node.getElementsByTagName("SimpleData");for(i=0,len=simpleDataNodes.length;i<len;i++){var ed={};data=simpleDataNodes[i];key=data.getAttribute("name");ed['value']=this.getChildValue(data);ed['displayName']=key;attributes[key]=ed;}
return attributes;},parseProperty:function(xmlNode,namespace,tagName){var value;var nodeList=this.getElementsByTagNameNS(xmlNode,namespace,tagName);try{value=OpenLayers.Util.getXmlNodeValue(nodeList[0]);}catch(e){value=null;}
return value;},write:function(features){if(!(features instanceof Array)){features=[features];}
var kml=this.createElementNS(this.kmlns,"kml");var folder=this.createFolderXML();for(var i=0,len=features.length;i<len;++i){folder.appendChild(this.createPlacemarkXML(features[i]));}
kml.appendChild(folder);return OpenLayers.Format.XML.prototype.write.apply(this,[kml]);},createFolderXML:function(){var folder=this.createElementNS(this.kmlns,"Folder");if(this.foldersName){var folderName=this.createElementNS(this.kmlns,"name");var folderNameText=this.createTextNode(this.foldersName);folderName.appendChild(folderNameText);folder.appendChild(folderName);}
if(this.foldersDesc){var folderDesc=this.createElementNS(this.kmlns,"description");var folderDescText=this.createTextNode(this.foldersDesc);folderDesc.appendChild(folderDescText);folder.appendChild(folderDesc);}
return folder;},createPlacemarkXML:function(feature){var placemarkName=this.createElementNS(this.kmlns,"name");var name=feature.style&&feature.style.label?feature.style.label:feature.attributes.name||feature.id;placemarkName.appendChild(this.createTextNode(name));var placemarkDesc=this.createElementNS(this.kmlns,"description");var desc=feature.attributes.description||this.placemarksDesc;placemarkDesc.appendChild(this.createTextNode(desc));var placemarkNode=this.createElementNS(this.kmlns,"Placemark");if(feature.fid!=null){placemarkNode.setAttribute("id",feature.fid);}
placemarkNode.appendChild(placemarkName);placemarkNode.appendChild(placemarkDesc);var geometryNode=this.buildGeometryNode(feature.geometry);placemarkNode.appendChild(geometryNode);return placemarkNode;},buildGeometryNode:function(geometry){if(this.internalProjection&&this.externalProjection){geometry=geometry.clone();geometry.transform(this.internalProjection,this.externalProjection);}
var className=geometry.CLASS_NAME;var type=className.substring(className.lastIndexOf(".")+1);var builder=this.buildGeometry[type.toLowerCase()];var node=null;if(builder){node=builder.apply(this,[geometry]);}
return node;},buildGeometry:{point:function(geometry){var kml=this.createElementNS(this.kmlns,"Point");kml.appendChild(this.buildCoordinatesNode(geometry));return kml;},multipoint:function(geometry){return this.buildGeometry.collection.apply(this,[geometry]);},linestring:function(geometry){var kml=this.createElementNS(this.kmlns,"LineString");kml.appendChild(this.buildCoordinatesNode(geometry));return kml;},multilinestring:function(geometry){return this.buildGeometry.collection.apply(this,[geometry]);},linearring:function(geometry){var kml=this.createElementNS(this.kmlns,"LinearRing");kml.appendChild(this.buildCoordinatesNode(geometry));return kml;},polygon:function(geometry){var kml=this.createElementNS(this.kmlns,"Polygon");var rings=geometry.components;var ringMember,ringGeom,type;for(var i=0,len=rings.length;i<len;++i){type=(i==0)?"outerBoundaryIs":"innerBoundaryIs";ringMember=this.createElementNS(this.kmlns,type);ringGeom=this.buildGeometry.linearring.apply(this,[rings[i]]);ringMember.appendChild(ringGeom);kml.appendChild(ringMember);}
return kml;},multipolygon:function(geometry){return this.buildGeometry.collection.apply(this,[geometry]);},collection:function(geometry){var kml=this.createElementNS(this.kmlns,"MultiGeometry");var child;for(var i=0,len=geometry.components.length;i<len;++i){child=this.buildGeometryNode.apply(this,[geometry.components[i]]);if(child){kml.appendChild(child);}}
return kml;}},buildCoordinatesNode:function(geometry){var coordinatesNode=this.createElementNS(this.kmlns,"coordinates");var path;var points=geometry.components;if(points){var point;var numPoints=points.length;var parts=new Array(numPoints);for(var i=0;i<numPoints;++i){point=points[i];parts[i]=point.x+","+point.y;}
path=parts.join(" ");}else{path=geometry.x+","+geometry.y;}
var txtNode=this.createTextNode(path);coordinatesNode.appendChild(txtNode);return coordinatesNode;},CLASS_NAME:"OpenLayers.Format.KML"});OpenLayers.Format.OSM=OpenLayers.Class(OpenLayers.Format.XML,{checkTags:false,interestingTagsExclude:null,areaTags:null,initialize:function(options){var layer_defaults={'interestingTagsExclude':['source','source_ref','source:ref','history','attribution','created_by'],'areaTags':['area','building','leisure','tourism','ruins','historic','landuse','military','natural','sport']};layer_defaults=OpenLayers.Util.extend(layer_defaults,options);var interesting={};for(var i=0;i<layer_defaults.interestingTagsExclude.length;i++){interesting[layer_defaults.interestingTagsExclude[i]]=true;}
layer_defaults.interestingTagsExclude=interesting;var area={};for(var i=0;i<layer_defaults.areaTags.length;i++){area[layer_defaults.areaTags[i]]=true;}
layer_defaults.areaTags=area;this.externalProjection=new OpenLayers.Projection("EPSG:4326");OpenLayers.Format.XML.prototype.initialize.apply(this,[layer_defaults]);},read:function(doc){if(typeof doc=="string"){doc=OpenLayers.Format.XML.prototype.read.apply(this,[doc]);}
var nodes=this.getNodes(doc);var ways=this.getWays(doc);var feat_list=new Array(ways.length);for(var i=0;i<ways.length;i++){var point_list=new Array(ways[i].nodes.length);var poly=this.isWayArea(ways[i])?1:0;for(var j=0;j<ways[i].nodes.length;j++){var node=nodes[ways[i].nodes[j]];var point=new OpenLayers.Geometry.Point(node.lon,node.lat);point.osm_id=parseInt(ways[i].nodes[j]);point_list[j]=point;node.used=true;}
var geometry=null;if(poly){geometry=new OpenLayers.Geometry.Polygon(new OpenLayers.Geometry.LinearRing(point_list));}else{geometry=new OpenLayers.Geometry.LineString(point_list);}
if(this.internalProjection&&this.externalProjection){geometry.transform(this.externalProjection,this.internalProjection);}
var feat=new OpenLayers.Feature.Vector(geometry,ways[i].tags);feat.osm_id=parseInt(ways[i].id);feat.fid="way."+feat.osm_id;feat_list[i]=feat;}
for(var node_id in nodes){var node=nodes[node_id];if(!node.used||this.checkTags){var tags=null;if(this.checkTags){var result=this.getTags(node.node,true);if(node.used&&!result[1]){continue;}
tags=result[0];}else{tags=this.getTags(node.node);}
var feat=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(node['lon'],node['lat']),tags);if(this.internalProjection&&this.externalProjection){feat.geometry.transform(this.externalProjection,this.internalProjection);}
feat.osm_id=parseInt(node_id);feat.fid="node."+feat.osm_id;feat_list.push(feat);}
node.node=null;}
return feat_list;},getNodes:function(doc){var node_list=doc.getElementsByTagName("node");var nodes={};for(var i=0;i<node_list.length;i++){var node=node_list[i];var id=node.getAttribute("id");nodes[id]={'lat':node.getAttribute("lat"),'lon':node.getAttribute("lon"),'node':node};}
return nodes;},getWays:function(doc){var way_list=doc.getElementsByTagName("way");var return_ways=[];for(var i=0;i<way_list.length;i++){var way=way_list[i];var way_object={id:way.getAttribute("id")};way_object.tags=this.getTags(way);var node_list=way.getElementsByTagName("nd");way_object.nodes=new Array(node_list.length);for(var j=0;j<node_list.length;j++){way_object.nodes[j]=node_list[j].getAttribute("ref");}
return_ways.push(way_object);}
return return_ways;},getTags:function(dom_node,interesting_tags){var tag_list=dom_node.getElementsByTagName("tag");var tags={};var interesting=false;for(var j=0;j<tag_list.length;j++){var key=tag_list[j].getAttribute("k");tags[key]=tag_list[j].getAttribute("v");if(interesting_tags){if(!this.interestingTagsExclude[key]){interesting=true;}}}
return interesting_tags?[tags,interesting]:tags;},isWayArea:function(way){var poly_shaped=false;var poly_tags=false;if(way.nodes[0]==way.nodes[way.nodes.length-1]){poly_shaped=true;}
if(this.checkTags){for(var key in way.tags){if(this.areaTags[key]){poly_tags=true;break;}}}
return poly_shaped&&(this.checkTags?poly_tags:true);},write:function(features){if(!(features instanceof Array)){features=[features];}
this.osm_id=1;this.created_nodes={};var root_node=this.createElementNS(null,"osm");root_node.setAttribute("version","0.5");root_node.setAttribute("generator","OpenLayers "+OpenLayers.VERSION_NUMBER);for(var i=features.length-1;i>=0;i--){var nodes=this.createFeatureNodes(features[i]);for(var j=0;j<nodes.length;j++){root_node.appendChild(nodes[j]);}}
return OpenLayers.Format.XML.prototype.write.apply(this,[root_node]);},createFeatureNodes:function(feature){var nodes=[];var className=feature.geometry.CLASS_NAME;var type=className.substring(className.lastIndexOf(".")+1);type=type.toLowerCase();var builder=this.createXML[type];if(builder){nodes=builder.apply(this,[feature]);}
return nodes;},createXML:{'point':function(point){var id=null;var geometry=point.geometry?point.geometry:point;var already_exists=false;if(point.osm_id){id=point.osm_id;if(this.created_nodes[id]){already_exists=true;}}else{id=-this.osm_id;this.osm_id++;}
if(already_exists){node=this.created_nodes[id];}else{var node=this.createElementNS(null,"node");}
this.created_nodes[id]=node;node.setAttribute("id",id);node.setAttribute("lon",geometry.x);node.setAttribute("lat",geometry.y);if(point.attributes){this.serializeTags(point,node);}
this.setState(point,node);return already_exists?[]:[node];},linestring:function(feature){var nodes=[];var geometry=feature.geometry;if(feature.osm_id){id=feature.osm_id;}else{id=-this.osm_id;this.osm_id++;}
var way=this.createElementNS(null,"way");way.setAttribute("id",id);for(var i=0;i<geometry.components.length;i++){var node=this.createXML['point'].apply(this,[geometry.components[i]]);if(node.length){node=node[0];var node_ref=node.getAttribute("id");nodes.push(node);}else{node_ref=geometry.components[i].osm_id;node=this.created_nodes[node_ref];}
this.setState(feature,node);var nd_dom=this.createElementNS(null,"nd");nd_dom.setAttribute("ref",node_ref);way.appendChild(nd_dom);}
this.serializeTags(feature,way);nodes.push(way);return nodes;},polygon:function(feature){var attrs=OpenLayers.Util.extend({'area':'yes'},feature.attributes);var feat=new OpenLayers.Feature.Vector(feature.geometry.components[0],attrs);feat.osm_id=feature.osm_id;return this.createXML['linestring'].apply(this,[feat]);}},serializeTags:function(feature,node){for(var key in feature.attributes){var tag=this.createElementNS(null,"tag");tag.setAttribute("k",key);tag.setAttribute("v",feature.attributes[key]);node.appendChild(tag);}},setState:function(feature,node){if(feature.state){var state=null;switch(feature.state){case OpenLayers.State.UPDATE:state="modify";case OpenLayers.State.DELETE:state="delete";}
if(state){node.setAttribute("action",state);}}},CLASS_NAME:"OpenLayers.Format.OSM"});OpenLayers.Geometry.MultiPolygon=OpenLayers.Class(OpenLayers.Geometry.Collection,{componentTypes:["OpenLayers.Geometry.Polygon"],initialize:function(components){OpenLayers.Geometry.Collection.prototype.initialize.apply(this,arguments);},CLASS_NAME:"OpenLayers.Geometry.MultiPolygon"});OpenLayers.Handler.Polygon=OpenLayers.Class(OpenLayers.Handler.Path,{polygon:null,initialize:function(control,callbacks,options){OpenLayers.Handler.Path.prototype.initialize.apply(this,arguments);},createFeature:function(pixel){var lonlat=this.control.map.getLonLatFromPixel(pixel);this.point=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonlat.lon,lonlat.lat));this.line=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LinearRing([this.point.geometry]));this.polygon=new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([this.line.geometry]));this.callback("create",[this.point.geometry,this.getSketch()]);this.point.geometry.clearBounds();this.layer.addFeatures([this.polygon,this.point],{silent:true});},destroyFeature:function(){OpenLayers.Handler.Path.prototype.destroyFeature.apply(this);this.polygon=null;},drawFeature:function(){this.layer.drawFeature(this.polygon,this.style);this.layer.drawFeature(this.point,this.style);},getSketch:function(){return this.polygon;},getGeometry:function(){var geometry=this.polygon&&this.polygon.geometry;if(geometry&&this.multi){geometry=new OpenLayers.Geometry.MultiPolygon([geometry]);}
return geometry;},dblclick:function(evt){if(!this.freehandMode(evt)){var index=this.line.geometry.components.length-2;this.line.geometry.removeComponent(this.line.geometry.components[index]);this.removePoint();this.finalize();}
return false;},CLASS_NAME:"OpenLayers.Handler.Polygon"});OpenLayers.Control.EditingToolbar=OpenLayers.Class(OpenLayers.Control.Panel,{initialize:function(layer,options){OpenLayers.Control.Panel.prototype.initialize.apply(this,[options]);this.addControls([new OpenLayers.Control.Navigation()]);var controls=[new OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.Point,{'displayClass':'olControlDrawFeaturePoint'}),new OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.Path,{'displayClass':'olControlDrawFeaturePath'}),new OpenLayers.Control.DrawFeature(layer,OpenLayers.Handler.Polygon,{'displayClass':'olControlDrawFeaturePolygon'})];this.addControls(controls);},draw:function(){var div=OpenLayers.Control.Panel.prototype.draw.apply(this,arguments);this.activateControl(this.controls[0]);return div;},CLASS_NAME:"OpenLayers.Control.EditingToolbar"});OpenLayers.Control.SLDSelect=OpenLayers.Class(OpenLayers.Control,{EVENT_TYPES:["selected"],clearOnDeactivate:false,layers:null,callbacks:null,selectionSymbolizer:{'Polygon':{fillColor:'#FF0000',stroke:false},'Line':{strokeColor:'#FF0000',strokeWidth:2},'Point':{graphicName:'square',fillColor:'#FF0000',pointRadius:5}},layerOptions:null,handlerOptions:null,sketchStyle:null,wfsCache:{},layerCache:{},initialize:function(handler,options){this.EVENT_TYPES=OpenLayers.Control.SLDSelect.prototype.EVENT_TYPES.concat(OpenLayers.Control.prototype.EVENT_TYPES);OpenLayers.Control.prototype.initialize.apply(this,[options]);this.callbacks=OpenLayers.Util.extend({done:this.select,click:this.select},this.callbacks);this.handlerOptions=this.handlerOptions||{};this.layerOptions=OpenLayers.Util.applyDefaults(this.layerOptions,{displayInLayerSwitcher:false});if(this.sketchStyle){this.handlerOptions.layerOptions=OpenLayers.Util.applyDefaults(this.handlerOptions.layerOptions,{styleMap:new OpenLayers.StyleMap({"default":this.sketchStyle})});}
this.handler=new handler(this,this.callbacks,this.handlerOptions);},destroy:function(){for(var key in this.layerCache){delete this.layerCache[key];}
for(var key in this.wfsCache){delete this.wfsCache[key];}
OpenLayers.Control.prototype.destroy.apply(this,arguments);},coupleLayerVisiblity:function(evt){this.setVisibility(evt.object.getVisibility());},createSelectionLayer:function(source){var selectionLayer;if(!this.layerCache[source.id]){selectionLayer=new OpenLayers.Layer.WMS.Post(source.name,source.url,source.params,OpenLayers.Util.applyDefaults(this.layerOptions,source.getOptions()));this.layerCache[source.id]=selectionLayer;if(this.layerOptions.displayInLayerSwitcher===false){source.events.on({"visibilitychanged":this.coupleLayerVisiblity,scope:selectionLayer});}
this.map.addLayer(selectionLayer);}else{selectionLayer=this.layerCache[source.id];}
return selectionLayer;},createSLD:function(layer,filters,geometryAttributes){var sld={version:"1.0.0",namedLayers:{}};var layerNames=[layer.params.LAYERS].join(",").split(",");for(var i=0,len=layerNames.length;i<len;i++){var name=layerNames[i];sld.namedLayers[name]={name:name,userStyles:[]};var symbolizer=this.selectionSymbolizer;var geometryAttribute=geometryAttributes[i];if(geometryAttribute.type.indexOf('Polygon')>=0){symbolizer={Polygon:this.selectionSymbolizer['Polygon']};}else if(geometryAttribute.type.indexOf('LineString')>=0){symbolizer={Line:this.selectionSymbolizer['Line']};}else if(geometryAttribute.type.indexOf('Point')>=0){symbolizer={Point:this.selectionSymbolizer['Point']};}
var filter=filters[i];sld.namedLayers[name].userStyles.push({name:'default',rules:[new OpenLayers.Rule({symbolizer:symbolizer,filter:filter,maxScaleDenominator:layer.options.minScale})]});}
return new OpenLayers.Format.SLD().write(sld);},parseDescribeLayer:function(request){var format=new OpenLayers.Format.WMSDescribeLayer();var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
var describeLayer=format.read(doc);var typeNames=[];var url=null;for(var i=0,len=describeLayer.length;i<len;i++){if(describeLayer[i].owsType=="WFS"){typeNames.push(describeLayer[i].typeName);url=describeLayer[i].owsURL;}}
var options={url:url,params:{SERVICE:"WFS",TYPENAME:typeNames.toString(),REQUEST:"DescribeFeatureType",VERSION:"1.0.0"},callback:function(request){var format=new OpenLayers.Format.WFSDescribeFeatureType();var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
var describeFeatureType=format.read(doc);this.control.wfsCache[this.layer.id]=describeFeatureType;this.control._queue&&this.control.applySelection();},scope:this};OpenLayers.Request.GET(options);},getGeometryAttributes:function(layer){var result=[];var cache=this.wfsCache[layer.id];for(var i=0,len=cache.featureTypes.length;i<len;i++){var typeName=cache.featureTypes[i];var properties=typeName.properties;for(var j=0,lenj=properties.length;j<lenj;j++){var property=properties[j];var type=property.type;if((type.indexOf('LineString')>=0)||(type.indexOf('GeometryAssociationType')>=0)||(type.indexOf('GeometryPropertyType')>=0)||(type.indexOf('Point')>=0)||(type.indexOf('Polygon')>=0)){result.push(property);}}}
return result;},activate:function(){var activated=OpenLayers.Control.prototype.activate.call(this);if(activated){for(var i=0,len=this.layers.length;i<len;i++){var layer=this.layers[i];if(layer&&!this.wfsCache[layer.id]){var options={url:layer.url,params:{SERVICE:"WMS",VERSION:layer.params.VERSION,LAYERS:layer.params.LAYERS,REQUEST:"DescribeLayer"},callback:this.parseDescribeLayer,scope:{layer:layer,control:this}};OpenLayers.Request.GET(options);}}}
return activated;},deactivate:function(){var deactivated=OpenLayers.Control.prototype.deactivate.call(this);if(deactivated){for(var i=0,len=this.layers.length;i<len;i++){var layer=this.layers[i];if(layer&&this.clearOnDeactivate===true){var layerCache=this.layerCache;var selectionLayer=layerCache[layer.id];if(selectionLayer){layer.events.un({"visibilitychanged":this.coupleLayerVisiblity,scope:selectionLayer});selectionLayer.destroy();delete layerCache[layer.id];}}}}
return deactivated;},setLayers:function(layers){if(this.active){this.deactivate();this.layers=layers;this.activate();}else{this.layers=layers;}},createFilter:function(geometryAttribute,geometry){var filter=null;if(this.handler instanceof OpenLayers.Handler.RegularPolygon){if(this.handler.irregular===true){filter=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.BBOX,property:geometryAttribute.name,value:geometry.getBounds()});}else{filter=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.INTERSECTS,property:geometryAttribute.name,value:geometry});}}else if(this.handler instanceof OpenLayers.Handler.Polygon){filter=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.INTERSECTS,property:geometryAttribute.name,value:geometry});}else if(this.handler instanceof OpenLayers.Handler.Path){if(geometryAttribute.type.indexOf('Point')>=0){filter=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.DWITHIN,property:geometryAttribute.name,distance:this.map.getExtent().getWidth()*0.01,distanceUnits:this.map.getUnits(),value:geometry});}else{filter=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.INTERSECTS,property:geometryAttribute.name,value:geometry});}}else if(this.handler instanceof OpenLayers.Handler.Click){if(geometryAttribute.type.indexOf('Polygon')>=0){filter=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.INTERSECTS,property:geometryAttribute.name,value:geometry});}else{filter=new OpenLayers.Filter.Spatial({type:OpenLayers.Filter.Spatial.DWITHIN,property:geometryAttribute.name,distance:this.map.getExtent().getWidth()*0.01,distanceUnits:this.map.getUnits(),value:geometry});}}
return filter;},select:function(geometry){this._queue=function(){for(var i=0,len=this.layers.length;i<len;i++){var layer=this.layers[i];var geometryAttributes=this.getGeometryAttributes(layer);var filters=[];for(var j=0,lenj=geometryAttributes.length;j<lenj;j++){var geometryAttribute=geometryAttributes[j];if(geometryAttribute!==null){if(!(geometry instanceof OpenLayers.Geometry)){var point=this.map.getLonLatFromPixel(geometry.xy);geometry=new OpenLayers.Geometry.Point(point.lon,point.lat);}
var filter=this.createFilter(geometryAttribute,geometry);if(filter!==null){filters.push(filter);}}}
var selectionLayer=this.createSelectionLayer(layer);var sld=this.createSLD(layer,filters,geometryAttributes);this.events.triggerEvent("selected",{layer:layer,filters:filters});selectionLayer.mergeNewParams({SLD_BODY:sld});delete this._queue;}};this.applySelection();},applySelection:function(){var canApply=true;for(var i=0,len=this.layers.length;i<len;i++){if(!this.wfsCache[this.layers[i].id]){canApply=false;break;}}
canApply&&this._queue.call(this);},CLASS_NAME:"OpenLayers.Control.SLDSelect"});OpenLayers.Format.ArcXML=OpenLayers.Class(OpenLayers.Format.XML,{fontStyleKeys:['antialiasing','blockout','font','fontcolor','fontsize','fontstyle','glowing','interval','outline','printmode','shadow','transparency'],request:null,response:null,initialize:function(options){this.request=new OpenLayers.Format.ArcXML.Request();this.response=new OpenLayers.Format.ArcXML.Response();if(options){if(options.requesttype=="feature"){this.request.get_image=null;var qry=this.request.get_feature.query;this.addCoordSys(qry.featurecoordsys,options.featureCoordSys);this.addCoordSys(qry.filtercoordsys,options.filterCoordSys);if(options.polygon){qry.isspatial=true;qry.spatialfilter.polygon=options.polygon;}else if(options.envelope){qry.isspatial=true;qry.spatialfilter.envelope={minx:0,miny:0,maxx:0,maxy:0};this.parseEnvelope(qry.spatialfilter.envelope,options.envelope);}}else if(options.requesttype=="image"){this.request.get_feature=null;var props=this.request.get_image.properties;this.parseEnvelope(props.envelope,options.envelope);this.addLayers(props.layerlist,options.layers);this.addImageSize(props.imagesize,options.tileSize);this.addCoordSys(props.featurecoordsys,options.featureCoordSys);this.addCoordSys(props.filtercoordsys,options.filterCoordSys);}else{this.request=null;}}
OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},parseEnvelope:function(env,arr){if(arr&&arr.length==4){env.minx=arr[0];env.miny=arr[1];env.maxx=arr[2];env.maxy=arr[3];}},addLayers:function(ll,lyrs){for(var lind=0,len=lyrs.length;lind<len;lind++){ll.push(lyrs[lind]);}},addImageSize:function(imsize,olsize){if(olsize!==null){imsize.width=olsize.w;imsize.height=olsize.h;imsize.printwidth=olsize.w;imsize.printheight=olsize.h;}},addCoordSys:function(featOrFilt,fsys){if(typeof fsys=="string"){featOrFilt.id=parseInt(fsys);featOrFilt.string=fsys;}
else if(typeof fsys=="object"&&fsys.proj!==null){featOrFilt.id=fsys.proj.srsProjNumber;featOrFilt.string=fsys.proj.srsCode;}else{featOrFilt=fsys;}},iserror:function(data){var ret=null;if(!data){ret=(this.response.error!=='');}else{data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);var errorNodes=data.documentElement.getElementsByTagName("ERROR");ret=(errorNodes!==null&&errorNodes.length>0);}
return ret;},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var arcNode=null;if(data&&data.documentElement){if(data.documentElement.nodeName=="ARCXML"){arcNode=data.documentElement;}else{arcNode=data.documentElement.getElementsByTagName("ARCXML")[0];}}
if(!arcNode||arcNode.firstChild.nodeName==='parsererror'){var error,source;try{error=data.firstChild.nodeValue;source=data.firstChild.childNodes[1].firstChild.nodeValue;}catch(err){}
throw{message:"Error parsing the ArcXML request",error:error,source:source};}
var response=this.parseResponse(arcNode);return response;},write:function(request){if(!request){request=this.request;}
var root=this.createElementNS("","ARCXML");root.setAttribute("version","1.1");var reqElem=this.createElementNS("","REQUEST");if(request.get_image!=null){var getElem=this.createElementNS("","GET_IMAGE");reqElem.appendChild(getElem);var propElem=this.createElementNS("","PROPERTIES");getElem.appendChild(propElem);var props=request.get_image.properties;if(props.featurecoordsys!=null){var feat=this.createElementNS("","FEATURECOORDSYS");propElem.appendChild(feat);if(props.featurecoordsys.id===0){feat.setAttribute("string",props.featurecoordsys['string']);}
else{feat.setAttribute("id",props.featurecoordsys.id);}}
if(props.filtercoordsys!=null){var filt=this.createElementNS("","FILTERCOORDSYS");propElem.appendChild(filt);if(props.filtercoordsys.id===0){filt.setAttribute("string",props.filtercoordsys.string);}
else{filt.setAttribute("id",props.filtercoordsys.id);}}
if(props.envelope!=null){var env=this.createElementNS("","ENVELOPE");propElem.appendChild(env);env.setAttribute("minx",props.envelope.minx);env.setAttribute("miny",props.envelope.miny);env.setAttribute("maxx",props.envelope.maxx);env.setAttribute("maxy",props.envelope.maxy);}
var imagesz=this.createElementNS("","IMAGESIZE");propElem.appendChild(imagesz);imagesz.setAttribute("height",props.imagesize.height);imagesz.setAttribute("width",props.imagesize.width);if(props.imagesize.height!=props.imagesize.printheight||props.imagesize.width!=props.imagesize.printwidth){imagesz.setAttribute("printheight",props.imagesize.printheight);imagesz.setArrtibute("printwidth",props.imagesize.printwidth);}
if(props.background!=null){var backgrnd=this.createElementNS("","BACKGROUND");propElem.appendChild(backgrnd);backgrnd.setAttribute("color",props.background.color.r+","+
props.background.color.g+","+
props.background.color.b);if(props.background.transcolor!==null){backgrnd.setAttribute("transcolor",props.background.transcolor.r+","+
props.background.transcolor.g+","+
props.background.transcolor.b);}}
if(props.layerlist!=null&&props.layerlist.length>0){var layerlst=this.createElementNS("","LAYERLIST");propElem.appendChild(layerlst);for(var ld=0;ld<props.layerlist.length;ld++){var ldef=this.createElementNS("","LAYERDEF");layerlst.appendChild(ldef);ldef.setAttribute("id",props.layerlist[ld].id);ldef.setAttribute("visible",props.layerlist[ld].visible);if(typeof props.layerlist[ld].query=="object"){var query=props.layerlist[ld].query;if(query.where.length<0){continue;}
var queryElem=null;if(typeof query.spatialfilter=="boolean"&&query.spatialfilter){queryElem=this.createElementNS("","SPATIALQUERY");}
else{queryElem=this.createElementNS("","QUERY");}
queryElem.setAttribute("where",query.where);if(typeof query.accuracy=="number"&&query.accuracy>0){queryElem.setAttribute("accuracy",query.accuracy);}
if(typeof query.featurelimit=="number"&&query.featurelimit<2000){queryElem.setAttribute("featurelimit",query.featurelimit);}
if(typeof query.subfields=="string"&&query.subfields!="#ALL#"){queryElem.setAttribute("subfields",query.subfields);}
if(typeof query.joinexpression=="string"&&query.joinexpression.length>0){queryElem.setAttribute("joinexpression",query.joinexpression);}
if(typeof query.jointables=="string"&&query.jointables.length>0){queryElem.setAttribute("jointables",query.jointables);}
ldef.appendChild(queryElem);}
if(typeof props.layerlist[ld].renderer=="object"){this.addRenderer(ldef,props.layerlist[ld].renderer);}}}}else if(request.get_feature!=null){var getElem=this.createElementNS("","GET_FEATURES");getElem.setAttribute("outputmode","newxml");getElem.setAttribute("checkesc","true");if(request.get_feature.geometry){getElem.setAttribute("geometry",request.get_feature.geometry);}
else{getElem.setAttribute("geometry","false");}
if(request.get_feature.compact){getElem.setAttribute("compact",request.get_feature.compact);}
if(request.get_feature.featurelimit=="number"){getElem.setAttribute("featurelimit",request.get_feature.featurelimit);}
getElem.setAttribute("globalenvelope","true");reqElem.appendChild(getElem);if(request.get_feature.layer!=null&&request.get_feature.layer.length>0){var lyrElem=this.createElementNS("","LAYER");lyrElem.setAttribute("id",request.get_feature.layer);getElem.appendChild(lyrElem);}
var fquery=request.get_feature.query;if(fquery!=null){var qElem=null;if(fquery.isspatial){qElem=this.createElementNS("","SPATIALQUERY");}else{qElem=this.createElementNS("","QUERY");}
getElem.appendChild(qElem);if(typeof fquery.accuracy=="number"){qElem.setAttribute("accuracy",fquery.accuracy);}
if(fquery.featurecoordsys!=null){var fcsElem1=this.createElementNS("","FEATURECOORDSYS");if(fquery.featurecoordsys.id==0){fcsElem1.setAttribute("string",fquery.featurecoordsys.string);}else{fcsElem1.setAttribute("id",fquery.featurecoordsys.id);}
qElem.appendChild(fcsElem1);}
if(fquery.filtercoordsys!=null){var fcsElem2=this.createElementNS("","FILTERCOORDSYS");if(fquery.filtercoordsys.id===0){fcsElem2.setAttribute("string",fquery.filtercoordsys.string);}else{fcsElem2.setAttribute("id",fquery.filtercoordsys.id);}
qElem.appendChild(fcsElem2);}
if(fquery.buffer>0){var bufElem=this.createElementNS("","BUFFER");bufElem.setAttribute("distance",fquery.buffer);qElem.appendChild(bufElem);}
if(fquery.isspatial){var spfElem=this.createElementNS("","SPATIALFILTER");spfElem.setAttribute("relation",fquery.spatialfilter.relation);qElem.appendChild(spfElem);if(fquery.spatialfilter.envelope){var envElem=this.createElementNS("","ENVELOPE");envElem.setAttribute("minx",fquery.spatialfilter.envelope.minx);envElem.setAttribute("miny",fquery.spatialfilter.envelope.miny);envElem.setAttribute("maxx",fquery.spatialfilter.envelope.maxx);envElem.setAttribute("maxy",fquery.spatialfilter.envelope.maxy);spfElem.appendChild(envElem);}else if(typeof fquery.spatialfilter.polygon=="object"){spfElem.appendChild(this.writePolygonGeometry(fquery.spatialfilter.polygon));}}
if(fquery.where!=null&&fquery.where.length>0){qElem.setAttribute("where",fquery.where);}}}
root.appendChild(reqElem);return OpenLayers.Format.XML.prototype.write.apply(this,[root]);},addGroupRenderer:function(ldef,toprenderer){var topRelem=this.createElementNS("","GROUPRENDERER");ldef.appendChild(topRelem);for(var rind=0;rind<toprenderer.length;rind++){var renderer=toprenderer[rind];this.addRenderer(topRelem,renderer);}},addRenderer:function(topRelem,renderer){if(renderer instanceof Array){this.addGroupRenderer(topRelem,renderer);}else{var renderElem=this.createElementNS("",renderer.type.toUpperCase()+"RENDERER");topRelem.appendChild(renderElem);if(renderElem.tagName=="VALUEMAPRENDERER"){this.addValueMapRenderer(renderElem,renderer);}else if(renderElem.tagName=="VALUEMAPLABELRENDERER"){this.addValueMapLabelRenderer(renderElem,renderer);}else if(renderElem.tagName=="SIMPLELABELRENDERER"){this.addSimpleLabelRenderer(renderElem,renderer);}else if(renderElem.tagName=="SCALEDEPENDENTRENDERER"){this.addScaleDependentRenderer(renderElem,renderer);}}},addScaleDependentRenderer:function(renderElem,renderer){if(typeof renderer.lower=="string"||typeof renderer.lower=="number"){renderElem.setAttribute("lower",renderer.lower);}
if(typeof renderer.upper=="string"||typeof renderer.upper=="number"){renderElem.setAttribute("upper",renderer.upper);}
this.addRenderer(renderElem,renderer.renderer);},addValueMapLabelRenderer:function(renderElem,renderer){renderElem.setAttribute("lookupfield",renderer.lookupfield);renderElem.setAttribute("labelfield",renderer.labelfield);if(typeof renderer.exacts=="object"){for(var ext=0,extlen=renderer.exacts.length;ext<extlen;ext++){var exact=renderer.exacts[ext];var eelem=this.createElementNS("","EXACT");if(typeof exact.value=="string"){eelem.setAttribute("value",exact.value);}
if(typeof exact.label=="string"){eelem.setAttribute("label",exact.label);}
if(typeof exact.method=="string"){eelem.setAttribute("method",exact.method);}
renderElem.appendChild(eelem);if(typeof exact.symbol=="object"){var selem=null;if(exact.symbol.type=="text"){selem=this.createElementNS("","TEXTSYMBOL");}
if(selem!=null){var keys=this.fontStyleKeys;for(var i=0,len=keys.length;i<len;i++){var key=keys[i];if(exact.symbol[key]){selem.setAttribute(key,exact.symbol[key]);}}
eelem.appendChild(selem);}}}}},addValueMapRenderer:function(renderElem,renderer){renderElem.setAttribute("lookupfield",renderer.lookupfield);if(typeof renderer.ranges=="object"){for(var rng=0,rnglen=renderer.ranges.length;rng<rnglen;rng++){var range=renderer.ranges[rng];var relem=this.createElementNS("","RANGE");relem.setAttribute("lower",range.lower);relem.setAttribute("upper",range.upper);renderElem.appendChild(relem);if(typeof range.symbol=="object"){var selem=null;if(range.symbol.type=="simplepolygon"){selem=this.createElementNS("","SIMPLEPOLYGONSYMBOL");}
if(selem!=null){if(typeof range.symbol.boundarycolor=="string"){selem.setAttribute("boundarycolor",range.symbol.boundarycolor);}
if(typeof range.symbol.fillcolor=="string"){selem.setAttribute("fillcolor",range.symbol.fillcolor);}
if(typeof range.symbol.filltransparency=="number"){selem.setAttribute("filltransparency",range.symbol.filltransparency);}
relem.appendChild(selem);}}}}else if(typeof renderer.exacts=="object"){for(var ext=0,extlen=renderer.exacts.length;ext<extlen;ext++){var exact=renderer.exacts[ext];var eelem=this.createElementNS("","EXACT");if(typeof exact.value=="string"){eelem.setAttribute("value",exact.value);}
if(typeof exact.label=="string"){eelem.setAttribute("label",exact.label);}
if(typeof exact.method=="string"){eelem.setAttribute("method",exact.method);}
renderElem.appendChild(eelem);if(typeof exact.symbol=="object"){var selem=null;if(exact.symbol.type=="simplemarker"){selem=this.createElementNS("","SIMPLEMARKERSYMBOL");}
if(selem!=null){if(typeof exact.symbol.antialiasing=="string"){selem.setAttribute("antialiasing",exact.symbol.antialiasing);}
if(typeof exact.symbol.color=="string"){selem.setAttribute("color",exact.symbol.color);}
if(typeof exact.symbol.outline=="string"){selem.setAttribute("outline",exact.symbol.outline);}
if(typeof exact.symbol.overlap=="string"){selem.setAttribute("overlap",exact.symbol.overlap);}
if(typeof exact.symbol.shadow=="string"){selem.setAttribute("shadow",exact.symbol.shadow);}
if(typeof exact.symbol.transparency=="number"){selem.setAttribute("transparency",exact.symbol.transparency);}
if(typeof exact.symbol.usecentroid=="string"){selem.setAttribute("usecentroid",exact.symbol.usecentroid);}
if(typeof exact.symbol.width=="number"){selem.setAttribute("width",exact.symbol.width);}
eelem.appendChild(selem);}}}}},addSimpleLabelRenderer:function(renderElem,renderer){renderElem.setAttribute("field",renderer.field);var keys=['featureweight','howmanylabels','labelbufferratio','labelpriorities','labelweight','linelabelposition','rotationalangles'];for(var i=0,len=keys.length;i<len;i++){var key=keys[i];if(renderer[key]){renderElem.setAttribute(key,renderer[key]);}}
if(renderer.symbol.type=="text"){var symbol=renderer.symbol;var selem=this.createElementNS("","TEXTSYMBOL");renderElem.appendChild(selem);var keys=this.fontStyleKeys;for(var i=0,len=keys.length;i<len;i++){var key=keys[i];if(symbol[key]){selem.setAttribute(key,renderer[key]);}}}},writePolygonGeometry:function(polygon){if(!(polygon instanceof OpenLayers.Geometry.Polygon)){throw{message:'Cannot write polygon geometry to ArcXML with an '+
polygon.CLASS_NAME+' object.',geometry:polygon};}
var polyElem=this.createElementNS("","POLYGON");for(var ln=0,lnlen=polygon.components.length;ln<lnlen;ln++){var ring=polygon.components[ln];var ringElem=this.createElementNS("","RING");for(var rn=0,rnlen=ring.components.length;rn<rnlen;rn++){var point=ring.components[rn];var pointElem=this.createElementNS("","POINT");pointElem.setAttribute("x",point.x);pointElem.setAttribute("y",point.y);ringElem.appendChild(pointElem);}
polyElem.appendChild(ringElem);}
return polyElem;},parseResponse:function(data){if(typeof data=="string"){var newData=new OpenLayers.Format.XML();data=newData.read(data);}
var response=new OpenLayers.Format.ArcXML.Response();var errorNode=data.getElementsByTagName("ERROR");if(errorNode!=null&&errorNode.length>0){response.error=this.getChildValue(errorNode,"Unknown error.");}else{var responseNode=data.getElementsByTagName("RESPONSE");if(responseNode==null||responseNode.length==0){response.error="No RESPONSE tag found in ArcXML response.";return response;}
var rtype=responseNode[0].firstChild.nodeName;if(rtype=="#text"){rtype=responseNode[0].firstChild.nextSibling.nodeName;}
if(rtype=="IMAGE"){var envelopeNode=data.getElementsByTagName("ENVELOPE");var outputNode=data.getElementsByTagName("OUTPUT");if(envelopeNode==null||envelopeNode.length==0){response.error="No ENVELOPE tag found in ArcXML response.";}else if(outputNode==null||outputNode.length==0){response.error="No OUTPUT tag found in ArcXML response.";}else{var envAttr=this.parseAttributes(envelopeNode[0]);var outputAttr=this.parseAttributes(outputNode[0]);if(typeof outputAttr.type=="string"){response.image={envelope:envAttr,output:{type:outputAttr.type,data:this.getChildValue(outputNode[0])}};}else{response.image={envelope:envAttr,output:outputAttr};}}}else if(rtype=="FEATURES"){var features=responseNode[0].getElementsByTagName("FEATURES");var featureCount=features[0].getElementsByTagName("FEATURECOUNT");response.features.featurecount=featureCount[0].getAttribute("count");if(response.features.featurecount>0){var envelope=features[0].getElementsByTagName("ENVELOPE");response.features.envelope=this.parseAttributes(envelope[0],typeof(0));var featureList=features[0].getElementsByTagName("FEATURE");for(var fn=0;fn<featureList.length;fn++){var feature=new OpenLayers.Feature.Vector();var fields=featureList[fn].getElementsByTagName("FIELD");for(var fdn=0;fdn<fields.length;fdn++){var fieldName=fields[fdn].getAttribute("name");var fieldValue=fields[fdn].getAttribute("value");feature.attributes[fieldName]=fieldValue;}
var geom=featureList[fn].getElementsByTagName("POLYGON");if(geom.length>0){var ring=geom[0].getElementsByTagName("RING");var polys=[];for(var rn=0;rn<ring.length;rn++){var linearRings=[];linearRings.push(this.parsePointGeometry(ring[rn]));var holes=ring[rn].getElementsByTagName("HOLE");for(var hn=0;hn<holes.length;hn++){linearRings.push(this.parsePointGeometry(holes[hn]));}
holes=null;polys.push(new OpenLayers.Geometry.Polygon(linearRings));linearRings=null;}
ring=null;if(polys.length==1){feature.geometry=polys[0];}else
{feature.geometry=new OpenLayers.Geometry.MultiPolygon(polys);}}
response.features.feature.push(feature);}}}else{response.error="Unidentified response type.";}}
return response;},parseAttributes:function(node,type){var attributes={};for(var attr=0;attr<node.attributes.length;attr++){if(type=="number"){attributes[node.attributes[attr].nodeName]=parseFloat(node.attributes[attr].nodeValue);}else{attributes[node.attributes[attr].nodeName]=node.attributes[attr].nodeValue;}}
return attributes;},parsePointGeometry:function(node){var ringPoints=[];var coords=node.getElementsByTagName("COORDS");if(coords.length>0){var coordArr=this.getChildValue(coords[0]);coordArr=coordArr.split(/;/);for(var cn=0;cn<coordArr.length;cn++){var coordItems=coordArr[cn].split(/ /);ringPoints.push(new OpenLayers.Geometry.Point(parseFloat(coordItems[0]),parseFloat(coordItems[1])));}
coords=null;}else{var point=node.getElementsByTagName("POINT");if(point.length>0){for(var pn=0;pn<point.length;pn++){ringPoints.push(new OpenLayers.Geometry.Point(parseFloat(point[pn].getAttribute("x")),parseFloat(point[pn].getAttribute("y"))));}}
point=null;}
return new OpenLayers.Geometry.LinearRing(ringPoints);},CLASS_NAME:"OpenLayers.Format.ArcXML"});OpenLayers.Format.ArcXML.Request=OpenLayers.Class({initialize:function(params){var defaults={get_image:{properties:{background:null,draw:true,envelope:{minx:0,miny:0,maxx:0,maxy:0},featurecoordsys:{id:0,string:"",datumtransformid:0,datumtransformstring:""},filtercoordsys:{id:0,string:"",datumtransformid:0,datumtransformstring:""},imagesize:{height:0,width:0,dpi:96,printheight:0,printwidth:0,scalesymbols:false},layerlist:[],output:{baseurl:"",legendbaseurl:"",legendname:"",legendpath:"",legendurl:"",name:"",path:"",type:"jpg",url:""}}},get_feature:{layer:"",query:{isspatial:false,featurecoordsys:{id:0,string:"",datumtransformid:0,datumtransformstring:""},filtercoordsys:{id:0,string:"",datumtransformid:0,datumtransformstring:""},buffer:0,where:"",spatialfilter:{relation:"envelope_intersection",envelope:null}}},environment:{separators:{cs:" ",ts:";"}},layer:[],workspaces:[]};return OpenLayers.Util.extend(this,defaults);},CLASS_NAME:"OpenLayers.Format.ArcXML.Request"});OpenLayers.Format.ArcXML.Response=OpenLayers.Class({initialize:function(params){var defaults={image:{envelope:null,output:''},features:{featurecount:0,envelope:null,feature:[]},error:''};return OpenLayers.Util.extend(this,defaults);},CLASS_NAME:"OpenLayers.Format.ArcXML.Response"});OpenLayers.Format.GML=OpenLayers.Class(OpenLayers.Format.XML,{featureNS:"http://mapserver.gis.umn.edu/mapserver",featurePrefix:"feature",featureName:"featureMember",layerName:"features",geometryName:"geometry",collectionName:"FeatureCollection",gmlns:"http://www.opengis.net/gml",extractAttributes:true,xy:true,initialize:function(options){this.regExes={trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)};OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
var featureNodes=this.getElementsByTagNameNS(data.documentElement,this.gmlns,this.featureName);var features=[];for(var i=0;i<featureNodes.length;i++){var feature=this.parseFeature(featureNodes[i]);if(feature){features.push(feature);}}
return features;},parseFeature:function(node){var order=["MultiPolygon","Polygon","MultiLineString","LineString","MultiPoint","Point","Envelope"];var type,nodeList,geometry,parser;for(var i=0;i<order.length;++i){type=order[i];nodeList=this.getElementsByTagNameNS(node,this.gmlns,type);if(nodeList.length>0){parser=this.parseGeometry[type.toLowerCase()];if(parser){geometry=parser.apply(this,[nodeList[0]]);if(this.internalProjection&&this.externalProjection){geometry.transform(this.externalProjection,this.internalProjection);}}else{OpenLayers.Console.error(OpenLayers.i18n("unsupportedGeometryType",{'geomType':type}));}
break;}}
var bounds;var boxNodes=this.getElementsByTagNameNS(node,this.gmlns,"Box");for(i=0;i<boxNodes.length;++i){var boxNode=boxNodes[i];var box=this.parseGeometry["box"].apply(this,[boxNode]);var parentNode=boxNode.parentNode;var parentName=parentNode.localName||parentNode.nodeName.split(":").pop();if(parentName==="boundedBy"){bounds=box;}else{geometry=box.toGeometry();}}
var attributes;if(this.extractAttributes){attributes=this.parseAttributes(node);}
var feature=new OpenLayers.Feature.Vector(geometry,attributes);feature.bounds=bounds;feature.gml={featureType:node.firstChild.nodeName.split(":")[1],featureNS:node.firstChild.namespaceURI,featureNSPrefix:node.firstChild.prefix};var childNode=node.firstChild;var fid;while(childNode){if(childNode.nodeType==1){fid=childNode.getAttribute("fid")||childNode.getAttribute("id");if(fid){break;}}
childNode=childNode.nextSibling;}
feature.fid=fid;return feature;},parseGeometry:{point:function(node){var nodeList,coordString;var coords=[];var nodeList=this.getElementsByTagNameNS(node,this.gmlns,"pos");if(nodeList.length>0){coordString=nodeList[0].firstChild.nodeValue;coordString=coordString.replace(this.regExes.trimSpace,"");coords=coordString.split(this.regExes.splitSpace);}
if(coords.length==0){nodeList=this.getElementsByTagNameNS(node,this.gmlns,"coordinates");if(nodeList.length>0){coordString=nodeList[0].firstChild.nodeValue;coordString=coordString.replace(this.regExes.removeSpace,"");coords=coordString.split(",");}}
if(coords.length==0){nodeList=this.getElementsByTagNameNS(node,this.gmlns,"coord");if(nodeList.length>0){var xList=this.getElementsByTagNameNS(nodeList[0],this.gmlns,"X");var yList=this.getElementsByTagNameNS(nodeList[0],this.gmlns,"Y");if(xList.length>0&&yList.length>0){coords=[xList[0].firstChild.nodeValue,yList[0].firstChild.nodeValue];}}}
if(coords.length==2){coords[2]=null;}
if(this.xy){return new OpenLayers.Geometry.Point(coords[0],coords[1],coords[2]);}
else{return new OpenLayers.Geometry.Point(coords[1],coords[0],coords[2]);}},multipoint:function(node){var nodeList=this.getElementsByTagNameNS(node,this.gmlns,"Point");var components=[];if(nodeList.length>0){var point;for(var i=0;i<nodeList.length;++i){point=this.parseGeometry.point.apply(this,[nodeList[i]]);if(point){components.push(point);}}}
return new OpenLayers.Geometry.MultiPoint(components);},linestring:function(node,ring){var nodeList,coordString;var coords=[];var points=[];nodeList=this.getElementsByTagNameNS(node,this.gmlns,"posList");if(nodeList.length>0){coordString=this.getChildValue(nodeList[0]);coordString=coordString.replace(this.regExes.trimSpace,"");coords=coordString.split(this.regExes.splitSpace);var dim=parseInt(nodeList[0].getAttribute("dimension"));var j,x,y,z;for(var i=0;i<coords.length/dim;++i){j=i*dim;x=coords[j];y=coords[j+1];z=(dim==2)?null:coords[j+2];if(this.xy){points.push(new OpenLayers.Geometry.Point(x,y,z));}else{points.push(new OpenLayers.Geometry.Point(y,x,z));}}}
if(coords.length==0){nodeList=this.getElementsByTagNameNS(node,this.gmlns,"coordinates");if(nodeList.length>0){coordString=this.getChildValue(nodeList[0]);coordString=coordString.replace(this.regExes.trimSpace,"");coordString=coordString.replace(this.regExes.trimComma,",");var pointList=coordString.split(this.regExes.splitSpace);for(var i=0;i<pointList.length;++i){coords=pointList[i].split(",");if(coords.length==2){coords[2]=null;}
if(this.xy){points.push(new OpenLayers.Geometry.Point(coords[0],coords[1],coords[2]));}else{points.push(new OpenLayers.Geometry.Point(coords[1],coords[0],coords[2]));}}}}
var line=null;if(points.length!=0){if(ring){line=new OpenLayers.Geometry.LinearRing(points);}else{line=new OpenLayers.Geometry.LineString(points);}}
return line;},multilinestring:function(node){var nodeList=this.getElementsByTagNameNS(node,this.gmlns,"LineString");var components=[];if(nodeList.length>0){var line;for(var i=0;i<nodeList.length;++i){line=this.parseGeometry.linestring.apply(this,[nodeList[i]]);if(line){components.push(line);}}}
return new OpenLayers.Geometry.MultiLineString(components);},polygon:function(node){var nodeList=this.getElementsByTagNameNS(node,this.gmlns,"LinearRing");var components=[];if(nodeList.length>0){var ring;for(var i=0;i<nodeList.length;++i){ring=this.parseGeometry.linestring.apply(this,[nodeList[i],true]);if(ring){components.push(ring);}}}
return new OpenLayers.Geometry.Polygon(components);},multipolygon:function(node){var nodeList=this.getElementsByTagNameNS(node,this.gmlns,"Polygon");var components=[];if(nodeList.length>0){var polygon;for(var i=0;i<nodeList.length;++i){polygon=this.parseGeometry.polygon.apply(this,[nodeList[i]]);if(polygon){components.push(polygon);}}}
return new OpenLayers.Geometry.MultiPolygon(components);},envelope:function(node){var components=[];var coordString;var envelope;var lpoint=this.getElementsByTagNameNS(node,this.gmlns,"lowerCorner");if(lpoint.length>0){var coords=[];if(lpoint.length>0){coordString=lpoint[0].firstChild.nodeValue;coordString=coordString.replace(this.regExes.trimSpace,"");coords=coordString.split(this.regExes.splitSpace);}
if(coords.length==2){coords[2]=null;}
if(this.xy){var lowerPoint=new OpenLayers.Geometry.Point(coords[0],coords[1],coords[2]);}else{var lowerPoint=new OpenLayers.Geometry.Point(coords[1],coords[0],coords[2]);}}
var upoint=this.getElementsByTagNameNS(node,this.gmlns,"upperCorner");if(upoint.length>0){var coords=[];if(upoint.length>0){coordString=upoint[0].firstChild.nodeValue;coordString=coordString.replace(this.regExes.trimSpace,"");coords=coordString.split(this.regExes.splitSpace);}
if(coords.length==2){coords[2]=null;}
if(this.xy){var upperPoint=new OpenLayers.Geometry.Point(coords[0],coords[1],coords[2]);}else{var upperPoint=new OpenLayers.Geometry.Point(coords[1],coords[0],coords[2]);}}
if(lowerPoint&&upperPoint){components.push(new OpenLayers.Geometry.Point(lowerPoint.x,lowerPoint.y));components.push(new OpenLayers.Geometry.Point(upperPoint.x,lowerPoint.y));components.push(new OpenLayers.Geometry.Point(upperPoint.x,upperPoint.y));components.push(new OpenLayers.Geometry.Point(lowerPoint.x,upperPoint.y));components.push(new OpenLayers.Geometry.Point(lowerPoint.x,lowerPoint.y));var ring=new OpenLayers.Geometry.LinearRing(components);envelope=new OpenLayers.Geometry.Polygon([ring]);}
return envelope;},box:function(node){var nodeList=this.getElementsByTagNameNS(node,this.gmlns,"coordinates");var coordString;var coords,beginPoint=null,endPoint=null;if(nodeList.length>0){coordString=nodeList[0].firstChild.nodeValue;coords=coordString.split(" ");if(coords.length==2){beginPoint=coords[0].split(",");endPoint=coords[1].split(",");}}
if(beginPoint!==null&&endPoint!==null){return new OpenLayers.Bounds(parseFloat(beginPoint[0]),parseFloat(beginPoint[1]),parseFloat(endPoint[0]),parseFloat(endPoint[1]));}}},parseAttributes:function(node){var attributes={};var childNode=node.firstChild;var children,i,child,grandchildren,grandchild,name,value;while(childNode){if(childNode.nodeType==1){children=childNode.childNodes;for(i=0;i<children.length;++i){child=children[i];if(child.nodeType==1){grandchildren=child.childNodes;if(grandchildren.length==1){grandchild=grandchildren[0];if(grandchild.nodeType==3||grandchild.nodeType==4){name=(child.prefix)?child.nodeName.split(":")[1]:child.nodeName;value=grandchild.nodeValue.replace(this.regExes.trimSpace,"");attributes[name]=value;}}else{attributes[child.nodeName.split(":").pop()]=null;}}}
break;}
childNode=childNode.nextSibling;}
return attributes;},write:function(features){if(!(features instanceof Array)){features=[features];}
var gml=this.createElementNS("http://www.opengis.net/wfs","wfs:"+this.collectionName);for(var i=0;i<features.length;i++){gml.appendChild(this.createFeatureXML(features[i]));}
return OpenLayers.Format.XML.prototype.write.apply(this,[gml]);},createFeatureXML:function(feature){var geometry=feature.geometry;var geometryNode=this.buildGeometryNode(geometry);var geomContainer=this.createElementNS(this.featureNS,this.featurePrefix+":"+
this.geometryName);geomContainer.appendChild(geometryNode);var featureNode=this.createElementNS(this.gmlns,"gml:"+this.featureName);var featureContainer=this.createElementNS(this.featureNS,this.featurePrefix+":"+
this.layerName);var fid=feature.fid||feature.id;featureContainer.setAttribute("fid",fid);featureContainer.appendChild(geomContainer);for(var attr in feature.attributes){var attrText=this.createTextNode(feature.attributes[attr]);var nodename=attr.substring(attr.lastIndexOf(":")+1);var attrContainer=this.createElementNS(this.featureNS,this.featurePrefix+":"+
nodename);attrContainer.appendChild(attrText);featureContainer.appendChild(attrContainer);}
featureNode.appendChild(featureContainer);return featureNode;},buildGeometryNode:function(geometry){if(this.externalProjection&&this.internalProjection){geometry=geometry.clone();geometry.transform(this.internalProjection,this.externalProjection);}
var className=geometry.CLASS_NAME;var type=className.substring(className.lastIndexOf(".")+1);var builder=this.buildGeometry[type.toLowerCase()];return builder.apply(this,[geometry]);},buildGeometry:{point:function(geometry){var gml=this.createElementNS(this.gmlns,"gml:Point");gml.appendChild(this.buildCoordinatesNode(geometry));return gml;},multipoint:function(geometry){var gml=this.createElementNS(this.gmlns,"gml:MultiPoint");var points=geometry.components;var pointMember,pointGeom;for(var i=0;i<points.length;i++){pointMember=this.createElementNS(this.gmlns,"gml:pointMember");pointGeom=this.buildGeometry.point.apply(this,[points[i]]);pointMember.appendChild(pointGeom);gml.appendChild(pointMember);}
return gml;},linestring:function(geometry){var gml=this.createElementNS(this.gmlns,"gml:LineString");gml.appendChild(this.buildCoordinatesNode(geometry));return gml;},multilinestring:function(geometry){var gml=this.createElementNS(this.gmlns,"gml:MultiLineString");var lines=geometry.components;var lineMember,lineGeom;for(var i=0;i<lines.length;++i){lineMember=this.createElementNS(this.gmlns,"gml:lineStringMember");lineGeom=this.buildGeometry.linestring.apply(this,[lines[i]]);lineMember.appendChild(lineGeom);gml.appendChild(lineMember);}
return gml;},linearring:function(geometry){var gml=this.createElementNS(this.gmlns,"gml:LinearRing");gml.appendChild(this.buildCoordinatesNode(geometry));return gml;},polygon:function(geometry){var gml=this.createElementNS(this.gmlns,"gml:Polygon");var rings=geometry.components;var ringMember,ringGeom,type;for(var i=0;i<rings.length;++i){type=(i==0)?"outerBoundaryIs":"innerBoundaryIs";ringMember=this.createElementNS(this.gmlns,"gml:"+type);ringGeom=this.buildGeometry.linearring.apply(this,[rings[i]]);ringMember.appendChild(ringGeom);gml.appendChild(ringMember);}
return gml;},multipolygon:function(geometry){var gml=this.createElementNS(this.gmlns,"gml:MultiPolygon");var polys=geometry.components;var polyMember,polyGeom;for(var i=0;i<polys.length;++i){polyMember=this.createElementNS(this.gmlns,"gml:polygonMember");polyGeom=this.buildGeometry.polygon.apply(this,[polys[i]]);polyMember.appendChild(polyGeom);gml.appendChild(polyMember);}
return gml;},bounds:function(bounds){var gml=this.createElementNS(this.gmlns,"gml:Box");gml.appendChild(this.buildCoordinatesNode(bounds));return gml;}},buildCoordinatesNode:function(geometry){var coordinatesNode=this.createElementNS(this.gmlns,"gml:coordinates");coordinatesNode.setAttribute("decimal",".");coordinatesNode.setAttribute("cs",",");coordinatesNode.setAttribute("ts"," ");var parts=[];if(geometry instanceof OpenLayers.Bounds){parts.push(geometry.left+","+geometry.bottom);parts.push(geometry.right+","+geometry.top);}else{var points=(geometry.components)?geometry.components:[geometry];for(var i=0;i<points.length;i++){parts.push(points[i].x+","+points[i].y);}}
var txtNode=this.createTextNode(parts.join(" "));coordinatesNode.appendChild(txtNode);return coordinatesNode;},CLASS_NAME:"OpenLayers.Format.GML"});OpenLayers.Format.GeoJSON=OpenLayers.Class(OpenLayers.Format.JSON,{ignoreExtraDims:false,initialize:function(options){OpenLayers.Format.JSON.prototype.initialize.apply(this,[options]);},read:function(json,type,filter){type=(type)?type:"FeatureCollection";var results=null;var obj=null;if(typeof json=="string"){obj=OpenLayers.Format.JSON.prototype.read.apply(this,[json,filter]);}else{obj=json;}
if(!obj){OpenLayers.Console.error("Bad JSON: "+json);}else if(typeof(obj.type)!="string"){OpenLayers.Console.error("Bad GeoJSON - no type: "+json);}else if(this.isValidType(obj,type)){switch(type){case"Geometry":try{results=this.parseGeometry(obj);}catch(err){OpenLayers.Console.error(err);}
break;case"Feature":try{results=this.parseFeature(obj);results.type="Feature";}catch(err){OpenLayers.Console.error(err);}
break;case"FeatureCollection":results=[];switch(obj.type){case"Feature":try{results.push(this.parseFeature(obj));}catch(err){results=null;OpenLayers.Console.error(err);}
break;case"FeatureCollection":for(var i=0,len=obj.features.length;i<len;++i){try{results.push(this.parseFeature(obj.features[i]));}catch(err){results=null;OpenLayers.Console.error(err);}}
break;default:try{var geom=this.parseGeometry(obj);results.push(new OpenLayers.Feature.Vector(geom));}catch(err){results=null;OpenLayers.Console.error(err);}}
break;}}
return results;},isValidType:function(obj,type){var valid=false;switch(type){case"Geometry":if(OpenLayers.Util.indexOf(["Point","MultiPoint","LineString","MultiLineString","Polygon","MultiPolygon","Box","GeometryCollection"],obj.type)==-1){OpenLayers.Console.error("Unsupported geometry type: "+
obj.type);}else{valid=true;}
break;case"FeatureCollection":valid=true;break;default:if(obj.type==type){valid=true;}else{OpenLayers.Console.error("Cannot convert types from "+
obj.type+" to "+type);}}
return valid;},parseFeature:function(obj){var feature,geometry,attributes,bbox;attributes=(obj.properties)?obj.properties:{};bbox=(obj.geometry&&obj.geometry.bbox)||obj.bbox;try{geometry=this.parseGeometry(obj.geometry);}catch(err){throw err;}
feature=new OpenLayers.Feature.Vector(geometry,attributes);if(bbox){feature.bounds=OpenLayers.Bounds.fromArray(bbox);}
if(obj.id){feature.fid=obj.id;}
return feature;},parseGeometry:function(obj){if(obj==null){return null;}
var geometry,collection=false;if(obj.type=="GeometryCollection"){if(!(obj.geometries instanceof Array)){throw"GeometryCollection must have geometries array: "+obj;}
var numGeom=obj.geometries.length;var components=new Array(numGeom);for(var i=0;i<numGeom;++i){components[i]=this.parseGeometry.apply(this,[obj.geometries[i]]);}
geometry=new OpenLayers.Geometry.Collection(components);collection=true;}else{if(!(obj.coordinates instanceof Array)){throw"Geometry must have coordinates array: "+obj;}
if(!this.parseCoords[obj.type.toLowerCase()]){throw"Unsupported geometry type: "+obj.type;}
try{geometry=this.parseCoords[obj.type.toLowerCase()].apply(this,[obj.coordinates]);}catch(err){throw err;}}
if(this.internalProjection&&this.externalProjection&&!collection){geometry.transform(this.externalProjection,this.internalProjection);}
return geometry;},parseCoords:{"point":function(array){if(this.ignoreExtraDims==false&&array.length!=2){throw"Only 2D points are supported: "+array;}
return new OpenLayers.Geometry.Point(array[0],array[1]);},"multipoint":function(array){var points=[];var p=null;for(var i=0,len=array.length;i<len;++i){try{p=this.parseCoords["point"].apply(this,[array[i]]);}catch(err){throw err;}
points.push(p);}
return new OpenLayers.Geometry.MultiPoint(points);},"linestring":function(array){var points=[];var p=null;for(var i=0,len=array.length;i<len;++i){try{p=this.parseCoords["point"].apply(this,[array[i]]);}catch(err){throw err;}
points.push(p);}
return new OpenLayers.Geometry.LineString(points);},"multilinestring":function(array){var lines=[];var l=null;for(var i=0,len=array.length;i<len;++i){try{l=this.parseCoords["linestring"].apply(this,[array[i]]);}catch(err){throw err;}
lines.push(l);}
return new OpenLayers.Geometry.MultiLineString(lines);},"polygon":function(array){var rings=[];var r,l;for(var i=0,len=array.length;i<len;++i){try{l=this.parseCoords["linestring"].apply(this,[array[i]]);}catch(err){throw err;}
r=new OpenLayers.Geometry.LinearRing(l.components);rings.push(r);}
return new OpenLayers.Geometry.Polygon(rings);},"multipolygon":function(array){var polys=[];var p=null;for(var i=0,len=array.length;i<len;++i){try{p=this.parseCoords["polygon"].apply(this,[array[i]]);}catch(err){throw err;}
polys.push(p);}
return new OpenLayers.Geometry.MultiPolygon(polys);},"box":function(array){if(array.length!=2){throw"GeoJSON box coordinates must have 2 elements";}
return new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing([new OpenLayers.Geometry.Point(array[0][0],array[0][1]),new OpenLayers.Geometry.Point(array[1][0],array[0][1]),new OpenLayers.Geometry.Point(array[1][0],array[1][1]),new OpenLayers.Geometry.Point(array[0][0],array[1][1]),new OpenLayers.Geometry.Point(array[0][0],array[0][1])])]);}},write:function(obj,pretty){var geojson={"type":null};if(obj instanceof Array){geojson.type="FeatureCollection";var numFeatures=obj.length;geojson.features=new Array(numFeatures);for(var i=0;i<numFeatures;++i){var element=obj[i];if(!element instanceof OpenLayers.Feature.Vector){var msg="FeatureCollection only supports collections "+"of features: "+element;throw msg;}
geojson.features[i]=this.extract.feature.apply(this,[element]);}}else if(obj.CLASS_NAME.indexOf("OpenLayers.Geometry")==0){geojson=this.extract.geometry.apply(this,[obj]);}else if(obj instanceof OpenLayers.Feature.Vector){geojson=this.extract.feature.apply(this,[obj]);if(obj.layer&&obj.layer.projection){geojson.crs=this.createCRSObject(obj);}}
return OpenLayers.Format.JSON.prototype.write.apply(this,[geojson,pretty]);},createCRSObject:function(object){var proj=object.layer.projection.toString();var crs={};if(proj.match(/epsg:/i)){var code=parseInt(proj.substring(proj.indexOf(":")+1));if(code==4326){crs={"type":"OGC","properties":{"urn":"urn:ogc:def:crs:OGC:1.3:CRS84"}};}else{crs={"type":"EPSG","properties":{"code":code}};}}
return crs;},extract:{'feature':function(feature){var geom=this.extract.geometry.apply(this,[feature.geometry]);return{"type":"Feature","id":feature.fid==null?feature.id:feature.fid,"properties":feature.attributes,"geometry":geom};},'geometry':function(geometry){if(geometry==null){return null;}
if(this.internalProjection&&this.externalProjection){geometry=geometry.clone();geometry.transform(this.internalProjection,this.externalProjection);}
var geometryType=geometry.CLASS_NAME.split('.')[2];var data=this.extract[geometryType.toLowerCase()].apply(this,[geometry]);var json;if(geometryType=="Collection"){json={"type":"GeometryCollection","geometries":data};}else{json={"type":geometryType,"coordinates":data};}
return json;},'point':function(point){return[point.x,point.y];},'multipoint':function(multipoint){var array=[];for(var i=0,len=multipoint.components.length;i<len;++i){array.push(this.extract.point.apply(this,[multipoint.components[i]]));}
return array;},'linestring':function(linestring){var array=[];for(var i=0,len=linestring.components.length;i<len;++i){array.push(this.extract.point.apply(this,[linestring.components[i]]));}
return array;},'multilinestring':function(multilinestring){var array=[];for(var i=0,len=multilinestring.components.length;i<len;++i){array.push(this.extract.linestring.apply(this,[multilinestring.components[i]]));}
return array;},'polygon':function(polygon){var array=[];for(var i=0,len=polygon.components.length;i<len;++i){array.push(this.extract.linestring.apply(this,[polygon.components[i]]));}
return array;},'multipolygon':function(multipolygon){var array=[];for(var i=0,len=multipolygon.components.length;i<len;++i){array.push(this.extract.polygon.apply(this,[multipolygon.components[i]]));}
return array;},'collection':function(collection){var len=collection.components.length;var array=new Array(len);for(var i=0;i<len;++i){array[i]=this.extract.geometry.apply(this,[collection.components[i]]);}
return array;}},CLASS_NAME:"OpenLayers.Format.GeoJSON"});OpenLayers.Format.ArcXML.Features=OpenLayers.Class(OpenLayers.Format.XML,{initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){var axl=new OpenLayers.Format.ArcXML();var parsed=axl.read(data);return parsed.features.feature;}});if(!OpenLayers.Format.GML){OpenLayers.Format.GML={};}
OpenLayers.Format.GML.Base=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{gml:"http://www.opengis.net/gml",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",wfs:"http://www.opengis.net/wfs"},defaultPrefix:"gml",schemaLocation:null,featureType:null,featureNS:null,geometryName:"geometry",extractAttributes:true,srsName:null,xy:true,geometryTypes:null,singleFeatureType:null,regExes:{trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)},initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);this.setGeometryTypes();if(options&&options.featureNS){this.setNamespace("feature",options.featureNS);}
this.singleFeatureType=!options||(typeof options.featureType==="string");},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var features=[];this.readNode(data,{features:features});if(features.length==0){var elements=this.getElementsByTagNameNS(data,this.namespaces.gml,"featureMember");if(elements.length){for(var i=0,len=elements.length;i<len;++i){this.readNode(elements[i],{features:features});}}else{var elements=this.getElementsByTagNameNS(data,this.namespaces.gml,"featureMembers");if(elements.length){this.readNode(elements[0],{features:features});}}}
return features;},readers:{"gml":{"featureMember":function(node,obj){this.readChildNodes(node,obj);},"featureMembers":function(node,obj){this.readChildNodes(node,obj);},"name":function(node,obj){obj.name=this.getChildValue(node);},"boundedBy":function(node,obj){var container={};this.readChildNodes(node,container);if(container.components&&container.components.length>0){obj.bounds=container.components[0];}},"Point":function(node,container){var obj={points:[]};this.readChildNodes(node,obj);if(!container.components){container.components=[];}
container.components.push(obj.points[0]);},"coordinates":function(node,obj){var str=this.getChildValue(node).replace(this.regExes.trimSpace,"");str=str.replace(this.regExes.trimComma,",");var pointList=str.split(this.regExes.splitSpace);var coords;var numPoints=pointList.length;var points=new Array(numPoints);for(var i=0;i<numPoints;++i){coords=pointList[i].split(",");if(this.xy){points[i]=new OpenLayers.Geometry.Point(coords[0],coords[1],coords[2]);}else{points[i]=new OpenLayers.Geometry.Point(coords[1],coords[0],coords[2]);}}
obj.points=points;},"coord":function(node,obj){var coord={};this.readChildNodes(node,coord);if(!obj.points){obj.points=[];}
obj.points.push(new OpenLayers.Geometry.Point(coord.x,coord.y,coord.z));},"X":function(node,coord){coord.x=this.getChildValue(node);},"Y":function(node,coord){coord.y=this.getChildValue(node);},"Z":function(node,coord){coord.z=this.getChildValue(node);},"MultiPoint":function(node,container){var obj={components:[]};this.readChildNodes(node,obj);container.components=[new OpenLayers.Geometry.MultiPoint(obj.components)];},"pointMember":function(node,obj){this.readChildNodes(node,obj);},"LineString":function(node,container){var obj={};this.readChildNodes(node,obj);if(!container.components){container.components=[];}
container.components.push(new OpenLayers.Geometry.LineString(obj.points));},"MultiLineString":function(node,container){var obj={components:[]};this.readChildNodes(node,obj);container.components=[new OpenLayers.Geometry.MultiLineString(obj.components)];},"lineStringMember":function(node,obj){this.readChildNodes(node,obj);},"Polygon":function(node,container){var obj={outer:null,inner:[]};this.readChildNodes(node,obj);obj.inner.unshift(obj.outer);if(!container.components){container.components=[];}
container.components.push(new OpenLayers.Geometry.Polygon(obj.inner));},"LinearRing":function(node,obj){var container={};this.readChildNodes(node,container);obj.components=[new OpenLayers.Geometry.LinearRing(container.points)];},"MultiPolygon":function(node,container){var obj={components:[]};this.readChildNodes(node,obj);container.components=[new OpenLayers.Geometry.MultiPolygon(obj.components)];},"polygonMember":function(node,obj){this.readChildNodes(node,obj);},"GeometryCollection":function(node,container){var obj={components:[]};this.readChildNodes(node,obj);container.components=[new OpenLayers.Geometry.Collection(obj.components)];},"geometryMember":function(node,obj){this.readChildNodes(node,obj);}},"feature":{"*":function(node,obj){var name;var local=node.localName||node.nodeName.split(":").pop();if(obj.features){if(!this.singleFeatureType&&(OpenLayers.Util.indexOf(this.featureType,local)!==-1)){name="_typeName";}else if(local===this.featureType){name="_typeName";}}else{if(node.childNodes.length==0||(node.childNodes.length==1&&node.firstChild.nodeType==3)){if(this.extractAttributes){name="_attribute";}}else{name="_geometry";}}
if(name){this.readers.feature[name].apply(this,[node,obj]);}},"_typeName":function(node,obj){var container={components:[],attributes:{}};this.readChildNodes(node,container);if(container.name){container.attributes.name=container.name;}
var feature=new OpenLayers.Feature.Vector(container.components[0],container.attributes);if(!this.singleFeatureType){feature.type=node.nodeName.split(":").pop();feature.namespace=node.namespaceURI;}
var fid=node.getAttribute("fid")||this.getAttributeNS(node,this.namespaces["gml"],"id");if(fid){feature.fid=fid;}
if(this.internalProjection&&this.externalProjection&&feature.geometry){feature.geometry.transform(this.externalProjection,this.internalProjection);}
if(container.bounds){feature.bounds=container.bounds;}
obj.features.push(feature);},"_geometry":function(node,obj){this.readChildNodes(node,obj);},"_attribute":function(node,obj){var local=node.localName||node.nodeName.split(":").pop();var value=this.getChildValue(node);obj.attributes[local]=value;}},"wfs":{"FeatureCollection":function(node,obj){this.readChildNodes(node,obj);}}},write:function(features){var name;if(features instanceof Array){name="featureMembers";}else{name="featureMember";}
var root=this.writeNode("gml:"+name,features);this.setAttributeNS(root,this.namespaces["xsi"],"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[root]);},writers:{"gml":{"featureMember":function(feature){var node=this.createElementNSPlus("gml:featureMember");this.writeNode("feature:_typeName",feature,node);return node;},"MultiPoint":function(geometry){var node=this.createElementNSPlus("gml:MultiPoint");for(var i=0;i<geometry.components.length;++i){this.writeNode("pointMember",geometry.components[i],node);}
return node;},"pointMember":function(geometry){var node=this.createElementNSPlus("gml:pointMember");this.writeNode("Point",geometry,node);return node;},"MultiLineString":function(geometry){var node=this.createElementNSPlus("gml:MultiLineString");for(var i=0;i<geometry.components.length;++i){this.writeNode("lineStringMember",geometry.components[i],node);}
return node;},"lineStringMember":function(geometry){var node=this.createElementNSPlus("gml:lineStringMember");this.writeNode("LineString",geometry,node);return node;},"MultiPolygon":function(geometry){var node=this.createElementNSPlus("gml:MultiPolygon");for(var i=0;i<geometry.components.length;++i){this.writeNode("polygonMember",geometry.components[i],node);}
return node;},"polygonMember":function(geometry){var node=this.createElementNSPlus("gml:polygonMember");this.writeNode("Polygon",geometry,node);return node;},"GeometryCollection":function(geometry){var node=this.createElementNSPlus("gml:GeometryCollection");for(var i=0,len=geometry.components.length;i<len;++i){this.writeNode("geometryMember",geometry.components[i],node);}
return node;},"geometryMember":function(geometry){var node=this.createElementNSPlus("gml:geometryMember");var child=this.writeNode("feature:_geometry",geometry);node.appendChild(child.firstChild);return node;}},"feature":{"_typeName":function(feature){var node=this.createElementNSPlus("feature:"+this.featureType,{attributes:{fid:feature.fid}});if(feature.geometry){this.writeNode("feature:_geometry",feature.geometry,node);}
for(var name in feature.attributes){var value=feature.attributes[name];if(value!=null){this.writeNode("feature:_attribute",{name:name,value:value},node);}}
return node;},"_geometry":function(geometry){if(this.externalProjection&&this.internalProjection){geometry=geometry.clone().transform(this.internalProjection,this.externalProjection);}
var node=this.createElementNSPlus("feature:"+this.geometryName);var type=this.geometryTypes[geometry.CLASS_NAME];var child=this.writeNode("gml:"+type,geometry,node);if(this.srsName){child.setAttribute("srsName",this.srsName);}
return node;},"_attribute":function(obj){return this.createElementNSPlus("feature:"+obj.name,{value:obj.value});}},"wfs":{"FeatureCollection":function(features){var node=this.createElementNSPlus("wfs:FeatureCollection");for(var i=0,len=features.length;i<len;++i){this.writeNode("gml:featureMember",features[i],node);}
return node;}}},setGeometryTypes:function(){this.geometryTypes={"OpenLayers.Geometry.Point":"Point","OpenLayers.Geometry.MultiPoint":"MultiPoint","OpenLayers.Geometry.LineString":"LineString","OpenLayers.Geometry.MultiLineString":"MultiLineString","OpenLayers.Geometry.Polygon":"Polygon","OpenLayers.Geometry.MultiPolygon":"MultiPolygon","OpenLayers.Geometry.Collection":"GeometryCollection"};},CLASS_NAME:"OpenLayers.Format.GML.Base"});OpenLayers.Format.WFS=OpenLayers.Class(OpenLayers.Format.GML,{layer:null,wfsns:"http://www.opengis.net/wfs",ogcns:"http://www.opengis.net/ogc",initialize:function(options,layer){OpenLayers.Format.GML.prototype.initialize.apply(this,[options]);this.layer=layer;if(this.layer.featureNS){this.featureNS=this.layer.featureNS;}
if(this.layer.options.geometry_column){this.geometryName=this.layer.options.geometry_column;}
if(this.layer.options.typename){this.featureName=this.layer.options.typename;}},write:function(features){var transaction=this.createElementNS(this.wfsns,'wfs:Transaction');transaction.setAttribute("version","1.0.0");transaction.setAttribute("service","WFS");for(var i=0;i<features.length;i++){switch(features[i].state){case OpenLayers.State.INSERT:transaction.appendChild(this.insert(features[i]));break;case OpenLayers.State.UPDATE:transaction.appendChild(this.update(features[i]));break;case OpenLayers.State.DELETE:transaction.appendChild(this.remove(features[i]));break;}}
return OpenLayers.Format.XML.prototype.write.apply(this,[transaction]);},createFeatureXML:function(feature){var geometryNode=this.buildGeometryNode(feature.geometry);var geomContainer=this.createElementNS(this.featureNS,"feature:"+this.geometryName);geomContainer.appendChild(geometryNode);var featureContainer=this.createElementNS(this.featureNS,"feature:"+this.featureName);featureContainer.appendChild(geomContainer);for(var attr in feature.attributes){var attrText=this.createTextNode(feature.attributes[attr]);var nodename=attr;if(attr.search(":")!=-1){nodename=attr.split(":")[1];}
var attrContainer=this.createElementNS(this.featureNS,"feature:"+nodename);attrContainer.appendChild(attrText);featureContainer.appendChild(attrContainer);}
return featureContainer;},insert:function(feature){var insertNode=this.createElementNS(this.wfsns,'wfs:Insert');insertNode.appendChild(this.createFeatureXML(feature));return insertNode;},update:function(feature){if(!feature.fid){OpenLayers.Console.userError(OpenLayers.i18n("noFID"));}
var updateNode=this.createElementNS(this.wfsns,'wfs:Update');updateNode.setAttribute("typeName",this.featurePrefix+':'+this.featureName);updateNode.setAttribute("xmlns:"+this.featurePrefix,this.featureNS);var propertyNode=this.createElementNS(this.wfsns,'wfs:Property');var nameNode=this.createElementNS(this.wfsns,'wfs:Name');var txtNode=this.createTextNode(this.geometryName);nameNode.appendChild(txtNode);propertyNode.appendChild(nameNode);var valueNode=this.createElementNS(this.wfsns,'wfs:Value');var geometryNode=this.buildGeometryNode(feature.geometry);if(feature.layer){geometryNode.setAttribute("srsName",feature.layer.projection.getCode());}
valueNode.appendChild(geometryNode);propertyNode.appendChild(valueNode);updateNode.appendChild(propertyNode);for(var propName in feature.attributes){propertyNode=this.createElementNS(this.wfsns,'wfs:Property');nameNode=this.createElementNS(this.wfsns,'wfs:Name');nameNode.appendChild(this.createTextNode(propName));propertyNode.appendChild(nameNode);valueNode=this.createElementNS(this.wfsns,'wfs:Value');valueNode.appendChild(this.createTextNode(feature.attributes[propName]));propertyNode.appendChild(valueNode);updateNode.appendChild(propertyNode);}
var filterNode=this.createElementNS(this.ogcns,'ogc:Filter');var filterIdNode=this.createElementNS(this.ogcns,'ogc:FeatureId');filterIdNode.setAttribute("fid",feature.fid);filterNode.appendChild(filterIdNode);updateNode.appendChild(filterNode);return updateNode;},remove:function(feature){if(!feature.fid){OpenLayers.Console.userError(OpenLayers.i18n("noFID"));return false;}
var deleteNode=this.createElementNS(this.wfsns,'wfs:Delete');deleteNode.setAttribute("typeName",this.featurePrefix+':'+this.featureName);deleteNode.setAttribute("xmlns:"+this.featurePrefix,this.featureNS);var filterNode=this.createElementNS(this.ogcns,'ogc:Filter');var filterIdNode=this.createElementNS(this.ogcns,'ogc:FeatureId');filterIdNode.setAttribute("fid",feature.fid);filterNode.appendChild(filterIdNode);deleteNode.appendChild(filterNode);return deleteNode;},destroy:function(){this.layer=null;},CLASS_NAME:"OpenLayers.Format.WFS"});OpenLayers.Layer.ArcIMS=OpenLayers.Class(OpenLayers.Layer.Grid,{DEFAULT_PARAMS:{ClientVersion:"9.2",ServiceName:''},tileSize:null,featureCoordSys:"4326",filterCoordSys:"4326",layers:null,async:true,name:"ArcIMS",isBaseLayer:true,DEFAULT_OPTIONS:{tileSize:new OpenLayers.Size(512,512),featureCoordSys:"4326",filterCoordSys:"4326",layers:null,isBaseLayer:true,async:true,name:"ArcIMS"},initialize:function(name,url,options){this.tileSize=new OpenLayers.Size(512,512);this.params=OpenLayers.Util.applyDefaults({ServiceName:options.serviceName},this.DEFAULT_PARAMS);this.options=OpenLayers.Util.applyDefaults(options,this.DEFAULT_OPTIONS);OpenLayers.Layer.Grid.prototype.initialize.apply(this,[name,url,this.params,options]);if(this.transparent){if(!this.isBaseLayer){this.isBaseLayer=false;}
if(this.format=="image/jpeg"){this.format=OpenLayers.Util.alphaHack()?"image/gif":"image/png";}}
if(this.options.layers===null){this.options.layers=[];}},destroy:function(){OpenLayers.Layer.Grid.prototype.destroy.apply(this,arguments);},getURL:function(bounds){var url="";bounds=this.adjustBounds(bounds);var axlReq=new OpenLayers.Format.ArcXML(OpenLayers.Util.extend(this.options,{requesttype:"image",envelope:bounds.toArray(),tileSize:this.tileSize}));var req=new OpenLayers.Request.POST({url:this.getFullRequestString(),data:axlReq.write(),async:false});if(req!=null){var doc=req.responseXML;if(!doc||!doc.documentElement){doc=req.responseText;}
var axlResp=new OpenLayers.Format.ArcXML();var arcxml=axlResp.read(doc);url=this.getUrlOrImage(arcxml.image.output);}
return url;},getURLasync:function(bounds,scope,prop,callback){bounds=this.adjustBounds(bounds);var axlReq=new OpenLayers.Format.ArcXML(OpenLayers.Util.extend(this.options,{requesttype:"image",envelope:bounds.toArray(),tileSize:this.tileSize}));OpenLayers.Request.POST({url:this.getFullRequestString(),async:true,data:axlReq.write(),callback:function(req){var doc=req.responseXML;if(!doc||!doc.documentElement){doc=req.responseText;}
var axlResp=new OpenLayers.Format.ArcXML();var arcxml=axlResp.read(doc);scope[prop]=this.getUrlOrImage(arcxml.image.output);callback.apply(scope);},scope:this});},getUrlOrImage:function(output){var ret="";if(output.url){ret=output.url;}else if(output.data){ret="data:image/"+output.type+";base64,"+output.data;}
return ret;},setLayerQuery:function(id,querydef){for(var lyr=0;lyr<this.options.layers.length;lyr++){if(id==this.options.layers[lyr].id){this.options.layers[lyr].query=querydef;return;}}
this.options.layers.push({id:id,visible:true,query:querydef});},getFeatureInfo:function(geometry,layer,options){var buffer=options.buffer||1;var callback=options.callback||function(){};var scope=options.scope||window;var requestOptions={};OpenLayers.Util.extend(requestOptions,this.options);requestOptions.requesttype="feature";if(geometry instanceof OpenLayers.LonLat){requestOptions.polygon=null;requestOptions.envelope=[geometry.lon-buffer,geometry.lat-buffer,geometry.lon+buffer,geometry.lat+buffer];}else if(geometry instanceof OpenLayers.Geometry.Polygon){requestOptions.envelope=null;requestOptions.polygon=geometry;}
var arcxml=new OpenLayers.Format.ArcXML(requestOptions);OpenLayers.Util.extend(arcxml.request.get_feature,options);arcxml.request.get_feature.layer=layer.id;if(typeof layer.query.accuracy=="number"){arcxml.request.get_feature.query.accuracy=layer.query.accuracy;}else{var mapCenter=this.map.getCenter();var viewPx=this.map.getViewPortPxFromLonLat(mapCenter);viewPx.x++;var mapOffCenter=this.map.getLonLatFromPixel(viewPx);arcxml.request.get_feature.query.accuracy=mapOffCenter.lon-mapCenter.lon;}
arcxml.request.get_feature.query.where=layer.query.where;arcxml.request.get_feature.query.spatialfilter.relation="area_intersection";OpenLayers.Request.POST({url:this.getFullRequestString({'CustomService':'Query'}),data:arcxml.write(),callback:function(request){var response=arcxml.parseResponse(request.responseText);if(!arcxml.iserror()){callback.call(scope,response.features);}else{callback.call(scope,null);}}});},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.ArcIMS(this.name,this.url,this.getOptions());}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);return obj;},addTile:function(bounds,position){return new OpenLayers.Tile.Image(this,position,bounds,null,this.tileSize);},CLASS_NAME:"OpenLayers.Layer.ArcIMS"});OpenLayers.Format.GML.v2=OpenLayers.Class(OpenLayers.Format.GML.Base,{schemaLocation:"http://www.opengis.net/gml http://schemas.opengis.net/gml/2.1.2/feature.xsd",initialize:function(options){OpenLayers.Format.GML.Base.prototype.initialize.apply(this,[options]);},readers:{"gml":OpenLayers.Util.applyDefaults({"outerBoundaryIs":function(node,container){var obj={};this.readChildNodes(node,obj);container.outer=obj.components[0];},"innerBoundaryIs":function(node,container){var obj={};this.readChildNodes(node,obj);container.inner.push(obj.components[0]);},"Box":function(node,container){var obj={};this.readChildNodes(node,obj);if(!container.components){container.components=[];}
var min=obj.points[0];var max=obj.points[1];container.components.push(new OpenLayers.Bounds(min.x,min.y,max.x,max.y));}},OpenLayers.Format.GML.Base.prototype.readers["gml"]),"feature":OpenLayers.Format.GML.Base.prototype.readers["feature"],"wfs":OpenLayers.Format.GML.Base.prototype.readers["wfs"]},write:function(features){var name;if(features instanceof Array){name="wfs:FeatureCollection";}else{name="gml:featureMember";}
var root=this.writeNode(name,features);this.setAttributeNS(root,this.namespaces["xsi"],"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[root]);},writers:{"gml":OpenLayers.Util.applyDefaults({"Point":function(geometry){var node=this.createElementNSPlus("gml:Point");this.writeNode("coordinates",[geometry],node);return node;},"coordinates":function(points){var numPoints=points.length;var parts=new Array(numPoints);var point;for(var i=0;i<numPoints;++i){point=points[i];if(this.xy){parts[i]=point.x+","+point.y;}else{parts[i]=point.y+","+point.x;}
if(point.z!=undefined){parts[i]+=","+point.z;}}
return this.createElementNSPlus("gml:coordinates",{attributes:{decimal:".",cs:",",ts:" "},value:(numPoints==1)?parts[0]:parts.join(" ")});},"LineString":function(geometry){var node=this.createElementNSPlus("gml:LineString");this.writeNode("coordinates",geometry.components,node);return node;},"Polygon":function(geometry){var node=this.createElementNSPlus("gml:Polygon");this.writeNode("outerBoundaryIs",geometry.components[0],node);for(var i=1;i<geometry.components.length;++i){this.writeNode("innerBoundaryIs",geometry.components[i],node);}
return node;},"outerBoundaryIs":function(ring){var node=this.createElementNSPlus("gml:outerBoundaryIs");this.writeNode("LinearRing",ring,node);return node;},"innerBoundaryIs":function(ring){var node=this.createElementNSPlus("gml:innerBoundaryIs");this.writeNode("LinearRing",ring,node);return node;},"LinearRing":function(ring){var node=this.createElementNSPlus("gml:LinearRing");this.writeNode("coordinates",ring.components,node);return node;},"Box":function(bounds){var node=this.createElementNSPlus("gml:Box");this.writeNode("coordinates",[{x:bounds.left,y:bounds.bottom},{x:bounds.right,y:bounds.top}],node);if(this.srsName){node.setAttribute("srsName",this.srsName);}
return node;}},OpenLayers.Format.GML.Base.prototype.writers["gml"]),"feature":OpenLayers.Format.GML.Base.prototype.writers["feature"],"wfs":OpenLayers.Format.GML.Base.prototype.writers["wfs"]},CLASS_NAME:"OpenLayers.Format.GML.v2"});OpenLayers.Format.GML.v3=OpenLayers.Class(OpenLayers.Format.GML.Base,{schemaLocation:"http://www.opengis.net/gml http://schemas.opengis.net/gml/3.1.1/profiles/gmlsfProfile/1.0.0/gmlsf.xsd",curve:false,multiCurve:true,surface:false,multiSurface:true,initialize:function(options){OpenLayers.Format.GML.Base.prototype.initialize.apply(this,[options]);},readers:{"gml":OpenLayers.Util.applyDefaults({"featureMembers":function(node,obj){this.readChildNodes(node,obj);},"Curve":function(node,container){var obj={points:[]};this.readChildNodes(node,obj);if(!container.components){container.components=[];}
container.components.push(new OpenLayers.Geometry.LineString(obj.points));},"segments":function(node,obj){this.readChildNodes(node,obj);},"LineStringSegment":function(node,container){var obj={};this.readChildNodes(node,obj);if(obj.points){Array.prototype.push.apply(container.points,obj.points);}},"pos":function(node,obj){var str=this.getChildValue(node).replace(this.regExes.trimSpace,"");var coords=str.split(this.regExes.splitSpace);var point;if(this.xy){point=new OpenLayers.Geometry.Point(coords[0],coords[1],coords[2]);}else{point=new OpenLayers.Geometry.Point(coords[1],coords[0],coords[2]);}
obj.points=[point];},"posList":function(node,obj){var str=this.getChildValue(node).replace(this.regExes.trimSpace,"");var coords=str.split(this.regExes.splitSpace);var dim=parseInt(node.getAttribute("dimension"))||2;var j,x,y,z;var numPoints=coords.length/dim;var points=new Array(numPoints);for(var i=0,len=coords.length;i<len;i+=dim){x=coords[i];y=coords[i+1];z=(dim==2)?undefined:coords[i+2];if(this.xy){points[i/dim]=new OpenLayers.Geometry.Point(x,y,z);}else{points[i/dim]=new OpenLayers.Geometry.Point(y,x,z);}}
obj.points=points;},"Surface":function(node,obj){this.readChildNodes(node,obj);},"patches":function(node,obj){this.readChildNodes(node,obj);},"PolygonPatch":function(node,obj){this.readers.gml.Polygon.apply(this,[node,obj]);},"exterior":function(node,container){var obj={};this.readChildNodes(node,obj);container.outer=obj.components[0];},"interior":function(node,container){var obj={};this.readChildNodes(node,obj);container.inner.push(obj.components[0]);},"MultiCurve":function(node,container){var obj={components:[]};this.readChildNodes(node,obj);if(obj.components.length>0){container.components=[new OpenLayers.Geometry.MultiLineString(obj.components)];}},"curveMember":function(node,obj){this.readChildNodes(node,obj);},"MultiSurface":function(node,container){var obj={components:[]};this.readChildNodes(node,obj);if(obj.components.length>0){container.components=[new OpenLayers.Geometry.MultiPolygon(obj.components)];}},"surfaceMember":function(node,obj){this.readChildNodes(node,obj);},"surfaceMembers":function(node,obj){this.readChildNodes(node,obj);},"pointMembers":function(node,obj){this.readChildNodes(node,obj);},"lineStringMembers":function(node,obj){this.readChildNodes(node,obj);},"polygonMembers":function(node,obj){this.readChildNodes(node,obj);},"geometryMembers":function(node,obj){this.readChildNodes(node,obj);},"Envelope":function(node,container){var obj={points:new Array(2)};this.readChildNodes(node,obj);if(!container.components){container.components=[];}
var min=obj.points[0];var max=obj.points[1];container.components.push(new OpenLayers.Bounds(min.x,min.y,max.x,max.y));},"lowerCorner":function(node,container){var obj={};this.readers.gml.pos.apply(this,[node,obj]);container.points[0]=obj.points[0];},"upperCorner":function(node,container){var obj={};this.readers.gml.pos.apply(this,[node,obj]);container.points[1]=obj.points[0];}},OpenLayers.Format.GML.Base.prototype.readers["gml"]),"feature":OpenLayers.Format.GML.Base.prototype.readers["feature"],"wfs":OpenLayers.Format.GML.Base.prototype.readers["wfs"]},write:function(features){var name;if(features instanceof Array){name="featureMembers";}else{name="featureMember";}
var root=this.writeNode("gml:"+name,features);this.setAttributeNS(root,this.namespaces["xsi"],"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[root]);},writers:{"gml":OpenLayers.Util.applyDefaults({"featureMembers":function(features){var node=this.createElementNSPlus("gml:featureMembers");for(var i=0,len=features.length;i<len;++i){this.writeNode("feature:_typeName",features[i],node);}
return node;},"Point":function(geometry){var node=this.createElementNSPlus("gml:Point");this.writeNode("pos",geometry,node);return node;},"pos":function(point){var pos=(this.xy)?(point.x+" "+point.y):(point.y+" "+point.x);return this.createElementNSPlus("gml:pos",{value:pos});},"LineString":function(geometry){var node=this.createElementNSPlus("gml:LineString");this.writeNode("posList",geometry.components,node);return node;},"Curve":function(geometry){var node=this.createElementNSPlus("gml:Curve");this.writeNode("segments",geometry,node);return node;},"segments":function(geometry){var node=this.createElementNSPlus("gml:segments");this.writeNode("LineStringSegment",geometry,node);return node;},"LineStringSegment":function(geometry){var node=this.createElementNSPlus("gml:LineStringSegment");this.writeNode("posList",geometry.components,node);return node;},"posList":function(points){var len=points.length;var parts=new Array(len);var point;for(var i=0;i<len;++i){point=points[i];if(this.xy){parts[i]=point.x+" "+point.y;}else{parts[i]=point.y+" "+point.x;}}
return this.createElementNSPlus("gml:posList",{value:parts.join(" ")});},"Surface":function(geometry){var node=this.createElementNSPlus("gml:Surface");this.writeNode("patches",geometry,node);return node;},"patches":function(geometry){var node=this.createElementNSPlus("gml:patches");this.writeNode("PolygonPatch",geometry,node);return node;},"PolygonPatch":function(geometry){var node=this.createElementNSPlus("gml:PolygonPatch",{attributes:{interpolation:"planar"}});this.writeNode("exterior",geometry.components[0],node);for(var i=1,len=geometry.components.length;i<len;++i){this.writeNode("interior",geometry.components[i],node);}
return node;},"Polygon":function(geometry){var node=this.createElementNSPlus("gml:Polygon");this.writeNode("exterior",geometry.components[0],node);for(var i=1,len=geometry.components.length;i<len;++i){this.writeNode("interior",geometry.components[i],node);}
return node;},"exterior":function(ring){var node=this.createElementNSPlus("gml:exterior");this.writeNode("LinearRing",ring,node);return node;},"interior":function(ring){var node=this.createElementNSPlus("gml:interior");this.writeNode("LinearRing",ring,node);return node;},"LinearRing":function(ring){var node=this.createElementNSPlus("gml:LinearRing");this.writeNode("posList",ring.components,node);return node;},"MultiCurve":function(geometry){var node=this.createElementNSPlus("gml:MultiCurve");for(var i=0,len=geometry.components.length;i<len;++i){this.writeNode("curveMember",geometry.components[i],node);}
return node;},"curveMember":function(geometry){var node=this.createElementNSPlus("gml:curveMember");if(this.curve){this.writeNode("Curve",geometry,node);}else{this.writeNode("LineString",geometry,node);}
return node;},"MultiSurface":function(geometry){var node=this.createElementNSPlus("gml:MultiSurface");for(var i=0,len=geometry.components.length;i<len;++i){this.writeNode("surfaceMember",geometry.components[i],node);}
return node;},"surfaceMember":function(polygon){var node=this.createElementNSPlus("gml:surfaceMember");if(this.surface){this.writeNode("Surface",polygon,node);}else{this.writeNode("Polygon",polygon,node);}
return node;},"Envelope":function(bounds){var node=this.createElementNSPlus("gml:Envelope");this.writeNode("lowerCorner",bounds,node);this.writeNode("upperCorner",bounds,node);if(this.srsName){node.setAttribute("srsName",this.srsName);}
return node;},"lowerCorner":function(bounds){var pos=(this.xy)?(bounds.left+" "+bounds.bottom):(bounds.bottom+" "+bounds.left);return this.createElementNSPlus("gml:lowerCorner",{value:pos});},"upperCorner":function(bounds){var pos=(this.xy)?(bounds.right+" "+bounds.top):(bounds.top+" "+bounds.right);return this.createElementNSPlus("gml:upperCorner",{value:pos});}},OpenLayers.Format.GML.Base.prototype.writers["gml"]),"feature":OpenLayers.Format.GML.Base.prototype.writers["feature"],"wfs":OpenLayers.Format.GML.Base.prototype.writers["wfs"]},setGeometryTypes:function(){this.geometryTypes={"OpenLayers.Geometry.Point":"Point","OpenLayers.Geometry.MultiPoint":"MultiPoint","OpenLayers.Geometry.LineString":(this.curve===true)?"Curve":"LineString","OpenLayers.Geometry.MultiLineString":(this.multiCurve===false)?"MultiLineString":"MultiCurve","OpenLayers.Geometry.Polygon":(this.surface===true)?"Surface":"Polygon","OpenLayers.Geometry.MultiPolygon":(this.multiSurface===false)?"MultiPolygon":"MultiSurface","OpenLayers.Geometry.Collection":"GeometryCollection"};},CLASS_NAME:"OpenLayers.Format.GML.v3"});OpenLayers.Format.Atom=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{atom:"http://www.w3.org/2005/Atom",georss:"http://www.georss.org/georss"},feedTitle:"untitled",defaultEntryTitle:"untitled",gmlParser:null,xy:false,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(doc){if(typeof doc=="string"){doc=OpenLayers.Format.XML.prototype.read.apply(this,[doc]);}
return this.parseFeatures(doc);},write:function(features){var doc;if(features instanceof Array){doc=this.createElementNSPlus("atom:feed");doc.appendChild(this.createElementNSPlus("atom:title",{value:this.feedTitle}));for(var i=0,ii=features.length;i<ii;i++){doc.appendChild(this.buildEntryNode(features[i]));}}
else{doc=this.buildEntryNode(features);}
return OpenLayers.Format.XML.prototype.write.apply(this,[doc]);},buildContentNode:function(content){var node=this.createElementNSPlus("atom:content",{attributes:{type:content.type||null}});if(content.src){node.setAttribute("src",content.src);}else{if(content.type=="text"||content.type==null){node.appendChild(this.createTextNode(content.value));}else if(content.type=="html"){if(typeof content.value!="string"){throw"HTML content must be in form of an escaped string";}
node.appendChild(this.createTextNode(content.value));}else if(content.type=="xhtml"){node.appendChild(content.value);}else if(content.type=="xhtml"||content.type.match(/(\+|\/)xml$/)){node.appendChild(content.value);}
else{node.appendChild(this.createTextNode(content.value));}}
return node;},buildEntryNode:function(feature){var attrib=feature.attributes;var atomAttrib=attrib.atom||{};var entryNode=this.createElementNSPlus("atom:entry");if(atomAttrib.authors){var authors=atomAttrib.authors instanceof Array?atomAttrib.authors:[atomAttrib.authors];for(var i=0,ii=authors.length;i<ii;i++){entryNode.appendChild(this.buildPersonConstructNode("author",authors[i]));}}
if(atomAttrib.categories){var categories=atomAttrib.categories instanceof Array?atomAttrib.categories:[atomAttrib.categories];var category;for(var i=0,ii=categories.length;i<ii;i++){category=categories[i];entryNode.appendChild(this.createElementNSPlus("atom:category",{attributes:{term:category.term,scheme:category.scheme||null,label:category.label||null}}));}}
if(atomAttrib.content){entryNode.appendChild(this.buildContentNode(atomAttrib.content));}
if(atomAttrib.contributors){var contributors=atomAttrib.contributors instanceof Array?atomAttrib.contributors:[atomAttrib.contributors];for(var i=0,ii=contributors.length;i<ii;i++){entryNode.appendChild(this.buildPersonConstructNode("contributor",contributors[i]));}}
if(feature.fid){entryNode.appendChild(this.createElementNSPlus("atom:id",{value:feature.fid}));}
if(atomAttrib.links){var links=atomAttrib.links instanceof Array?atomAttrib.links:[atomAttrib.links];var link;for(var i=0,ii=links.length;i<ii;i++){link=links[i];entryNode.appendChild(this.createElementNSPlus("atom:link",{attributes:{href:link.href,rel:link.rel||null,type:link.type||null,hreflang:link.hreflang||null,title:link.title||null,length:link.length||null}}));}}
if(atomAttrib.published){entryNode.appendChild(this.createElementNSPlus("atom:published",{value:atomAttrib.published}));}
if(atomAttrib.rights){entryNode.appendChild(this.createElementNSPlus("atom:rights",{value:atomAttrib.rights}));}
if(atomAttrib.summary||attrib.description){entryNode.appendChild(this.createElementNSPlus("atom:summary",{value:atomAttrib.summary||attrib.description}));}
entryNode.appendChild(this.createElementNSPlus("atom:title",{value:atomAttrib.title||attrib.title||this.defaultEntryTitle}));if(atomAttrib.updated){entryNode.appendChild(this.createElementNSPlus("atom:updated",{value:atomAttrib.updated}));}
if(feature.geometry){var whereNode=this.createElementNSPlus("georss:where");whereNode.appendChild(this.buildGeometryNode(feature.geometry));entryNode.appendChild(whereNode);}
return entryNode;},initGmlParser:function(){this.gmlParser=new OpenLayers.Format.GML.v3({xy:this.xy,featureNS:"http://example.com#feature",internalProjection:this.internalProjection,externalProjection:this.externalProjection});},buildGeometryNode:function(geometry){if(!this.gmlParser){this.initGmlParser();}
var node=this.gmlParser.writeNode("feature:_geometry",geometry);return node.firstChild;},buildPersonConstructNode:function(name,value){var oNames=["uri","email"];var personNode=this.createElementNSPlus("atom:"+name);personNode.appendChild(this.createElementNSPlus("atom:name",{value:value.name}));for(var i=0,ii=oNames.length;i<ii;i++){if(value[oNames[i]]){personNode.appendChild(this.createElementNSPlus("atom:"+oNames[i],{value:value[oNames[i]]}));}}
return personNode;},getFirstChildValue:function(node,nsuri,name,def){var value;var nodes=this.getElementsByTagNameNS(node,nsuri,name);if(nodes&&nodes.length>0){value=this.getChildValue(nodes[0],def);}else{value=def;}
return value;},parseFeature:function(node){var atomAttrib={};var value=null;var nodes=null;var attval=null;var atomns=this.namespaces.atom;this.parsePersonConstructs(node,"author",atomAttrib);nodes=this.getElementsByTagNameNS(node,atomns,"category");if(nodes.length>0){atomAttrib.categories=[];}
for(var i=0,ii=nodes.length;i<ii;i++){value={};value.term=nodes[i].getAttribute("term");attval=nodes[i].getAttribute("scheme");if(attval){value.scheme=attval;}
attval=nodes[i].getAttribute("label");if(attval){value.label=attval;}
atomAttrib.categories.push(value);}
nodes=this.getElementsByTagNameNS(node,atomns,"content");if(nodes.length>0){value={};attval=nodes[0].getAttribute("type");if(attval){value.type=attval;}
attval=nodes[0].getAttribute("src");if(attval){value.src=attval;}else{if(value.type=="text"||value.type=="html"||value.type==null){value.value=this.getFirstChildValue(node,atomns,"content",null);}else if(value.type=="xhtml"||value.type.match(/(\+|\/)xml$/)){value.value=this.getChildEl(nodes[0]);}else{value.value=this.getFirstChildValue(node,atomns,"content",null);}
atomAttrib.content=value;}}
this.parsePersonConstructs(node,"contributor",atomAttrib);atomAttrib.id=this.getFirstChildValue(node,atomns,"id",null);nodes=this.getElementsByTagNameNS(node,atomns,"link");if(nodes.length>0){atomAttrib.links=new Array(nodes.length);}
var oAtts=["rel","type","hreflang","title","length"];for(var i=0,ii=nodes.length;i<ii;i++){value={};value.href=nodes[i].getAttribute("href");for(var j=0,jj=oAtts.length;j<jj;j++){attval=nodes[i].getAttribute(oAtts[j]);if(attval){value[oAtts[j]]=attval;}}
atomAttrib.links[i]=value;}
value=this.getFirstChildValue(node,atomns,"published",null);if(value){atomAttrib.published=value;}
value=this.getFirstChildValue(node,atomns,"rights",null);if(value){atomAttrib.rights=value;}
value=this.getFirstChildValue(node,atomns,"summary",null);if(value){atomAttrib.summary=value;}
atomAttrib.title=this.getFirstChildValue(node,atomns,"title",null);atomAttrib.updated=this.getFirstChildValue(node,atomns,"updated",null);var featureAttrib={title:atomAttrib.title,description:atomAttrib.summary,atom:atomAttrib};var geometry=this.parseLocations(node)[0];var feature=new OpenLayers.Feature.Vector(geometry,featureAttrib);feature.fid=atomAttrib.id;return feature;},parseFeatures:function(node){var features=[];var entries=this.getElementsByTagNameNS(node,this.namespaces.atom,"entry");if(entries.length==0){entries=[node];}
for(var i=0,ii=entries.length;i<ii;i++){features.push(this.parseFeature(entries[i]));}
return features;},parseLocations:function(node){var georssns=this.namespaces.georss;var locations={components:[]};var where=this.getElementsByTagNameNS(node,georssns,"where");if(where&&where.length>0){if(!this.gmlParser){this.initGmlParser();}
for(var i=0,ii=where.length;i<ii;i++){this.gmlParser.readChildNodes(where[i],locations);}}
var components=locations.components;var point=this.getElementsByTagNameNS(node,georssns,"point");if(point&&point.length>0){for(var i=0,ii=point.length;i<ii;i++){var xy=OpenLayers.String.trim(point[i].firstChild.nodeValue).split(/\s+/);if(xy.length!=2){xy=OpenLayers.String.trim(point[i].firstChild.nodeValue).split(/\s*,\s*/);}
components.push(new OpenLayers.Geometry.Point(parseFloat(xy[1]),parseFloat(xy[0])));}}
var line=this.getElementsByTagNameNS(node,georssns,"line");if(line&&line.length>0){var coords;var p;var points;for(var i=0,ii=line.length;i<ii;i++){coords=OpenLayers.String.trim(line[i].firstChild.nodeValue).split(/\s+/);points=[];for(var j=0,jj=coords.length;j<jj;j+=2){p=new OpenLayers.Geometry.Point(parseFloat(coords[j+1]),parseFloat(coords[j]));points.push(p);}
components.push(new OpenLayers.Geometry.LineString(points));}}
var polygon=this.getElementsByTagNameNS(node,georssns,"polygon");if(polygon&&polygon.length>0){var coords;var p;var points;for(var i=0,ii=polygon.length;i<ii;i++){coords=OpenLayers.String.trim(polygon[i].firstChild.nodeValue).split(/\s+/);points=[];for(var j=0,jj=coords.length;j<jj;j+=2){p=new OpenLayers.Geometry.Point(parseFloat(coords[j+1]),parseFloat(coords[j]));points.push(p);}
components.push(new OpenLayers.Geometry.Polygon([new OpenLayers.Geometry.LinearRing(components)]));}}
if(this.internalProjection&&this.externalProjection){for(var i=0,ii=components.length;i<ii;i++){if(components[i]){components[i].transform(this.externalProjection,this.internalProjection);}}}
return components;},parsePersonConstructs:function(node,name,data){var persons=[];var atomns=this.namespaces.atom;var nodes=this.getElementsByTagNameNS(node,atomns,name);var oAtts=["uri","email"];for(var i=0,ii=nodes.length;i<ii;i++){var value={};value.name=this.getFirstChildValue(nodes[i],atomns,"name",null);for(var j=0,jj=oAtts.length;j<jj;j++){var attval=this.getFirstChildValue(nodes[i],atomns,oAtts[j],null);if(attval){value[oAtts[j]]=attval;}}
persons.push(value);}
if(persons.length>0){data[name+"s"]=persons;}},CLASS_NAME:"OpenLayers.Format.Atom"});OpenLayers.Format.Filter.v1_0_0=OpenLayers.Class(OpenLayers.Format.GML.v2,OpenLayers.Format.Filter.v1,{VERSION:"1.0.0",schemaLocation:"http://www.opengis.net/ogc/filter/1.0.0/filter.xsd",initialize:function(options){OpenLayers.Format.GML.v2.prototype.initialize.apply(this,[options]);},readers:{"ogc":OpenLayers.Util.applyDefaults({"PropertyIsEqualTo":function(node,obj){var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO});this.readChildNodes(node,filter);obj.filters.push(filter);},"PropertyIsNotEqualTo":function(node,obj){var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.NOT_EQUAL_TO});this.readChildNodes(node,filter);obj.filters.push(filter);},"PropertyIsLike":function(node,obj){var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LIKE});this.readChildNodes(node,filter);var wildCard=node.getAttribute("wildCard");var singleChar=node.getAttribute("singleChar");var esc=node.getAttribute("escape");filter.value2regex(wildCard,singleChar,esc);obj.filters.push(filter);}},OpenLayers.Format.Filter.v1.prototype.readers["ogc"]),"gml":OpenLayers.Format.GML.v2.prototype.readers["gml"],"feature":OpenLayers.Format.GML.v2.prototype.readers["feature"]},writers:{"ogc":OpenLayers.Util.applyDefaults({"PropertyIsEqualTo":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsEqualTo");this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.value,node);return node;},"PropertyIsNotEqualTo":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsNotEqualTo");this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.value,node);return node;},"PropertyIsLike":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsLike",{attributes:{wildCard:"*",singleChar:".",escape:"!"}});this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.regex2value(),node);return node;},"BBOX":function(filter){var node=this.createElementNSPlus("ogc:BBOX");this.writeNode("PropertyName",filter,node);var box=this.writeNode("gml:Box",filter.value,node);if(filter.projection){box.setAttribute("srsName",filter.projection);}
return node;}},OpenLayers.Format.Filter.v1.prototype.writers["ogc"]),"gml":OpenLayers.Format.GML.v2.prototype.writers["gml"],"feature":OpenLayers.Format.GML.v2.prototype.writers["feature"]},writeSpatial:function(filter,name){var node=this.createElementNSPlus("ogc:"+name);this.writeNode("PropertyName",filter,node);var child;if(filter.value instanceof OpenLayers.Geometry){child=this.writeNode("feature:_geometry",filter.value).firstChild;}else{child=this.writeNode("gml:Box",filter.value);}
if(filter.projection){child.setAttribute("srsName",filter.projection);}
node.appendChild(child);return node;},CLASS_NAME:"OpenLayers.Format.Filter.v1_0_0"});OpenLayers.Format.Filter.v1_1_0=OpenLayers.Class(OpenLayers.Format.GML.v3,OpenLayers.Format.Filter.v1,{VERSION:"1.1.0",schemaLocation:"http://www.opengis.net/ogc/filter/1.1.0/filter.xsd",initialize:function(options){OpenLayers.Format.GML.v3.prototype.initialize.apply(this,[options]);},readers:{"ogc":OpenLayers.Util.applyDefaults({"PropertyIsEqualTo":function(node,obj){var matchCase=node.getAttribute("matchCase");var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.EQUAL_TO,matchCase:!(matchCase==="false"||matchCase==="0")});this.readChildNodes(node,filter);obj.filters.push(filter);},"PropertyIsNotEqualTo":function(node,obj){var matchCase=node.getAttribute("matchCase");var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.NOT_EQUAL_TO,matchCase:!(matchCase==="false"||matchCase==="0")});this.readChildNodes(node,filter);obj.filters.push(filter);},"PropertyIsLike":function(node,obj){var filter=new OpenLayers.Filter.Comparison({type:OpenLayers.Filter.Comparison.LIKE});this.readChildNodes(node,filter);var wildCard=node.getAttribute("wildCard");var singleChar=node.getAttribute("singleChar");var esc=node.getAttribute("escapeChar");filter.value2regex(wildCard,singleChar,esc);obj.filters.push(filter);}},OpenLayers.Format.Filter.v1.prototype.readers["ogc"]),"gml":OpenLayers.Format.GML.v3.prototype.readers["gml"],"feature":OpenLayers.Format.GML.v3.prototype.readers["feature"]},writers:{"ogc":OpenLayers.Util.applyDefaults({"PropertyIsEqualTo":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsEqualTo",{attributes:{matchCase:filter.matchCase}});this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.value,node);return node;},"PropertyIsNotEqualTo":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsNotEqualTo",{attributes:{matchCase:filter.matchCase}});this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.value,node);return node;},"PropertyIsLike":function(filter){var node=this.createElementNSPlus("ogc:PropertyIsLike",{attributes:{wildCard:"*",singleChar:".",escapeChar:"!"}});this.writeNode("PropertyName",filter,node);this.writeNode("Literal",filter.regex2value(),node);return node;},"BBOX":function(filter){var node=this.createElementNSPlus("ogc:BBOX");this.writeNode("PropertyName",filter,node);var box=this.writeNode("gml:Envelope",filter.value);if(filter.projection){box.setAttribute("srsName",filter.projection);}
node.appendChild(box);return node;}},OpenLayers.Format.Filter.v1.prototype.writers["ogc"]),"gml":OpenLayers.Format.GML.v3.prototype.writers["gml"],"feature":OpenLayers.Format.GML.v3.prototype.writers["feature"]},writeSpatial:function(filter,name){var node=this.createElementNSPlus("ogc:"+name);this.writeNode("PropertyName",filter,node);var child;if(filter.value instanceof OpenLayers.Geometry){child=this.writeNode("feature:_geometry",filter.value).firstChild;}else{child=this.writeNode("gml:Envelope",filter.value);}
if(filter.projection){child.setAttribute("srsName",filter.projection);}
node.appendChild(child);return node;},CLASS_NAME:"OpenLayers.Format.Filter.v1_1_0"});OpenLayers.Format.SOSCapabilities.v1_0_0=OpenLayers.Class(OpenLayers.Format.SOSCapabilities,{namespaces:{ows:"http://www.opengis.net/ows/1.1",sos:"http://www.opengis.net/sos/1.0",gml:"http://www.opengis.net/gml",xlink:"http://www.w3.org/1999/xlink"},regExes:{trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)},initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);this.options=options;},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var capabilities={};this.readNode(data,capabilities);return capabilities;},readers:{"gml":OpenLayers.Util.applyDefaults({"name":function(node,obj){obj.name=this.getChildValue(node);},"TimePeriod":function(node,obj){obj.timePeriod={};this.readChildNodes(node,obj.timePeriod);},"beginPosition":function(node,timePeriod){timePeriod.beginPosition=this.getChildValue(node);},"endPosition":function(node,timePeriod){timePeriod.endPosition=this.getChildValue(node);}},OpenLayers.Format.GML.v3.prototype.readers["gml"]),"sos":{"Capabilities":function(node,obj){this.readChildNodes(node,obj);},"Contents":function(node,obj){obj.contents={};this.readChildNodes(node,obj.contents);},"ObservationOfferingList":function(node,contents){contents.offeringList={};this.readChildNodes(node,contents.offeringList);},"ObservationOffering":function(node,offeringList){var id=this.getAttributeNS(node,this.namespaces.gml,"id");offeringList[id]={procedures:[],observedProperties:[],featureOfInterestIds:[],responseFormats:[],resultModels:[],responseModes:[]};this.readChildNodes(node,offeringList[id]);},"time":function(node,offering){offering.time={};this.readChildNodes(node,offering.time);},"procedure":function(node,offering){offering.procedures.push(this.getAttributeNS(node,this.namespaces.xlink,"href"));},"observedProperty":function(node,offering){offering.observedProperties.push(this.getAttributeNS(node,this.namespaces.xlink,"href"));},"featureOfInterest":function(node,offering){offering.featureOfInterestIds.push(this.getAttributeNS(node,this.namespaces.xlink,"href"));},"responseFormat":function(node,offering){offering.responseFormats.push(this.getChildValue(node));},"resultModel":function(node,offering){offering.resultModels.push(this.getChildValue(node));},"responseMode":function(node,offering){offering.responseModes.push(this.getChildValue(node));;}},"ows":OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers["ows"]},CLASS_NAME:"OpenLayers.Format.SOSCapabilities.v1_0_0"});OpenLayers.Format.SOSGetFeatureOfInterest=OpenLayers.Class(OpenLayers.Format.XML,{VERSION:"1.0.0",namespaces:{sos:"http://www.opengis.net/sos/1.0",gml:"http://www.opengis.net/gml",sa:"http://www.opengis.net/sampling/1.0",xsi:"http://www.w3.org/2001/XMLSchema-instance"},schemaLocation:"http://www.opengis.net/sos/1.0 http://schemas.opengis.net/sos/1.0.0/sosAll.xsd",defaultPrefix:"sos",regExes:{trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)},initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var info={features:[]};this.readNode(data,info);var features=[];for(var i=0,len=info.features.length;i<len;i++){var container=info.features[i];if(this.internalProjection&&this.externalProjection&&container.components[0]){container.components[0].transform(this.externalProjection,this.internalProjection);}
var feature=new OpenLayers.Feature.Vector(container.components[0],container.attributes);features.push(feature);}
return features;},readers:{"sa":{"SamplingPoint":function(node,obj){if(!obj.attributes){var feature={attributes:{}};obj.features.push(feature);obj=feature;}
obj.attributes.id=this.getAttributeNS(node,this.namespaces.gml,"id");this.readChildNodes(node,obj);},"position":function(node,obj){this.readChildNodes(node,obj);}},"gml":OpenLayers.Util.applyDefaults({"FeatureCollection":function(node,obj){this.readChildNodes(node,obj);},"featureMember":function(node,obj){var feature={attributes:{}};obj.features.push(feature);this.readChildNodes(node,feature);},"name":function(node,obj){obj.attributes.name=this.getChildValue(node);},"pos":function(node,obj){if(!this.externalProjection){this.externalProjection=new OpenLayers.Projection(node.getAttribute("srsName"));}
OpenLayers.Format.GML.v3.prototype.readers.gml.pos.apply(this,[node,obj]);}},OpenLayers.Format.GML.v3.prototype.readers.gml)},writers:{"sos":{"GetFeatureOfInterest":function(options){var node=this.createElementNSPlus("GetFeatureOfInterest",{attributes:{version:this.VERSION,service:'SOS',"xsi:schemaLocation":this.schemaLocation}});for(var i=0,len=options.fois.length;i<len;i++){this.writeNode("FeatureOfInterestId",{foi:options.fois[i]},node);}
return node;},"FeatureOfInterestId":function(options){var node=this.createElementNSPlus("FeatureOfInterestId",{value:options.foi});return node;}}},CLASS_NAME:"OpenLayers.Format.SOSGetFeatureOfInterest"});OpenLayers.Format.SOSGetObservation=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{ows:"http://www.opengis.net/ows",gml:"http://www.opengis.net/gml",sos:"http://www.opengis.net/sos/1.0",ogc:"http://www.opengis.net/ogc",om:"http://www.opengis.net/om/1.0",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},regExes:{trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)},VERSION:"1.0.0",schemaLocation:"http://www.opengis.net/sos/1.0 http://schemas.opengis.net/sos/1.0.0/sosGetObservation.xsd",defaultPrefix:"sos",initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var info={measurements:[]};this.readNode(data,info);return info;},write:function(options){var node=this.writeNode("sos:GetObservation",options);node.setAttribute("xmlns:om",this.namespaces.om);this.setAttributeNS(node,this.namespaces.xsi,"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[node]);},readers:{"om":{"ObservationCollection":function(node,obj){obj.id=this.getAttributeNS(node,this.namespaces.gml,"id");this.readChildNodes(node,obj);},"member":function(node,observationCollection){this.readChildNodes(node,observationCollection);},"Measurement":function(node,observationCollection){var measurement={};observationCollection.measurements.push(measurement);this.readChildNodes(node,measurement);},"samplingTime":function(node,measurement){var samplingTime={};measurement.samplingTime=samplingTime;this.readChildNodes(node,samplingTime);},"observedProperty":function(node,measurement){measurement.observedProperty=this.getAttributeNS(node,this.namespaces.xlink,"href");this.readChildNodes(node,measurement);},"procedure":function(node,measurement){measurement.procedure=this.getAttributeNS(node,this.namespaces.xlink,"href");this.readChildNodes(node,measurement);},"result":function(node,measurement){var result={};measurement.result=result;if(this.getChildValue(node)!==''){result.value=this.getChildValue(node);result.uom=node.getAttribute("uom");}else{this.readChildNodes(node,result);}}},"gml":OpenLayers.Util.applyDefaults({"TimeInstant":function(node,samplingTime){var timeInstant={};samplingTime.timeInstant=timeInstant;this.readChildNodes(node,timeInstant);},"timePosition":function(node,timeInstant){timeInstant.timePosition=this.getChildValue(node);}},OpenLayers.Format.GML.v3.prototype.readers.gml)},writers:{"sos":{"GetObservation":function(options){var node=this.createElementNSPlus("GetObservation",{attributes:{version:this.VERSION,service:'SOS'}});this.writeNode("offering",options,node);this.writeNode("eventTime",options,node);this.writeNode("procedure",options,node);this.writeNode("observedProperty",options,node);this.writeNode("responseFormat",options,node);this.writeNode("resultModel",options,node);this.writeNode("responseMode",options,node);return node;},"responseFormat":function(options){return this.createElementNSPlus("responseFormat",{value:options.responseFormat});},"procedure":function(options){return this.createElementNSPlus("procedure",{value:options.procedure});},"offering":function(options){return this.createElementNSPlus("offering",{value:options.offering});},"observedProperty":function(options){return this.createElementNSPlus("observedProperty",{value:options.observedProperty});},"eventTime":function(options){var node=this.createElementNSPlus("eventTime");if(options.eventTime==='latest'){this.writeNode("ogc:TM_Equals",options,node);}
return node;},"resultModel":function(options){return this.createElementNSPlus("resultModel",{value:options.resultModel});},"responseMode":function(options){return this.createElementNSPlus("responseMode",{value:options.responseMode});}},"ogc":{"TM_Equals":function(options){var node=this.createElementNSPlus("ogc:TM_Equals");this.writeNode("ogc:PropertyName",{property:"urn:ogc:data:time:iso8601"},node);if(options.eventTime==='latest'){this.writeNode("gml:TimeInstant",{value:'latest'},node);}
return node;},"PropertyName":function(options){return this.createElementNSPlus("ogc:PropertyName",{value:options.property});}},"gml":{"TimeInstant":function(options){var node=this.createElementNSPlus("gml:TimeInstant");this.writeNode("gml:timePosition",options,node);return node;},"timePosition":function(options){var node=this.createElementNSPlus("gml:timePosition",{value:options.value});return node;}}},CLASS_NAME:"OpenLayers.Format.SOSGetObservation"});OpenLayers.Format.CSWGetRecords.v2_0_2=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance",csw:"http://www.opengis.net/cat/csw/2.0.2",dc:"http://purl.org/dc/elements/1.1/",dct:"http://purl.org/dc/terms/",ows:"http://www.opengis.net/ows"},defaultPrefix:"csw",version:"2.0.2",schemaLocation:"http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd",requestId:null,resultType:null,outputFormat:null,outputSchema:null,startPosition:null,maxRecords:null,DistributedSearch:null,ResponseHandler:null,Query:null,regExes:{trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)},initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var obj={};this.readNode(data,obj);return obj;},readers:{"csw":{"GetRecordsResponse":function(node,obj){obj.records=[];this.readChildNodes(node,obj);var version=this.getAttributeNS(node,"",'version');if(version!=""){obj.version=version;}},"RequestId":function(node,obj){obj.RequestId=this.getChildValue(node);},"SearchStatus":function(node,obj){obj.SearchStatus={};var timestamp=this.getAttributeNS(node,"",'timestamp');if(timestamp!=""){obj.SearchStatus.timestamp=timestamp;}},"SearchResults":function(node,obj){this.readChildNodes(node,obj);var attrs=node.attributes;var SearchResults={};for(var i=0,len=attrs.length;i<len;++i){if((attrs[i].name=="numberOfRecordsMatched")||(attrs[i].name=="numberOfRecordsReturned")||(attrs[i].name=="nextRecord")){SearchResults[attrs[i].name]=parseInt(attrs[i].nodeValue);}else{SearchResults[attrs[i].name]=attrs[i].nodeValue;}}
obj.SearchResults=SearchResults;},"SummaryRecord":function(node,obj){var record={type:"SummaryRecord"};this.readChildNodes(node,record);obj.records.push(record);},"BriefRecord":function(node,obj){var record={type:"BriefRecord"};this.readChildNodes(node,record);obj.records.push(record);},"DCMIRecord":function(node,obj){var record={type:"DCMIRecord"};this.readChildNodes(node,record);obj.records.push(record);},"Record":function(node,obj){var record={type:"Record"};this.readChildNodes(node,record);obj.records.push(record);}},"dc":{"*":function(node,obj){var name=node.localName||node.nodeName.split(":").pop();if(!(obj[name]instanceof Array)){obj[name]=new Array();}
var dc_element={};var attrs=node.attributes;for(var i=0,len=attrs.length;i<len;++i){dc_element[attrs[i].name]=attrs[i].nodeValue;}
dc_element.value=this.getChildValue(node);obj[name].push(dc_element);}},"dct":{"*":function(node,obj){var name=node.localName||node.nodeName.split(":").pop();if(!(obj[name]instanceof Array)){obj[name]=new Array();}
obj[name].push(this.getChildValue(node));}},"ows":OpenLayers.Util.applyDefaults({"BoundingBox":function(node,obj){if(obj.bounds){obj.BoundingBox=[{crs:obj.projection,value:[obj.bounds.left,obj.bounds.bottom,obj.bounds.right,obj.bounds.top]}];delete obj.projection;delete obj.bounds;}
OpenLayers.Format.OWSCommon.v1_0_0.prototype.readers["ows"]["BoundingBox"].apply(this,arguments);}},OpenLayers.Format.OWSCommon.v1_0_0.prototype.readers["ows"])},write:function(options){var node=this.writeNode("csw:GetRecords",options);return OpenLayers.Format.XML.prototype.write.apply(this,[node]);},writers:{"csw":{"GetRecords":function(options){if(!options){options={};}
var node=this.createElementNSPlus("csw:GetRecords",{attributes:{service:"CSW",version:this.version,requestId:options.requestId||this.requestId,resultType:options.resultType||this.resultType,outputFormat:options.outputFormat||this.outputFormat,outputSchema:options.outputSchema||this.outputSchema,startPosition:options.startPosition||this.startPosition,maxRecords:options.maxRecords||this.maxRecords}});if(options.DistributedSearch||this.DistributedSearch){this.writeNode("csw:DistributedSearch",options.DistributedSearch||this.DistributedSearch,node);}
var ResponseHandler=options.ResponseHandler||this.ResponseHandler;if(ResponseHandler instanceof Array&&ResponseHandler.length>0){for(var i=0,len=ResponseHandler.length;i<len;i++){this.writeNode("csw:ResponseHandler",ResponseHandler[i],node);}}
this.writeNode("Query",options.Query||this.Query,node);return node;},"DistributedSearch":function(options){var node=this.createElementNSPlus("csw:DistributedSearch",{attributes:{hopCount:options.hopCount}});return node;},"ResponseHandler":function(options){var node=this.createElementNSPlus("csw:ResponseHandler",{value:options.value});return node;},"Query":function(options){if(!options){options={};}
var node=this.createElementNSPlus("csw:Query",{attributes:{typeNames:options.typeNames||"csw:Record"}});var ElementName=options.ElementName;if(ElementName instanceof Array&&ElementName.length>0){for(var i=0,len=ElementName.length;i<len;i++){this.writeNode("csw:ElementName",ElementName[i],node);}}else{this.writeNode("csw:ElementSetName",options.ElementSetName||{value:'summary'},node);}
if(options.Constraint){this.writeNode("csw:Constraint",options.Constraint,node);}
return node;},"ElementName":function(options){var node=this.createElementNSPlus("csw:ElementName",{value:options.value});return node;},"ElementSetName":function(options){var node=this.createElementNSPlus("csw:ElementSetName",{attributes:{typeNames:options.typeNames},value:options.value});return node;},"Constraint":function(options){var node=this.createElementNSPlus("csw:Constraint",{attributes:{version:options.version}});if(options.Filter){var format=new OpenLayers.Format.Filter({version:options.version});node.appendChild(format.write(options.Filter));}else if(options.CqlText){var child=this.createElementNSPlus("CqlText",{value:options.CqlText.value});node.appendChild(child);}
return node;}}},CLASS_NAME:"OpenLayers.Format.CSWGetRecords.v2_0_2"});OpenLayers.Format.SLD.v1=OpenLayers.Class(OpenLayers.Format.Filter.v1_0_0,{namespaces:{sld:"http://www.opengis.net/sld",ogc:"http://www.opengis.net/ogc",gml:"http://www.opengis.net/gml",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},defaultPrefix:"sld",schemaLocation:null,multipleSymbolizers:false,featureTypeCounter:null,defaultSymbolizer:{fillColor:"#808080",fillOpacity:1,strokeColor:"#000000",strokeOpacity:1,strokeWidth:1,strokeDashstyle:"solid",pointRadius:3,graphicName:"square"},initialize:function(options){OpenLayers.Format.Filter.v1_0_0.prototype.initialize.apply(this,[options]);},read:function(data,options){options=OpenLayers.Util.applyDefaults(options,this.options);var sld={namedLayers:options.namedLayersAsArray===true?[]:{}};this.readChildNodes(data,sld);return sld;},readers:OpenLayers.Util.applyDefaults({"sld":{"StyledLayerDescriptor":function(node,sld){sld.version=node.getAttribute("version");this.readChildNodes(node,sld);},"Name":function(node,obj){obj.name=this.getChildValue(node);},"Title":function(node,obj){obj.title=this.getChildValue(node);},"Abstract":function(node,obj){obj.description=this.getChildValue(node);},"NamedLayer":function(node,sld){var layer={userStyles:[],namedStyles:[]};this.readChildNodes(node,layer);for(var i=0,len=layer.userStyles.length;i<len;++i){layer.userStyles[i].layerName=layer.name;}
if(sld.namedLayers instanceof Array){sld.namedLayers.push(layer);}else{sld.namedLayers[layer.name]=layer;}},"NamedStyle":function(node,layer){layer.namedStyles.push(this.getChildName(node.firstChild));},"UserStyle":function(node,layer){var obj={defaultsPerSymbolizer:true,rules:[]};this.featureTypeCounter=-1;this.readChildNodes(node,obj);var style;if(this.multipleSymbolizers){delete obj.defaultsPerSymbolizer;style=new OpenLayers.Style2(obj);}else{style=new OpenLayers.Style(this.defaultSymbolizer,obj);}
layer.userStyles.push(style);},"IsDefault":function(node,style){if(this.getChildValue(node)=="1"){style.isDefault=true;}},"FeatureTypeStyle":function(node,style){++this.featureTypeCounter;var obj={rules:this.multipleSymbolizers?style.rules:[]};this.readChildNodes(node,obj);if(!this.multipleSymbolizers){style.rules=obj.rules;}},"Rule":function(node,obj){var config;if(this.multipleSymbolizers){config={symbolizers:[]};}
var rule=new OpenLayers.Rule(config);this.readChildNodes(node,rule);obj.rules.push(rule);},"ElseFilter":function(node,rule){rule.elseFilter=true;},"MinScaleDenominator":function(node,rule){rule.minScaleDenominator=parseFloat(this.getChildValue(node));},"MaxScaleDenominator":function(node,rule){rule.maxScaleDenominator=parseFloat(this.getChildValue(node));},"TextSymbolizer":function(node,rule){var config={};this.readChildNodes(node,config);if(this.multipleSymbolizers){config.zIndex=this.featureTypeCounter;rule.symbolizers.push(new OpenLayers.Symbolizer.Text(config));}else{rule.symbolizer["Text"]=OpenLayers.Util.applyDefaults(config,rule.symbolizer["Text"]);}},"Label":function(node,symbolizer){var obj={};this.readChildNodes(node,obj);if(obj.property){symbolizer.label="${"+obj.property+"}";}else{var value=this.readOgcExpression(node);if(value){symbolizer.label=value;}}},"Font":function(node,symbolizer){this.readChildNodes(node,symbolizer);},"Halo":function(node,symbolizer){var obj={};this.readChildNodes(node,obj);symbolizer.haloRadius=obj.haloRadius;symbolizer.haloColor=obj.fillColor;symbolizer.haloOpacity=obj.fillOpacity;},"Radius":function(node,symbolizer){var radius=this.readOgcExpression(node);if(radius!=null){symbolizer.haloRadius=radius;}},"RasterSymbolizer":function(node,rule){var config={};this.readChildNodes(node,config);if(this.multipleSymbolizers){config.zIndex=this.featureTypeCounter;rule.symbolizers.push(new OpenLayers.Symbolizer.Raster(config));}else{rule.symbolizer["Raster"]=OpenLayers.Util.applyDefaults(config,rule.symbolizer["Raster"]);}},"Geometry":function(node,obj){obj.geometry={};this.readChildNodes(node,obj.geometry);},"ColorMap":function(node,symbolizer){symbolizer.colorMap=[];this.readChildNodes(node,symbolizer.colorMap);},"ColorMapEntry":function(node,colorMap){var q=node.getAttribute("quantity");var o=node.getAttribute("opacity");colorMap.push({color:node.getAttribute("color"),quantity:q!==null?parseFloat(q):undefined,label:node.getAttribute("label")||undefined,opacity:o!==null?parseFloat(o):undefined});},"LineSymbolizer":function(node,rule){var config={};this.readChildNodes(node,config);if(this.multipleSymbolizers){config.zIndex=this.featureTypeCounter;rule.symbolizers.push(new OpenLayers.Symbolizer.Line(config));}else{rule.symbolizer["Line"]=OpenLayers.Util.applyDefaults(config,rule.symbolizer["Line"]);}},"PolygonSymbolizer":function(node,rule){var config={fill:false,stroke:false};if(!this.multipleSymbolizers){config=rule.symbolizer["Polygon"]||config;}
this.readChildNodes(node,config);if(this.multipleSymbolizers){config.zIndex=this.featureTypeCounter;rule.symbolizers.push(new OpenLayers.Symbolizer.Polygon(config));}else{rule.symbolizer["Polygon"]=config;}},"PointSymbolizer":function(node,rule){var config={fill:false,stroke:false,graphic:false};if(!this.multipleSymbolizers){config=rule.symbolizer["Point"]||config;}
this.readChildNodes(node,config);if(this.multipleSymbolizers){config.zIndex=this.featureTypeCounter;rule.symbolizers.push(new OpenLayers.Symbolizer.Point(config));}else{rule.symbolizer["Point"]=config;}},"Stroke":function(node,symbolizer){symbolizer.stroke=true;this.readChildNodes(node,symbolizer);},"Fill":function(node,symbolizer){symbolizer.fill=true;this.readChildNodes(node,symbolizer);},"CssParameter":function(node,symbolizer){var cssProperty=node.getAttribute("name");var symProperty=this.cssMap[cssProperty];if(symProperty){var value=this.readOgcExpression(node);if(value){symbolizer[symProperty]=value;}}},"Graphic":function(node,symbolizer){symbolizer.graphic=true;var graphic={};this.readChildNodes(node,graphic);var properties=["stroke","strokeColor","strokeWidth","strokeOpacity","strokeLinecap","fill","fillColor","fillOpacity","graphicName","rotation","graphicFormat"];var prop,value;for(var i=0,len=properties.length;i<len;++i){prop=properties[i];value=graphic[prop];if(value!=undefined){symbolizer[prop]=value;}}
if(graphic.opacity!=undefined){symbolizer.graphicOpacity=graphic.opacity;}
if(graphic.size!=undefined){symbolizer.pointRadius=graphic.size/2;}
if(graphic.href!=undefined){symbolizer.externalGraphic=graphic.href;}
if(graphic.rotation!=undefined){symbolizer.rotation=graphic.rotation;}},"ExternalGraphic":function(node,graphic){this.readChildNodes(node,graphic);},"Mark":function(node,graphic){this.readChildNodes(node,graphic);},"WellKnownName":function(node,graphic){graphic.graphicName=this.getChildValue(node);},"Opacity":function(node,obj){var opacity=this.readOgcExpression(node);if(opacity){obj.opacity=opacity;}},"Size":function(node,obj){var size=this.readOgcExpression(node);if(size){obj.size=size;}},"Rotation":function(node,obj){var rotation=this.readOgcExpression(node);if(rotation){obj.rotation=rotation;}},"OnlineResource":function(node,obj){obj.href=this.getAttributeNS(node,this.namespaces.xlink,"href");},"Format":function(node,graphic){graphic.graphicFormat=this.getChildValue(node);}}},OpenLayers.Format.Filter.v1_0_0.prototype.readers),cssMap:{"stroke":"strokeColor","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","stroke-linecap":"strokeLinecap","stroke-dasharray":"strokeDashstyle","fill":"fillColor","fill-opacity":"fillOpacity","font-family":"fontFamily","font-size":"fontSize","font-weight":"fontWeight","font-style":"fontStyle"},getCssProperty:function(sym){var css=null;for(var prop in this.cssMap){if(this.cssMap[prop]==sym){css=prop;break;}}
return css;},getGraphicFormat:function(href){var format,regex;for(var key in this.graphicFormats){if(this.graphicFormats[key].test(href)){format=key;break;}}
return format||this.defautlGraphicFormat;},defaultGraphicFormat:"image/png",graphicFormats:{"image/jpeg":/\.jpe?g$/i,"image/gif":/\.gif$/i,"image/png":/\.png$/i},write:function(sld){return this.writers.sld.StyledLayerDescriptor.apply(this,[sld]);},writers:OpenLayers.Util.applyDefaults({"sld":{"StyledLayerDescriptor":function(sld){var root=this.createElementNSPlus("sld:StyledLayerDescriptor",{attributes:{"version":this.VERSION,"xsi:schemaLocation":this.schemaLocation}});root.setAttribute("xmlns:ogc",this.namespaces.ogc);root.setAttribute("xmlns:gml",this.namespaces.gml);if(sld.name){this.writeNode("Name",sld.name,root);}
if(sld.title){this.writeNode("Title",sld.title,root);}
if(sld.description){this.writeNode("Abstract",sld.description,root);}
if(sld.namedLayers instanceof Array){for(var i=0,len=sld.namedLayers.length;i<len;++i){this.writeNode("NamedLayer",sld.namedLayers[i],root);}}else{for(var name in sld.namedLayers){this.writeNode("NamedLayer",sld.namedLayers[name],root);}}
return root;},"Name":function(name){return this.createElementNSPlus("sld:Name",{value:name});},"Title":function(title){return this.createElementNSPlus("sld:Title",{value:title});},"Abstract":function(description){return this.createElementNSPlus("sld:Abstract",{value:description});},"NamedLayer":function(layer){var node=this.createElementNSPlus("sld:NamedLayer");this.writeNode("Name",layer.name,node);if(layer.namedStyles){for(var i=0,len=layer.namedStyles.length;i<len;++i){this.writeNode("NamedStyle",layer.namedStyles[i],node);}}
if(layer.userStyles){for(var i=0,len=layer.userStyles.length;i<len;++i){this.writeNode("UserStyle",layer.userStyles[i],node);}}
return node;},"NamedStyle":function(name){var node=this.createElementNSPlus("sld:NamedStyle");this.writeNode("Name",name,node);return node;},"UserStyle":function(style){var node=this.createElementNSPlus("sld:UserStyle");if(style.name){this.writeNode("Name",style.name,node);}
if(style.title){this.writeNode("Title",style.title,node);}
if(style.description){this.writeNode("Abstract",style.description,node);}
if(style.isDefault){this.writeNode("IsDefault",style.isDefault,node);}
if(this.multipleSymbolizers&&style.rules){var rulesByZ={0:[]};var zValues=[0];var rule,ruleMap,symbolizer,zIndex,clone;for(var i=0,ii=style.rules.length;i<ii;++i){rule=style.rules[i];if(rule.symbolizers){ruleMap={};for(var j=0,jj=rule.symbolizers.length;j<jj;++j){symbolizer=rule.symbolizers[j];zIndex=symbolizer.zIndex;if(!(zIndex in ruleMap)){clone=rule.clone();clone.symbolizers=[];ruleMap[zIndex]=clone;}
ruleMap[zIndex].symbolizers.push(symbolizer.clone());}
for(zIndex in ruleMap){if(!(zIndex in rulesByZ)){zValues.push(zIndex);rulesByZ[zIndex]=[];}
rulesByZ[zIndex].push(ruleMap[zIndex]);}}else{rulesByZ[0].push(rule.clone());}}
zValues.sort();var rules;for(var i=0,ii=zValues.length;i<ii;++i){rules=rulesByZ[zValues[i]];if(rules.length>0){clone=style.clone();clone.rules=rulesByZ[zValues[i]];this.writeNode("FeatureTypeStyle",clone,node);}}}else{this.writeNode("FeatureTypeStyle",style,node);}
return node;},"IsDefault":function(bool){return this.createElementNSPlus("sld:IsDefault",{value:(bool)?"1":"0"});},"FeatureTypeStyle":function(style){var node=this.createElementNSPlus("sld:FeatureTypeStyle");for(var i=0,len=style.rules.length;i<len;++i){this.writeNode("Rule",style.rules[i],node);}
return node;},"Rule":function(rule){var node=this.createElementNSPlus("sld:Rule");if(rule.name){this.writeNode("Name",rule.name,node);}
if(rule.title){this.writeNode("Title",rule.title,node);}
if(rule.description){this.writeNode("Abstract",rule.description,node);}
if(rule.elseFilter){this.writeNode("ElseFilter",null,node);}else if(rule.filter){this.writeNode("ogc:Filter",rule.filter,node);}
if(rule.minScaleDenominator!=undefined){this.writeNode("MinScaleDenominator",rule.minScaleDenominator,node);}
if(rule.maxScaleDenominator!=undefined){this.writeNode("MaxScaleDenominator",rule.maxScaleDenominator,node);}
var type,symbolizer;if(this.multipleSymbolizers&&rule.symbolizers){var symbolizer;for(var i=0,ii=rule.symbolizers.length;i<ii;++i){symbolizer=rule.symbolizers[i];type=symbolizer.CLASS_NAME.split(".").pop();this.writeNode(type+"Symbolizer",symbolizer,node);}}else{var types=OpenLayers.Style.SYMBOLIZER_PREFIXES;for(var i=0,len=types.length;i<len;++i){type=types[i];symbolizer=rule.symbolizer[type];if(symbolizer){this.writeNode(type+"Symbolizer",symbolizer,node);}}}
return node;},"ElseFilter":function(){return this.createElementNSPlus("sld:ElseFilter");},"MinScaleDenominator":function(scale){return this.createElementNSPlus("sld:MinScaleDenominator",{value:scale});},"MaxScaleDenominator":function(scale){return this.createElementNSPlus("sld:MaxScaleDenominator",{value:scale});},"LineSymbolizer":function(symbolizer){var node=this.createElementNSPlus("sld:LineSymbolizer");this.writeNode("Stroke",symbolizer,node);return node;},"Stroke":function(symbolizer){var node=this.createElementNSPlus("sld:Stroke");if(symbolizer.strokeColor!=undefined){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"strokeColor"},node);}
if(symbolizer.strokeOpacity!=undefined){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"strokeOpacity"},node);}
if(symbolizer.strokeWidth!=undefined){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"strokeWidth"},node);}
if(symbolizer.strokeDashstyle!=undefined&&symbolizer.strokeDashstyle!=="solid"){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"strokeDashstyle"},node);}
if(symbolizer.strokeLinecap!=undefined){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"strokeLinecap"},node);}
return node;},"CssParameter":function(obj){return this.createElementNSPlus("sld:CssParameter",{attributes:{name:this.getCssProperty(obj.key)},value:obj.symbolizer[obj.key]});},"TextSymbolizer":function(symbolizer){var node=this.createElementNSPlus("sld:TextSymbolizer");if(symbolizer.label!=null){this.writeNode("Label",symbolizer.label,node);}
if(symbolizer.fontFamily!=null||symbolizer.fontSize!=null||symbolizer.fontWeight!=null||symbolizer.fontStyle!=null){this.writeNode("Font",symbolizer,node);}
if(symbolizer.haloRadius!=null||symbolizer.haloColor!=null||symbolizer.haloOpacity!=null){this.writeNode("Halo",symbolizer,node);}
if(symbolizer.fillColor!=null||symbolizer.fillOpacity!=null){this.writeNode("Fill",symbolizer,node);}
return node;},"Font":function(symbolizer){var node=this.createElementNSPlus("sld:Font");if(symbolizer.fontFamily){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fontFamily"},node);}
if(symbolizer.fontSize){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fontSize"},node);}
if(symbolizer.fontWeight){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fontWeight"},node);}
if(symbolizer.fontStyle){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fontStyle"},node);}
return node;},"Label":function(label){var node=this.createElementNSPlus("sld:Label");var tokens=label.split("${");node.appendChild(this.createTextNode(tokens[0]));var item,last;for(var i=1,len=tokens.length;i<len;i++){item=tokens[i];last=item.indexOf("}");if(last>0){this.writeNode("ogc:PropertyName",{property:item.substring(0,last)},node);node.appendChild(this.createTextNode(item.substring(++last)));}else{node.appendChild(this.createTextNode("${"+item));}}
return node;},"Halo":function(symbolizer){var node=this.createElementNSPlus("sld:Halo");if(symbolizer.haloRadius){this.writeNode("Radius",symbolizer.haloRadius,node);}
if(symbolizer.haloColor||symbolizer.haloOpacity){this.writeNode("Fill",{fillColor:symbolizer.haloColor,fillOpacity:symbolizer.haloOpacity},node);}
return node;},"Radius":function(value){return this.createElementNSPlus("sld:Radius",{value:value});},"RasterSymbolizer":function(symbolizer){var node=this.createElementNSPlus("sld:RasterSymbolizer");if(symbolizer.geometry){this.writeNode("Geometry",symbolizer.geometry,node);}
if(symbolizer.opacity){this.writeNode("Opacity",symbolizer.opacity,node);}
if(symbolizer.colorMap){this.writeNode("ColorMap",symbolizer.colorMap,node);}
return node;},"Geometry":function(geometry){var node=this.createElementNSPlus("sld:Geometry");if(geometry.property){this.writeNode("ogc:PropertyName",geometry,node);}
return node;},"ColorMap":function(colorMap){var node=this.createElementNSPlus("sld:ColorMap");for(var i=0,len=colorMap.length;i<len;++i){this.writeNode("ColorMapEntry",colorMap[i],node);}
return node;},"ColorMapEntry":function(colorMapEntry){var node=this.createElementNSPlus("sld:ColorMapEntry");var a=colorMapEntry;node.setAttribute("color",a.color);a.opacity!==undefined&&node.setAttribute("opacity",parseFloat(a.opacity));a.quantity!==undefined&&node.setAttribute("quantity",parseFloat(a.quantity));a.label!==undefined&&node.setAttribute("label",a.label);return node;},"PolygonSymbolizer":function(symbolizer){var node=this.createElementNSPlus("sld:PolygonSymbolizer");if(symbolizer.fill!==false){this.writeNode("Fill",symbolizer,node);}
if(symbolizer.stroke!==false){this.writeNode("Stroke",symbolizer,node);}
return node;},"Fill":function(symbolizer){var node=this.createElementNSPlus("sld:Fill");if(symbolizer.fillColor){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fillColor"},node);}
if(symbolizer.fillOpacity!=null){this.writeNode("CssParameter",{symbolizer:symbolizer,key:"fillOpacity"},node);}
return node;},"PointSymbolizer":function(symbolizer){var node=this.createElementNSPlus("sld:PointSymbolizer");this.writeNode("Graphic",symbolizer,node);return node;},"Graphic":function(symbolizer){var node=this.createElementNSPlus("sld:Graphic");if(symbolizer.externalGraphic!=undefined){this.writeNode("ExternalGraphic",symbolizer,node);}else{this.writeNode("Mark",symbolizer,node);}
if(symbolizer.graphicOpacity!=undefined){this.writeNode("Opacity",symbolizer.graphicOpacity,node);}
if(symbolizer.pointRadius!=undefined){this.writeNode("Size",symbolizer.pointRadius*2,node);}
if(symbolizer.rotation!=undefined){this.writeNode("Rotation",symbolizer.rotation,node);}
return node;},"ExternalGraphic":function(symbolizer){var node=this.createElementNSPlus("sld:ExternalGraphic");this.writeNode("OnlineResource",symbolizer.externalGraphic,node);var format=symbolizer.graphicFormat||this.getGraphicFormat(symbolizer.externalGraphic);this.writeNode("Format",format,node);return node;},"Mark":function(symbolizer){var node=this.createElementNSPlus("sld:Mark");if(symbolizer.graphicName){this.writeNode("WellKnownName",symbolizer.graphicName,node);}
if(symbolizer.fill!==false){this.writeNode("Fill",symbolizer,node);}
if(symbolizer.stroke!==false){this.writeNode("Stroke",symbolizer,node);}
return node;},"WellKnownName":function(name){return this.createElementNSPlus("sld:WellKnownName",{value:name});},"Opacity":function(value){return this.createElementNSPlus("sld:Opacity",{value:value});},"Size":function(value){return this.createElementNSPlus("sld:Size",{value:value});},"Rotation":function(value){return this.createElementNSPlus("sld:Rotation",{value:value});},"OnlineResource":function(href){return this.createElementNSPlus("sld:OnlineResource",{attributes:{"xlink:type":"simple","xlink:href":href}});},"Format":function(format){return this.createElementNSPlus("sld:Format",{value:format});}}},OpenLayers.Format.Filter.v1_0_0.prototype.writers),CLASS_NAME:"OpenLayers.Format.SLD.v1"});OpenLayers.Format.WFST.v1_0_0=OpenLayers.Class(OpenLayers.Format.Filter.v1_0_0,OpenLayers.Format.WFST.v1,{version:"1.0.0",srsNameInQuery:false,schemaLocations:{"wfs":"http://schemas.opengis.net/wfs/1.0.0/WFS-transaction.xsd"},initialize:function(options){OpenLayers.Format.Filter.v1_0_0.prototype.initialize.apply(this,[options]);OpenLayers.Format.WFST.v1.prototype.initialize.apply(this,[options]);},readers:{"wfs":OpenLayers.Util.applyDefaults({"WFS_TransactionResponse":function(node,obj){obj.insertIds=[];obj.success=false;this.readChildNodes(node,obj);},"InsertResult":function(node,container){var obj={fids:[]};this.readChildNodes(node,obj);container.insertIds.push(obj.fids[0]);},"TransactionResult":function(node,obj){this.readChildNodes(node,obj);},"Status":function(node,obj){this.readChildNodes(node,obj);},"SUCCESS":function(node,obj){obj.success=true;}},OpenLayers.Format.WFST.v1.prototype.readers["wfs"]),"gml":OpenLayers.Format.GML.v2.prototype.readers["gml"],"feature":OpenLayers.Format.GML.v2.prototype.readers["feature"],"ogc":OpenLayers.Format.Filter.v1_0_0.prototype.readers["ogc"]},writers:{"wfs":OpenLayers.Util.applyDefaults({"Query":function(options){options=OpenLayers.Util.extend({featureNS:this.featureNS,featurePrefix:this.featurePrefix,featureType:this.featureType,srsName:this.srsName,srsNameInQuery:this.srsNameInQuery},options);var node=this.createElementNSPlus("wfs:Query",{attributes:{typeName:(options.featureNS?options.featurePrefix+":":"")+
options.featureType}});if(options.srsNameInQuery&&options.srsName){node.setAttribute("srsName",options.srsName);}
if(options.featureNS){node.setAttribute("xmlns:"+options.featurePrefix,options.featureNS);}
if(options.propertyNames){for(var i=0,len=options.propertyNames.length;i<len;i++){this.writeNode("ogc:PropertyName",{property:options.propertyNames[i]},node);}}
if(options.filter){this.setFilterProperty(options.filter);this.writeNode("ogc:Filter",options.filter,node);}
return node;}},OpenLayers.Format.WFST.v1.prototype.writers["wfs"]),"gml":OpenLayers.Format.GML.v2.prototype.writers["gml"],"feature":OpenLayers.Format.GML.v2.prototype.writers["feature"],"ogc":OpenLayers.Format.Filter.v1_0_0.prototype.writers["ogc"]},CLASS_NAME:"OpenLayers.Format.WFST.v1_0_0"});OpenLayers.Format.WFST.v1_1_0=OpenLayers.Class(OpenLayers.Format.Filter.v1_1_0,OpenLayers.Format.WFST.v1,{version:"1.1.0",schemaLocations:{"wfs":"http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"},initialize:function(options){OpenLayers.Format.Filter.v1_1_0.prototype.initialize.apply(this,[options]);OpenLayers.Format.WFST.v1.prototype.initialize.apply(this,[options]);},readers:{"wfs":OpenLayers.Util.applyDefaults({"FeatureCollection":function(node,obj){obj.numberOfFeatures=parseInt(node.getAttribute("numberOfFeatures"));OpenLayers.Format.WFST.v1.prototype.readers["wfs"]["FeatureCollection"].apply(this,arguments);},"TransactionResponse":function(node,obj){obj.insertIds=[];obj.success=false;this.readChildNodes(node,obj);},"TransactionSummary":function(node,obj){obj.success=true;},"InsertResults":function(node,obj){this.readChildNodes(node,obj);},"Feature":function(node,container){var obj={fids:[]};this.readChildNodes(node,obj);container.insertIds.push(obj.fids[0]);}},OpenLayers.Format.WFST.v1.prototype.readers["wfs"]),"gml":OpenLayers.Format.GML.v3.prototype.readers["gml"],"feature":OpenLayers.Format.GML.v3.prototype.readers["feature"],"ogc":OpenLayers.Format.Filter.v1_1_0.prototype.readers["ogc"]},writers:{"wfs":OpenLayers.Util.applyDefaults({"GetFeature":function(options){var node=OpenLayers.Format.WFST.v1.prototype.writers["wfs"]["GetFeature"].apply(this,arguments);options&&options.resultType&&this.setAttributes(node,{resultType:options.resultType});return node;},"Query":function(options){options=OpenLayers.Util.extend({featureNS:this.featureNS,featurePrefix:this.featurePrefix,featureType:this.featureType,srsName:this.srsName},options);var node=this.createElementNSPlus("wfs:Query",{attributes:{typeName:(options.featureNS?options.featurePrefix+":":"")+
options.featureType,srsName:options.srsName}});if(options.featureNS){node.setAttribute("xmlns:"+options.featurePrefix,options.featureNS);}
if(options.propertyNames){for(var i=0,len=options.propertyNames.length;i<len;i++){this.writeNode("wfs:PropertyName",{property:options.propertyNames[i]},node);}}
if(options.filter){this.setFilterProperty(options.filter);this.writeNode("ogc:Filter",options.filter,node);}
return node;},"PropertyName":function(obj){return this.createElementNSPlus("wfs:PropertyName",{value:obj.property});}},OpenLayers.Format.WFST.v1.prototype.writers["wfs"]),"gml":OpenLayers.Format.GML.v3.prototype.writers["gml"],"feature":OpenLayers.Format.GML.v3.prototype.writers["feature"],"ogc":OpenLayers.Format.Filter.v1_1_0.prototype.writers["ogc"]},CLASS_NAME:"OpenLayers.Format.WFST.v1_1_0"});OpenLayers.Protocol.SOS.v1_0_0=OpenLayers.Class(OpenLayers.Protocol,{fois:null,formatOptions:null,initialize:function(options){OpenLayers.Protocol.prototype.initialize.apply(this,[options]);if(!options.format){this.format=new OpenLayers.Format.SOSGetFeatureOfInterest(this.formatOptions);}},destroy:function(){if(this.options&&!this.options.format){this.format.destroy();}
this.format=null;OpenLayers.Protocol.prototype.destroy.apply(this);},read:function(options){options=OpenLayers.Util.extend({},options);OpenLayers.Util.applyDefaults(options,this.options||{});var response=new OpenLayers.Protocol.Response({requestType:"read"});var format=this.format;var data=OpenLayers.Format.XML.prototype.write.apply(format,[format.writeNode("sos:GetFeatureOfInterest",{fois:this.fois})]);response.priv=OpenLayers.Request.POST({url:options.url,callback:this.createCallback(this.handleRead,response,options),data:data});return response;},handleRead:function(response,options){if(options.callback){var request=response.priv;if(request.status>=200&&request.status<300){response.features=this.parseFeatures(request);response.code=OpenLayers.Protocol.Response.SUCCESS;}else{response.code=OpenLayers.Protocol.Response.FAILURE;}
options.callback.call(options.scope,response);}},parseFeatures:function(request){var doc=request.responseXML;if(!doc||!doc.documentElement){doc=request.responseText;}
if(!doc||doc.length<=0){return null;}
return this.format.read(doc);},CLASS_NAME:"OpenLayers.Protocol.SOS.v1_0_0"});OpenLayers.Format.SLD.v1_0_0=OpenLayers.Class(OpenLayers.Format.SLD.v1,{VERSION:"1.0.0",schemaLocation:"http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd",initialize:function(options){OpenLayers.Format.SLD.v1.prototype.initialize.apply(this,[options]);},CLASS_NAME:"OpenLayers.Format.SLD.v1_0_0"});OpenLayers.Protocol.WFS.v1_0_0=OpenLayers.Class(OpenLayers.Protocol.WFS.v1,{version:"1.0.0",CLASS_NAME:"OpenLayers.Protocol.WFS.v1_0_0"});OpenLayers.Protocol.WFS.v1_1_0=OpenLayers.Class(OpenLayers.Protocol.WFS.v1,{version:"1.1.0",CLASS_NAME:"OpenLayers.Protocol.WFS.v1_1_0"});OpenLayers.Format.OWSContext.v0_3_1=OpenLayers.Class(OpenLayers.Format.XML,{namespaces:{owc:"http://www.opengis.net/ows-context",gml:"http://www.opengis.net/gml",kml:"http://www.opengis.net/kml/2.2",ogc:"http://www.opengis.net/ogc",ows:"http://www.opengis.net/ows",sld:"http://www.opengis.net/sld",xlink:"http://www.w3.org/1999/xlink",xsi:"http://www.w3.org/2001/XMLSchema-instance"},VERSION:"0.3.1",schemaLocation:"http://www.opengis.net/ows-context http://www.ogcnetwork.net/schemas/owc/0.3.1/owsContext.xsd",defaultPrefix:"owc",extractAttributes:true,xy:true,regExes:{trimSpace:(/^\s*|\s*$/g),removeSpace:(/\s*/g),splitSpace:(/\s+/),trimComma:(/\s*,\s*/g)},featureNS:"http://mapserver.gis.umn.edu/mapserver",featureType:'vector',geometryName:'geometry',nestingLayerLookup:null,initialize:function(options){OpenLayers.Format.XML.prototype.initialize.apply(this,[options]);OpenLayers.Format.GML.v2.prototype.setGeometryTypes.call(this);},setNestingPath:function(l){if(l.layersContext){for(var i=0,len=l.layersContext.length;i<len;i++){var layerContext=l.layersContext[i];var nPath=[];var nTitle=l.title||"";if(l.metadata&&l.metadata.nestingPath){nPath=l.metadata.nestingPath.slice();}
if(nTitle!=""){nPath.push(nTitle);}
layerContext.metadata.nestingPath=nPath;if(layerContext.layersContext){this.setNestingPath(layerContext);}}}},decomposeNestingPath:function(nPath){var a=[];if(nPath instanceof Array){while(nPath.length>0){a.push(nPath.slice());nPath.pop();}
a.reverse();}
return a;},read:function(data){if(typeof data=="string"){data=OpenLayers.Format.XML.prototype.read.apply(this,[data]);}
if(data&&data.nodeType==9){data=data.documentElement;}
var context={};this.readNode(data,context);this.setNestingPath({layersContext:context.layersContext});var layers=[];this.processLayer(layers,context);delete context.layersContext;context.layersContext=layers;return context;},processLayer:function(layerArray,layer){if(layer.layersContext){for(var i=0,len=layer.layersContext.length;i<len;i++){var l=layer.layersContext[i];layerArray.push(l);if(l.layersContext){this.processLayer(layerArray,l);}}}},write:function(context,options){var name="OWSContext";this.nestingLayerLookup={};options=options||{};OpenLayers.Util.applyDefaults(options,context);var root=this.writeNode(name,options);this.nestingLayerLookup=null;this.setAttributeNS(root,this.namespaces["xsi"],"xsi:schemaLocation",this.schemaLocation);return OpenLayers.Format.XML.prototype.write.apply(this,[root]);},readers:{"kml":{"Document":function(node,obj){obj.features=new OpenLayers.Format.KML({kmlns:this.namespaces.kml,extractStyles:true}).read(node);}},"owc":{"OWSContext":function(node,obj){this.readChildNodes(node,obj);},"General":function(node,obj){this.readChildNodes(node,obj);},"ResourceList":function(node,obj){this.readChildNodes(node,obj);},"Layer":function(node,obj){var layerContext={metadata:{},visibility:(node.getAttribute("hidden")!="1"),queryable:(node.getAttribute("queryable")=="1"),opacity:((node.getAttribute("opacity")!=null)?parseFloat(node.getAttribute("opacity")):null),name:node.getAttribute("name"),categoryLayer:(node.getAttribute("name")==null),formats:[],styles:[]};if(!obj.layersContext){obj.layersContext=[];}
obj.layersContext.push(layerContext);this.readChildNodes(node,layerContext);},"InlineGeometry":function(node,obj){obj.features=[];var elements=this.getElementsByTagNameNS(node,this.namespaces.gml,"featureMember");var el;if(elements.length>=1){el=elements[0];}
if(el&&el.firstChild){var featurenode=(el.firstChild.nextSibling)?el.firstChild.nextSibling:el.firstChild;this.setNamespace("feature",featurenode.namespaceURI);this.featureType=featurenode.localName||featurenode.nodeName.split(":").pop();this.readChildNodes(node,obj);}},"Server":function(node,obj){if((!obj.service&&!obj.version)||(obj.service!=OpenLayers.Format.Context.serviceTypes.WMS)){obj.service=node.getAttribute("service");obj.version=node.getAttribute("version");this.readChildNodes(node,obj);}},"Name":function(node,obj){obj.name=this.getChildValue(node);this.readChildNodes(node,obj);},"Title":function(node,obj){obj.title=this.getChildValue(node);this.readChildNodes(node,obj);},"StyleList":function(node,obj){this.readChildNodes(node,obj.styles);},"Style":function(node,obj){var style={};obj.push(style);this.readChildNodes(node,style);},"LegendURL":function(node,obj){var legend={};obj.legend=legend;this.readChildNodes(node,legend);},"OnlineResource":function(node,obj){obj.url=this.getAttributeNS(node,this.namespaces.xlink,"href");this.readChildNodes(node,obj);}},"ows":OpenLayers.Format.OWSCommon.v1_0_0.prototype.readers.ows,"gml":OpenLayers.Format.GML.v2.prototype.readers.gml,"sld":OpenLayers.Format.SLD.v1_0_0.prototype.readers.sld,"feature":OpenLayers.Format.GML.v2.prototype.readers.feature},writers:{"owc":{"OWSContext":function(options){var node=this.createElementNSPlus("OWSContext",{attributes:{version:this.VERSION,id:options.id||OpenLayers.Util.createUniqueID("OpenLayers_OWSContext_")}});this.writeNode("General",options,node);this.writeNode("ResourceList",options,node);return node;},"General":function(options){var node=this.createElementNSPlus("General");this.writeNode("ows:BoundingBox",options,node);this.writeNode("ows:Title",options.title||'OpenLayers OWSContext',node);return node;},"ResourceList":function(options){var node=this.createElementNSPlus("ResourceList");for(var i=0,len=options.layers.length;i<len;i++){var layer=options.layers[i];var decomposedPath=this.decomposeNestingPath(layer.metadata.nestingPath);this.writeNode("_Layer",{layer:layer,subPaths:decomposedPath},node);}
return node;},"Server":function(options){var node=this.createElementNSPlus("Server",{attributes:{version:options.version,service:options.service}});this.writeNode("OnlineResource",options,node);return node;},"OnlineResource":function(options){var node=this.createElementNSPlus("OnlineResource",{attributes:{"xlink:href":options.url}});return node;},"InlineGeometry":function(layer){var node=this.createElementNSPlus("InlineGeometry");this.writeNode("gml:boundedBy",layer.getDataExtent(),node);for(var i=0,len=layer.features.length;i<len;i++){this.writeNode("gml:featureMember",layer.features[i],node);}
return node;},"StyleList":function(styles){var node=this.createElementNSPlus("StyleList");for(var i=0,len=styles.length;i<len;i++){this.writeNode("Style",styles[i],node);}
return node;},"Style":function(style){var node=this.createElementNSPlus("Style");this.writeNode("Name",style,node);this.writeNode("Title",style,node);this.writeNode("LegendURL",style,node);return node;},"Name":function(obj){var node=this.createElementNSPlus("Name",{value:obj.name});return node;},"Title":function(obj){var node=this.createElementNSPlus("Title",{value:obj.title});return node;},"LegendURL":function(style){var node=this.createElementNSPlus("LegendURL");this.writeNode("OnlineResource",style.legend,node);return node;},"_WMS":function(layer){var node=this.createElementNSPlus("Layer",{attributes:{name:layer.params.LAYERS,queryable:layer.queryable?"1":"0",hidden:layer.visibility?"0":"1",opacity:layer.opacity?layer.opacity:null}});this.writeNode("ows:Title",layer.name,node);this.writeNode("ows:OutputFormat",layer.params.FORMAT,node);this.writeNode("Server",{service:OpenLayers.Format.Context.serviceTypes.WMS,version:layer.params.VERSION,url:layer.url},node);if(layer.metadata.styles&&layer.metadata.styles.length>0){this.writeNode("StyleList",layer.metadata.styles,node);}
return node;},"_Layer":function(options){var layer,subPaths,node,title;layer=options.layer;subPaths=options.subPaths;node=null;title=null;if(subPaths.length>0){var path=subPaths[0].join("/");var index=path.lastIndexOf("/");node=this.nestingLayerLookup[path];title=(index>0)?path.substring(index+1,path.length):path;if(!node){node=this.createElementNSPlus("Layer");this.writeNode("ows:Title",title,node);this.nestingLayerLookup[path]=node;}
options.subPaths.shift();this.writeNode("_Layer",options,node);return node;}else{if(layer instanceof OpenLayers.Layer.WMS){node=this.writeNode("_WMS",layer);}else if(layer instanceof OpenLayers.Layer.Vector){if(layer.protocol instanceof OpenLayers.Protocol.WFS.v1){node=this.writeNode("_WFS",layer);}else if(layer.protocol instanceof OpenLayers.Protocol.HTTP){if(layer.protocol.format instanceof OpenLayers.Format.GML){layer.protocol.format.version="2.1.2";node=this.writeNode("_GML",layer);}else if(layer.protocol.format instanceof OpenLayers.Format.KML){layer.protocol.format.version="2.2";node=this.writeNode("_KML",layer);}}else{this.setNamespace("feature",this.featureNS);node=this.writeNode("_InlineGeometry",layer);}}
if(layer.options.maxScale){this.writeNode("sld:MinScaleDenominator",layer.options.maxScale,node);}
if(layer.options.minScale){this.writeNode("sld:MaxScaleDenominator",layer.options.minScale,node);}
this.nestingLayerLookup[layer.name]=node;return node;}},"_WFS":function(layer){var node=this.createElementNSPlus("Layer",{attributes:{name:layer.protocol.featurePrefix+":"+layer.protocol.featureType,hidden:layer.visibility?"0":"1"}});this.writeNode("ows:Title",layer.name,node);this.writeNode("Server",{service:OpenLayers.Format.Context.serviceTypes.WFS,version:layer.protocol.version,url:layer.protocol.url},node);return node;},"_InlineGeometry":function(layer){var node=this.createElementNSPlus("Layer",{attributes:{name:this.featureType,hidden:layer.visibility?"0":"1"}});this.writeNode("ows:Title",layer.name,node);this.writeNode("InlineGeometry",layer,node);return node;},"_GML":function(layer){var node=this.createElementNSPlus("Layer");this.writeNode("ows:Title",layer.name,node);this.writeNode("Server",{service:OpenLayers.Format.Context.serviceTypes.GML,url:layer.protocol.url,version:layer.protocol.format.version},node);return node;},"_KML":function(layer){var node=this.createElementNSPlus("Layer");this.writeNode("ows:Title",layer.name,node);this.writeNode("Server",{service:OpenLayers.Format.Context.serviceTypes.KML,version:layer.protocol.format.version,url:layer.protocol.url},node);return node;}},"gml":OpenLayers.Util.applyDefaults({"boundedBy":function(bounds){var node=this.createElementNSPlus("gml:boundedBy");this.writeNode("gml:Box",bounds,node);return node;}},OpenLayers.Format.GML.v2.prototype.writers.gml),"ows":OpenLayers.Format.OWSCommon.v1_0_0.prototype.writers.ows,"sld":OpenLayers.Format.SLD.v1_0_0.prototype.writers.sld,"feature":OpenLayers.Format.GML.v2.prototype.writers.feature},CLASS_NAME:"OpenLayers.Format.OWSContext.v0_3_1"});
(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,d=e.filter,g=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,_=Object.keys,j=i.bind,w=function(n){return n instanceof w?n:this instanceof w?(this._wrapped=n,void 0):new w(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=w),exports._=w):n._=w,w.VERSION="1.4.4";var A=w.each=w.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a in n)if(w.has(n,a)&&t.call(e,n[a],a,n)===r)return};w.map=w.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e[e.length]=t.call(r,n,u,i)}),e)};var O="Reduce of empty array with no initial value";w.reduce=w.foldl=w.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=w.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},w.reduceRight=w.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=w.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=w.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},w.find=w.detect=function(n,t,r){var e;return E(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},w.filter=w.select=function(n,t,r){var e=[];return null==n?e:d&&n.filter===d?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&(e[e.length]=n)}),e)},w.reject=function(n,t,r){return w.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},w.every=w.all=function(n,t,e){t||(t=w.identity);var u=!0;return null==n?u:g&&n.every===g?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var E=w.some=w.any=function(n,t,e){t||(t=w.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};w.contains=w.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:E(n,function(n){return n===t})},w.invoke=function(n,t){var r=o.call(arguments,2),e=w.isFunction(t);return w.map(n,function(n){return(e?t:n[t]).apply(n,r)})},w.pluck=function(n,t){return w.map(n,function(n){return n[t]})},w.where=function(n,t,r){return w.isEmpty(t)?r?null:[]:w[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},w.findWhere=function(n,t){return w.where(n,t,!0)},w.max=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.max.apply(Math,n);if(!t&&w.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>=e.computed&&(e={value:n,computed:a})}),e.value},w.min=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.min.apply(Math,n);if(!t&&w.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;e.computed>a&&(e={value:n,computed:a})}),e.value},w.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=w.random(r++),e[r-1]=e[t],e[t]=n}),e};var k=function(n){return w.isFunction(n)?n:function(t){return t[n]}};w.sortBy=function(n,t,r){var e=k(t);return w.pluck(w.map(n,function(n,t,u){return{value:n,index:t,criteria:e.call(r,n,t,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index<t.index?-1:1}),"value")};var F=function(n,t,r,e){var u={},i=k(t||w.identity);return A(n,function(t,a){var o=i.call(r,t,a,n);e(u,o,t)}),u};w.groupBy=function(n,t,r){return F(n,t,r,function(n,t,r){(w.has(n,t)?n[t]:n[t]=[]).push(r)})},w.countBy=function(n,t,r){return F(n,t,r,function(n,t){w.has(n,t)||(n[t]=0),n[t]++})},w.sortedIndex=function(n,t,r,e){r=null==r?w.identity:k(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;u>r.call(e,n[o])?i=o+1:a=o}return i},w.toArray=function(n){return n?w.isArray(n)?o.call(n):n.length===+n.length?w.map(n,w.identity):w.values(n):[]},w.size=function(n){return null==n?0:n.length===+n.length?n.length:w.keys(n).length},w.first=w.head=w.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:o.call(n,0,t)},w.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},w.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},w.rest=w.tail=w.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},w.compact=function(n){return w.filter(n,w.identity)};var R=function(n,t,r){return A(n,function(n){w.isArray(n)?t?a.apply(r,n):R(n,t,r):r.push(n)}),r};w.flatten=function(n,t){return R(n,t,[])},w.without=function(n){return w.difference(n,o.call(arguments,1))},w.uniq=w.unique=function(n,t,r,e){w.isFunction(t)&&(e=r,r=t,t=!1);var u=r?w.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:w.contains(a,r))||(a.push(r),i.push(n[e]))}),i},w.union=function(){return w.uniq(c.apply(e,arguments))},w.intersection=function(n){var t=o.call(arguments,1);return w.filter(w.uniq(n),function(n){return w.every(t,function(t){return w.indexOf(t,n)>=0})})},w.difference=function(n){var t=c.apply(e,o.call(arguments,1));return w.filter(n,function(n){return!w.contains(t,n)})},w.zip=function(){for(var n=o.call(arguments),t=w.max(w.pluck(n,"length")),r=Array(t),e=0;t>e;e++)r[e]=w.pluck(n,""+e);return r},w.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},w.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=w.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},w.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},w.range=function(n,t,r){1>=arguments.length&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=Array(e);e>u;)i[u++]=n,n+=r;return i},w.bind=function(n,t){if(n.bind===j&&j)return j.apply(n,o.call(arguments,1));var r=o.call(arguments,2);return function(){return n.apply(t,r.concat(o.call(arguments)))}},w.partial=function(n){var t=o.call(arguments,1);return function(){return n.apply(this,t.concat(o.call(arguments)))}},w.bindAll=function(n){var t=o.call(arguments,1);return 0===t.length&&(t=w.functions(n)),A(t,function(t){n[t]=w.bind(n[t],n)}),n},w.memoize=function(n,t){var r={};return t||(t=w.identity),function(){var e=t.apply(this,arguments);return w.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},w.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},w.defer=function(n){return w.delay.apply(w,[n,1].concat(o.call(arguments,1)))},w.throttle=function(n,t){var r,e,u,i,a=0,o=function(){a=new Date,u=null,i=n.apply(r,e)};return function(){var c=new Date,l=t-(c-a);return r=this,e=arguments,0>=l?(clearTimeout(u),u=null,a=c,i=n.apply(r,e)):u||(u=setTimeout(o,l)),i}},w.debounce=function(n,t,r){var e,u;return function(){var i=this,a=arguments,o=function(){e=null,r||(u=n.apply(i,a))},c=r&&!e;return clearTimeout(e),e=setTimeout(o,t),c&&(u=n.apply(i,a)),u}},w.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},w.wrap=function(n,t){return function(){var r=[n];return a.apply(r,arguments),t.apply(this,r)}},w.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},w.after=function(n,t){return 0>=n?t():function(){return 1>--n?t.apply(this,arguments):void 0}},w.keys=_||function(n){if(n!==Object(n))throw new TypeError("Invalid object");var t=[];for(var r in n)w.has(n,r)&&(t[t.length]=r);return t},w.values=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push(n[r]);return t},w.pairs=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push([r,n[r]]);return t},w.invert=function(n){var t={};for(var r in n)w.has(n,r)&&(t[n[r]]=r);return t},w.functions=w.methods=function(n){var t=[];for(var r in n)w.isFunction(n[r])&&t.push(r);return t.sort()},w.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},w.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},w.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)w.contains(r,u)||(t[u]=n[u]);return t},w.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)null==n[r]&&(n[r]=t[r])}),n},w.clone=function(n){return w.isObject(n)?w.isArray(n)?n.slice():w.extend({},n):n},w.tap=function(n,t){return t(n),n};var I=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof w&&(n=n._wrapped),t instanceof w&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==t+"";case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;r.push(n),e.push(t);var a=0,o=!0;if("[object Array]"==u){if(a=n.length,o=a==t.length)for(;a--&&(o=I(n[a],t[a],r,e)););}else{var c=n.constructor,f=t.constructor;if(c!==f&&!(w.isFunction(c)&&c instanceof c&&w.isFunction(f)&&f instanceof f))return!1;for(var s in n)if(w.has(n,s)&&(a++,!(o=w.has(t,s)&&I(n[s],t[s],r,e))))break;if(o){for(s in t)if(w.has(t,s)&&!a--)break;o=!a}}return r.pop(),e.pop(),o};w.isEqual=function(n,t){return I(n,t,[],[])},w.isEmpty=function(n){if(null==n)return!0;if(w.isArray(n)||w.isString(n))return 0===n.length;for(var t in n)if(w.has(n,t))return!1;return!0},w.isElement=function(n){return!(!n||1!==n.nodeType)},w.isArray=x||function(n){return"[object Array]"==l.call(n)},w.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){w["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),w.isArguments(arguments)||(w.isArguments=function(n){return!(!n||!w.has(n,"callee"))}),"function"!=typeof/./&&(w.isFunction=function(n){return"function"==typeof n}),w.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},w.isNaN=function(n){return w.isNumber(n)&&n!=+n},w.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},w.isNull=function(n){return null===n},w.isUndefined=function(n){return n===void 0},w.has=function(n,t){return f.call(n,t)},w.noConflict=function(){return n._=t,this},w.identity=function(n){return n},w.times=function(n,t,r){for(var e=Array(n),u=0;n>u;u++)e[u]=t.call(r,u);return e},w.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))};var M={escape:{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"}};M.unescape=w.invert(M.escape);var S={escape:RegExp("["+w.keys(M.escape).join("")+"]","g"),unescape:RegExp("("+w.keys(M.unescape).join("|")+")","g")};w.each(["escape","unescape"],function(n){w[n]=function(t){return null==t?"":(""+t).replace(S[n],function(t){return M[n][t]})}}),w.result=function(n,t){if(null==n)return null;var r=n[t];return w.isFunction(r)?r.call(n):r},w.mixin=function(n){A(w.functions(n),function(t){var r=w[t]=n[t];w.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),D.call(this,r.apply(w,n))}})};var N=0;w.uniqueId=function(n){var t=++N+"";return n?n+t:t},w.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var T=/(.)^/,q={"'":"'","\\":"\\","\r":"r","\n":"n","	":"t","\u2028":"u2028","\u2029":"u2029"},B=/\\|'|\r|\n|\t|\u2028|\u2029/g;w.template=function(n,t,r){var e;r=w.defaults({},r,w.templateSettings);var u=RegExp([(r.escape||T).source,(r.interpolate||T).source,(r.evaluate||T).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(B,function(n){return"\\"+q[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,w);var c=function(n){return e.call(this,n,w)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},w.chain=function(n){return w(n).chain()};var D=function(n){return this._chain?w(n).chain():n};w.mixin(w),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];w.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],D.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];w.prototype[n]=function(){return D.call(this,t.apply(this._wrapped,arguments))}}),w.extend(w.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this);/*global setImmediate: false, setTimeout: false, console: false */
(function () {

    var async = {};

    // global on the server, window in the browser
    var root, previous_async;

    root = this;
    if (root != null) {
      previous_async = root.async;
    }

    async.noConflict = function () {
        root.async = previous_async;
        return async;
    };

    function only_once(fn) {
        var called = false;
        return function() {
            if (called) throw new Error("Callback was already called.");
            called = true;
            fn.apply(root, arguments);
        }
    }

    //// cross-browser compatiblity functions ////

    var _each = function (arr, iterator) {
        if (arr.forEach) {
            return arr.forEach(iterator);
        }
        for (var i = 0; i < arr.length; i += 1) {
            iterator(arr[i], i, arr);
        }
    };

    var _map = function (arr, iterator) {
        if (arr.map) {
            return arr.map(iterator);
        }
        var results = [];
        _each(arr, function (x, i, a) {
            results.push(iterator(x, i, a));
        });
        return results;
    };

    var _reduce = function (arr, iterator, memo) {
        if (arr.reduce) {
            return arr.reduce(iterator, memo);
        }
        _each(arr, function (x, i, a) {
            memo = iterator(memo, x, i, a);
        });
        return memo;
    };

    var _keys = function (obj) {
        if (Object.keys) {
            return Object.keys(obj);
        }
        var keys = [];
        for (var k in obj) {
            if (obj.hasOwnProperty(k)) {
                keys.push(k);
            }
        }
        return keys;
    };

    //// exported async module functions ////

    //// nextTick implementation with browser-compatible fallback ////
    if (typeof process === 'undefined' || !(process.nextTick)) {
        if (typeof setImmediate === 'function') {
            async.nextTick = function (fn) {
                // not a direct alias for IE10 compatibility
                setImmediate(fn);
            };
            async.setImmediate = async.nextTick;
        }
        else {
            async.nextTick = function (fn) {
                setTimeout(fn, 0);
            };
            async.setImmediate = async.nextTick;
        }
    }
    else {
        async.nextTick = process.nextTick;
        if (typeof setImmediate !== 'undefined') {
            async.setImmediate = setImmediate;
        }
        else {
            async.setImmediate = async.nextTick;
        }
    }

    async.each = function (arr, iterator, callback) {
        callback = callback || function () {};
        if (!arr.length) {
            return callback();
        }
        var completed = 0;
        _each(arr, function (x) {
            iterator(x, only_once(function (err) {
                if (err) {
                    callback(err);
                    callback = function () {};
                }
                else {
                    completed += 1;
                    if (completed >= arr.length) {
                        callback(null);
                    }
                }
            }));
        });
    };
    async.forEach = async.each;

    async.eachSeries = function (arr, iterator, callback) {
        callback = callback || function () {};
        if (!arr.length) {
            return callback();
        }
        var completed = 0;
        var iterate = function () {
            iterator(arr[completed], function (err) {
                if (err) {
                    callback(err);
                    callback = function () {};
                }
                else {
                    completed += 1;
                    if (completed >= arr.length) {
                        callback(null);
                    }
                    else {
                        iterate();
                    }
                }
            });
        };
        iterate();
    };
    async.forEachSeries = async.eachSeries;

    async.eachLimit = function (arr, limit, iterator, callback) {
        var fn = _eachLimit(limit);
        fn.apply(null, [arr, iterator, callback]);
    };
    async.forEachLimit = async.eachLimit;

    var _eachLimit = function (limit) {

        return function (arr, iterator, callback) {
            callback = callback || function () {};
            if (!arr.length || limit <= 0) {
                return callback();
            }
            var completed = 0;
            var started = 0;
            var running = 0;

            (function replenish () {
                if (completed >= arr.length) {
                    return callback();
                }

                while (running < limit && started < arr.length) {
                    started += 1;
                    running += 1;
                    iterator(arr[started - 1], function (err) {
                        if (err) {
                            callback(err);
                            callback = function () {};
                        }
                        else {
                            completed += 1;
                            running -= 1;
                            if (completed >= arr.length) {
                                callback();
                            }
                            else {
                                replenish();
                            }
                        }
                    });
                }
            })();
        };
    };


    var doParallel = function (fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            return fn.apply(null, [async.each].concat(args));
        };
    };
    var doParallelLimit = function(limit, fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            return fn.apply(null, [_eachLimit(limit)].concat(args));
        };
    };
    var doSeries = function (fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            return fn.apply(null, [async.eachSeries].concat(args));
        };
    };


    var _asyncMap = function (eachfn, arr, iterator, callback) {
        var results = [];
        arr = _map(arr, function (x, i) {
            return {index: i, value: x};
        });
        eachfn(arr, function (x, callback) {
            iterator(x.value, function (err, v) {
                results[x.index] = v;
                callback(err);
            });
        }, function (err) {
            callback(err, results);
        });
    };
    async.map = doParallel(_asyncMap);
    async.mapSeries = doSeries(_asyncMap);
    async.mapLimit = function (arr, limit, iterator, callback) {
        return _mapLimit(limit)(arr, iterator, callback);
    };

    var _mapLimit = function(limit) {
        return doParallelLimit(limit, _asyncMap);
    };

    // reduce only has a series version, as doing reduce in parallel won't
    // work in many situations.
    async.reduce = function (arr, memo, iterator, callback) {
        async.eachSeries(arr, function (x, callback) {
            iterator(memo, x, function (err, v) {
                memo = v;
                callback(err);
            });
        }, function (err) {
            callback(err, memo);
        });
    };
    // inject alias
    async.inject = async.reduce;
    // foldl alias
    async.foldl = async.reduce;

    async.reduceRight = function (arr, memo, iterator, callback) {
        var reversed = _map(arr, function (x) {
            return x;
        }).reverse();
        async.reduce(reversed, memo, iterator, callback);
    };
    // foldr alias
    async.foldr = async.reduceRight;

    var _filter = function (eachfn, arr, iterator, callback) {
        var results = [];
        arr = _map(arr, function (x, i) {
            return {index: i, value: x};
        });
        eachfn(arr, function (x, callback) {
            iterator(x.value, function (v) {
                if (v) {
                    results.push(x);
                }
                callback();
            });
        }, function (err) {
            callback(_map(results.sort(function (a, b) {
                return a.index - b.index;
            }), function (x) {
                return x.value;
            }));
        });
    };
    async.filter = doParallel(_filter);
    async.filterSeries = doSeries(_filter);
    // select alias
    async.select = async.filter;
    async.selectSeries = async.filterSeries;

    var _reject = function (eachfn, arr, iterator, callback) {
        var results = [];
        arr = _map(arr, function (x, i) {
            return {index: i, value: x};
        });
        eachfn(arr, function (x, callback) {
            iterator(x.value, function (v) {
                if (!v) {
                    results.push(x);
                }
                callback();
            });
        }, function (err) {
            callback(_map(results.sort(function (a, b) {
                return a.index - b.index;
            }), function (x) {
                return x.value;
            }));
        });
    };
    async.reject = doParallel(_reject);
    async.rejectSeries = doSeries(_reject);

    var _detect = function (eachfn, arr, iterator, main_callback) {
        eachfn(arr, function (x, callback) {
            iterator(x, function (result) {
                if (result) {
                    main_callback(x);
                    main_callback = function () {};
                }
                else {
                    callback();
                }
            });
        }, function (err) {
            main_callback();
        });
    };
    async.detect = doParallel(_detect);
    async.detectSeries = doSeries(_detect);

    async.some = function (arr, iterator, main_callback) {
        async.each(arr, function (x, callback) {
            iterator(x, function (v) {
                if (v) {
                    main_callback(true);
                    main_callback = function () {};
                }
                callback();
            });
        }, function (err) {
            main_callback(false);
        });
    };
    // any alias
    async.any = async.some;

    async.every = function (arr, iterator, main_callback) {
        async.each(arr, function (x, callback) {
            iterator(x, function (v) {
                if (!v) {
                    main_callback(false);
                    main_callback = function () {};
                }
                callback();
            });
        }, function (err) {
            main_callback(true);
        });
    };
    // all alias
    async.all = async.every;

    async.sortBy = function (arr, iterator, callback) {
        async.map(arr, function (x, callback) {
            iterator(x, function (err, criteria) {
                if (err) {
                    callback(err);
                }
                else {
                    callback(null, {value: x, criteria: criteria});
                }
            });
        }, function (err, results) {
            if (err) {
                return callback(err);
            }
            else {
                var fn = function (left, right) {
                    var a = left.criteria, b = right.criteria;
                    return a < b ? -1 : a > b ? 1 : 0;
                };
                callback(null, _map(results.sort(fn), function (x) {
                    return x.value;
                }));
            }
        });
    };

    async.auto = function (tasks, callback) {
        callback = callback || function () {};
        var keys = _keys(tasks);
        if (!keys.length) {
            return callback(null);
        }

        var results = {};

        var listeners = [];
        var addListener = function (fn) {
            listeners.unshift(fn);
        };
        var removeListener = function (fn) {
            for (var i = 0; i < listeners.length; i += 1) {
                if (listeners[i] === fn) {
                    listeners.splice(i, 1);
                    return;
                }
            }
        };
        var taskComplete = function () {
            _each(listeners.slice(0), function (fn) {
                fn();
            });
        };

        addListener(function () {
            if (_keys(results).length === keys.length) {
                callback(null, results);
                callback = function () {};
            }
        });

        _each(keys, function (k) {
            var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k];
            var taskCallback = function (err) {
                var args = Array.prototype.slice.call(arguments, 1);
                if (args.length <= 1) {
                    args = args[0];
                }
                if (err) {
                    var safeResults = {};
                    _each(_keys(results), function(rkey) {
                        safeResults[rkey] = results[rkey];
                    });
                    safeResults[k] = args;
                    callback(err, safeResults);
                    // stop subsequent errors hitting callback multiple times
                    callback = function () {};
                }
                else {
                    results[k] = args;
                    async.setImmediate(taskComplete);
                }
            };
            var requires = task.slice(0, Math.abs(task.length - 1)) || [];
            var ready = function () {
                return _reduce(requires, function (a, x) {
                    return (a && results.hasOwnProperty(x));
                }, true) && !results.hasOwnProperty(k);
            };
            if (ready()) {
                task[task.length - 1](taskCallback, results);
            }
            else {
                var listener = function () {
                    if (ready()) {
                        removeListener(listener);
                        task[task.length - 1](taskCallback, results);
                    }
                };
                addListener(listener);
            }
        });
    };

    async.waterfall = function (tasks, callback) {
        callback = callback || function () {};
        if (tasks.constructor !== Array) {
          var err = new Error('First argument to waterfall must be an array of functions');
          return callback(err);
        }
        if (!tasks.length) {
            return callback();
        }
        var wrapIterator = function (iterator) {
            return function (err) {
                if (err) {
                    callback.apply(null, arguments);
                    callback = function () {};
                }
                else {
                    var args = Array.prototype.slice.call(arguments, 1);
                    var next = iterator.next();
                    if (next) {
                        args.push(wrapIterator(next));
                    }
                    else {
                        args.push(callback);
                    }
                    async.setImmediate(function () {
                        iterator.apply(null, args);
                    });
                }
            };
        };
        wrapIterator(async.iterator(tasks))();
    };

    var _parallel = function(eachfn, tasks, callback) {
        callback = callback || function () {};
        if (tasks.constructor === Array) {
            eachfn.map(tasks, function (fn, callback) {
                if (fn) {
                    fn(function (err) {
                        var args = Array.prototype.slice.call(arguments, 1);
                        if (args.length <= 1) {
                            args = args[0];
                        }
                        callback.call(null, err, args);
                    });
                }
            }, callback);
        }
        else {
            var results = {};
            eachfn.each(_keys(tasks), function (k, callback) {
                tasks[k](function (err) {
                    var args = Array.prototype.slice.call(arguments, 1);
                    if (args.length <= 1) {
                        args = args[0];
                    }
                    results[k] = args;
                    callback(err);
                });
            }, function (err) {
                callback(err, results);
            });
        }
    };

    async.parallel = function (tasks, callback) {
        _parallel({ map: async.map, each: async.each }, tasks, callback);
    };

    async.parallelLimit = function(tasks, limit, callback) {
        _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
    };

    async.series = function (tasks, callback) {
        callback = callback || function () {};
        if (tasks.constructor === Array) {
            async.mapSeries(tasks, function (fn, callback) {
                if (fn) {
                    fn(function (err) {
                        var args = Array.prototype.slice.call(arguments, 1);
                        if (args.length <= 1) {
                            args = args[0];
                        }
                        callback.call(null, err, args);
                    });
                }
            }, callback);
        }
        else {
            var results = {};
            async.eachSeries(_keys(tasks), function (k, callback) {
                tasks[k](function (err) {
                    var args = Array.prototype.slice.call(arguments, 1);
                    if (args.length <= 1) {
                        args = args[0];
                    }
                    results[k] = args;
                    callback(err);
                });
            }, function (err) {
                callback(err, results);
            });
        }
    };

    async.iterator = function (tasks) {
        var makeCallback = function (index) {
            var fn = function () {
                if (tasks.length) {
                    tasks[index].apply(null, arguments);
                }
                return fn.next();
            };
            fn.next = function () {
                return (index < tasks.length - 1) ? makeCallback(index + 1): null;
            };
            return fn;
        };
        return makeCallback(0);
    };

    async.apply = function (fn) {
        var args = Array.prototype.slice.call(arguments, 1);
        return function () {
            return fn.apply(
                null, args.concat(Array.prototype.slice.call(arguments))
            );
        };
    };

    var _concat = function (eachfn, arr, fn, callback) {
        var r = [];
        eachfn(arr, function (x, cb) {
            fn(x, function (err, y) {
                r = r.concat(y || []);
                cb(err);
            });
        }, function (err) {
            callback(err, r);
        });
    };
    async.concat = doParallel(_concat);
    async.concatSeries = doSeries(_concat);

    async.whilst = function (test, iterator, callback) {
        if (test()) {
            iterator(function (err) {
                if (err) {
                    return callback(err);
                }
                async.whilst(test, iterator, callback);
            });
        }
        else {
            callback();
        }
    };

    async.doWhilst = function (iterator, test, callback) {
        iterator(function (err) {
            if (err) {
                return callback(err);
            }
            if (test()) {
                async.doWhilst(iterator, test, callback);
            }
            else {
                callback();
            }
        });
    };

    async.until = function (test, iterator, callback) {
        if (!test()) {
            iterator(function (err) {
                if (err) {
                    return callback(err);
                }
                async.until(test, iterator, callback);
            });
        }
        else {
            callback();
        }
    };

    async.doUntil = function (iterator, test, callback) {
        iterator(function (err) {
            if (err) {
                return callback(err);
            }
            if (!test()) {
                async.doUntil(iterator, test, callback);
            }
            else {
                callback();
            }
        });
    };

    async.queue = function (worker, concurrency) {
        if (concurrency === undefined) {
            concurrency = 1;
        }
        function _insert(q, data, pos, callback) {
          if(data.constructor !== Array) {
              data = [data];
          }
          _each(data, function(task) {
              var item = {
                  data: task,
                  callback: typeof callback === 'function' ? callback : null
              };

              if (pos) {
                q.tasks.unshift(item);
              } else {
                q.tasks.push(item);
              }

              if (q.saturated && q.tasks.length === concurrency) {
                  q.saturated();
              }
              async.setImmediate(q.process);
          });
        }

        var workers = 0;
        var q = {
            tasks: [],
            concurrency: concurrency,
            saturated: null,
            empty: null,
            drain: null,
            push: function (data, callback) {
              _insert(q, data, false, callback);
            },
            unshift: function (data, callback) {
              _insert(q, data, true, callback);
            },
            process: function () {
                if (workers < q.concurrency && q.tasks.length) {
                    var task = q.tasks.shift();
                    if (q.empty && q.tasks.length === 0) {
                        q.empty();
                    }
                    workers += 1;
                    var next = function () {
                        workers -= 1;
                        if (task.callback) {
                            task.callback.apply(task, arguments);
                        }
                        if (q.drain && q.tasks.length + workers === 0) {
                            q.drain();
                        }
                        q.process();
                    };
                    var cb = only_once(next);
                    worker(task.data, cb);
                }
            },
            length: function () {
                return q.tasks.length;
            },
            running: function () {
                return workers;
            }
        };
        return q;
    };

    async.cargo = function (worker, payload) {
        var working     = false,
            tasks       = [];

        var cargo = {
            tasks: tasks,
            payload: payload,
            saturated: null,
            empty: null,
            drain: null,
            push: function (data, callback) {
                if(data.constructor !== Array) {
                    data = [data];
                }
                _each(data, function(task) {
                    tasks.push({
                        data: task,
                        callback: typeof callback === 'function' ? callback : null
                    });
                    if (cargo.saturated && tasks.length === payload) {
                        cargo.saturated();
                    }
                });
                async.setImmediate(cargo.process);
            },
            process: function process() {
                if (working) return;
                if (tasks.length === 0) {
                    if(cargo.drain) cargo.drain();
                    return;
                }

                var ts = typeof payload === 'number'
                            ? tasks.splice(0, payload)
                            : tasks.splice(0);

                var ds = _map(ts, function (task) {
                    return task.data;
                });

                if(cargo.empty) cargo.empty();
                working = true;
                worker(ds, function () {
                    working = false;

                    var args = arguments;
                    _each(ts, function (data) {
                        if (data.callback) {
                            data.callback.apply(null, args);
                        }
                    });

                    process();
                });
            },
            length: function () {
                return tasks.length;
            },
            running: function () {
                return working;
            }
        };
        return cargo;
    };

    var _console_fn = function (name) {
        return function (fn) {
            var args = Array.prototype.slice.call(arguments, 1);
            fn.apply(null, args.concat([function (err) {
                var args = Array.prototype.slice.call(arguments, 1);
                if (typeof console !== 'undefined') {
                    if (err) {
                        if (console.error) {
                            console.error(err);
                        }
                    }
                    else if (console[name]) {
                        _each(args, function (x) {
                            console[name](x);
                        });
                    }
                }
            }]));
        };
    };
    async.log = _console_fn('log');
    async.dir = _console_fn('dir');
    /*async.info = _console_fn('info');
    async.warn = _console_fn('warn');
    async.error = _console_fn('error');*/

    async.memoize = function (fn, hasher) {
        var memo = {};
        var queues = {};
        hasher = hasher || function (x) {
            return x;
        };
        var memoized = function () {
            var args = Array.prototype.slice.call(arguments);
            var callback = args.pop();
            var key = hasher.apply(null, args);
            if (key in memo) {
                callback.apply(null, memo[key]);
            }
            else if (key in queues) {
                queues[key].push(callback);
            }
            else {
                queues[key] = [callback];
                fn.apply(null, args.concat([function () {
                    memo[key] = arguments;
                    var q = queues[key];
                    delete queues[key];
                    for (var i = 0, l = q.length; i < l; i++) {
                      q[i].apply(null, arguments);
                    }
                }]));
            }
        };
        memoized.memo = memo;
        memoized.unmemoized = fn;
        return memoized;
    };

    async.unmemoize = function (fn) {
      return function () {
        return (fn.unmemoized || fn).apply(null, arguments);
      };
    };

    async.times = function (count, iterator, callback) {
        var counter = [];
        for (var i = 0; i < count; i++) {
            counter.push(i);
        }
        return async.map(counter, iterator, callback);
    };

    async.timesSeries = function (count, iterator, callback) {
        var counter = [];
        for (var i = 0; i < count; i++) {
            counter.push(i);
        }
        return async.mapSeries(counter, iterator, callback);
    };

    async.compose = function (/* functions... */) {
        var fns = Array.prototype.reverse.call(arguments);
        return function () {
            var that = this;
            var args = Array.prototype.slice.call(arguments);
            var callback = args.pop();
            async.reduce(fns, args, function (newargs, fn, cb) {
                fn.apply(that, newargs.concat([function () {
                    var err = arguments[0];
                    var nextargs = Array.prototype.slice.call(arguments, 1);
                    cb(err, nextargs);
                }]))
            },
            function (err, results) {
                callback.apply(that, [err].concat(results));
            });
        };
    };

    var _applyEach = function (eachfn, fns /*args...*/) {
        var go = function () {
            var that = this;
            var args = Array.prototype.slice.call(arguments);
            var callback = args.pop();
            return eachfn(fns, function (fn, cb) {
                fn.apply(that, args.concat([cb]));
            },
            callback);
        };
        if (arguments.length > 2) {
            var args = Array.prototype.slice.call(arguments, 2);
            return go.apply(this, args);
        }
        else {
            return go;
        }
    };
    async.applyEach = doParallel(_applyEach);
    async.applyEachSeries = doSeries(_applyEach);

    async.forever = function (fn, callback) {
        function next(err) {
            if (err) {
                if (callback) {
                    return callback(err);
                }
                throw err;
            }
            fn(next);
        }
        next();
    };

    root.async = async;

}());
(function() {

    var redblack = {};
    var root = this;
    var orig = root.redblack;

    if (typeof module !== 'undefined' && module.exports) {
        module.exports = redblack;
    } else {
        root.redblack = redblack;
    }

    redblack.VERSION = '0.1.2';

    redblack.noConflict = function() {
        root.redblack = orig;
        return redblack;
    };

    redblack.tree = function() {
        return new Tree();
    };

    var BLACK = redblack.BLACK = 'black';
    var RED = redblack.RED = 'red';

    // Node
    // ---------------

    function Node(key, value) {
        this.key = key;
        this.value = value;
        this.color = RED;
        this.left = null;
        this.right = null;
        this.parent = null;
    };

    Node.prototype.grandparent = function() {
        if (this.parent === null) return null;
        return this.parent.parent;
    };

    Node.prototype.sibling = function() {
        if (this.parent === null) return null;
        return this === this.parent.left ? this.parent.right : this.parent.left;
    };

    Node.prototype.uncle = function() {
        if (this.parent === null) return null;
        return this.parent.sibling();
    };

    // Cursor
    // ---------------

    function Cursor(tree, start, end) {
        this.tree = tree;
        this.start = start;
        this.end = end;

        var self = this;
        this.walk = function walk(node, iterator) {
            if (node === null) return;

            if (start !== undefined && node.key < start) {
                walk(node.right, iterator);
            } else if (end !== undefined && node.key > end) {
                walk(node.left, iterator);
            } else {
                walk(node.left, iterator);
                iterator(node.value, node.key, self.tree);
                walk(node.right, iterator);
            }
        };
    };

    Cursor.prototype.forEach = function(iterator) {
        this.walk(this.tree.root, iterator);
    };

    Cursor.prototype.map = function(iterator) {
        var results = [];

        this.forEach(function(value, key, tree) {
            results.push(iterator(value, key, tree));
        });

        return results;
    };

    // Tree
    // ---------------

    function Tree() {
        this.root = null;
        this.balancer = new Balancer(this);
    };

    Tree.prototype.get = function(key) {
        var node = find(this.root, key);
        return node === null ? null : node.value;
    };

    Tree.prototype.insert = function(key, value) {
        var newNode = new Node(key, value);

        if (this.root === null) {
            this.root = newNode;
        } else {
            var node = this.root;

            while (true) {
                if (key < node.key) {
                    if (node.left === null) {
                        node.left = newNode;
                        break;
                    } else {
                        node = node.left;
                    }
                } else if (key > node.key) {
                    if (node.right === null) {
                        node.right = newNode;
                        break;
                    } else {
                        node = node.right;
                    }
                } else {
                    node.value = value;
                    return;
                }
            }

            newNode.parent = node;
        }

        this.balancer.inserted(newNode);
    };

    Tree.prototype.delete = function(key) {
        var node = find(this.root, key);
        if (node === null) return;

        if (node.left !== null && node.right !== null) {
            var pred = node.left;
            while (pred.right !== null) pred = pred.right;

            node.key = pred.key;
            node.value = pred.value;
            node = pred;
        }

        var child = (node.right === null) ? node.left : node.right;
        if (nodeColor(node) === BLACK) {
            node.color = nodeColor(child);
            this.balancer.deleted(node);
        }

        this.balancer.replaceNode(node, child);

        if (nodeColor(this.root) === RED) {
            this.root.color = BLACK;
        }
    };

    Tree.prototype.range = function(start, end) {
        return new Cursor(this, start, end);
    };

    // Proxy cursor methods
    for (var method in Cursor.prototype) {
        if (Cursor.prototype.hasOwnProperty(method)) {
            var func = Cursor.prototype[method];
            Tree.prototype[method] = function() {
                var cursor = new Cursor(this);
                return func.apply(cursor, arguments);
            };
        }
    }

    // Balancer
    // ---------------

    function Balancer(tree) {
        this.tree = tree;
    };

    Balancer.prototype.inserted = function(node) {
        this.insertCase1(node);
    };

    Balancer.prototype.deleted = function(node) {
        this.deleteCase1(node);
    };

    Balancer.prototype.replaceNode = function(original, replacement) {
        if (original.parent === null) {
            this.tree.root = replacement;
        } else {
            if (original === original.parent.left) {
                original.parent.left = replacement;
            } else {
                original.parent.right = replacement;
            }
        }

        if (replacement !== null) {
            replacement.parent = original.parent;
        }
    };

    Balancer.prototype.rotateLeft = function(node) {
        var right = node.right;
        this.replaceNode(node, right);

        // Update pointers
        node.right = right.left;
        if (right.left !== null) right.left.parent = node;
        right.left = node;
        node.parent = right;
    };

    Balancer.prototype.rotateRight = function(node) {
        var left = node.left;
        this.replaceNode(node, left);

        // Update pointers
        node.left = left.right;
        if (left.right !== null) left.right.parent = node;
        left.right = node;
        node.parent = left;
    };

    Balancer.prototype.insertCase1 = function(node) {
        if (node.parent === null) {
            node.color = BLACK;
        } else {
            this.insertCase2(node);
        }
    };

    Balancer.prototype.insertCase2 = function(node) {
        if (nodeColor(node.parent) === BLACK) {
            return;
        } else {
            this.insertCase3(node);
        }
    };

    Balancer.prototype.insertCase3 = function(node) {
        var uncle = node.uncle();
        var grandparent = node.grandparent();

        if (uncle !== null && nodeColor(uncle) === RED) {
            node.parent.color = BLACK;
            uncle.color = BLACK;
            grandparent.color = RED;
            this.insertCase1(grandparent);
        } else {
            this.insertCase4(node);
        }
    };

    Balancer.prototype.insertCase4 = function(node) {
        var grandparent = node.grandparent();

        if (node === node.parent.right && node.parent === grandparent.left) {
            this.rotateLeft(node.parent);
            node = node.left;
        } else if (node === node.parent.left && node.parent === grandparent.right) {
            this.rotateRight(node.parent);
            node = node.right;
        }

        this.insertCase5(node);
    };

    Balancer.prototype.insertCase5 = function(node) {
        var grandparent = node.grandparent();

        node.parent.color = BLACK;
        grandparent.color = RED;

        if (node === node.parent.left && node.parent === grandparent.left) {
            this.rotateRight(grandparent);
        } else if (node === node.parent.right && node.parent === grandparent.right) {
            this.rotateLeft(grandparent);
        }
    };

    Balancer.prototype.deleteCase1 = function(node) {
        if (node.parent !== null) this.deleteCase2(node);
    };

    Balancer.prototype.deleteCase2 = function(node) {
        var sibling = node.sibling();

        if (nodeColor(sibling) === RED) {
            node.parent.color = RED;
            sibling.color = BLACK;
            if (node === node.parent.left) {
                this.rotateLeft(node.parent);
            } else {
                this.rotateRight(node.parent);
            }
        }

        this.deleteCase3(node);
    };

    Balancer.prototype.deleteCase3 = function(node) {
        var sibling = node.sibling();

        if (nodeColor(node.parent) === BLACK &&
            nodeColor(sibling) === BLACK &&
            nodeColor(sibling.left) === BLACK &&
            nodeColor(sibling.right) === BLACK) {

            sibling.color = RED;
            this.deleteCase1(node.parent);
        } else {
            this.deleteCase4(node);
        }
    };

    Balancer.prototype.deleteCase4 = function(node) {
        var sibling = node.sibling();

        if (nodeColor(node.parent) === RED &&
            nodeColor(sibling) === BLACK &&
            nodeColor(sibling.left) === BLACK &&
            nodeColor(sibling.right) === BLACK) {

            sibling.color = RED;
            node.parent.color = BLACK;
        } else {
            this.deleteCase5(node);
        }
    };

    Balancer.prototype.deleteCase5 = function(node) {
        var sibling = node.sibling();

        if (node === node.parent.left &&
            nodeColor(sibling) === BLACK &&
            nodeColor(sibling.left) === RED &&
            nodeColor(sibling.right) === BLACK) {

            sibling.color = RED;
            sibling.left.color = BLACK;
            this.rotateRight(sibling);
        } else if (node === node.parent.right &&
            nodeColor(sibling) === BLACK &&
            nodeColor(sibling.right) === RED &&
            nodeColor(sibling.left) === BLACK) {

            sibling.color = RED;
            sibling.right.color = BLACK;
            this.rotateLeft(sibling);
        }

        this.deleteCase6(node);
    };

    Balancer.prototype.deleteCase6 = function(node) {
        var sibling = node.sibling();

        sibling.color = nodeColor(node.parent);
        node.parent.color = BLACK;

        if (node === node.parent.left) {
            sibling.right.color = BLACK;
            this.rotateLeft(node.parent);
        } else {
            sibling.left.color = BLACK;
            this.rotateRight(node.parent);
        }
    };

    // Helpers
    // ---------------

    function nodeColor(node) {
        return node === null ? BLACK : node.color;
    };

    function find(node, key) {
        while (node !== null) {
            if (key === node.key) {
                return node;
            } else if (key < node.key) {
                node = node.left;
            } else if (key > node.key) {
                node = node.right;
            }
        }

        return node;
    };

})();
/*
	meSpeak  v.1.9.6
	based on speak.js, https://github.com/kripken/speak.js
	eSpeak and other code here are under the GNU GPL.
	meSpeak (Modular eSpeak) is a mod of 'speak.js' by N.Landsteiner (2011-2014), www.masswerk.at
	adding support for Webkit/Safari and external voice-modules
	v.1.1 and later default to play via the Web Audio API and uses the HTMLAudioElement as a second option.
	official project page: http://www.masswerk.at/mespeak
*/
var meSpeak=(function(){"use strict";function ESpeak(){var vprint=(self.console)?console.log:function(){};var Module={noInitialRun:true};"use strict";if(!Module.arguments){try{Module.arguments=arguments;}catch(e){Module.arguments=[];}}
var Runtime={stackSave:function(){return STACKTOP;},stackRestore:function(stackTop){STACKTOP=stackTop;},forceAlign:function(target,quantum){quantum=quantum||4;if(isNumber(target)&&isNumber(quantum)){return Math.ceil(target/quantum)*quantum;}else{return'Math.ceil(('+target+')/'+quantum+')*'+quantum;}},isNumberType:function(type){return type in Runtime.INT_TYPES||type in Runtime.FLOAT_TYPES;},isPointerType:function isPointerType(type){return pointingLevels(type)>0;},isStructType:function isStructType(type){if(isPointerType(type))return false;if(new RegExp(/^\[\d+\ x\ (.*)\]/g).test(type))return true;if(new RegExp(/<?{ [^}]* }>?/g).test(type))return true;return!Runtime.isNumberType(type)&&type[0]=='%';},INT_TYPES:{"i1":0,"i8":0,"i16":0,"i32":0,"i64":0},FLOAT_TYPES:{"float":0,"double":0},or64:function(x,y){var l=(x|0)|(y|0);var h=(Math.round(x/4294967296)|Math.round(y/4294967296))*4294967296;return l+h;},and64:function(x,y){var l=(x|0)&(y|0);var h=(Math.round(x/4294967296)&Math.round(y/4294967296))*4294967296;return l+h;},xor64:function(x,y){var l=(x|0)^(y|0);var h=(Math.round(x/4294967296)^Math.round(y/4294967296))*4294967296;return l+h;},getNativeFieldSize:function getNativeFieldSize(type){return Math.max(Runtime.getNativeTypeSize(type),4);},getNativeTypeSize:function getNativeTypeSize(type){if(4==1)return 1;var size={'_i1':1,'_i8':1,'_i16':2,'_i32':4,'_i64':8,"_float":4,"_double":8}['_'+type];if(!size&&type[type.length-1]=='*'){size=4;}
return size;},dedup:function dedup(items,ident){var seen={};if(ident){return items.filter(function(item){if(seen[item[ident]])return false;seen[item[ident]]=true;return true;});}else{return items.filter(function(item){if(seen[item])return false;seen[item]=true;return true;});}},set:function set(){var args=typeof arguments[0]==='object'?arguments[0]:arguments;var ret={};for(var i=0;i<args.length;i++){ret[args[i]]=0;}
return ret;},calculateStructAlignment:function calculateStructAlignment(type){type.flatSize=0;type.alignSize=0;var diffs=[];var prev=-1;type.flatIndexes=type.fields.map(function(field){var size,alignSize;if(Runtime.isNumberType(field)||Runtime.isPointerType(field)){size=Runtime.getNativeTypeSize(field);alignSize=size;}else if(Runtime.isStructType(field)){size=Types.types[field].flatSize;alignSize=Types.types[field].alignSize;}else{dprint('Unclear type in struct: '+field+', in '+type.name_+' :: '+dump(Types.types[type.name_]));assert(0);}
alignSize=type.packed?1:Math.min(alignSize,4);type.alignSize=Math.max(type.alignSize,alignSize);var curr=Runtime.alignMemory(type.flatSize,alignSize);type.flatSize=curr+size;if(prev>=0){diffs.push(curr-prev);}
prev=curr;return curr;});type.flatSize=Runtime.alignMemory(type.flatSize,type.alignSize);if(diffs.length==0){type.flatFactor=type.flatSize;}else if(Runtime.dedup(diffs).length==1){type.flatFactor=diffs[0];}
type.needsFlattening=(type.flatFactor!=1);return type.flatIndexes;},generateStructInfo:function(struct,typeName,offset){var type,alignment;if(typeName){offset=offset||0;type=(typeof Types==='undefined'?Runtime.typeInfo:Types.types)[typeName];if(!type)return null;if(!struct)struct=(typeof Types==='undefined'?Runtime:Types).structMetadata[typeName.replace(/.*\./,'')];if(!struct)return null;assert(type.fields.length===struct.length,'Number of named fields must match the type for '+typeName+'. Perhaps due to inheritance, which is not supported yet?');alignment=type.flatIndexes;}else{var type={fields:struct.map(function(item){return item[0]})};alignment=Runtime.calculateStructAlignment(type);}
var ret={__size__:type.flatSize};if(typeName){struct.forEach(function(item,i){if(typeof item==='string'){ret[item]=alignment[i]+offset;}else{var key;for(var k in item)key=k;ret[key]=Runtime.generateStructInfo(item[key],type.fields[i],alignment[i]);}});}else{struct.forEach(function(item,i){ret[item[1]]=alignment[i];});}
return ret;},stackAlloc:function stackAlloc(size){var ret=STACKTOP;_memset(STACKTOP,0,size);STACKTOP+=size;STACKTOP=Math.ceil((STACKTOP)/4)*4;;return ret;},staticAlloc:function staticAlloc(size){var ret=STATICTOP;STATICTOP+=size;STATICTOP=Math.ceil((STATICTOP)/4)*4;;return ret;},alignMemory:function alignMemory(size,quantum){var ret=size=Math.ceil((size)/(quantum?quantum:4))*(quantum?quantum:4);;return ret;},__dummy__:0}
var CorrectionsMonitor={MAX_ALLOWED:0,corrections:0,sigs:{},note:function(type,succeed,sig){if(!succeed){this.corrections++;if(this.corrections>=this.MAX_ALLOWED)abort('\n\nToo many corrections!');}},vprint:function(){var items=[];for(var sig in this.sigs){items.push({sig:sig,fails:this.sigs[sig][0],succeeds:this.sigs[sig][1],total:this.sigs[sig][0]+this.sigs[sig][1]});}
items.sort(function(x,y){return y.total-x.total;});for(var i=0;i<items.length;i++){var item=items[i];vprint(item.sig+' : '+item.total+' hits, %'+(Math.ceil(100*item.fails/item.total))+' failures');}}};function cRound(x){return x>=0?Math.floor(x):Math.ceil(x);}
var __globalConstructor__=function globalConstructor(){};var __THREW__=false;var __ATEXIT__=[];var ABORT=false;var undef=0;var tempValue,tempInt,tempBigInt;function abort(text){vprint(text+':\n'+(new Error).stack);ABORT=true;throw"Assertion: "+text;}
function assert(condition,text){if(!condition){abort('Assertion failed: '+text);}}
function setValue(ptr,value,type){if(type[type.length-1]==='*')type='i32';switch(type){case'i1':HEAP8[(ptr)]=value;;break;case'i8':HEAP8[(ptr)]=value;;break;case'i16':HEAP16[((ptr)>>1)]=value;;break;case'i32':HEAP32[((ptr)>>2)]=value;;break;case'i64':HEAP32[((ptr)>>2)]=value;;break;case'float':HEAPF32[((ptr)>>2)]=value;;break;case'double':HEAPF32[((ptr)>>2)]=value;;break;default:abort('invalid type for setValue: '+type);}}
Module.setValue=setValue;function getValue(ptr,type){if(type[type.length-1]==='*')type='i32';switch(type){case'i1':return HEAP8[(ptr)];case'i8':return HEAP8[(ptr)];case'i16':return HEAP16[((ptr)>>1)];case'i32':return HEAP32[((ptr)>>2)];case'i64':return HEAP32[((ptr)>>2)];case'float':return HEAPF32[((ptr)>>2)];case'double':return HEAPF32[((ptr)>>2)];default:abort('invalid type for setValue: '+type);}
return null;}
Module.getValue=getValue;var ALLOC_NORMAL=0;var ALLOC_STACK=1;var ALLOC_STATIC=2;Module.ALLOC_NORMAL=ALLOC_NORMAL;Module.ALLOC_STACK=ALLOC_STACK;Module.ALLOC_STATIC=ALLOC_STATIC;function allocate(slab,types,allocator){var zeroinit,size;if(typeof slab==='number'){zeroinit=true;size=slab;}else{zeroinit=false;size=slab.length;}
var ret=[_malloc,Runtime.stackAlloc,Runtime.staticAlloc][allocator===undefined?ALLOC_STATIC:allocator](Math.max(size,1));var singleType=typeof types==='string'?types:null;var i=0,type;while(i<size){var curr=zeroinit?0:slab[i];if(typeof curr==='function'){curr=Runtime.getFunctionIndex(curr);}
type=singleType||types[i];if(type===0){i++;continue;}
setValue(ret+i,curr,type);i+=Runtime.getNativeTypeSize(type);}
return ret;}
Module.allocate=allocate;function Pointer_stringify(ptr){var ret="";var i=0;var t;var nullByte=String.fromCharCode(0);while(1){t=String.fromCharCode(HEAPU8[(ptr+i)]);if(t==nullByte){break;}else{}
ret+=t;i+=1;}
return ret;}
Module.Pointer_stringify=Pointer_stringify;function Array_stringify(array){var ret="";for(var i=0;i<array.length;i++){ret+=String.fromCharCode(array[i]);}
return ret;}
Module.Array_stringify=Array_stringify;var FUNCTION_TABLE;var PAGE_SIZE=4096;function alignMemoryPage(x){return Math.ceil(x/PAGE_SIZE)*PAGE_SIZE;}
var HEAP;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32;var STACK_ROOT,STACKTOP,STACK_MAX;var STATICTOP;var HAS_TYPED_ARRAYS=false;var TOTAL_MEMORY=Module.TOTAL_MEMORY||52428800;var FAST_MEMORY=Module.FAST_MEMORY||2097152;HAS_TYPED_ARRAYS=false;try{HAS_TYPED_ARRAYS=!!Int32Array&&!!Float32Array&&!!(new Int32Array(1).subarray);}catch(e){}
if(HAS_TYPED_ARRAYS){var buffer=new ArrayBuffer(TOTAL_MEMORY);HEAP8=new Int8Array(buffer);HEAP16=new Int16Array(buffer);HEAP32=new Int32Array(buffer);HEAPU8=new Uint8Array(buffer);HEAPU16=new Uint16Array(buffer);HEAPU32=new Uint32Array(buffer);HEAPF32=new Float32Array(buffer);HEAP32[0]=255;assert(HEAPU8[0]===255&&HEAPU8[3]===0,'Typed arrays 2 must be run on a little-endian system');}else
{abort('Cannot fallback to non-typed array case in USE_TYPED_ARRAYS == 2: Code is too specialized');}
var base=intArrayFromString('(null)');for(var i=0;i<base.length;i++){HEAP8[(i)]=base[i];}
Module.HEAP=HEAP;Module.HEAP8=HEAP8;Module.HEAP16=HEAP16;Module.HEAP32=HEAP32;Module.HEAPU8=HEAPU8;Module.HEAPU16=HEAPU16;Module.HEAPU32=HEAPU32;Module.HEAPF32=HEAPF32;STACK_ROOT=STACKTOP=alignMemoryPage(10);var TOTAL_STACK=1024*1024;STACK_MAX=STACK_ROOT+TOTAL_STACK;STATICTOP=alignMemoryPage(STACK_MAX);function __shutdownRuntime__(){while(__ATEXIT__.length>0){var atexit=__ATEXIT__.pop();var func=atexit.func;if(typeof func==='number'){func=FUNCTION_TABLE[func];}
func(atexit.arg===undefined?null:atexit.arg);}
CorrectionsMonitor.vprint();}
function Array_copy(ptr,num){if(HAS_TYPED_ARRAYS){return Array.prototype.slice.call(HEAP8.subarray(ptr,ptr+num));}else{return HEAP8.slice(ptr,ptr+num);}
return HEAP.slice(ptr,ptr+num);}
Module.Array_copy=Array_copy;function String_len(ptr){var i=0;while(HEAP8[(ptr+i)])i++;return i;}
Module.String_len=String_len;function String_copy(ptr,addZero){var len=String_len(ptr);if(addZero)len++;var ret=Array_copy(ptr,len);if(addZero)ret[len-1]=0;return ret;}
Module.String_copy=String_copy;if(typeof self.console==='object'&&typeof console.log==='function'){this.vprint=function(x){console.log(x)};}else if(typeof vprint==='undefined'){this.vprint=function(){};}
function intArrayFromString(stringy,dontAddNull){var ret=[];var t;var i=0;while(i<stringy.length){var chr=stringy.charCodeAt(i);if(chr>0xFF){chr&=0xFF;}
ret.push(chr);i=i+1;}
if(!dontAddNull){ret.push(0);}
return ret;}
Module.intArrayFromString=intArrayFromString;function intArrayToString(array){var ret=[];for(var i=0;i<array.length;i++){var chr=array[i];if(chr>0xFF){chr&=0xFF;}
ret.push(String.fromCharCode(chr));}
return ret.join('');}
Module.intArrayToString=intArrayToString;function unSign(value,bits,ignore,sig){if(value>=0){return value;}
return bits<=32?2*Math.abs(1<<(bits-1))+value:Math.pow(2,bits)+value;}
function reSign(value,bits,ignore,sig){if(value<=0){return value;}
var half=bits<=32?Math.abs(1<<(bits-1)):Math.pow(2,bits-1);if(value>=half&&(bits<=32||value>half)){value=-2*half+value;}
return value;}
Runtime.QUANTUM_SIZE=4
var $struct___sFILE___SIZE=104;var $struct___sFILE___FLATTENER=[0,4,8,12,14,16,24,28,32,36,40,44,48,56,60,64,67,68,76,80,84,88,92,100];var $struct___sbuf___SIZE=8;var $struct__reent___SIZE=1060;var $struct__reent___FLATTENER=[0,4,8,12,16,20,48,52,56,60,64,68,72,76,80,84,88,328,332,732,736,748];var $struct__Bigint___SIZE=24;var $union_anon_0___SIZE=240;var $struct_anon_1___SIZE=240;var $struct__atexit___SIZE=400;var $struct__atexit___FLATTENER=[0,4,8,136];var $struct__on_exit_args___SIZE=264;var $struct__on_exit_args___FLATTENER=[0,128,256,260];var $struct__glue___SIZE=12;var $struct__mbstate_t___SIZE=8;var $union_anon___SIZE=4;var $struct_option___SIZE=16;var $struct_MNEM_TAB___SIZE=8;var $struct_MatchRecord___SIZE=16;var $struct_TUNE___SIZE=68;var $struct_TUNE___FLATTENER=[0,12,16,24,25,26,27,28,29,30,31,32,33,34,35,36,39,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,64];var $struct_SYLLABLE___SIZE=6;var $struct_TONE_HEAD___SIZE=16;var $struct_TONE_HEAD___FLATTENER=[0,1,2,3,4,8,9,10,12];var $struct_SSML_STACK___SIZE=76;var $struct_SSML_STACK___FLATTENER=[0,4,8,12,16,56];var $struct_PARAM_STACK_45___SIZE=64;var $struct_ACCENTS___SIZE=8;var $struct_MBROLA_TAB___SIZE=24;var $struct_PHONEME_TAB___SIZE=16;var $struct_PHONEME_TAB___FLATTENER=[0,4,8,10,11,12,13,14,15];var $struct_PHONEME_TAB_LIST_106___SIZE=48;var $struct_PHONEME_TAB_LIST_106___FLATTENER=[0,32,36,40,44];var $struct_frameref_t___SIZE=8;var $struct_frame_t___SIZE=64;var $struct_frame_t___FLATTENER=[0,2,16,17,18,26,32,35,39,44,49,56,63];var $struct_PHONEME_DATA___SIZE=152;var $struct_PHONEME_DATA___FLATTENER=[0,4,68,88,108,124,128,132];var $struct_PHONEME_LIST___SIZE=24;var $struct_PHONEME_LIST___FLATTENER=[0,1,2,3,4,6,8,12,14,15,16,17,18,19,20,21];var $struct_SPEED_FACTORS___SIZE=64;var $struct_voice_t___SIZE=1344;var $struct_voice_t___FLATTENER=[0,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,144,162,180,198,216,234,252,272,308,344];var $struct_SOUND_ICON___SIZE=16;var $struct_Translator___SIZE=8328;var $struct_Translator___FLATTENER=[0,280,284,288,292,332,632,652,656,660,668,676,692,696,700,704,708,964,968,1000,1048,1052,1056,5152,5256,6280,6792,7272,7752,7756,8012,8268,8272,8276,8280,8284,8288,8292,8296,8300,8304,8308,8312,8316,8320,8324];var $struct_LANGUAGE_OPTIONS___SIZE=280;var $struct_LANGUAGE_OPTIONS___FLATTENER=[0,4,8,12,16,20,24,100,176,180,184,188,192,196,200,204,208,212,216,220,224,228,232,240,244,248,249,250,251,252,256,260,264,268,272,276];var $struct_PHONEME_LIST2___SIZE=8;var $struct_PHONEME_LIST2___FLATTENER=[0,1,2,3,4,6];var $struct_REPLACE_PHONEMES___SIZE=3;var $struct_datablock___SIZE=16;var $struct_espeak_VOICE___SIZE=24;var $struct_espeak_VOICE___FLATTENER=[0,4,8,12,13,14,15,16,20];var $struct_wavegen_peaks_t___SIZE=80;var $struct_wavegen_peaks_t___FLATTENER=[0,4,8,12,16,24,32,40,48,56,64,72];var $struct_RESONATOR___SIZE=40;var $struct_WGEN_DATA___SIZE=64;var $struct_sonicStreamStruct___SIZE=88;var $struct_klatt_frame_t___SIZE=288;var $struct_klatt_frame_t___FLATTENER=[0,4,8,48,88,128,168,172,176,180,184,188,192,196,200,204,208,248];var $struct_klatt_global_t___SIZE=2748;var $struct_klatt_global_t___FLATTENER=[0,4,8,12,16,20,24,28,32,36,40,44,48,52,56,64,72,80,88,96,104,112,120,128,136,144,152,160,164,172,176,180,184,188,1468];var $struct_resonator_t___SIZE=64;var $struct_klatt_peaks_t___SIZE=80;var $struct_klatt_peaks_t___FLATTENER=[0,4,8,12,16,24,32,40,48,56,64,72];var $struct_frame_t_199___SIZE=64;var $struct_frame_t_199___FLATTENER=[0,2,16,17,18,26,32,35,39,44,49,56,63];var $struct_stat___SIZE=80;var $struct_stat___FLATTENER=[0,8,12,16,20,24,28,36,40,44,48,52,56,60,64,68,72];var $struct_PARAM_STACK___SIZE=64;var $struct_PHONEME_TAB_LIST___SIZE=48;var $struct_PHONEME_TAB_LIST___FLATTENER=[0,32,36,40,44];var $struct_PHONEME_TAB_11___SIZE=16;var $struct_PHONEME_TAB_11___FLATTENER=[0,4,8,10,11,12,13,14,15];var $struct_RGROUP___SIZE=28;var $struct_RGROUP___FLATTENER=[0,16,20,24];var $struct_WORD_TAB___SIZE=12;var $struct_WORD_TAB___FLATTENER=[0,4,6,8,9,10];var $struct_PHONEME_TAB_LIST_25___SIZE=48;var $struct_PHONEME_TAB_LIST_25___FLATTENER=[0,32,36,40,44];var $struct_WORD_TAB_29___SIZE=12;var $struct_WORD_TAB_29___FLATTENER=[0,4,6,8,9,10];var $struct_Translator_33___SIZE=8328;var $struct_Translator_33___FLATTENER=[0,280,284,288,292,332,632,652,656,660,668,676,692,696,700,704,708,964,968,1000,1048,1052,1056,5152,5256,6280,6792,7272,7752,7756,8012,8268,8272,8276,8280,8284,8288,8292,8296,8300,8304,8308,8312,8316,8320,8324];var $struct_LANGUAGE_OPTIONS_32___SIZE=280;var $struct_LANGUAGE_OPTIONS_32___FLATTENER=[0,4,8,12,16,20,24,100,176,180,184,188,192,196,200,204,208,212,216,220,224,228,232,240,244,248,249,250,251,252,256,260,264,268,272,276];var $struct_TONE_NUCLEUS___SIZE=16;var $struct_TONE_NUCLEUS___FLATTENER=[0,1,2,3,4,5,8,12,13,14];var $struct_PARAM_STACK_54___SIZE=64;var $struct_FMT_PARAMS___SIZE=48;var $struct_FMT_PARAMS_111___SIZE=48;var $struct_SPECT_SEQ___SIZE=1104;var $struct_SPECT_SEQ___FLATTENER=[0,2,3,4];var $struct_frame_t2___SIZE=44;var $struct_frame_t2___FLATTENER=[0,2,16,17,18,26,32,35,39];var $struct_SPECT_SEQK___SIZE=1604;var $struct_SPECT_SEQK___FLATTENER=[0,2,3,4];var $struct_pollfd___SIZE=8;var $struct_pollfd___FLATTENER=[0,4,6];var $struct_dirent___SIZE=1040;var $struct_dirent___FLATTENER=[0,4,1028,1032,1036];var $struct_getopt_data___SIZE=20;var _path_home;var _filetype;var _wavefile;var _uri_callback;var _phoneme_callback;var _f_wave;var _quiet;var _samples_total;var _samples_split;var _wavefile_count;var _end_of_sentence;var _voice_pcnt;var __impure_ptr;var __ZZ13DisplayVoicesP7__sFILEPcE7genders;var __str1;var __str3;var __str4;var __str5;var __ZZ4mainE12long_options;var __str6;var __str7;var __str8;var __str9;var __str10;var __str11;var __str12;var __str13;var __str14;var __str15;var __str16;var __str17;var __str18;var __str19;var __str21;var __str23;var __str25;var __str27;var __str28;var __str29;var __str30;var __ZZL12OpenWaveFilePKciE8wave_hdr;var __str32;var __str33;var __str35;var __str36;var __str37;var __str38;var __str39;var __str40;var __str41;var __ZL5f_log;var __str42;var __str143;var __str244;var __str345;var __str446;var __str547;var __str648;var _mnem_rules;var __str749;var __str850;var __str951;var __str1052;var __str1153;var __str1254;var __str1355;var __str1456;var __str1557;var __str1658;var __str1759;var __str1860;var __str1961;var __str2062;var __str2163;var __str2264;var __str2365;var __str2466;var __str2567;var __str2668;var __str2769;var __str2870;var __str2971;var __str3072;var __str3173;var __str3274;var __str3375;var __str3476;var __str3577;var __str3678;var __str3779;var __str3880;var __str3981;var __str4082;var __str4183;var __str4284;var __str43;var __str44;var __str45;var __str46;var __str47;var __str48;var __str49;var __str50;var __str51;var __str52;var __str53;var __str54;var __str55;var __str56;var __str57;var _mnem_flags;var __ZZ22print_dictionary_flagsPjE3buf;var __str59;var __ZZ10DecodeRulePKciPciE6output;var __ZZ10DecodeRulePKciPciE7symbols;var __ZZ10DecodeRulePKciPciE10symbols_lg;var __str60;var __str61;var __str62;var __str64;var __str65;var __ZL11error_count;var __ZL21error_need_dictionary;var __ZL19letterGroupsDefined;var __ZL10debug_flag;var __str66;var __str67;var __str69;var __str71;var __str72;var __str73;var __str74;var __str75;var __str76;var __str77;var __str78;var __ZL7linenum;var __ZL10group_name;var __str79;var __ZL9group3_ix;var __str81;var __str82;var __str83;var __str84;var __str85;var __str89;var __ZL9rule_cond;var __ZL8rule_pre;var __ZL9rule_post;var __ZL10rule_match;var __ZL13rule_phonemes;var __str90;var __str91;var __str92;var __str93;var __str94;var __str95;var __ZZL16copy_rule_stringPcRiE6outbuf;var __ZZL16copy_rule_stringPcRiE10next_state;var __ZZL16copy_rule_stringPcRiE16lettergp_letters;var __str97;var __str98;var __str99;var __str100;var __str101;var __str102;var __str103;var __ZL11hash_chains;var __ZL11hash_counts;var __ZL9text_mode_b;var __str104;var __str106;var __str107;var __ZZL12compile_linePcS_PiE10nullstring;var __str108;var __str109;var __str110;var __str111;var __str112;var __str113;var __str114;var __str115;var _dictionary_skipwords;var _dictionary_name;var __ZL13remove_accent;var __str116;var __str2118;var __str3119;var __str4120;var __str5121;var __str7123;var _ipa1;var __str8124;var __str9125;var __ZL15stress_phonemes;var __ZZ13SetWordStressP10TranslatorPcPjiiE15consonant_types;var __ZZ13SetWordStressP10TranslatorPcPjiiE8guess_ru;var __ZZ13SetWordStressP10TranslatorPcPjiiE10guess_ru_v;var __ZZ13SetWordStressP10TranslatorPcPjiiE10guess_ru_t;var __ZZ14TranslateRulesP10TranslatorPcS1_iS1_iPjE9str_pause;var __str10126;var __str11127;var __ZL13diereses_list;var __ZZ14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TABE16word_replacement;var __str15131;var __str16132;var __ZZ11LookupFlagsP10TranslatorPKcE5flags;var __ZZ12RemoveEndingP10TranslatorPciS1_E6ending;var __ZZ12RemoveEndingP10TranslatorPciS1_E16add_e_exceptions;var __str17133;var __ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions;var __str18134;var __str19135;var __str20136;var __str21137;var __str22138;var __str23139;var __str24140;var __str25141;var __str27143;var __str28144;var __str29145;var __str30146;var __str31147;var __ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best;var __str32148;var __str34150;var _env_fall;var _env_rise;var _env_frise;var __ZL11env_r_frise;var __ZL10env_frise2;var __ZL12env_r_frise2;var __ZL12env_risefall;var __ZL13env_fallrise3;var __ZL13env_fallrise4;var __ZL9env_fall2;var __ZL9env_rise2;var __ZL16env_risefallrise;var _envelope_data;var __ZL18tone_nucleus_table;var _punctuation_to_tone;var _n_tunes;var _tunes;var __ZL12syllable_tab;var __ZL8no_tonic_b;var __ZL15tone_head_table;var __ZL10number_pre;var __ZL10tone_posn2;var __ZL9tone_posn;var __ZL11number_tail;var __ZL14tone_pitch_env;var __ZZL18calc_pitch_segmentiiP9TONE_HEADP12TONE_NUCLEUSiiE12continue_tab;var __ZL8min_drop;var __ZL7drops_0;var __ZL5oflow;var __ZL9oflow_emf;var __ZL10oflow_less;var __ZL12last_primary;var _namedata;var __ZL7f_input;var _p_textinput;var _p_wchar_input;var __ZL10ungot_word;var _count_characters;var __ZL10ssml_stack;var __ZL16current_voice_id;var _param_stack;var _param_defaults;var _walpha_tab;var __ZL10ungot_char;var __ZL12end_of_input_b;var __str167;var __str1168;var __str2169;var __str3170;var __str4171;var __str5172;var __str6173;var __str7174;var __str8175;var __str9176;var __str10177;var __str11178;var __str12179;var __str13180;var __str14181;var __str15182;var __str16183;var __str17184;var __str18185;var __str19186;var __str20187;var __str21188;var __str22189;var __str23190;var __str24191;var __str25192;var __str26193;var __str27194;var __str28195;var __str29196;var __str30197;var __str31198;var __ZL8ssmltags;var __ZL10n_namedata;var __ZL11namedata_ix;var __str32199;var __str33200;var __str34201;var __str35202;var __str36203;var __str37204;var __ZL18xml_char_mnemonics;var __ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E12ungot_string;var __ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix;var __ZL19clear_skipping_text_b;var __ZL11ungot_char2;var __ZL19ssml_ignore_l_angle;var __str38205;var __ZL10sayas_mode;var __ZL11ignore_text_b;var __ZL11punct_chars;var __ZL16punct_attributes;var __str41208;var __ZL12chars_ignore;var __str42209;var __ZL10audio_text_b;var __ZL17speech_parameters;var __ZL12n_ssml_stack;var __ZL13n_param_stack;var __ZL7xmlbase;var __ZZL14LookupCharNameP10TranslatoriiE3buf;var __str47214;var __str48215;var __str49216;var __ZZL13WordToString2jE3buf;var __str50217;var __str51218;var __str52219;var __str53220;var __str54221;var __str55222;var __str57224;var __str58225;var __str59226;var __str60227;var __ZZL14ProcessSsmlTagPwPcRiiiE10mnem_punct;var __str61228;var __str62229;var __str63230;var __ZZL14ProcessSsmlTagPwPcRiiiE13mnem_capitals;var __str64231;var __str65232;var __str66233;var __ZZL14ProcessSsmlTagPwPcRiiiE17mnem_interpret_as;var __str68235;var __str69236;var __str70237;var __str71238;var __str72239;var __ZZL14ProcessSsmlTagPwPcRiiiE17mnem_sayas_format;var __str73240;var __ZZL14ProcessSsmlTagPwPcRiiiE10mnem_break;var __str74241;var __str75242;var __str76243;var __str77244;var __ZZL14ProcessSsmlTagPwPcRiiiE13mnem_emphasis;var __str78245;var __str79246;var __ZZL14ProcessSsmlTagPwPcRiiiE12prosody_attr;var __str80247;var __str81248;var __str82249;var __ZL22ignore_if_self_closing;var __str83250;var __str84251;var __str85252;var __str86253;var __str87254;var __ZZL14ProcessSsmlTagPwPcRiiiE23emphasis_to_pitch_range;var __ZZL14ProcessSsmlTagPwPcRiiiE18emphasis_to_volume;var __str88255;var __str89256;var __str90257;var __str91258;var __ZL11sayas_start;var __str92259;var __str94261;var __str95262;var __str96263;var __str97264;var __str98265;var __str99266;var __ZZL14ProcessSsmlTagPwPcRiiiE11break_value;var __str100267;var __str101268;var __str102269;var __ZZL18GetVoiceAttributesPwiE11mnem_gender;var __str105272;var __str106273;var __str108275;var __ZZL14LoadSoundFile2PKcE4slot;var __str111278;var __str112279;var __str113280;var __str114281;var __ZZL14ReplaceKeyNamePciRiE8keynames;var __ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume;var __str115282;var __str116283;var __str117;var __str118;var __str119;var __ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_rate;var __str120;var __str121;var __str122;var __str123;var __ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_pitch;var __str124;var __str125;var __str126;var __str127;var __ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_range;var __ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_tabs;var __ZZL17ProcessParamStackPcRiE10cmd_letter;var __str128;var __ZZL16GetSsmlAttributePwPKcE5empty;var __ZZL4GetCvE6ungot2;var __ZZL4GetCvE5mask2;var __ZL6speed1;var __ZL6speed2;var __ZL6speed3;var __ZL12speed_lookup;var __ZL14wav_factor_350;var __ZL16pause_factor_350;var __ZZ11CalcLengthsP10TranslatorE14more_syllables;var __str294;var __ZL18letter_accents_0e0;var __ZL18letter_accents_250;var __ZL13non_ascii_tab;var __ZL11accents_tab;var __str297;var __str1298;var __str2299;var __ZZ12LookupLetterP10TranslatorjiPciE13single_letter;var __str5302;var __str6303;var __str7304;var __str8305;var __str9306;var __str10307;var __str11308;var __str12309;var __ZZ14TranslateRomanP10TranslatorPcS1_P8WORD_TABE12roman_values;var __str13310;var __str14311;var __ZZL17TranslateNumber_1P10TranslatorPcS1_PjP8WORD_TABiE9str_pause;var __ZL14n_digit_lookup;var __ZL12digit_lookup;var __ZL14number_control;var __ZL23speak_missing_thousands;var __ZL11ph_ordinal2;var __str15312;var __str16313;var __str17314;var __str18315;var __str19316;var __str20317;var __str21318;var __str22319;var __str23320;var __str24321;var __str25322;var __str26323;var __str27324;var __str28325;var __str29326;var __str30327;var __str31328;var __str32329;var __str33330;var __str35332;var __str36333;var __str37334;var __str39336;var __str40337;var __str41338;var __str42339;var __str43340;var __str44341;var __str45342;var __str46343;var __str47344;var __str48345;var __str49346;var __str50347;var __str51348;var __str52349;var __str53350;var __str54351;var __str55352;var __str56353;var __str57354;var __str58355;var __str59356;var __str60357;var __str61358;var __str62359;var __str63360;var __str64361;var __str65362;var __str66363;var __str67364;var __str68365;var __str69366;var __str70367;var __str71368;var __str72369;var __str73370;var __str74371;var __str75372;var __str76373;var __str77374;var __str78375;var _option_mbrola_phonemes;var __ZL10mbrola_tab;var __ZL15mbr_name_prefix;var __str382;var __str1383;var __str2384;var __str3385;var __str4386;var __ZL14mbrola_control;var __ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix;var __ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE11embedded_ix;var __ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE10word_count;var __str6388;var __str8390;var __str9391;var __str10392;var __str11393;var __str12394;var __ZZ10MbrolaFilliiE9n_samples;var __ZZL10WritePitchiiiiiE6output;var __str13395;var __str14396;var __str15397;var __str16398;var __ZZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_E4mnem;var __str399;var _version_string;var _version_phdata;var _option_device_number;var _f_logespeak;var _logging_type;var _n_phoneme_tab;var _current_phoneme_table;var _phoneme_tab;var _phoneme_tab_flags;var _phoneme_index;var _phondata_ptr;var _wavefile_data;var __ZL16phoneme_tab_data;var _n_phoneme_tables;var _phoneme_tab_list;var _phoneme_tab_number;var _wavefile_ix;var _wavefile_amp;var _wavefile_ix2;var _wavefile_amp2;var _seq_len_adjust;var _vowel_transition;var _vowel_transition0;var _vowel_transition1;var __str1412;var __str2413;var __str3414;var __str4415;var __ZZ11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LISTE10frames_buf;var __str5416;var __str7418;var __str9420;var __str10421;var __str11422;var __str13424;var __str15426;var __str16427;var _this_ph_data;var __ZZL13NumInstnWordsPtE7n_words;var __ZZL18InterpretConditionP10TranslatoriP12PHONEME_LISTiE11ph_position;var __ZZL15StressConditionP10TranslatorP12PHONEME_LISTiiE15condition_level;var __str17428;var __str18429;var __str19430;var _n_phoneme_list;var _phoneme_list;var _mbrola_delay;var _mbrola_name;var _speed;var __ZL9new_voice;var _n_soundicon_tab;var _soundicon_tab;var __ZZ12WordToStringjE3buf;var __ZL14last_pitch_cmd;var __ZL12last_amp_cmd;var __ZL10last_frame;var __ZL15syllable_centre;var __ZZ18FormantTransition2P10frameref_tRijjP11PHONEME_TABiE10vcolouring;var __ZL10modn_flags;var __ZZ8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTiE9wave_flag_b;var __ZL13fmt_amplitude;var __ZL10last_wcmdq;var __ZL12pitch_length;var __ZL10amp_length;var __ZZ8GenerateP12PHONEME_LISTPiiE2ix;var __ZZ8GenerateP12PHONEME_LISTPiiE11embedded_ix;var __ZZ8GenerateP12PHONEME_LISTPiiE10word_count;var __ZZ8GenerateP12PHONEME_LISTPiiE8sourceix;var __ZL14syllable_start;var __ZL12syllable_end;var __ZL8timer_on_b;var __ZL6paused_b;var __ZZ15SpeakNextClauseP7__sFILEPKviE6f_text;var __ZZ15SpeakNextClauseP7__sFILEPKviE6p_text;var __str459;var __str1460;var __ZZL13set_frame_rmsP7frame_tiE8sqrt_tab;var __ZZL10AllocFramevE2ix;var __ZZL10AllocFramevE10frame_pool;var _translator;var _translator2;var __ZL20translator2_language;var _f_trans;var _option_tone2;var _option_tone_flags;var _option_phonemes;var _option_phoneme_events;var _option_quiet;var _option_endpause;var _option_capitals;var _option_punctuation;var _option_sayas;var _option_ssml;var _option_phoneme_input;var _option_phoneme_variants;var _option_wordgap;var _skip_sentences;var _skip_words;var _skip_characters;var _skip_marker;var _skipping_text;var _end_character_position;var _count_sentences;var _count_words;var _clause_start_char;var _clause_start_word;var _new_sentence;var _pre_pause;var _word_phonemes;var _n_ph_list2;var _ph_list2;var _option_punctlist;var _ctrl_embedded;var _option_multibyte;var _option_linelength;var _embedded_list;var _n_replace_phonemes;var _replace_phonemes;var __ZL10ISO_8859_1;var __ZL10ISO_8859_2;var __ZL10ISO_8859_3;var __ZL10ISO_8859_4;var __ZL10ISO_8859_5;var __ZL10ISO_8859_7;var __ZL10ISO_8859_9;var __ZL11ISO_8859_14;var __ZL6KOI8_R;var __ZL5ISCII;var _charsets;var __ZL15length_mod_tabs;var __ZZ7IsAlphajE18extra_indic_alphas;var __ZL8brackets;var __ZZ8utf8_outjPcE4code;var __ZZ8utf8_in2PiPKciE4mask;var __str543;var __str1544;var __ZZ13TranslateWordP10TranslatorPciP8WORD_TABE7word_zz;var __ZZ13TranslateWordP10TranslatorPciP8WORD_TABE7word_iz;var __ZZ13TranslateWordP10TranslatorPciP8WORD_TABE7word_ss;var __str2545;var __str4547;var __str5548;var __str6549;var __ZL18any_stressed_words_b;var __ZZ15TranslateClauseP10TranslatorP7__sFILEPKvPiPPcE17voice_change_name;var __ZL11embedded_ix;var __ZL13embedded_read;var __ZL6source;var __str7550;var __str8551;var __ZL16max_clause_pause;var __ZL13option_sayas2;var __ZL18count_sayas_digits;var __ZL6breaks;var __ZL13word_emphasis_b;var __ZL15option_emphasis;var __ZL13embedded_flag_b;var __str9552;var __str10553;var __str11554;var __ZZL13TranslateCharP10TranslatorPcijjPiE20hangul_compatibility;var __ZZL14SubstituteCharP10TranslatorjjPiE11ignore_next_b;var __str12555;var __ZL14length_mods_en;var __ZL15length_mods_en0;var __ZL17length_mods_equal;var __str580;var __str1581;var __str2582;var __str3583;var __str4584;var __ZL14mbr_samplerate;var __ZL14mbr_voice_path;var __ZL10mbr_volume;var __ZL9mbr_state;var __ZL7mbr_pid;var __ZL10mbr_cmd_fd;var __str5585;var __ZL12mbr_audio_fd;var __ZL12mbr_errorbuf;var __ZL12mbr_error_fd;var __str7587;var __str8588;var __str9589;var __str10590;var __str11591;var __str12592;var __str13593;var __str14594;var __str15595;var __str16596;var __str17597;var __ZL21mbr_pending_data_head;var __ZL21mbr_pending_data_tail;var __str18598;var __str19599;var __str20600;var __str21601;var __ZL13mbr_proc_stat;var __str22602;var __str23603;var __str24604;var __str25605;var __str27607;var __str28608;var __str30610;var __str31611;var __str32612;var __str33613;var __str34614;var __str35615;var __ZZ15SetIndicLettersP10TranslatorE15dev_consonants2;var __ZZ16SelectTranslatorPKcE17stress_lengths_fr;var __ZZ16SelectTranslatorPKcE14stress_amps_fr;var __ZZ16SelectTranslatorPKcE14stress_amps_sk;var __ZZ16SelectTranslatorPKcE17stress_lengths_sk;var __ZZ16SelectTranslatorPKcE17stress_lengths_ta;var __ZZ16SelectTranslatorPKcE14stress_amps_ta;var __ZZ16SelectTranslatorPKcE17stress_lengths_af;var __ZZ16SelectTranslatorPKcE17stress_lengths_bn;var __ZZ16SelectTranslatorPKcE14stress_amps_bn;var __ZZ16SelectTranslatorPKcE17stress_lengths_cy;var __ZZ16SelectTranslatorPKcE14stress_amps_cy;var __ZZ16SelectTranslatorPKcE17stress_lengths_da;var __ZZ16SelectTranslatorPKcE17stress_lengths_de;var __ZZ16SelectTranslatorPKcE14stress_amps_de;var __ZZ16SelectTranslatorPKcE17stress_lengths_en;var __str630;var __ZZ16SelectTranslatorPKcE17stress_lengths_el;var __ZZ16SelectTranslatorPKcE14stress_amps_el;var __ZZ16SelectTranslatorPKcE9el_vowels;var __ZZ16SelectTranslatorPKcE10el_fvowels;var __ZZ16SelectTranslatorPKcE12el_voiceless;var __ZZ16SelectTranslatorPKcE13el_consonants;var __ZZ16SelectTranslatorPKcE18el_char_apostrophe;var __ZZ16SelectTranslatorPKcE17stress_lengths_eo;var __ZZ16SelectTranslatorPKcE14stress_amps_eo;var __ZZ16SelectTranslatorPKcE18eo_char_apostrophe;var __ZZ16SelectTranslatorPKcE17stress_lengths_es;var __ZZ16SelectTranslatorPKcE14stress_amps_es;var __ZZ16SelectTranslatorPKcE20ca_punct_within_word;var __ZZ16SelectTranslatorPKcE17stress_lengths_eu;var __ZZ16SelectTranslatorPKcE14stress_amps_eu;var __ZZ16SelectTranslatorPKcE14stress_amps_fi;var __ZZ16SelectTranslatorPKcE17stress_lengths_fi;var __ZZ16SelectTranslatorPKcE17stress_lengths_hi;var __ZZ16SelectTranslatorPKcE14stress_amps_hi;var __ZZ16SelectTranslatorPKcE14stress_amps_hr;var __ZZ16SelectTranslatorPKcE17stress_lengths_hr;var __ZZ16SelectTranslatorPKcE17stress_lengths_sr;var __ZL22replace_cyrillic_latin;var __ZZ16SelectTranslatorPKcE14stress_amps_hu;var __ZZ16SelectTranslatorPKcE17stress_lengths_hu;var __ZZ16SelectTranslatorPKcE17stress_lengths_hy;var __ZZ16SelectTranslatorPKcE9hy_vowels;var __ZZ16SelectTranslatorPKcE13hy_consonants;var __ZZ16SelectTranslatorPKcE17stress_lengths_id;var __ZZ16SelectTranslatorPKcE14stress_amps_id;var __ZZ16SelectTranslatorPKcE17stress_lengths_is;var __ZZ16SelectTranslatorPKcE16is_lettergroup_B;var __str1631;var __str2632;var __ZZ16SelectTranslatorPKcE17stress_lengths_it;var __ZZ16SelectTranslatorPKcE14stress_amps_it;var __ZZ16SelectTranslatorPKcE18stress_lengths_jbo;var __ZZ16SelectTranslatorPKcE21jbo_punct_within_word;var __ZZ16SelectTranslatorPKcE9ka_vowels;var __ZZ16SelectTranslatorPKcE13ka_consonants;var __ZZ16SelectTranslatorPKcE10ko_ivowels;var __ZZ16SelectTranslatorPKcE9ko_voiced;var __ZZ16SelectTranslatorPKcE14stress_amps_ku;var __ZZ16SelectTranslatorPKcE17stress_lengths_ku;var __ZZ16SelectTranslatorPKcE14stress_amps_lv;var __ZZ16SelectTranslatorPKcE17stress_lengths_lv;var __ZZ16SelectTranslatorPKcE15vowels_cyrillic;var __ZZ16SelectTranslatorPKcE14stress_amps_mk;var __ZZ16SelectTranslatorPKcE17stress_lengths_mk;var __ZZ16SelectTranslatorPKcE17stress_lengths_nl;var __str3633;var __ZZ16SelectTranslatorPKcE17stress_lengths_no;var __ZZ16SelectTranslatorPKcE14stress_amps_om;var __ZZ16SelectTranslatorPKcE17stress_lengths_om;var __ZZ16SelectTranslatorPKcE17stress_lengths_pl;var __ZZ16SelectTranslatorPKcE14stress_amps_pl;var __ZZ16SelectTranslatorPKcE17stress_lengths_pt;var __ZZ16SelectTranslatorPKcE14stress_amps_pt;var __str4634;var __ZZ16SelectTranslatorPKcE17stress_lengths_ro;var __ZZ16SelectTranslatorPKcE14stress_amps_ro;var __str5635;var __ZZ16SelectTranslatorPKcE17stress_lengths_sq;var __ZZ16SelectTranslatorPKcE14stress_amps_sq;var __ZZ16SelectTranslatorPKcE14stress_amps_sv;var __ZZ16SelectTranslatorPKcE17stress_lengths_sv;var __ZZ16SelectTranslatorPKcE17stress_lengths_sw;var __ZZ16SelectTranslatorPKcE14stress_amps_sw;var __ZZ16SelectTranslatorPKcE14stress_amps_tr;var __ZZ16SelectTranslatorPKcE17stress_lengths_tr;var __ZZ16SelectTranslatorPKcE17stress_lengths_vi;var __ZZ16SelectTranslatorPKcE14stress_amps_vi;var __ZZ16SelectTranslatorPKcE9vowels_vi;var __ZZ16SelectTranslatorPKcE17stress_lengths_zh;var __ZZ16SelectTranslatorPKcE14stress_amps_zh;var __ZZL18Translator_RussianP10TranslatorE14stress_amps_ru;var __ZZL18Translator_RussianP10TranslatorE17stress_lengths_ru;var __ZZL18Translator_RussianP10TranslatorE11ru_ivowels2;var __ZZL18SetCyrillicLettersP10TranslatorE9ru_vowels;var __ZZL18SetCyrillicLettersP10TranslatorE13ru_consonants;var __ZZL18SetCyrillicLettersP10TranslatorE7ru_soft;var __ZZL18SetCyrillicLettersP10TranslatorE7ru_hard;var __ZZL18SetCyrillicLettersP10TranslatorE10ru_nothard;var __ZZL18SetCyrillicLettersP10TranslatorE9ru_voiced;var __ZZL18SetCyrillicLettersP10TranslatorE10ru_ivowels;var __ZL8pairs_ru;var __ZZL13NewTranslatorvE12stress_amps2;var __ZZL13NewTranslatorvE15stress_lengths2;var __ZZL13NewTranslatorvE13empty_wstring;var __ZZL13NewTranslatorvE13punct_in_word;var __ZZL13NewTranslatorvE13default_tunes;var __str6636;var __str7637;var __str8638;var __str9639;var __str10640;var __str11641;var __str12642;var __str13643;var __str646;var __str1647;var __str2648;var _genders;var _tone_points;var _formant_rate;var _voice_selected;var __str3653;var __str4654;var __ZL11options_tab;var __str5655;var __str6656;var __str7657;var __str8658;var __str9659;var __str10660;var __str11661;var __str12662;var __str13663;var __str14664;var __str15665;var __str16666;var __str17667;var __str18668;var __str19669;var __str20670;var __str21671;var __str22672;var __str23673;var __str24674;var __str25675;var __str26676;var __str27677;var __str28678;var __str29679;var __str30680;var __str31681;var __str32682;var __str33683;var __str34684;var __str35685;var __str36686;var __str37687;var __str38688;var __str39689;var __str40690;var __str41691;var __str42692;var __str43693;var __ZL11keyword_tab;var __ZL15variants_either;var __ZL13variants_male;var __ZL15variants_female;var _variant_lists;var __ZL9voicedata;var _voice;var __str44696;var __ZZ10VoiceResetiE15default_heights;var __ZZ10VoiceResetiE14default_widths;var __ZZ10VoiceResetiE13breath_widths;var __ZL18formant_rate_22050;var __ZZ9LoadVoicePKciE16voice_identifier;var __ZZ9LoadVoicePKciE10voice_name;var __ZZ9LoadVoicePKciE15voice_languages;var __str45697;var __str46698;var __str47699;var __str48700;var __str49701;var __str50702;var __str51703;var __str52704;var __str53705;var __str54706;var __str55707;var __str56708;var __str57709;var __str58710;var __str59711;var __str60712;var __str61713;var __str62714;var __str63715;var __str64716;var __str65717;var __str66718;var __str67719;var __str68720;var __str69721;var __ZL13n_voices_list;var __ZL11voices_list;var __str70722;var __ZZ11SelectVoiceP12espeak_VOICEPiE14voice_variants;var __ZZ11SelectVoiceP12espeak_VOICEPiE8voice_id;var __ZZ11SelectVoiceP12espeak_VOICEPiE3buf;var __str71723;var __ZZ14SetVoiceByNamePKcE3buf;var __ZZ17espeak_ListVoicesE6voices;var __str72724;var __ZL15len_path_voices;var __str73725;var __str74726;var __str75727;var __ZZL23ExtractVoiceVariantNamePciE12variant_name;var __str76728;var __str77729;var __str78730;var __str79731;var __str80732;var __str81733;var __str82734;var _sin_tab;var _wvoice;var _f_log;var _option_waveout;var _option_log_frames;var _embedded_value;var _samplerate;var _samplerate_native;var __ZL5peaks;var _echo_head;var _echo_tail;var _echo_amp;var _echo_buf;var __ZL7rbreath;var _wdata;var __ZL13amplitude_env;var _out_ptr;var _out_start;var _out_end;var _outbuf_size;var _wcmdq;var _wcmdq_head;var _wcmdq_tail;var _embedded_default;var _current_source_index;var __ZL18sonicSpeedupStream;var _sonicSpeed;var _pitch_adjust_tab;var _pk_shape1;var __ZL16PHASE_INC_FACTOR;var __ZL11Flutter_inc;var __ZL11samplecount;var __ZL8nsamples;var __ZL9wavephase;var __ZL12wavemult_max;var __ZL15wavemult_offset;var __ZL8wavemult;var __ZL9pk_shape2;var __ZL8pk_shape;var __ZZ12GetAmplitudevE12amp_emphasis;var __ZL17general_amplitude;var __ZL11peak_height;var __ZL13peak_harmonic;var __ZL16option_harmonic1_b;var __ZL9harmspect;var __ZL8harm_inc;var __ZL10minus_pi_t;var __ZL8two_pi_t;var __ZZ7WavegenvE4maxh;var __ZZ7WavegenvE5maxh2;var __ZZ7WavegenvE3agc;var __ZZ7WavegenvE13h_switch_sign;var __ZZ7WavegenvE11cycle_count;var __ZZ7WavegenvE10amplitude2;var __ZL8end_wave_b;var __ZL7hswitch;var __ZL6hspect;var __ZL8phaseinc;var __ZL13cycle_samples;var __ZL9hf_factor;var __ZL6cbytes;var __ZL12glottal_flag;var __ZL14glottal_reduce;var __ZL6amp_ix;var __ZL15modulation_type;var __ZL14modulation_tab;var __ZL7voicing;var __ZL12embedded_max;var __ZZ15WavegenSetVoiceP7voice_tE2v2;var __ZL13consonant_amp;var __ZL11flutter_amp;var __ZZ8SetSynthiiP7frame_tS0_P7voice_tE19glottal_reduce_tab1;var __ZZ8SetSynthiiP7frame_tS0_P7voice_tE19glottal_reduce_tab2;var __ZL17samplecount_start;var __ZZ12WavegenFill2iE6resume;var __ZZ12WavegenFill2iE13echo_complete;var __ZL11echo_length;var __ZL7amp_inc;var __ZZL8PlayWaveiiPhiiE9n_samples;var __ZZL8PlayWaveiiPhiiE2ix;var __ZZL11PlaySilenceiiE9n_samples;var __ZZL17AdvanceParametersvE10Flutter_ix;var __ZL11Flutter_tab;var _pause_phonemes;var __ZZ15MakePhonemeListP10TranslatoriiE12types_double;var __ZL8kt_frame;var __ZL10kt_globals;var __ZL5peaks801;var __ZL12sample_count;var __ZL8nsamples802;var __ZL6klattp;var __ZL10klattp_inc;var __ZL7klattp1;var __ZL8end_wave803;var __ZZ14SetSynth_KlattiiP7frame_tS0_P7voice_tiE7prev_fr;var __ZL13scale_wav_tab;var __ZZ9KlattInitvE15natural_samples;var __ZZ9KlattInitvE10formant_hz;var __ZZ9KlattInitvE9bandwidth;var __ZZ9KlattInitvE12parallel_amp;var __ZZ9KlattInitvE11parallel_bw;var __ZZL7parwaveP13klatt_frame_tE5noise;var __ZZL7parwaveP13klatt_frame_tE5voice;var __ZZL7parwaveP13klatt_frame_tE5vlast;var __ZZL7parwaveP13klatt_frame_tE8glotlast;var __ZZL7parwaveP13klatt_frame_tE5sourc;var __ZZL21pitch_synch_par_resetP13klatt_frame_tE4skew;var __ZZL21pitch_synch_par_resetP13klatt_frame_tE2B0;var __ZZL7DBtoLINlE8amptable;var __ZZL14natural_sourcevE5vwave;var __ZZL16impulsive_sourcevE7doublet;var __ZZL16impulsive_sourcevE5vwave;var __ZZL9gen_noisedE5nlast;var __ZZL7flutterP13klatt_frame_tE10time_count;var __ZZL10frame_initP13klatt_frame_tE14amp_par_factor;var __str810;var __str1811;var _optarg;var _optind;var _opterr;var _optopt;var __ZL8optwhere;var __str831;var __str1832;var __str2833;var __str3834;var __str4835;var __str5836;var __str6837;var _llvm_dbg_declare;var ERRNO_CODES={E2BIG:7,EACCES:13,EADDRINUSE:98,EADDRNOTAVAIL:99,EAFNOSUPPORT:97,EAGAIN:11,EALREADY:114,EBADF:9,EBADMSG:74,EBUSY:16,ECANCELED:125,ECHILD:10,ECONNABORTED:103,ECONNREFUSED:111,ECONNRESET:104,EDEADLK:35,EDESTADDRREQ:89,EDOM:33,EDQUOT:122,EEXIST:17,EFAULT:14,EFBIG:27,EHOSTUNREACH:113,EIDRM:43,EILSEQ:84,EINPROGRESS:115,EINTR:4,EINVAL:22,EIO:5,EISCONN:106,EISDIR:21,ELOOP:40,EMFILE:24,EMLINK:31,EMSGSIZE:90,EMULTIHOP:72,ENAMETOOLONG:36,ENETDOWN:100,ENETRESET:102,ENETUNREACH:101,ENFILE:23,ENOBUFS:105,ENODATA:61,ENODEV:19,ENOENT:2,ENOEXEC:8,ENOLCK:37,ENOLINK:67,ENOMEM:12,ENOMSG:42,ENOPROTOOPT:92,ENOSPC:28,ENOSR:63,ENOSTR:60,ENOSYS:38,ENOTCONN:107,ENOTDIR:20,ENOTEMPTY:39,ENOTRECOVERABLE:131,ENOTSOCK:88,ENOTSUP:95,ENOTTY:25,ENXIO:6,EOVERFLOW:75,EOWNERDEAD:130,EPERM:1,EPIPE:32,EPROTO:71,EPROTONOSUPPORT:93,EPROTOTYPE:91,ERANGE:34,EROFS:30,ESPIPE:29,ESRCH:3,ESTALE:116,ETIME:62,ETIMEDOUT:110,ETXTBSY:26,EWOULDBLOCK:11,EXDEV:18};function ___setErrNo(value){if(!___setErrNo.ret)___setErrNo.ret=allocate([0],'i32',ALLOC_STATIC);HEAP32[((___setErrNo.ret)>>2)]=value;return value;}
var _stdin=0;var _stdout=0;var _stderr=0;var __impure_ptr=0;var FS={currentPath:"/",nextInode:2,streams:[null],ignorePermissions:true,absolutePath:function(relative,base){if(typeof relative!=='string')return null;if(base===undefined)base=FS.currentPath;if(relative&&relative[0]=='/')base='';var full=base+'/'+relative;var parts=full.split('/').reverse();var absolute=[''];while(parts.length){var part=parts.pop();if(part==''||part=='.'){}else if(part=='..'){if(absolute.length>1)absolute.pop();}else{absolute.push(part);}}
return absolute.length==1?'/':absolute.join('/');},analyzePath:function(path,dontResolveLastLink,linksVisited){var ret={isRoot:false,exists:false,error:0,name:null,path:null,object:null,parentExists:false,parentPath:null,parentObject:null};path=FS.absolutePath(path);if(path=='/'){ret.isRoot=true;ret.exists=ret.parentExists=true;ret.name='/';ret.path=ret.parentPath='/';ret.object=ret.parentObject=FS.root;}else if(path!==null){linksVisited=linksVisited||0;path=path.slice(1).split('/');var current=FS.root;var traversed=[''];while(path.length){if(path.length==1&&current.isFolder){ret.parentExists=true;ret.parentPath=traversed.length==1?'/':traversed.join('/');ret.parentObject=current;ret.name=path[0];}
var target=path.shift();if(!current.isFolder){ret.error=ERRNO_CODES.ENOTDIR;break;}else if(!current.read){ret.error=ERRNO_CODES.EACCES;break;}else if(!current.contents.hasOwnProperty(target)){ret.error=ERRNO_CODES.ENOENT;break;}
current=current.contents[target];if(current.link&&!(dontResolveLastLink&&path.length==0)){if(linksVisited>40){ret.error=ERRNO_CODES.ELOOP;break;}
var link=FS.absolutePath(current.link,traversed.join('/'));return FS.analyzePath([link].concat(path).join('/'),dontResolveLastLink,linksVisited+1);}
traversed.push(target);if(path.length==0){ret.exists=true;ret.path=traversed.join('/');ret.object=current;}}
return ret;}
return ret;},findObject:function(path,dontResolveLastLink){FS.ensureRoot();var ret=FS.analyzePath(path,dontResolveLastLink);if(ret.exists){return ret.object;}else{___setErrNo(ret.error);return null;}},createObject:function(parent,name,properties,canRead,canWrite){if(!parent)parent='/';if(typeof parent==='string')parent=FS.findObject(parent);if(!parent){___setErrNo(ERRNO_CODES.EACCES);throw new Error('Parent path must exist.');}
if(!parent.isFolder){___setErrNo(ERRNO_CODES.ENOTDIR);throw new Error('Parent must be a folder.');}
if(!parent.write&&!FS.ignorePermissions){___setErrNo(ERRNO_CODES.EACCES);throw new Error('Parent folder must be writeable.');}
if(!name||name=='.'||name=='..'){___setErrNo(ERRNO_CODES.ENOENT);throw new Error('Name must not be empty.');}
if(parent.contents.hasOwnProperty(name)){___setErrNo(ERRNO_CODES.EEXIST);throw new Error("Can't overwrite object.");}
parent.contents[name]={read:canRead===undefined?true:canRead,write:canWrite===undefined?false:canWrite,timestamp:Date.now(),inodeNumber:FS.nextInode++};for(var key in properties){if(properties.hasOwnProperty(key)){parent.contents[name][key]=properties[key];}}
return parent.contents[name];},createFolder:function(parent,name,canRead,canWrite){var properties={isFolder:true,isDevice:false,contents:{}};return FS.createObject(parent,name,properties,canRead,canWrite);},createPath:function(parent,path,canRead,canWrite){var current=FS.findObject(parent);if(current===null)throw new Error('Invalid parent.');path=path.split('/').reverse();while(path.length){var part=path.pop();if(!part)continue;if(!current.contents.hasOwnProperty(part)){FS.createFolder(current,part,canRead,canWrite);}
current=current.contents[part];}
return current;},createFile:function(parent,name,properties,canRead,canWrite){properties.isFolder=false;return FS.createObject(parent,name,properties,canRead,canWrite);},createDataFile:function(parent,name,data,canRead,canWrite){if(typeof data==='string'){var dataArray=[];for(var i=0;i<data.length;i++)dataArray.push(data.charCodeAt(i));data=dataArray;}
var properties={isDevice:false,contents:data};return FS.createFile(parent,name,properties,canRead,canWrite);},createLazyFile:function(parent,name,url,canRead,canWrite){var properties={isDevice:false,url:url};return FS.createFile(parent,name,properties,canRead,canWrite);},createLink:function(parent,name,target,canRead,canWrite){var properties={isDevice:false,link:target};return FS.createFile(parent,name,properties,canRead,canWrite);},createDevice:function(parent,name,input,output){if(!(input||output)){throw new Error('A device must have at least one callback defined.');}
var ops={isDevice:true,input:input,output:output};return FS.createFile(parent,name,ops,Boolean(input),Boolean(output));},forceLoadFile:function(obj){if(obj.isDevice||obj.isFolder||obj.link||obj.contents)return true;___setErrNo(ERRNO_CODES.EIO);return false;},ensureRoot:function(){if(FS.root)return;FS.root={read:true,write:false,isFolder:true,isDevice:false,timestamp:Date.now(),inodeNumber:1,contents:{}};},init:function(input,output,error){if(FS.init.initialized)return;FS.init.initialized=true;FS.ensureRoot();if(!input)input=function(){if(!input.cache||!input.cache.length){var result;if(typeof readline=='function'){result=readline();}
if(!result)result='';input.cache=intArrayFromString(result+'\n',true);input.cache=intArrayFromString('\n',true);}
return input.cache.shift();};if(!output)output=function(val){if(val===null||val==='\n'.charCodeAt(0)){output.printer(output.buffer.join(''));output.buffer=[];}else{output.buffer.push(String.fromCharCode(val));}};if(!output.printer)output.printer=vprint;if(!output.buffer)output.buffer=[];if(!error)error=output;FS.createFolder('/','tmp',true,true);var devFolder=FS.createFolder('/','dev',true,false);var stdin=FS.createDevice(devFolder,'stdin',input);var stdout=FS.createDevice(devFolder,'stdout',null,output);var stderr=FS.createDevice(devFolder,'stderr',null,error);FS.createDevice(devFolder,'tty',input,output);FS.streams[1]={path:'/dev/stdin',object:stdin,position:0,isRead:true,isWrite:false,isAppend:false,error:false,eof:false,ungotten:[]};FS.streams[2]={path:'/dev/stdout',object:stdout,position:0,isRead:false,isWrite:true,isAppend:false,error:false,eof:false,ungotten:[]};FS.streams[3]={path:'/dev/stderr',object:stderr,position:0,isRead:false,isWrite:true,isAppend:false,error:false,eof:false,ungotten:[]};_stdin=allocate([1],'void*',ALLOC_STATIC);_stdout=allocate([2],'void*',ALLOC_STATIC);_stderr=allocate([3],'void*',ALLOC_STATIC);FS.streams[_stdin]=FS.streams[1];FS.streams[_stdout]=FS.streams[2];FS.streams[_stderr]=FS.streams[3];__impure_ptr=allocate([allocate([0,0,0,0,_stdin,0,0,0,_stdout,0,0,0,_stderr,0,0,0],'void*',ALLOC_STATIC)],'void*',ALLOC_STATIC);FS.ignorePermissions=false;},quit:function(){try{if(FS.streams[2].object.output.buffer.length>0)FS.streams[2].object.output('\n'.charCodeAt(0));if(FS.streams[3].object.output.buffer.length>0)FS.streams[3].object.output('\n'.charCodeAt(0));}
catch(e){recoverFromFSError(e);}}};var ___stat_struct_layout={__size__:80,st_dev:0,st_ino:8,st_mode:12,st_nlink:16,st_uid:20,st_gid:24,st_rdev:28,st_size:36,st_atime:40,st_spare1:44,st_mtime:48,st_spare2:52,st_ctime:56,st_spare3:60,st_blksize:64,st_blocks:68,st_spare4:72};function _stat(path,buf,dontResolveLastLink){var obj=FS.findObject(Pointer_stringify(path),dontResolveLastLink);if(obj===null||!FS.forceLoadFile(obj))return-1;var offsets=___stat_struct_layout;HEAP32[((buf+offsets.st_nlink)>>2)]=1;HEAP32[((buf+offsets.st_uid)>>2)]=0;HEAP32[((buf+offsets.st_gid)>>2)]=0;HEAP32[((buf+offsets.st_blksize)>>2)]=4096;HEAP32[((buf+offsets.st_ino)>>2)]=obj.inodeNumber;var time=Math.floor(obj.timestamp/1000);if(offsets.st_atime===undefined){offsets.st_atime=offsets.st_atim.tv_sec;offsets.st_mtime=offsets.st_mtim.tv_sec;offsets.st_ctime=offsets.st_ctim.tv_sec;var nanosec=(obj.timestamp%1000)*1000;HEAP32[((buf+offsets.st_atim.tv_nsec)>>2)]=nanosec;HEAP32[((buf+offsets.st_mtim.tv_nsec)>>2)]=nanosec;HEAP32[((buf+offsets.st_ctim.tv_nsec)>>2)]=nanosec;}
HEAP32[((buf+offsets.st_atime)>>2)]=time;HEAP32[((buf+offsets.st_mtime)>>2)]=time;HEAP32[((buf+offsets.st_ctime)>>2)]=time;var mode=0;var size=0;var blocks=0;var dev=0;var rdev=0;if(obj.isDevice){dev=rdev=obj.inodeNumber;size=blocks=0;mode=0x2000;}else{dev=1;rdev=0;if(obj.isFolder){size=4096;blocks=1;mode=0x4000;}else{var data=obj.contents||obj.link;size=data.length;blocks=Math.ceil(data.length/4096);mode=obj.link===undefined?0x8000:0xA000;}}
HEAP32[((buf+offsets.st_dev)>>2)]=dev;HEAP32[((buf+offsets.st_rdev)>>2)]=rdev;HEAP32[((buf+offsets.st_size)>>2)]=size;HEAP32[((buf+offsets.st_blocks)>>2)]=blocks;if(obj.read)mode|=0x16D;if(obj.write)mode|=0x92;HEAP32[((buf+offsets.st_mode)>>2)]=mode;return 0;}
function _malloc(size){var ret=STATICTOP;STATICTOP+=size;STATICTOP=Math.ceil((STATICTOP)/4)*4;;return ret;}
function _pwrite(fildes,buf,nbyte,offset){var stream=FS.streams[fildes];if(!stream||stream.object.isDevice){___setErrNo(ERRNO_CODES.EBADF);return-1;}else if(!stream.isWrite){___setErrNo(ERRNO_CODES.EACCES);return-1;}else if(stream.object.isFolder){___setErrNo(ERRNO_CODES.EISDIR);return-1;}else if(nbyte<0||offset<0){___setErrNo(ERRNO_CODES.EINVAL);return-1;}else{var contents=stream.object.contents;while(contents.length<offset)contents.push(0);for(var i=0;i<nbyte;i++){contents[offset+i]=HEAP8[(buf+i)];}
stream.object.timestamp=Date.now();return i;}}function _write(fildes,buf,nbyte){var stream=FS.streams[fildes];if(!stream){___setErrNo(ERRNO_CODES.EBADF);return-1;}else if(!stream.isWrite){___setErrNo(ERRNO_CODES.EACCES);return-1;}else if(nbyte<0){___setErrNo(ERRNO_CODES.EINVAL);return-1;}else{if(stream.object.isDevice){if(stream.object.output){for(var i=0;i<nbyte;i++){try{stream.object.output(HEAP8[(buf+i)]);}catch(e){___setErrNo(ERRNO_CODES.EIO);return-1;}}
stream.object.timestamp=Date.now();return i;}else{___setErrNo(ERRNO_CODES.ENXIO);return-1;}}else{var bytesWritten=_pwrite(fildes,buf,nbyte,stream.position);if(bytesWritten!=-1)stream.position+=bytesWritten;return bytesWritten;}}}function _fwrite(ptr,size,nitems,stream){var bytesToWrite=nitems*size;if(bytesToWrite==0)return 0;var bytesWritten=_write(stream,ptr,bytesToWrite);if(bytesWritten==-1){if(FS.streams[stream])FS.streams[stream].error=true;return-1;}else{return Math.floor(bytesWritten/size);}}
function __formatString(format,varargs){var textIndex=format;var argIndex=0;var getNextArg=function(type){var ret;if(type==='float'||type==='double'){ret=HEAPF32[((varargs+argIndex)>>2)];}else{ret=HEAP32[((varargs+argIndex)>>2)];}
argIndex+=Runtime.getNativeFieldSize(type);return Number(ret);};var ret=[];var curr,next,currArg;while(1){var startTextIndex=textIndex;curr=HEAP8[(textIndex)];if(curr===0)break;next=HEAP8[(textIndex+1)];if(curr=='%'.charCodeAt(0)){var flagAlwaysSigned=false;var flagLeftAlign=false;var flagAlternative=false;var flagZeroPad=false;flagsLoop:while(1){switch(next){case'+'.charCodeAt(0):flagAlwaysSigned=true;break;case'-'.charCodeAt(0):flagLeftAlign=true;break;case'#'.charCodeAt(0):flagAlternative=true;break;case'0'.charCodeAt(0):if(flagZeroPad){break flagsLoop;}else{flagZeroPad=true;break;}
default:break flagsLoop;}
textIndex++;next=HEAP8[(textIndex+1)];}
var width=0;if(next=='*'.charCodeAt(0)){width=getNextArg('i32');textIndex++;next=HEAP8[(textIndex+1)];}else{while(next>='0'.charCodeAt(0)&&next<='9'.charCodeAt(0)){width=width*10+(next-'0'.charCodeAt(0));textIndex++;next=HEAP8[(textIndex+1)];}}
var precisionSet=false;if(next=='.'.charCodeAt(0)){var precision=0;precisionSet=true;textIndex++;next=HEAP8[(textIndex+1)];if(next=='*'.charCodeAt(0)){precision=getNextArg('i32');textIndex++;}else{while(1){var precisionChr=HEAP8[(textIndex+1)];if(precisionChr<'0'.charCodeAt(0)||precisionChr>'9'.charCodeAt(0))break;precision=precision*10+(precisionChr-'0'.charCodeAt(0));textIndex++;}}
next=HEAP8[(textIndex+1)];}else{var precision=6;}
var argSize;switch(String.fromCharCode(next)){case'h':var nextNext=HEAP8[(textIndex+2)];if(nextNext=='h'.charCodeAt(0)){textIndex++;argSize=1;}else{argSize=2;}
break;case'l':var nextNext=HEAP8[(textIndex+2)];if(nextNext=='l'.charCodeAt(0)){textIndex++;argSize=8;}else{argSize=4;}
break;case'L':case'q':case'j':argSize=8;break;case'z':case't':case'I':argSize=4;break;default:argSize=undefined;}
if(argSize!==undefined)textIndex++;next=HEAP8[(textIndex+1)];if(['d','i','u','o','x','X','p'].indexOf(String.fromCharCode(next))!=-1){var signed=next=='d'.charCodeAt(0)||next=='i'.charCodeAt(0);argSize=argSize||4;var currArg=getNextArg('i'+(argSize*8));if(argSize<=4){var limit=Math.pow(256,argSize)-1;currArg=(signed?reSign:unSign)(currArg&limit,argSize*8);}
var currAbsArg=Math.abs(currArg);var argText;var prefix='';if(next=='d'.charCodeAt(0)||next=='i'.charCodeAt(0)){argText=reSign(currArg,8*argSize,1).toString(10);}else if(next=='u'.charCodeAt(0)){argText=unSign(currArg,8*argSize,1).toString(10);currArg=Math.abs(currArg);}else if(next=='o'.charCodeAt(0)){argText=(flagAlternative?'0':'')+currAbsArg.toString(8);}else if(next=='x'.charCodeAt(0)||next=='X'.charCodeAt(0)){prefix=flagAlternative?'0x':'';if(currArg<0){currArg=-currArg;argText=(currAbsArg-1).toString(16);var buffer=[];for(var i=0;i<argText.length;i++){buffer.push((0xF-parseInt(argText[i],16)).toString(16));}
argText=buffer.join('');while(argText.length<argSize*2)argText='f'+argText;}else{argText=currAbsArg.toString(16);}
if(next=='X'.charCodeAt(0)){prefix=prefix.toUpperCase();argText=argText.toUpperCase();}}else if(next=='p'.charCodeAt(0)){if(currAbsArg===0){argText='(nil)';}else{prefix='0x';argText=currAbsArg.toString(16);}}
if(precisionSet){while(argText.length<precision){argText='0'+argText;}}
if(flagAlwaysSigned){if(currArg<0){prefix='-'+prefix;}else{prefix='+'+prefix;}}
while(prefix.length+argText.length<width){if(flagLeftAlign){argText+=' ';}else{if(flagZeroPad){argText='0'+argText;}else{prefix=' '+prefix;}}}
argText=prefix+argText;argText.split('').forEach(function(chr){ret.push(chr.charCodeAt(0));});}else if(['f','F','e','E','g','G'].indexOf(String.fromCharCode(next))!=-1){var currArg=getNextArg(argSize===4?'float':'double');var argText;if(isNaN(currArg)){argText='nan';flagZeroPad=false;}else if(!isFinite(currArg)){argText=(currArg<0?'-':'')+'inf';flagZeroPad=false;}else{var isGeneral=false;var effectivePrecision=Math.min(precision,20);if(next=='g'.charCodeAt(0)||next=='G'.charCodeAt(0)){isGeneral=true;precision=precision||1;var exponent=parseInt(currArg.toExponential(effectivePrecision).split('e')[1],10);if(precision>exponent&&exponent>=-4){next=((next=='g'.charCodeAt(0))?'f':'F').charCodeAt(0);precision-=exponent+1;}else{next=((next=='g'.charCodeAt(0))?'e':'E').charCodeAt(0);precision--;}
effectivePrecision=Math.min(precision,20);}
if(next=='e'.charCodeAt(0)||next=='E'.charCodeAt(0)){argText=currArg.toExponential(effectivePrecision);if(/[eE][-+]\d$/.test(argText)){argText=argText.slice(0,-1)+'0'+argText.slice(-1);}}else if(next=='f'.charCodeAt(0)||next=='F'.charCodeAt(0)){argText=currArg.toFixed(effectivePrecision);}
var parts=argText.split('e');if(isGeneral&&!flagAlternative){while(parts[0].length>1&&parts[0].indexOf('.')!=-1&&(parts[0].slice(-1)=='0'||parts[0].slice(-1)=='.')){parts[0]=parts[0].slice(0,-1);}}else{if(flagAlternative&&argText.indexOf('.')==-1)parts[0]+='.';while(precision>effectivePrecision++)parts[0]+='0';}
argText=parts[0]+(parts.length>1?'e'+parts[1]:'');if(next=='E'.charCodeAt(0))argText=argText.toUpperCase();if(flagAlwaysSigned&&currArg>=0){argText='+'+argText;}}
while(argText.length<width){if(flagLeftAlign){argText+=' ';}else{if(flagZeroPad&&(argText[0]=='-'||argText[0]=='+')){argText=argText[0]+'0'+argText.slice(1);}else{argText=(flagZeroPad?'0':' ')+argText;}}}
if(next<'a'.charCodeAt(0))argText=argText.toUpperCase();argText.split('').forEach(function(chr){ret.push(chr.charCodeAt(0));});}else if(next=='s'.charCodeAt(0)){var arg=getNextArg('i8*');var copiedString;if(arg){copiedString=String_copy(arg);if(precisionSet&&copiedString.length>precision){copiedString=copiedString.slice(0,precision);}}else{copiedString=intArrayFromString('(null)',true);}
if(!flagLeftAlign){while(copiedString.length<width--){ret.push(' '.charCodeAt(0));}}
ret=ret.concat(copiedString);if(flagLeftAlign){while(copiedString.length<width--){ret.push(' '.charCodeAt(0));}}}else if(next=='c'.charCodeAt(0)){if(flagLeftAlign)ret.push(getNextArg('i8'));while(--width>0){ret.push(' '.charCodeAt(0));}
if(!flagLeftAlign)ret.push(getNextArg('i8'));}else if(next=='n'.charCodeAt(0)){var ptr=getNextArg('i32*');HEAP32[((ptr)>>2)]=ret.length;}else if(next=='%'.charCodeAt(0)){ret.push(curr);}else{for(var i=startTextIndex;i<textIndex+2;i++){ret.push(HEAP8[(i)]);}}
textIndex+=2;}else{ret.push(curr);textIndex+=1;}}
return ret;}function _fprintf(stream,format,varargs){var result=__formatString(format,varargs);var stack=Runtime.stackSave();var ret=_fwrite(allocate(result,'i8',ALLOC_STACK),1,result.length,stream);Runtime.stackRestore(stack);return ret;}
function _free(){}
function _strlen(ptr){return String_len(ptr);}
function _strcpy(pdest,psrc){var i=0;do{var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=psrc+i;$dest$=pdest+i;$stop$=$src$+1;if(($dest$%4)==($src$%4)&&1>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
i++;}while(HEAP8[(psrc+i-1)]!=0);return pdest;}
function _snprintf(s,n,format,varargs){var result=__formatString(format,varargs);var limit=(n===undefined)?result.length:Math.min(result.length,n-1);for(var i=0;i<limit;i++){HEAP8[(s+i)]=result[i];;}
HEAP8[(s+i)]=0;;return result.length;}function _sprintf(s,format,varargs){return _snprintf(s,undefined,format,varargs);}
function _fputc(c,stream){var chr=unSign(c&0xFF);HEAP8[(_fputc.ret)]=chr;var ret=_write(stream,_fputc.ret,1);if(ret==-1){if(stream in FS.streams)FS.streams[stream].error=true;return-1;}else{return chr;}}
function __scanString(format,get,unget,varargs){format=Pointer_stringify(format);var formatIndex=0;var argsi=0;var fields=0;var argIndex=0;for(var formatIndex=0;formatIndex<format.length;formatIndex++){if(next<=0)return fields;var next=get();if(next<=0)return fields;if(format[formatIndex]==='%'){formatIndex++;var maxSpecifierStart=formatIndex;while(format[formatIndex].charCodeAt(0)>='0'.charCodeAt(0)&&format[formatIndex].charCodeAt(0)<='9'.charCodeAt(0)){formatIndex++;}
var max_;if(formatIndex!=maxSpecifierStart){max_=parseInt(format.slice(maxSpecifierStart,formatIndex),10);}
var type=format[formatIndex];formatIndex++;var curr=0;var buffer=[];while((curr<max_||isNaN(max_))&&next>0){if((type==='d'&&next>='0'.charCodeAt(0)&&next<='9'.charCodeAt(0))||(type==='x'&&(next>='0'.charCodeAt(0)&&next<='9'.charCodeAt(0)||next>='a'.charCodeAt(0)&&next<='f'.charCodeAt(0)||next>='A'.charCodeAt(0)&&next<='F'.charCodeAt(0)))||(type==='s')&&(formatIndex>=format.length||next!==format[formatIndex].charCodeAt(0))){buffer.push(String.fromCharCode(next));next=get();curr++;}else{break;}}
if(buffer.length===0)return 0;var text=buffer.join('');var argPtr=HEAP32[((varargs+argIndex)>>2)];argIndex+=Runtime.getNativeFieldSize('void*');switch(type){case'd':HEAP32[((argPtr)>>2)]=parseInt(text,10);break;case'x':HEAP32[((argPtr)>>2)]=parseInt(text,16);break;case's':var array=intArrayFromString(text);for(var j=0;j<array.length;j++){HEAP8[(argPtr+j)]=array[j];}
break;}
fields++;}else{if(format[formatIndex].charCodeAt(0)!==next){unget(next);return fields;}}}
return fields;}function _sscanf(s,format,varargs){var index=0;var get=function(){return HEAP8[(s+index++)];};var unget=function(){index--;};return __scanString(format,get,unget,varargs);}
function _printf(format,varargs){var stdout=HEAP32[((_stdout)>>2)];return _fprintf(stdout,format,varargs);}
function __exit(status){__shutdownRuntime__();ABORT=true;throw'exit('+status+') called, at '+new Error().stack;}function _exit(status){__exit(status);}
function _isspace(chr){return chr in{32:0,9:0,10:0,11:0,12:0,13:0};}
function _isdigit(chr){return chr>='0'.charCodeAt(0)&&chr<='9'.charCodeAt(0);}function _atoi(s){var c;while((c=HEAP8[(s)])&&_isspace(c))s++;if(!c||!_isdigit(c))return 0;var e=s;while((c=HEAP8[(e)])&&_isdigit(c))e++;return Math.floor(Number(Pointer_stringify(s).substr(0,e-s)));}
var ___dirent_struct_layout={__size__:1040,d_ino:0,d_name:4,d_off:1028,d_reclen:1032,d_type:1036};function _open(path,oflag,varargs){var mode=HEAP32[((varargs)>>2)];var accessMode=oflag&3;var isWrite=accessMode!=0;var isRead=accessMode!=1;var isCreate=Boolean(oflag&512);var isExistCheck=Boolean(oflag&2048);var isTruncate=Boolean(oflag&1024);var isAppend=Boolean(oflag&8);var origPath=path;path=FS.analyzePath(Pointer_stringify(path));if(!path.parentExists){___setErrNo(path.error);return-1;}
var target=path.object||null;var finalPath;if(target){if(isCreate&&isExistCheck){___setErrNo(ERRNO_CODES.EEXIST);return-1;}
if((isWrite||isCreate||isTruncate)&&target.isFolder){___setErrNo(ERRNO_CODES.EISDIR);return-1;}
if(isRead&&!target.read||isWrite&&!target.write){___setErrNo(ERRNO_CODES.EACCES);return-1;}
if(isTruncate&&!target.isDevice){target.contents=[];}else{if(!FS.forceLoadFile(target)){___setErrNo(ERRNO_CODES.EIO);return-1;}}
finalPath=path.path;}else{if(!isCreate){___setErrNo(ERRNO_CODES.ENOENT);return-1;}
if(!path.parentObject.write){___setErrNo(ERRNO_CODES.EACCES);return-1;}
target=FS.createDataFile(path.parentObject,path.name,[],mode&0x100,mode&0x80);finalPath=path.parentPath+'/'+path.name;}
var id=FS.streams.length;if(target.isFolder){var entryBuffer=0;if(___dirent_struct_layout){entryBuffer=_malloc(___dirent_struct_layout.__size__);}
var contents=[];for(var key in target.contents)contents.push(key);FS.streams[id]={path:finalPath,object:target,position:-2,isRead:true,isWrite:false,isAppend:false,error:false,eof:false,ungotten:[],contents:contents,currentEntry:entryBuffer};}else{FS.streams[id]={path:finalPath,object:target,position:0,isRead:isRead,isWrite:isWrite,isAppend:isAppend,error:false,eof:false,ungotten:[]};}
return id;}function _fopen(filename,mode){var flags;mode=Pointer_stringify(mode);if(mode[0]=='r'){if(mode.indexOf('+')!=-1){flags=2;}else{flags=0;}}else if(mode[0]=='w'){if(mode.indexOf('+')!=-1){flags=2;}else{flags=1;}
flags|=512;flags|=1024;}else if(mode[0]=='a'){if(mode.indexOf('+')!=-1){flags=2;}else{flags=1;}
flags|=512;flags|=8;}else{___setErrNo(ERRNO_CODES.EINVAL);return 0;}
var ret=_open(filename,flags,allocate([0x1FF,0,0,0],'i32',ALLOC_STACK));return(ret==-1)?0:ret;}
function _memset(ptr,value,num){var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=ptr;$stop$=$dest$+num;$value4$=value;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=value;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=value;}}var _llvm_memset_p0i8_i32=_memset;function _strrchr(ptr,chr){var ptr2=ptr+_strlen(ptr);do{if(HEAP8[(ptr2)]==chr)return ptr2;ptr2--;}while(ptr2>=ptr);return 0;}
function _close(fildes){if(FS.streams[fildes]){if(FS.streams[fildes].currentEntry){_free(FS.streams[fildes].currentEntry);}
delete FS.streams[fildes];return 0;}else{___setErrNo(ERRNO_CODES.EBADF);return-1;}}
function _fsync(fildes){if(FS.streams[fildes]){return 0;}else{___setErrNo(ERRNO_CODES.EBADF);return-1;}}function _fclose(stream){_fsync(stream);return _close(stream);}
function _fflush(stream){var flush=function(filedes){if(filedes in FS.streams&&FS.streams[filedes].object.output){FS.streams[filedes].object.output(null);}};try{if(stream===0){for(var i in FS.streams)flush(i);}else{flush(stream);}
return 0;}catch(e){___setErrNo(ERRNO_CODES.EIO);return-1;}}
function _ftell(stream){if(stream in FS.streams){stream=FS.streams[stream];if(stream.object.isDevice){___setErrNo(ERRNO_CODES.ESPIPE);return-1;}else{return stream.position;}}else{___setErrNo(ERRNO_CODES.EBADF);return-1;}}
function _lseek(fildes,offset,whence){if(FS.streams[fildes]&&!FS.streams[fildes].isDevice){var stream=FS.streams[fildes];var position=offset;if(whence===1){position+=stream.position;}else if(whence===2){position+=stream.object.contents.length;}
if(position<0){___setErrNo(ERRNO_CODES.EINVAL);return-1;}else{stream.ungotten=[];stream.position=position;return position;}}else{___setErrNo(ERRNO_CODES.EBADF);return-1;}}function _fseek(stream,offset,whence){var ret=_lseek(stream,offset,whence);if(ret==-1){return-1;}else{FS.streams[stream].eof=false;return 0;}}
function _strncmp(px,py,n){var i=0;while(i<n){var x=HEAP8[(px+i)];var y=HEAP8[(py+i)];if(x==y&&x==0)return 0;if(x==0)return-1;if(y==0)return 1;if(x==y){i++;continue;}else{return x>y?1:-1;}}
return 0;}function _strcmp(px,py){return _strncmp(px,py,TOTAL_MEMORY);}
function _setlocale(category,locale){if(!_setlocale.ret)_setlocale.ret=allocate([0],'i8',ALLOC_NORMAL);return _setlocale.ret;}
var _environ=null;var ___environ=null;function ___buildEnvironment(env){var MAX_ENV_VALUES=64;var TOTAL_ENV_SIZE=1024;var poolPtr;var envPtr;if(_environ===null){ENV.USER='root';ENV.PATH='/';ENV.PWD='/';ENV.HOME='/';ENV.LANG='en_US.UTF-8';ENV._='./this.program';poolPtr=allocate(TOTAL_ENV_SIZE,'i8',ALLOC_STATIC);envPtr=allocate(MAX_ENV_VALUES*4,'i8*',ALLOC_STATIC);HEAP32[((envPtr)>>2)]=poolPtr;_environ=allocate([envPtr],'i8**',ALLOC_STATIC);___environ=_environ;}else{envPtr=HEAP32[((_environ)>>2)];poolPtr=HEAP32[((envPtr)>>2)];}
var strings=[];var totalSize=0;for(var key in env){if(typeof env[key]==='string'){var line=key+'='+env[key];strings.push(line);totalSize+=line.length;}}
if(totalSize>TOTAL_ENV_SIZE){throw new Error('Environment size exceeded TOTAL_ENV_SIZE!');}
var ptrSize=4;for(var i=0;i<strings.length;i++){var line=strings[i];for(var j=0;j<line.length;j++){HEAP8[(poolPtr+j)]=line.charCodeAt(j);}
HEAP8[(poolPtr+j)]=0;HEAP32[((envPtr+i*ptrSize)>>2)]=poolPtr;poolPtr+=line.length+1;}
HEAP32[((envPtr+strings.length*ptrSize)>>2)]=0;}var ENV={};function _getenv(name){if(name===0)return 0;name=Pointer_stringify(name);if(!ENV.hasOwnProperty(name))return 0;if(_getenv.ret)_free(_getenv.ret);_getenv.ret=allocate(intArrayFromString(ENV[name]),'i8',ALLOC_NORMAL);return _getenv.ret;}
function _access(path,amode){path=Pointer_stringify(path);var target=FS.findObject(path);if(target===null)return-1;if((amode&2&&!target.write)||((amode&1||amode&4)&&!target.read)){___setErrNo(ERRNO_CODES.EACCES);return-1;}else{return 0;}}
function _strcat(pdest,psrc){var len=_strlen(pdest);var i=0;do{var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=psrc+i;$dest$=pdest+len+i;$stop$=$src$+1;if(($dest$%4)==($src$%4)&&1>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
i++;}while(HEAP8[(psrc+i-1)]!=0);return pdest;}
function _pread(fildes,buf,nbyte,offset){var stream=FS.streams[fildes];if(!stream||stream.object.isDevice){___setErrNo(ERRNO_CODES.EBADF);return-1;}else if(!stream.isRead){___setErrNo(ERRNO_CODES.EACCES);return-1;}else if(stream.object.isFolder){___setErrNo(ERRNO_CODES.EISDIR);return-1;}else if(nbyte<0||offset<0){___setErrNo(ERRNO_CODES.EINVAL);return-1;}else{var bytesRead=0;while(stream.ungotten.length&&nbyte>0){HEAP8[(buf++)]=stream.ungotten.pop();nbyte--;bytesRead++;}
var contents=stream.object.contents;var size=Math.min(contents.length-offset,nbyte);for(var i=0;i<size;i++){HEAP8[(buf+i)]=contents[offset+i];bytesRead++;}
return bytesRead;}}function _read(fildes,buf,nbyte){var stream=FS.streams[fildes];if(!stream){___setErrNo(ERRNO_CODES.EBADF);return-1;}else if(!stream.isRead){___setErrNo(ERRNO_CODES.EACCES);return-1;}else if(nbyte<0){___setErrNo(ERRNO_CODES.EINVAL);return-1;}else{var bytesRead;if(stream.object.isDevice){if(stream.object.input){bytesRead=0;while(stream.ungotten.length&&nbyte>0){HEAP8[(buf++)]=stream.ungotten.pop();nbyte--;bytesRead++;}
for(var i=0;i<nbyte;i++){try{var result=stream.object.input();}catch(e){___setErrNo(ERRNO_CODES.EIO);return-1;}
if(result===null||result===undefined)break;bytesRead++;HEAP8[(buf+i)]=result;}
return bytesRead;}else{___setErrNo(ERRNO_CODES.ENXIO);return-1;}}else{var ungotSize=stream.ungotten.length;bytesRead=_pread(fildes,buf,nbyte,stream.position);if(bytesRead!=-1){stream.position+=(stream.ungotten.length-ungotSize)+bytesRead;}
return bytesRead;}}}function _fgetc(stream){if(!(stream in FS.streams))return-1;var streamObj=FS.streams[stream];if(streamObj.eof||streamObj.error)return-1;var ret=_read(stream,_fgetc.ret,1);if(ret==0){streamObj.eof=true;return-1;}else if(ret==-1){streamObj.error=true;return-1;}else{return HEAP8[(_fgetc.ret)];}}function _fgets(s,n,stream){if(!(stream in FS.streams))return 0;var streamObj=FS.streams[stream];if(streamObj.error||streamObj.eof)return 0;var byte_;for(var i=0;i<n-1&&byte_!='\n'.charCodeAt(0);i++){byte_=_fgetc(stream);if(byte_==-1){if(streamObj.error)return 0;else if(streamObj.eof)break;}
HEAP8[(s+i)]=byte_;}
HEAP8[(s+i)]=0;return s;}
function _strstr(ptr1,ptr2){var str1=Pointer_stringify(ptr1);var str2=Pointer_stringify(ptr2);var ret=str1.search(str2);return ret>=0?ptr1+ret:0;}
function _memcmp(p1,p2,num){for(var i=0;i<num;i++){var v1=HEAP8[(p1+i)];var v2=HEAP8[(p2+i)];if(v1!=v2)return v1>v2?1:-1;}
return 0;}
function _memcpy(dest,src,num,idunno){var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=src;$dest$=dest;$stop$=$src$+num;if(($dest$%4)==($src$%4)&&num>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};}function _qsort(base,num,size,comparator){if(num==0||size==0)return;comparator=FUNCTION_TABLE[comparator];var keys=[];for(var i=0;i<num;i++)keys.push(i);keys.sort(function(a,b){return comparator(base+a*size,base+b*size);});var temp=_malloc(num*size);_memcpy(temp,base,num*size);for(var i=0;i<num;i++){if(keys[i]==i)continue;_memcpy(base+i*size,temp+keys[i]*size,size);}
_free(temp);}
function _unlink(path){path=FS.analyzePath(Pointer_stringify(path));if(!path.parentExists||!path.exists){___setErrNo(path.error);return-1;}else if(path.object.isFolder){___setErrNo(ERRNO_CODES.EISDIR);return-1;}else if(!path.object.write){___setErrNo(ERRNO_CODES.EACCES);return-1;}else{delete path.parentObject.contents[path.name];return 0;}}
function _rmdir(path){path=FS.analyzePath(Pointer_stringify(path));if(!path.parentExists||!path.exists){___setErrNo(path.error);return-1;}else if(!path.object.write||path.isRoot){___setErrNo(ERRNO_CODES.EACCES);return-1;}else if(!path.object.isFolder){___setErrNo(ERRNO_CODES.ENOTDIR);return-1;}else{for(var i in path.object.contents){___setErrNo(ERRNO_CODES.ENOTEMPTY);return-1;}
if(path.path==FS.currentPath){___setErrNo(ERRNO_CODES.EBUSY);return-1;}else{delete path.parentObject.contents[path.name];return 0;}}}function _remove(path){var ret=_unlink(path);if(ret==-1)ret=_rmdir(path);return ret;}
var _llvm_memcpy_p0i8_p0i8_i32=_memcpy;function _isalnum(chr){return(chr>=48&&chr<=57)||(chr>=97&&chr<=122)||(chr>=65&&chr<=90)||(chr>=0xC0&&chr<=0xD6)||(chr>=0xDF&&chr<=0xF6)||(chr>=0xD8&&chr<=0xDE)||(chr>=0xF8&&chr<=0xFF);}
function _strchr(ptr,chr){ptr--;do{ptr++;var val=HEAP8[(ptr)];if(val==chr)return ptr;}while(val);return 0;}
function _strncpy(pdest,psrc,num){var padding=false,curr;for(var i=0;i<num;i++){curr=padding?0:HEAP8[(psrc+i)];HEAP8[(pdest+i)]=curr;padding=padding||HEAP8[(psrc+i)]==0;}
return pdest;}
function _fread(ptr,size,nitems,stream){var bytesToRead=nitems*size;if(bytesToRead==0)return 0;var bytesRead=_read(stream,ptr,bytesToRead);var streamObj=FS.streams[stream];if(bytesRead==-1){if(streamObj)streamObj.error=true;return-1;}else{if(bytesRead<bytesToRead)streamObj.eof=true;return Math.floor(bytesRead/size);}}
function _tolower(chr){if((chr>=65&&chr<90)||(chr>=0xC0&&chr<=0xD6)||(chr>=0xD8&&chr<=0xDE))return chr-65+97;return chr;}
function _isalpha(chr){return(chr>=97&&chr<=122)||(chr>=65&&chr<=90)||(chr>=0xC0&&chr<=0xD6)||(chr>=0xDF&&chr<=0xF6)||(chr>=0xD8&&chr<=0xDE)||(chr>=0xF8&&chr<=0xFF);}
function _isupper(chr){return(chr>=65&&chr<=90)||(chr>=0xC0&&chr<=0xD6)||(chr>=0xD8&&chr<=0xDE);}
function _islower(chr){return(chr>=97&&chr<=122)||(chr>=0xDF&&chr<=0xF6)||(chr>=0xF8&&chr<=0xFF);}
function _ispunct(chr){return(chr>=33&&chr<=47)||(chr>=58&&chr<=64)||(chr>=91&&chr<=96)||(chr>=123&&chr<=126);}
var _atof;function _realloc(ptr,size){if(!size){if(ptr)_free(ptr);return 0;}
var ret=_malloc(size);if(ptr){_memcpy(ret,ptr,size);_free(ptr);}
return ret;}
var _mkstemp;function _system(command){___setErrNo(ERRNO_CODES.EAGAIN);return-1;}
function _ungetc(c,stream){if(stream in FS.streams){c=unSign(c&0xFF);FS.streams[stream].ungotten.push(c);return c;}else{return-1;}}
function _strdup(ptr){var len=String_len(ptr);var newStr=_malloc(len+1);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=ptr;$dest$=newStr;$stop$=$src$+len;if(($dest$%4)==($src$%4)&&len>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};HEAP8[(newStr+len)]=0;;return newStr;}
function _kill(pid,sig){___setErrNo(ERRNO_CODES.EPERM);return-1;}
function ___errno_location(){return ___setErrNo.ret;}
var ___errno=___errno_location;var ERRNO_MESSAGES={1:"Operation not permitted",2:"No such file or directory",3:"No such process",4:"Interrupted system call",5:"Input/output error",6:"No such device or address",8:"Exec format error",9:"Bad file descriptor",10:"No child processes",11:"Resource temporarily unavailable",12:"Cannot allocate memory",13:"Permission denied",14:"Bad address",16:"Device or resource busy",17:"File exists",18:"Invalid cross-device link",19:"No such device",20:"Not a directory",21:"Is a directory",22:"Invalid argument",23:"Too many open files in system",24:"Too many open files",25:"Inappropriate ioctl for device",26:"Text file busy",27:"File too large",28:"No space left on device",29:"Illegal seek",30:"Read-only file system",31:"Too many links",32:"Broken pipe",33:"Numerical argument out of domain",34:"Numerical result out of range",35:"Resource deadlock avoided",36:"File name too long",37:"No locks available",38:"Function not implemented",39:"Directory not empty",40:"Too many levels of symbolic links",42:"No message of desired type",43:"Identifier removed",60:"Device not a stream",61:"No data available",62:"Timer expired",63:"Out of streams resources",67:"Link has been severed",71:"Protocol error",72:"Multihop attempted",74:"Bad message",75:"Value too large for defined data type",84:"Invalid or incomplete multibyte or wide character",88:"Socket operation on non-socket",89:"Destination address required",90:"Message too long",91:"Protocol wrong type for socket",92:"Protocol not available",93:"Protocol not supported",95:"Operation not supported",97:"Address family not supported by protocol",98:"Address already in use",99:"Cannot assign requested address",100:"Network is down",101:"Network is unreachable",102:"Network dropped connection on reset",103:"Software caused connection abort",104:"Connection reset by peer",105:"No buffer space available",106:"Transport endpoint is already connected",107:"Transport endpoint is not connected",110:"Connection timed out",111:"Connection refused",113:"No route to host",114:"Operation already in progress",115:"Operation now in progress",116:"Stale NFS file handle",122:"Disk quota exceeded",125:"Operation canceled",130:"Owner died",131:"State not recoverable"};function _strerror_r(errnum,strerrbuf,buflen){if(errnum in ERRNO_MESSAGES){if(ERRNO_MESSAGES[errnum].length>buflen-1){return ___setErrNo(ERRNO_CODES.ERANGE);}else{var msg=ERRNO_MESSAGES[errnum];for(var i=0;i<msg.length;i++){HEAP8[(strerrbuf+i)]=msg.charCodeAt(i);}
HEAP8[(strerrbuf+i)]=0;return 0;}}else{return ___setErrNo(ERRNO_CODES.EINVAL);}}function _strerror(errnum){if(!_strerror.buffer)_strerror.buffer=_malloc(256);_strerror_r(errnum,_strerror.buffer,256);return _strerror.buffer;}
function _memmove(dest,src,num,idunno){if(num===0)return;var tmp=_malloc(num);_memcpy(tmp,src,num);_memcpy(dest,tmp,num);_free(tmp);}
var _llvm_memmove_p0i8_p0i8_i32=_memmove;var _llvm_va_start;var _vfprintf=_fprintf;function _llvm_va_end(){}
function _wait(stat_loc){___setErrNo(ERRNO_CODES.ECHILD);return-1;}
var _waitpid=_wait;var _vsnprintf=_snprintf;var ___pollfd_struct_layout=null;function _poll(fds,nfds,timeout){var offsets=___pollfd_struct_layout;var nonzero=0;for(var i=0;i<nfds;i++){var pollfd=fds+___pollfd_struct_layout.__size__*i;var fd=HEAP32[((pollfd+offsets.fd)>>2)];var events=HEAP16[((pollfd+offsets.events)>>1)];var revents=0;if(fd in FS.streams){var stream=FS.streams[fd];if(events&1)revents|=1;if(events&2)revents|=2;}else{if(events&4)revents|=4;}
if(revents)nonzero++;HEAP16[((pollfd+offsets.revents)>>1)]=revents;}
return nonzero;}
function _memchr(ptr,chr,num){chr=unSign(chr);for(var i=0;i<num;i++){if(HEAP8[(ptr)]==chr)return ptr;ptr++;}
return 0;}
function _fork(){___setErrNo(ERRNO_CODES.EAGAIN);return-1;}
var ___flock_struct_layout=null;function _fcntl(fildes,cmd,varargs){if(!(fildes in FS.streams)){___setErrNo(ERRNO_CODES.EBADF);return-1;}
var stream=FS.streams[fildes];switch(cmd){case 0:var arg=HEAP32[((varargs)>>2)];if(arg<0){___setErrNo(ERRNO_CODES.EINVAL);return-1;}
var newStream={};for(var member in stream){newStream[member]=stream[member];}
if(arg in FS.streams)arg=FS.streams.length;FS.streams[arg]=newStream;return arg;case 1:case 2:return 0;case 3:var flags=0;if(stream.isRead&&stream.isWrite)flags=2;else if(!stream.isRead&&stream.isWrite)flags=1;else if(stream.isRead&&!stream.isWrite)flags=0;if(stream.isAppend)flags|=8;return flags;case 4:var arg=HEAP32[((varargs)>>2)];stream.isAppend=Boolean(arg|8);return 0;case 7:case 20:var arg=HEAP32[((varargs)>>2)];var offset=___flock_struct_layout.l_type;HEAP16[((arg+offset)>>1)]=3;return 0;case 8:case 9:case 21:case 22:return 0;case 6:case 5:___setErrNo(ERRNO_CODES.EINVAL);return-1;default:___setErrNo(ERRNO_CODES.EINVAL);return-1;}
return-1;}
function _dup2(fildes,fildes2){if(fildes2<0){___setErrNo(ERRNO_CODES.EBADF);return-1;}else if(fildes===fildes2&&FS.streams[fildes]){return fildes;}else{_close(fildes2);return _fcntl(fildes,0,allocate([fildes2,0,0,0],'i32',ALLOC_STACK));}}
function _signal(sig,func){return 0;}
function _execl(){___setErrNo(ERRNO_CODES.ENOEXEC);return-1;}
var _execlp=_execl;function _pipe(fildes){___setErrNo(ERRNO_CODES.ENOSYS);return-1;}
function _opendir(dirname){var path=FS.absolutePath(Pointer_stringify(dirname));if(path===null){___setErrNo(ERRNO_CODES.ENOENT);return 0;}
var target=FS.findObject(path);if(target===null)return 0;if(!target.isFolder){___setErrNo(ERRNO_CODES.ENOTDIR);return 0;}else if(!target.read){___setErrNo(ERRNO_CODES.EACCES);return 0;}
var id=FS.streams.length;var contents=[];for(var key in target.contents)contents.push(key);FS.streams[id]={path:path,object:target,position:-2,isRead:true,isWrite:false,isAppend:false,error:false,eof:false,ungotten:[],contents:contents,currentEntry:_malloc(___dirent_struct_layout.__size__)};return id;}
function _readdir_r(dirp,entry,result){if(!FS.streams[dirp]||!FS.streams[dirp].object.isFolder){return ___setErrNo(ERRNO_CODES.EBADF);}
var stream=FS.streams[dirp];var loc=stream.position;var entries=0;for(var key in stream.contents)entries++;if(loc<-2||loc>=entries){HEAP32[((result)>>2)]=0;}else{var name,inode;if(loc===-2){name='.';inode=1;}else if(loc===-1){name='..';inode=1;}else{name=stream.contents[loc];inode=stream.object.contents[name].inodeNumber;}
stream.position++;var offsets=___dirent_struct_layout;HEAP32[((entry+offsets.d_ino)>>2)]=inode;HEAP32[((entry+offsets.d_off)>>2)]=stream.position;HEAP32[((entry+offsets.d_reclen)>>2)]=name.length+1;for(var i=0;i<name.length;i++){HEAP8[(entry+offsets.d_name+i)]=name.charCodeAt(i);}
HEAP8[(entry+offsets.d_name+i)]=0;var type=stream.object.isDevice?2:stream.object.isFolder?4:stream.object.link!==undefined?10:8;HEAP8[(entry+offsets.d_type)]=type;HEAP32[((result)>>2)]=entry;}
return 0;}
function _readdir(dirp){if(!FS.streams[dirp]||!FS.streams[dirp].object.isFolder){___setErrNo(ERRNO_CODES.EBADF);return 0;}else{if(!_readdir.result)_readdir.result=_malloc(4);_readdir_r(dirp,FS.streams[dirp].currentEntry,_readdir.result);if(HEAP32[((_readdir.result)>>2)]===0){return 0;}else{return FS.streams[dirp].currentEntry;}}}
function _closedir(dirp){if(!FS.streams[dirp]||!FS.streams[dirp].object.isFolder){return ___setErrNo(ERRNO_CODES.EBADF);}else{_free(FS.streams[dirp].currentEntry);delete FS.streams[dirp];return 0;}}
function _calloc(n,s){var ret=_malloc(n*s);_memset(ret,0,n*s);return ret;}
var _cos=Math.cos;var ___rand_state=42;function _rand(){___rand_state=(1103515245*___rand_state+12345)%0x100000000;return ___rand_state&0x7FFFFFFF;}
var _exp=Math.exp;var _sin=Math.sin;var _vsprintf=_sprintf;function _fputs(s,stream){return _write(stream,s,_strlen(s));}
function _exp2(x){return Math.pow(2,x);}
function __Z13GetFileLengthPKc($filename){var __stackBase__=STACKTOP;STACKTOP+=80;_memset(__stackBase__,0,80);var __label__;var $retval;var $filename_addr;var $statbuf=__stackBase__;$filename_addr=$filename;var $0=$filename_addr;var $call=_stat($0,$statbuf);var $cmp=((($call))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $st_mode=(($statbuf+12)&4294967295);var $1=HEAP32[(($st_mode)>>2)];var $and=($1)&61440;var $cmp1=((($and))|0)==16384;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=-2;;}
else if(__label__==4){var $st_size=(($statbuf+36)&4294967295);var $2=HEAP32[(($st_size)>>2)];$retval=$2;;}}
var $3=$retval;STACKTOP=__stackBase__;return $3;return null;}
function __Z5Alloci($size){;var __label__;var $size_addr;var $p;$size_addr=$size;var $0=$size_addr;var $call=_malloc($0);$p=$call;var $cmp=((($call))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($1+12)&4294967295);var $2=HEAP32[(($_stderr)>>2)];var $3=_fwrite(((__str106)&4294967295),22,1,$2);;}
var $4=$p;;return $4;return null;}
function __Z4FreePv($ptr){;var __label__;var $ptr_addr;$ptr_addr=$ptr;var $0=$ptr_addr;var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$ptr_addr;;;};return;return;}
function __Z13DisplayVoicesP7__sFILEPc($f_out,$language){var __stackBase__=STACKTOP;STACKTOP+=36;_memset(__stackBase__,0,36);var __label__;var $f_out_addr;var $language_addr;var $ix;var $p;var $len;var $count;var $scores;var $v;var $lang_name;var $age_buf=__stackBase__;var $voices;var $voice_select=__stackBase__+12;$f_out_addr=$f_out;$language_addr=$language;$scores=0;var $0=$language_addr;var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=3;;}
$land_lhs_true$$if_else$2:do{if(__label__==1){var $1=$language_addr;var $arrayidx=(($1)&4294967295);var $2=HEAP8[($arrayidx)];var $conv=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));var $cmp1=((($conv))|0)!=0;if(!($cmp1)){__label__=3;break $land_lhs_true$$if_else$2;}
var $3=$language_addr;var $languages=(($voice_select+4)&4294967295);HEAP32[(($languages)>>2)]=$3;var $age=(($voice_select+13)&4294967295);HEAP8[($age)]=0;var $gender=(($voice_select+12)&4294967295);HEAP8[($gender)]=0;var $name=(($voice_select)&4294967295);HEAP32[(($name)>>2)]=0;var $call=_espeak_ListVoices($voice_select);$voices=((__ZZ17espeak_ListVoicesE6voices)&4294967295);$scores=1;__label__=4;break $land_lhs_true$$if_else$2;}}while(0);if(__label__==3){var $call2=_espeak_ListVoices(0);$voices=((__ZZ17espeak_ListVoicesE6voices)&4294967295);;}
var $4=$f_out_addr;var $5=_fwrite(((__str1)&4294967295),64,1,$4);$ix=0;var $6=$ix;var $7=$voices;var $arrayidx43=(($7+4*$6)&4294967295);var $8=HEAP32[(($arrayidx43)>>2)];$v=$8;var $cmp54=((($8))|0)!=0;if($cmp54){__label__=5;;}else{__label__=15;;}
$for_body_lr_ph$$for_end$8:do{if(__label__==5){var $arraydecay=(($age_buf)&4294967295);var $arraydecay26=(($age_buf)&4294967295);;$for_body$10:while(1){$count=0;var $9=$v;var $languages6=(($9+4)&4294967295);var $10=HEAP32[(($languages6)>>2)];$p=$10;var $11=$p;var $12=HEAP8[($11)];var $conv71=(tempInt=(($12)),(tempInt>=128?tempInt-256:tempInt));var $cmp82=((($conv71))|0)!=0;if($cmp82){__label__=7;;}else{__label__=14;;}
$while_body$$while_end$12:do{if(__label__==7){while(1){var $13=$p;var $add_ptr=(($13+1)&4294967295);var $call9=_strlen($add_ptr);$len=$call9;var $14=$p;var $add_ptr10=(($14+1)&4294967295);$lang_name=$add_ptr10;var $15=$v;var $age11=(($15+13)&4294967295);var $16=HEAPU8[($age11)];var $conv12=((($16))&255);var $cmp13=((($conv12))|0)==0;if($cmp13){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str41208)&4294967295);$dest$=$arraydecay;$stop$=$src$+4;if(($dest$%4)==($src$%4)&&4>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}
else if(__label__==9){var $17=$v;var $age18=(($17+13)&4294967295);var $18=HEAPU8[($age18)];var $conv19=((($18))&255);var $call20=_sprintf($arraydecay,((__str3)&4294967295),allocate([$conv19,0,0,0],["i32",0,0,0],ALLOC_STACK));;}
var $19=$count;var $cmp22=((($19))|0)==0;var $20=$f_out_addr;if($cmp22){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $21=$p;var $arrayidx24=(($21)&4294967295);var $22=HEAP8[($arrayidx24)];var $conv25=(tempInt=(($22)),(tempInt>=128?tempInt-256:tempInt));var $23=$lang_name;var $24=$v;var $gender27=(($24+12)&4294967295);var $25=HEAPU8[($gender27)];var $idxprom=((($25))&255);var $arrayidx28=((__ZZ13DisplayVoicesP7__sFILEPcE7genders+$idxprom)&4294967295);var $26=HEAP8[($arrayidx28)];var $conv29=(tempInt=(($26)),(tempInt>=128?tempInt-256:tempInt));var $27=$v;var $name30=(($27)&4294967295);var $28=HEAP32[(($name30)>>2)];var $29=$v;var $identifier=(($29+8)&4294967295);var $30=HEAP32[(($identifier)>>2)];var $call31=_fprintf($20,((__str4)&4294967295),allocate([$conv25,0,0,0,$23,0,0,0,$arraydecay26,0,0,0,$conv29,0,0,0,$28,0,0,0,$30,0,0,0],["i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==12){var $31=$lang_name;var $32=$p;var $arrayidx33=(($32)&4294967295);var $33=HEAP8[($arrayidx33)];var $conv34=(tempInt=(($33)),(tempInt>=128?tempInt-256:tempInt));var $call35=_fprintf($20,((__str5)&4294967295),allocate([$31,0,0,0,$conv34,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));;}
var $34=$count;var $inc=((($34)+1)&4294967295);$count=$inc;var $35=$len;var $add=((($35)+2)&4294967295);var $36=$p;var $add_ptr37=(($36+$add)&4294967295);$p=$add_ptr37;var $37=$p;var $38=HEAP8[($37)];var $conv7=(tempInt=(($38)),(tempInt>=128?tempInt-256:tempInt));var $cmp8=((($conv7))|0)!=0;if($cmp8){__label__=7;continue;}else{__label__=14;break $while_body$$while_end$12;}}}}while(0);var $39=$f_out_addr;var $call38=_fputc(10,$39);var $40=$ix;var $inc39=((($40)+1)&4294967295);$ix=$inc39;var $41=$ix;var $42=$voices;var $arrayidx4=(($42+4*$41)&4294967295);var $43=HEAP32[(($arrayidx4)>>2)];$v=$43;var $cmp5=((($43))|0)!=0;if($cmp5){__label__=6;continue $for_body$10;}else{__label__=15;break $for_body_lr_ph$$for_end$8;}}}}while(0);STACKTOP=__stackBase__;return;return;}
function __Z13WVoiceChangedP7voice_t($wvoice){;var __label__;;return;return;}
function __Z11MarkerEventijiPh($type,$char_position,$value,$out_ptr){;var __label__;var $type_addr;var $char_position_addr;var $value_addr;var $out_ptr_addr;$type_addr=$type;$char_position_addr=$char_position;$value_addr=$value;$out_ptr_addr=$out_ptr;var $0=$type_addr;var $cmp=((($0))|0)==2;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((_end_of_sentence)>>2)]=1;;};return;return;}
function _main($argc,$argv){;var __label__;var __lastLabel__=null;var $_ZL9help_text;$_ZL9help_text=((__str37)&4294967295);var $_ZZ4mainE8err_load;$_ZZ4mainE8err_load=((__str18)&4294967295);var $retval;var $argc_addr;var $argv_addr;var $f_text;var $p_text;var $data_path;var $option_index=STACKTOP;_memset(STACKTOP,0,4);STACKTOP+=4;STACKTOP=Math.ceil((STACKTOP)/4)*4;;var $c;var $value=STACKTOP;_memset(STACKTOP,0,4);STACKTOP+=4;STACKTOP=Math.ceil((STACKTOP)/4)*4;;var $speed;var $ix;var $optarg2;var $amp;var $wordgap;var $speaking;var $flag_stdin;var $flag_compile;var $pitch_adjustment;var $voice_select=STACKTOP;_memset(STACKTOP,0,24);STACKTOP+=24;STACKTOP=Math.ceil((STACKTOP)/4)*4;;var $filename=STACKTOP;_memset(STACKTOP,0,200);STACKTOP+=200;STACKTOP=Math.ceil((STACKTOP)/4)*4;;var $voicename=STACKTOP;_memset(STACKTOP,0,40);STACKTOP+=40;STACKTOP=Math.ceil((STACKTOP)/4)*4;;var $dictname=STACKTOP;_memset(STACKTOP,0,40);STACKTOP+=40;STACKTOP=Math.ceil((STACKTOP)/4)*4;;var $extn;$retval=0;$argc_addr=$argc;$argv_addr=$argv;$f_text=0;$p_text=0;$data_path=0;HEAP32[(($option_index)>>2)]=0;$speed=175;$amp=100;$wordgap=0;$speaking=0;$flag_stdin=0;$flag_compile=0;$pitch_adjustment=50;var $arrayidx=(($voicename)&4294967295);HEAP8[($arrayidx)]=0;HEAP8[(((_mbrola_name)&4294967295))]=0;var $arrayidx1=(($dictname)&4294967295);HEAP8[($arrayidx1)]=0;HEAP8[(((_wavefile)&4294967295))]=0;var $arrayidx2=(($filename)&4294967295);HEAP8[($arrayidx2)]=0;HEAP32[((_option_linelength)>>2)]=0;HEAP32[((_option_phonemes)>>2)]=0;HEAP32[((_option_waveout)>>2)]=0;HEAP32[((_option_wordgap)>>2)]=0;HEAP32[((_option_endpause)>>2)]=1;HEAP32[((_option_phoneme_input)>>2)]=1;HEAP32[((_option_multibyte)>>2)]=0;var $0=HEAP32[((__impure_ptr)>>2)];var $_stdout=(($0+8)&4294967295);var $1=HEAP32[(($_stdout)>>2)];HEAP32[((_f_trans)>>2)]=$1;var $2=$argc_addr;var $3=$argv_addr;var $call6=_getopt_long($2,$3,((__str19)&4294967295),((__ZZ4mainE12long_options)&4294967295),$option_index);$c=$call6;var $cmp7=((($call6))|0)==-1;if($cmp7){__label__=43;;}else{__label__=1;;}
$while_end71$$if_end_lr_ph$2:do{if(__label__==1){var $arraydecay=(($filename)&4294967295);var $arraydecay32=(($voicename)&4294967295);var $arraydecay41=(($voicename)&4294967295);var $_pr8=$c;__lastLabel__=1;;$if_end$4:while(1){var $4=__lastLabel__==1?$_pr8:($call);var $5=HEAP32[((_optarg)>>2)];$optarg2=$5;if($4==98){__lastLabel__=2;__label__=3;;}
else if($4==104){__lastLabel__=2;__label__=5;;}
else if($4==107){__lastLabel__=2;__label__=6;;}
else if($4==120){__lastLabel__=2;__label__=7;;}
else if($4==88){__lastLabel__=2;__label__=8;;}
else if($4==109){__lastLabel__=2;__label__=9;;}
else if($4==112){__lastLabel__=2;__label__=10;;}
else if($4==113){__lastLabel__=2;__label__=12;;}
else if($4==102){__lastLabel__=2;__label__=13;;}
else if($4==108){__lastLabel__=2;__label__=14;;}
else if($4==97){__lastLabel__=2;__label__=15;;}
else if($4==115){__lastLabel__=2;__label__=16;;}
else if($4==103){__lastLabel__=2;__label__=17;;}
else if($4==118){__lastLabel__=2;__label__=18;;}
else if($4==119){__lastLabel__=2;__label__=19;;}
else if($4==122){__lastLabel__=2;__label__=20;;}
else if($4==256){__lastLabel__=2;__label__=21;;}
else if($4==261){__lastLabel__=2;__label__=22;;}
else if($4==257){__lastLabel__=2;__label__=23;;}
else if($4==258){__lastLabel__=2;__label__=23;;}
else if($4==259){__lastLabel__=2;__label__=26;;}
else if($4==260){__lastLabel__=2;__label__=32;;}
else if($4==262){__lastLabel__=2;__label__=33;;}
else if($4==263){__lastLabel__=2;__label__=36;;}
else if($4==264){__lastLabel__=2;__label__=37;;}
else if($4==265){__lastLabel__=2;__label__=40;;}
else if($4==266){__lastLabel__=2;__label__=41;;}
else{__lastLabel__=2;__label__=42;;}
$sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6:do{if(__label__==42){_exit(0);__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==3){HEAP32[((_option_multibyte)>>2)]=2;var $6=$optarg2;var $call3=_sscanf($6,((__str63715)&4294967295),allocate([$value,0,0,0],["i32*",0,0,0],ALLOC_STACK));var $cmp4=((($call3))|0)==1;var $7=HEAP32[(($value)>>2)];var $cmp5=((($7))|0)<=4;var $or_cond=($cmp4)&($cmp5);if(!($or_cond)){__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
var $8=HEAP32[(($value)>>2)];HEAP32[((_option_multibyte)>>2)]=$8;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==5){var $9=$argv_addr;var $arrayidx9=(($9)&4294967295);var $10=HEAP32[(($arrayidx9)>>2)];var $11=$data_path;__ZL9init_pathPcS_($10,$11);var $12=HEAP32[((_version_string)>>2)];var $13=$_ZL9help_text;var $call10=_printf(((__str21)&4294967295),allocate([$12,0,0,0,((_path_home)&4294967295),0,0,0,$13,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));_exit(0);__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==6){var $14=$optarg2;var $call12=_atoi($14);HEAP32[((_option_capitals)>>2)]=$call12;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==7){HEAP32[((_option_phonemes)>>2)]=1;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==8){HEAP32[((_option_phonemes)>>2)]=2;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==9){HEAP32[((_option_ssml)>>2)]=1;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==10){var $15=$optarg2;var $call17=_atoi($15);$pitch_adjustment=$call17;var $16=$pitch_adjustment;var $cmp18=((($16))|0)>99;if(!($cmp18)){__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
$pitch_adjustment=99;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==12){HEAP32[((_quiet)>>2)]=1;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==13){var $17=$optarg2;__Z8strncpy0PcPKci($arraydecay,$17,200);__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==14){HEAP32[(($value)>>2)]=0;var $18=$optarg2;var $call24=_atoi($18);HEAP32[(($value)>>2)]=$call24;var $19=HEAP32[(($value)>>2)];HEAP32[((_option_linelength)>>2)]=$19;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==15){var $20=$optarg2;var $call26=_atoi($20);$amp=$call26;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==16){var $21=$optarg2;var $call28=_atoi($21);$speed=$call28;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==17){var $22=$optarg2;var $call30=_atoi($22);$wordgap=$call30;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==18){var $23=$optarg2;__Z8strncpy0PcPKci($arraydecay32,$23,40);__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==19){HEAP32[((_option_waveout)>>2)]=1;var $24=$optarg2;__Z8strncpy0PcPKci(((_wavefile)&4294967295),$24,200);__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==20){HEAP32[((_option_endpause)>>2)]=0;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==21){$flag_stdin=1;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==22){HEAP32[((_option_waveout)>>2)]=1;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str12)&4294967295);$dest$=((_wavefile)&4294967295);$stop$=$src$+7;if(($dest$%4)==($src$%4)&&7>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==23){var $cmp39=((($5))|0)!=0;if($cmp39){__label__=24;;}else{__label__=25;;}
if(__label__==24){var $25=$optarg2;__Z8strncpy0PcPKci($arraydecay41,$25,40);;}
var $26=$c;$flag_compile=$26;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==26){HEAP32[((_option_punctuation)>>2)]=1;var $27=$optarg2;var $cmp44=((($27))|0)!=0;if(!($cmp44)){__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
$ix=0;__lastLabel__=27;;while(1){var $28=__lastLabel__==30?$inc:(0);var $cmp47=((($28))|0)<60;if(!($cmp47)){__label__=31;break;}
var $29=$ix;var $30=$optarg2;var $arrayidx48=(($30+$29)&4294967295);var $31=HEAP8[($arrayidx48)];var $conv=(tempInt=(($31)),(tempInt>=128?tempInt-256:tempInt));var $32=$ix;var $arrayidx49=((_option_punctlist+$32*4)&4294967295);HEAP32[(($arrayidx49)>>2)]=$conv;var $cmp50=((($conv))|0)!=0;if(!($cmp50)){__label__=31;break;}
var $33=$ix;var $inc=((($33)+1)&4294967295);$ix=$inc;__lastLabel__=30;__label__=28;continue;}
HEAP32[((((_option_punctlist+236)&4294967295))>>2)]=0;HEAP32[((_option_punctuation)>>2)]=2;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==32){var $34=$argv_addr;var $arrayidx54=(($34)&4294967295);var $35=HEAP32[(($arrayidx54)>>2)];var $36=$data_path;__ZL9init_pathPcS_($35,$36);var $37=HEAP32[((__impure_ptr)>>2)];var $_stdout55=(($37+8)&4294967295);var $38=HEAP32[(($_stdout55)>>2)];var $39=$optarg2;__Z13DisplayVoicesP7__sFILEPc($38,$39);_exit(0);var $_pr=$optarg2;__lastLabel__=32;__label__=33;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==36){var $42=$optarg2;$data_path=$42;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==37){var $43=$optarg2;var $call63=_fopen($43,((__str11422)&4294967295));HEAP32[((_f_trans)>>2)]=$call63;var $cmp64=((($call63))|0)==0;if(!($cmp64)){__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
var $46=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($46+12)&4294967295);var $47=HEAP32[(($_stderr)>>2)];var $48=$optarg2;var $call66=_fprintf($47,((__str23)&4294967295),allocate([$48,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $49=HEAP32[((__impure_ptr)>>2)];var $_stderr67=(($49+12)&4294967295);var $50=HEAP32[(($_stderr67)>>2)];HEAP32[((_f_trans)>>2)]=$50;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==40){HEAP32[((_option_mbrola_phonemes)>>2)]=16;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}
else if(__label__==41){HEAP32[((_option_phonemes)>>2)]=3;__label__=38;break $sw_default$$sw_bb$$sw_bb8$$sw_bb11$$sw_bb13$$sw_bb14$$sw_bb15$$sw_bb16$$sw_bb21$$sw_bb22$$sw_bb23$$sw_bb25$$sw_bb27$$sw_bb29$$sw_bb31$$sw_bb33$$sw_bb34$$sw_bb35$$sw_bb36$$sw_bb38$$sw_bb43$$sw_bb53$$sw_bb56$$sw_bb61$$sw_bb62$$sw_bb69$$sw_bb70$6;}}while(0);if(__label__==33){var $40=__lastLabel__==32?$_pr:($5);var $cmp57=((($40))|0)==0;if($cmp57){__label__=34;;}else{__label__=35;;}
if(__label__==34){HEAP32[((_samples_split)>>2)]=30;;}
else if(__label__==35){var $41=$optarg2;var $call59=_atoi($41);HEAP32[((_samples_split)>>2)]=$call59;;}}
var $44=$argc_addr;var $45=$argv_addr;var $call=_getopt_long($44,$45,((__str19)&4294967295),((__ZZ4mainE12long_options)&4294967295),$option_index);$c=$call;var $cmp=((($call))|0)==-1;if($cmp){__lastLabel__=38;__label__=43;break $while_end71$$if_end_lr_ph$2;}else{__lastLabel__=38;__label__=2;continue $if_end$4;}}}}while(0);var $51=$argv_addr;var $arrayidx72=(($51)&4294967295);var $52=HEAP32[(($arrayidx72)>>2)];var $53=$data_path;__ZL9init_pathPcS_($52,$53);__ZL10initialisev();var $54=$flag_compile;var $tobool=((($54))|0)!=0;if($tobool){__label__=44;;}else{__label__=45;;}
if(__label__==44){var $arraydecay75=(($voicename)&4294967295);var $call76=__Z9LoadVoicePKci($arraydecay75,5);var $55=$flag_compile;var $and=($55)&1;var $call77=__Z17CompileDictionaryPKcS0_P7__sFILEPci(0,((_dictionary_name)&4294967295),0,0,$and);_exit(0);;}
var $arrayidx79=(($voicename)&4294967295);var $56=HEAP8[($arrayidx79)];var $conv80=(tempInt=(($56)),(tempInt>=128?tempInt-256:tempInt));var $cmp81=((($conv80))|0)==0;if($cmp81){__label__=46;;}else{__label__=47;;}
if(__label__==46){var $arraydecay83=(($voicename)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str45697)&4294967295);$dest$=$arraydecay83;$stop$=$src$+8;if(($dest$%4)==($src$%4)&&8>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}
var $arraydecay86=(($voicename)&4294967295);var $call87=__Z14SetVoiceByNamePKc($arraydecay86);var $cmp88=((($call87))|0)!=0;if($cmp88){__label__=48;;}else{__label__=50;;}
$if_then89$$if_end98$58:do{if(__label__==48){var $57=$voice_select;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$57;$stop$=$dest$+24;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $arraydecay90=(($voicename)&4294967295);var $languages=(($voice_select+4)&4294967295);HEAP32[(($languages)>>2)]=$arraydecay90;var $call91=__Z20SetVoiceByPropertiesP12espeak_VOICE($voice_select);var $cmp92=((($call91))|0)!=0;if(!($cmp92)){__label__=50;break $if_then89$$if_end98$58;}
var $58=HEAP32[((__impure_ptr)>>2)];var $_stderr94=(($58+12)&4294967295);var $59=HEAP32[(($_stderr94)>>2)];var $60=$_ZZ4mainE8err_load;var $arraydecay95=(($voicename)&4294967295);var $call96=_fprintf($59,((__str25)&4294967295),allocate([$60,0,0,0,$arraydecay95,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));_exit(2);;}}while(0);var $61=$speed;__Z12SetParameteriii(1,$61,0);var $62=$amp;__Z12SetParameteriii(2,$62,0);var $63=HEAP32[((_option_capitals)>>2)];__Z12SetParameteriii(6,$63,0);var $64=HEAP32[((_option_punctuation)>>2)];__Z12SetParameteriii(5,$64,0);var $65=$wordgap;__Z12SetParameteriii(7,$65,0);var $66=$pitch_adjustment;var $cmp99=((($66))|0)!=50;if($cmp99){__label__=51;;}else{__label__=52;;}
if(__label__==51){var $67=$pitch_adjustment;__Z12SetParameteriii(3,$67,0);;}
var $68=HEAP32[((_voice)>>2)];__Z13DoVoiceChangeP7voice_t($68);var $arrayidx102=(($filename)&4294967295);var $69=HEAP8[($arrayidx102)];var $conv103=(tempInt=(($69)),(tempInt>=128?tempInt-256:tempInt));var $cmp104=((($conv103))|0)==0;if($cmp104){__label__=53;;}else{__label__=59;;}
$if_then105$$if_else116$65:do{if(__label__==53){var $70=HEAP32[((_optind)>>2)];var $71=$argc_addr;var $cmp106=((($70))|0)<((($71))|0);var $72=$flag_stdin;if($cmp106){__label__=54;;}else{__label__=57;;}
if(__label__==54){var $cmp108=((($72))|0)==0;if($cmp108){__label__=56;;}else{__label__=55;;}
if(__label__==56){var $75=HEAP32[((_optind)>>2)];var $76=$argv_addr;var $arrayidx110=(($76+4*$75)&4294967295);var $77=HEAP32[(($arrayidx110)>>2)];$p_text=$77;;}
else if(__label__==55){var $73=HEAP32[((__impure_ptr)>>2)];var $_stdin3=(($73+4)&4294967295);var $74=HEAP32[(($_stdin3)>>2)];$f_text=$74;__lastLabel__=55;__label__=61;break $if_then105$$if_else116$65;}}
else if(__label__==57){var $78=HEAP32[((__impure_ptr)>>2)];var $_stdin=(($78+4)&4294967295);var $79=HEAP32[(($_stdin)>>2)];$f_text=$79;var $cmp112=((($72))|0)==0;if($cmp112){__lastLabel__=57;;}else{__lastLabel__=57;__label__=61;break $if_then105$$if_else116$65;}
HEAP32[((_option_linelength)>>2)]=-1;;}
var $_pr5=$f_text;__lastLabel__=60;;}
else if(__label__==59){var $arraydecay117=(($filename)&4294967295);var $call118=_fopen($arraydecay117,((__str51703)&4294967295));$f_text=$call118;__lastLabel__=59;;}}while(0);var $80=__lastLabel__==60?$_pr5:(__lastLabel__==55?$74:(__lastLabel__==57?$79:($call118)));var $cmp120=((($80))|0)==0;if($cmp120){__label__=62;;}else{__label__=64;;}
$land_lhs_true121$$if_end127$77:do{if(__label__==62){var $81=$p_text;var $cmp122=((($81))|0)==0;if(!($cmp122)){__label__=64;break $land_lhs_true121$$if_end127$77;}
var $82=HEAP32[((__impure_ptr)>>2)];var $_stderr124=(($82+12)&4294967295);var $83=HEAP32[(($_stderr124)>>2)];var $84=$_ZZ4mainE8err_load;var $arraydecay125=(($filename)&4294967295);var $call126=_fprintf($83,((__str27)&4294967295),allocate([$84,0,0,0,$arraydecay125,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));_exit(1);;}}while(0);var $85=HEAP32[((_option_waveout)>>2)];var $tobool128=((($85))|0)!=0;var $86=HEAP32[((_quiet)>>2)];var $tobool129=((($86))|0)!=0;var $or_cond1=($tobool128)|($tobool129);if($or_cond1){__label__=65;;}else{__label__=79;;}
$if_then130$$if_else168$81:do{if(__label__==65){var $87=HEAP32[((_quiet)>>2)];var $tobool131=((($87))|0)!=0;var $88=HEAP32[((_samplerate)>>2)];if($tobool131){__label__=66;;}else{__label__=67;;}
$if_then132$$if_else134$83:do{if(__label__==66){var $call133=__ZL12OpenWaveFilePKci(0,$88);HEAP32[((_option_waveout)>>2)]=1;;}
else if(__label__==67){var $89=HEAP32[((_samples_split)>>2)];var $mul=((($88)*60)&4294967295);var $mul135=((($mul)*($89))&4294967295);HEAP32[((_samples_split)>>2)]=$mul135;var $90=HEAP32[((_samples_split)>>2)];var $tobool136=((($90))|0)!=0;if($tobool136){__label__=68;;}else{__label__=71;;}
if(__label__==68){var $call138=_strrchr(((_wavefile)&4294967295),46);$extn=$call138;var $91=$extn;var $cmp139=((($91))|0)!=0;if(!($cmp139)){__label__=73;break $if_then132$$if_else134$83;}
var $call141=_strlen(((_wavefile)&4294967295));var $add_ptr=((((_wavefile)&4294967295)+$call141)&4294967295);var $92=$extn;var $sub_ptr_lhs_cast=($add_ptr);var $sub_ptr_rhs_cast=($92);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);var $cmp142=((($sub_ptr_sub))|0)<=4;if(!($cmp142)){__label__=73;break $if_then132$$if_else134$83;}
var $93=$extn;var $call144=_strcpy(((_filetype)&4294967295),$93);var $94=$extn;HEAP8[($94)]=0;;}
else if(__label__==71){var $95=HEAP32[((_samplerate)>>2)];var $call147=__ZL12OpenWaveFilePKci(((_wavefile)&4294967295),$95);var $cmp148=((($call147))|0)!=0;if(!($cmp148)){__label__=73;break $if_then132$$if_else134$83;}
var $96=HEAP32[((__impure_ptr)>>2)];var $_stderr150=(($96+12)&4294967295);var $97=HEAP32[(($_stderr150)>>2)];var $call151=_fprintf($97,((__str28)&4294967295),allocate([((_wavefile)&4294967295),0,0,0],["i8*",0,0,0],ALLOC_STACK));_exit(3);;}}}while(0);__Z8InitTexti(0);var $98=$f_text;var $99=$p_text;var $call155=__Z15SpeakNextClauseP7__sFILEPKvi($98,$99,0);$ix=1;;while(1){var $call156=__ZL11WavegenFilev();var $cmp157=((($call156))|0)!=0;if($cmp157){__label__=75;;}else{__label__=76;;}
if(__label__==75){var $100=$ix;var $cmp159=((($100))|0)==0;if($cmp159){__label__=78;break;}}
var $call163=__Z8GenerateP12PHONEME_LISTPii(((_phoneme_list)&4294967295),_n_phoneme_list,1);var $cmp164=((($call163))|0)==0;if(!($cmp164)){__label__=74;continue;}
var $call166=__Z15SpeakNextClauseP7__sFILEPKvi(0,0,1);$ix=$call166;__label__=74;continue;}
__ZL13CloseWaveFilev();__label__=83;break $if_then130$$if_else168$81;}
else if(__label__==79){__Z8InitTexti(0);var $101=$f_text;var $102=$p_text;var $call170=__Z15SpeakNextClauseP7__sFILEPKvi($101,$102,0);var $103=HEAP32[((_option_quiet)>>2)];var $tobool171=((($103))|0)!=0;if($tobool171){__label__=80;;}else{__label__=82;;}
if(__label__==80){while(1){var $call173=__Z15SpeakNextClauseP7__sFILEPKvi(0,0,1);var $cmp174=((($call173))|0)!=0;if($cmp174){__label__=80;continue;}else{__label__=81;break;}}
$retval=0;__label__=87;break $if_then130$$if_else168$81;}
else if(__label__==82){var $104=HEAP32[((__impure_ptr)>>2)];var $_stderr178=(($104+12)&4294967295);var $105=HEAP32[(($_stderr178)>>2)];var $106=_fwrite(((__str29)&4294967295),79,1,$105);__label__=83;break $if_then130$$if_else168$81;}}}while(0);if(__label__==83){var $107=HEAP32[((_f_trans)>>2)];var $108=HEAP32[((__impure_ptr)>>2)];var $_stdout181=(($108+8)&4294967295);var $109=HEAP32[(($_stdout181)>>2)];var $cmp182=((($107))|0)!=((($109))|0);if($cmp182){__label__=84;;}else{__label__=86;;}
$land_lhs_true183$$if_end188$108:do{if(__label__==84){var $110=HEAP32[((_f_trans)>>2)];var $111=HEAP32[((__impure_ptr)>>2)];var $_stderr184=(($111+12)&4294967295);var $112=HEAP32[(($_stderr184)>>2)];var $cmp185=((($110))|0)!=((($112))|0);if(!($cmp185)){__label__=86;break $land_lhs_true183$$if_end188$108;}
var $113=HEAP32[((_f_trans)>>2)];var $call187=_fclose($113);;}}while(0);$retval=0;;}
var $114=$retval;;return $114;return null;}
Module["_main"]=_main;function __ZL9init_pathPcS_($argv0,$path_specified){;var __label__;var $argv0_addr;var $path_specified_addr;var $env;$argv0_addr=$argv0;$path_specified_addr=$path_specified;var $0=$path_specified_addr;var $tobool=((($0))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){var $1=$path_specified_addr;var $call=_sprintf(((_path_home)&4294967295),((__str38)&4294967295),allocate([$1,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==2){var $call1=_getenv(((__str39)&4294967295));$env=$call1;var $cmp=((($call1))|0)!=0;if($cmp){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $2=$env;var $call3=_snprintf(((_path_home)&4294967295),150,((__str38)&4294967295),allocate([$2,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $call4=__Z13GetFileLengthPKc(((_path_home)&4294967295));var $cmp5=((($call4))|0)==-2;if($cmp5){__label__=6;break $if_then$$if_end$2;}}
var $call9=_getenv(((__str40)&4294967295));var $call10=_snprintf(((_path_home)&4294967295),150,((__str38)&4294967295),allocate([$call9,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $call11=_access(((_path_home)&4294967295),4);var $cmp12=((($call11))|0)!=0;if(!($cmp12)){__label__=6;break $if_then$$if_end$2;}
var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str41)&4294967295);$dest$=((_path_home)&4294967295);$stop$=$src$+23;if(($dest$%4)==($src$%4)&&23>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}}while(0);;return;return;}
function __ZL10initialisev(){;var __label__;var $param;var $result;var $call=_setlocale(2,((__str32)&4294967295));var $cmp=((($call))|0)==0;if($cmp){__label__=1;;}else{__label__=3;;}
$if_then$$if_end5$2:do{if(__label__==1){var $call1=_setlocale(2,((__str33)&4294967295));var $cmp2=((($call1))|0)==0;if(!($cmp2)){__label__=3;break $if_then$$if_end5$2;}
var $call4=_setlocale(2,((__str13643)&4294967295));;}}while(0);__Z11WavegenInitii(22050,0);var $call6=__Z10LoadPhDatav();$result=$call6;var $cmp7=((($call6))|0)!=1;if($cmp7){__label__=4;;}else{__label__=7;;}
if(__label__==4){var $0=$result;var $cmp9=((($0))|0)==-1;var $1=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($1+12)&4294967295);var $2=HEAP32[(($_stderr)>>2)];if($cmp9){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $3=_fwrite(((__str35)&4294967295),27,1,$2);_exit(1);;}
else if(__label__==6){var $4=$result;var $call13=_fprintf($2,((__str36)&4294967295),allocate([$4,0,0,0,83200,0,0,0,((_path_home)&4294967295),0,0,0],["i32",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}}
__Z10LoadConfigv();__Z13SetVoiceStackP12espeak_VOICE(0);__Z14SynthesizeInitv();$param=0;;while(1){var $5=$param;var $arrayidx=((_param_defaults+$5*4)&4294967295);var $6=HEAP32[(($arrayidx)>>2)];var $7=$param;var $arrayidx17=((((_param_stack+4)&4294967295)+$7*4)&4294967295);HEAP32[(($arrayidx17)>>2)]=$6;var $8=$param;var $inc=((($8)+1)&4294967295);$param=$inc;var $cmp16=((($inc))|0)<15;if($cmp16){__label__=8;continue;}else{__label__=9;break;}};return;return;}
function __ZL12OpenWaveFilePKci($path,$rate){;var __label__;var __lastLabel__=null;var $retval;var $path_addr;var $rate_addr;$path_addr=$path;$rate_addr=$rate;var $0=$path_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=2;;}
else if(__label__==2){var $1=$path_addr;var $call=_strcmp($1,((__str12)&4294967295));var $cmp1=((($call))|0)==0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $2=HEAP32[((__impure_ptr)>>2)];var $_stdout=(($2+8)&4294967295);var $3=HEAP32[(($_stdout)>>2)];HEAP32[((_f_wave)>>2)]=$3;__lastLabel__=3;;}
else if(__label__==4){var $4=$path_addr;var $call3=_fopen($4,((__str79)&4294967295));HEAP32[((_f_wave)>>2)]=$call3;__lastLabel__=4;;}
var $5=__lastLabel__==4?$call3:($3);var $cmp5=((($5))|0)!=0;if($cmp5){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $6=HEAP32[((_f_wave)>>2)];var $call7=_fwrite(((__ZZL12OpenWaveFilePKciE8wave_hdr)&4294967295),1,24,$6);var $7=HEAP32[((_f_wave)>>2)];var $8=$rate_addr;__Z11Write4BytesP7__sFILEi($7,$8);var $9=HEAP32[((_f_wave)>>2)];var $10=$rate_addr;var $mul=((($10)*2)&4294967295);__Z11Write4BytesP7__sFILEi($9,$mul);var $11=HEAP32[((_f_wave)>>2)];var $call8=_fwrite(((__ZZL12OpenWaveFilePKciE8wave_hdr+32)&4294967295),1,12,$11);$retval=0;;}
else if(__label__==7){$retval=1;;}}
var $12=$retval;;return $12;return null;}
function __ZL11WavegenFilev(){var __stackBase__=STACKTOP;STACKTOP+=1236;_memset(__stackBase__,0,1236);var __label__;var $retval;var $finished;var $wav_outbuf=__stackBase__;var $fname=__stackBase__+1024;var $arraydecay=(($wav_outbuf)&4294967295);HEAP32[((_out_start)>>2)]=$arraydecay;HEAP32[((_out_ptr)>>2)]=$arraydecay;var $arraydecay1=(($wav_outbuf)&4294967295);var $add_ptr=(($arraydecay1+1024)&4294967295);HEAP32[((_out_end)>>2)]=$add_ptr;var $call=__Z11WavegenFilli(0);$finished=$call;var $0=HEAP32[((_quiet)>>2)];var $tobool=((($0))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){var $1=$finished;$retval=$1;;}
else if(__label__==2){var $2=HEAP32[((_f_wave)>>2)];var $cmp=((($2))|0)==0;if($cmp){__label__=3;;}else{__label__=5;;}
$if_then2$$if_end10$5:do{if(__label__==3){var $arraydecay3=(($fname)&4294967295);var $3=HEAP32[((_wavefile_count)>>2)];var $inc=((($3)+1)&4294967295);HEAP32[((_wavefile_count)>>2)]=$inc;var $call4=_sprintf($arraydecay3,((__str30)&4294967295),allocate([((_wavefile)&4294967295),0,0,0,$inc,0,0,0,((_filetype)&4294967295),0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay5=(($fname)&4294967295);var $4=HEAP32[((_samplerate)>>2)];var $call6=__ZL12OpenWaveFilePKci($arraydecay5,$4);var $cmp7=((($call6))|0)!=0;if(!($cmp7)){__label__=5;break $if_then2$$if_end10$5;}
$retval=1;__label__=12;break $if_then$$if_end$2;}}while(0);var $5=HEAP32[((_end_of_sentence)>>2)];var $tobool11=((($5))|0)!=0;if($tobool11){__label__=6;;}else{__label__=9;;}
$if_then12$$if_end17$9:do{if(__label__==6){HEAP32[((_end_of_sentence)>>2)]=0;var $6=HEAPU32[((_samples_split)>>2)];var $cmp13=((($6))>>>0)>0;if(!($cmp13)){__label__=9;break $if_then12$$if_end17$9;}
var $7=HEAPU32[((_samples_total)>>2)];var $8=HEAPU32[((_samples_split)>>2)];var $cmp14=((($7))>>>0)>((($8))>>>0);if(!($cmp14)){__label__=9;break $if_then12$$if_end17$9;}
__ZL13CloseWaveFilev();HEAP32[((_samples_total)>>2)]=0;;}}while(0);var $9=HEAP32[((_f_wave)>>2)];var $cmp18=((($9))|0)!=0;if($cmp18){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $10=HEAP32[((_out_ptr)>>2)];var $arraydecay20=(($wav_outbuf)&4294967295);var $sub_ptr_lhs_cast=($10);var $sub_ptr_rhs_cast=($arraydecay20);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);var $div=((((($sub_ptr_sub))|0)/2)|0);var $11=HEAP32[((_samples_total)>>2)];var $add=((($11)+($div))&4294967295);HEAP32[((_samples_total)>>2)]=$add;var $arraydecay21=(($wav_outbuf)&4294967295);var $12=HEAP32[((_out_ptr)>>2)];var $arraydecay22=(($wav_outbuf)&4294967295);var $sub_ptr_lhs_cast23=($12);var $sub_ptr_rhs_cast24=($arraydecay22);var $sub_ptr_sub25=((($sub_ptr_lhs_cast23)-($sub_ptr_rhs_cast24))&4294967295);var $13=HEAP32[((_f_wave)>>2)];var $call26=_fwrite($arraydecay21,1,$sub_ptr_sub25,$13);;}
var $14=$finished;$retval=$14;;}}while(0);var $15=$retval;STACKTOP=__stackBase__;return $15;return null;}
function __ZL13CloseWaveFilev(){;var __label__;var $pos;var $0=HEAP32[((_f_wave)>>2)];var $cmp=((($0))|0)==0;if($cmp){__label__=3;;}else{__label__=1;;}
$return$$lor_lhs_false$2:do{if(__label__==1){var $1=HEAP32[((_f_wave)>>2)];var $2=HEAP32[((__impure_ptr)>>2)];var $_stdout=(($2+8)&4294967295);var $3=HEAP32[(($_stdout)>>2)];var $cmp1=((($1))|0)==((($3))|0);if($cmp1){__label__=3;break $return$$lor_lhs_false$2;}
var $4=HEAP32[((_f_wave)>>2)];var $call=_fflush($4);var $5=HEAP32[((_f_wave)>>2)];var $call2=_ftell($5);$pos=$call2;var $6=HEAP32[((_f_wave)>>2)];var $call3=_fseek($6,4,0);var $7=HEAP32[((_f_wave)>>2)];var $8=$pos;var $sub=((($8)-8)&4294967295);__Z11Write4BytesP7__sFILEi($7,$sub);var $9=HEAP32[((_f_wave)>>2)];var $call4=_fseek($9,40,0);var $10=HEAP32[((_f_wave)>>2)];var $11=$pos;var $sub5=((($11)-44)&4294967295);__Z11Write4BytesP7__sFILEi($10,$sub5);var $12=HEAP32[((_f_wave)>>2)];var $call6=_fclose($12);HEAP32[((_f_wave)>>2)]=0;;}}while(0);;return;return;}
function __Z8isspace2j($c){;var __label__;var $retval;var $c_addr;var $c2;$c_addr=$c;var $0=$c_addr;var $and=($0)&255;$c2=$and;var $cmp=((($and))|0)==0;var $1=$c_addr;var $cmp1=((($1))>>>0)>32;var $or_cond=($cmp)|($cmp1);if($or_cond){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){$retval=1;;}
var $2=$retval;;return $2;return null;}
function __Z14LookupMnemNameP8MNEM_TABi($table,$value){;var __label__;var $retval;var $table_addr;var $value_addr;$table_addr=$table;$value_addr=$value;;while(1){var $0=$table_addr;var $mnem=(($0)&4294967295);var $1=HEAP32[(($mnem)>>2)];var $cmp=((($1))|0)!=0;if(!($cmp)){__label__=5;break;}
var $2=$table_addr;var $value1=(($2+4)&4294967295);var $3=HEAP32[(($value1)>>2)];var $4=$value_addr;var $cmp2=((($3))|0)==((($4))|0);var $5=$table_addr;if($cmp2){__label__=3;break;}
var $incdec_ptr=(($5+8)&4294967295);$table_addr=$incdec_ptr;__label__=1;continue;}
if(__label__==5){$retval=((__str13643)&4294967295);;}
else if(__label__==3){var $mnem3=(($5)&4294967295);var $6=HEAP32[(($mnem3)>>2)];$retval=$6;;}
var $7=$retval;;return $7;return null;}
function __Z22print_dictionary_flagsPj($flags){;var __label__;var $flags_addr;$flags_addr=$flags;var $0=$flags_addr;var $arrayidx=(($0)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];var $and=($1)&15;var $add=((($and)+64)&4294967295);var $call=__Z14LookupMnemNameP8MNEM_TABi(((_mnem_flags)&4294967295),$add);var $2=$flags_addr;var $arrayidx1=(($2)&4294967295);var $3=HEAP32[(($arrayidx1)>>2)];var $4=$flags_addr;var $arrayidx2=(($4+4)&4294967295);var $5=HEAP32[(($arrayidx2)>>2)];var $call3=_sprintf(((__ZZ22print_dictionary_flagsPjE3buf)&4294967295),((__str59)&4294967295),allocate([$call,0,0,0,$3,0,0,0,$5,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STACK));;return((__ZZ22print_dictionary_flagsPjE3buf)&4294967295);return null;}
function __Z10DecodeRulePKciPci($group_chars,$group_length,$rule,$control){var __stackBase__=STACKTOP;STACKTOP+=140;_memset(__stackBase__,0,140);var __label__;var __lastLabel__=null;var $group_chars_addr;var $group_length_addr;var $rule_addr;var $control_addr;var $rb;var $c;var $p;var $ix;var $match_type;var $finished;var $value;var $linenum;var $flags;var $suffix_char;var $condition_num;var $at_start;var $name;var $buf=__stackBase__;var $buf_pre=__stackBase__+60;var $suffix=__stackBase__+120;$group_chars_addr=$group_chars;$group_length_addr=$group_length;$rule_addr=$rule;$control_addr=$control;$finished=0;$linenum=0;$condition_num=0;$at_start=0;$match_type=0;var $arrayidx=(($buf_pre)&4294967295);HEAP8[($arrayidx)]=0;$ix=0;var $0=$ix;var $1=$group_length_addr;var $cmp9=((($0))|0)<((($1))|0);var $2=$ix;if($cmp9){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=2;;}
$for_body$$for_end$2:do{if(__label__==1){while(1){var $3=__lastLabel__==1?$10:($2);var $4=$group_chars_addr;var $arrayidx1=(($4+$3)&4294967295);var $5=HEAP8[($arrayidx1)];var $6=$ix;var $arrayidx2=(($buf+$6)&4294967295);HEAP8[($arrayidx2)]=$5;var $7=$ix;var $inc=((($7)+1)&4294967295);$ix=$inc;var $8=$ix;var $9=$group_length_addr;var $cmp=((($8))|0)<((($9))|0);var $10=$ix;if($cmp){__lastLabel__=1;__label__=1;continue;}else{__lastLabel__=1;__label__=2;break $for_body$$for_end$2;}}}}while(0);var $_lcssa8=__lastLabel__==0?$2:($10);var $arrayidx3=(($buf+$_lcssa8)&4294967295);HEAP8[($arrayidx3)]=0;var $arraydecay=(($buf)&4294967295);var $call=_strlen($arraydecay);var $arrayidx4=(($buf+$call)&4294967295);$p=$arrayidx4;var $11=$finished;var $tobool6=((($11))|0)!=0;var $lnot7=($tobool6)^1;if($lnot7){__label__=3;;}else{__label__=38;;}
$while_body_lr_ph$$while_end$6:do{if(__label__==3){var $arraydecay9=(($buf_pre)&4294967295);var $arraydecay11=(($buf)&4294967295);var $arraydecay13=(($buf)&4294967295);var $arraydecay58=(($suffix)&4294967295);var $arraydecay70=(($suffix)&4294967295);var $arraydecay80=(($suffix)&4294967295);var $arraydecay82=(($suffix)&4294967295);;$while_body$8:while(1){var $12=$rule_addr;var $incdec_ptr=(($12+1)&4294967295);$rule_addr=$incdec_ptr;var $13=HEAP8[($12)];$rb=$13;var $14=$rb;var $conv=((($14))&255);var $cmp5=((($conv))|0)<=9;var $15=$rb;var $conv6=((($15))&255);if($cmp5){__label__=5;;}else{__label__=12;;}
$if_then$$if_end$10:do{if(__label__==5){if($conv6==0){__label__=6;;}
else if($conv6==3){__label__=6;;}
else if($conv6==8){__label__=7;;}
else if($conv6==1){__label__=8;;}
else if($conv6==2){__label__=9;;}
else if($conv6==9){__label__=11;;}
else if($conv6==5){__label__=10;;}
else{__label__=37;break $if_then$$if_end$10;}
if(__label__==6){$finished=1;__label__=37;break $if_then$$if_end$10;}
else if(__label__==7){$at_start=1;;}
else if(__label__==9){$match_type=2;var $17=$p;HEAP8[($17)]=0;var $strlen=_strlen($arraydecay11);var $endptr=(($arraydecay11+$strlen)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str60)&4294967295);$dest$=$endptr;$stop$=$src$+3;if(($dest$%4)==($src$%4)&&3>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $call14=_strlen($arraydecay13);var $arrayidx15=(($buf+$call14)&4294967295);$p=$arrayidx15;__label__=37;break $if_then$$if_end$10;}
else if(__label__==11){var $20=$rule_addr;var $arrayidx20=(($20+1)&4294967295);var $21=HEAP8[($arrayidx20)];var $conv21=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));var $and=($conv21)&255;var $sub=((($and)-1)&4294967295);$value=$sub;var $22=$rule_addr;var $arrayidx22=(($22)&4294967295);var $23=HEAP8[($arrayidx22)];var $conv23=(tempInt=(($23)),(tempInt>=128?tempInt-256:tempInt));var $and24=($conv23)&255;var $24=$value;var $mul=((($24)*255)&4294967295);var $sub25=((($mul)-1)&4294967295);var $add=((($sub25)+($and24))&4294967295);$linenum=$add;var $25=$rule_addr;var $add_ptr=(($25+2)&4294967295);$rule_addr=$add_ptr;__label__=37;break $if_then$$if_end$10;}
else if(__label__==10){var $18=$rule_addr;var $incdec_ptr17=(($18+1)&4294967295);$rule_addr=$incdec_ptr17;var $19=HEAP8[($18)];var $conv18=(tempInt=(($19)),(tempInt>=128?tempInt-256:tempInt));$condition_num=$conv18;__label__=37;break $if_then$$if_end$10;}
$match_type=1;var $16=$p;HEAP8[($16)]=0;$p=$arraydecay9;;}
else if(__label__==12){var $cmp27=((($conv6))|0)==28;if($cmp27){__label__=13;;}else{__label__=17;;}
if(__label__==13){var $26=$rule_addr;var $incdec_ptr29=(($26+1)&4294967295);$rule_addr=$incdec_ptr29;var $27=HEAP8[($26)];var $conv30=(tempInt=(($27)),(tempInt>=128?tempInt-256:tempInt));var $and31=($conv30)&255;$value=$and31;var $28=$value;var $cmp32=((($28))|0)!=1;if($cmp32){__label__=15;;}else{__label__=14;;}
$if_then35$$lor_lhs_false$22:do{if(__label__==14){var $29=$control_addr;var $and33=($29)&-2147483648;var $tobool34=((($and33))|0)!=0;if($tobool34){__label__=15;break $if_then35$$lor_lhs_false$22;}else{__label__=16;break $if_then35$$lor_lhs_false$22;}}}while(0);if(__label__==15){var $30=$p;var $arrayidx36=(($30)&4294967295);HEAP8[($arrayidx36)]=36;var $31=$value;var $call37=__Z14LookupMnemNameP8MNEM_TABi(((_mnem_rules)&4294967295),$31);$name=$call37;var $32=$p;var $arrayidx38=(($32+1)&4294967295);var $33=$name;var $call39=_strcpy($arrayidx38,$33);var $34=$name;var $call40=_strlen($34);var $add41=((($call40)+1)&4294967295);var $35=$p;var $add_ptr42=(($35+$add41)&4294967295);$p=$add_ptr42;;}
$c=32;;}
else if(__label__==17){var $36=$rb;var $conv44=((($36))&255);var $cmp45=((($conv44))|0)==14;if($cmp45){__label__=18;;}else{__label__=25;;}
if(__label__==18){var $37=$rule_addr;var $arrayidx47=(($37)&4294967295);var $38=HEAP8[($arrayidx47)];var $conv48=(tempInt=(($38)),(tempInt>=128?tempInt-256:tempInt));var $and49=($conv48)&127;var $shl=((($and49)*256)&4294967295);var $39=$rule_addr;var $arrayidx50=(($39+1)&4294967295);var $40=HEAP8[($arrayidx50)];var $conv51=(tempInt=(($40)),(tempInt>=128?tempInt-256:tempInt));var $and52=($conv51)&127;var $add53=((($and52)+($shl))&4294967295);$flags=$add53;$suffix_char=83;var $41=$flags;var $and54=($41)&4;var $tobool55=((($and54))|0)!=0;if($tobool55){__label__=19;;}else{__label__=20;;}
if(__label__==19){$suffix_char=80;;}
var $42=$suffix_char;var $43=$rule_addr;var $arrayidx59=(($43+2)&4294967295);var $44=HEAP8[($arrayidx59)];var $conv60=(tempInt=(($44)),(tempInt>=128?tempInt-256:tempInt));var $and61=($conv60)&127;var $call62=_sprintf($arraydecay58,((__str62)&4294967295),allocate([$42,0,0,0,$and61,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $45=$rule_addr;var $add_ptr63=(($45+3)&4294967295);$rule_addr=$add_ptr63;$ix=0;;while(1){var $46=$flags;var $and67=($46)&1;var $tobool68=((($and67))|0)!=0;if($tobool68){__label__=22;;}else{__label__=23;;}
if(__label__==22){var $call71=_strlen($arraydecay70);var $arrayidx72=(($suffix+$call71)&4294967295);var $47=$ix;var $arrayidx73=((((__str61)&4294967295)+$47)&4294967295);var $48=HEAP8[($arrayidx73)];var $conv74=(tempInt=(($48)),(tempInt>=128?tempInt-256:tempInt));var $char=((($conv74))&255);HEAP8[($arrayidx72)]=$char;var $nul=(($arrayidx72+1)&4294967295);HEAP8[($nul)]=0;;}
var $49=$flags;var $shr=($49)>>1;$flags=$shr;var $50=$ix;var $inc78=((($50)+1)&4294967295);$ix=$inc78;var $cmp65=((($inc78))|0)<9;if($cmp65){__label__=21;continue;}else{__label__=24;break;}}
var $51=$p;var $call81=_strcpy($51,$arraydecay80);var $call83=_strlen($arraydecay82);var $52=$p;var $add_ptr84=(($52+$call83)&4294967295);$p=$add_ptr84;$c=32;;}
else if(__label__==25){var $53=$rb;var $conv86=((($53))&255);var $cmp87=((($conv86))|0)==17;if($cmp87){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $54=$rule_addr;var $incdec_ptr89=(($54+1)&4294967295);$rule_addr=$incdec_ptr89;var $55=HEAP8[($54)];var $conv90=(tempInt=(($55)),(tempInt>=128?tempInt-256:tempInt));var $sub91=((($conv90)-65)&4294967295);var $arrayidx92=((__ZZ10DecodeRulePKciPciE10symbols_lg+$sub91)&4294967295);var $56=HEAP8[($arrayidx92)];$c=$56;;}
else if(__label__==27){var $57=$rb;var $conv94=((($57))&255);var $cmp95=((($conv94))|0)==18;if($cmp95){__label__=28;;}else{__label__=31;;}
if(__label__==28){var $58=$rule_addr;var $incdec_ptr97=(($58+1)&4294967295);$rule_addr=$incdec_ptr97;var $59=HEAP8[($58)];var $conv98=(tempInt=(($59)),(tempInt>=128?tempInt-256:tempInt));var $sub99=((($conv98)-65)&4294967295);$value=$sub99;var $60=$p;var $arrayidx100=(($60)&4294967295);HEAP8[($arrayidx100)]=76;var $61=$value;var $div=((((($61))|0)/10)|0);var $add101=((($div)+48)&4294967295);var $conv102=((($add101))&255);var $62=$p;var $arrayidx103=(($62+1)&4294967295);HEAP8[($arrayidx103)]=$conv102;var $63=$value;var $rem=((($63))|0)%10;var $add104=((($rem)+48)&4294967295);var $conv105=((($add104))&255);$c=$conv105;var $64=$match_type;var $cmp106=((($64))|0)==1;if($cmp106){__label__=29;;}else{__label__=30;;}
if(__label__==29){var $65=$c;var $66=$p;var $arrayidx108=(($66)&4294967295);HEAP8[($arrayidx108)]=$65;$c=76;;}
var $67=$p;var $add_ptr110=(($67+2)&4294967295);$p=$add_ptr110;;}
else if(__label__==31){var $68=$rb;var $conv112=((($68))&255);var $cmp113=((($conv112))|0)<=31;var $69=$rb;var $idxprom=((($69))&255);if($cmp113){__label__=32;;}else{__label__=33;;}
if(__label__==32){var $arrayidx115=((__ZZ10DecodeRulePKciPciE7symbols+$idxprom)&4294967295);var $70=HEAP8[($arrayidx115)];$c=$70;;}
else if(__label__==33){var $cmp118=((($idxprom))|0)==32;if($cmp118){__label__=34;;}else{__label__=35;;}
if(__label__==34){$c=95;;}
else if(__label__==35){var $71=$rb;$c=$71;;}}}}}}
var $72=$c;var $73=$p;var $incdec_ptr127=(($73+1)&4294967295);$p=$incdec_ptr127;HEAP8[($73)]=$72;;}}while(0);var $74=$finished;var $tobool=((($74))|0)!=0;var $lnot=($tobool)^1;if($lnot){__label__=4;continue $while_body$8;}else{__label__=38;break $while_body_lr_ph$$while_end$6;}}}}while(0);var $75=$p;HEAP8[($75)]=0;$p=((__ZZ10DecodeRulePKciPciE6output)&4294967295);var $76=$linenum;var $cmp128=((($76))|0)>0;if($cmp128){__label__=39;;}else{__label__=40;;}
if(__label__==39){var $77=$p;var $78=$linenum;var $call130=_sprintf($77,((__str64)&4294967295),allocate([$78,0,0,0],["i32",0,0,0],ALLOC_STACK));var $79=$p;var $add_ptr131=(($79+7)&4294967295);$p=$add_ptr131;;}
var $80=$condition_num;var $cmp133=((($80))|0)>0;if($cmp133){__label__=41;;}else{__label__=42;;}
if(__label__==41){var $81=$p;var $82=$condition_num;var $call135=_sprintf($81,((__str65)&4294967295),allocate([$82,0,0,0],["i32",0,0,0],ALLOC_STACK));var $83=$p;var $call136=_strlen($83);var $84=$p;var $arrayidx137=(($84+$call136)&4294967295);$p=$arrayidx137;;}
var $arraydecay139=(($buf_pre)&4294967295);var $call140=_strlen($arraydecay139);$ix=$call140;var $cmp141=((($call140))|0)>0;var $_pr=$at_start;var $tobool145=((($_pr))|0)!=0;if($cmp141){__label__=44;;}else{__label__=43;;}
$if_then144$$lor_lhs_false142$64:do{if(__label__==44){if($tobool145){__label__=45;break $if_then144$$lor_lhs_false142$64;}else{__label__=46;break $if_then144$$lor_lhs_false142$64;}}
else if(__label__==43){if($tobool145){__label__=45;break $if_then144$$lor_lhs_false142$64;}else{__label__=49;break $if_then144$$lor_lhs_false142$64;}}}while(0);$if_then146$$while_cond149_preheader$$if_end157$67:do{if(__label__==45){var $85=$p;var $incdec_ptr147=(($85+1)&4294967295);$p=$incdec_ptr147;HEAP8[($85)]=95;__label__=46;break $if_then146$$while_cond149_preheader$$if_end157$67;}}while(0);if(__label__==46){var $86=$ix;var $dec4=((($86)-1)&4294967295);$ix=$dec4;var $cmp1505=((($dec4))|0)>=0;if($cmp1505){__label__=47;;}else{__label__=48;;}
$while_body151$$while_end154$71:do{if(__label__==47){while(1){var $87=$ix;var $arrayidx152=(($buf_pre+$87)&4294967295);var $88=HEAP8[($arrayidx152)];var $89=$p;var $incdec_ptr153=(($89+1)&4294967295);$p=$incdec_ptr153;HEAP8[($89)]=$88;var $90=$ix;var $dec=((($90)-1)&4294967295);$ix=$dec;var $cmp150=((($dec))|0)>=0;if($cmp150){__label__=47;continue;}else{__label__=48;break $while_body151$$while_end154$71;}}}}while(0);var $91=$p;var $incdec_ptr155=(($91+1)&4294967295);$p=$incdec_ptr155;HEAP8[($91)]=41;var $92=$p;var $incdec_ptr156=(($92+1)&4294967295);$p=$incdec_ptr156;HEAP8[($92)]=32;;}
var $93=$p;HEAP8[($93)]=0;var $94=$p;var $arraydecay158=(($buf)&4294967295);var $call159=_strcat($94,$arraydecay158);var $call160=_strlen(((__ZZ10DecodeRulePKciPciE6output)&4294967295));$ix=$call160;var $cmp1623=((($call160))|0)<8;var $95=$ix;if($cmp1623){__lastLabel__=49;__label__=50;;}else{__lastLabel__=49;__label__=51;;}
$while_body163$$while_end166$76:do{if(__label__==50){while(1){var $96=__lastLabel__==50?$97:($95);var $inc164=((($96)+1)&4294967295);$ix=$inc164;var $arrayidx165=((__ZZ10DecodeRulePKciPciE6output+$96)&4294967295);HEAP8[($arrayidx165)]=32;var $_pr2=$ix;var $cmp162=((($_pr2))|0)<8;var $97=$ix;if($cmp162){__lastLabel__=50;__label__=50;continue;}else{__lastLabel__=50;__label__=51;break $while_body163$$while_end166$76;}}}}while(0);var $_lcssa=__lastLabel__==49?$95:($97);var $arrayidx167=((__ZZ10DecodeRulePKciPciE6output+$_lcssa)&4294967295);HEAP8[($arrayidx167)]=0;STACKTOP=__stackBase__;return((__ZZ10DecodeRulePKciPciE6output)&4294967295);return null;}
function __Z13string_sorterPPcS0_($a,$b){;var __label__;var $retval;var $a_addr;var $b_addr;var $pa;var $pb;var $ix;$a_addr=$a;$b_addr=$b;var $0=$a_addr;var $1=HEAP32[(($0)>>2)];$pa=$1;var $2=$b_addr;var $3=HEAP32[(($2)>>2)];$pb=$3;var $call=_strcmp($1,$3);$ix=$call;var $cmp=((($call))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $4=$ix;$retval=$4;;}
else if(__label__==2){var $5=$pa;var $call1=_strlen($5);var $add=((($call1)+1)&4294967295);var $6=$pa;var $add_ptr=(($6+$add)&4294967295);$pa=$add_ptr;var $7=$pb;var $call2=_strlen($7);var $add3=((($call2)+1)&4294967295);var $8=$pb;var $add_ptr4=(($8+$add3)&4294967295);$pb=$add_ptr4;var $9=$pa;var $10=$pb;var $call5=_strcmp($9,$10);$retval=$call5;;}
var $11=$retval;;return $11;return null;}
function __Z17CompileDictionaryPKcS0_P7__sFILEPci($dsource,$dict_name,$log,$fname_err,$flags){var __stackBase__=STACKTOP;STACKTOP+=724;_memset(__stackBase__,0,724);var __label__;var $retval;var $dsource_addr;var $dict_name_addr;var $log_addr;var $fname_err_addr;var $flags_addr;var $f_in;var $f_out;var $offset_rules;var $value;var $fname_in=__stackBase__;var $fname_out=__stackBase__+196;var $fname_temp=__stackBase__+364;var $path=__stackBase__+532;$dsource_addr=$dsource;$dict_name_addr=$dict_name;$log_addr=$log;$fname_err_addr=$fname_err;$flags_addr=$flags;$offset_rules=0;HEAP32[((__ZL11error_count)>>2)]=0;HEAP32[((__ZL21error_need_dictionary)>>2)]=0;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=((__ZL19letterGroupsDefined)&4294967295);$stop$=$dest$+26;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $0=$flags_addr;var $and=($0)&1;HEAP32[((__ZL10debug_flag)>>2)]=$and;var $1=$dsource_addr;var $cmp=((($1))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$dsource_addr=((__str13643)&4294967295);;}
var $2=$log_addr;HEAP32[((__ZL5f_log)>>2)]=$2;var $cmp1=((($2))|0)==0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $3=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($3+12)&4294967295);var $4=HEAP32[(($_stderr)>>2)];HEAP32[((__ZL5f_log)>>2)]=$4;;}
var $arraydecay=(($path)&4294967295);var $5=$dsource_addr;var $6=$dict_name_addr;var $call=_sprintf($arraydecay,((__str66)&4294967295),allocate([$5,0,0,0,$6,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay4=(($fname_in)&4294967295);var $arraydecay5=(($path)&4294967295);var $call6=_sprintf($arraydecay4,((__str67)&4294967295),allocate([$arraydecay5,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $arraydecay7=(($fname_in)&4294967295);var $call8=_fopen($arraydecay7,((__str51703)&4294967295));$f_in=$call8;var $cmp9=((($call8))|0)==0;if($cmp9){__label__=5;;}else{__label__=9;;}
$if_then10$$if_end23$8:do{if(__label__==5){var $arraydecay11=(($fname_in)&4294967295);var $arraydecay12=(($path)&4294967295);var $call13=_sprintf($arraydecay11,((__str69)&4294967295),allocate([$arraydecay12,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $arraydecay14=(($fname_in)&4294967295);var $call15=__ZL9fopen_logPKcS0_($arraydecay14,((__str51703)&4294967295));$f_in=$call15;var $cmp16=((($call15))|0)==0;if(!($cmp16)){__label__=9;break $if_then10$$if_end23$8;}
var $7=$fname_err_addr;var $tobool=((($7))|0)!=0;if($tobool){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $8=$fname_err_addr;var $arraydecay19=(($fname_in)&4294967295);var $call20=_strcpy($8,$arraydecay19);;}
$retval=-1;__label__=17;break $if_then10$$if_end23$8;}}while(0);if(__label__==9){var $arraydecay24=(($fname_out)&4294967295);var $9=$dict_name_addr;var $call25=_sprintf($arraydecay24,((__str116)&4294967295),allocate([((_path_home)&4294967295),0,0,0,47,0,0,0,$9,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay26=(($fname_out)&4294967295);var $call27=__ZL9fopen_logPKcS0_($arraydecay26,((__str71)&4294967295));$f_out=$call27;var $cmp28=((($call27))|0)==0;if($cmp28){__label__=10;;}else{__label__=13;;}
if(__label__==10){var $10=$fname_err_addr;var $tobool30=((($10))|0)!=0;if($tobool30){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $11=$fname_err_addr;var $arraydecay32=(($fname_in)&4294967295);var $call33=_strcpy($11,$arraydecay32);;}
$retval=-1;;}
else if(__label__==13){var $arraydecay36=(($fname_temp)&4294967295);var $call37=_sprintf($arraydecay36,((__str72)&4294967295),allocate([((_path_home)&4294967295),0,0,0,47,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));$value=1024;var $12=$f_out;var $13=$value;__Z11Write4BytesP7__sFILEi($12,$13);var $14=$f_out;var $15=$offset_rules;__Z11Write4BytesP7__sFILEi($14,$15);__ZL22compile_dictlist_startv();var $16=HEAP32[((__ZL5f_log)>>2)];var $17=HEAP32[((_phoneme_tab_number)>>2)];var $arrayidx=((_phoneme_tab_list+$17*48)&4294967295);var $name=(($arrayidx)&4294967295);var $arraydecay38=(($name)&4294967295);var $call39=_fprintf($16,((__str73)&4294967295),allocate([$arraydecay38,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $arraydecay40=(($path)&4294967295);__ZL21compile_dictlist_filePKcS0_($arraydecay40,((__str74)&4294967295));var $18=HEAP32[((_translator)>>2)];var $langopts=(($18)&4294967295);var $listx=(($langopts+260)&4294967295);var $19=HEAP32[(($listx)>>2)];var $tobool42=((($19))|0)!=0;var $arraydecay44=(($path)&4294967295);if($tobool42){__label__=14;;}else{__label__=15;;}
if(__label__==14){__ZL21compile_dictlist_filePKcS0_($arraydecay44,((__str75)&4294967295));var $arraydecay46=(($path)&4294967295);__ZL21compile_dictlist_filePKcS0_($arraydecay46,((__str76)&4294967295));;}
else if(__label__==15){__ZL21compile_dictlist_filePKcS0_($arraydecay44,((__str76)&4294967295));var $arraydecay50=(($path)&4294967295);__ZL21compile_dictlist_filePKcS0_($arraydecay50,((__str75)&4294967295));;}
var $arraydecay53=(($path)&4294967295);__ZL21compile_dictlist_filePKcS0_($arraydecay53,((__str77)&4294967295));var $20=$f_out;__ZL20compile_dictlist_endP7__sFILE($20);var $21=$f_out;var $call55=_ftell($21);$offset_rules=$call55;var $22=HEAP32[((__ZL5f_log)>>2)];var $arraydecay56=(($fname_in)&4294967295);var $call57=_fprintf($22,((__str78)&4294967295),allocate([$arraydecay56,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $23=$f_in;var $24=$f_out;var $arraydecay58=(($fname_temp)&4294967295);__ZL17compile_dictrulesP7__sFILES0_Pc($23,$24,$arraydecay58);var $25=$f_in;var $call60=_fclose($25);var $26=$f_out;var $call61=_fseek($26,4,0);var $27=$f_out;var $28=$offset_rules;__Z11Write4BytesP7__sFILEi($27,$28);var $29=$f_out;var $call62=_fclose($29);var $30=HEAP32[((_translator)>>2)];var $31=$dict_name_addr;var $call63=__Z14LoadDictionaryP10TranslatorPKci($30,$31,0);var $32=HEAP32[((__ZL11error_count)>>2)];$retval=$32;;}}
var $33=$retval;STACKTOP=__stackBase__;return $33;return null;}
function __ZL9fopen_logPKcS0_($fname,$access){;var __label__;var $fname_addr;var $access_addr;var $f;$fname_addr=$fname;$access_addr=$access;var $0=$fname_addr;var $1=$access_addr;var $call=_fopen($0,$1);$f=$call;var $cmp=((($call))|0)==0;var $2=HEAP32[((__ZL5f_log)>>2)];var $cmp1=((($2))|0)!=0;var $or_cond=($cmp)&($cmp1);if($or_cond){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $3=HEAP32[((__ZL5f_log)>>2)];var $4=$access_addr;var $5=$fname_addr;var $call3=_fprintf($3,((__str115)&4294967295),allocate([$4,0,0,0,$5,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
var $6=$f;;return $6;return null;}
function __ZL22compile_dictlist_startv(){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $ix;var $p;var $p2=__stackBase__;$ix=0;var $0=$p2;;$for_body$2:while(1){var $1=$ix;var $arrayidx=((__ZL11hash_chains+$1*4)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];$p=$2;var $cmp11=((($2))|0)!=0;if($cmp11){__label__=2;;}else{__label__=3;;}
$while_body$$while_end$4:do{if(__label__==2){while(1){var $3=$p;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$3;$dest$=$0;$stop$=$src$+4;if(($dest$%4)==($src$%4)&&4>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $4=$p;;var $5=HEAP32[(($p2)>>2)];$p=$5;var $cmp1=((($5))|0)!=0;if($cmp1){__label__=2;continue;}else{__label__=3;break $while_body$$while_end$4;}}}}while(0);var $6=$ix;var $arrayidx2=((__ZL11hash_chains+$6*4)&4294967295);HEAP32[(($arrayidx2)>>2)]=0;var $7=$ix;var $arrayidx3=((__ZL11hash_counts+$7*4)&4294967295);HEAP32[(($arrayidx3)>>2)]=0;var $8=$ix;var $inc=((($8)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<1024;if($cmp){__label__=1;continue $for_body$2;}else{__label__=4;break $for_body$2;}}
STACKTOP=__stackBase__;return;return;}
function __ZL21compile_dictlist_filePKcS0_($path,$filename){var __stackBase__=STACKTOP;STACKTOP+=528;_memset(__stackBase__,0,528);var __label__;var $retval;var $path_addr;var $filename_addr;var $length;var $hash=__stackBase__;var $p;var $count;var $f_in;var $buf=__stackBase__+4;var $fname=__stackBase__+204;var $dict_line=__stackBase__+400;$path_addr=$path;$filename_addr=$filename;$count=0;HEAP8[(__ZL9text_mode_b)]=0;var $arraydecay=(($fname)&4294967295);var $0=$path_addr;var $1=$filename_addr;var $call=_sprintf($arraydecay,((__str104)&4294967295),allocate([$0,0,0,0,$1,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay1=(($fname)&4294967295);var $call2=_fopen($arraydecay1,((__str51703)&4294967295));$f_in=$call2;var $cmp=((($call2))|0)==0;if($cmp){__label__=1;;}else{__label__=3;;}
$if_then$$if_end9$2:do{if(__label__==1){var $arraydecay3=(($fname)&4294967295);var $2=$path_addr;var $3=$filename_addr;var $call4=_sprintf($arraydecay3,((__str47699)&4294967295),allocate([$2,0,0,0,$3,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay5=(($fname)&4294967295);var $call6=_fopen($arraydecay5,((__str51703)&4294967295));$f_in=$call6;var $cmp7=((($call6))|0)==0;if(!($cmp7)){__label__=3;break $if_then$$if_end9$2;}
$retval=-1;__label__=11;break $if_then$$if_end9$2;}}while(0);if(__label__==3){var $4=HEAP32[((__ZL5f_log)>>2)];var $arraydecay10=(($fname)&4294967295);var $call11=_fprintf($4,((__str78)&4294967295),allocate([$arraydecay10,0,0,0],["i8*",0,0,0],ALLOC_STACK));HEAP32[((__ZL7linenum)>>2)]=0;var $arraydecay12=(($buf)&4294967295);var $arraydecay15=(($buf)&4294967295);var $arraydecay16=(($dict_line)&4294967295);var $arraydecay33=(($dict_line)&4294967295);;$while_cond$7:while(1){var $5=$f_in;var $call13=_fgets($arraydecay12,200,$5);var $cmp14=((($call13))|0)!=0;if(!($cmp14)){__label__=10;break $while_cond$7;}
var $6=HEAP32[((__ZL7linenum)>>2)];var $inc=((($6)+1)&4294967295);HEAP32[((__ZL7linenum)>>2)]=$inc;var $call17=__ZL12compile_linePcS_Pi($arraydecay15,$arraydecay16,$hash);$length=$call17;var $7=$length;var $cmp18=((($7))|0)==0;if($cmp18){__label__=4;continue $while_cond$7;}
var $8=HEAP32[(($hash)>>2)];var $arrayidx=((__ZL11hash_counts+$8*4)&4294967295);var $9=HEAP32[(($arrayidx)>>2)];var $inc21=((($9)+1)&4294967295);HEAP32[(($arrayidx)>>2)]=$inc21;var $10=$length;var $add=((($10)+4)&4294967295);var $call22=_malloc($add);$p=$call22;var $11=$p;var $cmp23=((($11))|0)==0;if($cmp23){__label__=7;break $while_cond$7;}
var $16=$p;var $17=HEAP32[(($hash)>>2)];var $arrayidx31=((__ZL11hash_chains+$17*4)&4294967295);var $18=$arrayidx31;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$18;$dest$=$16;$stop$=$src$+4;if(($dest$%4)==($src$%4)&&4>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $19=$p;var $20=HEAP32[(($hash)>>2)];var $arrayidx32=((__ZL11hash_chains+$20*4)&4294967295);HEAP32[(($arrayidx32)>>2)]=$19;var $21=$p;var $add_ptr=(($21+4)&4294967295);var $22=$length;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay33;$dest$=$add_ptr;$stop$=$src$+$22;if(($dest$%4)==($src$%4)&&$22>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $23=$count;var $inc34=((($23)+1)&4294967295);$count=$inc34;__label__=4;continue $while_cond$7;}
$while_end$$if_then24$12:do{if(__label__==7){var $12=HEAP32[((__ZL5f_log)>>2)];var $cmp25=((($12))|0)!=0;if(!($cmp25)){__label__=10;break $while_end$$if_then24$12;}
var $13=HEAP32[((__ZL5f_log)>>2)];var $14=_fwrite(((__str106)&4294967295),22,1,$13);var $15=HEAP32[((__ZL11error_count)>>2)];var $inc28=((($15)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc28;;}}while(0);var $24=HEAP32[((__ZL5f_log)>>2)];var $25=$count;var $call35=_fprintf($24,((__str107)&4294967295),allocate([$25,0,0,0],["i32",0,0,0],ALLOC_STACK));var $26=$f_in;var $call36=_fclose($26);$retval=0;;}
STACKTOP=__stackBase__;return;return;}
function __ZL20compile_dictlist_endP7__sFILE($f_out){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $f_out_addr;var $hash;var $length;var $p=__stackBase__;$f_out_addr=$f_out;$hash=0;var $0=$p;;$for_body$2:while(1){var $1=$hash;var $arrayidx=((__ZL11hash_chains+$1*4)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];HEAP32[(($p)>>2)]=$2;var $3=$f_out_addr;var $call=_ftell($3);var $4=$hash;var $arrayidx2=((__ZL11hash_counts+$4*4)&4294967295);HEAP32[(($arrayidx2)>>2)]=$call;var $5=HEAP32[(($p)>>2)];var $cmp31=((($5))|0)!=0;if($cmp31){__label__=2;;}else{__label__=3;;}
$while_body$$while_end$4:do{if(__label__==2){while(1){var $6=HEAP32[(($p)>>2)];var $add_ptr=(($6+4)&4294967295);var $7=HEAP8[($add_ptr)];var $conv=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));$length=$conv;var $8=HEAP32[(($p)>>2)];var $add_ptr4=(($8+4)&4294967295);var $9=$length;var $10=$f_out_addr;var $call5=_fwrite($add_ptr4,$9,1,$10);var $11=HEAP32[(($p)>>2)];var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$11;$dest$=$0;$stop$=$src$+4;if(($dest$%4)==($src$%4)&&4>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $12=HEAP32[(($p)>>2)];var $cmp3=((($12))|0)!=0;if($cmp3){__label__=2;continue;}else{__label__=3;break $while_body$$while_end$4;}}}}while(0);var $13=$f_out_addr;var $call6=_fputc(0,$13);var $14=$hash;var $inc=((($14)+1)&4294967295);$hash=$inc;var $cmp1=((($inc))|0)<1024;if($cmp1){__label__=1;continue $for_body$2;}else{__label__=4;break $for_body$2;}}
STACKTOP=__stackBase__;return;return;}
function __ZL17compile_dictrulesP7__sFILES0_Pc($f_in,$f_out,$fname_temp){var __stackBase__=STACKTOP;STACKTOP+=11876;_memset(__stackBase__,0,11876);var __label__;var __lastLabel__=null;var $retval;var $f_in_addr;var $f_out_addr;var $fname_temp_addr;var $prule;var $p;var $ix;var $c=__stackBase__;var $gp;var $f_temp;var $n_rules=__stackBase__+4;var $count;var $different;var $wc=__stackBase__+8;var $prev_rgroup_name;var $char_code=__stackBase__+12;var $compile_mode;var $buf;var $buf1=__stackBase__+16;var $rules=__stackBase__+516;var $n_rgroups;var $n_groups3;var $rgroup=__stackBase__+8516;var $replace1;var $replace2;var $p123;$f_in_addr=$f_in;$f_out_addr=$f_out;$fname_temp_addr=$fname_temp;HEAP32[(($n_rules)>>2)]=0;$count=0;$compile_mode=0;$n_rgroups=0;$n_groups3=0;HEAP32[((__ZL7linenum)>>2)]=0;HEAP8[(((__ZL10group_name)&4294967295))]=0;var $0=$fname_temp_addr;var $call=__ZL9fopen_logPKcS0_($0,((__str79)&4294967295));$f_temp=$call;var $cmp=((($call))|0)==0;if($cmp){__label__=2;;}else{__label__=1;;}
if(__label__==2){$retval=1;;}
else if(__label__==1){var $arraydecay=(($buf1)&4294967295);var $arraydecay25=(($rules)&4294967295);var $1=$n_rules;;$for_cond$5:while(1){var $2=HEAP32[((__ZL7linenum)>>2)];var $inc=((($2)+1)&4294967295);HEAP32[((__ZL7linenum)>>2)]=$inc;var $3=$f_in_addr;var $call1=_fgets($arraydecay,500,$3);$buf=$call1;var $cmp2=((($call1))|0)!=0;if($cmp2){__label__=4;;}else{__label__=10;;}
$if_then3$$if_then16$7:do{if(__label__==4){var $4=$buf;var $call4=_strstr($4,((__str82734)&4294967295));$p=$call4;var $cmp5=((($call4))|0)!=0;if($cmp5){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $5=$p;HEAP8[($5)]=0;;}
var $6=$buf;var $arrayidx=(($6)&4294967295);var $7=HEAP8[($arrayidx)];var $conv=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $cmp8=((($conv))|0)==13;if($cmp8){__lastLabel__=6;__label__=7;;}else{__lastLabel__=6;__label__=8;;}
if(__label__==7){var $8=$buf;var $incdec_ptr=(($8+1)&4294967295);$buf=$incdec_ptr;__lastLabel__=7;;}
var $9=__lastLabel__==6?$6:($incdec_ptr);var $cmp12=((($9))|0)==0;if($cmp12){__label__=10;break $if_then3$$if_then16$7;}
var $10=$buf;var $arrayidx13=(($10)&4294967295);var $11=HEAP8[($arrayidx13)];var $conv14=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $cmp15=((($conv14))|0)==46;if($cmp15){__label__=10;break $if_then3$$if_then16$7;}
var $69=$compile_mode;if($69==1){__label__=44;;}
else if($69==2){__label__=47;;}
else{__label__=3;continue $for_cond$5;}
if(__label__==44){var $70=$buf;var $call114=__ZL12compile_rulePc($70);$prule=$call114;var $71=$prule;var $cmp115=((($71))|0)!=0;if(!($cmp115)){__label__=3;continue $for_cond$5;}
var $72=HEAP32[(($n_rules)>>2)];var $cmp117=((($72))|0)<2000;if(!($cmp117)){__label__=3;continue $for_cond$5;}
var $73=$prule;var $74=HEAP32[(($n_rules)>>2)];var $inc119=((($74)+1)&4294967295);HEAP32[(($n_rules)>>2)]=$inc119;var $arrayidx120=(($rules+$74*4)&4294967295);HEAP32[(($arrayidx120)>>2)]=$73;__label__=3;continue $for_cond$5;}
else if(__label__==47){var $75=$buf;$p123=$75;$replace1=0;$replace2=0;var $76=$p123;var $77=HEAP8[($76)];var $conv1254=(tempInt=(($77)),(tempInt>=128?tempInt-256:tempInt));var $call1265=__Z8isspace2j($conv1254);var $tobool6=((($call1265))|0)!=0;if($tobool6){__label__=48;;}else{__label__=49;;}
$while_body127$$while_end129$22:do{if(__label__==48){while(1){var $78=$p123;var $incdec_ptr128=(($78+1)&4294967295);$p123=$incdec_ptr128;var $79=$p123;var $80=HEAP8[($79)];var $conv125=(tempInt=(($80)),(tempInt>=128?tempInt-256:tempInt));var $call126=__Z8isspace2j($conv125);var $tobool=((($call126))|0)!=0;if($tobool){__label__=48;continue;}else{__label__=49;break $while_body127$$while_end129$22;}}}}while(0);$ix=0;var $81=$p123;var $82=HEAPU8[($81)];var $conv1317=((($82))&255);var $cmp1328=((($conv1317))|0)>32;if($cmp1328){__label__=50;;}else{__label__=51;;}
$while_body133$$while_cond138_loopexit$26:do{if(__label__==50){while(1){var $83=$p123;var $call134=__Z7utf8_inPiPKc($c,$83);var $84=$p123;var $add_ptr=(($84+$call134)&4294967295);$p123=$add_ptr;var $85=HEAP32[(($c)>>2)];var $86=$ix;var $shl=($85)<<($86);var $87=$replace1;var $add135=((($87)+($shl))&4294967295);$replace1=$add135;var $88=$ix;var $add136=((($88)+16)&4294967295);$ix=$add136;var $89=$p123;var $90=HEAPU8[($89)];var $conv131=((($90))&255);var $cmp132=((($conv131))|0)>32;if($cmp132){__label__=50;continue;}else{__label__=51;break $while_body133$$while_cond138_loopexit$26;}}}}while(0);var $91=$p123;var $92=HEAP8[($91)];var $conv1399=(tempInt=(($92)),(tempInt>=128?tempInt-256:tempInt));var $call14010=__Z8isspace2j($conv1399);var $tobool14111=((($call14010))|0)!=0;if($tobool14111){__label__=52;;}else{__label__=53;;}
$while_body142$$while_end144$30:do{if(__label__==52){while(1){var $93=$p123;var $incdec_ptr143=(($93+1)&4294967295);$p123=$incdec_ptr143;var $94=$p123;var $95=HEAP8[($94)];var $conv139=(tempInt=(($95)),(tempInt>=128?tempInt-256:tempInt));var $call140=__Z8isspace2j($conv139);var $tobool141=((($call140))|0)!=0;if($tobool141){__label__=52;continue;}else{__label__=53;break $while_body142$$while_end144$30;}}}}while(0);$ix=0;var $96=$p123;var $97=HEAPU8[($96)];var $conv14612=((($97))&255);var $cmp14713=((($conv14612))|0)>32;if($cmp14713){__label__=54;;}else{__label__=55;;}
$while_body148$$while_end154$34:do{if(__label__==54){while(1){var $98=$p123;var $call149=__Z7utf8_inPiPKc($c,$98);var $99=$p123;var $add_ptr150=(($99+$call149)&4294967295);$p123=$add_ptr150;var $100=HEAP32[(($c)>>2)];var $101=$ix;var $shl151=($100)<<($101);var $102=$replace2;var $add152=((($102)+($shl151))&4294967295);$replace2=$add152;var $103=$ix;var $add153=((($103)+16)&4294967295);$ix=$add153;var $104=$p123;var $105=HEAPU8[($104)];var $conv146=((($105))&255);var $cmp147=((($conv146))|0)>32;if($cmp147){__label__=54;continue;}else{__label__=55;break $while_body148$$while_end154$34;}}}}while(0);var $106=$replace1;var $cmp155=((($106))|0)!=0;if(!($cmp155)){__label__=3;continue $for_cond$5;}
var $107=$f_out_addr;var $108=$replace1;__Z11Write4BytesP7__sFILEi($107,$108);var $109=$f_out_addr;var $110=$replace2;__Z11Write4BytesP7__sFILEi($109,$110);__label__=3;continue $for_cond$5;}}}while(0);var $12=HEAP32[(($n_rules)>>2)];var $cmp17=((($12))|0)>0;if($cmp17){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $13=$n_rgroups;var $arrayidx19=(($rgroup+$13*28)&4294967295);var $name=(($arrayidx19)&4294967295);var $arraydecay20=(($name)&4294967295);var $call21=_strcpy($arraydecay20,((__ZL10group_name)&4294967295));var $14=HEAP32[((__ZL9group3_ix)>>2)];var $15=$n_rgroups;var $arrayidx22=(($rgroup+$15*28)&4294967295);var $group3_ix=(($arrayidx22+24)&4294967295);HEAP32[(($group3_ix)>>2)]=$14;var $16=$f_temp;var $call23=_ftell($16);var $17=$n_rgroups;var $arrayidx24=(($rgroup+$17*28)&4294967295);var $start=(($arrayidx24+16)&4294967295);HEAP32[(($start)>>2)]=$call23;var $18=$f_temp;var $19=HEAP32[(($n_rules)>>2)];__ZL17output_rule_groupP7__sFILEiPPcS1_($18,$19,$arraydecay25);var $20=$f_temp;var $call26=_ftell($20);var $21=$n_rgroups;var $arrayidx27=(($rgroup+$21*28)&4294967295);var $start28=(($arrayidx27+16)&4294967295);var $22=HEAP32[(($start28)>>2)];var $sub=((($call26)-($22))&4294967295);var $23=$n_rgroups;var $arrayidx29=(($rgroup+$23*28)&4294967295);var $length=(($arrayidx29+20)&4294967295);HEAP32[(($length)>>2)]=$sub;var $24=$n_rgroups;var $inc30=((($24)+1)&4294967295);$n_rgroups=$inc30;var $25=HEAP32[(($n_rules)>>2)];var $26=$count;var $add=((($26)+($25))&4294967295);$count=$add;;}
HEAP32[(($n_rules)>>2)]=0;var $27=$compile_mode;var $cmp32=((($27))|0)==2;if($cmp32){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $28=$f_out_addr;var $call34=_fwrite($1,1,4,$28);$compile_mode=0;;}
var $29=$buf;var $cmp36=((($29))|0)==0;if($cmp36){__label__=57;break $for_cond$5;}
var $30=$buf;var $call39=_memcmp($30,((__str81)&4294967295),2);var $cmp40=((($call39))|0)==0;var $31=$buf;if($cmp40){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $arrayidx42=(($31+2)&4294967295);var $32=$f_out_addr;__ZL19compile_lettergroupPcP7__sFILE($arrayidx42,$32);__label__=3;continue $for_cond$5;}
else if(__label__==17){var $call45=_memcmp($31,((__str82)&4294967295),8);var $cmp46=((($call45))|0)==0;if($cmp46){__label__=18;;}else{__label__=20;;}
$if_then47$$if_end53$50:do{if(__label__==18){$compile_mode=2;var $33=$f_out_addr;var $call48=_fputc(6,$33);var $34=$f_out_addr;var $call49=_fputc(20,$34);var $35=$f_out_addr;var $call5014=_ftell($35);var $and15=($call5014)&3;var $cmp5116=((($and15))|0)!=0;if(!($cmp5116)){__label__=20;break $if_then47$$if_end53$50;}
while(1){var $36=$f_out_addr;var $call52=_fputc(0,$36);var $37=$f_out_addr;var $call50=_ftell($37);var $and=($call50)&3;var $cmp51=((($and))|0)!=0;if($cmp51){__label__=19;continue;}else{__label__=20;break $if_then47$$if_end53$50;}}}}while(0);var $38=$buf;var $call54=_memcmp($38,((__str83)&4294967295),6);var $cmp55=((($call54))|0)==0;if(!($cmp55)){__label__=3;continue $for_cond$5;}
$compile_mode=1;var $39=$buf;var $arrayidx57=(($39+6)&4294967295);$p=$arrayidx57;;$while_cond58$56:while(1){var $40=$p;var $arrayidx59=(($40)&4294967295);var $41=HEAPU8[($arrayidx59)];var $conv60=((($41))&255);var $cmp61=((($conv60))|0)==32;if($cmp61){__label__=24;;}else{__label__=23;;}
if(__label__==23){var $42=$p;var $arrayidx62=(($42)&4294967295);var $43=HEAPU8[($arrayidx62)];var $conv63=((($43))&255);var $cmp64=((($conv63))|0)==9;if(!($cmp64)){__label__=25;break $while_cond58$56;}}
var $44=$p;var $incdec_ptr66=(($44+1)&4294967295);$p=$incdec_ptr66;__label__=22;continue $while_cond58$56;}
$ix=0;;$while_cond68$62:while(1){var $45=$p;var $46=HEAPU8[($45)];var $conv69=((($46))&255);var $cmp70=((($conv69))|0)>32;if(!($cmp70)){__label__=29;break $while_cond68$62;}
var $47=$ix;var $cmp71=((($47))|0)<12;if(!($cmp71)){__label__=29;break $while_cond68$62;}
var $48=$p;var $incdec_ptr73=(($48+1)&4294967295);$p=$incdec_ptr73;var $49=HEAP8[($48)];var $50=$ix;var $inc74=((($50)+1)&4294967295);$ix=$inc74;var $arrayidx75=((__ZL10group_name+$50)&4294967295);HEAP8[($arrayidx75)]=$49;__label__=26;continue $while_cond68$62;}
var $51=$ix;var $arrayidx77=((__ZL10group_name+$51)&4294967295);HEAP8[($arrayidx77)]=0;HEAP32[((__ZL9group3_ix)>>2)]=0;var $call78=_sscanf(((__ZL10group_name)&4294967295),((__str84)&4294967295),allocate([$char_code,0,0,0],["i32*",0,0,0],ALLOC_STACK));var $cmp79=((($call78))|0)==1;if($cmp79){__label__=30;;}else{__label__=33;;}
$if_then80$$if_else$67:do{if(__label__==30){$p=((__ZL10group_name)&4294967295);var $52=HEAPU32[(($char_code)>>2)];var $cmp81=((($52))>>>0)>256;if($cmp81){__label__=31;;}else{__label__=32;;}
if(__label__==31){var $53=HEAPU32[(($char_code)>>2)];var $shr=($53)>>>8;var $conv83=((($shr))&255);var $54=$p;var $incdec_ptr84=(($54+1)&4294967295);$p=$incdec_ptr84;HEAP8[($54)]=$conv83;;}
var $55=HEAP32[(($char_code)>>2)];var $conv86=((($55))&255);var $56=$p;var $incdec_ptr87=(($56+1)&4294967295);$p=$incdec_ptr87;HEAP8[($56)]=$conv86;var $57=$p;HEAP8[($57)]=0;__label__=37;break $if_then80$$if_else$67;}
else if(__label__==33){var $58=HEAP32[((_translator)>>2)];var $letter_bits_offset=(($58+964)&4294967295);var $59=HEAP32[(($letter_bits_offset)>>2)];var $cmp88=((($59))|0)>0;if(!($cmp88)){__label__=37;break $if_then80$$if_else$67;}
var $call90=__Z7utf8_inPiPKc($wc,((__ZL10group_name)&4294967295));var $60=HEAP32[(($wc)>>2)];var $61=HEAP32[((_translator)>>2)];var $letter_bits_offset91=(($61+964)&4294967295);var $62=HEAP32[(($letter_bits_offset91)>>2)];var $sub92=((($60)-($62))&4294967295);$ix=$sub92;var $cmp93=((($sub92))|0)>=0;if(!($cmp93)){__label__=37;break $if_then80$$if_else$67;}
var $63=$ix;var $cmp94=((($63))|0)<128;if(!($cmp94)){__label__=37;break $if_then80$$if_else$67;}
var $64=$ix;var $add96=((($64)+1)&4294967295);HEAP32[((__ZL9group3_ix)>>2)]=$add96;__lastLabel__=36;__label__=38;break $if_then80$$if_else$67;}}while(0);if(__label__==37){var $_pr=HEAP32[((__ZL9group3_ix)>>2)];__lastLabel__=37;;}
var $65=__lastLabel__==37?$_pr:($add96);var $cmp100=((($65))|0)==0;if(!($cmp100)){__label__=3;continue $for_cond$5;}
var $call102=_strlen(((__ZL10group_name)&4294967295));var $cmp103=((($call102))>>>0)>2;if(!($cmp103)){__label__=3;continue $for_cond$5;}
var $call105=__Z7utf8_inPiPKc($c,((__ZL10group_name)&4294967295));var $cmp106=((($call105))|0)<2;if($cmp106){__label__=41;;}else{__label__=42;;}
if(__label__==41){var $66=HEAP32[((__ZL5f_log)>>2)];var $67=HEAP32[((__ZL7linenum)>>2)];var $call108=_fprintf($66,((__str85)&4294967295),allocate([$67,0,0,0],["i32",0,0,0],ALLOC_STACK));var $68=HEAP32[((__ZL11error_count)>>2)];var $inc109=((($68)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc109;;}
HEAP8[(((__ZL10group_name+2)&4294967295))]=0;__label__=3;continue $for_cond$5;}}
var $111=$f_temp;var $call158=_fclose($111);var $arraydecay159=(($rgroup)&4294967295);var $112=$arraydecay159;var $113=$n_rgroups;_qsort($112,$113,28,2);var $114=$fname_temp_addr;var $call160=_fopen($114,((__str18429)&4294967295));$f_temp=$call160;var $cmp161=((($call160))|0)==0;if($cmp161){__label__=58;;}else{__label__=59;;}
if(__label__==58){$retval=2;;}
else if(__label__==59){$prev_rgroup_name=((__str15397)&4294967295);$gp=0;var $115=$gp;var $116=$n_rgroups;var $cmp1653=((($115))|0)<((($116))|0);if($cmp1653){__label__=60;;}else{__label__=70;;}
$for_body$$for_end210$88:do{if(__label__==60){$for_body$89:while(1){var $117=$f_temp;var $118=$gp;var $arrayidx166=(($rgroup+$118*28)&4294967295);var $start167=(($arrayidx166+16)&4294967295);var $119=HEAP32[(($start167)>>2)];var $call168=_fseek($117,$119,0);var $120=$gp;var $arrayidx169=(($rgroup+$120*28)&4294967295);var $name170=(($arrayidx169)&4294967295);var $arraydecay171=(($name170)&4294967295);var $121=$prev_rgroup_name;var $call172=_strcmp($arraydecay171,$121);$different=$call172;var $cmp173=((($call172))|0)!=0;if($cmp173){__label__=61;;}else{__label__=67;;}
if(__label__==61){var $122=$gp;var $cmp175=((($122))|0)>0;if($cmp175){__label__=62;;}else{__label__=63;;}
if(__label__==62){var $123=$f_out_addr;var $call177=_fputc(7,$123);;}
var $124=$f_out_addr;var $call179=_fputc(6,$124);var $125=$gp;var $arrayidx180=(($rgroup+$125*28)&4294967295);var $group3_ix181=(($arrayidx180+24)&4294967295);var $126=HEAP32[(($group3_ix181)>>2)];var $cmp182=((($126))|0)!=0;if($cmp182){__label__=64;;}else{__label__=65;;}
if(__label__==64){var $127=$n_groups3;var $inc184=((($127)+1)&4294967295);$n_groups3=$inc184;var $128=$f_out_addr;var $call185=_fputc(1,$128);var $129=$gp;var $arrayidx186=(($rgroup+$129*28)&4294967295);var $group3_ix187=(($arrayidx186+24)&4294967295);var $130=HEAP32[(($group3_ix187)>>2)];var $131=$f_out_addr;var $call188=_fputc($130,$131);;}
else if(__label__==65){var $132=$f_out_addr;var $133=$gp;var $arrayidx190=(($rgroup+$133*28)&4294967295);var $name191=(($arrayidx190)&4294967295);var $arraydecay192=(($name191)&4294967295);$prev_rgroup_name=$arraydecay192;var $fputs=_fputs($arraydecay192,$132);;}
var $134=$f_out_addr;var $call195=_fputc(0,$134);;}
var $135=$gp;var $arrayidx197=(($rgroup+$135*28)&4294967295);var $length198=(($arrayidx197+20)&4294967295);var $136=HEAP32[(($length198)>>2)];$ix=$136;var $cmp2002=((($136))|0)>0;if($cmp2002){__label__=68;;}else{__label__=69;;}
$for_body201$$for_end204$101:do{if(__label__==68){while(1){var $137=$f_temp;var $call202=_fgetc($137);HEAP32[(($c)>>2)]=$call202;var $138=HEAP32[(($c)>>2)];var $139=$f_out_addr;var $call203=_fputc($138,$139);var $140=$ix;var $dec=((($140)-1)&4294967295);$ix=$dec;var $cmp200=((($dec))|0)>0;if($cmp200){__label__=68;continue;}else{__label__=69;break $for_body201$$for_end204$101;}}}}while(0);var $141=$gp;var $inc209=((($141)+1)&4294967295);$gp=$inc209;var $142=$gp;var $143=$n_rgroups;var $cmp165=((($142))|0)<((($143))|0);if($cmp165){__label__=60;continue $for_body$89;}else{__label__=70;break $for_body$$for_end210$88;}}}}while(0);var $144=$f_out_addr;var $call211=_fputc(7,$144);var $145=$f_out_addr;var $call212=_fputc(0,$145);var $146=$f_temp;var $call213=_fclose($146);var $147=$fname_temp_addr;var $call214=_remove($147);var $148=HEAP32[((__ZL5f_log)>>2)];var $149=$count;var $150=$n_rgroups;var $151=$n_groups3;var $call215=_fprintf($148,((__str89)&4294967295),allocate([$149,0,0,0,$150,0,0,0,$151,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STACK));$retval=0;;}}
STACKTOP=__stackBase__;return;return;}
function __ZL17output_rule_groupP7__sFILEiPPcS1_($f_out,$n_rules,$rules){var __stackBase__=STACKTOP;STACKTOP+=512;_memset(__stackBase__,0,512);var __label__;var $f_out_addr;var $n_rules_addr;var $rules_addr;var $name_addr;var $ix;var $len1;var $len2;var $len_name;var $p;var $p2;var $p3;var $common;var $nextchar_count=__stackBase__;$f_out_addr=$f_out;$n_rules_addr=$n_rules;$rules_addr=$rules;$name_addr=((__ZL10group_name)&4294967295);var $arraydecay=(($nextchar_count)&4294967295);var $0=$arraydecay;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$0;$stop$=$dest$+512;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $1=$name_addr;var $call=_strlen($1);$len_name=$call;$common=((__str13643)&4294967295);var $2=$rules_addr;var $3=$2;var $4=$n_rules_addr;_qsort($3,$4,4,4);var $5=$name_addr;var $call1=_strcmp($5,((__str103)&4294967295));var $cmp=((($call1))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$len_name=0;;}
$ix=0;var $6=$ix;var $7=$n_rules_addr;var $cmp21=((($6))|0)<((($7))|0);if($cmp21){__label__=3;;}else{__label__=11;;}
$for_body$$for_end$5:do{if(__label__==3){$for_body$6:while(1){var $8=$ix;var $9=$rules_addr;var $arrayidx=(($9+4*$8)&4294967295);var $10=HEAP32[(($arrayidx)>>2)];$p=$10;var $11=$p;var $call3=_strlen($11);var $add=((($call3)+1)&4294967295);$len1=$add;var $12=$len1;var $13=$p;var $arrayidx4=(($13+$12)&4294967295);$p3=$arrayidx4;var $14=$p3;var $15=$len_name;var $add_ptr=(($14+$15)&4294967295);$p2=$add_ptr;var $16=$p2;var $call5=_strlen($16);$len2=$call5;var $17=$p2;var $arrayidx6=(($17)&4294967295);var $18=HEAPU8[($arrayidx6)];var $idxprom=((($18))&255);var $arrayidx7=(($nextchar_count+$idxprom*2)&4294967295);var $19=HEAP16[(($arrayidx7)>>1)];var $inc=((($19)+1)&65535);HEAP16[(($arrayidx7)>>1)]=$inc;var $20=$common;var $arrayidx8=(($20)&4294967295);var $21=HEAP8[($arrayidx8)];var $conv=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));var $cmp9=((($conv))|0)!=0;if($cmp9){__label__=4;;}else{__label__=6;;}
$land_lhs_true$$if_else$8:do{if(__label__==4){var $22=$p;var $23=$common;var $call10=_strcmp($22,$23);var $cmp11=((($call10))|0)==0;if(!($cmp11)){__label__=6;break $land_lhs_true$$if_else$8;}
var $24=$p2;var $25=$len2;var $26=$f_out_addr;var $call13=_fwrite($24,$25,1,$26);var $27=$f_out_addr;var $call14=_fputc(0,$27);__label__=10;break $land_lhs_true$$if_else$8;}}while(0);if(__label__==6){var $28=$ix;var $29=$n_rules_addr;var $sub=((($29)-1)&4294967295);var $cmp15=((($28))|0)<((($sub))|0);if($cmp15){__label__=7;;}else{__label__=9;;}
$land_lhs_true16$$if_end24$13:do{if(__label__==7){var $30=$p;var $31=$ix;var $add17=((($31)+1)&4294967295);var $32=$rules_addr;var $arrayidx18=(($32+4*$add17)&4294967295);var $33=HEAP32[(($arrayidx18)>>2)];var $call19=_strcmp($30,$33);var $cmp20=((($call19))|0)==0;if(!($cmp20)){__label__=9;break $land_lhs_true16$$if_end24$13;}
var $34=$ix;var $35=$rules_addr;var $arrayidx22=(($35+4*$34)&4294967295);var $36=HEAP32[(($arrayidx22)>>2)];$common=$36;var $37=$f_out_addr;var $call23=_fputc(4,$37);;}}while(0);var $38=$p2;var $39=$len2;var $40=$f_out_addr;var $call25=_fwrite($38,$39,1,$40);var $41=$f_out_addr;var $call26=_fputc(3,$41);var $42=$p;var $43=$len1;var $44=$f_out_addr;var $call27=_fwrite($42,$43,1,$44);;}
var $45=$ix;var $inc29=((($45)+1)&4294967295);$ix=$inc29;var $46=$ix;var $47=$n_rules_addr;var $cmp2=((($46))|0)<((($47))|0);if($cmp2){__label__=3;continue $for_body$6;}else{__label__=11;break $for_body$$for_end$5;}}}}while(0);STACKTOP=__stackBase__;return;return;}
function __ZL19compile_lettergroupPcP7__sFILE($input,$f_out){var __stackBase__=STACKTOP;STACKTOP+=1000;_memset(__stackBase__,0,1000);var __label__;var __lastLabel__=null;var $retval;var $input_addr;var $f_out_addr;var $p;var $p_start;var $group;var $ix;var $n_items;var $length;var $max_length;var $items=__stackBase__;var $item_length=__stackBase__+800;$input_addr=$input;$f_out_addr=$f_out;$max_length=0;var $0=$input_addr;$p=$0;var $1=$p;var $arrayidx=(($1)&4294967295);var $2=HEAP8[($arrayidx)];var $conv=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp=((($conv)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call=((($isdigit))&1);var $tobool=((($call))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
$lor_lhs_false$$if_then$2:do{if(__label__==1){var $3=$p;var $arrayidx1=(($3+1)&4294967295);var $4=HEAP8[($arrayidx1)];var $conv2=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp1=((($conv2)-48)&4294967295);var $isdigit2=((($isdigittmp1))>>>0)<10;var $call3=((($isdigit2))&1);var $tobool4=((($call3))|0)!=0;if(!($tobool4)){__label__=2;break $lor_lhs_false$$if_then$2;}
var $8=$p;var $arrayidx6=(($8)&4294967295);var $call7=_atoi($arrayidx6);$group=$call7;var $9=$group;var $cmp=((($9))|0)>=26;if($cmp){__label__=5;;}else{__label__=4;;}
if(__label__==5){var $12=HEAP32[((__ZL5f_log)>>2)];var $13=HEAP32[((__ZL7linenum)>>2)];var $call9=_fprintf($12,((__str101)&4294967295),allocate([$13,0,0,0,25,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $14=HEAP32[((__ZL11error_count)>>2)];var $inc10=((($14)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc10;$retval=1;__label__=26;break $lor_lhs_false$$if_then$2;}
else if(__label__==4){var $10=$p;var $11=HEAP8[($10)];var $conv1210=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $call1311=__Z8isspace2j($conv1210);var $tobool1412=((($call1311))|0)!=0;var $lnot13=($tobool1412)^1;if($lnot13){__label__=6;;}else{__label__=7;;}
$while_body$$while_end$8:do{if(__label__==6){while(1){var $15=$p;var $incdec_ptr=(($15+1)&4294967295);$p=$incdec_ptr;var $16=$p;var $17=HEAP8[($16)];var $conv12=(tempInt=(($17)),(tempInt>=128?tempInt-256:tempInt));var $call13=__Z8isspace2j($conv12);var $tobool14=((($call13))|0)!=0;var $lnot=($tobool14)^1;if($lnot){__label__=6;continue;}else{__label__=7;break $while_body$$while_end$8;}}}}while(0);var $18=$f_out_addr;var $call15=_fputc(6,$18);var $19=$f_out_addr;var $call16=_fputc(18,$19);var $20=$group;var $add=((($20)+65)&4294967295);var $21=$f_out_addr;var $call17=_fputc($add,$21);var $22=$group;var $arrayidx18=((__ZL19letterGroupsDefined+$22)&4294967295);var $23=HEAP8[($arrayidx18)];var $conv19=(tempInt=(($23)),(tempInt>=128?tempInt-256:tempInt));var $cmp20=((($conv19))|0)!=0;if($cmp20){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $24=HEAP32[((__ZL5f_log)>>2)];var $25=HEAP32[((__ZL7linenum)>>2)];var $26=$group;var $call22=_fprintf($24,((__str102)&4294967295),allocate([$25,0,0,0,$26,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $27=HEAP32[((__ZL11error_count)>>2)];var $inc23=((($27)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc23;;}
var $28=$group;var $arrayidx25=((__ZL19letterGroupsDefined+$28)&4294967295);HEAP8[($arrayidx25)]=1;$n_items=0;__lastLabel__=9;;$while_cond26$15:while(1){var $29=__lastLabel__==18?$_pr:(0);var $cmp27=((($29))|0)<200;if(!($cmp27)){__label__=19;break $while_cond26$15;}
var $30=$p;var $31=HEAP8[($30)];var $conv306=(tempInt=(($31)),(tempInt>=128?tempInt-256:tempInt));var $call317=__Z8isspace2j($conv306);var $tobool328=((($call317))|0)!=0;var $32=$p;if($tobool328){__lastLabel__=11;__label__=12;;}else{__lastLabel__=11;__label__=13;;}
$while_body33$$while_end35$18:do{if(__label__==12){while(1){var $33=__lastLabel__==12?$36:($32);var $incdec_ptr34=(($33+1)&4294967295);$p=$incdec_ptr34;var $34=$p;var $35=HEAP8[($34)];var $conv30=(tempInt=(($35)),(tempInt>=128?tempInt-256:tempInt));var $call31=__Z8isspace2j($conv30);var $tobool32=((($call31))|0)!=0;var $36=$p;if($tobool32){__lastLabel__=12;__label__=12;continue;}else{__lastLabel__=12;__label__=13;break $while_body33$$while_end35$18;}}}}while(0);var $_lcssa=__lastLabel__==11?$32:($36);var $37=HEAP8[($_lcssa)];var $conv36=(tempInt=(($37)),(tempInt>=128?tempInt-256:tempInt));var $cmp37=((($conv36))|0)==0;if($cmp37){__label__=19;break $while_cond26$15;}
var $38=$p;$p_start=$38;var $39=$n_items;var $arrayidx40=(($items+$39*4)&4294967295);HEAP32[(($arrayidx40)>>2)]=$38;;while(1){var $40=$p;var $41=HEAP8[($40)];var $conv42=(tempInt=(($41)),(tempInt>=128?tempInt-256:tempInt));var $and=($conv42)&255;var $cmp43=((($and))|0)>32;var $42=$p;var $incdec_ptr45=(($42+1)&4294967295);$p=$incdec_ptr45;if($cmp43){__label__=15;continue;}else{__label__=16;break;}}
HEAP8[($42)]=0;var $43=$p;var $44=$p_start;var $sub_ptr_lhs_cast=($43);var $sub_ptr_rhs_cast=($44);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$length=$sub_ptr_sub;var $45=$length;var $46=$max_length;var $cmp48=((($45))|0)>((($46))|0);if($cmp48){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $47=$length;$max_length=$47;;}
var $48=$length;var $conv51=((($48))&255);var $49=$n_items;var $inc52=((($49)+1)&4294967295);$n_items=$inc52;var $arrayidx53=(($item_length+$49)&4294967295);HEAP8[($arrayidx53)]=$conv51;var $_pr=$n_items;__lastLabel__=18;__label__=10;continue $while_cond26$15;}
var $_pr3=$max_length;var $cmp565=((($_pr3))|0)>1;if($cmp565){__label__=20;;}else{__label__=25;;}
$while_body57$$while_end67$30:do{if(__label__==20){$while_body57$31:while(1){$ix=0;var $50=$ix;var $51=$n_items;var $cmp584=((($50))|0)<((($51))|0);if($cmp584){__label__=21;;}else{__label__=24;;}
$for_body$$for_end$33:do{if(__label__==21){while(1){var $52=$ix;var $arrayidx59=(($item_length+$52)&4294967295);var $53=HEAP8[($arrayidx59)];var $conv60=(tempInt=(($53)),(tempInt>=128?tempInt-256:tempInt));var $54=$max_length;var $cmp61=((($conv60))|0)==((($54))|0);if($cmp61){__label__=22;;}else{__label__=23;;}
if(__label__==22){var $55=$ix;var $arrayidx63=(($items+$55*4)&4294967295);var $56=HEAP32[(($arrayidx63)>>2)];var $57=$max_length;var $58=$f_out_addr;var $call64=_fwrite($56,1,$57,$58);;}
var $59=$ix;var $inc66=((($59)+1)&4294967295);$ix=$inc66;var $60=$ix;var $61=$n_items;var $cmp58=((($60))|0)<((($61))|0);if($cmp58){__label__=21;continue;}else{__label__=24;break $for_body$$for_end$33;}}}}while(0);var $62=$max_length;var $dec=((($62)-1)&4294967295);$max_length=$dec;var $cmp56=((($dec))|0)>1;if($cmp56){__label__=20;continue $while_body57$31;}else{__label__=25;break $while_body57$$while_end67$30;}}}}while(0);var $63=$f_out_addr;var $call68=_fputc(7,$63);$retval=0;__label__=26;break $lor_lhs_false$$if_then$2;}}}while(0);if(__label__==2){var $5=HEAP32[((__ZL5f_log)>>2)];var $6=HEAP32[((__ZL7linenum)>>2)];var $call5=_fprintf($5,((__str100)&4294967295),allocate([$6,0,0,0],["i32",0,0,0],ALLOC_STACK));var $7=HEAP32[((__ZL11error_count)>>2)];var $inc=((($7)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc;$retval=1;;}
STACKTOP=__stackBase__;return;return;}
function __ZL12compile_rulePc($input){var __stackBase__=STACKTOP;STACKTOP+=244;_memset(__stackBase__,0,244);var __label__;var $retval;var $input_addr;var $ix;var $c;var $wc=__stackBase__;var $p;var $prule;var $len;var $len_name;var $start;var $state=__stackBase__+4;var $finish;var $pre_bracket;var $buf=__stackBase__+8;var $output=__stackBase__+88;var $bad_phoneme=__stackBase__+240;$input_addr=$input;HEAP32[(($state)>>2)]=2;$finish=0;$pre_bracket=0;var $arrayidx=(($buf)&4294967295);HEAP8[($arrayidx)]=0;HEAP8[(((__ZL9rule_cond)&4294967295))]=0;HEAP8[(((__ZL8rule_pre)&4294967295))]=0;HEAP8[(((__ZL9rule_post)&4294967295))]=0;HEAP8[(((__ZL10rule_match)&4294967295))]=0;HEAP8[(((__ZL13rule_phonemes)&4294967295))]=0;var $arraydecay=(($buf)&4294967295);$p=$arraydecay;$ix=0;var $0=$finish;var $cmp2=((($0))|0)==0;if($cmp2){__label__=1;;}else{__label__=13;;}
$for_body_lr_ph$$for_end$2:do{if(__label__==1){var $arraydecay3=(($buf)&4294967295);var $arraydecay4=(($buf)&4294967295);var $arraydecay6=(($buf)&4294967295);var $arraydecay7=(($buf)&4294967295);var $arraydecay12=(($buf)&4294967295);var $arraydecay14=(($buf)&4294967295);var $arraydecay15=(($buf)&4294967295);;$for_body$4:while(1){var $1=$ix;var $2=$input_addr;var $arrayidx1=(($2+$1)&4294967295);var $3=HEAP8[($arrayidx1)];$c=$3;var $4=$ix;var $5=$input_addr;var $arrayidx2=(($5+$4)&4294967295);var $6=HEAPU8[($arrayidx2)];$c=$6;var $conv=((($6))&255);if($conv==41){__label__=3;;}
else if($conv==40){__label__=4;;}
else if($conv==10){__label__=6;break $for_body$4;}
else if($conv==13){__label__=6;break $for_body$4;}
else if($conv==0){__label__=6;break $for_body$4;}
else if($conv==9){__label__=7;;}
else if($conv==32){__label__=7;;}
else if($conv==63){__label__=8;;}
else{__label__=11;;}
$sw_default$$sw_bb$$sw_bb5$$sw_bb13$$sw_bb16$6:do{if(__label__==11){var $21=$c;var $22=$p;var $incdec_ptr20=(($22+1)&4294967295);$p=$incdec_ptr20;HEAP8[($22)]=$21;;}
else if(__label__==3){var $7=$p;HEAP8[($7)]=0;HEAP32[(($state)>>2)]=1;$pre_bracket=1;__ZL16copy_rule_stringPcRi($arraydecay3,$state);$p=$arraydecay4;;}
else if(__label__==4){var $8=$p;HEAP8[($8)]=0;HEAP32[(($state)>>2)]=2;__ZL16copy_rule_stringPcRi($arraydecay6,$state);HEAP32[(($state)>>2)]=3;$p=$arraydecay7;var $9=$ix;var $add=((($9)+1)&4294967295);var $10=$input_addr;var $arrayidx8=(($10+$add)&4294967295);var $11=HEAP8[($arrayidx8)];var $conv9=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $cmp10=((($conv9))|0)==32;if(!($cmp10)){__label__=12;break $sw_default$$sw_bb$$sw_bb5$$sw_bb13$$sw_bb16$6;}
var $12=HEAP32[((__ZL5f_log)>>2)];var $13=HEAP32[((__ZL7linenum)>>2)];var $call=_fprintf($12,((__str90)&4294967295),allocate([$13,0,0,0],["i32",0,0,0],ALLOC_STACK));var $14=HEAP32[((__ZL11error_count)>>2)];var $inc=((($14)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc;;}
else if(__label__==7){var $17=$p;HEAP8[($17)]=0;__ZL16copy_rule_stringPcRi($arraydecay14,$state);$p=$arraydecay15;;}
else if(__label__==8){var $18=HEAP32[(($state)>>2)];var $cmp17=((($18))|0)==2;if($cmp17){__label__=9;;}else{__label__=10;;}
if(__label__==9){HEAP32[(($state)>>2)]=0;;}
else if(__label__==10){var $19=$c;var $20=$p;var $incdec_ptr=(($20+1)&4294967295);$p=$incdec_ptr;HEAP8[($20)]=$19;;}}}while(0);var $_pr=$finish;var $23=$ix;var $inc21=((($23)+1)&4294967295);$ix=$inc21;var $cmp=((($_pr))|0)==0;if($cmp){__label__=2;continue $for_body$4;}else{__label__=13;break $for_body_lr_ph$$for_end$2;}}
var $15=$p;HEAP8[($15)]=0;__ZL16copy_rule_stringPcRi($arraydecay12,$state);$finish=1;var $16=$ix;var $inc213=((($16)+1)&4294967295);$ix=$inc213;;}}while(0);var $call22=_strcmp(((__ZL10rule_match)&4294967295),((__str91)&4294967295));var $cmp23=((($call22))|0)==0;if($cmp23){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $call25=_strcpy(((__ZL10rule_match)&4294967295),((__ZL10group_name)&4294967295));;}
var $24=HEAP8[(((__ZL10rule_match)&4294967295))];var $conv27=(tempInt=(($24)),(tempInt>=128?tempInt-256:tempInt));var $cmp28=((($conv27))|0)==0;if($cmp28){__label__=16;;}else{__label__=19;;}
if(__label__==16){var $25=HEAP8[(((__ZL9rule_post)&4294967295))];var $conv30=(tempInt=(($25)),(tempInt>=128?tempInt-256:tempInt));var $cmp31=((($conv30))|0)!=0;if($cmp31){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $26=HEAP32[((__ZL5f_log)>>2)];var $27=HEAP32[((__ZL7linenum)>>2)];var $call33=_fprintf($26,((__str92)&4294967295),allocate([$27,0,0,0],["i32",0,0,0],ALLOC_STACK));var $28=HEAP32[((__ZL11error_count)>>2)];var $inc34=((($28)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc34;;}
$retval=0;;}
else if(__label__==19){var $arraydecay37=(($buf)&4294967295);var $arraydecay38=(($bad_phoneme)&4294967295);var $call39=__Z14EncodePhonemesPcS_Ph(((__ZL13rule_phonemes)&4294967295),$arraydecay37,$arraydecay38);var $arrayidx40=(($bad_phoneme)&4294967295);var $29=HEAPU8[($arrayidx40)];var $conv41=((($29))&255);var $cmp42=((($conv41))|0)!=0;if($cmp42){__label__=20;;}else{__label__=21;;}
if(__label__==20){var $30=HEAP32[((__ZL5f_log)>>2)];var $31=HEAP32[((__ZL7linenum)>>2)];var $arrayidx44=(($bad_phoneme)&4294967295);var $32=HEAPU8[($arrayidx44)];var $conv45=((($32))&255);var $33=$input_addr;var $call46=_fprintf($30,((__str93)&4294967295),allocate([$31,0,0,0,$conv45,0,0,0,$33,0,0,0],["i32",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $34=HEAP32[((__ZL11error_count)>>2)];var $inc47=((($34)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc47;;}
var $arraydecay49=(($output)&4294967295);var $arraydecay50=(($buf)&4294967295);var $call51=_strcpy($arraydecay49,$arraydecay50);var $arraydecay52=(($buf)&4294967295);var $call53=_strlen($arraydecay52);var $add54=((($call53)+1)&4294967295);$len=$add54;var $call55=_strlen(((__ZL10group_name)&4294967295));$len_name=$call55;var $cmp56=((($call55))|0)>0;if($cmp56){__label__=22;;}else{__label__=26;;}
$land_lhs_true$$if_end70$31:do{if(__label__==22){var $35=$len_name;var $call57=_memcmp(((__ZL10rule_match)&4294967295),((__ZL10group_name)&4294967295),$35);var $cmp58=((($call57))|0)!=0;if(!($cmp58)){__label__=26;break $land_lhs_true$$if_end70$31;}
var $call60=__Z7utf8_inPiPKc($wc,((__ZL10rule_match)&4294967295));var $36=HEAP8[(((__ZL10group_name)&4294967295))];var $conv61=(tempInt=(($36)),(tempInt>=128?tempInt-256:tempInt));var $cmp62=((($conv61))|0)==57;if($cmp62){__label__=24;;}else{__label__=25;;}
if(__label__==24){var $37=HEAP32[(($wc)>>2)];var $call64=__Z7IsDigitj($37);var $tobool=((($call64))|0)!=0;if($tobool){__label__=26;break $land_lhs_true$$if_end70$31;}}
var $38=HEAP32[((__ZL5f_log)>>2)];var $39=HEAP32[((__ZL7linenum)>>2)];var $call67=_fprintf($38,((__str94)&4294967295),allocate([$39,0,0,0,((__ZL10rule_match)&4294967295),0,0,0,((__ZL10group_name)&4294967295),0,0,0],["i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $40=HEAP32[((__ZL11error_count)>>2)];var $inc68=((($40)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc68;;}}while(0);var $41=$len;var $arrayidx71=(($output+$41)&4294967295);var $call72=_strcpy($arrayidx71,((__ZL10rule_match)&4294967295));var $call73=_strlen(((__ZL10rule_match)&4294967295));var $42=$len;var $add74=((($42)+($call73))&4294967295);$len=$add74;var $43=HEAP32[((__ZL10debug_flag)>>2)];var $tobool75=((($43))|0)!=0;if($tobool75){__label__=27;;}else{__label__=28;;}
if(__label__==27){var $44=$len;var $arrayidx77=(($output+$44)&4294967295);HEAP8[($arrayidx77)]=9;var $45=HEAP32[((__ZL7linenum)>>2)];var $rem=((($45))|0)%255;var $add78=((($rem)+1)&4294967295);var $conv79=((($add78))&255);var $46=$len;var $add80=((($46)+1)&4294967295);var $arrayidx81=(($output+$add80)&4294967295);HEAP8[($arrayidx81)]=$conv79;var $47=HEAP32[((__ZL7linenum)>>2)];var $div=((((($47))|0)/255)|0);var $add82=((($div)+1)&4294967295);var $conv83=((($add82))&255);var $48=$len;var $add84=((($48)+2)&4294967295);var $arrayidx85=(($output+$add84)&4294967295);HEAP8[($arrayidx85)]=$conv83;var $49=$len;var $add86=((($49)+3)&4294967295);$len=$add86;;}
var $50=HEAP8[(((__ZL9rule_cond)&4294967295))];var $conv88=(tempInt=(($50)),(tempInt>=128?tempInt-256:tempInt));var $cmp89=((($conv88))|0)!=0;if($cmp89){__label__=29;;}else{__label__=35;;}
if(__label__==29){$ix=-1;var $51=HEAP8[(((__ZL9rule_cond)&4294967295))];var $conv91=(tempInt=(($51)),(tempInt>=128?tempInt-256:tempInt));var $cmp92=((($conv91))|0)==33;if($cmp92){__label__=30;;}else{__label__=31;;}
if(__label__==30){var $call94=_atoi(((__ZL9rule_cond+1)&4294967295));var $add95=((($call94)+32)&4294967295);$ix=$add95;;}
else if(__label__==31){var $call97=_atoi(((__ZL9rule_cond)&4294967295));$ix=$call97;;}
var $52=$ix;var $cmp99=((($52))|0)>0;var $53=$ix;var $cmp101=((($53))|0)<255;var $or_cond=($cmp99)&($cmp101);if($or_cond){__label__=33;;}else{__label__=34;;}
if(__label__==33){var $54=$len;var $inc103=((($54)+1)&4294967295);$len=$inc103;var $arrayidx104=(($output+$54)&4294967295);HEAP8[($arrayidx104)]=5;var $55=$ix;var $conv105=((($55))&255);var $56=$len;var $inc106=((($56)+1)&4294967295);$len=$inc106;var $arrayidx107=(($output+$56)&4294967295);HEAP8[($arrayidx107)]=$conv105;;}
else if(__label__==34){var $57=HEAP32[((__ZL5f_log)>>2)];var $58=HEAP32[((__ZL7linenum)>>2)];var $59=$ix;var $call109=_fprintf($57,((__str95)&4294967295),allocate([$58,0,0,0,$59,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $60=HEAP32[((__ZL11error_count)>>2)];var $inc110=((($60)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc110;;}}
var $61=HEAP8[(((__ZL8rule_pre)&4294967295))];var $conv113=(tempInt=(($61)),(tempInt>=128?tempInt-256:tempInt));var $cmp114=((($conv113))|0)!=0;if($cmp114){__label__=36;;}else{__label__=41;;}
$if_then115$$if_end132$51:do{if(__label__==36){$start=0;var $62=HEAP8[(((__ZL8rule_pre)&4294967295))];var $conv116=(tempInt=(($62)),(tempInt>=128?tempInt-256:tempInt));var $cmp117=((($conv116))|0)==32;if($cmp117){__label__=37;;}else{__label__=38;;}
if(__label__==37){$c=8;$start=1;;}
else if(__label__==38){$c=1;;}
var $63=$c;var $64=$len;var $inc121=((($64)+1)&4294967295);$len=$inc121;var $arrayidx122=(($output+$64)&4294967295);HEAP8[($arrayidx122)]=$63;var $call123=_strlen(((__ZL8rule_pre)&4294967295));var $sub=((($call123)-1)&4294967295);$ix=$sub;var $65=$ix;var $66=$start;var $cmp1251=((($65))|0)>=((($66))|0);if(!($cmp1251)){__label__=41;break $if_then115$$if_end132$51;}
while(1){var $67=$ix;var $arrayidx127=((__ZL8rule_pre+$67)&4294967295);var $68=HEAP8[($arrayidx127)];var $69=$len;var $inc128=((($69)+1)&4294967295);$len=$inc128;var $arrayidx129=(($output+$69)&4294967295);HEAP8[($arrayidx129)]=$68;var $70=$ix;var $dec=((($70)-1)&4294967295);$ix=$dec;var $71=$ix;var $72=$start;var $cmp125=((($71))|0)>=((($72))|0);if($cmp125){__label__=40;continue;}else{__label__=41;break $if_then115$$if_end132$51;}}}}while(0);var $73=HEAP8[(((__ZL9rule_post)&4294967295))];var $conv133=(tempInt=(($73)),(tempInt>=128?tempInt-256:tempInt));var $cmp134=((($conv133))|0)!=0;if($cmp134){__label__=42;;}else{__label__=43;;}
if(__label__==42){var $74=$len;var $arrayidx136=(($output+$74)&4294967295);var $call137=_sprintf($arrayidx136,((__str70722)&4294967295),allocate([2,0,0,0,((__ZL9rule_post)&4294967295),0,0,0],["i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $call138=_strlen(((__ZL9rule_post)&4294967295));var $75=$len;var $add139=((($call138)+1)&4294967295);var $add140=((($add139)+($75))&4294967295);$len=$add140;;}
var $76=$len;var $inc142=((($76)+1)&4294967295);$len=$inc142;var $arrayidx143=(($output+$76)&4294967295);HEAP8[($arrayidx143)]=0;var $77=$len;var $call144=_malloc($77);$prule=$call144;var $78=$prule;var $arraydecay145=(($output)&4294967295);var $79=$len;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay145;$dest$=$78;$stop$=$src$+$79;if(($dest$%4)==($src$%4)&&$79>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $80=$prule;$retval=$80;;}
var $81=$retval;STACKTOP=__stackBase__;return $81;return null;}
function __ZL13rgroup_sorterP6RGROUPS0_($a,$b){;var __label__;var $retval;var $a_addr;var $b_addr;var $ix;$a_addr=$a;$b_addr=$b;var $0=$b_addr;var $name=(($0)&4294967295);var $arraydecay=(($name)&4294967295);var $call=_strlen($arraydecay);var $1=$a_addr;var $name1=(($1)&4294967295);var $arraydecay2=(($name1)&4294967295);var $call3=_strlen($arraydecay2);var $sub=((($call)-($call3))&4294967295);$ix=$sub;var $2=$ix;var $cmp=((($2))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $3=$ix;$retval=$3;;}
else if(__label__==2){var $4=$a_addr;var $name4=(($4)&4294967295);var $arraydecay5=(($name4)&4294967295);var $5=$b_addr;var $name6=(($5)&4294967295);var $arraydecay7=(($name6)&4294967295);var $call8=_strcmp($arraydecay5,$arraydecay7);$ix=$call8;var $6=$ix;var $cmp9=((($6))|0)!=0;if($cmp9){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $7=$ix;$retval=$7;;}
else if(__label__==4){var $8=$a_addr;var $start=(($8+16)&4294967295);var $9=HEAP32[(($start)>>2)];var $10=$b_addr;var $start12=(($10+16)&4294967295);var $11=HEAP32[(($start12)>>2)];var $sub13=((($9)-($11))&4294967295);$retval=$sub13;;}}
var $12=$retval;;return $12;return null;}
function __ZL16copy_rule_stringPcRi($string,$state){;var __label__;var $string_addr;var $state_addr;var $output;var $p;var $ix;var $len;var $c;var $sxflags;var $value;var $literal;var $mr;$string_addr=$string;$state_addr=$state;var $0=$string_addr;var $arrayidx=(($0)&4294967295);var $1=HEAP8[($arrayidx)];var $conv=(tempInt=(($1)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)==0;if($cmp){__label__=75;;}else{__label__=1;;}
if(__label__==1){var $2=$state_addr;var $3=HEAP32[(($2)>>2)];var $arrayidx1=((__ZZL16copy_rule_stringPcRiE6outbuf+$3*4)&4294967295);var $4=HEAP32[(($arrayidx1)>>2)];$output=$4;var $5=$state_addr;var $6=HEAP32[(($5)>>2)];var $cmp2=((($6))|0)==4;if($cmp2){__label__=2;;}else{__label__=5;;}
if(__label__==2){var $call=_strlen(((__ZL13rule_phonemes)&4294967295));$len=$call;var $7=$len;var $cmp4=((($7))|0)>0;if($cmp4){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $8=$len;var $inc=((($8)+1)&4294967295);$len=$inc;var $arrayidx6=((__ZL13rule_phonemes+$8)&4294967295);HEAP8[($arrayidx6)]=32;;}
var $9=$len;var $arrayidx8=((__ZL13rule_phonemes+$9)&4294967295);$output=$arrayidx8;;}
$sxflags=8421376;var $10=$string_addr;$p=$10;$ix=0;;$for_cond$10:while(1){$literal=0;var $11=$p;var $incdec_ptr=(($11+1)&4294967295);$p=$incdec_ptr;var $12=HEAP8[($11)];$c=$12;var $13=$c;var $conv10=(tempInt=(($13)),(tempInt>=128?tempInt-256:tempInt));var $cmp11=((($conv10))|0)==92;if($cmp11){__label__=7;;}else{__label__=15;;}
if(__label__==7){var $14=$p;var $incdec_ptr13=(($14+1)&4294967295);$p=$incdec_ptr13;var $15=HEAP8[($14)];$c=$15;var $16=$c;var $conv14=(tempInt=(($16)),(tempInt>=128?tempInt-256:tempInt));var $cmp15=((($conv14))|0)>=48;if($cmp15){__label__=8;;}else{__label__=14;;}
$land_lhs_true$$if_end45$14:do{if(__label__==8){var $17=$c;var $conv16=(tempInt=(($17)),(tempInt>=128?tempInt-256:tempInt));var $cmp17=((($conv16))|0)<=51;if(!($cmp17)){__label__=14;break $land_lhs_true$$if_end45$14;}
var $18=$p;var $arrayidx19=(($18)&4294967295);var $19=HEAP8[($arrayidx19)];var $conv20=(tempInt=(($19)),(tempInt>=128?tempInt-256:tempInt));var $cmp21=((($conv20))|0)>=48;if(!($cmp21)){__label__=14;break $land_lhs_true$$if_end45$14;}
var $20=$p;var $arrayidx23=(($20)&4294967295);var $21=HEAP8[($arrayidx23)];var $conv24=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));var $cmp25=((($conv24))|0)<=55;if(!($cmp25)){__label__=14;break $land_lhs_true$$if_end45$14;}
var $22=$p;var $arrayidx27=(($22+1)&4294967295);var $23=HEAP8[($arrayidx27)];var $conv28=(tempInt=(($23)),(tempInt>=128?tempInt-256:tempInt));var $cmp29=((($conv28))|0)>=48;if(!($cmp29)){__label__=14;break $land_lhs_true$$if_end45$14;}
var $24=$p;var $arrayidx31=(($24+1)&4294967295);var $25=HEAP8[($arrayidx31)];var $conv32=(tempInt=(($25)),(tempInt>=128?tempInt-256:tempInt));var $cmp33=((($conv32))|0)<=55;if(!($cmp33)){__label__=14;break $land_lhs_true$$if_end45$14;}
var $26=$c;var $conv35=(tempInt=(($26)),(tempInt>=128?tempInt-256:tempInt));var $sub=((($conv35)-48)&4294967295);var $mul=((($sub)*64)&4294967295);var $27=$p;var $arrayidx36=(($27)&4294967295);var $28=HEAP8[($arrayidx36)];var $conv37=(tempInt=(($28)),(tempInt>=128?tempInt-256:tempInt));var $sub38=((($conv37)-48)&4294967295);var $mul39=((($sub38)*8)&4294967295);var $29=$p;var $arrayidx40=(($29+1)&4294967295);var $30=HEAP8[($arrayidx40)];var $conv41=(tempInt=(($30)),(tempInt>=128?tempInt-256:tempInt));var $add=((($mul)-48)&4294967295);var $sub42=((($add)+($conv41))&4294967295);var $add43=((($sub42)+($mul39))&4294967295);var $conv44=((($add43))&255);$c=$conv44;var $31=$p;var $add_ptr=(($31+2)&4294967295);$p=$add_ptr;;}}while(0);$literal=1;;}
var $32=$state_addr;var $33=HEAP32[(($32)>>2)];var $cmp47=((($33))|0)==1;if($cmp47){__label__=17;;}else{__label__=16;;}
$if_then49$$lor_lhs_false$23:do{if(__label__==16){var $34=$state_addr;var $35=HEAP32[(($34)>>2)];var $cmp48=((($35))|0)==3;if($cmp48){__label__=17;break $if_then49$$lor_lhs_false$23;}else{__label__=73;break $if_then49$$lor_lhs_false$23;}}}while(0);$if_then49$$if_end212$25:do{if(__label__==17){var $36=$literal;var $cmp50=((($36))|0)==0;if(!($cmp50)){__label__=73;break $if_then49$$if_end212$25;}
var $37=$c;var $conv52=(tempInt=(($37)),(tempInt>=128?tempInt-256:tempInt));if($conv52==95){__label__=19;;}
else if($conv52==89){__label__=20;;}
else if($conv52==65){__label__=21;;}
else if($conv52==66){__label__=21;;}
else if($conv52==67){__label__=21;;}
else if($conv52==72){__label__=21;;}
else if($conv52==70){__label__=21;;}
else if($conv52==71){__label__=21;;}
else if($conv52==68){__label__=24;;}
else if($conv52==75){__label__=25;;}
else if($conv52==78){__label__=26;;}
else if($conv52==86){__label__=27;;}
else if($conv52==90){__label__=28;;}
else if($conv52==43){__label__=29;;}
else if($conv52==64){__label__=30;;}
else if($conv52==38){__label__=31;;}
else if($conv52==37){__label__=32;;}
else if($conv52==35){__label__=33;;}
else if($conv52==33){__label__=34;;}
else if($conv52==84){__label__=35;;}
else if($conv52==87){__label__=36;;}
else if($conv52==88){__label__=37;;}
else if($conv52==74){__label__=38;;}
else if($conv52==76){__label__=39;;}
else if($conv52==36){__label__=48;;}
else if($conv52==80){__label__=55;;}
else if($conv52==83){__label__=56;;}
else{__label__=73;break $if_then49$$if_end212$25;}
$sw_bb$$sw_bb53$$sw_bb54$$sw_bb74$$sw_bb75$$sw_bb76$$sw_bb77$$sw_bb78$$sw_bb79$$sw_bb80$$sw_bb81$$sw_bb82$$sw_bb83$$sw_bb84$$sw_bb85$$sw_bb88$$sw_bb89$$sw_bb90$$sw_bb91$$sw_bb137$$sw_bb158$$sw_bb159$28:do{if(__label__==19){$c=32;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==20){$c=73;__label__=21;break $sw_bb$$sw_bb53$$sw_bb54$$sw_bb74$$sw_bb75$$sw_bb76$$sw_bb77$$sw_bb78$$sw_bb79$$sw_bb80$$sw_bb81$$sw_bb82$$sw_bb83$$sw_bb84$$sw_bb85$$sw_bb88$$sw_bb89$$sw_bb90$$sw_bb91$$sw_bb137$$sw_bb158$$sw_bb159$28;}
else if(__label__==24){$c=15;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==25){$c=25;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==26){$c=24;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==27){$c=26;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==28){$c=16;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==29){$c=12;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==30){$c=21;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==31){$c=10;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==32){$c=11;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==33){$c=13;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==34){$c=19;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==35){var $48=$ix;var $inc86=((($48)+1)&4294967295);$ix=$inc86;var $49=$output;var $arrayidx87=(($49+$48)&4294967295);HEAP8[($arrayidx87)]=28;$c=17;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==36){$c=31;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==37){$c=29;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==38){$c=23;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==39){var $50=$p;var $incdec_ptr92=(($50+1)&4294967295);$p=$incdec_ptr92;var $51=HEAP8[($50)];var $conv93=(tempInt=(($51)),(tempInt>=128?tempInt-256:tempInt));var $sub94=((($conv93)-48)&4294967295);var $conv95=((($sub94))&255);$c=$conv95;var $52=$p;var $incdec_ptr96=(($52+1)&4294967295);$p=$incdec_ptr96;var $53=HEAP8[($52)];var $conv97=(tempInt=(($53)),(tempInt>=128?tempInt-256:tempInt));var $sub98=((($conv97)-48)&4294967295);$value=$sub98;var $54=$c;var $conv99=(tempInt=(($54)),(tempInt>=128?tempInt-256:tempInt));var $mul100=((($conv99)*10)&4294967295);var $55=$value;var $add101=((($mul100)+($55))&4294967295);var $conv102=((($add101))&255);$c=$conv102;var $56=$value;var $cmp103=((($56))|0)<0;var $57=$value;var $cmp105=((($57))|0)>9;var $or_cond=($cmp103)|($cmp105);if($or_cond){__label__=40;;}else{__label__=41;;}
$if_then106$$if_else109$47:do{if(__label__==40){$c=0;var $58=HEAP32[((__ZL5f_log)>>2)];var $59=HEAP32[((__ZL7linenum)>>2)];var $call107=_fprintf($58,((__str97)&4294967295),allocate([$59,0,0,0],["i32",0,0,0],ALLOC_STACK));var $60=HEAP32[((__ZL11error_count)>>2)];var $inc108=((($60)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc108;;}
else if(__label__==41){var $61=$c;var $conv110=(tempInt=(($61)),(tempInt>=128?tempInt-256:tempInt));var $cmp111=((($conv110))|0)<=0;if($cmp111){__label__=44;;}else{__label__=42;;}
$if_then120$$lor_lhs_false112$50:do{if(__label__==42){var $62=$c;var $conv113=(tempInt=(($62)),(tempInt>=128?tempInt-256:tempInt));var $cmp114=((($conv113))|0)>=26;if($cmp114){__label__=44;break $if_then120$$lor_lhs_false112$50;}
var $63=$c;var $conv116=(tempInt=(($63)),(tempInt>=128?tempInt-256:tempInt));var $arrayidx117=((__ZL19letterGroupsDefined+$conv116)&4294967295);var $64=HEAP8[($arrayidx117)];var $conv118=(tempInt=(($64)),(tempInt>=128?tempInt-256:tempInt));var $cmp119=((($conv118))|0)==0;if(!($cmp119)){__label__=45;break $if_then106$$if_else109$47;}}}while(0);var $65=HEAP32[((__ZL5f_log)>>2)];var $66=HEAP32[((__ZL7linenum)>>2)];var $67=$c;var $conv121=(tempInt=(($67)),(tempInt>=128?tempInt-256:tempInt));var $call122=_fprintf($65,((__str98)&4294967295),allocate([$66,0,0,0,$conv121,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $68=HEAP32[((__ZL11error_count)>>2)];var $inc123=((($68)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc123;;}}while(0);var $69=$c;var $conv126=(tempInt=(($69)),(tempInt>=128?tempInt-256:tempInt));var $add127=((($conv126)+65)&4294967295);var $conv128=((($add127))&255);$c=$conv128;var $70=$state_addr;var $71=HEAP32[(($70)>>2)];var $cmp129=((($71))|0)==1;if($cmp129){__label__=46;;}else{__label__=47;;}
if(__label__==46){var $72=$c;var $73=$ix;var $inc131=((($73)+1)&4294967295);$ix=$inc131;var $74=$output;var $arrayidx132=(($74+$73)&4294967295);HEAP8[($arrayidx132)]=$72;$c=18;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==47){var $75=$ix;var $inc134=((($75)+1)&4294967295);$ix=$inc134;var $76=$output;var $arrayidx135=(($76+$75)&4294967295);HEAP8[($arrayidx135)]=18;__label__=73;break $if_then49$$if_end212$25;}}
else if(__label__==48){var $77=$ix;var $inc138=((($77)+1)&4294967295);$ix=$inc138;var $78=$output;var $arrayidx139=(($78+$77)&4294967295);HEAP8[($arrayidx139)]=28;$c=0;$mr=((_mnem_rules)&4294967295);;while(1){var $79=$mr;var $mnem=(($79)&4294967295);var $80=HEAP32[(($mnem)>>2)];var $cmp140=((($80))|0)!=0;if(!($cmp140)){__label__=53;break;}
var $81=$mr;var $mnem141=(($81)&4294967295);var $82=HEAP32[(($mnem141)>>2)];var $call142=_strlen($82);$len=$call142;var $83=$p;var $84=$mr;var $mnem143=(($84)&4294967295);var $85=HEAP32[(($mnem143)>>2)];var $86=$len;var $call144=_memcmp($83,$85,$86);var $cmp145=((($call144))|0)==0;var $87=$mr;if($cmp145){__label__=51;break;}
var $incdec_ptr151=(($87+8)&4294967295);$mr=$incdec_ptr151;__label__=49;continue;}
if(__label__==51){var $value147=(($87+4)&4294967295);var $88=HEAP32[(($value147)>>2)];var $conv148=((($88))&255);$c=$conv148;var $89=$len;var $90=$p;var $add_ptr149=(($90+$89)&4294967295);$p=$add_ptr149;;}
var $91=$c;var $conv152=(tempInt=(($91)),(tempInt>=128?tempInt-256:tempInt));var $cmp153=((($conv152))|0)==0;if(!($cmp153)){__label__=73;break $if_then49$$if_end212$25;}
var $92=HEAP32[((__ZL5f_log)>>2)];var $93=HEAP32[((__ZL7linenum)>>2)];var $call155=_fprintf($92,((__str99)&4294967295),allocate([$93,0,0,0],["i32",0,0,0],ALLOC_STACK));var $94=HEAP32[((__ZL11error_count)>>2)];var $inc156=((($94)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc156;__label__=73;break $if_then49$$if_end212$25;}
else if(__label__==55){var $95=$sxflags;var $or=($95)|1024;$sxflags=$or;__label__=56;break $sw_bb$$sw_bb53$$sw_bb54$$sw_bb74$$sw_bb75$$sw_bb76$$sw_bb77$$sw_bb78$$sw_bb79$$sw_bb80$$sw_bb81$$sw_bb82$$sw_bb83$$sw_bb84$$sw_bb85$$sw_bb88$$sw_bb89$$sw_bb90$$sw_bb91$$sw_bb137$$sw_bb158$$sw_bb159$28;}}while(0);if(__label__==21){var $38=$state_addr;var $39=HEAP32[(($38)>>2)];var $cmp55=((($39))|0)==1;if($cmp55){__label__=22;;}else{__label__=23;;}
if(__label__==22){var $40=$c;var $conv57=(tempInt=(($40)),(tempInt>=128?tempInt-256:tempInt));var $sub58=((($conv57)-65)&4294967295);var $arrayidx59=((__ZZL16copy_rule_stringPcRiE16lettergp_letters+$sub58)&4294967295);var $41=HEAP8[($arrayidx59)];var $conv60=(tempInt=(($41)),(tempInt>=128?tempInt-256:tempInt));var $add61=((($conv60)+65)&4294967295);var $conv62=((($add61))&255);var $42=$ix;var $inc63=((($42)+1)&4294967295);$ix=$inc63;var $43=$output;var $arrayidx64=(($43+$42)&4294967295);HEAP8[($arrayidx64)]=$conv62;$c=17;;}
else if(__label__==23){var $44=$ix;var $inc65=((($44)+1)&4294967295);$ix=$inc65;var $45=$output;var $arrayidx66=(($45+$44)&4294967295);HEAP8[($arrayidx66)]=17;var $46=$c;var $conv67=(tempInt=(($46)),(tempInt>=128?tempInt-256:tempInt));var $sub68=((($conv67)-65)&4294967295);var $arrayidx69=((__ZZL16copy_rule_stringPcRiE16lettergp_letters+$sub68)&4294967295);var $47=HEAP8[($arrayidx69)];var $conv70=(tempInt=(($47)),(tempInt>=128?tempInt-256:tempInt));var $add71=((($conv70)+65)&4294967295);var $conv72=((($add71))&255);$c=$conv72;;}}
else if(__label__==56){var $96=$ix;var $inc160=((($96)+1)&4294967295);$ix=$inc160;var $97=$output;var $arrayidx161=(($97+$96)&4294967295);HEAP8[($arrayidx161)]=14;$value=0;;while(1){var $98=$p;var $incdec_ptr163=(($98+1)&4294967295);$p=$incdec_ptr163;var $99=HEAP8[($98)];$c=$99;var $conv164=(tempInt=(($99)),(tempInt>=128?tempInt-256:tempInt));var $call165=__Z8isspace2j($conv164);var $tobool=((($call165))|0)!=0;if($tobool){__label__=72;break;}
var $100=$c;var $conv166=(tempInt=(($100)),(tempInt>=128?tempInt-256:tempInt));var $cmp167=((($conv166))|0)!=0;if(!($cmp167)){__label__=72;break;}
var $101=$c;var $conv169=(tempInt=(($101)),(tempInt>=128?tempInt-256:tempInt));if($conv169==101){__label__=60;;}
else if($conv169==105){__label__=61;;}
else if($conv169==112){__label__=62;;}
else if($conv169==118){__label__=63;;}
else if($conv169==100){__label__=64;;}
else if($conv169==102){__label__=65;;}
else if($conv169==113){__label__=66;;}
else if($conv169==116){__label__=67;;}
else if($conv169==98){__label__=68;;}
else if($conv169==97){__label__=69;;}
else{__label__=70;;}
if(__label__==70){var $112=$c;var $conv190=(tempInt=(($112)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp=((($conv190)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call191=((($isdigit))&1);var $tobool192=((($call191))|0)!=0;if(!($tobool192)){__label__=57;continue;}
var $113=$value;var $mul194=((($113)*10)&4294967295);var $114=$c;var $conv195=(tempInt=(($114)),(tempInt>=128?tempInt-256:tempInt));var $sub196=((($mul194)-48)&4294967295);var $add197=((($sub196)+($conv195))&4294967295);$value=$add197;__label__=57;continue;}
else if(__label__==60){var $102=$sxflags;var $or171=($102)|256;$sxflags=$or171;__label__=57;continue;}
else if(__label__==61){var $103=$sxflags;var $or173=($103)|512;$sxflags=$or173;__label__=57;continue;}
else if(__label__==62){var $104=$sxflags;var $or175=($104)|1024;$sxflags=$or175;__label__=57;continue;}
else if(__label__==63){var $105=$sxflags;var $or177=($105)|2048;$sxflags=$or177;__label__=57;continue;}
else if(__label__==64){var $106=$sxflags;var $or179=($106)|4096;$sxflags=$or179;__label__=57;continue;}
else if(__label__==65){var $107=$sxflags;var $or181=($107)|8192;$sxflags=$or181;__label__=57;continue;}
else if(__label__==66){var $108=$sxflags;var $or183=($108)|16384;$sxflags=$or183;__label__=57;continue;}
else if(__label__==67){var $109=$sxflags;var $or185=($109)|65536;$sxflags=$or185;__label__=57;continue;}
else if(__label__==68){var $110=$sxflags;var $or187=($110)|131072;$sxflags=$or187;__label__=57;continue;}
else if(__label__==69){var $111=$sxflags;var $or189=($111)|262144;$sxflags=$or189;__label__=57;continue;}}
var $115=$p;var $incdec_ptr200=(($115+-1)&4294967295);$p=$incdec_ptr200;var $116=$sxflags;var $shr=($116)>>16;var $conv201=((($shr))&255);var $117=$ix;var $inc202=((($117)+1)&4294967295);$ix=$inc202;var $118=$output;var $arrayidx203=(($118+$117)&4294967295);HEAP8[($arrayidx203)]=$conv201;var $119=$sxflags;var $shr204=($119)>>8;var $conv205=((($shr204))&255);var $120=$ix;var $inc206=((($120)+1)&4294967295);$ix=$inc206;var $121=$output;var $arrayidx207=(($121+$120)&4294967295);HEAP8[($arrayidx207)]=$conv205;var $122=$value;var $or208=($122)|128;var $conv209=((($or208))&255);$c=$conv209;;}}}while(0);var $123=$c;var $124=$ix;var $inc213=((($124)+1)&4294967295);$ix=$inc213;var $125=$output;var $arrayidx214=(($125+$124)&4294967295);HEAP8[($arrayidx214)]=$123;var $126=$c;var $conv215=(tempInt=(($126)),(tempInt>=128?tempInt-256:tempInt));var $cmp216=((($conv215))|0)==0;if($cmp216){__label__=74;break $for_cond$10;}else{__label__=6;continue $for_cond$10;}}
var $127=$state_addr;var $128=HEAP32[(($127)>>2)];var $arrayidx219=((__ZZL16copy_rule_stringPcRiE10next_state+$128*4)&4294967295);var $129=HEAP32[(($arrayidx219)>>2)];var $130=$state_addr;HEAP32[(($130)>>2)]=$129;;};return;return;}
function __ZL12compile_linePcS_Pi($linebuf,$dict_line,$hash){var __stackBase__=STACKTOP;STACKTOP+=312;_memset(__stackBase__,0,312);var __label__;var __lastLabel__=null;var $retval;var $linebuf_addr;var $dict_line_addr;var $hash_addr;var $c;var $p;var $word;var $phonetic;var $ix;var $step;var $n_flag_codes;var $flag_offset;var $length;var $multiple_words;var $multiple_numeric_hyphen;var $multiple_string;var $multiple_string_end;var $len_word;var $len_phonetic;var $text_not_phonemes;var $wc=__stackBase__;var $all_upper_case;var $mnemptr;var $comment;var $flag_codes=__stackBase__+4;var $encoded_ph=__stackBase__+104;var $bad_phoneme=__stackBase__+304;var $c2=__stackBase__+308;$linebuf_addr=$linebuf;$dict_line_addr=$dict_line;$hash_addr=$hash;$n_flag_codes=0;$multiple_words=0;$multiple_numeric_hyphen=0;$multiple_string=0;$multiple_string_end=0;$comment=0;$text_not_phonemes=0;$word=((__ZZL12compile_linePcS_PiE10nullstring)&4294967295);$phonetic=((__ZZL12compile_linePcS_PiE10nullstring)&4294967295);var $0=$linebuf_addr;var $call=_memcmp($0,((__str108)&4294967295),2);var $cmp=((($call))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$step=1;;}
var $1=$linebuf_addr;$p=$1;$step=0;$c=0;var $2=$c;var $conv13=((($2))&255);var $cmp114=((($conv13))|0)!=10;if($cmp114){__label__=3;;}else{__label__=55;;}
$while_body$$while_end147$5:do{if(__label__==3){$while_body$6:while(1){var $3=$p;var $4=HEAP8[($3)];$c=$4;var $5=$c;var $conv2=((($5))&255);var $cmp3=((($conv2))|0)==63;if($cmp3){__label__=4;;}else{__label__=12;;}
$land_lhs_true$$if_end28$8:do{if(__label__==4){var $6=$step;var $cmp4=((($6))|0)==0;if(!($cmp4)){__label__=12;break $land_lhs_true$$if_end28$8;}
$flag_offset=100;var $7=$p;var $incdec_ptr=(($7+1)&4294967295);$p=$incdec_ptr;var $8=$p;var $9=HEAP8[($8)];var $conv6=(tempInt=(($9)),(tempInt>=128?tempInt-256:tempInt));var $cmp7=((($conv6))|0)==33;if($cmp7){__label__=6;;}else{__label__=7;;}
if(__label__==6){$flag_offset=132;var $10=$p;var $incdec_ptr9=(($10+1)&4294967295);$p=$incdec_ptr9;;}
$ix=0;var $11=$p;var $12=HEAP8[($11)];var $conv11=(tempInt=(($12)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp=((($conv11)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call12=((($isdigit))&1);var $tobool=((($call12))|0)!=0;if($tobool){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $13=$p;var $14=HEAP8[($13)];var $conv14=(tempInt=(($14)),(tempInt>=128?tempInt-256:tempInt));var $15=$ix;var $sub=((($15)-48)&4294967295);var $add=((($sub)+($conv14))&4294967295);$ix=$add;var $16=$p;var $incdec_ptr15=(($16+1)&4294967295);$p=$incdec_ptr15;;}
var $17=$p;var $18=HEAP8[($17)];var $conv17=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp1=((($conv17)-48)&4294967295);var $isdigit2=((($isdigittmp1))>>>0)<10;var $call18=((($isdigit2))&1);var $tobool19=((($call18))|0)!=0;if($tobool19){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $19=$ix;var $mul=((($19)*10)&4294967295);var $20=$p;var $21=HEAP8[($20)];var $conv21=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));var $sub22=((($mul)-48)&4294967295);var $add23=((($sub22)+($conv21))&4294967295);$ix=$add23;var $22=$p;var $incdec_ptr24=(($22+1)&4294967295);$p=$incdec_ptr24;;}
var $23=$ix;var $24=$flag_offset;var $add26=((($24)+($23))&4294967295);var $conv27=((($add26))&255);var $25=$n_flag_codes;var $inc=((($25)+1)&4294967295);$n_flag_codes=$inc;var $arrayidx=(($flag_codes+$25)&4294967295);HEAP8[($arrayidx)]=$conv27;var $26=$p;var $27=HEAP8[($26)];$c=$27;;}}while(0);var $28=$c;var $conv29=((($28))&255);var $cmp30=((($conv29))|0)==36;if($cmp30){__label__=13;;}else{__label__=25;;}
$land_lhs_true31$$if_end64$21:do{if(__label__==13){var $29=$p;var $arrayidx32=(($29+1)&4294967295);var $30=HEAP8[($arrayidx32)];var $conv33=(tempInt=(($30)),(tempInt>=128?tempInt-256:tempInt));var $call34=_isalnum($conv33);var $tobool35=((($call34))|0)!=0;if(!($tobool35)){__label__=25;break $land_lhs_true31$$if_end64$21;}
var $31=$p;$mnemptr=$31;var $32=$p;var $33=HEAPU8[($32)];$c=$33;var $conv389=((($33))&255);var $call3910=__Z8isspace2j($conv389);var $tobool4011=((($call3910))|0)!=0;var $lnot12=($tobool4011)^1;var $34=$p;if($lnot12){__lastLabel__=14;__label__=15;;}else{__lastLabel__=14;__label__=16;;}
$while_body41$$while_end$24:do{if(__label__==15){while(1){var $35=__lastLabel__==15?$38:($34);var $incdec_ptr42=(($35+1)&4294967295);$p=$incdec_ptr42;var $36=$p;var $37=HEAPU8[($36)];$c=$37;var $conv38=((($37))&255);var $call39=__Z8isspace2j($conv38);var $tobool40=((($call39))|0)!=0;var $lnot=($tobool40)^1;var $38=$p;if($lnot){__lastLabel__=15;__label__=15;continue;}else{__lastLabel__=15;__label__=16;break $while_body41$$while_end$24;}}}}while(0);var $_lcssa=__lastLabel__==14?$34:($38);HEAP8[($_lcssa)]=0;var $39=$mnemptr;var $call43=__Z10LookupMnemP8MNEM_TABPKc(((_mnem_flags)&4294967295),$39);$ix=$call43;var $cmp44=((($call43))>>>0)>0;if($cmp44){__label__=17;;}else{__label__=24;;}
if(__label__==17){var $40=$ix;var $cmp46=((($40))|0)==200;if($cmp46){__label__=18;;}else{__label__=19;;}
if(__label__==18){HEAP8[(__ZL9text_mode_b)]=1;;}
else if(__label__==19){var $41=$ix;var $cmp48=((($41))|0)==201;if($cmp48){__label__=20;;}else{__label__=21;;}
if(__label__==20){HEAP8[(__ZL9text_mode_b)]=0;;}
else if(__label__==21){var $42=$ix;var $cmp51=((($42))|0)==29;if($cmp51){__label__=22;;}else{__label__=23;;}
if(__label__==22){$text_not_phonemes=1;;}
else if(__label__==23){var $43=$ix;var $conv54=((($43))&255);var $44=$n_flag_codes;var $inc55=((($44)+1)&4294967295);$n_flag_codes=$inc55;var $arrayidx56=(($flag_codes+$44)&4294967295);HEAP8[($arrayidx56)]=$conv54;;}}}}
else if(__label__==24){var $45=HEAP32[((__ZL5f_log)>>2)];var $46=HEAP32[((__ZL7linenum)>>2)];var $47=$mnemptr;var $call61=_fprintf($45,((__str109)&4294967295),allocate([$46,0,0,0,$47,0,0,0],["i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $48=HEAP32[((__ZL11error_count)>>2)];var $inc62=((($48)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc62;;}}}while(0);var $49=$c;var $conv65=((($49))&255);var $cmp66=((($conv65))|0)==47;if($cmp66){__label__=26;;}else{__label__=29;;}
$land_lhs_true67$$if_end74$41:do{if(__label__==26){var $50=$p;var $arrayidx68=(($50+1)&4294967295);var $51=HEAP8[($arrayidx68)];var $conv69=(tempInt=(($51)),(tempInt>=128?tempInt-256:tempInt));var $cmp70=((($conv69))|0)==47;if(!($cmp70)){__label__=29;break $land_lhs_true67$$if_end74$41;}
var $52=$multiple_words;var $cmp72=((($52))|0)==0;if(!($cmp72)){__label__=29;break $land_lhs_true67$$if_end74$41;}
$c=10;var $53=$p;$comment=$53;;}}while(0);var $54=$step;if($54==0){__label__=30;;}
else if($54==1){__label__=34;;}
else if($54==2){__label__=46;;}
else if($54==3){__label__=50;;}
else if($54==4){__label__=52;;}
else{__label__=54;;}
$sw_epilog$$sw_bb$$sw_bb85$$sw_bb119$$sw_bb133$$sw_bb139$46:do{if(__label__==30){var $55=$c;var $conv75=((($55))&255);var $cmp76=((($conv75))|0)==40;if($cmp76){__label__=31;;}else{__label__=32;;}
if(__label__==31){$multiple_words=1;var $56=$p;var $add_ptr=(($56+1)&4294967295);$word=$add_ptr;$step=1;;}
else if(__label__==32){var $57=$c;var $conv79=((($57))&255);var $call80=__Z8isspace2j($conv79);var $tobool81=((($call80))|0)!=0;if($tobool81){__label__=54;break $sw_epilog$$sw_bb$$sw_bb85$$sw_bb119$$sw_bb133$$sw_bb139$46;}
var $58=$p;$word=$58;$step=1;;}}
else if(__label__==34){var $59=$c;var $conv86=((($59))&255);var $cmp87=((($conv86))|0)==45;if($cmp87){__label__=35;;}else{__label__=39;;}
$land_lhs_true88$$if_end99$53:do{if(__label__==35){var $60=$multiple_words;var $tobool89=((($60))|0)!=0;if(!($tobool89)){__label__=39;break $land_lhs_true88$$if_end99$53;}
var $61=$word;var $arrayidx91=(($61)&4294967295);var $62=HEAP8[($arrayidx91)];var $conv92=(tempInt=(($62)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp3=((($conv92)-48)&4294967295);var $isdigit4=((($isdigittmp3))>>>0)<10;var $call93=((($isdigit4))&1);var $tobool94=((($call93))|0)!=0;if($tobool94){__label__=37;;}else{__label__=38;;}
if(__label__==37){$multiple_numeric_hyphen=1;;}
var $63=$n_flag_codes;var $inc97=((($63)+1)&4294967295);$n_flag_codes=$inc97;var $arrayidx98=(($flag_codes+$63)&4294967295);HEAP8[($arrayidx98)]=44;$c=32;;}}while(0);var $64=$c;var $conv100=((($64))&255);var $call101=__Z8isspace2j($conv100);var $tobool102=((($call101))|0)!=0;if($tobool102){__label__=40;;}else{__label__=43;;}
if(__label__==40){var $65=$p;var $arrayidx104=(($65)&4294967295);HEAP8[($arrayidx104)]=0;var $66=$multiple_words;var $tobool105=((($66))|0)!=0;if($tobool105){__label__=41;;}else{__label__=42;;}
if(__label__==41){var $67=$p;var $add_ptr107=(($67+1)&4294967295);$multiple_string_end=$add_ptr107;$multiple_string=$add_ptr107;$step=2;;}
else if(__label__==42){$step=3;;}}
else if(__label__==43){var $68=$c;var $conv111=((($68))&255);var $cmp112=((($conv111))|0)==41;if(!($cmp112)){__label__=54;break $sw_epilog$$sw_bb$$sw_bb85$$sw_bb119$$sw_bb133$$sw_bb139$46;}
var $69=$multiple_words;var $tobool114=((($69))|0)!=0;if(!($tobool114)){__label__=54;break $sw_epilog$$sw_bb$$sw_bb85$$sw_bb119$$sw_bb133$$sw_bb139$46;}
var $70=$p;var $arrayidx116=(($70)&4294967295);HEAP8[($arrayidx116)]=0;$step=3;$multiple_words=0;;}}
else if(__label__==46){var $71=$c;var $conv120=((($71))&255);var $call121=__Z8isspace2j($conv120);var $tobool122=((($call121))|0)!=0;if($tobool122){__label__=47;;}else{__label__=48;;}
if(__label__==47){var $72=$multiple_words;var $inc124=((($72)+1)&4294967295);$multiple_words=$inc124;;}
else if(__label__==48){var $73=$c;var $conv126=((($73))&255);var $cmp127=((($conv126))|0)==41;if(!($cmp127)){__label__=54;break $sw_epilog$$sw_bb$$sw_bb85$$sw_bb119$$sw_bb133$$sw_bb139$46;}
var $74=$p;var $arrayidx129=(($74)&4294967295);HEAP8[($arrayidx129)]=32;var $75=$p;var $add_ptr130=(($75+1)&4294967295);$multiple_string_end=$add_ptr130;$step=3;;}}
else if(__label__==50){var $76=$c;var $conv134=((($76))&255);var $call135=__Z8isspace2j($conv134);var $tobool136=((($call135))|0)!=0;if($tobool136){__label__=54;break $sw_epilog$$sw_bb$$sw_bb85$$sw_bb119$$sw_bb133$$sw_bb139$46;}
var $77=$p;$phonetic=$77;$step=4;;}
else if(__label__==52){var $78=$c;var $conv140=((($78))&255);var $call141=__Z8isspace2j($conv140);var $tobool142=((($call141))|0)!=0;if(!($tobool142)){__label__=54;break $sw_epilog$$sw_bb$$sw_bb85$$sw_bb119$$sw_bb133$$sw_bb139$46;}
var $79=$p;var $arrayidx144=(($79)&4294967295);HEAP8[($arrayidx144)]=0;$step=5;;}}while(0);var $80=$p;var $incdec_ptr146=(($80+1)&4294967295);$p=$incdec_ptr146;var $81=$c;var $conv=((($81))&255);var $cmp1=((($conv))|0)!=10;if($cmp1){__label__=3;continue $while_body$6;}else{__label__=55;break $while_body$$while_end147$5;}}}}while(0);var $82=$word;var $arrayidx148=(($82)&4294967295);var $83=HEAP8[($arrayidx148)];var $conv149=(tempInt=(($83)),(tempInt>=128?tempInt-256:tempInt));var $cmp150=((($conv149))|0)==0;if($cmp150){__label__=56;;}else{__label__=57;;}
if(__label__==56){$retval=0;;}
else if(__label__==57){var $_b=HEAPU8[(__ZL9text_mode_b)];var $84=((($_b))&1);var $tobool153=((($84))|0)!=0;if($tobool153){__label__=58;;}else{__label__=59;;}
$if_end155_thread$$if_end155$82:do{if(__label__==58){$text_not_phonemes=1;__label__=60;break $if_end155_thread$$if_end155$82;}
else if(__label__==59){var $_pr=$text_not_phonemes;var $tobool156=((($_pr))|0)!=0;if($tobool156){__label__=60;break $if_end155_thread$$if_end155$82;}
var $96=$phonetic;var $arraydecay176=(($encoded_ph)&4294967295);var $arraydecay177=(($bad_phoneme)&4294967295);var $call178=__Z14EncodePhonemesPcS_Ph($96,$arraydecay176,$arraydecay177);var $arraydecay179=(($encoded_ph)&4294967295);var $call180=_strchr($arraydecay179,21);var $cmp181=((($call180))|0)!=0;if($cmp181){__label__=65;;}else{__label__=66;;}
if(__label__==65){var $97=$n_flag_codes;var $inc183=((($97)+1)&4294967295);$n_flag_codes=$inc183;var $arrayidx184=(($flag_codes+$97)&4294967295);HEAP8[($arrayidx184)]=10;;}
var $arrayidx186=(($bad_phoneme)&4294967295);var $98=HEAPU8[($arrayidx186)];var $conv187=((($98))&255);var $cmp188=((($conv187))|0)!=0;if(!($cmp188)){__label__=68;break $if_end155_thread$$if_end155$82;}
var $99=HEAP32[((__ZL5f_log)>>2)];var $100=HEAP32[((__ZL7linenum)>>2)];var $arrayidx190=(($bad_phoneme)&4294967295);var $101=HEAPU8[($arrayidx190)];var $conv191=((($101))&255);var $arrayidx192=(($bad_phoneme)&4294967295);var $102=HEAPU8[($arrayidx192)];var $conv193=((($102))&255);var $103=$word;var $104=$phonetic;var $call194=_fprintf($99,((__str112)&4294967295),allocate([$100,0,0,0,$conv191,0,0,0,$conv193,0,0,0,$103,0,0,0,$104,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $105=HEAP32[((__ZL11error_count)>>2)];var $inc195=((($105)+1)&4294967295);HEAP32[((__ZL11error_count)>>2)]=$inc195;__label__=68;break $if_end155_thread$$if_end155$82;}}while(0);$if_then157$$if_end197$90:do{if(__label__==60){var $85=$word;var $arrayidx158=(($85)&4294967295);var $86=HEAP8[($arrayidx158)];var $conv159=(tempInt=(($86)),(tempInt>=128?tempInt-256:tempInt));var $cmp160=((($conv159))|0)==95;if($cmp160){__label__=61;;}else{__label__=63;;}
if(__label__==61){var $87=$phonetic;var $strlen=_strlen($87);var $endptr=(($87+$strlen)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str110)&4294967295);$dest$=$endptr;$stop$=$src$+2;if(($dest$%4)==($src$%4)&&2>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $88=HEAP32[((_translator)>>2)];var $89=$phonetic;var $call163=__Z13TranslateWordP10TranslatorPciP8WORD_TAB($88,$89,0,0);$text_not_phonemes=0;var $arraydecay=(($encoded_ph)&4294967295);__Z8strncpy0PcPKci($arraydecay,((_word_phonemes)&4294967295),156);var $90=HEAP8[(((_word_phonemes)&4294967295))];var $conv164=(tempInt=(($90)),(tempInt>=128?tempInt-256:tempInt));var $cmp165=((($conv164))|0)==0;var $91=HEAP32[((__ZL21error_need_dictionary)>>2)];var $cmp167=((($91))|0)<3;var $or_cond=($cmp165)&($cmp167);if(!($or_cond)){__label__=68;break $if_then157$$if_end197$90;}
var $92=HEAP32[((__ZL21error_need_dictionary)>>2)];var $inc169=((($92)+1)&4294967295);HEAP32[((__ZL21error_need_dictionary)>>2)]=$inc169;var $93=HEAP32[((__ZL5f_log)>>2)];var $94=HEAP32[((__ZL7linenum)>>2)];var $call170=_fprintf($93,((__str111)&4294967295),allocate([$94,0,0,0],["i32",0,0,0],ALLOC_STACK));;}
else if(__label__==63){var $arraydecay173=(($encoded_ph)&4294967295);var $95=$phonetic;__Z8strncpy0PcPKci($arraydecay173,$95,156);;}}}while(0);var $106=$text_not_phonemes;var $107=HEAP32[((_translator)>>2)];var $langopts=(($107)&4294967295);var $textmode=(($langopts+252)&4294967295);var $108=HEAP8[($textmode)];var $conv198=(tempInt=(($108)),(tempInt>=128?tempInt-256:tempInt));var $cmp199=((($106))|0)!=((($conv198))|0);if($cmp199){__label__=69;;}else{__label__=70;;}
if(__label__==69){var $109=$n_flag_codes;var $inc201=((($109)+1)&4294967295);$n_flag_codes=$inc201;var $arrayidx202=(($flag_codes+$109)&4294967295);HEAP8[($arrayidx202)]=29;;}
var $110=$word;var $call204=_sscanf($110,((__str113)&4294967295),allocate([$wc,0,0,0],["i32*",0,0,0],ALLOC_STACK));var $cmp205=((($call204))|0)==1;if($cmp205){__label__=71;;}else{__label__=72;;}
$if_then206$$if_else209$100:do{if(__label__==71){var $111=HEAP32[(($wc)>>2)];var $112=$word;var $call207=__Z8utf8_outjPc($111,$112);$ix=$call207;var $113=$ix;var $114=$word;var $arrayidx208=(($114+$113)&4294967295);HEAP8[($arrayidx208)]=0;;}
else if(__label__==72){var $115=$word;var $arrayidx210=(($115)&4294967295);var $116=HEAP8[($arrayidx210)];var $conv211=(tempInt=(($116)),(tempInt>=128?tempInt-256:tempInt));var $cmp212=((($conv211))|0)!=95;if(!($cmp212)){__label__=80;break $if_then206$$if_else209$100;}
$all_upper_case=1;var $117=$word;$p=$117;var $118=$word;$p=$118;var $119=$p;var $call2146=__Z7utf8_inPiPKc($c2,$119);$ix=$call2146;var $120=HEAP32[(($c2)>>2)];var $cmp2157=((($120))|0)==0;if($cmp2157){__label__=78;;}else{__label__=74;;}
$for_end$$if_end217$104:do{if(__label__==74){while(1){var $121=HEAP32[(($c2)>>2)];var $call218=_iswupper($121);var $tobool219=((($call218))|0)!=0;if($tobool219){__label__=75;;}else{__label__=76;;}
if(__label__==75){var $122=HEAP32[(($c2)>>2)];var $call221=_towlower($122);var $123=$p;var $call222=__Z8utf8_outjPc($call221,$123);;}
else if(__label__==76){$all_upper_case=0;;}
var $124=$ix;var $125=$p;var $add_ptr225=(($125+$124)&4294967295);$p=$add_ptr225;var $126=$p;var $call214=__Z7utf8_inPiPKc($c2,$126);$ix=$call214;var $127=HEAP32[(($c2)>>2)];var $cmp215=((($127))|0)==0;if($cmp215){__label__=78;break $for_end$$if_end217$104;}else{__label__=74;continue;}}}}while(0);var $128=$all_upper_case;var $tobool226=((($128))|0)!=0;if(!($tobool226)){__label__=80;break $if_then206$$if_else209$100;}
var $129=$n_flag_codes;var $inc228=((($129)+1)&4294967295);$n_flag_codes=$inc228;var $arrayidx229=(($flag_codes+$129)&4294967295);HEAP8[($arrayidx229)]=42;;}}while(0);var $130=$word;var $call233=_strlen($130);$len_word=$call233;var $131=HEAP32[((_translator)>>2)];var $transpose_min=(($131+288)&4294967295);var $132=HEAP32[(($transpose_min)>>2)];var $cmp234=((($132))|0)>0;if($cmp234){__label__=81;;}else{__label__=82;;}
if(__label__==81){var $133=HEAP32[((_translator)>>2)];var $134=$word;var $call236=__Z17TransposeAlphabetP10TranslatorPc($133,$134);$len_word=$call236;;}
var $135=$word;var $call238=__Z14HashDictionaryPKc($135);var $136=$hash_addr;HEAP32[(($136)>>2)]=$call238;var $arraydecay239=(($encoded_ph)&4294967295);var $call240=_strlen($arraydecay239);$len_phonetic=$call240;var $137=$len_word;var $conv241=((($137))&255);var $138=$dict_line_addr;var $arrayidx242=(($138+1)&4294967295);HEAP8[($arrayidx242)]=$conv241;var $139=$len_word;var $and=($139)&63;$len_word=$and;var $140=$dict_line_addr;var $arrayidx243=(($140+2)&4294967295);var $141=$word;var $142=$len_word;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$141;$dest$=$arrayidx243;$stop$=$src$+$142;if(($dest$%4)==($src$%4)&&$142>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $143=$len_phonetic;var $cmp244=((($143))|0)==0;if($cmp244){__label__=83;;}else{__label__=84;;}
if(__label__==83){var $144=$dict_line_addr;var $arrayidx246=(($144+1)&4294967295);var $145=HEAP8[($arrayidx246)];var $conv247=(tempInt=(($145)),(tempInt>=128?tempInt-256:tempInt));var $or=($conv247)|128;var $conv248=((($or))&255);HEAP8[($arrayidx246)]=$conv248;var $146=$len_word;var $add249=((($146)+2)&4294967295);$length=$add249;;}
else if(__label__==84){var $147=$len_word;var $148=$len_phonetic;var $add251=((($147)+3)&4294967295);var $add252=((($add251)+($148))&4294967295);$length=$add252;var $149=$len_word;var $add253=((($149)+2)&4294967295);var $150=$dict_line_addr;var $arrayidx254=(($150+$add253)&4294967295);var $arraydecay255=(($encoded_ph)&4294967295);var $call256=_strcpy($arrayidx254,$arraydecay255);;}
$ix=0;var $151=$ix;var $152=$n_flag_codes;var $cmp2598=((($151))>>>0)<((($152))>>>0);if($cmp2598){__label__=86;;}else{__label__=87;;}
$for_body$$for_end264$121:do{if(__label__==86){while(1){var $153=$ix;var $arrayidx260=(($flag_codes+$153)&4294967295);var $154=HEAP8[($arrayidx260)];var $155=$ix;var $156=$length;var $add261=((($156)+($155))&4294967295);var $157=$dict_line_addr;var $arrayidx262=(($157+$add261)&4294967295);HEAP8[($arrayidx262)]=$154;var $158=$ix;var $inc263=((($158)+1)&4294967295);$ix=$inc263;var $159=$ix;var $160=$n_flag_codes;var $cmp259=((($159))>>>0)<((($160))>>>0);if($cmp259){__label__=86;continue;}else{__label__=87;break $for_body$$for_end264$121;}}}}while(0);var $161=$n_flag_codes;var $162=$length;var $add265=((($162)+($161))&4294967295);$length=$add265;var $163=$multiple_string;var $cmp266=((($163))|0)!=0;if($cmp266){__label__=88;;}else{__label__=94;;}
$land_lhs_true267$$if_end286$125:do{if(__label__==88){var $164=$multiple_words;var $cmp268=((($164))|0)>0;if(!($cmp268)){__label__=94;break $land_lhs_true267$$if_end286$125;}
var $165=$multiple_words;var $cmp270=((($165))|0)>10;if($cmp270){__label__=90;;}else{__label__=91;;}
if(__label__==90){var $166=HEAP32[((__ZL5f_log)>>2)];var $167=HEAP32[((__ZL7linenum)>>2)];var $168=$multiple_words;var $call272=_fprintf($166,((__str114)&4294967295),allocate([$167,0,0,0,$168,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));;}
else if(__label__==91){var $169=$multiple_words;var $add274=((($169)+80)&4294967295);var $conv275=((($add274))&255);var $170=$length;var $inc276=((($170)+1)&4294967295);$length=$inc276;var $171=$dict_line_addr;var $arrayidx277=(($171+$170)&4294967295);HEAP8[($arrayidx277)]=$conv275;var $172=$multiple_string_end;var $173=$multiple_string;var $sub_ptr_lhs_cast=($172);var $sub_ptr_rhs_cast=($173);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$ix=$sub_ptr_sub;var $174=$multiple_numeric_hyphen;var $tobool278=((($174))|0)!=0;if($tobool278){__label__=92;;}else{__label__=93;;}
if(__label__==92){var $175=$length;var $inc280=((($175)+1)&4294967295);$length=$inc280;var $176=$dict_line_addr;var $arrayidx281=(($176+$175)&4294967295);HEAP8[($arrayidx281)]=32;;}
var $177=$length;var $178=$dict_line_addr;var $arrayidx283=(($178+$177)&4294967295);var $179=$multiple_string;var $180=$ix;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$179;$dest$=$arrayidx283;$stop$=$src$+$180;if(($dest$%4)==($src$%4)&&$180>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $181=$ix;var $182=$length;var $add284=((($182)+($181))&4294967295);$length=$add284;;}}}while(0);var $183=$length;var $conv287=((($183))&255);var $184=$dict_line_addr;var $arrayidx288=(($184)&4294967295);HEAP8[($arrayidx288)]=$conv287;var $185=$length;$retval=$185;;}
var $186=$retval;STACKTOP=__stackBase__;return $186;return null;}
function __Z8strncpy0PcPKci($to,$from,$size){;var __label__;var $to_addr;var $from_addr;var $size_addr;$to_addr=$to;$from_addr=$from;$size_addr=$size;var $0=$to_addr;var $1=$from_addr;var $2=$size_addr;var $call=_strncpy($0,$1,$2);var $3=$size_addr;var $sub=((($3)-1)&4294967295);var $4=$to_addr;var $arrayidx=(($4+$sub)&4294967295);HEAP8[($arrayidx)]=0;;return;return;}
function __Z13Reverse4Bytesi($word){;var __label__;var $word_addr;$word_addr=$word;var $0=$word_addr;;return $0;return null;}
function __Z10LookupMnemP8MNEM_TABPKc($table,$string){;var __label__;var $retval;var $table_addr;var $string_addr;$table_addr=$table;$string_addr=$string;;while(1){var $0=$table_addr;var $mnem=(($0)&4294967295);var $1=HEAP32[(($mnem)>>2)];var $cmp=((($1))|0)!=0;if(!($cmp)){__label__=5;break;}
var $2=$string_addr;var $3=$table_addr;var $mnem1=(($3)&4294967295);var $4=HEAP32[(($mnem1)>>2)];var $call=_strcmp($2,$4);var $cmp2=((($call))|0)==0;var $5=$table_addr;if($cmp2){__label__=3;break;}
var $incdec_ptr=(($5+8)&4294967295);$table_addr=$incdec_ptr;__label__=1;continue;}
if(__label__==5){var $7=$table_addr;var $value3=(($7+4)&4294967295);var $8=HEAP32[(($value3)>>2)];$retval=$8;;}
else if(__label__==3){var $value=(($5+4)&4294967295);var $6=HEAP32[(($value)>>2)];$retval=$6;;}
var $9=$retval;;return $9;return null;}
function __Z14LoadDictionaryP10TranslatorPKci($tr,$name,$no_error){var __stackBase__=STACKTOP;STACKTOP+=172;_memset(__stackBase__,0,172);var __label__;var $retval;var $tr_addr;var $name_addr;var $no_error_addr;var $hash;var $p;var $pw;var $length;var $f;var $size;var $fname=__stackBase__;$tr_addr=$tr;$name_addr=$name;$no_error_addr=$no_error;var $0=$name_addr;var $call=_strcpy(((_dictionary_name)&4294967295),$0);var $1=$tr_addr;var $dictionary_name=(($1+292)&4294967295);var $arraydecay=(($dictionary_name)&4294967295);var $2=$name_addr;var $call1=_strcpy($arraydecay,$2);var $arraydecay2=(($fname)&4294967295);var $3=$name_addr;var $call3=_sprintf($arraydecay2,((__str116)&4294967295),allocate([((_path_home)&4294967295),0,0,0,47,0,0,0,$3,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay4=(($fname)&4294967295);var $call5=__Z13GetFileLengthPKc($arraydecay4);$size=$call5;var $4=$tr_addr;var $data_dictlist=(($4+1052)&4294967295);var $5=HEAP32[(($data_dictlist)>>2)];var $cmp=((($5))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $6=$tr_addr;var $data_dictlist6=(($6+1052)&4294967295);var $7=HEAP32[(($data_dictlist6)>>2)];__Z4FreePv($7);var $8=$tr_addr;var $data_dictlist7=(($8+1052)&4294967295);HEAP32[(($data_dictlist7)>>2)]=0;;}
var $arraydecay8=(($fname)&4294967295);var $call9=_fopen($arraydecay8,((__str18429)&4294967295));$f=$call9;var $cmp10=((($call9))|0)==0;if($cmp10){__label__=4;;}else{__label__=3;;}
$if_then12$$lor_lhs_false$5:do{if(__label__==3){var $9=$size;var $cmp11=((($9))>>>0)<=0;if($cmp11){__label__=4;break $if_then12$$lor_lhs_false$5;}
var $13=$size;var $call19=__Z5Alloci($13);var $14=$tr_addr;var $data_dictlist20=(($14+1052)&4294967295);HEAP32[(($data_dictlist20)>>2)]=$call19;var $15=$tr_addr;var $data_dictlist21=(($15+1052)&4294967295);var $16=HEAP32[(($data_dictlist21)>>2)];var $17=$size;var $18=$f;var $call22=_fread($16,1,$17,$18);$size=$call22;var $19=$f;var $call23=_fclose($19);var $20=$tr_addr;var $data_dictlist24=(($20+1052)&4294967295);var $21=HEAP32[(($data_dictlist24)>>2)];var $22=$21;$pw=$22;var $23=$pw;var $arrayidx=(($23+4)&4294967295);var $24=HEAP32[(($arrayidx)>>2)];var $call25=__Z13Reverse4Bytesi($24);$length=$call25;var $25=$size;var $cmp26=((($25))>>>0)<=1032;if($cmp26){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $26=HEAP32[((__impure_ptr)>>2)];var $_stderr28=(($26+12)&4294967295);var $27=HEAP32[(($_stderr28)>>2)];var $arraydecay29=(($fname)&4294967295);var $call30=_fprintf($27,((__str3119)&4294967295),allocate([$arraydecay29,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=2;__label__=19;break $if_then12$$lor_lhs_false$5;}
else if(__label__==9){var $28=$pw;var $arrayidx32=(($28)&4294967295);var $29=HEAP32[(($arrayidx32)>>2)];var $call33=__Z13Reverse4Bytesi($29);var $cmp34=((($call33))|0)!=1024;if($cmp34){__label__=11;;}else{__label__=10;;}
$if_then39$$lor_lhs_false35$11:do{if(__label__==10){var $30=$length;var $cmp36=((($30))|0)<=0;var $31=$length;var $cmp38=((($31))|0)>134217728;var $or_cond=($cmp36)|($cmp38);if($or_cond){__label__=11;break $if_then39$$lor_lhs_false35$11;}
var $37=$length;var $38=$tr_addr;var $data_dictlist46=(($38+1052)&4294967295);var $39=HEAP32[(($data_dictlist46)>>2)];var $arrayidx47=(($39+$37)&4294967295);var $40=$tr_addr;var $data_dictrules=(($40+1048)&4294967295);HEAP32[(($data_dictrules)>>2)]=$arrayidx47;var $41=$tr_addr;__ZL10InitGroupsP10Translator($41);var $42=$tr_addr;var $groups1=(($42+5256)&4294967295);var $arrayidx48=(($groups1)&4294967295);var $43=HEAP32[(($arrayidx48)>>2)];var $cmp49=((($43))|0)==0;if($cmp49){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $44=HEAP32[((__impure_ptr)>>2)];var $_stderr51=(($44+12)&4294967295);var $45=HEAP32[(($_stderr51)>>2)];var $46=$name_addr;var $call52=_fprintf($45,((__str5121)&4294967295),allocate([$46,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
var $47=$tr_addr;var $data_dictlist54=(($47+1052)&4294967295);var $48=HEAP32[(($data_dictlist54)>>2)];var $arrayidx55=(($48+8)&4294967295);$p=$arrayidx55;$hash=0;;$for_body$17:while(1){var $49=$p;var $50=$hash;var $51=$tr_addr;var $dict_hashtab=(($51+1056)&4294967295);var $arrayidx57=(($dict_hashtab+$50*4)&4294967295);HEAP32[(($arrayidx57)>>2)]=$49;var $52=$p;var $53=HEAP8[($52)];var $conv1=(tempInt=(($53)),(tempInt>=128?tempInt-256:tempInt));$length=$conv1;var $cmp582=((($conv1))|0)!=0;if($cmp582){__label__=16;;}else{__label__=17;;}
$while_body$$while_end$19:do{if(__label__==16){while(1){var $54=$length;var $55=$p;var $add_ptr=(($55+$54)&4294967295);$p=$add_ptr;var $56=$p;var $57=HEAP8[($56)];var $conv=(tempInt=(($57)),(tempInt>=128?tempInt-256:tempInt));$length=$conv;var $cmp58=((($conv))|0)!=0;if($cmp58){__label__=16;continue;}else{__label__=17;break $while_body$$while_end$19;}}}}while(0);var $58=$p;var $incdec_ptr=(($58+1)&4294967295);$p=$incdec_ptr;var $59=$hash;var $inc=((($59)+1)&4294967295);$hash=$inc;var $cmp56=((($inc))|0)<1024;if($cmp56){__label__=15;continue $for_body$17;}else{__label__=18;break $for_body$17;}}
$retval=0;__label__=19;break $if_then12$$lor_lhs_false$5;}}while(0);var $32=HEAP32[((__impure_ptr)>>2)];var $_stderr40=(($32+12)&4294967295);var $33=HEAP32[(($_stderr40)>>2)];var $arraydecay41=(($fname)&4294967295);var $34=$pw;var $arrayidx42=(($34)&4294967295);var $35=HEAP32[(($arrayidx42)>>2)];var $call43=__Z13Reverse4Bytesi($35);var $36=$length;var $call44=_fprintf($33,((__str4120)&4294967295),allocate([$arraydecay41,0,0,0,$call43,0,0,0,$36,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STACK));$retval=2;__label__=19;break $if_then12$$lor_lhs_false$5;}}}while(0);if(__label__==4){var $10=$no_error_addr;var $cmp13=((($10))|0)==0;if($cmp13){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $11=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($11+12)&4294967295);var $12=HEAP32[(($_stderr)>>2)];var $arraydecay15=(($fname)&4294967295);var $call16=_fprintf($12,((__str2118)&4294967295),allocate([$arraydecay15,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
$retval=1;;}
var $60=$retval;STACKTOP=__stackBase__;return $60;return null;}
function __ZL10InitGroupsP10Translator($tr){;var __label__;var __lastLabel__=null;var $tr_addr;var $ix;var $p;var $p_name;var $pw;var $c;var $c2;var $len;$tr_addr=$tr;var $0=$tr_addr;var $n_groups2=(($0+7752)&4294967295);HEAP32[(($n_groups2)>>2)]=0;$ix=0;;$for_body$2:while(1){var $1=$ix;var $2=$tr_addr;var $groups1=(($2+5256)&4294967295);var $arrayidx=(($groups1+$1*4)&4294967295);HEAP32[(($arrayidx)>>2)]=0;var $3=$ix;var $4=$tr_addr;var $groups2_count=(($4+7756)&4294967295);var $arrayidx1=(($groups2_count+$3)&4294967295);HEAP8[($arrayidx1)]=0;var $5=$ix;var $6=$tr_addr;var $groups2_start=(($6+8012)&4294967295);var $arrayidx2=(($groups2_start+$5)&4294967295);HEAP8[($arrayidx2)]=-1;var $7=$ix;var $inc=((($7)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<256;if($cmp){__label__=1;continue $for_body$2;}else{__label__=2;break $for_body$2;}}
var $8=$tr_addr;var $letterGroups=(($8+5152)&4294967295);var $arraydecay=(($letterGroups)&4294967295);var $9=$arraydecay;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$9;$stop$=$dest$+104;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $10=$tr_addr;var $groups3=(($10+6280)&4294967295);var $arraydecay3=(($groups3)&4294967295);var $11=$arraydecay3;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$11;$stop$=$dest$+512;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $12=$tr_addr;var $data_dictrules=(($12+1048)&4294967295);var $13=HEAP32[(($data_dictrules)>>2)];$p=$13;;$while_cond$5:while(1){var $14=$p;var $15=HEAP8[($14)];var $conv=(tempInt=(($15)),(tempInt>=128?tempInt-256:tempInt));var $cmp4=((($conv))|0)!=0;if(!($cmp4)){__label__=25;break $while_cond$5;}
var $16=$p;var $17=HEAP8[($16)];var $conv5=(tempInt=(($17)),(tempInt>=128?tempInt-256:tempInt));var $cmp6=((($conv5))|0)!=6;if($cmp6){__label__=5;break $while_cond$5;}
var $23=$p;var $incdec_ptr=(($23+1)&4294967295);$p=$incdec_ptr;var $24=$p;var $arrayidx8=(($24)&4294967295);var $25=HEAP8[($arrayidx8)];var $conv9=(tempInt=(($25)),(tempInt>=128?tempInt-256:tempInt));var $cmp10=((($conv9))|0)==20;var $26=$p;if($cmp10){__label__=7;;}else{__label__=10;;}
if(__label__==7){var $27=($26);var $add=((($27)+4)&4294967295);var $and=($add)&-4;var $28=($and);$pw=$28;var $29=$pw;var $30=$tr_addr;var $langopts=(($30)&4294967295);var $replace_chars=(($langopts+264)&4294967295);HEAP32[(($replace_chars)>>2)]=$29;var $31=$pw;var $arrayidx134=(($31)&4294967295);var $32=HEAP32[(($arrayidx134)>>2)];var $cmp145=((($32))|0)!=0;var $33=$pw;if($cmp145){__lastLabel__=7;__label__=8;;}else{__lastLabel__=7;__label__=9;;}
$while_body15$$while_end$11:do{if(__label__==8){while(1){var $34=__lastLabel__==8?$37:($33);var $add_ptr=(($34+8)&4294967295);$pw=$add_ptr;var $35=$pw;var $arrayidx13=(($35)&4294967295);var $36=HEAP32[(($arrayidx13)>>2)];var $cmp14=((($36))|0)!=0;var $37=$pw;if($cmp14){__lastLabel__=8;__label__=8;continue;}else{__lastLabel__=8;__label__=9;break $while_body15$$while_end$11;}}}}while(0);var $_lcssa3=__lastLabel__==7?$33:($37);var $add_ptr16=(($_lcssa3+4)&4294967295);var $38=$add_ptr16;$p=$38;__label__=3;continue $while_cond$5;}
else if(__label__==10){var $arrayidx18=(($26)&4294967295);var $39=HEAP8[($arrayidx18)];var $conv19=(tempInt=(($39)),(tempInt>=128?tempInt-256:tempInt));var $cmp20=((($conv19))|0)==18;var $40=$p;if($cmp20){__label__=11;;}else{__label__=13;;}
$if_then21$$if_else$16:do{if(__label__==11){var $arrayidx22=(($40+1)&4294967295);var $41=HEAP8[($arrayidx22)];var $conv23=(tempInt=(($41)),(tempInt>=128?tempInt-256:tempInt));var $sub=((($conv23)-65)&4294967295);$ix=$sub;var $42=$p;var $add_ptr24=(($42+2)&4294967295);$p=$add_ptr24;var $43=$ix;var $cmp25=((($43))|0)>=0;var $44=$ix;var $cmp26=((($44))|0)<26;var $or_cond=($cmp25)&($cmp26);if(!($or_cond)){__label__=22;break $if_then21$$if_else$16;}
var $45=$p;var $46=$ix;var $47=$tr_addr;var $letterGroups28=(($47+5152)&4294967295);var $arrayidx29=(($letterGroups28+$46*4)&4294967295);HEAP32[(($arrayidx29)>>2)]=$45;;}
else if(__label__==13){var $call31=_strlen($40);$len=$call31;var $48=$p;$p_name=$48;var $49=$p_name;var $arrayidx32=(($49)&4294967295);var $50=HEAP8[($arrayidx32)];$c=$50;var $51=$p_name;var $arrayidx33=(($51+1)&4294967295);var $52=HEAP8[($arrayidx33)];$c2=$52;var $53=$len;var $add34=((($53)+1)&4294967295);var $54=$p;var $add_ptr35=(($54+$add34)&4294967295);$p=$add_ptr35;var $55=$len;var $cmp36=((($55))|0)==1;if($cmp36){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $56=$p;var $57=$c;var $idxprom=((($57))&255);var $58=$tr_addr;var $groups138=(($58+5256)&4294967295);var $arrayidx39=(($groups138+$idxprom*4)&4294967295);HEAP32[(($arrayidx39)>>2)]=$56;;}
else if(__label__==15){var $59=$len;var $cmp41=((($59))|0)==0;if($cmp41){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $60=$p;var $61=$tr_addr;var $groups143=(($61+5256)&4294967295);var $arrayidx44=(($groups143)&4294967295);HEAP32[(($arrayidx44)>>2)]=$60;;}
else if(__label__==17){var $62=$c;var $conv46=((($62))&255);var $cmp47=((($conv46))|0)==1;if($cmp47){__label__=18;;}else{__label__=19;;}
if(__label__==18){var $63=$p;var $64=$c2;var $conv49=((($64))&255);var $sub50=((($conv49)-1)&4294967295);var $65=$tr_addr;var $groups351=(($65+6280)&4294967295);var $arrayidx52=(($groups351+$sub50*4)&4294967295);HEAP32[(($arrayidx52)>>2)]=$63;;}
else if(__label__==19){var $66=$c;var $idxprom54=((($66))&255);var $67=$tr_addr;var $groups2_start55=(($67+8012)&4294967295);var $arrayidx56=(($groups2_start55+$idxprom54)&4294967295);var $68=HEAPU8[($arrayidx56)];var $conv57=((($68))&255);var $cmp58=((($conv57))|0)==255;if($cmp58){__label__=20;;}else{__label__=21;;}
if(__label__==20){var $69=$tr_addr;var $n_groups260=(($69+7752)&4294967295);var $70=HEAP32[(($n_groups260)>>2)];var $conv61=((($70))&255);var $71=$c;var $idxprom62=((($71))&255);var $72=$tr_addr;var $groups2_start63=(($72+8012)&4294967295);var $arrayidx64=(($groups2_start63+$idxprom62)&4294967295);HEAP8[($arrayidx64)]=$conv61;;}
var $73=$c;var $idxprom66=((($73))&255);var $74=$tr_addr;var $groups2_count67=(($74+7756)&4294967295);var $arrayidx68=(($groups2_count67+$idxprom66)&4294967295);var $75=HEAP8[($arrayidx68)];var $inc69=((($75)+1)&255);HEAP8[($arrayidx68)]=$inc69;var $76=$p;var $77=$tr_addr;var $n_groups270=(($77+7752)&4294967295);var $78=HEAP32[(($n_groups270)>>2)];var $79=$tr_addr;var $groups2=(($79+6792)&4294967295);var $arrayidx71=(($groups2+$78*4)&4294967295);HEAP32[(($arrayidx71)>>2)]=$76;var $80=$c;var $conv72=((($80))&255);var $81=$c2;var $conv73=((($81))&255);var $shl=((($conv73)*256)&4294967295);var $add74=((($shl)+($conv72))&4294967295);var $82=$tr_addr;var $n_groups275=(($82+7752)&4294967295);var $83=HEAPU32[(($n_groups275)>>2)];var $inc76=((($83)+1)&4294967295);HEAP32[(($n_groups275)>>2)]=$inc76;var $84=$tr_addr;var $groups2_name=(($84+7272)&4294967295);var $arrayidx77=(($groups2_name+$83*4)&4294967295);HEAP32[(($arrayidx77)>>2)]=$add74;;}}}}}while(0);var $85=$p;var $86=HEAP8[($85)];var $conv831=(tempInt=(($86)),(tempInt>=128?tempInt-256:tempInt));var $cmp842=((($conv831))|0)!=7;var $87=$p;if($cmp842){__lastLabel__=22;__label__=23;;}else{__lastLabel__=22;__label__=24;;}
$while_body85$$while_end89$33:do{if(__label__==23){while(1){var $88=__lastLabel__==23?$92:($87);var $call86=_strlen($88);var $add87=((($call86)+1)&4294967295);var $89=$p;var $add_ptr88=(($89+$add87)&4294967295);$p=$add_ptr88;var $90=$p;var $91=HEAP8[($90)];var $conv83=(tempInt=(($91)),(tempInt>=128?tempInt-256:tempInt));var $cmp84=((($conv83))|0)!=7;var $92=$p;if($cmp84){__lastLabel__=23;__label__=23;continue;}else{__lastLabel__=23;__label__=24;break $while_body85$$while_end89$33;}}}}while(0);var $_lcssa=__lastLabel__==22?$87:($92);var $incdec_ptr90=(($_lcssa+1)&4294967295);$p=$incdec_ptr90;__label__=3;continue $while_cond$5;}}
if(__label__==5){var $18=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($18+12)&4294967295);var $19=HEAP32[(($_stderr)>>2)];var $20=$p;var $21=$tr_addr;var $data_dictrules7=(($21+1048)&4294967295);var $22=HEAP32[(($data_dictrules7)>>2)];var $sub_ptr_lhs_cast=($20);var $sub_ptr_rhs_cast=($22);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);var $call=_fprintf($19,((__str34150)&4294967295),allocate([((_dictionary_name)&4294967295),0,0,0,$sub_ptr_sub,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));;};return;return;}
function __Z14HashDictionaryPKc($string){;var __label__;var __lastLabel__=null;var $string_addr;var $c;var $chars;var $hash;$string_addr=$string;$chars=0;$hash=0;var $0=$string_addr;var $incdec_ptr1=(($0+1)&4294967295);$string_addr=$incdec_ptr1;var $1=HEAP8[($0)];var $conv2=(tempInt=(($1)),(tempInt>=128?tempInt-256:tempInt));var $and4=($conv2)&255;$c=$and4;var $cmp5=((($and4))|0)!=0;var $2=$hash;if($cmp5){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=2;;}
$while_body$$while_end$2:do{if(__label__==1){while(1){var $3=__lastLabel__==1?$10:($2);var $mul=((($3)*8)&4294967295);var $4=$c;var $add=((($4)+($mul))&4294967295);$hash=$add;var $5=$hash;var $and1=($5)&1023;var $6=$hash;var $shr=($6)>>8;var $xor=($shr)^($and1);$hash=$xor;var $7=$chars;var $inc=((($7)+1)&4294967295);$chars=$inc;var $8=$string_addr;var $incdec_ptr=(($8+1)&4294967295);$string_addr=$incdec_ptr;var $9=HEAP8[($8)];var $conv=(tempInt=(($9)),(tempInt>=128?tempInt-256:tempInt));var $and=($conv)&255;$c=$and;var $cmp=((($and))|0)!=0;var $10=$hash;if($cmp){__lastLabel__=1;__label__=1;continue;}else{__lastLabel__=1;__label__=2;break $while_body$$while_end$2;}}}}while(0);var $_lcssa=__lastLabel__==0?$2:($10);var $11=$chars;var $add2=((($11)+($_lcssa))&4294967295);var $and3=($add2)&1023;;return $and3;return null;}
function __Z14EncodePhonemesPcS_Ph($p,$outptr,$bad_phoneme){;var __label__;var __lastLabel__=null;var $retval;var $p_addr;var $outptr_addr;var $bad_phoneme_addr;var $ix;var $c;var $count;var $max;var $max_ph;var $consumed;var $mnemonic_word;var $p_lang;$p_addr=$p;$outptr_addr=$outptr;$bad_phoneme_addr=$bad_phoneme;var $0=$bad_phoneme_addr;var $arrayidx=(($0)&4294967295);HEAP8[($arrayidx)]=0;var $1=$p_addr;var $2=HEAP8[($1)];var $conv4=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));var $call5=_isspace($conv4);var $tobool6=((($call5))|0)!=0;if($tobool6){__label__=1;;}else{__label__=2;;}
$while_body$$while_cond1$2:do{if(__label__==1){while(1){var $3=$p_addr;var $incdec_ptr=(($3+1)&4294967295);$p_addr=$incdec_ptr;var $4=$p_addr;var $5=HEAP8[($4)];var $conv=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $call=_isspace($conv);var $tobool=((($call))|0)!=0;if($tobool){__label__=1;continue;}else{__label__=2;break $while_body$$while_cond1$2;}}}}while(0);$while_cond1$5:while(1){var $6=$p_addr;var $7=HEAPU8[($6)];$c=$7;var $conv2=((($7))&255);var $cmp=((($conv2))|0)!=0;if(!($cmp)){__label__=34;break $while_cond1$5;}
var $8=$c;var $conv3=((($8))&255);var $call4=_isspace($conv3);var $tobool5=((($call4))|0)!=0;var $lnot=($tobool5)^1;if(!($lnot)){__label__=34;break $while_cond1$5;}
$consumed=0;var $9=$c;var $conv7=((($9))&255);var $cond=((($conv7))|0)==124;if($cond){__label__=5;;}else{__label__=7;;}
$sw_bb$$sw_default$9:do{if(__label__==5){var $10=$p_addr;var $arrayidx8=(($10+1)&4294967295);var $11=HEAPU8[($arrayidx8)];$c=$11;var $conv9=((($11))&255);var $cmp10=((($conv9))|0)==124;if($cmp10){__label__=7;break $sw_bb$$sw_default$9;}
var $12=$p_addr;var $incdec_ptr11=(($12+1)&4294967295);$p_addr=$incdec_ptr11;__label__=2;continue $while_cond1$5;}}while(0);$max=-1;$max_ph=0;$ix=1;var $13=$ix;var $14=HEAP32[((_n_phoneme_tab)>>2)];var $cmp121=((($13))|0)<((($14))|0);if(!($cmp121)){__label__=22;break $while_cond1$5;}
$for_body$13:while(1){var $15=$ix;var $arrayidx13=((_phoneme_tab+$15*4)&4294967295);var $16=HEAP32[(($arrayidx13)>>2)];var $cmp14=((($16))|0)==0;if($cmp14){__label__=20;;}else{__label__=9;;}
$for_inc$$if_end16$15:do{if(__label__==9){var $17=$ix;var $arrayidx17=((_phoneme_tab+$17*4)&4294967295);var $18=HEAP32[(($arrayidx17)>>2)];var $type=(($18+11)&4294967295);var $19=HEAPU8[($type)];var $conv18=((($19))&255);var $cmp19=((($conv18))|0)==15;if($cmp19){__label__=20;break $for_inc$$if_end16$15;}
$count=0;var $20=$ix;var $arrayidx22=((_phoneme_tab+$20*4)&4294967295);var $21=HEAP32[(($arrayidx22)>>2)];var $mnemonic=(($21)&4294967295);var $22=HEAP32[(($mnemonic)>>2)];$mnemonic_word=$22;;while(1){var $23=$count;var $24=$p_addr;var $arrayidx24=(($24+$23)&4294967295);var $25=HEAPU8[($arrayidx24)];$c=$25;var $conv25=((($25))&255);var $cmp26=((($conv25))|0)>32;if(!($cmp26)){__label__=13;break;}
var $26=$count;var $cmp27=((($26))|0)<4;if(!($cmp27)){__label__=13;break;}
var $28=$c;var $conv29=((($28))&255);var $29=$mnemonic_word;var $30=$count;var $mul=((($30)*8)&4294967295);var $shr=($29)>>>((($mul))>>>0);var $and=($shr)&255;var $cmp30=((($conv29))|0)==((($and))|0);var $31=$count;if($cmp30){__lastLabel__=14;;}else{__lastLabel__=14;__label__=16;break;}
var $inc=((($31)+1)&4294967295);$count=$inc;__label__=11;continue;}
if(__label__==13){var $27=$count;__lastLabel__=13;;}
var $32=__lastLabel__==13?$27:($31);var $33=$max;var $cmp34=((($32))|0)>((($33))|0);if(!($cmp34)){__label__=20;break $for_inc$$if_end16$15;}
var $34=$count;var $cmp36=((($34))|0)==4;if($cmp36){__label__=19;;}else{__label__=18;;}
if(__label__==18){var $35=$mnemonic_word;var $36=$count;var $mul37=((($36)*8)&4294967295);var $shr38=($35)>>>((($mul37))>>>0);var $and39=($shr38)&255;var $cmp40=((($and39))|0)==0;if(!($cmp40)){__label__=20;break $for_inc$$if_end16$15;}}
var $37=$count;$max=$37;var $38=$ix;var $arrayidx42=((_phoneme_tab+$38*4)&4294967295);var $39=HEAP32[(($arrayidx42)>>2)];var $code=(($39+10)&4294967295);var $40=HEAPU8[($code)];var $conv43=((($40))&255);$max_ph=$conv43;;}}while(0);var $41=$ix;var $inc45=((($41)+1)&4294967295);$ix=$inc45;var $42=$ix;var $43=HEAP32[((_n_phoneme_tab)>>2)];var $cmp12=((($42))|0)<((($43))|0);if($cmp12){__label__=8;continue $for_body$13;}else{__label__=21;break $for_body$13;}}
var $_pr=$max_ph;var $cmp46=((($_pr))|0)==0;if($cmp46){__label__=22;break $while_cond1$5;}
var $50=$max;var $cmp52=((($50))|0)<=0;if($cmp52){__label__=24;;}else{__label__=25;;}
if(__label__==24){$max=1;;}
var $51=$consumed;var $52=$max;var $add=((($52)+($51))&4294967295);var $53=$p_addr;var $add_ptr55=(($53+$add)&4294967295);$p_addr=$add_ptr55;var $54=$max_ph;var $conv56=((($54))&255);var $55=$outptr_addr;var $incdec_ptr57=(($55+1)&4294967295);$outptr_addr=$incdec_ptr57;HEAP8[($55)]=$conv56;var $56=$max_ph;var $cmp58=((($56))|0)==21;if(!($cmp58)){__label__=2;continue $while_cond1$5;}
var $57=$outptr_addr;$p_lang=$57;;while(1){var $58=$p_addr;var $59=HEAPU8[($58)];$c=$59;var $conv61=((($59))&255);var $call62=_isspace($conv61);var $tobool63=((($call62))|0)!=0;if($tobool63){__label__=30;break;}
var $60=$c;var $conv65=((($60))&255);var $cmp66=((($conv65))|0)!=0;if(!($cmp66)){__label__=30;break;}
var $61=$p_addr;var $incdec_ptr69=(($61+1)&4294967295);$p_addr=$incdec_ptr69;var $62=$c;var $conv70=((($62))&255);var $call71=_tolower($conv70);var $conv72=((($call71))&255);var $63=$outptr_addr;var $incdec_ptr73=(($63+1)&4294967295);$outptr_addr=$incdec_ptr73;HEAP8[($63)]=$conv72;__label__=27;continue;}
var $64=$outptr_addr;HEAP8[($64)]=0;var $65=$c;var $conv75=((($65))&255);var $cmp76=((($conv75))|0)==0;if($cmp76){__label__=31;;}else{__label__=33;;}
if(__label__==31){var $66=$p_lang;var $call78=_strcmp($66,((__str52704)&4294967295));var $cmp79=((($call78))|0)==0;if($cmp79){__label__=32;break $while_cond1$5;}else{__label__=2;continue $while_cond1$5;}}
else if(__label__==33){var $69=$outptr_addr;var $incdec_ptr83=(($69+1)&4294967295);$outptr_addr=$incdec_ptr83;HEAP8[($69)]=124;__label__=2;continue $while_cond1$5;}}
if(__label__==34){var $70=$outptr_addr;HEAP8[($70)]=0;var $71=$p_addr;$retval=$71;;}
else if(__label__==22){var $44=$p_addr;var $45=HEAP8[($44)];var $46=$bad_phoneme_addr;var $arrayidx48=(($46)&4294967295);HEAP8[($arrayidx48)]=$45;var $47=$bad_phoneme_addr;var $arrayidx49=(($47+1)&4294967295);HEAP8[($arrayidx49)]=0;var $48=$outptr_addr;var $incdec_ptr50=(($48+1)&4294967295);$outptr_addr=$incdec_ptr50;HEAP8[($48)]=0;var $49=$p_addr;var $add_ptr=(($49+1)&4294967295);$retval=$add_ptr;;}
else if(__label__==32){var $67=$p_lang;HEAP8[($67)]=0;var $68=$p_addr;$retval=$68;;}
var $72=$retval;;return $72;return null;}
function __Z14DecodePhonemesPKcPc($inptr,$outptr){;var __label__;var $inptr_addr;var $outptr_addr;var $phcode;var $c;var $mnem;var $ph;$inptr_addr=$inptr;$outptr_addr=$outptr;var $0=$inptr_addr;var $incdec_ptr8=(($0+1)&4294967295);$inptr_addr=$incdec_ptr8;var $1=HEAPU8[($0)];$phcode=$1;var $conv9=((($1))&255);var $cmp10=((($conv9))|0)>0;if($cmp10){__label__=1;;}else{__label__=14;;}
$while_body$$while_end40$2:do{if(__label__==1){$while_body$3:while(1){var $2=$phcode;var $conv1=((($2))&255);var $cmp2=((($conv1))|0)==255;if($cmp2){__label__=2;;}else{__label__=3;;}
$while_cond_backedge$$if_end$5:do{if(__label__==3){var $5=$phcode;var $idxprom=((($5))&255);var $arrayidx=((_phoneme_tab+$idxprom*4)&4294967295);var $6=HEAPU32[(($arrayidx)>>2)];$ph=$6;var $cmp3=((($6))|0)==0;if($cmp3){__label__=2;break $while_cond_backedge$$if_end$5;}
var $7=$ph;var $type=(($7+11)&4294967295);var $8=HEAPU8[($type)];var $conv6=((($8))&255);var $cmp7=((($conv6))|0)==1;if($cmp7){__label__=5;;}else{__label__=9;;}
$land_lhs_true$$if_else$8:do{if(__label__==5){var $9=$ph;var $std_length=(($9+14)&4294967295);var $10=HEAPU8[($std_length)];var $conv8=((($10))&255);var $cmp9=((($conv8))|0)<=4;if(!($cmp9)){__label__=9;break $land_lhs_true$$if_else$8;}
var $11=$ph;var $program=(($11+8)&4294967295);var $12=HEAPU16[(($program)>>1)];var $conv11=((($12))&65535);var $cmp12=((($conv11))|0)==0;if(!($cmp12)){__label__=9;break $land_lhs_true$$if_else$8;}
var $13=$ph;var $std_length14=(($13+14)&4294967295);var $14=HEAPU8[($std_length14)];var $conv15=((($14))&255);var $cmp16=((($conv15))|0)>1;if(!($cmp16)){__label__=2;break $while_cond_backedge$$if_end$5;}
var $15=$ph;var $std_length18=(($15+14)&4294967295);var $16=HEAPU8[($std_length18)];var $idxprom19=((($16))&255);var $arrayidx20=((((__str7123)&4294967295)+$idxprom19)&4294967295);var $17=HEAP8[($arrayidx20)];var $18=$outptr_addr;var $incdec_ptr21=(($18+1)&4294967295);$outptr_addr=$incdec_ptr21;HEAP8[($18)]=$17;__label__=2;break $while_cond_backedge$$if_end$5;}}while(0);var $19=$ph;var $mnemonic=(($19)&4294967295);var $20=HEAP32[(($mnemonic)>>2)];$mnem=$20;var $21=$mnem;var $and4=($21)&255;var $conv245=((($and4))&255);$c=$conv245;var $conv256=((($conv245))&255);var $cmp267=((($conv256))|0)!=0;if($cmp267){__label__=10;;}else{__label__=11;;}
$while_body27$$while_end$14:do{if(__label__==10){while(1){var $22=$c;var $23=$outptr_addr;var $incdec_ptr28=(($23+1)&4294967295);$outptr_addr=$incdec_ptr28;HEAP8[($23)]=$22;var $24=$mnem;var $shr=($24)>>>8;$mnem=$shr;var $25=$mnem;var $and=($25)&255;var $conv24=((($and))&255);$c=$conv24;var $conv25=((($conv24))&255);var $cmp26=((($conv25))|0)!=0;if($cmp26){__label__=10;continue;}else{__label__=11;break $while_body27$$while_end$14;}}}}while(0);var $26=$phcode;var $conv29=((($26))&255);var $cmp30=((($conv29))|0)==21;if(!($cmp30)){__label__=2;break $while_cond_backedge$$if_end$5;}
var $27=$inptr_addr;var $28=HEAP8[($27)];var $conv331=(tempInt=(($28)),(tempInt>=128?tempInt-256:tempInt));var $call2=_isalpha($conv331);var $tobool3=((($call2))|0)!=0;if(!($tobool3)){__label__=2;break $while_cond_backedge$$if_end$5;}
while(1){var $29=$inptr_addr;var $incdec_ptr35=(($29+1)&4294967295);$inptr_addr=$incdec_ptr35;var $30=HEAP8[($29)];var $31=$outptr_addr;var $incdec_ptr36=(($31+1)&4294967295);$outptr_addr=$incdec_ptr36;HEAP8[($31)]=$30;var $32=$inptr_addr;var $33=HEAP8[($32)];var $conv33=(tempInt=(($33)),(tempInt>=128?tempInt-256:tempInt));var $call=_isalpha($conv33);var $tobool=((($call))|0)!=0;if($tobool){__label__=13;continue;}else{__label__=2;break $while_cond_backedge$$if_end$5;}}}}while(0);var $3=$inptr_addr;var $incdec_ptr=(($3+1)&4294967295);$inptr_addr=$incdec_ptr;var $4=HEAPU8[($3)];$phcode=$4;var $conv=((($4))&255);var $cmp=((($conv))|0)>0;if($cmp){__label__=1;continue $while_body$3;}else{__label__=14;break $while_body$$while_end40$2;}}}}while(0);var $34=$outptr_addr;HEAP8[($34)]=0;;return;return;}
function __Z26GetTranslatedPhonemeStringPci($phon_out,$n_phon_out){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $phon_out_addr;var $n_phon_out_addr;var $ix;var $phon_out_ix=__stackBase__;var $stress;var $c;var $p;var $plist;$phon_out_addr=$phon_out;$n_phon_out_addr=$n_phon_out;HEAP32[(($phon_out_ix)>>2)]=0;var $0=$phon_out_addr;var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=28;;}
if(__label__==1){$ix=1;;$for_cond$4:while(1){var $1=$ix;var $2=HEAP32[((_n_phoneme_list)>>2)];var $sub=((($2)-2)&4294967295);var $cmp1=((($1))|0)<((($sub))|0);if(!($cmp1)){__label__=25;break $for_cond$4;}
var $3=HEAP32[(($phon_out_ix)>>2)];var $4=$n_phon_out_addr;var $sub2=((($4)-6)&4294967295);var $cmp3=((($3))|0)<((($sub2))|0);if(!($cmp3)){__label__=25;break $for_cond$4;}
var $5=$ix;var $arrayidx=((_phoneme_list+$5*24)&4294967295);$plist=$arrayidx;var $6=$plist;var $newword=(($6+19)&4294967295);var $7=HEAP8[($newword)];var $tobool=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $8=HEAP32[(($phon_out_ix)>>2)];var $inc=((($8)+1)&4294967295);HEAP32[(($phon_out_ix)>>2)]=$inc;var $9=$phon_out_addr;var $arrayidx5=(($9+$8)&4294967295);HEAP8[($arrayidx5)]=32;;}
var $10=$plist;var $synthflags=(($10+4)&4294967295);var $11=HEAPU16[(($synthflags)>>1)];var $conv=((($11))&65535);var $and=($conv)&4;var $tobool6=((($and))|0)!=0;if($tobool6){__label__=7;;}else{__label__=15;;}
$if_then7$$if_end27$11:do{if(__label__==7){var $12=$plist;var $stresslevel=(($12+1)&4294967295);var $13=HEAPU8[($stresslevel)];var $conv8=((($13))&255);$stress=$conv8;var $cmp9=((($conv8))|0)>1;if(!($cmp9)){__label__=15;break $if_then7$$if_end27$11;}
$c=0;var $14=$stress;var $cmp11=((($14))|0)>5;if($cmp11){__label__=9;;}else{__label__=10;;}
if(__label__==9){$stress=5;;}
var $15=HEAP32[((_option_phonemes)>>2)];var $cmp14=((($15))|0)==3;if($cmp14){__label__=11;;}else{__label__=13;;}
$if_then15$$if_end21$17:do{if(__label__==11){$c=716;var $16=$stress;var $cmp16=((($16))|0)>3;if(!($cmp16)){__label__=14;break $if_then15$$if_end21$17;}
$c=712;;}
else if(__label__==13){var $17=$stress;var $arrayidx19=((((__str8124)&4294967295)+$17)&4294967295);var $18=HEAP8[($arrayidx19)];var $conv20=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));$c=$conv20;var $cmp22=((($conv20))|0)!=0;if(!($cmp22)){__label__=15;break $if_then7$$if_end27$11;}}}while(0);var $19=$c;var $20=HEAP32[(($phon_out_ix)>>2)];var $21=$phon_out_addr;var $arrayidx24=(($21+$20)&4294967295);var $call=__Z8utf8_outjPc($19,$arrayidx24);var $22=HEAP32[(($phon_out_ix)>>2)];var $add=((($22)+($call))&4294967295);HEAP32[(($phon_out_ix)>>2)]=$add;;}}while(0);var $23=$plist;var $ph=(($23+8)&4294967295);var $24=HEAP32[(($ph)>>2)];var $code=(($24+10)&4294967295);var $25=HEAPU8[($code)];var $conv28=((($25))&255);var $cmp29=((($conv28))|0)==21;if($cmp29){__label__=16;;}else{__label__=17;;}
$if_then30$$if_else37$23:do{if(__label__==16){var $26=$plist;var $tone_ph=(($26+3)&4294967295);var $27=HEAPU8[($tone_ph)];var $idxprom=((($27))&255);var $arrayidx31=((_phoneme_tab_list+$idxprom*48)&4294967295);var $name=(($arrayidx31)&4294967295);var $arraydecay=(($name)&4294967295);$p=$arraydecay;var $28=HEAP32[(($phon_out_ix)>>2)];var $29=$phon_out_addr;var $arrayidx32=(($29+$28)&4294967295);var $30=$p;var $call33=_sprintf($arrayidx32,((__str9125)&4294967295),allocate([$30,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $31=$p;var $call34=_strlen($31);var $32=HEAP32[(($phon_out_ix)>>2)];var $add35=((($call34)+2)&4294967295);var $add36=((($add35)+($32))&4294967295);HEAP32[(($phon_out_ix)>>2)]=$add36;;}
else if(__label__==17){var $33=$phon_out_addr;var $34=$plist;var $ph38=(($34+8)&4294967295);var $35=HEAP32[(($ph38)>>2)];var $36=$plist;__ZL15WritePhMnemonicPcPiP11PHONEME_TABP12PHONEME_LIST($33,$phon_out_ix,$35,$36);var $37=$plist;var $synthflags39=(($37+4)&4294967295);var $38=HEAPU16[(($synthflags39)>>1)];var $conv40=((($38))&65535);var $and41=($conv40)&8;var $tobool42=((($and41))|0)!=0;if($tobool42){__label__=18;;}else{__label__=19;;}
if(__label__==18){var $39=$phon_out_addr;var $40=HEAP32[((((_phoneme_tab+48)&4294967295))>>2)];__ZL15WritePhMnemonicPcPiP11PHONEME_TABP12PHONEME_LIST($39,$phon_out_ix,$40,0);;}
var $41=$plist;var $synthflags45=(($41+4)&4294967295);var $42=HEAPU16[(($synthflags45)>>1)];var $conv46=((($42))&65535);var $and47=($conv46)&4;var $tobool48=((($and47))|0)!=0;if($tobool48){__label__=20;;}else{__label__=22;;}
$land_lhs_true$$if_end52$29:do{if(__label__==20){var $43=$plist;var $type=(($43+15)&4294967295);var $44=HEAPU8[($type)];var $conv49=((($44))&255);var $cmp50=((($conv49))|0)!=2;if(!($cmp50)){__label__=22;break $land_lhs_true$$if_end52$29;}
var $45=$phon_out_addr;var $46=HEAP32[((((_phoneme_tab+80)&4294967295))>>2)];__ZL15WritePhMnemonicPcPiP11PHONEME_TABP12PHONEME_LIST($45,$phon_out_ix,$46,0);;}}while(0);var $47=$plist;var $tone_ph53=(($47+3)&4294967295);var $48=HEAPU8[($tone_ph53)];var $conv54=((($48))&255);var $cmp55=((($conv54))|0)>0;if(!($cmp55)){__label__=24;break $if_then30$$if_else37$23;}
var $49=$phon_out_addr;var $50=$plist;var $tone_ph57=(($50+3)&4294967295);var $51=HEAPU8[($tone_ph57)];var $idxprom58=((($51))&255);var $arrayidx59=((_phoneme_tab+$idxprom58*4)&4294967295);var $52=HEAP32[(($arrayidx59)>>2)];__ZL15WritePhMnemonicPcPiP11PHONEME_TABP12PHONEME_LIST($49,$phon_out_ix,$52,0);;}}while(0);var $53=$ix;var $inc62=((($53)+1)&4294967295);$ix=$inc62;__label__=2;continue $for_cond$4;}
var $54=HEAP32[(($phon_out_ix)>>2)];var $55=$n_phon_out_addr;var $cmp63=((($54))|0)>=((($55))|0);if($cmp63){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $56=$n_phon_out_addr;var $sub65=((($56)-1)&4294967295);HEAP32[(($phon_out_ix)>>2)]=$sub65;;}
var $57=HEAP32[(($phon_out_ix)>>2)];var $58=$phon_out_addr;var $arrayidx67=(($58+$57)&4294967295);HEAP8[($arrayidx67)]=0;;}
STACKTOP=__stackBase__;return;return;}
function __ZL15WritePhMnemonicPcPiP11PHONEME_TABP12PHONEME_LIST($phon_out,$ix,$ph,$plist){var __stackBase__=STACKTOP;STACKTOP+=152;_memset(__stackBase__,0,152);var __label__;var __lastLabel__=null;var $phon_out_addr;var $ix_addr;var $ph_addr;var $plist_addr;var $c;var $mnem;var $len;var $first;var $ipa_control;var $phdata=__stackBase__;$phon_out_addr=$phon_out;$ix_addr=$ix;$ph_addr=$ph;$plist_addr=$plist;$ipa_control=0;var $0=HEAP32[((_option_phonemes)>>2)];var $cmp=((($0))|0)==3;if($cmp){__label__=1;;}else{__label__=8;;}
$if_then$$if_end20$2:do{if(__label__==1){var $ipa_string=(($phdata+132)&4294967295);var $arrayidx=(($ipa_string)&4294967295);HEAP8[($arrayidx)]=0;var $1=$plist_addr;var $cmp1=((($1))|0)==0;if($cmp1){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $2=$ph_addr;var $code=(($2+10)&4294967295);var $3=HEAPU8[($code)];var $conv=((($3))&255);__Z17InterpretPhoneme2iP12PHONEME_DATA($conv,$phdata);;}
else if(__label__==3){var $4=$plist_addr;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$4,$phdata);;}
var $ipa_string3=(($phdata+132)&4294967295);var $arraydecay=(($ipa_string3)&4294967295);var $call=_strlen($arraydecay);$len=$call;var $cmp4=((($call))|0)>0;if(!($cmp4)){__label__=8;break $if_then$$if_end20$2;}
var $ipa_string6=(($phdata+132)&4294967295);var $arrayidx7=(($ipa_string6)&4294967295);var $5=HEAP8[($arrayidx7)];var $conv8=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));$ipa_control=$conv8;var $cmp9=((($conv8))>>>0)>32;if($cmp9){__lastLabel__=5;__label__=6;;}else{__lastLabel__=5;__label__=7;;}
if(__label__==6){var $6=$ix_addr;var $7=HEAP32[(($6)>>2)];var $8=$phon_out_addr;var $arrayidx11=(($8+$7)&4294967295);var $ipa_string12=(($phdata+132)&4294967295);var $arraydecay13=(($ipa_string12)&4294967295);var $call14=_strcpy($arrayidx11,$arraydecay13);var $9=$len;var $10=$ix_addr;var $11=HEAP32[(($10)>>2)];var $add=((($11)+($9))&4294967295);HEAP32[(($10)>>2)]=$add;var $_pr=$ipa_control;__lastLabel__=6;;}
var $12=__lastLabel__==6?$_pr:($conv8);var $cmp16=((($12))>>>0)>=32;if($cmp16){__label__=23;break $if_then$$if_end20$2;}else{__label__=8;break $if_then$$if_end20$2;}}}while(0);$for_end$$if_end20$12:do{if(__label__==8){$first=1;var $13=$ph_addr;var $mnemonic=(($13)&4294967295);var $14=HEAP32[(($mnemonic)>>2)];$mnem=$14;;$for_cond$14:while(1){var $15=$mnem;var $and=($15)&255;$c=$and;var $cmp21=((($and))|0)!=0;if(!($cmp21)){__label__=23;break $for_end$$if_end20$12;}
var $16=$c;var $cmp22=((($16))|0)==47;var $17=HEAP32[((_option_phoneme_variants)>>2)];var $cmp23=((($17))|0)==0;var $or_cond=($cmp22)&($cmp23);if($or_cond){__label__=23;break $for_end$$if_end20$12;}
var $18=HEAP32[((_option_phonemes)>>2)];var $cmp26=((($18))|0)==3;if($cmp26){__label__=12;;}else{__label__=20;;}
$if_then27$$if_else54$18:do{if(__label__==12){var $19=$first;var $tobool=((($19))|0)!=0;var $20=$c;var $cmp29=((($20))|0)==95;var $or_cond3=($tobool)&($cmp29);if($or_cond3){__label__=23;break $for_end$$if_end20$12;}
var $cmp32=((($20))|0)==35;if($cmp32){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $21=$ph_addr;var $type=(($21+11)&4294967295);var $22=HEAPU8[($type)];var $conv34=((($22))&255);var $cmp35=((($conv34))|0)==2;if($cmp35){__label__=23;break $for_end$$if_end20$12;}}
var $23=$first;var $tobool38=((($23))|0)!=0;if($tobool38){__label__=17;;}else{__label__=16;;}
if(__label__==16){var $24=$c;var $isdigittmp=((($24)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call40=((($isdigit))&1);var $tobool41=((($call40))|0)!=0;if($tobool41){__label__=22;break $if_then27$$if_else54$18;}}
var $25=$c;var $cmp44=((($25))|0)>=32;var $26=$c;var $cmp46=((($26))|0)<128;var $or_cond1=($cmp44)&($cmp46);if($or_cond1){__label__=18;;}else{__label__=19;;}
if(__label__==18){var $27=$c;var $sub=((($27)-32)&4294967295);var $arrayidx48=((_ipa1+$sub*2)&4294967295);var $28=HEAPU16[(($arrayidx48)>>1)];var $conv49=((($28))&65535);$c=$conv49;;}
var $29=$c;var $30=$ix_addr;var $31=HEAP32[(($30)>>2)];var $32=$phon_out_addr;var $arrayidx51=(($32+$31)&4294967295);var $call52=__Z8utf8_outjPc($29,$arrayidx51);var $33=$ix_addr;var $34=HEAP32[(($33)>>2)];var $add53=((($34)+($call52))&4294967295);HEAP32[(($33)>>2)]=$add53;__label__=21;break $if_then27$$if_else54$18;}
else if(__label__==20){var $35=$c;var $conv55=((($35))&255);var $36=$ix_addr;var $37=HEAP32[(($36)>>2)];var $inc=((($37)+1)&4294967295);HEAP32[(($36)>>2)]=$inc;var $38=$phon_out_addr;var $arrayidx56=(($38+$37)&4294967295);HEAP8[($arrayidx56)]=$conv55;__label__=21;break $if_then27$$if_else54$18;}}while(0);if(__label__==21){$first=0;;}
var $39=$mnem;var $shr=($39)>>8;$mnem=$shr;__label__=9;continue $for_cond$14;}}}while(0);STACKTOP=__stackBase__;return;return;}
function __Z7IsVowelP10Translatori($tr,$letter){;var __label__;var $tr_addr;var $letter_addr;$tr_addr=$tr;$letter_addr=$letter;var $0=$tr_addr;var $1=$letter_addr;var $call=__ZL8IsLetterP10Translatorii($0,$1,7);;return $call;return null;}
function __ZL8IsLetterP10Translatorii($tr,$letter,$group){;var __label__;var $retval;var $tr_addr;var $letter_addr;var $group_addr;var $letter2;$tr_addr=$tr;$letter_addr=$letter;$group_addr=$group;var $0=$group_addr;var $1=$tr_addr;var $letter_groups=(($1+968)&4294967295);var $arrayidx=(($letter_groups+$0*4)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];var $cmp=((($2))|0)!=0;var $3=$group_addr;if($cmp){__label__=1;;}else{__label__=4;;}
$if_then$$if_end4$2:do{if(__label__==1){var $4=$tr_addr;var $letter_groups1=(($4+968)&4294967295);var $arrayidx2=(($letter_groups1+$3*4)&4294967295);var $5=HEAP32[(($arrayidx2)>>2)];var $6=$letter_addr;var $call=_wcschr($5,$6);var $tobool=((($call))|0)!=0;if($tobool){__label__=2;;}else{__label__=3;;}
if(__label__==2){$retval=1;;}
else if(__label__==3){$retval=0;;}}
else if(__label__==4){var $cmp5=((($3))|0)>7;if($cmp5){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=0;;}
else if(__label__==6){var $7=$tr_addr;var $letter_bits_offset=(($7+964)&4294967295);var $8=HEAP32[(($letter_bits_offset)>>2)];var $cmp8=((($8))|0)>0;var $9=$letter_addr;if($cmp8){__label__=7;;}else{__label__=11;;}
$if_then9$$if_else15$11:do{if(__label__==7){var $10=$tr_addr;var $letter_bits_offset10=(($10+964)&4294967295);var $11=HEAP32[(($letter_bits_offset10)>>2)];var $sub=((($9)-($11))&4294967295);$letter2=$sub;var $cmp11=((($sub))|0)>0;if($cmp11){__label__=8;;}else{__label__=10;;}
$land_lhs_true$$if_else$13:do{if(__label__==8){var $12=$letter2;var $cmp12=((($12))|0)<128;if(!($cmp12)){__label__=10;break $land_lhs_true$$if_else$13;}
var $13=$letter2;$letter_addr=$13;__label__=13;break $if_then9$$if_else15$11;}}while(0);$retval=0;__label__=16;break $if_then$$if_end4$2;}
else if(__label__==11){var $cmp16=((($9))|0)>=192;var $14=$letter_addr;var $cmp18=((($14))|0)<606;var $or_cond=($cmp16)&($cmp18);if(!($or_cond)){__label__=13;break $if_then9$$if_else15$11;}
var $15=$letter_addr;var $sub20=((($15)-192)&4294967295);var $arrayidx21=((__ZL13remove_accent+$sub20)&4294967295);var $16=HEAPU8[($arrayidx21)];var $idxprom=((($16))&255);var $17=$tr_addr;var $letter_bits=(($17+708)&4294967295);var $arrayidx22=(($letter_bits+$idxprom)&4294967295);var $18=HEAPU8[($arrayidx22)];var $conv=((($18))&255);var $19=$group_addr;var $shl=1<<($19);var $and=($shl)&($conv);$retval=$and;__label__=16;break $if_then$$if_end4$2;}}while(0);var $20=$letter_addr;var $cmp25=((($20))|0)>=0;var $21=$letter_addr;var $cmp27=((($21))|0)<128;var $or_cond1=($cmp25)&($cmp27);if($or_cond1){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $22=$letter_addr;var $23=$tr_addr;var $letter_bits29=(($23+708)&4294967295);var $arrayidx30=(($letter_bits29+$22)&4294967295);var $24=HEAPU8[($arrayidx30)];var $conv31=((($24))&255);var $25=$group_addr;var $shl32=1<<($25);var $and33=($shl32)&($conv31);$retval=$and33;;}
else if(__label__==15){$retval=0;;}}}}while(0);var $26=$retval;;return $26;return null;}
function __Z14UnpronouncableP10TranslatorPci($tr,$word,$posn){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $word_addr;var $posn_addr;var $c=__stackBase__;var $c1;var $vowel_posn;var $index;var $count;var $apostrophe;$tr_addr=$tr;$word_addr=$word;$posn_addr=$posn;$c1=0;$vowel_posn=9;$apostrophe=0;var $0=$word_addr;var $call=__Z7utf8_inPiPKc($c,$0);var $1=$tr_addr;var $letter_bits_offset=(($1+964)&4294967295);var $2=HEAP32[(($letter_bits_offset)>>2)];var $cmp=((($2))|0)>0;if($cmp){__label__=1;;}else{__label__=3;;}
$land_lhs_true$$if_end$2:do{if(__label__==1){var $3=HEAP32[(($c)>>2)];var $cmp1=((($3))|0)<577;if(!($cmp1)){__label__=3;break $land_lhs_true$$if_end$2;}
$retval=0;__label__=30;break $land_lhs_true$$if_end$2;}}while(0);$return$$if_end$5:do{if(__label__==3){var $4=$tr_addr;var $langopts=(($4)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx=(($param+20)&4294967295);var $5=HEAP32[(($arrayidx)>>2)];var $cmp2=((($5))|0)==1;if($cmp2){__label__=4;;}else{__label__=5;;}
if(__label__==4){$retval=0;;}
else if(__label__==5){var $6=$word_addr;var $7=HEAP8[($6)];var $conv=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));HEAP32[(($c)>>2)]=$conv;var $cmp5=((($conv))|0)==32;if($cmp5){__label__=7;;}else{__label__=6;;}
$if_then9$$lor_lhs_false$10:do{if(__label__==6){var $8=HEAP32[(($c)>>2)];var $cmp6=((($8))|0)==0;var $9=HEAP32[(($c)>>2)];var $cmp8=((($9))|0)==39;var $or_cond=($cmp6)|($cmp8);if($or_cond){__label__=7;break $if_then9$$lor_lhs_false$10;}
$index=0;$count=0;;$for_cond$13:while(1){var $10=$index;var $11=$word_addr;var $arrayidx11=(($11+$10)&4294967295);var $call12=__Z7utf8_inPiPKc($c,$arrayidx11);var $12=$index;var $add=((($12)+($call12))&4294967295);$index=$add;var $13=HEAP32[(($c)>>2)];var $cmp13=((($13))|0)==0;var $14=HEAP32[(($c)>>2)];var $cmp15=((($14))|0)==32;var $or_cond1=($cmp13)|($cmp15);if($or_cond1){__label__=21;break $for_cond$13;}
var $15=HEAP32[(($c)>>2)];var $cmp18=((($15))|0)==39;if($cmp18){__label__=11;;}else{__label__=13;;}
if(__label__==11){var $16=$count;var $cmp20=((($16))|0)>1;if($cmp20){__label__=21;break $for_cond$13;}
var $17=$posn_addr;var $cmp22=((($17))|0)>0;if($cmp22){__label__=21;break $for_cond$13;}}
var $18=$count;var $cmp25=((($18))|0)==0;if($cmp25){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $19=HEAP32[(($c)>>2)];$c1=$19;;}
var $20=$count;var $inc=((($20)+1)&4294967295);$count=$inc;var $21=$tr_addr;var $22=HEAP32[(($c)>>2)];var $call28=__Z7IsVowelP10Translatori($21,$22);var $tobool=((($call28))|0)!=0;if($tobool){__label__=16;break $for_cond$13;}
var $24=HEAP32[(($c)>>2)];var $cmp31=((($24))|0)==39;if($cmp31){__label__=18;;}else{__label__=19;;}
if(__label__==18){$apostrophe=1;__label__=9;continue $for_cond$13;}
else if(__label__==19){var $25=HEAP32[(($c)>>2)];var $call33=_iswalpha($25);var $tobool34=((($call33))|0)!=0;if($tobool34){__label__=9;continue $for_cond$13;}else{__label__=20;break $for_cond$13;}}}
if(__label__==21){var $_pr=$vowel_posn;__lastLabel__=21;;}
else if(__label__==16){var $23=$count;$vowel_posn=$23;__lastLabel__=16;;}
else if(__label__==20){$retval=0;__label__=30;break $return$$if_end$5;}
var $26=__lastLabel__==21?$_pr:($23);var $cmp38=((($26))|0)>2;if($cmp38){__label__=23;;}else{__label__=25;;}
$land_lhs_true39$$if_end46$32:do{if(__label__==23){var $27=$tr_addr;var $langopts40=(($27)&4294967295);var $param41=(($langopts40+24)&4294967295);var $arrayidx42=(($param41+20)&4294967295);var $28=HEAP32[(($arrayidx42)>>2)];var $cmp43=((($28))|0)==2;if(!($cmp43)){__label__=25;break $land_lhs_true39$$if_end46$32;}
var $29=$tr_addr;var $30=$word_addr;var $call45=__ZL15Unpronouncable2P10TranslatorPc($29,$30);$retval=$call45;__label__=30;break $return$$if_end$5;}}while(0);var $31=$c1;var $32=$tr_addr;var $langopts47=(($32)&4294967295);var $param48=(($langopts47+24)&4294967295);var $arrayidx49=(($param48+20)&4294967295);var $33=HEAP32[(($arrayidx49)>>2)];var $cmp50=((($31))|0)==((($33))|0);if($cmp50){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $34=$vowel_posn;var $dec=((($34)-1)&4294967295);$vowel_posn=$dec;;}
var $35=$vowel_posn;var $36=$tr_addr;var $langopts53=(($36)&4294967295);var $max_initial_consonants=(($langopts53+248)&4294967295);var $37=HEAP8[($max_initial_consonants)];var $conv54=(tempInt=(($37)),(tempInt>=128?tempInt-256:tempInt));var $add55=((($conv54)+1)&4294967295);var $cmp56=((($35))|0)>((($add55))|0);if($cmp56){__label__=28;;}else{__label__=29;;}
if(__label__==28){$retval=1;__label__=30;break $return$$if_end$5;}
else if(__label__==29){$retval=0;__label__=30;break $return$$if_end$5;}}}while(0);$retval=0;;}}}while(0);var $38=$retval;STACKTOP=__stackBase__;return $38;return null;}
function __ZL15Unpronouncable2P10TranslatorPc($tr,$word){var __stackBase__=STACKTOP;STACKTOP+=160;_memset(__stackBase__,0,160);var __label__;var $retval;var $tr_addr;var $word_addr;var $c;var $end_flags;var $ph_buf=__stackBase__;$tr_addr=$tr;$word_addr=$word;var $arrayidx=(($ph_buf)&4294967295);HEAP8[($arrayidx)]=0;var $0=$word_addr;var $arrayidx1=(($0+-1)&4294967295);var $1=HEAP8[($arrayidx1)];var $conv=(tempInt=(($1)),(tempInt>=128?tempInt-256:tempInt));$c=$conv;var $2=$word_addr;var $arrayidx2=(($2+-1)&4294967295);HEAP8[($arrayidx2)]=32;var $3=$tr_addr;var $4=$word_addr;var $arraydecay=(($ph_buf)&4294967295);var $call=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($3,$4,$arraydecay,160,0,-2147483648,0);$end_flags=$call;var $5=$c;var $conv3=((($5))&255);var $6=$word_addr;var $arrayidx4=(($6+-1)&4294967295);HEAP8[($arrayidx4)]=$conv3;var $7=$end_flags;var $cmp=((($7))|0)==0;if($cmp){__label__=2;;}else{__label__=1;;}
$if_then$$lor_lhs_false$2:do{if(__label__==1){var $8=$end_flags;var $and=($8)&32768;var $tobool=((($and))|0)!=0;if($tobool){__label__=2;break $if_then$$lor_lhs_false$2;}
$retval=0;__label__=4;break $if_then$$lor_lhs_false$2;}}while(0);if(__label__==2){$retval=1;;}
var $9=$retval;STACKTOP=__stackBase__;return $9;return null;}
function __Z16ChangeWordStressP10TranslatorPci($tr,$word,$new_stress){var __stackBase__=STACKTOP;STACKTOP+=248;_memset(__stackBase__,0,248);var __label__;var $tr_addr;var $word_addr;var $new_stress_addr;var $ix;var $p;var $max_stress;var $vowel_count=__stackBase__;var $stressed_syllable=__stackBase__+4;var $phonetic=__stackBase__+8;var $vowel_stress=__stackBase__+168;$tr_addr=$tr;$word_addr=$word;$new_stress_addr=$new_stress;HEAP32[(($stressed_syllable)>>2)]=0;var $arraydecay=(($phonetic)&4294967295);var $0=$word_addr;var $call=_strcpy($arraydecay,$0);var $1=$tr_addr;var $arraydecay1=(($phonetic)&4294967295);var $arraydecay2=(($vowel_stress)&4294967295);var $call3=__ZL14GetVowelStressP10TranslatorPhPaRiS3_i($1,$arraydecay1,$arraydecay2,$vowel_count,$stressed_syllable,0);$max_stress=$call3;var $2=$new_stress_addr;var $cmp=((($2))|0)>=4;$ix=1;if($cmp){__label__=2;;}else{__label__=1;;}
$for_cond$$for_cond9_preheader$2:do{if(__label__==2){while(1){var $5=$ix;var $6=HEAP32[(($vowel_count)>>2)];var $cmp4=((($5))|0)<((($6))|0);if(!($cmp4)){__label__=9;break $for_cond$$for_cond9_preheader$2;}
var $7=$ix;var $arrayidx=(($vowel_stress+$7)&4294967295);var $8=HEAP8[($arrayidx)];var $conv=(tempInt=(($8)),(tempInt>=128?tempInt-256:tempInt));var $9=$max_stress;var $cmp5=((($conv))|0)>=((($9))|0);if($cmp5){__label__=4;break;}
var $12=$ix;var $inc=((($12)+1)&4294967295);$ix=$inc;__label__=2;continue;}
var $10=$new_stress_addr;var $conv7=((($10))&255);var $11=$ix;var $arrayidx8=(($vowel_stress+$11)&4294967295);HEAP8[($arrayidx8)]=$conv7;;}
else if(__label__==1){var $3=$ix;var $4=HEAP32[(($vowel_count)>>2)];var $cmp101=((($3))|0)<((($4))|0);if(!($cmp101)){__label__=9;break $for_cond$$for_cond9_preheader$2;}
while(1){var $13=$ix;var $arrayidx12=(($vowel_stress+$13)&4294967295);var $14=HEAP8[($arrayidx12)];var $conv13=(tempInt=(($14)),(tempInt>=128?tempInt-256:tempInt));var $15=$new_stress_addr;var $cmp14=((($conv13))|0)>((($15))|0);if($cmp14){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $16=$new_stress_addr;var $conv16=((($16))&255);var $17=$ix;var $arrayidx17=(($vowel_stress+$17)&4294967295);HEAP8[($arrayidx17)]=$conv16;;}
var $18=$ix;var $inc20=((($18)+1)&4294967295);$ix=$inc20;var $19=$ix;var $20=HEAP32[(($vowel_count)>>2)];var $cmp10=((($19))|0)<((($20))|0);if($cmp10){__label__=6;continue;}else{__label__=9;break $for_cond$$for_cond9_preheader$2;}}}}while(0);$ix=1;var $arraydecay23=(($phonetic)&4294967295);$p=$arraydecay23;var $21=$p;var $22=HEAPU8[($21)];var $conv242=((($22))&255);var $cmp253=((($conv242))|0)!=0;if($cmp253){__label__=10;;}else{__label__=17;;}
$while_body$$while_end$15:do{if(__label__==10){$while_body$16:while(1){var $23=$p;var $24=HEAPU8[($23)];var $idxprom=((($24))&255);var $arrayidx26=((_phoneme_tab+$idxprom*4)&4294967295);var $25=HEAP32[(($arrayidx26)>>2)];var $type=(($25+11)&4294967295);var $26=HEAPU8[($type)];var $conv27=((($26))&255);var $cmp28=((($conv27))|0)==2;if($cmp28){__label__=11;;}else{__label__=16;;}
$land_lhs_true$$if_end44$18:do{if(__label__==11){var $27=$p;var $28=HEAPU8[($27)];var $idxprom29=((($28))&255);var $arrayidx30=((_phoneme_tab+$idxprom29*4)&4294967295);var $29=HEAP32[(($arrayidx30)>>2)];var $phflags=(($29+4)&4294967295);var $30=HEAP32[(($phflags)>>2)];var $and=($30)&1048576;var $tobool=((($and))|0)!=0;if($tobool){__label__=16;break $land_lhs_true$$if_end44$18;}
var $31=$ix;var $arrayidx32=(($vowel_stress+$31)&4294967295);var $32=HEAP8[($arrayidx32)];var $conv33=(tempInt=(($32)),(tempInt>=128?tempInt-256:tempInt));var $cmp34=((($conv33))|0)==0;if($cmp34){__label__=14;;}else{__label__=13;;}
$if_then38$$lor_lhs_false$21:do{if(__label__==13){var $33=$ix;var $arrayidx35=(($vowel_stress+$33)&4294967295);var $34=HEAP8[($arrayidx35)];var $conv36=(tempInt=(($34)),(tempInt>=128?tempInt-256:tempInt));var $cmp37=((($conv36))|0)>1;if($cmp37){__label__=14;break $if_then38$$lor_lhs_false$21;}else{__label__=15;break $if_then38$$lor_lhs_false$21;}}}while(0);if(__label__==14){var $35=$ix;var $arrayidx39=(($vowel_stress+$35)&4294967295);var $36=HEAPU8[($arrayidx39)];var $idxprom40=((($36))&255);var $arrayidx41=((__ZL15stress_phonemes+$idxprom40)&4294967295);var $37=HEAP8[($arrayidx41)];var $38=$word_addr;var $incdec_ptr=(($38+1)&4294967295);$word_addr=$incdec_ptr;HEAP8[($38)]=$37;;}
var $39=$ix;var $inc43=((($39)+1)&4294967295);$ix=$inc43;;}}while(0);var $40=$p;var $incdec_ptr45=(($40+1)&4294967295);$p=$incdec_ptr45;var $41=HEAP8[($40)];var $42=$word_addr;var $incdec_ptr46=(($42+1)&4294967295);$word_addr=$incdec_ptr46;HEAP8[($42)]=$41;var $43=$p;var $44=HEAPU8[($43)];var $conv24=((($44))&255);var $cmp25=((($conv24))|0)!=0;if($cmp25){__label__=10;continue $while_body$16;}else{__label__=17;break $while_body$$while_end$15;}}}}while(0);var $45=$word_addr;HEAP8[($45)]=0;STACKTOP=__stackBase__;return;return;}
function __ZL14GetVowelStressP10TranslatorPhPaRiS3_i($tr,$phonemes,$vowel_stress,$vowel_count,$stressed_syllable,$control){;var __label__;var __lastLabel__=null;var $tr_addr;var $phonemes_addr;var $vowel_stress_addr;var $vowel_count_addr;var $stressed_syllable_addr;var $control_addr;var $phcode;var $ph;var $ph_out;var $count;var $max_stress;var $ix;var $j;var $stress;var $primary_posn;$tr_addr=$tr;$phonemes_addr=$phonemes;$vowel_stress_addr=$vowel_stress;$vowel_count_addr=$vowel_count;$stressed_syllable_addr=$stressed_syllable;$control_addr=$control;var $0=$phonemes_addr;$ph_out=$0;$count=1;$max_stress=-1;$stress=-1;$primary_posn=0;var $1=$vowel_stress_addr;var $arrayidx=(($1)&4294967295);HEAP8[($arrayidx)]=1;;$while_cond$2:while(1){var $2=$phonemes_addr;var $incdec_ptr=(($2+1)&4294967295);$phonemes_addr=$incdec_ptr;var $3=HEAPU8[($2)];$phcode=$3;var $conv=((($3))&255);var $cmp=((($conv))|0)!=0;if(!($cmp)){__label__=39;break $while_cond$2;}
var $4=$count;var $cmp1=((($4))|0)<79;if(!($cmp1)){__label__=39;break $while_cond$2;}
var $5=$phcode;var $idxprom=((($5))&255);var $arrayidx2=((_phoneme_tab+$idxprom*4)&4294967295);var $6=HEAPU32[(($arrayidx2)>>2)];$ph=$6;var $cmp3=((($6))|0)==0;if($cmp3){__label__=1;continue $while_cond$2;}
var $7=$ph;var $type=(($7+11)&4294967295);var $8=HEAPU8[($type)];var $conv4=((($8))&255);var $cmp5=((($conv4))|0)==1;if($cmp5){__label__=5;;}else{__label__=24;;}
$land_lhs_true$$if_end53$7:do{if(__label__==5){var $9=$ph;var $program=(($9+8)&4294967295);var $10=HEAPU16[(($program)>>1)];var $conv6=((($10))&65535);var $cmp7=((($conv6))|0)==0;if(!($cmp7)){__label__=24;break $land_lhs_true$$if_end53$7;}
var $11=$phcode;var $conv9=((($11))&255);var $cmp10=((($conv9))|0)==8;if($cmp10){__label__=7;;}else{__label__=20;;}
if(__label__==7){var $12=$count;var $sub=((($12)-1)&4294967295);$j=$sub;__lastLabel__=7;;$while_cond12$12:while(1){var $13=__lastLabel__==19?$dec:($sub);var $cmp13=((($13))|0)>0;if(!($cmp13)){__label__=1;continue $while_cond$2;}
var $14=$stressed_syllable_addr;var $15=HEAP32[(($14)>>2)];var $cmp15=((($15))|0)==0;if(!($cmp15)){__label__=1;continue $while_cond$2;}
var $16=$j;var $17=$vowel_stress_addr;var $arrayidx17=(($17+$16)&4294967295);var $18=HEAP8[($arrayidx17)];var $conv18=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));var $cmp19=((($conv18))|0)<4;if(!($cmp19)){__label__=1;continue $while_cond$2;}
var $19=$j;var $20=$vowel_stress_addr;var $arrayidx22=(($20+$19)&4294967295);var $21=HEAP8[($arrayidx22)];var $conv23=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));var $cmp24=((($conv23))|0)!=0;if($cmp24){__label__=12;;}else{__label__=19;;}
if(__label__==12){var $22=$j;var $23=$vowel_stress_addr;var $arrayidx26=(($23+$22)&4294967295);var $24=HEAP8[($arrayidx26)];var $conv27=(tempInt=(($24)),(tempInt>=128?tempInt-256:tempInt));var $cmp28=((($conv27))|0)!=1;if($cmp28){__label__=13;break $while_cond12$12;}}
var $39=$j;var $dec=((($39)-1)&4294967295);$j=$dec;__lastLabel__=19;__label__=8;continue $while_cond12$12;}
var $25=$j;var $26=$vowel_stress_addr;var $arrayidx30=(($26+$25)&4294967295);HEAP8[($arrayidx30)]=4;var $27=$max_stress;var $cmp31=((($27))|0)<4;if($cmp31){__label__=14;;}else{__label__=15;;}
if(__label__==14){$max_stress=4;var $28=$j;$primary_posn=$28;;}
$ix=1;var $29=$ix;var $30=$j;var $cmp344=((($29))|0)<((($30))|0);if(!($cmp344)){__label__=1;continue $while_cond$2;}
while(1){var $31=$ix;var $32=$vowel_stress_addr;var $arrayidx35=(($32+$31)&4294967295);var $33=HEAP8[($arrayidx35)];var $conv36=(tempInt=(($33)),(tempInt>=128?tempInt-256:tempInt));var $cmp37=((($conv36))|0)==4;if($cmp37){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $34=$ix;var $35=$vowel_stress_addr;var $arrayidx39=(($35+$34)&4294967295);HEAP8[($arrayidx39)]=3;;}
var $36=$ix;var $inc=((($36)+1)&4294967295);$ix=$inc;var $37=$ix;var $38=$j;var $cmp34=((($37))|0)<((($38))|0);if($cmp34){__label__=16;continue;}else{__label__=1;continue $while_cond$2;}}}
else if(__label__==20){var $40=$ph;var $std_length=(($40+14)&4294967295);var $41=HEAPU8[($std_length)];var $conv42=((($41))&255);var $cmp43=((($conv42))|0)<4;if($cmp43){__label__=22;;}else{__label__=21;;}
if(__label__==21){var $42=$stressed_syllable_addr;var $43=HEAP32[(($42)>>2)];var $cmp44=((($43))|0)==0;if(!($cmp44)){__label__=1;continue $while_cond$2;}}
var $44=$ph;var $std_length46=(($44+14)&4294967295);var $45=HEAPU8[($std_length46)];var $conv47=((($45))&255);$stress=$conv47;var $46=$stress;var $47=$max_stress;var $cmp48=((($46))|0)>((($47))|0);if(!($cmp48)){__label__=1;continue $while_cond$2;}
var $48=$stress;$max_stress=$48;__label__=1;continue $while_cond$2;}}}while(0);var $49=$ph;var $type54=(($49+11)&4294967295);var $50=HEAPU8[($type54)];var $conv55=((($50))&255);var $cmp56=((($conv55))|0)==2;if($cmp56){__label__=25;;}else{__label__=34;;}
$land_lhs_true57$$if_else78$35:do{if(__label__==25){var $51=$ph;var $phflags=(($51+4)&4294967295);var $52=HEAP32[(($phflags)>>2)];var $and=($52)&1048576;var $tobool=((($and))|0)!=0;if($tobool){__label__=34;break $land_lhs_true57$$if_else78$35;}
var $53=$stress;var $conv59=((($53))&255);var $54=$count;var $55=$vowel_stress_addr;var $arrayidx60=(($55+$54)&4294967295);HEAP8[($arrayidx60)]=$conv59;var $56=$stress;var $cmp61=((($56))|0)>=4;if($cmp61){__lastLabel__=26;__label__=27;;}else{__lastLabel__=26;__label__=29;;}
$land_lhs_true62$$if_end65$38:do{if(__label__==27){var $57=$stress;var $58=$max_stress;var $cmp63=((($57))|0)>=((($58))|0);if($cmp63){__lastLabel__=27;;}else{__lastLabel__=27;__label__=29;break $land_lhs_true62$$if_end65$38;}
var $59=$count;$primary_posn=$59;var $60=$stress;$max_stress=$60;__lastLabel__=28;;}}while(0);var $61=__lastLabel__==28?$60:(__lastLabel__==27?$57:($56));var $cmp66=((($61))|0)<0;if($cmp66){__label__=30;;}else{__label__=33;;}
$land_lhs_true67$$if_end76$42:do{if(__label__==30){var $62=$control_addr;var $and68=($62)&1;var $tobool69=((($and68))|0)!=0;if(!($tobool69)){__label__=33;break $land_lhs_true67$$if_end76$42;}
var $63=$ph;var $phflags71=(($63+4)&4294967295);var $64=HEAP32[(($phflags71)>>2)];var $and72=($64)&2;var $tobool73=((($and72))|0)!=0;if(!($tobool73)){__label__=33;break $land_lhs_true67$$if_end76$42;}
var $65=$count;var $66=$vowel_stress_addr;var $arrayidx75=(($66+$65)&4294967295);HEAP8[($arrayidx75)]=1;;}}while(0);var $67=$count;var $inc77=((($67)+1)&4294967295);$count=$inc77;$stress=-1;__label__=38;break $land_lhs_true57$$if_else78$35;}}while(0);$if_else78$$if_end93$47:do{if(__label__==34){var $68=$phcode;var $conv79=((($68))&255);var $cmp80=((($conv79))|0)==20;if(!($cmp80)){__label__=38;break $if_else78$$if_end93$47;}
var $69=$stress;var $conv82=((($69))&255);var $70=$count;var $71=$vowel_stress_addr;var $arrayidx83=(($71+$70)&4294967295);HEAP8[($arrayidx83)]=$conv82;var $72=$stress;var $cmp84=((($72))|0)==0;if(!($cmp84)){__label__=38;break $if_else78$$if_end93$47;}
var $73=$control_addr;var $and86=($73)&1;var $tobool87=((($and86))|0)!=0;if(!($tobool87)){__label__=38;break $if_else78$$if_end93$47;}
var $74=$count;var $inc89=((($74)+1)&4294967295);$count=$inc89;var $75=$vowel_stress_addr;var $arrayidx90=(($75+$74)&4294967295);HEAP8[($arrayidx90)]=1;;}}while(0);var $76=$phcode;var $77=$ph_out;var $incdec_ptr94=(($77+1)&4294967295);$ph_out=$incdec_ptr94;HEAP8[($77)]=$76;__label__=1;continue $while_cond$2;}
var $78=$count;var $79=$vowel_stress_addr;var $arrayidx96=(($79+$78)&4294967295);HEAP8[($arrayidx96)]=1;var $80=$ph_out;HEAP8[($80)]=0;var $81=$stressed_syllable_addr;var $82=HEAP32[(($81)>>2)];var $cmp97=((($82))|0)>0;if($cmp97){__label__=40;;}else{__label__=43;;}
$if_then98$$if_end104$54:do{if(__label__==40){var $83=$stressed_syllable_addr;var $84=HEAP32[(($83)>>2)];var $85=$count;var $cmp99=((($84))|0)>=((($85))|0);if($cmp99){__label__=41;;}else{__label__=42;;}
if(__label__==41){var $86=$count;var $sub101=((($86)-1)&4294967295);var $87=$stressed_syllable_addr;HEAP32[(($87)>>2)]=$sub101;;}
var $88=$stressed_syllable_addr;var $89=HEAP32[(($88)>>2)];var $90=$vowel_stress_addr;var $arrayidx103=(($90+$89)&4294967295);HEAP8[($arrayidx103)]=4;$max_stress=4;var $91=$stressed_syllable_addr;var $92=HEAP32[(($91)>>2)];$primary_posn=$92;;}
else if(__label__==43){var $_pr=$max_stress;var $cmp105=((($_pr))|0)==5;if(!($cmp105)){__label__=53;break $if_then98$$if_end104$54;}
$ix=1;var $93=$ix;var $94=$count;var $cmp1083=((($93))|0)<((($94))|0);if($cmp1083){__label__=45;;}else{__label__=52;;}
$for_body109$$for_end130$61:do{if(__label__==45){while(1){var $95=$ix;var $96=$vowel_stress_addr;var $arrayidx110=(($96+$95)&4294967295);var $97=HEAP8[($arrayidx110)];var $conv111=(tempInt=(($97)),(tempInt>=128?tempInt-256:tempInt));var $cmp112=((($conv111))|0)==4;if($cmp112){__label__=46;;}else{__label__=49;;}
if(__label__==46){var $98=$tr_addr;var $langopts=(($98)&4294967295);var $stress_flags=(($langopts+12)&4294967295);var $99=HEAP32[(($stress_flags)>>2)];var $and114=($99)&131072;var $tobool115=((($and114))|0)!=0;var $100=$ix;var $101=$vowel_stress_addr;var $arrayidx117=(($101+$100)&4294967295);if($tobool115){__label__=47;;}else{__label__=48;;}
if(__label__==47){HEAP8[($arrayidx117)]=1;;}
else if(__label__==48){HEAP8[($arrayidx117)]=3;;}}
var $102=$ix;var $103=$vowel_stress_addr;var $arrayidx122=(($103+$102)&4294967295);var $104=HEAP8[($arrayidx122)];var $conv123=(tempInt=(($104)),(tempInt>=128?tempInt-256:tempInt));var $cmp124=((($conv123))|0)==5;if($cmp124){__label__=50;;}else{__label__=51;;}
if(__label__==50){var $105=$ix;var $106=$vowel_stress_addr;var $arrayidx126=(($106+$105)&4294967295);HEAP8[($arrayidx126)]=4;var $107=$ix;$primary_posn=$107;;}
var $108=$ix;var $inc129=((($108)+1)&4294967295);$ix=$inc129;var $109=$ix;var $110=$count;var $cmp108=((($109))|0)<((($110))|0);if($cmp108){__label__=45;continue;}else{__label__=52;break $for_body109$$for_end130$61;}}}}while(0);$max_stress=4;;}}while(0);var $111=$primary_posn;var $112=$stressed_syllable_addr;HEAP32[(($112)>>2)]=$111;var $113=$count;var $114=$vowel_count_addr;HEAP32[(($114)>>2)]=$113;var $115=$max_stress;;return $115;return null;}
function __Z13SetWordStressP10TranslatorPcPjii($tr,$output,$dictionary_flags,$tonic,$control){var __stackBase__=STACKTOP;STACKTOP+=408;_memset(__stackBase__,0,408);var __label__;var __lastLabel__=null;var $tr_addr;var $output_addr;var $dictionary_flags_addr;var $tonic_addr;var $control_addr;var $phcode;var $p;var $ph;var $stress;var $max_stress;var $vowel_count=__stackBase__;var $ix;var $v;var $v_stress;var $stressed_syllable=__stackBase__+4;var $max_stress_posn;var $unstressed_word;var $max_output;var $final_ph;var $final_ph2;var $mnem;var $mnem2;var $post_tonic;var $opt_length;var $done;var $stressflags;var $dflags;var $first_primary;var $vowel_stress=__stackBase__+8;var $syllable_weight=__stackBase__+88;var $vowel_length=__stackBase__+168;var $phonetic=__stackBase__+248;var $weight;var $lengthened;var $wt;var $max_weight;var $prev_stressed;var $shorten;$tr_addr=$tr;$output_addr=$output;$dictionary_flags_addr=$dictionary_flags;$tonic_addr=$tonic;$control_addr=$control;$unstressed_word=0;$dflags=0;var $0=$tr_addr;var $langopts=(($0)&4294967295);var $stress_flags=(($langopts+12)&4294967295);var $1=HEAP32[(($stress_flags)>>2)];$stressflags=$1;var $2=$dictionary_flags_addr;var $cmp=((($2))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $3=$dictionary_flags_addr;var $arrayidx=(($3)&4294967295);var $4=HEAP32[(($arrayidx)>>2)];$dflags=$4;;}
$ix=0;__lastLabel__=2;;$for_cond$5:while(1){var $5=__lastLabel__==7?$inc:(0);var $cmp1=((($5))|0)<160;var $6=$ix;if($cmp1){__lastLabel__=3;;}else{__lastLabel__=3;__label__=8;break $for_cond$5;}
var $7=$output_addr;var $arrayidx2=(($7+$6)&4294967295);var $8=HEAP8[($arrayidx2)];var $9=$ix;var $arrayidx3=(($phonetic+$9)&4294967295);HEAP8[($arrayidx3)]=$8;var $10=$ix;var $arrayidx4=(($phonetic+$10)&4294967295);var $11=HEAPU8[($arrayidx4)];var $conv=((($11))&255);var $12=HEAP32[((_n_phoneme_tab)>>2)];var $cmp5=((($conv))|0)>=((($12))|0);if($cmp5){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $13=$ix;var $arrayidx7=(($phonetic+$13)&4294967295);HEAP8[($arrayidx7)]=13;;}
var $14=$ix;var $arrayidx9=(($phonetic+$14)&4294967295);var $15=HEAPU8[($arrayidx9)];var $conv10=((($15))&255);var $cmp11=((($conv10))|0)==0;if($cmp11){__lastLabel__=6;__label__=8;break $for_cond$5;}else{__lastLabel__=6;;}
var $16=$ix;var $inc=((($16)+1)&4294967295);$ix=$inc;__lastLabel__=7;__label__=3;continue $for_cond$5;}
var $17=__lastLabel__==6?$14:($6);var $cmp14=((($17))|0)==0;if($cmp14){__label__=223;;}else{__label__=9;;}
if(__label__==9){var $18=$ix;var $sub=((($18)-1)&4294967295);var $arrayidx17=(($phonetic+$sub)&4294967295);var $19=HEAPU8[($arrayidx17)];var $conv18=((($19))&255);$final_ph=$conv18;var $20=$ix;var $sub19=((($20)-2)&4294967295);var $arrayidx20=(($phonetic+$sub19)&4294967295);var $21=HEAPU8[($arrayidx20)];var $conv21=((($21))&255);$final_ph2=$conv21;var $22=$output_addr;var $add_ptr=(($22+157)&4294967295);$max_output=$add_ptr;var $23=$dflags;var $and=($23)&7;HEAP32[(($stressed_syllable)>>2)]=$and;var $24=$dflags;var $and22=($24)&8;var $tobool=((($and22))|0)!=0;if($tobool){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $25=$dflags;var $and24=($25)&3;HEAP32[(($stressed_syllable)>>2)]=$and24;$unstressed_word=1;;}
var $26=$tr_addr;var $arraydecay=(($phonetic)&4294967295);var $arraydecay26=(($vowel_stress)&4294967295);var $call=__ZL14GetVowelStressP10TranslatorPhPaRiS3_i($26,$arraydecay,$arraydecay26,$vowel_count,$stressed_syllable,1);$max_stress=$call;var $cmp27=((($call))|0)<0;if($cmp27){__label__=12;;}else{__label__=17;;}
$land_lhs_true$$if_end40$18:do{if(__label__==12){var $27=$dictionary_flags_addr;var $tobool28=((($27))|0)!=0;if(!($tobool28)){__label__=17;break $land_lhs_true$$if_end40$18;}
var $28=$tr_addr;var $langopts30=(($28)&4294967295);var $stress_flags31=(($langopts30+12)&4294967295);var $29=HEAP32[(($stress_flags31)>>2)];var $and32=($29)&1;var $tobool33=((($and32))|0)!=0;if($tobool33){__label__=14;;}else{__label__=16;;}
$land_lhs_true34$$if_end39$21:do{if(__label__==14){var $30=HEAP32[(($vowel_count)>>2)];var $cmp35=((($30))|0)==2;if(!($cmp35)){__label__=16;break $land_lhs_true34$$if_end39$21;}
var $arrayidx37=(($vowel_stress+1)&4294967295);HEAP8[($arrayidx37)]=0;var $31=$dictionary_flags_addr;var $arrayidx38=(($31)&4294967295);var $32=HEAP32[(($arrayidx38)>>2)];var $or=($32)|4096;HEAP32[(($arrayidx38)>>2)]=$or;;}}while(0);$max_stress=0;;}}while(0);$ix=1;var $arraydecay41=(($phonetic)&4294967295);$p=$arraydecay41;var $33=$p;var $34=HEAPU8[($33)];var $conv4319=((($34))&255);var $cmp4420=((($conv4319))|0)!=0;if($cmp4420){__label__=18;;}else{__label__=33;;}
$for_body45$$for_end109$26:do{if(__label__==18){$for_body45$27:while(1){var $35=$p;var $arrayidx46=(($35)&4294967295);var $36=HEAPU8[($arrayidx46)];var $idxprom=((($36))&255);var $arrayidx47=((_phoneme_tab+$idxprom*4)&4294967295);var $37=HEAP32[(($arrayidx47)>>2)];var $type=(($37+11)&4294967295);var $38=HEAPU8[($type)];var $conv48=((($38))&255);var $cmp49=((($conv48))|0)==2;if($cmp49){__label__=19;;}else{__label__=32;;}
$land_lhs_true50$$for_inc107$29:do{if(__label__==19){var $39=$p;var $arrayidx51=(($39)&4294967295);var $40=HEAPU8[($arrayidx51)];var $idxprom52=((($40))&255);var $arrayidx53=((_phoneme_tab+$idxprom52*4)&4294967295);var $41=HEAP32[(($arrayidx53)>>2)];var $phflags=(($41+4)&4294967295);var $42=HEAP32[(($phflags)>>2)];var $and54=($42)&1048576;var $tobool55=((($and54))|0)!=0;if($tobool55){__label__=32;break $land_lhs_true50$$for_inc107$29;}
$weight=0;$lengthened=0;var $43=$p;var $arrayidx57=(($43+1)&4294967295);var $44=HEAPU8[($arrayidx57)];var $idxprom58=((($44))&255);var $arrayidx59=((_phoneme_tab+$idxprom58*4)&4294967295);var $45=HEAP32[(($arrayidx59)>>2)];var $code=(($45+10)&4294967295);var $46=HEAPU8[($code)];var $conv60=((($46))&255);var $cmp61=((($conv60))|0)==12;if($cmp61){__label__=21;;}else{__label__=22;;}
$if_end63_thread$$if_end63$32:do{if(__label__==21){$lengthened=1;__label__=24;break $if_end63_thread$$if_end63$32;}
else if(__label__==22){var $_pr3=$lengthened;var $tobool64=((($_pr3))|0)!=0;if($tobool64){__label__=24;break $if_end63_thread$$if_end63$32;}
var $47=$p;var $arrayidx65=(($47)&4294967295);var $48=HEAPU8[($arrayidx65)];var $idxprom66=((($48))&255);var $arrayidx67=((_phoneme_tab+$idxprom66*4)&4294967295);var $49=HEAP32[(($arrayidx67)>>2)];var $phflags68=(($49+4)&4294967295);var $50=HEAP32[(($phflags68)>>2)];var $and69=($50)&2097152;var $tobool70=((($and69))|0)!=0;if($tobool70){__label__=24;break $if_end63_thread$$if_end63$32;}else{__label__=25;break $if_end63_thread$$if_end63$32;}}}while(0);if(__label__==24){var $51=$weight;var $inc72=((($51)+1)&4294967295);$weight=$inc72;;}
var $52=$weight;var $conv74=((($52))&255);var $53=$ix;var $arrayidx75=(($vowel_length+$53)&4294967295);HEAP8[($arrayidx75)]=$conv74;var $54=$lengthened;var $tobool76=((($54))|0)!=0;if($tobool76){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $55=$p;var $incdec_ptr=(($55+1)&4294967295);$p=$incdec_ptr;;}
var $56=$p;var $arrayidx79=(($56+1)&4294967295);var $57=HEAPU8[($arrayidx79)];var $idxprom80=((($57))&255);var $arrayidx81=((_phoneme_tab+$idxprom80*4)&4294967295);var $58=HEAP32[(($arrayidx81)>>2)];var $type82=(($58+11)&4294967295);var $59=HEAPU8[($type82)];var $idxprom83=((($59))&255);var $arrayidx84=((__ZZ13SetWordStressP10TranslatorPcPjiiE15consonant_types+$idxprom83)&4294967295);var $60=HEAP8[($arrayidx84)];var $tobool85=(tempInt=(($60)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool85){__label__=28;;}else{__label__=31;;}
$land_lhs_true86$$if_end102$42:do{if(__label__==28){var $61=$p;var $arrayidx87=(($61+2)&4294967295);var $62=HEAPU8[($arrayidx87)];var $idxprom88=((($62))&255);var $arrayidx89=((_phoneme_tab+$idxprom88*4)&4294967295);var $63=HEAP32[(($arrayidx89)>>2)];var $type90=(($63+11)&4294967295);var $64=HEAPU8[($type90)];var $conv91=((($64))&255);var $cmp92=((($conv91))|0)!=2;if($cmp92){__label__=30;;}else{__label__=29;;}
if(__label__==29){var $65=$p;var $arrayidx94=(($65+1)&4294967295);var $66=HEAPU8[($arrayidx94)];var $idxprom95=((($66))&255);var $arrayidx96=((_phoneme_tab+$idxprom95*4)&4294967295);var $67=HEAP32[(($arrayidx96)>>2)];var $phflags97=(($67+4)&4294967295);var $68=HEAP32[(($phflags97)>>2)];var $and98=($68)&2097152;var $tobool99=((($and98))|0)!=0;if(!($tobool99)){__label__=31;break $land_lhs_true86$$if_end102$42;}}
var $69=$weight;var $inc101=((($69)+1)&4294967295);$weight=$inc101;;}}while(0);var $70=$weight;var $conv103=((($70))&255);var $71=$ix;var $arrayidx104=(($syllable_weight+$71)&4294967295);HEAP8[($arrayidx104)]=$conv103;var $72=$ix;var $inc105=((($72)+1)&4294967295);$ix=$inc105;;}}while(0);var $73=$p;var $incdec_ptr108=(($73+1)&4294967295);$p=$incdec_ptr108;var $74=$p;var $75=HEAPU8[($74)];var $conv43=((($75))&255);var $cmp44=((($conv43))|0)!=0;if($cmp44){__label__=18;continue $for_body45$27;}else{__label__=33;break $for_body45$$for_end109$26;}}}}while(0);var $76=$tr_addr;var $langopts110=(($76)&4294967295);var $stress_rule=(($langopts110+8)&4294967295);var $77=HEAP32[(($stress_rule)>>2)];if($77==8){__label__=34;;}
else if($77==1){__label__=36;;}
else if($77==10){__label__=41;;}
else if($77==2){__label__=44;;}
else if($77==3){__label__=68;;}
else if($77==4){__label__=75;;}
else if($77==5){__label__=81;;}
else if($77==6){__label__=89;;}
else if($77==7){__label__=101;;}
else if($77==9){__label__=108;;}
else{__label__=112;;}
$sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50:do{if(__label__==34){var $arrayidx111=(($syllable_weight+1)&4294967295);var $78=HEAP8[($arrayidx111)];var $conv112=(tempInt=(($78)),(tempInt>=128?tempInt-256:tempInt));var $cmp113=((($conv112))|0)>0;if($cmp113){__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
var $arrayidx115=(($syllable_weight+2)&4294967295);var $79=HEAP8[($arrayidx115)];var $conv116=(tempInt=(($79)),(tempInt>=128?tempInt-256:tempInt));var $cmp117=((($conv116))|0)==0;if($cmp117){__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}else{__label__=36;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}}
else if(__label__==41){var $84=HEAP32[(($stressed_syllable)>>2)];var $cmp131=((($84))|0)==0;if(!($cmp131)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
var $85=HEAP32[(($vowel_count)>>2)];var $cmp133=((($85))|0)<4;if(!($cmp133)){__label__=44;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
var $86=HEAP32[(($vowel_count)>>2)];var $sub135=((($86)-1)&4294967295);var $arrayidx136=(($vowel_stress+$sub135)&4294967295);HEAP8[($arrayidx136)]=4;$max_stress=4;__label__=114;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
else if(__label__==68){var $129=HEAP32[(($stressed_syllable)>>2)];var $cmp229=((($129))|0)==0;if(!($cmp229)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
var $130=HEAP32[(($vowel_count)>>2)];var $sub231=((($130)-1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub231;__lastLabel__=69;;while(1){var $131=__lastLabel__==73?$dec239:($sub231);var $cmp232=((($131))|0)>0;if(!($cmp232)){__label__=74;break;}
var $132=HEAP32[(($stressed_syllable)>>2)];var $arrayidx233=(($vowel_stress+$132)&4294967295);var $133=HEAP8[($arrayidx233)];var $conv234=(tempInt=(($133)),(tempInt>=128?tempInt-256:tempInt));var $cmp235=((($conv234))|0)<0;var $134=HEAP32[(($stressed_syllable)>>2)];if($cmp235){__label__=72;break;}
var $dec239=((($134)-1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$dec239;__lastLabel__=73;__label__=70;continue;}
if(__label__==72){var $arrayidx237=(($vowel_stress+$134)&4294967295);HEAP8[($arrayidx237)]=4;;}
$max_stress=4;__label__=114;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
else if(__label__==75){var $135=HEAP32[(($stressed_syllable)>>2)];var $cmp243=((($135))|0)==0;if(!($cmp243)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
var $136=HEAP32[(($vowel_count)>>2)];var $sub245=((($136)-3)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub245;var $137=HEAP32[(($stressed_syllable)>>2)];var $cmp246=((($137))|0)<1;if($cmp246){__label__=77;;}else{__label__=78;;}
if(__label__==77){HEAP32[(($stressed_syllable)>>2)]=1;;}
var $138=$max_stress;var $cmp249=((($138))|0)==0;if($cmp249){__label__=79;;}else{__label__=80;;}
if(__label__==79){var $139=HEAP32[(($stressed_syllable)>>2)];var $arrayidx251=(($vowel_stress+$139)&4294967295);HEAP8[($arrayidx251)]=4;;}
$max_stress=4;__label__=114;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
else if(__label__==81){var $140=HEAP32[(($stressed_syllable)>>2)];var $cmp255=((($140))|0)==0;if(!($cmp255)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
var $141=HEAP32[(($vowel_count)>>2)];var $sub257=((($141)-3)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub257;var $142=HEAP32[(($vowel_count)>>2)];var $cmp258=((($142))|0)<16;if($cmp258){__label__=83;;}else{__label__=88;;}
if(__label__==83){var $143=$final_ph;var $arrayidx260=((_phoneme_tab+$143*4)&4294967295);var $144=HEAP32[(($arrayidx260)>>2)];var $type261=(($144+11)&4294967295);var $145=HEAPU8[($type261)];var $conv262=((($145))&255);var $cmp263=((($conv262))|0)==2;if($cmp263){__label__=84;;}else{__label__=85;;}
if(__label__==84){var $146=HEAP32[(($vowel_count)>>2)];var $arrayidx265=((__ZZ13SetWordStressP10TranslatorPcPjiiE10guess_ru_v+$146)&4294967295);var $147=HEAP8[($arrayidx265)];var $conv266=(tempInt=(($147)),(tempInt>=128?tempInt-256:tempInt));HEAP32[(($stressed_syllable)>>2)]=$conv266;;}
else if(__label__==85){var $148=$final_ph;var $arrayidx268=((_phoneme_tab+$148*4)&4294967295);var $149=HEAP32[(($arrayidx268)>>2)];var $type269=(($149+11)&4294967295);var $150=HEAPU8[($type269)];var $conv270=((($150))&255);var $cmp271=((($conv270))|0)==4;var $151=HEAP32[(($vowel_count)>>2)];if($cmp271){__label__=86;;}else{__label__=87;;}
if(__label__==86){var $arrayidx273=((__ZZ13SetWordStressP10TranslatorPcPjiiE10guess_ru_t+$151)&4294967295);var $152=HEAP8[($arrayidx273)];var $conv274=(tempInt=(($152)),(tempInt>=128?tempInt-256:tempInt));HEAP32[(($stressed_syllable)>>2)]=$conv274;;}
else if(__label__==87){var $arrayidx276=((__ZZ13SetWordStressP10TranslatorPcPjiiE8guess_ru+$151)&4294967295);var $153=HEAP8[($arrayidx276)];var $conv277=(tempInt=(($153)),(tempInt>=128?tempInt-256:tempInt));HEAP32[(($stressed_syllable)>>2)]=$conv277;;}}}
var $154=HEAP32[(($stressed_syllable)>>2)];var $arrayidx281=(($vowel_stress+$154)&4294967295);HEAP8[($arrayidx281)]=4;$max_stress=4;__label__=114;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
else if(__label__==89){var $155=HEAP32[(($stressed_syllable)>>2)];var $cmp284=((($155))|0)==0;if(!($cmp284)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
$max_weight=-1;$ix=1;var $156=$ix;var $157=HEAP32[(($vowel_count)>>2)];var $sub28714=((($157)-1)&4294967295);var $cmp28815=((($156))|0)<((($sub28714))|0);if($cmp28815){__label__=91;;}else{__label__=95;;}
$for_body289$$for_end302$86:do{if(__label__==91){$for_body289$87:while(1){var $158=$ix;var $arrayidx290=(($vowel_stress+$158)&4294967295);var $159=HEAP8[($arrayidx290)];var $conv291=(tempInt=(($159)),(tempInt>=128?tempInt-256:tempInt));var $cmp292=((($conv291))|0)<0;if($cmp292){__label__=92;;}else{__label__=94;;}
$if_then293$$for_inc300$89:do{if(__label__==92){var $160=$ix;var $arrayidx294=(($syllable_weight+$160)&4294967295);var $161=HEAP8[($arrayidx294)];var $conv295=(tempInt=(($161)),(tempInt>=128?tempInt-256:tempInt));$wt=$conv295;var $162=$max_weight;var $cmp296=((($conv295))|0)>=((($162))|0);if(!($cmp296)){__label__=94;break $if_then293$$for_inc300$89;}
var $163=$wt;$max_weight=$163;var $164=HEAP32[(($stressed_syllable)>>2)];$prev_stressed=$164;var $165=$ix;HEAP32[(($stressed_syllable)>>2)]=$165;;}}while(0);var $166=$ix;var $inc301=((($166)+1)&4294967295);$ix=$inc301;var $167=$ix;var $168=HEAP32[(($vowel_count)>>2)];var $sub287=((($168)-1)&4294967295);var $cmp288=((($167))|0)<((($sub287))|0);if($cmp288){__label__=91;continue $for_body289$87;}else{__label__=95;break $for_body289$$for_end302$86;}}}}while(0);var $169=HEAP32[(($vowel_count)>>2)];var $sub303=((($169)-1)&4294967295);var $arrayidx304=(($syllable_weight+$sub303)&4294967295);var $170=HEAP8[($arrayidx304)];var $conv305=(tempInt=(($170)),(tempInt>=128?tempInt-256:tempInt));var $cmp306=((($conv305))|0)==2;var $171=$max_weight;if($cmp306){__label__=96;;}else{__label__=98;;}
$land_lhs_true307$$if_else311$94:do{if(__label__==96){var $cmp308=((($171))|0)<2;if(!($cmp308)){__label__=100;break $land_lhs_true307$$if_else311$94;}
var $172=HEAP32[(($vowel_count)>>2)];var $sub310=((($172)-1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub310;;}
else if(__label__==98){var $cmp312=((($171))|0)<=0;if(!($cmp312)){__label__=100;break $land_lhs_true307$$if_else311$94;}
HEAP32[(($stressed_syllable)>>2)]=1;;}}while(0);var $173=HEAP32[(($stressed_syllable)>>2)];var $arrayidx316=(($vowel_stress+$173)&4294967295);HEAP8[($arrayidx316)]=4;$max_stress=4;__label__=114;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
else if(__label__==101){var $174=HEAP32[(($stressed_syllable)>>2)];var $cmp319=((($174))|0)==0;if(!($cmp319)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
var $175=HEAP32[(($vowel_count)>>2)];var $sub321=((($175)-1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub321;$ix=1;;while(1){var $176=$ix;var $177=HEAP32[(($vowel_count)>>2)];var $cmp323=((($176))|0)<((($177))|0);if(!($cmp323)){__label__=107;break;}
var $178=$ix;var $arrayidx325=(($vowel_stress+$178)&4294967295);var $179=HEAP8[($arrayidx325)];var $conv326=(tempInt=(($179)),(tempInt>=128?tempInt-256:tempInt));var $cmp327=((($conv326))|0)==1;var $180=$ix;if($cmp327){__label__=105;break;}
var $inc332=((($180)+1)&4294967295);$ix=$inc332;__label__=103;continue;}
if(__label__==105){var $sub329=((($180)-1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub329;;}
var $181=HEAP32[(($stressed_syllable)>>2)];var $arrayidx334=(($vowel_stress+$181)&4294967295);HEAP8[($arrayidx334)]=4;$max_stress=4;__label__=114;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
else if(__label__==108){$ix=1;var $182=$ix;var $183=HEAP32[(($vowel_count)>>2)];var $cmp33813=((($182))|0)<((($183))|0);if(!($cmp33813)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}
while(1){var $184=$ix;var $arrayidx340=(($vowel_stress+$184)&4294967295);var $185=HEAP8[($arrayidx340)];var $conv341=(tempInt=(($185)),(tempInt>=128?tempInt-256:tempInt));var $cmp342=((($conv341))|0)<0;if($cmp342){__label__=110;;}else{__label__=111;;}
if(__label__==110){var $186=$ix;var $arrayidx344=(($vowel_stress+$186)&4294967295);HEAP8[($arrayidx344)]=4;;}
var $187=$ix;var $inc347=((($187)+1)&4294967295);$ix=$inc347;var $188=$ix;var $189=HEAP32[(($vowel_count)>>2)];var $cmp338=((($188))|0)<((($189))|0);if($cmp338){__label__=109;continue;}else{__label__=112;break $sw_epilog$$sw_bb$$sw_bb120$$sw_bb130$$sw_bb139$$sw_bb228$$sw_bb242$$sw_bb254$$sw_bb283$$sw_bb318$$sw_bb336$50;}}}}while(0);$sw_epilog$$sw_bb120$$if_else351$$sw_bb139$115:do{if(__label__==36){var $80=HEAP32[(($stressed_syllable)>>2)];var $cmp121=((($80))|0)==0;if(!($cmp121)){__label__=112;break $sw_epilog$$sw_bb120$$if_else351$$sw_bb139$115;}
var $81=HEAP32[(($vowel_count)>>2)];var $cmp123=((($81))|0)>2;if(!($cmp123)){__label__=112;break $sw_epilog$$sw_bb120$$if_else351$$sw_bb139$115;}
HEAP32[(($stressed_syllable)>>2)]=2;var $82=$max_stress;var $cmp125=((($82))|0)==0;if($cmp125){__label__=39;;}else{__label__=40;;}
if(__label__==39){var $83=HEAP32[(($stressed_syllable)>>2)];var $arrayidx127=(($vowel_stress+$83)&4294967295);HEAP8[($arrayidx127)]=4;;}
$max_stress=4;__label__=114;break $sw_epilog$$sw_bb120$$if_else351$$sw_bb139$115;}
else if(__label__==44){var $_pr5=HEAP32[(($stressed_syllable)>>2)];var $cmp140=((($_pr5))|0)==0;if(!($cmp140)){__label__=112;break $sw_epilog$$sw_bb120$$if_else351$$sw_bb139$115;}
$max_stress=4;var $87=HEAP32[(($vowel_count)>>2)];var $cmp142=((($87))|0)>2;if($cmp142){__label__=46;;}else{__label__=63;;}
$if_then143$$if_else208$124:do{if(__label__==46){var $88=HEAP32[(($vowel_count)>>2)];var $sub144=((($88)-2)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub144;var $89=$stressflags;var $and145=($89)&768;var $tobool146=((($and145))|0)!=0;if($tobool146){__label__=47;;}else{__label__=55;;}
$if_then147$$if_end179$126:do{if(__label__==47){var $90=$final_ph;var $arrayidx148=((_phoneme_tab+$90*4)&4294967295);var $91=HEAP32[(($arrayidx148)>>2)];var $type149=(($91+11)&4294967295);var $92=HEAPU8[($type149)];var $conv150=((($92))&255);var $cmp151=((($conv150))|0)!=2;if(!($cmp151)){__label__=55;break $if_then147$$if_end179$126;}
var $93=$stressflags;var $and153=($93)&256;var $tobool154=((($and153))|0)!=0;if($tobool154){__label__=49;;}else{__label__=50;;}
if(__label__==49){var $94=HEAP32[(($vowel_count)>>2)];var $sub156=((($94)-1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub156;;}
else if(__label__==50){var $95=$final_ph;var $arrayidx157=((_phoneme_tab+$95*4)&4294967295);var $96=HEAP32[(($arrayidx157)>>2)];var $mnemonic=(($96)&4294967295);var $97=HEAP32[(($mnemonic)>>2)];$mnem=$97;var $98=$final_ph2;var $arrayidx158=((_phoneme_tab+$98*4)&4294967295);var $99=HEAP32[(($arrayidx158)>>2)];var $mnemonic159=(($99)&4294967295);var $100=HEAP32[(($mnemonic159)>>2)];$mnem2=$100;var $101=$mnem;var $cmp160=((($101))|0)==115;if($cmp160){__label__=51;;}else{__label__=52;;}
if(__label__==51){var $102=$mnem2;var $cmp162=((($102))|0)==110;if($cmp162){__label__=55;break $if_then147$$if_end179$126;}}
var $103=$mnem;var $cmp165=((($103))|0)!=110;var $104=$mnem;var $cmp167=((($104))|0)!=115;var $or_cond=($cmp165)&($cmp167);if($or_cond){__label__=54;;}else{__label__=53;;}
if(__label__==53){var $105=$final_ph2;var $arrayidx169=((_phoneme_tab+$105*4)&4294967295);var $106=HEAP32[(($arrayidx169)>>2)];var $type170=(($106+11)&4294967295);var $107=HEAPU8[($type170)];var $conv171=((($107))&255);var $cmp172=((($conv171))|0)!=2;if(!($cmp172)){__label__=55;break $if_then147$$if_end179$126;}}
var $108=HEAP32[(($vowel_count)>>2)];var $sub174=((($108)-1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub174;;}}}while(0);var $109=$stressflags;var $and180=($109)&524288;var $tobool181=((($and180))|0)!=0;if($tobool181){__label__=56;;}else{__label__=58;;}
$if_then182$$if_end193$139:do{if(__label__==56){var $110=HEAP32[(($vowel_count)>>2)];var $sub183=((($110)-1)&4294967295);var $arrayidx184=(($vowel_length+$sub183)&4294967295);var $111=HEAP8[($arrayidx184)];var $conv185=(tempInt=(($111)),(tempInt>=128?tempInt-256:tempInt));var $112=HEAP32[(($vowel_count)>>2)];var $sub186=((($112)-2)&4294967295);var $arrayidx187=(($vowel_length+$sub186)&4294967295);var $113=HEAP8[($arrayidx187)];var $conv188=(tempInt=(($113)),(tempInt>=128?tempInt-256:tempInt));var $cmp189=((($conv185))|0)>((($conv188))|0);if(!($cmp189)){__label__=58;break $if_then182$$if_end193$139;}
var $114=HEAP32[(($vowel_count)>>2)];var $sub191=((($114)-1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$sub191;;}}while(0);var $115=HEAP32[(($stressed_syllable)>>2)];var $arrayidx194=(($vowel_stress+$115)&4294967295);var $116=HEAP8[($arrayidx194)];var $conv195=(tempInt=(($116)),(tempInt>=128?tempInt-256:tempInt));var $cmp196=((($conv195))|0)==0;if($cmp196){__lastLabel__=58;__label__=60;;}else{__lastLabel__=58;__label__=59;;}
if(__label__==59){var $117=HEAP32[(($stressed_syllable)>>2)];var $arrayidx198=(($vowel_stress+$117)&4294967295);var $118=HEAP8[($arrayidx198)];var $conv199=(tempInt=(($118)),(tempInt>=128?tempInt-256:tempInt));var $cmp200=((($conv199))|0)==1;if($cmp200){__lastLabel__=59;;}else{__lastLabel__=59;__label__=64;break $if_then143$$if_else208$124;}}
var $119=__lastLabel__==59?$117:($115);var $cmp202=((($119))|0)>1;var $120=HEAP32[(($stressed_syllable)>>2)];if($cmp202){__label__=61;;}else{__label__=62;;}
if(__label__==61){var $dec=((($120)-1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$dec;;}
else if(__label__==62){var $inc205=((($120)+1)&4294967295);HEAP32[(($stressed_syllable)>>2)]=$inc205;;}}
else if(__label__==63){HEAP32[(($stressed_syllable)>>2)]=1;;}}while(0);var $121=HEAP32[(($stressed_syllable)>>2)];var $arrayidx210=(($vowel_stress+$121)&4294967295);var $122=HEAP8[($arrayidx210)];var $conv211=(tempInt=(($122)),(tempInt>=128?tempInt-256:tempInt));var $cmp212=((($conv211))|0)<0;if(!($cmp212)){__label__=112;break $sw_epilog$$sw_bb120$$if_else351$$sw_bb139$115;}
var $123=HEAP32[(($stressed_syllable)>>2)];var $sub214=((($123)-1)&4294967295);var $arrayidx215=(($vowel_stress+$sub214)&4294967295);var $124=HEAP8[($arrayidx215)];var $conv216=(tempInt=(($124)),(tempInt>=128?tempInt-256:tempInt));var $cmp217=((($conv216))|0)<4;if($cmp217){__label__=67;;}else{__label__=66;;}
if(__label__==66){var $125=HEAP32[(($stressed_syllable)>>2)];var $add=((($125)+1)&4294967295);var $arrayidx219=(($vowel_stress+$add)&4294967295);var $126=HEAP8[($arrayidx219)];var $conv220=(tempInt=(($126)),(tempInt>=128?tempInt-256:tempInt));var $cmp221=((($conv220))|0)<4;if(!($cmp221)){__label__=112;break $sw_epilog$$sw_bb120$$if_else351$$sw_bb139$115;}}
var $127=$max_stress;var $conv223=((($127))&255);var $128=HEAP32[(($stressed_syllable)>>2)];var $arrayidx224=(($vowel_stress+$128)&4294967295);HEAP8[($arrayidx224)]=$conv223;__label__=112;break $sw_epilog$$sw_bb120$$if_else351$$sw_bb139$115;}}while(0);$sw_epilog$$if_else351$155:do{if(__label__==112){var $_pr9=$max_stress;var $cmp349=((($_pr9))|0)<4;if(!($cmp349)){__label__=114;break $sw_epilog$$if_else351$155;}
$stress=4;__label__=115;break $sw_epilog$$if_else351$155;}}while(0);if(__label__==114){$stress=3;;}
var $190=$stressflags;var $and353=($190)&4096;var $tobool354=((($and353))|0)!=0;if($tobool354){__label__=116;;}else{__label__=121;;}
$land_lhs_true355$$if_end370$161:do{if(__label__==116){var $191=HEAP32[(($vowel_count)>>2)];var $cmp356=((($191))|0)==2;if(!($cmp356)){__label__=121;break $land_lhs_true355$$if_end370$161;}
var $arrayidx358=(($vowel_stress+1)&4294967295);var $192=HEAP8[($arrayidx358)];var $conv359=(tempInt=(($192)),(tempInt>=128?tempInt-256:tempInt));var $cmp360=((($conv359))|0)==4;if($cmp360){__label__=118;;}else{__label__=119;;}
if(__label__==118){var $arrayidx362=(($vowel_stress+2)&4294967295);HEAP8[($arrayidx362)]=3;;}
var $arrayidx364=(($vowel_stress+2)&4294967295);var $193=HEAP8[($arrayidx364)];var $conv365=(tempInt=(($193)),(tempInt>=128?tempInt-256:tempInt));var $cmp366=((($conv365))|0)==4;if(!($cmp366)){__label__=121;break $land_lhs_true355$$if_end370$161;}
var $arrayidx368=(($vowel_stress+1)&4294967295);HEAP8[($arrayidx368)]=3;;}}while(0);var $194=$stressflags;var $and371=($194)&8192;var $tobool372=((($and371))|0)!=0;if($tobool372){__label__=122;;}else{__label__=126;;}
$land_lhs_true373$$if_end386$169:do{if(__label__==122){var $arrayidx374=(($vowel_stress+1)&4294967295);var $195=HEAP8[($arrayidx374)];var $conv375=(tempInt=(($195)),(tempInt>=128?tempInt-256:tempInt));var $cmp376=((($conv375))|0)<0;if(!($cmp376)){__label__=126;break $land_lhs_true373$$if_end386$169;}
var $196=HEAP32[(($vowel_count)>>2)];var $cmp378=((($196))|0)>2;if(!($cmp378)){__label__=126;break $land_lhs_true373$$if_end386$169;}
var $arrayidx380=(($vowel_stress+2)&4294967295);var $197=HEAP8[($arrayidx380)];var $conv381=(tempInt=(($197)),(tempInt>=128?tempInt-256:tempInt));var $cmp382=((($conv381))|0)>=4;if(!($cmp382)){__label__=126;break $land_lhs_true373$$if_end386$169;}
var $arrayidx384=(($vowel_stress+1)&4294967295);HEAP8[($arrayidx384)]=3;;}}while(0);$done=0;$first_primary=0;$v=1;var $198=$v;var $199=HEAP32[(($vowel_count)>>2)];var $cmp38818=((($198))|0)<((($199))|0);if($cmp38818){__label__=127;;}else{__label__=151;;}
$for_body389$$for_end471$175:do{if(__label__==127){$for_body389$176:while(1){var $200=$v;var $arrayidx390=(($vowel_stress+$200)&4294967295);var $201=HEAP8[($arrayidx390)];var $conv391=(tempInt=(($201)),(tempInt>=128?tempInt-256:tempInt));var $cmp392=((($conv391))|0)<0;if($cmp392){__label__=128;;}else{__label__=145;;}
$if_then393$$if_end454$178:do{if(__label__==128){var $202=$stressflags;var $and394=($202)&16;var $tobool395=((($and394))|0)!=0;if($tobool395){__label__=129;;}else{__label__=131;;}
$land_lhs_true396$$if_else402$180:do{if(__label__==129){var $203=$stress;var $cmp397=((($203))|0)<4;if(!($cmp397)){__label__=131;break $land_lhs_true396$$if_else402$180;}
var $204=$v;var $205=HEAP32[(($vowel_count)>>2)];var $sub399=((($205)-1)&4294967295);var $cmp400=((($204))|0)==((($sub399))|0);if($cmp400){__label__=145;break $if_then393$$if_end454$178;}}}while(0);var $206=$stressflags;var $and403=($206)&32768;var $tobool404=((($and403))|0)!=0;if($tobool404){__label__=132;;}else{__label__=134;;}
$land_lhs_true405$$if_else410$184:do{if(__label__==132){var $207=$done;var $cmp406=((($207))|0)==0;if(!($cmp406)){__label__=134;break $land_lhs_true405$$if_else410$184;}
var $208=$stress;var $conv408=((($208))&255);var $209=$v;var $arrayidx409=(($vowel_stress+$209)&4294967295);HEAP8[($arrayidx409)]=$conv408;$done=1;$stress=3;__label__=145;break $if_then393$$if_end454$178;}}while(0);var $210=$v;var $sub411=((($210)-1)&4294967295);var $arrayidx412=(($vowel_stress+$sub411)&4294967295);var $211=HEAP8[($arrayidx412)];var $conv413=(tempInt=(($211)),(tempInt>=128?tempInt-256:tempInt));var $cmp414=((($conv413))|0)<=1;if(!($cmp414)){__label__=145;break $if_then393$$if_end454$178;}
var $212=$v;var $add416=((($212)+1)&4294967295);var $arrayidx417=(($vowel_stress+$add416)&4294967295);var $213=HEAP8[($arrayidx417)];var $conv418=(tempInt=(($213)),(tempInt>=128?tempInt-256:tempInt));var $cmp419=((($conv418))|0)<=1;if($cmp419){__label__=138;;}else{__label__=136;;}
if(__label__==136){var $214=$stress;var $cmp421=((($214))|0)==4;if(!($cmp421)){__label__=145;break $if_then393$$if_end454$178;}
var $215=$v;var $add423=((($215)+1)&4294967295);var $arrayidx424=(($vowel_stress+$add423)&4294967295);var $216=HEAP8[($arrayidx424)];var $conv425=(tempInt=(($216)),(tempInt>=128?tempInt-256:tempInt));var $cmp426=((($conv425))|0)<=2;if(!($cmp426)){__label__=145;break $if_then393$$if_end454$178;}}
var $217=$stress;var $cmp428=((($217))|0)==3;if($cmp428){__label__=139;;}else{__label__=140;;}
if(__label__==139){var $218=$stressflags;var $and430=($218)&32;var $tobool431=((($and430))|0)!=0;if($tobool431){__label__=150;break $if_then393$$if_end454$178;}}
var $219=$v;var $cmp434=((($219))|0)>1;if($cmp434){__label__=141;;}else{__label__=144;;}
$land_lhs_true435$$if_end448$196:do{if(__label__==141){var $220=$stressflags;var $and436=($220)&64;var $tobool437=((($and436))|0)!=0;if(!($tobool437)){__label__=144;break $land_lhs_true435$$if_end448$196;}
var $221=$v;var $arrayidx439=(($syllable_weight+$221)&4294967295);var $222=HEAP8[($arrayidx439)];var $conv440=(tempInt=(($222)),(tempInt>=128?tempInt-256:tempInt));var $cmp441=((($conv440))|0)==0;if(!($cmp441)){__label__=144;break $land_lhs_true435$$if_end448$196;}
var $223=$v;var $add443=((($223)+1)&4294967295);var $arrayidx444=(($syllable_weight+$add443)&4294967295);var $224=HEAP8[($arrayidx444)];var $conv445=(tempInt=(($224)),(tempInt>=128?tempInt-256:tempInt));var $cmp446=((($conv445))|0)>0;if($cmp446){__label__=150;break $if_then393$$if_end454$178;}}}while(0);var $225=$stress;var $conv449=((($225))&255);var $226=$v;var $arrayidx450=(($vowel_stress+$226)&4294967295);HEAP8[($arrayidx450)]=$conv449;$done=1;$stress=3;__label__=145;break $if_then393$$if_end454$178;}}while(0);$if_end454$$for_inc469$201:do{if(__label__==145){var $227=$v;var $arrayidx455=(($vowel_stress+$227)&4294967295);var $228=HEAP8[($arrayidx455)];var $conv456=(tempInt=(($228)),(tempInt>=128?tempInt-256:tempInt));var $cmp457=((($conv456))|0)>=4;if(!($cmp457)){__label__=150;break $if_end454$$for_inc469$201;}
var $229=$first_primary;var $cmp459=((($229))|0)==0;if($cmp459){__label__=147;;}else{__label__=148;;}
if(__label__==147){var $230=$v;$first_primary=$230;;}
else if(__label__==148){var $231=$stressflags;var $and462=($231)&128;var $tobool463=((($and462))|0)!=0;if(!($tobool463)){__label__=150;break $if_end454$$for_inc469$201;}
var $232=$v;var $arrayidx465=(($vowel_stress+$232)&4294967295);HEAP8[($arrayidx465)]=3;;}}}while(0);var $233=$v;var $inc470=((($233)+1)&4294967295);$v=$inc470;var $234=$v;var $235=HEAP32[(($vowel_count)>>2)];var $cmp388=((($234))|0)<((($235))|0);if($cmp388){__label__=127;continue $for_body389$176;}else{__label__=151;break $for_body389$$for_end471$175;}}}}while(0);var $236=$unstressed_word;var $tobool472=((($236))|0)!=0;if($tobool472){__label__=152;;}else{__label__=156;;}
$land_lhs_true473$$if_end482$210:do{if(__label__==152){var $237=$tonic_addr;var $cmp474=((($237))|0)<0;if(!($cmp474)){__label__=156;break $land_lhs_true473$$if_end482$210;}
var $238=HEAP32[(($vowel_count)>>2)];var $cmp476=((($238))|0)<=2;var $239=$tr_addr;var $langopts478=(($239)&4294967295);if($cmp476){__label__=154;;}else{__label__=155;;}
if(__label__==154){var $unstressed_wd1=(($langopts478+16)&4294967295);var $240=HEAP32[(($unstressed_wd1)>>2)];$tonic_addr=$240;;}
else if(__label__==155){var $unstressed_wd2=(($langopts478+20)&4294967295);var $241=HEAP32[(($unstressed_wd2)>>2)];$tonic_addr=$241;;}}}while(0);$max_stress=0;$max_stress_posn=0;$v=1;var $242=$v;var $243=HEAP32[(($vowel_count)>>2)];var $cmp48417=((($242))|0)<((($243))|0);if($cmp48417){__label__=157;;}else{__label__=160;;}
$for_body485$$for_end495$217:do{if(__label__==157){while(1){var $244=$v;var $arrayidx486=(($vowel_stress+$244)&4294967295);var $245=HEAP8[($arrayidx486)];var $conv487=(tempInt=(($245)),(tempInt>=128?tempInt-256:tempInt));var $246=$max_stress;var $cmp488=((($conv487))|0)>=((($246))|0);if($cmp488){__label__=158;;}else{__label__=159;;}
if(__label__==158){var $247=$v;var $arrayidx490=(($vowel_stress+$247)&4294967295);var $248=HEAP8[($arrayidx490)];var $conv491=(tempInt=(($248)),(tempInt>=128?tempInt-256:tempInt));$max_stress=$conv491;var $249=$v;$max_stress_posn=$249;;}
var $250=$v;var $inc494=((($250)+1)&4294967295);$v=$inc494;var $251=$v;var $252=HEAP32[(($vowel_count)>>2)];var $cmp484=((($251))|0)<((($252))|0);if($cmp484){__label__=157;continue;}else{__label__=160;break $for_body485$$for_end495$217;}}}}while(0);var $253=$tonic_addr;var $cmp496=((($253))|0)>=0;if($cmp496){__label__=161;;}else{__label__=164;;}
if(__label__==161){var $254=$tonic_addr;var $255=$max_stress;var $cmp498=((($254))|0)>((($255))|0);var $256=$max_stress;var $cmp500=((($256))|0)<=4;var $or_cond1=($cmp498)|($cmp500);if($or_cond1){__label__=162;;}else{__label__=163;;}
if(__label__==162){var $257=$tonic_addr;var $conv502=((($257))&255);var $258=$max_stress_posn;var $arrayidx503=(($vowel_stress+$258)&4294967295);HEAP8[($arrayidx503)]=$conv502;;}
var $259=$tonic_addr;$max_stress=$259;;}
var $arraydecay506=(($phonetic)&4294967295);$p=$arraydecay506;$v=1;var $260=$control_addr;var $and507=($260)&1;var $tobool508=((($and507))|0)!=0;if($tobool508){__label__=174;;}else{__label__=165;;}
$if_end544$$land_lhs_true509$230:do{if(__label__==165){var $261=$p;var $262=HEAPU8[($261)];var $idxprom510=((($262))&255);var $arrayidx511=((_phoneme_tab+$idxprom510*4)&4294967295);var $263=HEAPU32[(($arrayidx511)>>2)];$ph=$263;var $cmp512=((($263))|0)!=0;if(!($cmp512)){__label__=174;break $if_end544$$land_lhs_true509$230;}
var $264=$ph;var $type514=(($264+11)&4294967295);var $265=HEAPU8[($type514)];var $conv515=((($265))&255);var $cmp516=((($conv515))|0)==1;if($cmp516){__label__=167;;}else{__label__=168;;}
if(__label__==167){var $266=$p;var $arrayidx518=(($266+1)&4294967295);var $267=HEAPU8[($arrayidx518)];var $idxprom519=((($267))&255);var $arrayidx520=((_phoneme_tab+$idxprom519*4)&4294967295);var $268=HEAP32[(($arrayidx520)>>2)];$ph=$268;;}
var $269=$tr_addr;var $langopts522=(($269)&4294967295);var $vowel_pause=(($langopts522+4)&4294967295);var $270=HEAP32[(($vowel_pause)>>2)];var $and523=($270)&48;var $tobool524=((($and523))|0)!=0;if(!($tobool524)){__label__=174;break $if_end544$$land_lhs_true509$230;}
var $271=$ph;var $type526=(($271+11)&4294967295);var $272=HEAPU8[($type526)];var $conv527=((($272))&255);var $cmp528=((($conv527))|0)==2;if(!($cmp528)){__label__=174;break $if_end544$$land_lhs_true509$230;}
var $273=$tr_addr;var $langopts530=(($273)&4294967295);var $vowel_pause531=(($langopts530+4)&4294967295);var $274=HEAP32[(($vowel_pause531)>>2)];var $and532=($274)&32;var $tobool533=((($and532))|0)!=0;if($tobool533){__label__=171;;}else{__label__=173;;}
$land_lhs_true534$$if_else540$238:do{if(__label__==171){var $arrayidx535=(($vowel_stress+1)&4294967295);var $275=HEAP8[($arrayidx535)];var $conv536=(tempInt=(($275)),(tempInt>=128?tempInt-256:tempInt));var $cmp537=((($conv536))|0)>=4;if(!($cmp537)){__label__=173;break $land_lhs_true534$$if_else540$238;}
var $276=$output_addr;var $incdec_ptr539=(($276+1)&4294967295);$output_addr=$incdec_ptr539;HEAP8[($276)]=11;__label__=174;break $if_end544$$land_lhs_true509$230;}}while(0);var $277=$output_addr;var $incdec_ptr541=(($277+1)&4294967295);$output_addr=$incdec_ptr541;HEAP8[($277)]=23;;}}while(0);var $arraydecay545=(($phonetic)&4294967295);$p=$arraydecay545;$post_tonic=0;;$while_cond546$243:while(1){var $278=$p;var $incdec_ptr547=(($278+1)&4294967295);$p=$incdec_ptr547;var $279=HEAPU8[($278)];$phcode=$279;var $conv548=((($279))&255);var $cmp549=((($conv548))|0)!=0;if(!($cmp549)){__label__=222;break $while_cond546$243;}
var $280=$output_addr;var $281=$max_output;var $cmp550=((($280))>>>0)<((($281))>>>0);if(!($cmp550)){__label__=222;break $while_cond546$243;}
var $282=$phcode;var $idxprom552=((($282))&255);var $arrayidx553=((_phoneme_tab+$idxprom552*4)&4294967295);var $283=HEAPU32[(($arrayidx553)>>2)];$ph=$283;var $cmp554=((($283))|0)==0;if($cmp554){__label__=175;continue $while_cond546$243;}
var $284=$ph;var $type557=(($284+11)&4294967295);var $285=HEAPU8[($type557)];var $conv558=((($285))&255);var $cmp559=((($conv558))|0)==0;if($cmp559){__label__=179;;}else{__label__=180;;}
$if_then560$$if_else561$248:do{if(__label__==179){var $286=$tr_addr;var $prev_last_stress=(($286+8288)&4294967295);HEAP32[(($prev_last_stress)>>2)]=0;;}
else if(__label__==180){var $287=$ph;var $type562=(($287+11)&4294967295);var $288=HEAPU8[($type562)];var $conv563=((($288))&255);var $cmp564=((($conv563))|0)==2;if($cmp564){__label__=181;;}else{__label__=182;;}
$land_lhs_true565$$lor_lhs_false569$251:do{if(__label__==181){var $289=$ph;var $phflags566=(($289+4)&4294967295);var $290=HEAP32[(($phflags566)>>2)];var $and567=($290)&1048576;var $tobool568=((($and567))|0)!=0;if($tobool568){__label__=182;break $land_lhs_true565$$lor_lhs_false569$251;}else{__label__=183;break $land_lhs_true565$$lor_lhs_false569$251;}}}while(0);if(__label__==182){var $291=$p;var $292=HEAPU8[($291)];var $conv570=((($292))&255);var $cmp571=((($conv570))|0)==20;if(!($cmp571)){__label__=220;break $if_then560$$if_else561$248;}}
var $293=$v;var $arrayidx573=(($vowel_stress+$293)&4294967295);var $294=HEAP8[($arrayidx573)];var $conv574=(tempInt=(($294)),(tempInt>=128?tempInt-256:tempInt));$v_stress=$conv574;var $295=$v_stress;var $296=$tr_addr;var $prev_last_stress575=(($296+8288)&4294967295);HEAP32[(($prev_last_stress575)>>2)]=$295;var $297=$v;var $sub576=((($297)-1)&4294967295);var $arrayidx577=(($vowel_stress+$sub576)&4294967295);var $298=HEAP8[($arrayidx577)];var $conv578=(tempInt=(($298)),(tempInt>=128?tempInt-256:tempInt));var $299=$max_stress;var $cmp579=((($conv578))|0)>=((($299))|0);if($cmp579){__label__=184;;}else{__label__=185;;}
if(__label__==184){$post_tonic=1;;}
var $300=$v_stress;var $cmp582=((($300))|0)<=1;if($cmp582){__label__=186;;}else{__label__=201;;}
$if_then583$$if_end627$259:do{if(__label__==186){var $301=$v;var $cmp584=((($301))|0)>1;if($cmp584){__label__=187;;}else{__label__=191;;}
$land_lhs_true585$$if_else594$261:do{if(__label__==187){var $302=$max_stress;var $cmp586=((($302))|0)>=4;if(!($cmp586)){__label__=191;break $land_lhs_true585$$if_else594$261;}
var $303=$stressflags;var $and588=($303)&4;var $tobool589=((($and588))|0)!=0;if(!($tobool589)){__label__=191;break $land_lhs_true585$$if_else594$261;}
var $304=$v;var $305=HEAP32[(($vowel_count)>>2)];var $sub591=((($305)-1)&4294967295);var $cmp592=((($304))|0)==((($sub591))|0);if(!($cmp592)){__label__=191;break $land_lhs_true585$$if_else594$261;}
$v_stress=0;__label__=201;break $if_then583$$if_end627$259;}}while(0);var $306=$stressflags;var $and595=($306)&2;var $tobool596=((($and595))|0)!=0;if($tobool596){__label__=194;;}else{__label__=192;;}
$if_then602$$lor_lhs_false597$267:do{if(__label__==192){var $307=$v;var $cmp598=((($307))|0)==1;if($cmp598){__label__=194;break $if_then602$$lor_lhs_false597$267;}
var $308=$v;var $309=HEAP32[(($vowel_count)>>2)];var $sub600=((($309)-1)&4294967295);var $cmp601=((($308))|0)==((($sub600))|0);if($cmp601){__label__=194;break $if_then602$$lor_lhs_false597$267;}
var $310=$v;var $311=HEAP32[(($vowel_count)>>2)];var $sub604=((($311)-2)&4294967295);var $cmp605=((($310))|0)==((($sub604))|0);if($cmp605){__label__=196;;}else{__label__=198;;}
$land_lhs_true606$$if_else612$271:do{if(__label__==196){var $312=HEAP32[(($vowel_count)>>2)];var $sub607=((($312)-1)&4294967295);var $arrayidx608=(($vowel_stress+$sub607)&4294967295);var $313=HEAP8[($arrayidx608)];var $conv609=(tempInt=(($313)),(tempInt>=128?tempInt-256:tempInt));var $cmp610=((($conv609))|0)<=1;if(!($cmp610)){__label__=198;break $land_lhs_true606$$if_else612$271;}
$v_stress=1;__label__=201;break $if_then583$$if_end627$259;}}while(0);var $314=$v;var $sub613=((($314)-1)&4294967295);var $arrayidx614=(($vowel_stress+$sub613)&4294967295);var $315=HEAP8[($arrayidx614)];var $conv615=(tempInt=(($315)),(tempInt>=128?tempInt-256:tempInt));var $cmp616=((($conv615))|0)<0;if($cmp616){__label__=200;;}else{__label__=199;;}
if(__label__==199){var $316=$stressflags;var $and618=($316)&65536;var $cmp619=((($and618))|0)==0;if(!($cmp619)){__label__=201;break $if_then583$$if_end627$259;}}
$v_stress=0;var $317=$v_stress;var $conv621=((($317))&255);var $318=$v;var $arrayidx622=(($vowel_stress+$318)&4294967295);HEAP8[($arrayidx622)]=$conv621;__label__=201;break $if_then583$$if_end627$259;}}while(0);$v_stress=1;;}}while(0);var $319=$v_stress;var $cmp628=((($319))|0)==0;var $320=$v_stress;var $cmp630=((($320))|0)>1;var $or_cond2=($cmp628)|($cmp630);if($or_cond2){__label__=202;;}else{__label__=203;;}
if(__label__==202){var $321=$v_stress;var $arrayidx632=((__ZL15stress_phonemes+$321)&4294967295);var $322=HEAP8[($arrayidx632)];var $323=$output_addr;var $incdec_ptr633=(($323+1)&4294967295);$output_addr=$incdec_ptr633;HEAP8[($323)]=$322;;}
var $324=$v;var $arrayidx635=(($vowel_stress+$324)&4294967295);var $325=HEAP8[($arrayidx635)];var $conv636=(tempInt=(($325)),(tempInt>=128?tempInt-256:tempInt));var $326=$max_stress;var $cmp637=((($conv636))|0)>((($326))|0);if($cmp637){__label__=204;;}else{__label__=205;;}
if(__label__==204){var $327=$v;var $arrayidx639=(($vowel_stress+$327)&4294967295);var $328=HEAP8[($arrayidx639)];var $conv640=(tempInt=(($328)),(tempInt>=128?tempInt-256:tempInt));$max_stress=$conv640;;}
var $329=$p;var $330=HEAPU8[($329)];var $conv642=((($330))&255);var $cmp643=((($conv642))|0)==12;if($cmp643){__label__=206;;}else{__label__=214;;}
$land_lhs_true644$$if_end665$286:do{if(__label__==206){var $331=$tr_addr;var $langopts645=(($331)&4294967295);var $param=(($langopts645+24)&4294967295);var $arrayidx646=(($param+8)&4294967295);var $332=HEAP32[(($arrayidx646)>>2)];$opt_length=$332;var $and647=($332)&1;var $tobool648=((($and647))|0)!=0;if(!($tobool648)){__label__=214;break $land_lhs_true644$$if_end665$286;}
$shorten=0;var $333=$opt_length;var $and650=($333)&16;var $tobool651=((($and650))|0)!=0;if($tobool651){__label__=208;;}else{__label__=210;;}
$if_then652$$if_else656$289:do{if(__label__==208){var $334=$v;var $335=$max_stress_posn;var $cmp653=((($334))|0)!=((($335))|0);if(!($cmp653)){__label__=212;break $if_then652$$if_else656$289;}
$shorten=1;__label__=213;break $if_then652$$if_else656$289;}
else if(__label__==210){var $336=$v_stress;var $cmp657=((($336))|0)<4;if(!($cmp657)){__label__=212;break $if_then652$$if_else656$289;}
$shorten=1;__label__=213;break $if_then652$$if_else656$289;}}while(0);if(__label__==212){var $_pr11=$shorten;var $tobool661=((($_pr11))|0)!=0;if(!($tobool661)){__label__=214;break $land_lhs_true644$$if_end665$286;}}
var $337=$p;var $incdec_ptr663=(($337+1)&4294967295);$p=$incdec_ptr663;;}}while(0);var $338=$v_stress;var $cmp666=((($338))|0)>=4;if($cmp666){__label__=215;;}else{__label__=219;;}
$land_lhs_true667$$if_end682$298:do{if(__label__==215){var $339=$tr_addr;var $langopts668=(($339)&4294967295);var $param669=(($langopts668+24)&4294967295);var $arrayidx670=(($param669+8)&4294967295);var $340=HEAP32[(($arrayidx670)>>2)];var $cmp671=((($340))|0)==2;if(!($cmp671)){__label__=219;break $land_lhs_true667$$if_end682$298;}
var $341=$v;var $342=HEAP32[(($vowel_count)>>2)];var $sub673=((($342)-2)&4294967295);var $cmp674=((($341))|0)==((($sub673))|0);if(!($cmp674)){__label__=219;break $land_lhs_true667$$if_end682$298;}
var $343=$v;var $arrayidx676=(($syllable_weight+$343)&4294967295);var $344=HEAP8[($arrayidx676)];var $conv677=(tempInt=(($344)),(tempInt>=128?tempInt-256:tempInt));var $cmp678=((($conv677))|0)==0;if(!($cmp678)){__label__=219;break $land_lhs_true667$$if_end682$298;}
var $345=$phcode;var $346=$output_addr;var $incdec_ptr680=(($346+1)&4294967295);$output_addr=$incdec_ptr680;HEAP8[($346)]=$345;$phcode=12;;}}while(0);var $347=$v;var $inc683=((($347)+1)&4294967295);$v=$inc683;;}}while(0);var $348=$phcode;var $conv686=((($348))&255);var $cmp687=((($conv686))|0)!=1;if(!($cmp687)){__label__=175;continue $while_cond546$243;}
var $349=$phcode;var $350=$output_addr;var $incdec_ptr689=(($350+1)&4294967295);$output_addr=$incdec_ptr689;HEAP8[($350)]=$349;__label__=175;continue $while_cond546$243;}
var $351=$output_addr;var $incdec_ptr692=(($351+1)&4294967295);$output_addr=$incdec_ptr692;HEAP8[($351)]=0;;}
STACKTOP=__stackBase__;return;return;}
function __Z14AppendPhonemesP10TranslatorPciPKc($tr,$string,$size,$ph){;var __label__;var $tr_addr;var $string_addr;var $size_addr;var $ph_addr;var $p;var $c;var $unstress_mark;var $length;$tr_addr=$tr;$string_addr=$string;$size_addr=$size;$ph_addr=$ph;var $0=$ph_addr;var $call=_strlen($0);var $1=$string_addr;var $call1=_strlen($1);var $add=((($call1)+($call))&4294967295);$length=$add;var $2=$length;var $3=$size_addr;var $cmp=((($2))|0)>=((($3))|0);if($cmp){__label__=14;;}else{__label__=1;;}
$if_end34$$if_end$2:do{if(__label__==1){$unstress_mark=0;var $4=$ph_addr;$p=$4;var $5=$p;var $incdec_ptr1=(($5+1)&4294967295);$p=$incdec_ptr1;var $6=HEAPU8[($5)];$c=$6;var $conv2=((($6))&255);var $cmp23=((($conv2))|0)!=0;if($cmp23){__label__=2;;}else{__label__=12;;}
$while_body$$while_end$4:do{if(__label__==2){$while_body$5:while(1){var $7=$c;var $conv3=((($7))&255);var $8=HEAP32[((_n_phoneme_tab)>>2)];var $cmp4=((($conv3))|0)>=((($8))|0);if($cmp4){__label__=3;;}else{__label__=4;;}
$while_cond_backedge$$if_end6$7:do{if(__label__==4){var $11=$c;var $idxprom=((($11))&255);var $arrayidx=((_phoneme_tab+$idxprom*4)&4294967295);var $12=HEAP32[(($arrayidx)>>2)];var $type=(($12+11)&4294967295);var $13=HEAPU8[($type)];var $conv7=((($13))&255);var $cmp8=((($conv7))|0)==1;var $14=$c;var $idxprom10=((($14))&255);var $arrayidx11=((_phoneme_tab+$idxprom10*4)&4294967295);var $15=HEAP32[(($arrayidx11)>>2)];if($cmp8){__label__=5;;}else{__label__=7;;}
if(__label__==5){var $std_length=(($15+14)&4294967295);var $16=HEAPU8[($std_length)];var $conv12=((($16))&255);var $cmp13=((($conv12))|0)<4;if(!($cmp13)){__label__=3;break $while_cond_backedge$$if_end6$7;}
$unstress_mark=1;;}
else if(__label__==7){var $type18=(($15+11)&4294967295);var $17=HEAPU8[($type18)];var $conv19=((($17))&255);var $cmp20=((($conv19))|0)==2;if(!($cmp20)){__label__=3;break $while_cond_backedge$$if_end6$7;}
var $18=$c;var $idxprom22=((($18))&255);var $arrayidx23=((_phoneme_tab+$idxprom22*4)&4294967295);var $19=HEAP32[(($arrayidx23)>>2)];var $phflags=(($19+4)&4294967295);var $20=HEAP32[(($phflags)>>2)];var $and=($20)&2;var $cmp24=((($and))|0)==0;if($cmp24){__label__=9;;}else{__label__=11;;}
$land_lhs_true$$if_end27$14:do{if(__label__==9){var $21=$unstress_mark;var $cmp25=((($21))|0)==0;if(!($cmp25)){__label__=11;break $land_lhs_true$$if_end27$14;}
var $22=$tr_addr;var $word_stressed_count=(($22+8300)&4294967295);var $23=HEAP32[(($word_stressed_count)>>2)];var $inc=((($23)+1)&4294967295);HEAP32[(($word_stressed_count)>>2)]=$inc;;}}while(0);$unstress_mark=0;var $24=$tr_addr;var $word_vowel_count=(($24+8296)&4294967295);var $25=HEAP32[(($word_vowel_count)>>2)];var $inc28=((($25)+1)&4294967295);HEAP32[(($word_vowel_count)>>2)]=$inc28;;}}}while(0);var $9=$p;var $incdec_ptr=(($9+1)&4294967295);$p=$incdec_ptr;var $10=HEAPU8[($9)];$c=$10;var $conv=((($10))&255);var $cmp2=((($conv))|0)!=0;if($cmp2){__label__=2;continue $while_body$5;}else{__label__=12;break $while_body$$while_end$4;}}}}while(0);var $26=$string_addr;var $cmp31=((($26))|0)!=0;if(!($cmp31)){__label__=14;break $if_end34$$if_end$2;}
var $27=$string_addr;var $28=$ph_addr;var $call33=_strcat($27,$28);;}}while(0);;return;return;}
function __Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($tr,$p_start,$phonemes,$ph_size,$end_phonemes,$word_flags,$dict_flags){var __stackBase__=STACKTOP;STACKTOP+=416;_memset(__stackBase__,0,416);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $p_start_addr;var $phonemes_addr;var $ph_size_addr;var $end_phonemes_addr;var $word_flags_addr;var $dict_flags_addr;var $c;var $c2;var $c12;var $c123;var $wc=__stackBase__;var $wc_prev;var $wc_bytes;var $p2=__stackBase__+4;var $found;var $g;var $g1;var $n;var $letter=__stackBase__+8;var $any_alpha;var $ix;var $digit_count;var $p=__stackBase__+12;var $dict_flags0;var $match1=__stackBase__+16;var $match2=__stackBase__+32;var $ph_buf=__stackBase__+48;var $word_copy=__stackBase__+88;var $wordbuf=__stackBase__+248;var $ix14;var $string=__stackBase__+368;var $buf=__stackBase__+376;$tr_addr=$tr;$p_start_addr=$p_start;$phonemes_addr=$phonemes;$ph_size_addr=$ph_size;$end_phonemes_addr=$end_phonemes;$word_flags_addr=$word_flags;$dict_flags_addr=$dict_flags;HEAP32[(($wc)>>2)]=0;$any_alpha=0;$digit_count=0;$dict_flags0=0;var $0=$tr_addr;var $data_dictrules=(($0+1048)&4294967295);var $1=HEAP32[(($data_dictrules)>>2)];var $cmp=((($1))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){$retval=0;;}
else if(__label__==2){var $2=$dict_flags_addr;var $cmp1=((($2))|0)!=0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $3=$dict_flags_addr;var $arrayidx=(($3)&4294967295);var $4=HEAP32[(($arrayidx)>>2)];$dict_flags0=$4;;}
$ix=0;__lastLabel__=4;;$for_cond$8:while(1){var $5=__lastLabel__==5?$_pr:(0);var $cmp4=((($5))|0)<159;if(!($cmp4)){__label__=8;break $for_cond$8;}
var $6=$ix;var $7=$p_start_addr;var $arrayidx5=(($7+$6)&4294967295);var $8=HEAP8[($arrayidx5)];$c=$8;var $9=$c;var $10=$ix;var $inc=((($10)+1)&4294967295);$ix=$inc;var $arrayidx6=(($word_copy+$10)&4294967295);HEAP8[($arrayidx6)]=$9;var $11=$c;var $conv=((($11))&255);var $cmp7=((($conv))|0)==0;if($cmp7){__label__=8;break $for_cond$8;}
var $_pr=$ix;__lastLabel__=5;__label__=6;continue $for_cond$8;}
var $12=$ix;var $arrayidx10=(($word_copy+$12)&4294967295);HEAP8[($arrayidx10)]=0;var $13=HEAP32[((_option_phonemes)>>2)];var $cmp11=((($13))|0)==2;if($cmp11){__label__=9;;}else{__label__=17;;}
$land_lhs_true$$if_end31$13:do{if(__label__==9){var $14=$word_flags_addr;var $and=($14)&268435456;var $cmp12=((($and))|0)==0;if(!($cmp12)){__label__=17;break $land_lhs_true$$if_end31$13;}
$ix14=0;;while(1){var $15=$ix14;var $16=$p_start_addr;var $arrayidx16=(($16+$15)&4294967295);var $17=HEAPU8[($arrayidx16)];$c=$17;var $conv17=((($17))&255);var $cmp18=((($conv17))|0)!=32;if(!($cmp18)){__label__=14;break;}
var $18=$c;var $conv19=((($18))&255);var $cmp20=((($conv19))|0)!=0;if(!($cmp20)){__label__=14;break;}
var $19=$c;var $20=$ix14;var $arrayidx22=(($wordbuf+$20)&4294967295);HEAP8[($arrayidx22)]=$19;var $21=$ix14;var $inc23=((($21)+1)&4294967295);$ix14=$inc23;__label__=11;continue;}
var $22=$ix14;var $arrayidx25=(($wordbuf+$22)&4294967295);HEAP8[($arrayidx25)]=0;var $23=$word_flags_addr;var $and26=($23)&-2147483648;var $tobool=((($and26))|0)!=0;var $24=HEAP32[((_f_trans)>>2)];var $arraydecay=(($wordbuf)&4294967295);if($tobool){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $call=_fprintf($24,((__str10126)&4294967295),allocate([$arraydecay,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==16){var $call29=_fprintf($24,((__str11127)&4294967295),allocate([$arraydecay,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}}}while(0);var $25=$p_start_addr;HEAP32[(($p)>>2)]=$25;var $26=$tr_addr;var $word_vowel_count=(($26+8296)&4294967295);HEAP32[(($word_vowel_count)>>2)]=0;var $27=$tr_addr;var $word_stressed_count=(($27+8300)&4294967295);HEAP32[(($word_stressed_count)>>2)]=0;var $28=$end_phonemes_addr;var $cmp32=((($28))|0)!=0;if($cmp32){__label__=18;;}else{__label__=19;;}
if(__label__==18){var $29=$end_phonemes_addr;var $arrayidx34=(($29)&4294967295);HEAP8[($arrayidx34)]=0;;}
var $arrayidx57=(($string)&4294967295);var $arrayidx58=(($string+1)&4294967295);var $arraydecay60=(($string)&4294967295);var $arraydecay61=(($buf)&4294967295);var $arraydecay66=(($buf)&4294967295);var $arraydecay69=(($buf)&4294967295);var $phonemes282=(($match1+4)&4294967295);var $phonemes285=(($match1+4)&4294967295);var $points287=(($match1)&4294967295);var $phonemes295=(($match1+4)&4294967295);var $end_type306=(($match1+8)&4294967295);var $end_type313=(($match1+8)&4294967295);var $del_fwd=(($match1+12)&4294967295);var $del_fwd342=(($match1+12)&4294967295);var $phonemes344=(($match1+4)&4294967295);var $points=(($match2)&4294967295);var $points107=(($match2)&4294967295);var $points112=(($match2)&4294967295);var $points113=(($match1)&4294967295);var $30=$match1;var $31=$match2;var $points241=(($match1)&4294967295);var $arraydecay266=(($ph_buf)&4294967295);var $arrayidx267=(($ph_buf)&4294967295);var $arraydecay270=(($ph_buf)&4294967295);var $phonemes271=(($match1+4)&4294967295);var $points272=(($match1)&4294967295);var $points135=(($match1)&4294967295);var $arraydecay230=(($ph_buf)&4294967295);var $arraydecay232=(($ph_buf)&4294967295);var $phonemes233=(($match1+4)&4294967295);var $points234=(($match1)&4294967295);;$while_cond$28:while(1){var $32=HEAP32[(($p)>>2)];var $33=HEAPU8[($32)];$c=$33;var $conv36=((($33))&255);var $cmp37=((($conv36))|0)!=32;if(!($cmp37)){__label__=104;break $while_cond$28;}
var $34=$c;var $conv39=((($34))&255);var $cmp40=((($conv39))|0)!=0;if(!($cmp40)){__label__=104;break $while_cond$28;}
var $35=HEAP32[(($wc)>>2)];$wc_prev=$35;var $36=HEAP32[(($p)>>2)];var $call42=__Z7utf8_inPiPKc($wc,$36);$wc_bytes=$call42;var $37=HEAP32[(($wc)>>2)];var $call43=__Z7IsAlphaj($37);var $tobool44=((($call43))|0)!=0;if($tobool44){__label__=23;;}else{__label__=24;;}
if(__label__==23){var $38=$any_alpha;var $inc46=((($38)+1)&4294967295);$any_alpha=$inc46;;}
var $39=$c;var $idxprom=((($39))&255);var $40=$tr_addr;var $groups2_count=(($40+7756)&4294967295);var $arrayidx48=(($groups2_count+$idxprom)&4294967295);var $41=HEAPU8[($arrayidx48)];var $conv49=((($41))&255);$n=$conv49;var $42=HEAP32[(($wc)>>2)];var $call50=__Z7IsDigitj($42);var $tobool51=((($call50))|0)!=0;if($tobool51){__label__=25;;}else{__label__=30;;}
$land_lhs_true52$$if_else70$35:do{if(__label__==25){var $43=$tr_addr;var $langopts=(($43)&4294967295);var $tone_numbers=(($langopts+250)&4294967295);var $44=HEAP8[($tone_numbers)];var $conv53=(tempInt=(($44)),(tempInt>=128?tempInt-256:tempInt));var $cmp54=((($conv53))|0)==0;if($cmp54){__label__=27;;}else{__label__=26;;}
if(__label__==26){var $45=$any_alpha;var $tobool55=((($45))|0)!=0;if($tobool55){__label__=30;break $land_lhs_true52$$if_else70$35;}}
HEAP8[($arrayidx57)]=95;var $46=HEAP32[(($p)>>2)];var $47=$wc_bytes;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$46;$dest$=$arrayidx58;$stop$=$src$+$47;if(($dest$%4)==($src$%4)&&$47>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $48=$wc_bytes;var $add=((($48)+1)&4294967295);var $arrayidx59=(($string+$add)&4294967295);HEAP8[($arrayidx59)]=0;var $49=$tr_addr;var $call62=__Z6LookupP10TranslatorPKcPc($49,$arraydecay60,$arraydecay61);var $50=$digit_count;var $inc63=((($50)+1)&4294967295);$digit_count=$inc63;var $cmp64=((($inc63))>>>0)>=2;if($cmp64){__label__=28;;}else{__label__=29;;}
if(__label__==28){var $strlen=_strlen($arraydecay66);var $endptr=(($arraydecay66+$strlen)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__ZZ14TranslateRulesP10TranslatorPcS1_iS1_iPjE9str_pause)&4294967295);$dest$=$endptr;$stop$=$src$+2;if(($dest$%4)==($src$%4)&&2>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};$digit_count=0;;}
var $51=$tr_addr;var $52=$phonemes_addr;var $53=$ph_size_addr;__Z14AppendPhonemesP10TranslatorPciPKc($51,$52,$53,$arraydecay69);var $54=$wc_bytes;var $55=HEAP32[(($p)>>2)];var $add_ptr=(($55+$54)&4294967295);HEAP32[(($p)>>2)]=$add_ptr;__label__=20;continue $while_cond$28;}}while(0);$digit_count=0;$found=0;var $56=HEAP32[(($wc)>>2)];var $57=$tr_addr;var $letter_bits_offset=(($57+964)&4294967295);var $58=HEAP32[(($letter_bits_offset)>>2)];var $sub=((($56)-($58))&4294967295);$ix=$sub;var $cmp71=((($sub))|0)>=0;if($cmp71){__label__=31;;}else{__label__=34;;}
$land_lhs_true72$$if_end81$44:do{if(__label__==31){var $59=$ix;var $cmp73=((($59))|0)<128;if(!($cmp73)){__label__=34;break $land_lhs_true72$$if_end81$44;}
var $60=$ix;var $61=$tr_addr;var $groups3=(($61+6280)&4294967295);var $arrayidx75=(($groups3+$60*4)&4294967295);var $62=HEAP32[(($arrayidx75)>>2)];var $cmp76=((($62))|0)!=0;if(!($cmp76)){__label__=34;break $land_lhs_true72$$if_end81$44;}
var $63=$tr_addr;var $64=$p_start_addr;var $65=$wc_bytes;var $66=$ix;var $67=$tr_addr;var $groups378=(($67+6280)&4294967295);var $arrayidx79=(($groups378+$66*4)&4294967295);var $68=HEAP32[(($arrayidx79)>>2)];var $69=$word_flags_addr;var $70=$dict_flags0;__ZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordii($63,$p,$64,$65,$68,$match1,$69,$70);$found=1;__label__=85;break $land_lhs_true72$$if_end81$44;}}while(0);$if_end281$$if_end81$48:do{if(__label__==34){var $_pr3=$found;var $tobool82=((($_pr3))|0)!=0;if($tobool82){__label__=85;break $if_end281$$if_end81$48;}
var $71=$n;var $cmp84=((($71))|0)>0;if($cmp84){__label__=36;;}else{__label__=43;;}
$if_then85$$if_end121$51:do{if(__label__==36){var $72=HEAP32[(($p)>>2)];var $arrayidx86=(($72+1)&4294967295);var $73=HEAP8[($arrayidx86)];$c2=$73;var $74=$c;var $conv87=((($74))&255);var $75=$c2;var $conv88=((($75))&255);var $shl=((($conv88)*256)&4294967295);var $add89=((($shl)+($conv87))&4294967295);$c12=$add89;var $76=$c12;var $77=HEAP32[(($p)>>2)];var $arrayidx90=(($77+2)&4294967295);var $78=HEAP8[($arrayidx90)];var $conv91=(tempInt=(($78)),(tempInt>=128?tempInt-256:tempInt));var $shl92=((($conv91)*65536)&4294967295);var $add93=((($shl92)+($76))&4294967295);$c123=$add93;var $79=$c;var $idxprom94=((($79))&255);var $80=$tr_addr;var $groups2_start=(($80+8012)&4294967295);var $arrayidx95=(($groups2_start+$idxprom94)&4294967295);var $81=HEAPU8[($arrayidx95)];var $conv96=((($81))&255);$g1=$conv96;var $82=$g1;$g=$82;var $83=$g;var $84=$g1;var $85=$n;var $add989=((($85)+($84))&4294967295);var $cmp9910=((($83))|0)<((($add989))|0);if(!($cmp9910)){__label__=43;break $if_then85$$if_end121$51;}
$for_body100$53:while(1){var $86=$g;var $87=$tr_addr;var $groups2_name=(($87+7272)&4294967295);var $arrayidx101=(($groups2_name+$86*4)&4294967295);var $88=HEAP32[(($arrayidx101)>>2)];var $89=$c12;var $cmp102=((($88))|0)==((($89))|0);if($cmp102){__label__=38;;}else{__label__=42;;}
$if_then103$$for_inc118$55:do{if(__label__==38){$found=1;var $90=HEAP32[(($p)>>2)];HEAP32[(($p2)>>2)]=$90;var $91=$tr_addr;var $92=$p_start_addr;var $93=$g;var $94=$tr_addr;var $groups2=(($94+6792)&4294967295);var $arrayidx104=(($groups2+$93*4)&4294967295);var $95=HEAP32[(($arrayidx104)>>2)];var $96=$word_flags_addr;var $97=$dict_flags0;__ZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordii($91,$p2,$92,2,$95,$match2,$96,$97);var $98=HEAP32[(($points)>>2)];var $cmp105=((($98))|0)>0;if($cmp105){__label__=39;;}else{__label__=40;;}
if(__label__==39){var $99=HEAP32[(($points107)>>2)];var $add108=((($99)+35)&4294967295);HEAP32[(($points107)>>2)]=$add108;;}
var $100=$tr_addr;var $101=$p_start_addr;var $102=$c;var $idxprom110=((($102))&255);var $103=$tr_addr;var $groups1=(($103+5256)&4294967295);var $arrayidx111=(($groups1+$idxprom110*4)&4294967295);var $104=HEAP32[(($arrayidx111)>>2)];var $105=$word_flags_addr;var $106=$dict_flags0;__ZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordii($100,$p,$101,1,$104,$match1,$105,$106);var $107=HEAP32[(($points112)>>2)];var $108=HEAP32[(($points113)>>2)];var $cmp114=((($107))|0)>=((($108))|0);if(!($cmp114)){__label__=42;break $if_then103$$for_inc118$55;}
var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$31;$dest$=$30;$stop$=$src$+16;if(($dest$%4)==($src$%4)&&16>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $109=HEAP32[(($p2)>>2)];HEAP32[(($p)>>2)]=$109;;}}while(0);var $110=$g;var $inc119=((($110)+1)&4294967295);$g=$inc119;var $111=$g;var $112=$g1;var $113=$n;var $add98=((($113)+($112))&4294967295);var $cmp99=((($111))|0)<((($add98))|0);if($cmp99){__label__=37;continue $for_body100$53;}else{__label__=43;break $if_then85$$if_end121$51;}}}}while(0);var $_pr5_pr=$found;var $tobool122=((($_pr5_pr))|0)!=0;if($tobool122){__label__=85;break $if_end281$$if_end81$48;}
var $114=$c;var $idxprom124=((($114))&255);var $115=$tr_addr;var $groups1125=(($115+5256)&4294967295);var $arrayidx126=(($groups1125+$idxprom124*4)&4294967295);var $116=HEAP32[(($arrayidx126)>>2)];var $cmp127=((($116))|0)!=0;var $117=$tr_addr;var $118=$p_start_addr;if($cmp127){__label__=45;;}else{__label__=46;;}
$if_then128$$if_else132$64:do{if(__label__==45){var $119=$c;var $idxprom129=((($119))&255);var $120=$tr_addr;var $groups1130=(($120+5256)&4294967295);var $arrayidx131=(($groups1130+$idxprom129*4)&4294967295);var $121=HEAP32[(($arrayidx131)>>2)];var $122=$word_flags_addr;var $123=$dict_flags0;__ZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordii($117,$p,$118,1,$121,$match1,$122,$123);__label__=74;break $if_then128$$if_else132$64;}
else if(__label__==46){var $124=$tr_addr;var $groups1133=(($124+5256)&4294967295);var $arrayidx134=(($groups1133)&4294967295);var $125=HEAP32[(($arrayidx134)>>2)];var $126=$word_flags_addr;var $127=$dict_flags0;__ZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordii($117,$p,$118,0,$125,$match1,$126,$127);var $128=HEAP32[(($points135)>>2)];var $cmp136=((($128))|0)==0;if(!($cmp136)){__label__=84;break $if_then128$$if_else132$64;}
var $129=HEAP32[((_option_sayas)>>2)];var $and138=($129)&16;var $cmp139=((($and138))|0)==0;if(!($cmp139)){__label__=74;break $if_then128$$if_else132$64;}
var $130=HEAP32[(($p)>>2)];var $add_ptr141=(($130+-1)&4294967295);var $call142=__Z7utf8_inPiPKc($letter,$add_ptr141);var $sub143=((($call142)-1)&4294967295);$n=$sub143;var $131=$tr_addr;var $letter_bits_offset144=(($131+964)&4294967295);var $132=HEAP32[(($letter_bits_offset144)>>2)];var $cmp145=((($132))|0)>0;if($cmp145){__label__=49;;}else{__label__=52;;}
$if_then146$$if_end155thread_pre_split$69:do{if(__label__==49){var $133=HEAP32[(($letter)>>2)];var $cmp147=((($133))|0)<=577;if($cmp147){__lastLabel__=49;;}else{__lastLabel__=49;__label__=53;break $if_then146$$if_end155thread_pre_split$69;}
var $134=HEAP32[(($letter)>>2)];var $call149=_iswalpha($134);var $tobool150=((($call149))|0)!=0;if($tobool150){__label__=51;break $while_cond$28;}else{__label__=52;break $if_then146$$if_end155thread_pre_split$69;}}}while(0);if(__label__==52){var $_pr7=HEAP32[(($letter)>>2)];__lastLabel__=52;;}
var $138=__lastLabel__==52?$_pr7:($133);var $cmp156=((($138))|0)==57384;if($cmp156){__label__=54;;}else{__label__=56;;}
$if_then157$$if_end166$75:do{if(__label__==54){var $139=HEAP32[((_pre_pause)>>2)];var $140=$tr_addr;var $langopts158=(($140)&4294967295);var $param2=(($langopts158+100)&4294967295);var $arrayidx159=(($param2+64)&4294967295);var $141=HEAP32[(($arrayidx159)>>2)];var $cmp160=((($139))|0)<((($141))|0);if(!($cmp160)){__label__=56;break $if_then157$$if_end166$75;}
var $142=$tr_addr;var $langopts162=(($142)&4294967295);var $param2163=(($langopts162+100)&4294967295);var $arrayidx164=(($param2163+64)&4294967295);var $143=HEAP32[(($arrayidx164)>>2)];HEAP32[((_pre_pause)>>2)]=$143;;}}while(0);var $144=HEAP32[(($letter)>>2)];var $call167=__Z9IsBracketi($144);var $tobool168=((($call167))|0)!=0;if($tobool168){__label__=57;;}else{__label__=59;;}
$if_then169$$if_end178$79:do{if(__label__==57){var $145=HEAP32[((_pre_pause)>>2)];var $146=$tr_addr;var $langopts170=(($146)&4294967295);var $param=(($langopts170+24)&4294967295);var $arrayidx171=(($param+64)&4294967295);var $147=HEAP32[(($arrayidx171)>>2)];var $cmp172=((($145))|0)<((($147))|0);if(!($cmp172)){__label__=59;break $if_then169$$if_end178$79;}
var $148=$tr_addr;var $langopts174=(($148)&4294967295);var $param175=(($langopts174+24)&4294967295);var $arrayidx176=(($param175+64)&4294967295);var $149=HEAP32[(($arrayidx176)>>2)];HEAP32[((_pre_pause)>>2)]=$149;;}}while(0);var $150=HEAP32[(($letter)>>2)];var $cmp179=((($150))|0)>=192;var $151=HEAP32[(($letter)>>2)];var $cmp181=((($151))|0)<606;var $or_cond=($cmp179)&($cmp181);if($or_cond){__label__=60;;}else{__label__=71;;}
$land_lhs_true182$$if_else223$83:do{if(__label__==60){var $152=HEAP32[(($letter)>>2)];var $sub183=((($152)-192)&4294967295);var $arrayidx184=((__ZL13remove_accent+$sub183)&4294967295);var $153=HEAPU8[($arrayidx184)];var $conv185=((($153))&255);$ix=$conv185;var $cmp186=((($conv185))|0)!=0;if(!($cmp186)){__label__=71;break $land_lhs_true182$$if_else223$83;}
var $154=HEAP32[(($p)>>2)];var $arrayidx188=(($154+-2)&4294967295);var $155=HEAP8[($arrayidx188)];var $conv189=(tempInt=(($155)),(tempInt>=128?tempInt-256:tempInt));var $cmp190=((($conv189))|0)!=32;if($cmp190){__label__=63;;}else{__label__=62;;}
if(__label__==62){var $156=$n;var $157=HEAP32[(($p)>>2)];var $arrayidx192=(($157+$156)&4294967295);var $158=HEAP8[($arrayidx192)];var $conv193=(tempInt=(($158)),(tempInt>=128?tempInt-256:tempInt));var $cmp194=((($conv193))|0)!=32;if(!($cmp194)){__label__=74;break $if_then128$$if_else132$64;}}
var $159=HEAP32[(($p)>>2)];var $add_ptr196=(($159+-1)&4294967295);HEAP32[(($p2)>>2)]=$add_ptr196;var $160=$ix;var $conv197=((($160))&255);var $161=HEAP32[(($p)>>2)];var $arrayidx198=(($161+-1)&4294967295);HEAP8[($arrayidx198)]=$conv197;var $162=$n;var $163=HEAP32[(($p)>>2)];var $arrayidx20011=(($163+$162)&4294967295);var $164=HEAP8[($arrayidx20011)];var $165=HEAP32[(($p)>>2)];var $arrayidx20112=(($165)&4294967295);HEAP8[($arrayidx20112)]=$164;var $conv20213=(tempInt=(($164)),(tempInt>=128?tempInt-256:tempInt));var $cmp20314=((($conv20213))|0)!=32;if($cmp20314){__label__=64;;}else{__label__=65;;}
$while_body204$$while_cond205_loopexit$89:do{if(__label__==64){while(1){var $166=HEAP32[(($p)>>2)];var $incdec_ptr=(($166+1)&4294967295);HEAP32[(($p)>>2)]=$incdec_ptr;var $167=$n;var $168=HEAP32[(($p)>>2)];var $arrayidx200=(($168+$167)&4294967295);var $169=HEAP8[($arrayidx200)];var $170=HEAP32[(($p)>>2)];var $arrayidx201=(($170)&4294967295);HEAP8[($arrayidx201)]=$169;var $conv202=(tempInt=(($169)),(tempInt>=128?tempInt-256:tempInt));var $cmp203=((($conv202))|0)!=32;if($cmp203){__label__=64;continue;}else{__label__=65;break $while_body204$$while_cond205_loopexit$89;}}}}while(0);var $171=$n;var $dec15=((($171)-1)&4294967295);$n=$dec15;var $cmp20616=((($171))|0)>0;if($cmp20616){__label__=66;;}else{__label__=67;;}
$while_body207$$while_end209$93:do{if(__label__==66){while(1){var $172=HEAP32[(($p)>>2)];var $incdec_ptr208=(($172+1)&4294967295);HEAP32[(($p)>>2)]=$incdec_ptr208;HEAP8[($172)]=32;var $173=$n;var $dec=((($173)-1)&4294967295);$n=$dec;var $cmp206=((($173))|0)>0;if($cmp206){__label__=66;continue;}else{__label__=67;break $while_body207$$while_end209$93;}}}}while(0);var $174=$tr_addr;var $langopts210=(($174)&4294967295);var $param211=(($langopts210+24)&4294967295);var $arrayidx212=(($param211+4)&4294967295);var $175=HEAP32[(($arrayidx212)>>2)];var $tobool213=((($175))|0)!=0;if($tobool213){__label__=68;;}else{__label__=70;;}
$land_lhs_true214$$if_end218$97:do{if(__label__==68){var $176=HEAP32[(($letter)>>2)];var $call215=__Z11lookupwcharPKti(((__ZL13diereses_list)&4294967295),$176);var $cmp216=((($call215))|0)>0;if(!($cmp216)){__label__=70;break $land_lhs_true214$$if_end218$97;}
var $177=HEAP32[(($p2)>>2)];HEAP32[(($p)>>2)]=$177;__label__=20;continue $while_cond$28;}}while(0);var $178=$phonemes_addr;var $arrayidx219=(($178)&4294967295);HEAP8[($arrayidx219)]=0;var $179=$p_start_addr;HEAP32[(($p)>>2)]=$179;var $180=$tr_addr;var $word_vowel_count220=(($180+8296)&4294967295);HEAP32[(($word_vowel_count220)>>2)]=0;var $181=$tr_addr;var $word_stressed_count221=(($181+8300)&4294967295);HEAP32[(($word_stressed_count221)>>2)]=0;__label__=20;continue $while_cond$28;}}while(0);var $182=HEAP32[(($letter)>>2)];var $cmp224=((($182))|0)>=12800;var $183=HEAP32[(($letter)>>2)];var $cmp226=((($183))|0)<42752;var $or_cond1=($cmp224)&($cmp226);if(!($or_cond1)){__label__=74;break $if_then128$$if_else132$64;}
var $184=$end_phonemes_addr;var $cmp228=((($184))|0)!=0;if(!($cmp228)){__label__=74;break $if_then128$$if_else132$64;}
var $185=$tr_addr;var $call231=__Z6LookupP10TranslatorPKcPc($185,((__str9306)&4294967295),$arraydecay230);HEAP32[(($phonemes233)>>2)]=$arraydecay232;HEAP32[(($points234)>>2)]=1;var $186=$wc_bytes;var $sub235=((($186)-1)&4294967295);var $187=HEAP32[(($p)>>2)];var $add_ptr236=(($187+$sub235)&4294967295);HEAP32[(($p)>>2)]=$add_ptr236;__label__=74;break $if_then128$$if_else132$64;}}while(0);$if_end240$$if_else278$104:do{if(__label__==74){var $_pr17=HEAP32[(($points241)>>2)];var $cmp242=((($_pr17))|0)==0;if(!($cmp242)){__label__=84;break $if_end240$$if_else278$104;}
var $188=HEAP32[(($wc)>>2)];var $cmp244=((($188))|0)>=768;var $189=HEAP32[(($wc)>>2)];var $cmp246=((($189))|0)<=879;var $or_cond2=($cmp244)&($cmp246);if($or_cond2){__label__=83;;}else{__label__=76;;}
$if_end275$$if_else248$107:do{if(__label__==76){var $190=HEAP32[(($wc)>>2)];var $call249=__Z7IsAlphaj($190);var $tobool250=((($call249))|0)!=0;if($tobool250){__label__=77;;}else{__label__=81;;}
if(__label__==77){var $191=$any_alpha;var $cmp252=((($191))|0)>1;if($cmp252){__label__=79;break $while_cond$28;}
var $192=$wc_bytes;var $sub254=((($192)-1)&4294967295);var $193=HEAP32[(($p)>>2)];var $arrayidx255=(($193+$sub254)&4294967295);var $194=HEAP8[($arrayidx255)];var $conv256=(tempInt=(($194)),(tempInt>=128?tempInt-256:tempInt));var $cmp257=((($conv256))|0)>32;if($cmp257){__label__=79;break $while_cond$28;}}
else if(__label__==81){var $199=$tr_addr;var $200=HEAP32[(($wc)>>2)];__Z12LookupLetterP10TranslatorjiPci($199,$200,-1,$arraydecay266,0);var $201=HEAP8[($arrayidx267)];var $tobool268=(tempInt=(($201)),(tempInt>=128?tempInt-256:tempInt))!=0;if(!($tobool268)){__label__=83;break $if_end275$$if_else248$107;}
HEAP32[(($phonemes271)>>2)]=$arraydecay270;HEAP32[(($points272)>>2)]=1;;}}}while(0);var $202=$wc_bytes;var $sub276=((($202)-1)&4294967295);var $203=HEAP32[(($p)>>2)];var $add_ptr277=(($203+$sub276)&4294967295);HEAP32[(($p)>>2)]=$add_ptr277;__label__=85;break $if_end281$$if_end81$48;}}while(0);var $204=$tr_addr;var $phonemes_repeat_count=(($204+652)&4294967295);HEAP32[(($phonemes_repeat_count)>>2)]=0;;}}while(0);var $205=HEAP32[(($phonemes282)>>2)];var $cmp283=((($205))|0)==0;if($cmp283){__label__=86;;}else{__label__=87;;}
if(__label__==86){HEAP32[(($phonemes285)>>2)]=((__str13643)&4294967295);;}
var $206=HEAP32[(($points287)>>2)];var $cmp288=((($206))|0)>0;if(!($cmp288)){__label__=20;continue $while_cond$28;}
var $207=$word_flags_addr;var $and290=($207)&-2147483648;var $tobool291=((($and290))|0)!=0;if($tobool291){__label__=89;break $while_cond$28;}
var $209=HEAP32[(($phonemes295)>>2)];var $arrayidx296=(($209)&4294967295);var $210=HEAP8[($arrayidx296)];var $conv297=(tempInt=(($210)),(tempInt>=128?tempInt-256:tempInt));var $cmp298=((($conv297))|0)==21;if($cmp298){__label__=91;;}else{__label__=93;;}
if(__label__==91){var $211=$word_flags_addr;var $and300=($211)&4096;var $cmp301=((($and300))|0)==0;if($cmp301){__label__=92;break $while_cond$28;}}
var $214=HEAP32[(($end_type306)>>2)];var $and307=($214)&-32769;HEAP32[(($end_type306)>>2)]=$and307;var $cmp309=((($and307))|0)!=0;if($cmp309){__label__=94;;}else{__label__=101;;}
$land_lhs_true310$$if_end339$125:do{if(__label__==94){var $215=$end_phonemes_addr;var $cmp311=((($215))|0)!=0;if(!($cmp311)){__label__=101;break $land_lhs_true310$$if_end339$125;}
var $216=HEAP32[(($end_type313)>>2)];var $and314=($216)&1024;var $tobool315=((($and314))|0)!=0;if(!($tobool315)){__label__=97;break $while_cond$28;}
var $217=$word_flags_addr;var $and317=($217)&536870912;var $tobool318=((($and317))|0)!=0;if(!($tobool318)){__label__=97;break $while_cond$28;}}}while(0);var $227=HEAP32[(($del_fwd)>>2)];var $cmp340=((($227))|0)!=0;if($cmp340){__label__=102;;}else{__label__=103;;}
if(__label__==102){var $228=HEAP32[(($del_fwd342)>>2)];HEAP8[($228)]=69;;}
var $229=$tr_addr;var $230=$phonemes_addr;var $231=$ph_size_addr;var $232=HEAP32[(($phonemes344)>>2)];__Z14AppendPhonemesP10TranslatorPciPKc($229,$230,$231,$232);__label__=20;continue $while_cond$28;}
$while_end346$$if_then292$$if_then302$$if_else320$$if_then258$$if_then151$133:do{if(__label__==89){var $end_type=(($match1+8)&4294967295);var $208=HEAP32[(($end_type)>>2)];var $or293=($208)|1;$retval=$or293;__label__=105;break $if_then$$if_end$2;}
else if(__label__==92){var $212=$phonemes_addr;var $phonemes303=(($match1+4)&4294967295);var $213=HEAP32[(($phonemes303)>>2)];var $call304=_strcpy($212,$213);$retval=0;__label__=105;break $if_then$$if_end$2;}
else if(__label__==97){var $end_type321=(($match1+8)&4294967295);var $218=HEAP32[(($end_type321)>>2)];var $and322=($218)&1024;var $tobool323=((($and322))|0)!=0;if($tobool323){__label__=98;;}else{__label__=100;;}
$land_lhs_true324$$if_end331$137:do{if(__label__==98){var $end_type325=(($match1+8)&4294967295);var $219=HEAP32[(($end_type325)>>2)];var $and326=($219)&127;var $cmp327=((($and326))|0)==0;if(!($cmp327)){__label__=100;break $land_lhs_true324$$if_end331$137;}
var $220=HEAP32[(($p)>>2)];var $221=$p_start_addr;var $sub_ptr_lhs_cast=($220);var $sub_ptr_rhs_cast=($221);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);var $end_type329=(($match1+8)&4294967295);var $222=HEAP32[(($end_type329)>>2)];var $or330=($sub_ptr_sub)|($222);HEAP32[(($end_type329)>>2)]=$or330;;}}while(0);var $223=$end_phonemes_addr;var $phonemes332=(($match1+4)&4294967295);var $224=HEAP32[(($phonemes332)>>2)];var $call333=_strcpy($223,$224);var $225=$p_start_addr;var $arraydecay334=(($word_copy)&4294967295);var $arraydecay335=(($word_copy)&4294967295);var $call336=_strlen($arraydecay335);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay334;$dest$=$225;$stop$=$src$+$call336;if(($dest$%4)==($src$%4)&&$call336>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $end_type337=(($match1+8)&4294967295);var $226=HEAP32[(($end_type337)>>2)];$retval=$226;__label__=105;break $if_then$$if_end$2;}
else if(__label__==79){var $195=$phonemes_addr;var $arrayidx259=(($195)&4294967295);HEAP8[($arrayidx259)]=0;var $196=$dict_flags_addr;var $cmp260=((($196))|0)!=0;if(!($cmp260)){__label__=104;break $while_end346$$if_then292$$if_then302$$if_else320$$if_then258$$if_then151$133;}
var $197=$dict_flags_addr;var $arrayidx262=(($197)&4294967295);var $198=HEAP32[(($arrayidx262)>>2)];var $or=($198)|65536;HEAP32[(($arrayidx262)>>2)]=$or;;}
else if(__label__==51){var $135=$phonemes_addr;var $136=$tr_addr;var $langopts152=(($136)&4294967295);var $ascii_language=(($langopts152+268)&4294967295);var $137=HEAP32[(($ascii_language)>>2)];var $call153=_sprintf($135,((__str70722)&4294967295),allocate([21,0,0,0,$137,0,0,0],["i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));$retval=0;__label__=105;break $if_then$$if_end$2;}}while(0);var $233=$tr_addr;var $234=$phonemes_addr;var $235=$dict_flags0;__Z21ApplySpecialAttributeP10TranslatorPci($233,$234,$235);var $236=$p_start_addr;var $arraydecay347=(($word_copy)&4294967295);var $arraydecay348=(($word_copy)&4294967295);var $call349=_strlen($arraydecay348);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay347;$dest$=$236;$stop$=$src$+$call349;if(($dest$%4)==($src$%4)&&$call349>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};$retval=0;;}}while(0);var $237=$retval;STACKTOP=__stackBase__;return $237;return null;}
function __Z6LookupP10TranslatorPKcPc($tr,$word,$ph_out){var __stackBase__=STACKTOP;STACKTOP+=12;_memset(__stackBase__,0,12);var __label__;var $tr_addr;var $word_addr;var $ph_out_addr;var $flags=__stackBase__;var $word1=__stackBase__+8;$tr_addr=$tr;$word_addr=$word;$ph_out_addr=$ph_out;var $arrayidx=(($flags+4)&4294967295);HEAP32[(($arrayidx)>>2)]=0;var $arrayidx1=(($flags)&4294967295);HEAP32[(($arrayidx1)>>2)]=0;var $0=$word_addr;HEAP32[(($word1)>>2)]=$0;var $1=$tr_addr;var $2=$ph_out_addr;var $arraydecay=(($flags)&4294967295);var $call=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($1,$word1,$2,$arraydecay,0,0);STACKTOP=__stackBase__;return $call;return null;}
function __ZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordii($tr,$word,$word_start,$group_length,$rule,$match_out,$word_flags,$dict_flags){var __stackBase__=STACKTOP;STACKTOP+=264;_memset(__stackBase__,0,264);var __label__;var __lastLabel__=null;var $tr_addr;var $word_addr;var $word_start_addr;var $group_length_addr;var $rule_addr;var $match_out_addr;var $word_flags_addr;var $dict_flags_addr;var $rb;var $letter;var $letter_w=__stackBase__;var $letter_xbytes;var $last_letter;var $pre_ptr;var $post_ptr;var $rule_start;var $p;var $ix;var $match_type;var $failed;var $unpron_ignore;var $consumed;var $syllable_count;var $vowel;var $letter_group;var $distance_right;var $distance_left;var $lg_pts;var $n_bytes;var $add_points;var $command;var $check_atstart;var $match=__stackBase__+4;var $total_consumed;var $condition_num;var $common_phonemes;var $group_chars;var $word_buf=__stackBase__+20;var $p222;var $vowel_count;var $p252;var $p269;var $p2;var $rule_w=__stackBase__+180;var $p419;var $pts;var $decoded_phonemes=__stackBase__+184;$tr_addr=$tr;$word_addr=$word;$word_start_addr=$word_start;$group_length_addr=$group_length;$rule_addr=$rule;$match_out_addr=$match_out;$word_flags_addr=$word_flags;$dict_flags_addr=$dict_flags;var $0=$word_addr;var $1=HEAP32[(($0)>>2)];$group_chars=$1;var $2=$rule_addr;var $cmp=((($2))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $3=$match_out_addr;var $points=(($3)&4294967295);HEAP32[(($points)>>2)]=0;var $4=$word_addr;var $5=HEAP32[(($4)>>2)];var $incdec_ptr=(($5+1)&4294967295);HEAP32[(($4)>>2)]=$incdec_ptr;;}
else if(__label__==2){$total_consumed=0;$common_phonemes=0;$match_type=0;HEAP32[((((__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best)&4294967295))>>2)]=0;HEAP32[((((__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best+4)&4294967295))>>2)]=((__str13643)&4294967295);HEAP32[((((__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best+8)&4294967295))>>2)]=0;HEAP32[((((__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best+12)&4294967295))>>2)]=0;var $6=$rule_addr;var $7=HEAP8[($6)];var $conv22=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $cmp123=((($conv22))|0)!=7;if($cmp123){__label__=3;;}else{__label__=198;;}
$while_body_lr_ph$$while_end549$5:do{if(__label__==3){var $points2=(($match)&4294967295);var $end_type=(($match+8)&4294967295);var $del_fwd=(($match+12)&4294967295);var $points518=(($match)&4294967295);var $8=$match;var $points524=(($match)&4294967295);var $points530=(($match)&4294967295);var $phonemes535=(($match+4)&4294967295);var $arraydecay536=(($decoded_phonemes)&4294967295);var $arraydecay538=(($decoded_phonemes)&4294967295);var $points515=(($match)&4294967295);var $phonemes=(($match+4)&4294967295);var $phonemes13=(($match+4)&4294967295);var $phonemes23=(($match+4)&4294967295);var $phonemes29=(($match+4)&4294967295);var $phonemes32=(($match+4)&4294967295);var $phonemes43=(($match+4)&4294967295);var $points66=(($match)&4294967295);var $points499=(($match)&4294967295);var $end_type171=(($match+8)&4294967295);var $arraydecay=(($word_buf)&4294967295);var $arrayidx195=(($word_buf+1)&4294967295);var $del_fwd291=(($match+12)&4294967295);var $end_type307=(($match+8)&4294967295);;$while_body$7:while(1){var $11=$word_flags_addr;var $and=($11)&-2147483648;$unpron_ignore=$and;$match_type=0;$consumed=0;$letter=0;$distance_right=-6;$distance_left=-2;$check_atstart=0;HEAP32[(($points2)>>2)]=1;HEAP32[(($end_type)>>2)]=0;HEAP32[(($del_fwd)>>2)]=0;var $12=$word_addr;var $13=HEAP32[(($12)>>2)];$pre_ptr=$13;var $14=$word_addr;var $15=HEAP32[(($14)>>2)];var $16=$group_length_addr;var $add_ptr=(($15+$16)&4294967295);$post_ptr=$add_ptr;var $17=$rule_addr;$rule_start=$17;$failed=0;var $18=$failed;var $tobool20=((($18))|0)!=0;var $lnot21=($tobool20)^1;if($lnot21){__lastLabel__=5;__label__=6;;}else{__lastLabel__=5;__label__=183;;}
$while_body4$$while_end502$9:do{if(__label__==6){$while_body4$10:while(1){var $19=$rule_addr;var $incdec_ptr5=(($19+1)&4294967295);$rule_addr=$incdec_ptr5;var $20=HEAP8[($19)];$rb=$20;var $21=$rb;var $conv6=((($21))&255);var $cmp7=((($conv6))|0)<=9;if($cmp7){__label__=7;;}else{__label__=33;;}
$if_then8$$if_end70$12:do{if(__label__==7){var $22=$rb;var $conv9=((($22))&255);if($conv9==0){__label__=8;;}
else if($conv9==8){__label__=18;;}
else if($conv9==1){__label__=19;;}
else if($conv9==2){__label__=21;;}
else if($conv9==3){__label__=22;;}
else if($conv9==4){__label__=23;;}
else if($conv9==5){__label__=24;;}
else if($conv9==9){__label__=32;;}
else{__label__=30;break $if_then8$$if_end70$12;}
if(__label__==8){var $23=$common_phonemes;var $cmp10=((($23))|0)!=0;if($cmp10){__label__=9;;}else{__label__=16;;}
$if_then11$$if_else$16:do{if(__label__==9){var $24=$common_phonemes;HEAP32[(($phonemes)>>2)]=$24;;while(1){var $25=HEAP32[(($phonemes13)>>2)];var $incdec_ptr14=(($25+1)&4294967295);HEAP32[(($phonemes13)>>2)]=$incdec_ptr14;var $26=HEAPU8[($25)];$rb=$26;var $conv15=((($26))&255);var $cmp16=((($conv15))|0)!=0;if(!($cmp16)){__label__=17;break $if_then11$$if_else$16;}
var $27=$rb;var $conv17=((($27))&255);var $cmp18=((($conv17))|0)!=3;if(!($cmp18)){__label__=17;break $if_then11$$if_else$16;}
var $28=$rb;var $conv20=((($28))&255);var $cmp21=((($conv20))|0)==5;if($cmp21){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $29=HEAP32[(($phonemes23)>>2)];var $incdec_ptr24=(($29+1)&4294967295);HEAP32[(($phonemes23)>>2)]=$incdec_ptr24;;}
var $30=$rb;var $conv26=((($30))&255);var $cmp27=((($conv26))|0)==9;if(!($cmp27)){__label__=10;continue;}
var $31=HEAP32[(($phonemes29)>>2)];var $add_ptr30=(($31+2)&4294967295);HEAP32[(($phonemes29)>>2)]=$add_ptr30;__label__=10;continue;}}
else if(__label__==16){HEAP32[(($phonemes32)>>2)]=((__str13643)&4294967295);;}}while(0);var $32=$rule_addr;var $incdec_ptr34=(($32+-1)&4294967295);$rule_addr=$incdec_ptr34;$failed=2;;}
else if(__label__==18){$check_atstart=1;$unpron_ignore=0;$match_type=1;;}
else if(__label__==19){$match_type=1;var $33=$word_flags_addr;var $and37=($33)&-2147483648;var $tobool38=((($and37))|0)!=0;if(!($tobool38)){__label__=30;break $if_then8$$if_end70$12;}
$failed=1;;}
else if(__label__==21){$match_type=2;;}
else if(__label__==22){var $34=$rule_addr;HEAP32[(($phonemes43)>>2)]=$34;$failed=2;;}
else if(__label__==23){var $35=$rule_addr;$common_phonemes=$35;;}
else if(__label__==24){var $36=$rule_addr;var $incdec_ptr46=(($36+1)&4294967295);$rule_addr=$incdec_ptr46;var $37=HEAP8[($36)];$condition_num=$37;var $38=$condition_num;var $conv47=((($38))&255);var $cmp48=((($conv47))|0)>=32;var $39=$tr_addr;var $dict_condition=(($39+692)&4294967295);var $40=HEAP32[(($dict_condition)>>2)];var $41=$condition_num;var $conv50=((($41))&255);if($cmp48){__label__=25;;}else{__label__=27;;}
$if_then49$$if_else55$35:do{if(__label__==25){var $sub=((($conv50)-32)&4294967295);var $shl=1<<($sub);var $and51=($shl)&($40);var $cmp52=((($and51))|0)!=0;if(!($cmp52)){__label__=29;break $if_then49$$if_else55$35;}
$failed=1;__label__=30;break $if_then8$$if_end70$12;}
else if(__label__==27){var $shl58=1<<($conv50);var $and59=($shl58)&($40);var $cmp60=((($and59))|0)==0;if(!($cmp60)){__label__=29;break $if_then49$$if_else55$35;}
$failed=1;__label__=30;break $if_then8$$if_end70$12;}}while(0);var $_pr=$failed;var $tobool64=((($_pr))|0)!=0;if($tobool64){__label__=30;break $if_then8$$if_end70$12;}
var $43=HEAP32[(($points66)>>2)];var $inc=((($43)+1)&4294967295);HEAP32[(($points66)>>2)]=$inc;;}
else if(__label__==32){var $44=$rule_addr;var $add_ptr69=(($44+2)&4294967295);$rule_addr=$add_ptr69;;}}
else if(__label__==33){$add_points=0;var $45=$match_type;if($45==0){__label__=34;;}
else if($45==2){__label__=41;;}
else if($45==1){__label__=119;;}
else{__label__=181;;}
$sw_epilog496$$sw_bb71$$sw_bb89$$sw_bb328$44:do{if(__label__==34){var $46=$letter;$last_letter=$46;var $47=$post_ptr;var $incdec_ptr72=(($47+1)&4294967295);$post_ptr=$incdec_ptr72;var $48=HEAP8[($47)];$letter=$48;var $49=$letter;var $conv73=((($49))&255);var $50=$rb;var $conv74=((($50))&255);var $cmp75=((($conv73))|0)==((($conv74))|0);if($cmp75){__label__=37;;}else{__label__=35;;}
$if_then80$$lor_lhs_false$46:do{if(__label__==35){var $51=$letter;var $conv76=((($51))&255);var $cmp77=((($conv76))|0)==69;if($cmp77){__label__=36;;}else{__label__=40;;}
if(__label__==36){var $52=$rb;var $conv78=((($52))&255);var $cmp79=((($conv78))|0)==101;if($cmp79){__label__=37;break $if_then80$$lor_lhs_false$46;}}
$failed=1;__label__=30;break $if_then8$$if_end70$12;}}while(0);var $53=$letter;var $conv81=((($53))&255);var $and82=($conv81)&192;var $cmp83=((($and82))|0)!=128;if($cmp83){__label__=38;;}else{__label__=39;;}
if(__label__==38){$add_points=21;;}
var $54=$consumed;var $inc86=((($54)+1)&4294967295);$consumed=$inc86;;}
else if(__label__==41){var $55=$distance_right;var $add=((($55)+6)&4294967295);$distance_right=$add;var $56=$distance_right;var $cmp90=((($56))|0)>18;if($cmp90){__label__=42;;}else{__label__=43;;}
if(__label__==42){$distance_right=19;;}
var $57=$letter;$last_letter=$57;var $58=$post_ptr;var $call=__Z7utf8_inPiPKc($letter_w,$58);var $sub93=((($call)-1)&4294967295);$letter_xbytes=$sub93;var $59=$post_ptr;var $incdec_ptr94=(($59+1)&4294967295);$post_ptr=$incdec_ptr94;var $60=HEAP8[($59)];$letter=$60;var $61=$rb;var $conv95=((($61))&255);if($conv95==17){__label__=44;;}
else if($conv95==18){__label__=49;;}
else if($conv95==25){__label__=52;;}
else if($conv95==15){__label__=57;;}
else if($conv95==16){__label__=62;;}
else if($conv95==11){__label__=65;;}
else if($conv95==28){__label__=68;;}
else if($conv95==45){__label__=78;;}
else if($conv95==21){__label__=83;;}
else if($conv95==29){__label__=94;;}
else if($conv95==23){__label__=101;;}
else if($conv95==12){__label__=105;;}
else if($conv95==13){__label__=106;;}
else if($conv95==14){__label__=111;;}
else if($conv95==24){__label__=112;;}
else{__label__=115;;}
if(__label__==115){var $186=$letter;var $conv315=((($186))&255);var $187=$rb;var $conv316=((($187))&255);var $cmp317=((($conv315))|0)==((($conv316))|0);if($cmp317){__label__=116;;}else{__label__=118;;}
if(__label__==116){var $188=$letter;var $conv319=((($188))&255);var $and320=($conv319)&192;var $cmp321=((($and320))|0)!=128;if(!($cmp321)){__label__=181;break $sw_epilog496$$sw_bb71$$sw_bb89$$sw_bb328$44;}
var $189=$distance_right;var $sub323=((21-($189))&4294967295);$add_points=$sub323;;}
else if(__label__==118){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==44){var $62=$rule_addr;var $incdec_ptr97=(($62+1)&4294967295);$rule_addr=$incdec_ptr97;var $63=HEAP8[($62)];var $conv98=(tempInt=(($63)),(tempInt>=128?tempInt-256:tempInt));var $sub99=((($conv98)-65)&4294967295);$letter_group=$sub99;var $64=$tr_addr;var $65=HEAP32[(($letter_w)>>2)];var $66=$letter_group;var $call100=__ZL8IsLetterP10Translatorii($64,$65,$66);var $tobool101=((($call100))|0)!=0;if($tobool101){__label__=45;;}else{__label__=48;;}
if(__label__==45){$lg_pts=20;var $67=$letter_group;var $cmp103=((($67))|0)==2;if($cmp103){__label__=46;;}else{__label__=47;;}
if(__label__==46){$lg_pts=19;;}
var $68=$lg_pts;var $69=$distance_right;var $sub106=((($68)-($69))&4294967295);$add_points=$sub106;var $70=$letter_xbytes;var $71=$post_ptr;var $add_ptr107=(($71+$70)&4294967295);$post_ptr=$add_ptr107;;}
else if(__label__==48){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==49){var $72=$rule_addr;var $incdec_ptr111=(($72+1)&4294967295);$rule_addr=$incdec_ptr111;var $73=HEAP8[($72)];var $conv112=(tempInt=(($73)),(tempInt>=128?tempInt-256:tempInt));var $sub113=((($conv112)-65)&4294967295);$letter_group=$sub113;var $74=$tr_addr;var $75=$post_ptr;var $add_ptr114=(($75+-1)&4294967295);var $76=$letter_group;var $call115=__ZL13IsLetterGroupP10TranslatorPcii($74,$add_ptr114,$76,0);$n_bytes=$call115;var $cmp116=((($call115))|0)>0;if($cmp116){__label__=50;;}else{__label__=51;;}
if(__label__==50){var $77=$distance_right;var $sub118=((20-($77))&4294967295);$add_points=$sub118;var $78=$n_bytes;var $sub119=((($78)-1)&4294967295);var $79=$post_ptr;var $add_ptr120=(($79+$sub119)&4294967295);$post_ptr=$add_ptr120;;}
else if(__label__==51){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==52){var $80=$tr_addr;var $81=HEAP32[(($letter_w)>>2)];var $call124=__ZL8IsLetterP10Translatorii($80,$81,0);var $tobool125=((($call124))|0)!=0;if($tobool125){__label__=55;;}else{__label__=53;;}
$if_then131$$lor_lhs_false126$77:do{if(__label__==53){var $82=HEAP32[(($letter_w)>>2)];var $cmp127=((($82))|0)==32;if($cmp127){__label__=54;;}else{__label__=56;;}
if(__label__==54){var $83=$word_flags_addr;var $and129=($83)&134217728;var $tobool130=((($and129))|0)!=0;if($tobool130){__label__=55;break $if_then131$$lor_lhs_false126$77;}}
var $84=$distance_right;var $sub133=((20-($84))&4294967295);$add_points=$sub133;var $85=$letter_xbytes;var $86=$post_ptr;var $add_ptr134=(($86+$85)&4294967295);$post_ptr=$add_ptr134;__label__=181;break $sw_epilog496$$sw_bb71$$sw_bb89$$sw_bb328$44;}}while(0);$failed=1;__label__=30;break $if_then8$$if_end70$12;}
else if(__label__==57){var $87=HEAP32[(($letter_w)>>2)];var $call137=__Z7IsDigitj($87);var $tobool138=((($call137))|0)!=0;if($tobool138){__label__=58;;}else{__label__=59;;}
if(__label__==58){var $88=$distance_right;var $sub140=((20-($88))&4294967295);$add_points=$sub140;var $89=$letter_xbytes;var $90=$post_ptr;var $add_ptr141=(($90+$89)&4294967295);$post_ptr=$add_ptr141;;}
else if(__label__==59){var $91=$tr_addr;var $langopts=(($91)&4294967295);var $tone_numbers=(($langopts+250)&4294967295);var $92=HEAP8[($tone_numbers)];var $tobool143=(tempInt=(($92)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool143){__label__=60;;}else{__label__=61;;}
if(__label__==60){var $93=$distance_right;var $sub145=((20-($93))&4294967295);$add_points=$sub145;var $94=$post_ptr;var $incdec_ptr146=(($94+-1)&4294967295);$post_ptr=$incdec_ptr146;;}
else if(__label__==61){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}}
else if(__label__==62){var $95=HEAP32[(($letter_w)>>2)];var $call151=_iswalpha($95);var $tobool152=((($call151))|0)!=0;if($tobool152){__label__=64;;}else{__label__=63;;}
if(__label__==64){$failed=1;__label__=30;break $if_then8$$if_end70$12;}
else if(__label__==63){var $96=$distance_right;var $sub154=((21-($96))&4294967295);$add_points=$sub154;var $97=$letter_xbytes;var $98=$post_ptr;var $add_ptr155=(($98+$97)&4294967295);$post_ptr=$add_ptr155;;}}
else if(__label__==65){var $99=$letter;var $conv159=((($99))&255);var $100=$last_letter;var $conv160=((($100))&255);var $cmp161=((($conv159))|0)==((($conv160))|0);if($cmp161){__label__=66;;}else{__label__=67;;}
if(__label__==66){var $101=$distance_right;var $sub163=((21-($101))&4294967295);$add_points=$sub163;;}
else if(__label__==67){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==68){var $102=$rule_addr;var $incdec_ptr167=(($102+1)&4294967295);$rule_addr=$incdec_ptr167;var $103=HEAP8[($102)];var $conv168=(tempInt=(($103)),(tempInt>=128?tempInt-256:tempInt));$command=$conv168;var $104=$command;var $cmp169=((($104))|0)==1;if($cmp169){__label__=69;;}else{__label__=70;;}
if(__label__==69){HEAP32[(($end_type171)>>2)]=32768;;}
else if(__label__==70){var $105=$command;var $and173=($105)&240;var $cmp174=((($and173))|0)==16;if($cmp174){__label__=71;;}else{__label__=74;;}
if(__label__==71){var $106=$dict_flags_addr;var $107=$command;var $and176=($107)&15;var $add177=((($and176)+19)&4294967295);var $shl178=1<<($add177);var $and179=($shl178)&($106);var $tobool180=((($and179))|0)!=0;if($tobool180){__label__=72;;}else{__label__=73;;}
if(__label__==72){$add_points=23;;}
else if(__label__==73){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==74){var $108=$command;var $and185=($108)&240;var $cmp186=((($and185))|0)==32;if(!($cmp186)){__label__=181;break $sw_epilog496$$sw_bb71$$sw_bb89$$sw_bb328$44;}
var $109=$word_addr;var $110=HEAP32[(($109)>>2)];var $111=$word_start_addr;var $sub_ptr_lhs_cast=($110);var $sub_ptr_rhs_cast=($111);var $sub_ptr_rhs_cast_neg=(((-($sub_ptr_rhs_cast)))&4294967295);var $112=$consumed;var $113=$group_length_addr;var $sub_ptr_sub=((($sub_ptr_lhs_cast)+1)&4294967295);var $add188=((($sub_ptr_sub)+($112))&4294967295);var $add189=((($add188)+($sub_ptr_rhs_cast_neg))&4294967295);var $add190=((($add189)+($113))&4294967295);$ix=$add190;var $114=$word_start_addr;var $add_ptr191=(($114+-1)&4294967295);var $115=$ix;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$add_ptr191;$dest$=$arraydecay;$stop$=$src$+$115;if(($dest$%4)==($src$%4)&&$115>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $116=$ix;var $arrayidx192=(($word_buf+$116)&4294967295);HEAP8[($arrayidx192)]=32;var $117=$ix;var $add193=((($117)+1)&4294967295);var $arrayidx194=(($word_buf+$add193)&4294967295);HEAP8[($arrayidx194)]=0;var $118=$tr_addr;var $call196=__Z11LookupFlagsP10TranslatorPKc($118,$arrayidx195);var $119=$command;var $and197=($119)&15;var $add198=((($and197)+19)&4294967295);var $shl199=1<<($add198);var $and200=($shl199)&($call196);var $tobool201=((($and200))|0)!=0;if($tobool201){__label__=76;;}else{__label__=77;;}
if(__label__==76){$add_points=23;;}
else if(__label__==77){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}}}
else if(__label__==78){var $120=$letter;var $conv209=((($120))&255);var $cmp210=((($conv209))|0)==45;if($cmp210){__label__=81;;}else{__label__=79;;}
$if_then217$$lor_lhs_false211$113:do{if(__label__==79){var $121=$letter;var $conv212=((($121))&255);var $cmp213=((($conv212))|0)==32;if($cmp213){__label__=80;;}else{__label__=82;;}
if(__label__==80){var $122=$word_flags_addr;var $and215=($122)&16384;var $tobool216=((($and215))|0)!=0;if($tobool216){__label__=81;break $if_then217$$lor_lhs_false211$113;}}
$failed=1;__label__=30;break $if_then8$$if_end70$12;}}while(0);var $123=$distance_right;var $sub218=((22-($123))&4294967295);$add_points=$sub218;;}
else if(__label__==83){var $124=$post_ptr;var $125=$letter_xbytes;var $add_ptr223=(($124+$125)&4294967295);$p222=$add_ptr223;$vowel_count=0;$syllable_count=1;var $126=$rule_addr;var $127=HEAP8[($126)];var $conv22514=(tempInt=(($127)),(tempInt>=128?tempInt-256:tempInt));var $cmp22615=((($conv22514))|0)==21;if($cmp22615){__label__=84;;}else{__label__=85;;}
$while_body227$$while_end230$120:do{if(__label__==84){while(1){var $128=$rule_addr;var $incdec_ptr228=(($128+1)&4294967295);$rule_addr=$incdec_ptr228;var $129=$syllable_count;var $add229=((($129)+1)&4294967295);$syllable_count=$add229;var $130=$rule_addr;var $131=HEAP8[($130)];var $conv225=(tempInt=(($131)),(tempInt>=128?tempInt-256:tempInt));var $cmp226=((($conv225))|0)==21;if($cmp226){__label__=84;continue;}else{__label__=85;break $while_body227$$while_end230$120;}}}}while(0);$vowel=0;var $132=HEAP32[(($letter_w)>>2)];var $cmp23216=((($132))|0)!=32;if($cmp23216){__lastLabel__=85;__label__=87;;}else{__lastLabel__=85;__label__=91;;}
$while_body233$$while_end244$124:do{if(__label__==87){$while_body233$125:while(1){var $133=__lastLabel__==86?$_pr24:(0);var $cmp234=((($133))|0)==0;if($cmp234){__label__=88;;}else{__label__=90;;}
$land_lhs_true235$$if_end240$127:do{if(__label__==88){var $134=$tr_addr;var $135=HEAP32[(($letter_w)>>2)];var $call236=__ZL8IsLetterP10Translatorii($134,$135,7);var $tobool237=((($call236))|0)!=0;if(!($tobool237)){__label__=90;break $land_lhs_true235$$if_end240$127;}
var $136=$vowel_count;var $inc239=((($136)+1)&4294967295);$vowel_count=$inc239;;}}while(0);var $137=$tr_addr;var $138=HEAP32[(($letter_w)>>2)];var $call241=__ZL8IsLetterP10Translatorii($137,$138,7);$vowel=$call241;var $139=$p222;var $call242=__Z7utf8_inPiPKc($letter_w,$139);var $140=$p222;var $add_ptr243=(($140+$call242)&4294967295);$p222=$add_ptr243;var $141=HEAP32[(($letter_w)>>2)];var $cmp232=((($141))|0)!=32;if(!($cmp232)){__label__=91;break $while_body233$$while_end244$124;}
var $_pr24=$vowel;__lastLabel__=86;__label__=87;continue $while_body233$125;}}}while(0);var $142=$syllable_count;var $143=$vowel_count;var $cmp245=((($142))|0)<=((($143))|0);if($cmp245){__label__=92;;}else{__label__=93;;}
if(__label__==92){var $144=$syllable_count;var $145=$distance_right;var $_neg=(((-($145)))&4294967295);var $add247=((($144)+18)&4294967295);var $sub248=((($add247)+($_neg))&4294967295);$add_points=$sub248;;}
else if(__label__==93){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==94){var $146=$post_ptr;var $147=$letter_xbytes;var $add_ptr253=(($146+$147)&4294967295);$p252=$add_ptr253;;while(1){var $148=HEAP32[(($letter_w)>>2)];var $cmp255=((($148))|0)!=32;if(!($cmp255)){__label__=99;break;}
var $149=$tr_addr;var $150=HEAP32[(($letter_w)>>2)];var $call257=__ZL8IsLetterP10Translatorii($149,$150,7);var $tobool258=((($call257))|0)!=0;if($tobool258){__label__=97;break;}
var $151=$p252;var $call261=__Z7utf8_inPiPKc($letter_w,$151);var $152=$p252;var $add_ptr262=(($152+$call261)&4294967295);$p252=$add_ptr262;__label__=95;continue;}
if(__label__==99){var $_pr2=$failed;var $tobool264=((($_pr2))|0)!=0;if($tobool264){__label__=30;break $if_then8$$if_end70$12;}
var $153=$distance_right;var $sub266=((19-($153))&4294967295);$add_points=$sub266;;}
else if(__label__==97){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==101){var $154=$post_ptr;var $155=$letter_xbytes;var $add_ptr270=(($154+$155)&4294967295);$p269=$add_ptr270;var $156=$p269;$p2=$156;var $157=$rule_addr;var $call271=__Z7utf8_inPiPKc($rule_w,$157);var $158=HEAP32[(($letter_w)>>2)];var $159=HEAP32[(($rule_w)>>2)];var $cmp27317=((($158))|0)!=((($159))|0);var $160=HEAP32[(($letter_w)>>2)];var $cmp27518=((($160))|0)!=32;var $or_cond19=($cmp27317)&($cmp27518);if($or_cond19){__label__=102;;}else{__label__=103;;}
$while_body277$$while_end280$146:do{if(__label__==102){while(1){var $161=$p269;$p2=$161;var $162=$p269;var $call278=__Z7utf8_inPiPKc($letter_w,$162);var $163=$p269;var $add_ptr279=(($163+$call278)&4294967295);$p269=$add_ptr279;var $164=HEAP32[(($letter_w)>>2)];var $165=HEAP32[(($rule_w)>>2)];var $cmp273=((($164))|0)!=((($165))|0);var $166=HEAP32[(($letter_w)>>2)];var $cmp275=((($166))|0)!=32;var $or_cond=($cmp273)&($cmp275);if($or_cond){__label__=102;continue;}else{__label__=103;break $while_body277$$while_end280$146;}}}}while(0);var $167=HEAP32[(($letter_w)>>2)];var $168=HEAP32[(($rule_w)>>2)];var $cmp281=((($167))|0)==((($168))|0);if(!($cmp281)){__label__=181;break $sw_epilog496$$sw_bb71$$sw_bb89$$sw_bb328$44;}
var $169=$p2;$post_ptr=$169;;}
else if(__label__==105){$add_points=20;;}
else if(__label__==106){var $170=$word_addr;var $171=HEAP32[(($170)>>2)];var $172=$group_length_addr;var $add_ptr286=(($171+$172)&4294967295);$p=$add_ptr286;;while(1){var $173=$p;var $174=$post_ptr;var $cmp287=((($173))>>>0)<((($174))>>>0);if(!($cmp287)){__label__=181;break $sw_epilog496$$sw_bb71$$sw_bb89$$sw_bb328$44;}
var $175=$p;var $176=HEAP8[($175)];var $conv288=(tempInt=(($176)),(tempInt>=128?tempInt-256:tempInt));var $cmp289=((($conv288))|0)==101;var $177=$p;if($cmp289){__label__=109;break;}
var $incdec_ptr293=(($177+1)&4294967295);$p=$incdec_ptr293;__label__=107;continue;}
HEAP32[(($del_fwd291)>>2)]=$177;;}
else if(__label__==111){var $178=$rule_addr;var $arrayidx295=(($178)&4294967295);var $179=HEAP8[($arrayidx295)];var $conv296=(tempInt=(($179)),(tempInt>=128?tempInt-256:tempInt));var $shl297=((($conv296)*65536)&4294967295);var $180=$rule_addr;var $arrayidx298=(($180+1)&4294967295);var $181=HEAP8[($arrayidx298)];var $conv299=(tempInt=(($181)),(tempInt>=128?tempInt-256:tempInt));var $and300=($conv299)&127;var $shl301=((($and300)*256)&4294967295);var $182=$rule_addr;var $arrayidx303=(($182+2)&4294967295);var $183=HEAP8[($arrayidx303)];var $conv304=(tempInt=(($183)),(tempInt>=128?tempInt-256:tempInt));var $and305=($conv304)&127;var $add302=((($shl301)+($shl297))&4294967295);var $add306=((($add302)+($and305))&4294967295);HEAP32[(($end_type307)>>2)]=$add306;var $184=$rule_addr;var $add_ptr308=(($184+3)&4294967295);$rule_addr=$add_ptr308;;}
else if(__label__==112){var $185=$word_flags_addr;var $and310=($185)&8192;var $tobool311=((($and310))|0)!=0;if($tobool311){__label__=113;;}else{__label__=114;;}
if(__label__==113){$failed=1;__label__=30;break $if_then8$$if_end70$12;}
else if(__label__==114){$add_points=1;;}}}
else if(__label__==119){var $190=$distance_left;var $add329=((($190)+2)&4294967295);$distance_left=$add329;var $191=$distance_left;var $cmp330=((($191))|0)>18;if($cmp330){__label__=120;;}else{__label__=121;;}
if(__label__==120){$distance_left=19;;}
var $192=$pre_ptr;var $193=HEAP8[($192)];$last_letter=$193;var $194=$pre_ptr;var $incdec_ptr333=(($194+-1)&4294967295);$pre_ptr=$incdec_ptr333;var $195=$pre_ptr;var $call334=__Z8utf8_in2PiPKci($letter_w,$195,1);var $sub335=((($call334)-1)&4294967295);$letter_xbytes=$sub335;var $196=$pre_ptr;var $197=HEAP8[($196)];$letter=$197;var $198=$rb;var $conv336=((($198))&255);if($conv336==17){__label__=122;;}
else if($conv336==18){__label__=127;;}
else if($conv336==25){__label__=130;;}
else if($conv336==11){__label__=133;;}
else if($conv336==15){__label__=136;;}
else if($conv336==16){__label__=139;;}
else if($conv336==21){__label__=142;;}
else if($conv336==10){__label__=147;;}
else if($conv336==29){__label__=150;;}
else if($conv336==26){__label__=157;;}
else if($conv336==19){__label__=160;;}
else if($conv336==46){__label__=163;;}
else if($conv336==45){__label__=170;;}
else{__label__=175;;}
if(__label__==175){var $268=$letter;var $conv478=((($268))&255);var $269=$rb;var $conv479=((($269))&255);var $cmp480=((($conv478))|0)==((($conv479))|0);if($cmp480){__label__=176;;}else{__label__=180;;}
if(__label__==176){var $270=$letter;var $conv482=((($270))&255);var $cmp483=((($conv482))|0)==32;if($cmp483){__label__=177;;}else{__label__=178;;}
if(__label__==177){$add_points=4;;}
else if(__label__==178){var $271=$letter;var $conv486=((($271))&255);var $and487=($conv486)&192;var $cmp488=((($and487))|0)!=128;if(!($cmp488)){__label__=181;break $sw_epilog496$$sw_bb71$$sw_bb89$$sw_bb328$44;}
var $272=$distance_left;var $sub490=((21-($272))&4294967295);$add_points=$sub490;;}}
else if(__label__==180){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==122){var $199=$rule_addr;var $incdec_ptr338=(($199+1)&4294967295);$rule_addr=$incdec_ptr338;var $200=HEAP8[($199)];var $conv339=(tempInt=(($200)),(tempInt>=128?tempInt-256:tempInt));var $sub340=((($conv339)-65)&4294967295);$letter_group=$sub340;var $201=$tr_addr;var $202=HEAP32[(($letter_w)>>2)];var $203=$letter_group;var $call341=__ZL8IsLetterP10Translatorii($201,$202,$203);var $tobool342=((($call341))|0)!=0;if($tobool342){__label__=123;;}else{__label__=126;;}
if(__label__==123){$lg_pts=20;var $204=$letter_group;var $cmp344=((($204))|0)==2;if($cmp344){__label__=124;;}else{__label__=125;;}
if(__label__==124){$lg_pts=19;;}
var $205=$lg_pts;var $206=$distance_left;var $sub347=((($205)-($206))&4294967295);$add_points=$sub347;var $207=$letter_xbytes;var $208=$pre_ptr;var $idx_neg=(((-($207)))&4294967295);var $add_ptr348=(($208+$idx_neg)&4294967295);$pre_ptr=$add_ptr348;;}
else if(__label__==126){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==127){var $209=$rule_addr;var $incdec_ptr352=(($209+1)&4294967295);$rule_addr=$incdec_ptr352;var $210=HEAP8[($209)];var $conv353=(tempInt=(($210)),(tempInt>=128?tempInt-256:tempInt));var $sub354=((($conv353)-65)&4294967295);$letter_group=$sub354;var $211=$tr_addr;var $212=$pre_ptr;var $213=$letter_group;var $call355=__ZL13IsLetterGroupP10TranslatorPcii($211,$212,$213,1);$n_bytes=$call355;var $cmp356=((($call355))|0)>0;if($cmp356){__label__=128;;}else{__label__=129;;}
if(__label__==128){var $214=$distance_right;var $sub358=((20-($214))&4294967295);$add_points=$sub358;var $215=$n_bytes;var $sub359=((($215)-1)&4294967295);var $216=$pre_ptr;var $idx_neg360=(((-($sub359)))&4294967295);var $add_ptr361=(($216+$idx_neg360)&4294967295);$pre_ptr=$add_ptr361;;}
else if(__label__==129){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==130){var $217=$tr_addr;var $218=HEAP32[(($letter_w)>>2)];var $call365=__ZL8IsLetterP10Translatorii($217,$218,0);var $tobool366=((($call365))|0)!=0;if($tobool366){__label__=132;;}else{__label__=131;;}
if(__label__==132){$failed=1;__label__=30;break $if_then8$$if_end70$12;}
else if(__label__==131){var $219=$distance_left;var $sub368=((20-($219))&4294967295);$add_points=$sub368;var $220=$letter_xbytes;var $221=$pre_ptr;var $idx_neg369=(((-($220)))&4294967295);var $add_ptr370=(($221+$idx_neg369)&4294967295);$pre_ptr=$add_ptr370;;}}
else if(__label__==133){var $222=$letter;var $conv374=((($222))&255);var $223=$last_letter;var $conv375=((($223))&255);var $cmp376=((($conv374))|0)==((($conv375))|0);if($cmp376){__label__=134;;}else{__label__=135;;}
if(__label__==134){var $224=$distance_left;var $sub378=((21-($224))&4294967295);$add_points=$sub378;;}
else if(__label__==135){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==136){var $225=HEAP32[(($letter_w)>>2)];var $call382=__Z7IsDigitj($225);var $tobool383=((($call382))|0)!=0;if($tobool383){__label__=137;;}else{__label__=138;;}
if(__label__==137){var $226=$distance_left;var $sub385=((21-($226))&4294967295);$add_points=$sub385;var $227=$letter_xbytes;var $228=$pre_ptr;var $idx_neg386=(((-($227)))&4294967295);var $add_ptr387=(($228+$idx_neg386)&4294967295);$pre_ptr=$add_ptr387;;}
else if(__label__==138){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==139){var $229=HEAP32[(($letter_w)>>2)];var $call391=_iswalpha($229);var $tobool392=((($call391))|0)!=0;if($tobool392){__label__=141;;}else{__label__=140;;}
if(__label__==141){$failed=1;__label__=30;break $if_then8$$if_end70$12;}
else if(__label__==140){var $230=$distance_right;var $sub394=((21-($230))&4294967295);$add_points=$sub394;var $231=$letter_xbytes;var $232=$pre_ptr;var $idx_neg395=(((-($231)))&4294967295);var $add_ptr396=(($232+$idx_neg395)&4294967295);$pre_ptr=$add_ptr396;;}}
else if(__label__==142){$syllable_count=1;var $233=$rule_addr;var $234=HEAP8[($233)];var $conv40112=(tempInt=(($234)),(tempInt>=128?tempInt-256:tempInt));var $cmp40213=((($conv40112))|0)==21;if($cmp40213){__label__=143;;}else{__label__=144;;}
$while_body403$$while_end406$204:do{if(__label__==143){while(1){var $235=$rule_addr;var $incdec_ptr404=(($235+1)&4294967295);$rule_addr=$incdec_ptr404;var $236=$syllable_count;var $inc405=((($236)+1)&4294967295);$syllable_count=$inc405;var $237=$rule_addr;var $238=HEAP8[($237)];var $conv401=(tempInt=(($238)),(tempInt>=128?tempInt-256:tempInt));var $cmp402=((($conv401))|0)==21;if($cmp402){__label__=143;continue;}else{__label__=144;break $while_body403$$while_end406$204;}}}}while(0);var $239=$syllable_count;var $240=$tr_addr;var $word_vowel_count=(($240+8296)&4294967295);var $241=HEAP32[(($word_vowel_count)>>2)];var $cmp407=((($239))|0)<=((($241))|0);if($cmp407){__label__=145;;}else{__label__=146;;}
if(__label__==145){var $242=$syllable_count;var $243=$distance_left;var $_neg11=(((-($243)))&4294967295);var $add409=((($242)+18)&4294967295);var $sub410=((($add409)+($_neg11))&4294967295);$add_points=$sub410;;}
else if(__label__==146){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==147){var $244=$tr_addr;var $word_stressed_count=(($244+8300)&4294967295);var $245=HEAP32[(($word_stressed_count)>>2)];var $cmp414=((($245))|0)>0;if($cmp414){__label__=148;;}else{__label__=149;;}
if(__label__==148){$add_points=19;;}
else if(__label__==149){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==150){var $246=$pre_ptr;var $247=$letter_xbytes;var $idx_neg420=(((-($247)))&4294967295);var $add_ptr421=(($246+$idx_neg420)&4294967295);var $add_ptr422=(($add_ptr421+-1)&4294967295);$p419=$add_ptr422;;while(1){var $248=HEAP32[(($letter_w)>>2)];var $cmp424=((($248))|0)!=32;if(!($cmp424)){__label__=155;break;}
var $249=$tr_addr;var $250=HEAP32[(($letter_w)>>2)];var $call426=__ZL8IsLetterP10Translatorii($249,$250,7);var $tobool427=((($call426))|0)!=0;if($tobool427){__label__=153;break;}
var $251=$p419;var $call430=__Z8utf8_in2PiPKci($letter_w,$251,1);var $252=$p419;var $idx_neg431=(((-($call430)))&4294967295);var $add_ptr432=(($252+$idx_neg431)&4294967295);$p419=$add_ptr432;__label__=151;continue;}
if(__label__==155){var $_pr4=$failed;var $tobool434=((($_pr4))|0)!=0;if($tobool434){__label__=30;break $if_then8$$if_end70$12;}
$add_points=3;;}
else if(__label__==153){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==157){var $253=$tr_addr;var $expect_verb=(($253+8272)&4294967295);var $254=HEAP32[(($expect_verb)>>2)];var $tobool438=((($254))|0)!=0;if($tobool438){__label__=158;;}else{__label__=159;;}
if(__label__==158){$add_points=1;;}
else if(__label__==159){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==160){var $255=$word_flags_addr;var $and443=($255)&2;var $tobool444=((($and443))|0)!=0;if($tobool444){__label__=161;;}else{__label__=162;;}
if(__label__==161){$add_points=1;;}
else if(__label__==162){$failed=1;__label__=30;break $if_then8$$if_end70$12;}}
else if(__label__==163){var $256=$pre_ptr;$p=$256;;while(1){var $257=$p;var $258=HEAP8[($257)];var $conv450=(tempInt=(($258)),(tempInt>=128?tempInt-256:tempInt));var $cmp451=((($conv450))|0)!=32;if(!($cmp451)){__label__=168;break;}
var $259=$p;var $260=HEAP8[($259)];var $conv453=(tempInt=(($260)),(tempInt>=128?tempInt-256:tempInt));var $cmp454=((($conv453))|0)==46;if($cmp454){__label__=166;break;}
var $261=$p;var $incdec_ptr458=(($261+-1)&4294967295);$p=$incdec_ptr458;__label__=164;continue;}
if(__label__==166){$add_points=50;;}
var $262=$p;var $263=HEAP8[($262)];var $conv460=(tempInt=(($263)),(tempInt>=128?tempInt-256:tempInt));var $cmp461=((($conv460))|0)==32;if(!($cmp461)){__label__=181;break $sw_epilog496$$sw_bb71$$sw_bb89$$sw_bb328$44;}
$failed=1;__label__=30;break $if_then8$$if_end70$12;}
else if(__label__==170){var $264=$letter;var $conv465=((($264))&255);var $cmp466=((($conv465))|0)==45;if($cmp466){__label__=173;;}else{__label__=171;;}
$if_then473$$lor_lhs_false467$242:do{if(__label__==171){var $265=$letter;var $conv468=((($265))&255);var $cmp469=((($conv468))|0)==32;if($cmp469){__label__=172;;}else{__label__=174;;}
if(__label__==172){var $266=$word_flags_addr;var $and471=($266)&128;var $tobool472=((($and471))|0)!=0;if($tobool472){__label__=173;break $if_then473$$lor_lhs_false467$242;}}
$failed=1;__label__=30;break $if_then8$$if_end70$12;}}while(0);var $267=$distance_right;var $sub474=((22-($267))&4294967295);$add_points=$sub474;;}}}while(0);var $_pr6_pr=$failed;var $cmp497=((($_pr6_pr))|0)==0;if(!($cmp497)){__label__=30;break $if_then8$$if_end70$12;}
var $273=$add_points;var $274=HEAP32[(($points499)>>2)];var $add500=((($274)+($273))&4294967295);HEAP32[(($points499)>>2)]=$add500;;}}while(0);var $42=$failed;var $tobool=((($42))|0)!=0;var $lnot=($tobool)^1;if($lnot){__lastLabel__=30;__label__=6;continue $while_body4$10;}else{__lastLabel__=30;__label__=183;break $while_body4$$while_end502$9;}}}}while(0);var $275=__lastLabel__==30?$42:($18);var $cmp503=((($275))|0)==2;if($cmp503){__label__=184;;}else{__label__=197;;}
$land_lhs_true504$$while_cond543$252:do{if(__label__==184){var $276=$unpron_ignore;var $cmp505=((($276))|0)==0;if(!($cmp505)){__label__=197;break $land_lhs_true504$$while_cond543$252;}
var $277=$check_atstart;var $cmp507=((($277))|0)==0;if($cmp507){__label__=189;;}else{__label__=186;;}
$if_end517$$lor_lhs_false508$255:do{if(__label__==186){var $278=$pre_ptr;var $arrayidx509=(($278+-1)&4294967295);var $279=HEAP8[($arrayidx509)];var $conv510=(tempInt=(($279)),(tempInt>=128?tempInt-256:tempInt));var $cmp511=((($conv510))|0)==32;if(!($cmp511)){__label__=197;break $land_lhs_true504$$while_cond543$252;}
var $_pr8=$check_atstart;var $tobool513=((($_pr8))|0)!=0;if(!($tobool513)){__label__=189;break $if_end517$$lor_lhs_false508$255;}
var $280=HEAP32[(($points515)>>2)];var $add516=((($280)+4)&4294967295);HEAP32[(($points515)>>2)]=$add516;;}}while(0);var $281=HEAP32[(($points518)>>2)];var $282=HEAP32[((((__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best)&4294967295))>>2)];var $cmp519=((($281))|0)>=((($282))|0);if($cmp519){__label__=190;;}else{__label__=191;;}
if(__label__==190){var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$8;$dest$=__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best;$stop$=$src$+16;if(($dest$%4)==($src$%4)&&16>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $283=$consumed;$total_consumed=$283;;}
var $284=HEAP32[((_option_phonemes)>>2)];var $cmp522=((($284))|0)==2;if(!($cmp522)){__label__=197;break $land_lhs_true504$$while_cond543$252;}
var $285=HEAP32[(($points524)>>2)];var $cmp525=((($285))|0)>0;if(!($cmp525)){__label__=197;break $land_lhs_true504$$while_cond543$252;}
var $286=$word_flags_addr;var $and527=($286)&268435456;var $cmp528=((($and527))|0)==0;if(!($cmp528)){__label__=197;break $land_lhs_true504$$while_cond543$252;}
var $287=HEAP32[(($points530)>>2)];$pts=$287;var $288=$group_length_addr;var $cmp531=((($288))|0)>1;if($cmp531){__label__=195;;}else{__label__=196;;}
if(__label__==195){var $289=$pts;var $add533=((($289)+35)&4294967295);$pts=$add533;;}
var $290=HEAP32[(($phonemes535)>>2)];__Z14DecodePhonemesPKcPc($290,$arraydecay536);var $291=HEAP32[((_f_trans)>>2)];var $292=$pts;var $293=$group_chars;var $294=$group_length_addr;var $295=$rule_start;var $296=$word_flags_addr;var $call537=__Z10DecodeRulePKciPci($293,$294,$295,$296);var $call539=_fprintf($291,((__str32148)&4294967295),allocate([$292,0,0,0,((__ZZ10DecodeRulePKciPciE6output)&4294967295),0,0,0,$arraydecay538,0,0,0],["i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}}while(0);while(1){var $297=$rule_addr;var $incdec_ptr544=(($297+1)&4294967295);$rule_addr=$incdec_ptr544;var $298=HEAP8[($297)];var $conv545=(tempInt=(($298)),(tempInt>=128?tempInt-256:tempInt));var $cmp546=((($conv545))|0)!=0;if($cmp546){__label__=197;continue;}else{__label__=4;break;}}
var $9=$rule_addr;var $arrayidx=(($9)&4294967295);var $10=HEAP8[($arrayidx)];var $conv=(tempInt=(($10)),(tempInt>=128?tempInt-256:tempInt));var $cmp1=((($conv))|0)!=7;if($cmp1){__label__=5;continue $while_body$7;}else{__label__=198;break $while_body_lr_ph$$while_end549$5;}}}}while(0);var $299=HEAP32[((_option_phonemes)>>2)];var $cmp550=((($299))|0)==2;if($cmp550){__label__=199;;}else{__label__=202;;}
$land_lhs_true551$$if_end559$273:do{if(__label__==199){var $300=$word_flags_addr;var $and552=($300)&268435456;var $cmp553=((($and552))|0)==0;if(!($cmp553)){__label__=202;break $land_lhs_true551$$if_end559$273;}
var $301=$group_length_addr;var $cmp555=((($301))|0)<=1;if(!($cmp555)){__label__=202;break $land_lhs_true551$$if_end559$273;}
var $302=HEAP32[((_f_trans)>>2)];var $fputc=_fputc(10,$302);;}}while(0);var $303=$group_length_addr;var $304=$total_consumed;var $add560=((($304)+($303))&4294967295);$total_consumed=$add560;var $cmp561=((($add560))|0)==0;if($cmp561){__label__=203;;}else{__label__=204;;}
if(__label__==203){$total_consumed=1;;}
var $305=$total_consumed;var $306=$word_addr;var $307=HEAP32[(($306)>>2)];var $add_ptr564=(($307+$305)&4294967295);HEAP32[(($306)>>2)]=$add_ptr564;var $308=HEAP32[((((__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best)&4294967295))>>2)];var $cmp565=((($308))|0)==0;if($cmp565){__label__=205;;}else{__label__=206;;}
if(__label__==205){HEAP32[((((__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best+4)&4294967295))>>2)]=((__str13643)&4294967295);;}
var $309=$match_out_addr;var $310=$309;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best;$dest$=$310;$stop$=$src$+16;if(($dest$%4)==($src$%4)&&16>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}
STACKTOP=__stackBase__;return;return;}
function __Z21ApplySpecialAttributeP10TranslatorPci($tr,$phonemes,$dict_flags){;var __label__;var $tr_addr;var $phonemes_addr;var $dict_flags_addr;var $len;var $p_end;$tr_addr=$tr;$phonemes_addr=$phonemes;$dict_flags_addr=$dict_flags;var $0=$dict_flags_addr;var $and=($0)&3145728;var $cmp=((($and))|0)==0;if($cmp){__label__=4;;}else{__label__=1;;}
$sw_epilog$$if_end$2:do{if(__label__==1){var $1=$phonemes_addr;var $call=_strlen($1);$len=$call;var $2=$len;var $sub=((($2)-1)&4294967295);var $3=$phonemes_addr;var $arrayidx=(($3+$sub)&4294967295);$p_end=$arrayidx;var $4=$tr_addr;var $translator_name=(($4+280)&4294967295);var $5=HEAP32[(($translator_name)>>2)];var $cond=((($5))|0)==29295;if(!($cond)){__label__=4;break $sw_epilog$$if_end$2;}
var $6=$p_end;var $arrayidx1=(($6)&4294967295);var $7=HEAP8[($arrayidx1)];var $conv=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $call2=__Z11PhonemeCodej(106);var $cmp3=((($conv))|0)==((($call2))|0);if(!($cmp3)){__label__=4;break $sw_epilog$$if_end$2;}
var $8=$p_end;var $arrayidx5=(($8)&4294967295);HEAP8[($arrayidx5)]=6;var $call6=__Z11PhonemeCodej(105);var $conv7=((($call6))&255);var $9=$p_end;var $arrayidx8=(($9+1)&4294967295);HEAP8[($arrayidx8)]=$conv7;var $10=$p_end;var $arrayidx9=(($10+2)&4294967295);HEAP8[($arrayidx9)]=0;;}}while(0);;return;return;}
function __Z22ApplySpecialAttribute2P10TranslatorPci($tr,$phonemes,$dict_flags){;var __label__;var $tr_addr;var $phonemes_addr;var $dict_flags_addr;var $ix;var $len;var $p;$tr_addr=$tr;$phonemes_addr=$phonemes;$dict_flags_addr=$dict_flags;var $0=$phonemes_addr;var $call=_strlen($0);$len=$call;var $1=$tr_addr;var $langopts=(($1)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx=(($param+60)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];var $and=($2)&2;var $tobool=((($and))|0)!=0;if($tobool){__label__=1;;}else{__label__=14;;}
$if_then$$if_end37$2:do{if(__label__==1){$ix=0;;while(1){var $3=$ix;var $4=$len;var $sub=((($4)-1)&4294967295);var $cmp=((($3))|0)<((($sub))|0);if(!($cmp)){__label__=14;break $if_then$$if_end37$2;}
var $5=$ix;var $6=$phonemes_addr;var $arrayidx1=(($6+$5)&4294967295);var $7=HEAP8[($arrayidx1)];var $conv=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $cmp2=((($conv))|0)==6;var $8=$ix;var $add=((($8)+1)&4294967295);if($cmp2){__label__=4;break;}
$ix=$add;__label__=2;continue;}
var $9=$phonemes_addr;var $arrayidx4=(($9+$add)&4294967295);$p=$arrayidx4;var $10=$dict_flags_addr;var $and5=($10)&2097152;var $cmp6=((($and5))|0)!=0;var $11=$p;var $12=HEAP8[($11)];var $conv8=(tempInt=(($12)),(tempInt>=128?tempInt-256:tempInt));if($cmp6){__label__=5;;}else{__label__=9;;}
if(__label__==5){var $call9=__Z11PhonemeCodej(69);var $cmp10=((($conv8))|0)==((($call9))|0);if($cmp10){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $call12=__Z11PhonemeCodej(101);var $conv13=((($call12))&255);var $13=$p;HEAP8[($13)]=$conv13;;}
var $14=$p;var $15=HEAP8[($14)];var $conv14=(tempInt=(($15)),(tempInt>=128?tempInt-256:tempInt));var $call15=__Z11PhonemeCodej(79);var $cmp16=((($conv14))|0)==((($call15))|0);if(!($cmp16)){__label__=14;break $if_then$$if_end37$2;}
var $call18=__Z11PhonemeCodej(111);var $conv19=((($call18))&255);var $16=$p;HEAP8[($16)]=$conv19;;}
else if(__label__==9){var $call22=__Z11PhonemeCodej(101);var $cmp23=((($conv8))|0)==((($call22))|0);if($cmp23){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $call25=__Z11PhonemeCodej(69);var $conv26=((($call25))&255);var $17=$p;HEAP8[($17)]=$conv26;;}
var $18=$p;var $19=HEAP8[($18)];var $conv28=(tempInt=(($19)),(tempInt>=128?tempInt-256:tempInt));var $call29=__Z11PhonemeCodej(111);var $cmp30=((($conv28))|0)==((($call29))|0);if(!($cmp30)){__label__=14;break $if_then$$if_end37$2;}
var $call32=__Z11PhonemeCodej(79);var $conv33=((($call32))&255);var $20=$p;HEAP8[($20)]=$conv33;;}}}while(0);;return;return;}
function __Z17TransposeAlphabetP10TranslatorPc($tr,$text){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $text_addr;var $c=__stackBase__;var $c2;var $ix;var $offset;var $min;var $max;var $p;var $p2;var $all_alpha;var $bits;var $acc;var $pairs_start;var $pairs_list;$tr_addr=$tr;$text_addr=$text;var $0=$text_addr;$p=$0;var $1=$text_addr;$p2=$1;$all_alpha=1;var $2=$tr_addr;var $transpose_min=(($2+288)&4294967295);var $3=HEAP32[(($transpose_min)>>2)];var $sub=((($3)-1)&4294967295);$offset=$sub;var $4=$tr_addr;var $transpose_min1=(($4+288)&4294967295);var $5=HEAP32[(($transpose_min1)>>2)];$min=$5;var $6=$tr_addr;var $transpose_max=(($6+284)&4294967295);var $7=HEAP32[(($transpose_max)>>2)];$max=$7;var $8=$max;var $9=$min;var $_neg=(((-($9)))&4294967295);var $sub2=((($8)+2)&4294967295);var $add=((($sub2)+($_neg))&4294967295);$pairs_start=$add;;$do_body$2:while(1){var $10=$p;var $call=__Z7utf8_inPiPKc($c,$10);var $11=$p;var $add_ptr=(($11+$call)&4294967295);$p=$add_ptr;var $12=HEAP32[(($c)>>2)];var $13=$min;var $cmp=((($12))|0)>=((($13))|0);if($cmp){__lastLabel__=1;__label__=2;;}else{__lastLabel__=1;__label__=4;;}
$land_lhs_true$$if_else$4:do{if(__label__==2){var $14=HEAP32[(($c)>>2)];var $15=$max;var $cmp3=((($14))|0)<=((($15))|0);if($cmp3){__lastLabel__=2;;}else{__lastLabel__=2;__label__=4;break $land_lhs_true$$if_else$4;}
var $16=HEAP32[(($c)>>2)];var $17=$offset;var $sub4=((($16)-($17))&4294967295);var $conv=((($sub4))&255);var $18=$p2;var $incdec_ptr=(($18+1)&4294967295);$p2=$incdec_ptr;HEAP8[($18)]=$conv;__label__=6;break $land_lhs_true$$if_else$4;}}while(0);$do_cond$$if_else$7:do{if(__label__==4){var $19=__lastLabel__==2?$14:($12);var $cmp5=((($19))|0)!=0;if(!($cmp5)){__label__=6;break $do_cond$$if_else$7;}
var $20=HEAP32[(($c)>>2)];var $21=$p2;var $call7=__Z8utf8_outjPc($20,$21);var $22=$p2;var $add_ptr8=(($22+$call7)&4294967295);$p2=$add_ptr8;$all_alpha=0;;}}while(0);var $23=HEAP32[(($c)>>2)];var $cmp10=((($23))|0)!=0;if($cmp10){__label__=1;continue $do_body$2;}else{__label__=7;break $do_body$2;}}
var $24=$p2;HEAP8[($24)]=0;var $25=$all_alpha;var $tobool=((($25))|0)!=0;if($tobool){__label__=8;;}else{__label__=21;;}
if(__label__==8){$acc=0;$bits=0;var $26=$text_addr;$p=$26;var $27=$text_addr;$p2=$27;var $28=$p;var $incdec_ptr121=(($28+1)&4294967295);$p=$incdec_ptr121;var $29=HEAP8[($28)];var $conv132=(tempInt=(($29)),(tempInt>=128?tempInt-256:tempInt));HEAP32[(($c)>>2)]=$conv132;var $cmp143=((($conv132))|0)!=0;if($cmp143){__label__=9;;}else{__label__=18;;}
$while_body$$while_end$14:do{if(__label__==9){$while_body$15:while(1){var $30=$tr_addr;var $frequent_pairs=(($30+8268)&4294967295);var $31=HEAP32[(($frequent_pairs)>>2)];$pairs_list=$31;var $cmp15=((($31))|0)!=0;if($cmp15){__label__=10;;}else{__label__=15;;}
$if_then16$$if_end28$17:do{if(__label__==10){var $32=HEAP32[(($c)>>2)];var $33=$p;var $34=HEAP8[($33)];var $conv17=(tempInt=(($34)),(tempInt>=128?tempInt-256:tempInt));var $shl=((($conv17)*256)&4294967295);var $add18=((($shl)+($32))&4294967295);$c2=$add18;$ix=0;;while(1){var $35=$c2;var $36=$ix;var $37=$pairs_list;var $arrayidx=(($37+2*$36)&4294967295);var $38=HEAP16[(($arrayidx)>>1)];var $conv19=(tempInt=(($38)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp20=((($35))|0)>=((($conv19))|0);if(!($cmp20)){__label__=15;break $if_then16$$if_end28$17;}
var $39=$c2;var $40=$ix;var $41=$pairs_list;var $arrayidx21=(($41+2*$40)&4294967295);var $42=HEAP16[(($arrayidx21)>>1)];var $conv22=(tempInt=(($42)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp23=((($39))|0)==((($conv22))|0);var $43=$ix;if($cmp23){__label__=13;break;}
var $inc=((($43)+1)&4294967295);$ix=$inc;__label__=11;continue;}
var $44=$pairs_start;var $add25=((($44)+($43))&4294967295);HEAP32[(($c)>>2)]=$add25;var $45=$p;var $incdec_ptr26=(($45+1)&4294967295);$p=$incdec_ptr26;;}}while(0);var $46=$acc;var $shl29=((($46)*64)&4294967295);var $47=HEAP32[(($c)>>2)];var $and=($47)&63;var $add30=((($and)+($shl29))&4294967295);$acc=$add30;var $48=$bits;var $add31=((($48)+6)&4294967295);$bits=$add31;var $cmp32=((($add31))|0)>=8;if($cmp32){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $49=$bits;var $sub34=((($49)-8)&4294967295);$bits=$sub34;var $50=$acc;var $51=$bits;var $shr=($50)>>((($51))|0);var $conv35=((($shr))&255);var $52=$p2;var $incdec_ptr36=(($52+1)&4294967295);$p2=$incdec_ptr36;HEAP8[($52)]=$conv35;;}
var $53=$p;var $incdec_ptr12=(($53+1)&4294967295);$p=$incdec_ptr12;var $54=HEAP8[($53)];var $conv13=(tempInt=(($54)),(tempInt>=128?tempInt-256:tempInt));HEAP32[(($c)>>2)]=$conv13;var $cmp14=((($conv13))|0)!=0;if($cmp14){__label__=9;continue $while_body$15;}else{__label__=18;break $while_body$$while_end$14;}}}}while(0);var $55=$bits;var $cmp38=((($55))|0)>0;if($cmp38){__label__=19;;}else{__label__=20;;}
if(__label__==19){var $56=$acc;var $57=$bits;var $sub40=((8-($57))&4294967295);var $shl41=($56)<<($sub40);var $conv42=((($shl41))&255);var $58=$p2;var $incdec_ptr43=(($58+1)&4294967295);$p2=$incdec_ptr43;HEAP8[($58)]=$conv42;;}
var $59=$p2;HEAP8[($59)]=0;var $60=$p2;var $61=$text_addr;var $sub_ptr_lhs_cast=($60);var $sub_ptr_rhs_cast=($61);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);var $or=($sub_ptr_sub)|64;$retval=$or;;}
else if(__label__==21){var $62=$p2;var $63=$text_addr;var $sub_ptr_lhs_cast46=($62);var $sub_ptr_rhs_cast47=($63);var $sub_ptr_sub48=((($sub_ptr_lhs_cast46)-($sub_ptr_rhs_cast47))&4294967295);$retval=$sub_ptr_sub48;;}
var $64=$retval;STACKTOP=__stackBase__;return $64;return null;}
function __Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($tr,$wordptr,$ph_out,$flags,$end_flags,$wtab){var __stackBase__=STACKTOP;STACKTOP+=164;_memset(__stackBase__,0,164);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $wordptr_addr;var $ph_out_addr;var $flags_addr;var $end_flags_addr;var $wtab_addr;var $length;var $found;var $word1;var $word2;var $c;var $nbytes;var $len;var $word=__stackBase__;var $letter=__stackBase__+160;$tr_addr=$tr;$wordptr_addr=$wordptr;$ph_out_addr=$ph_out;$flags_addr=$flags;$end_flags_addr=$end_flags;$wtab_addr=$wtab;$length=0;var $0=$wordptr_addr;var $1=HEAP32[(($0)>>2)];$word1=$1;$word2=$1;;$while_cond$2:while(1){var $2=$word2;var $call=__Z11utf8_nbytesPKc($2);$nbytes=$call;var $3=$word2;var $arrayidx=(($3+$call)&4294967295);var $4=HEAP8[($arrayidx)];var $conv=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)==32;if(!($cmp)){__label__=2;break $while_cond$2;}
var $6=$nbytes;var $add=((($6)+1)&4294967295);var $7=$word2;var $arrayidx1=(($7+$add)&4294967295);var $8=HEAP8[($arrayidx1)];var $conv2=(tempInt=(($8)),(tempInt>=128?tempInt-256:tempInt));var $cmp3=((($conv2))|0)==46;var $9=$length;if($cmp3){__lastLabel__=3;;}else{__lastLabel__=3;__label__=5;break $while_cond$2;}
var $arrayidx4=(($word+$9)&4294967295);var $10=$word2;var $11=$nbytes;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$10;$dest$=$arrayidx4;$stop$=$src$+$11;if(($dest$%4)==($src$%4)&&$11>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $12=$nbytes;var $13=$length;var $add5=((($13)+($12))&4294967295);$length=$add5;var $14=$length;var $inc=((($14)+1)&4294967295);$length=$inc;var $arrayidx6=(($word+$14)&4294967295);HEAP8[($arrayidx6)]=46;var $15=$nbytes;var $add7=((($15)+3)&4294967295);var $16=$word2;var $add_ptr=(($16+$add7)&4294967295);$word2=$add_ptr;__label__=1;continue $while_cond$2;}
if(__label__==2){var $5=$length;__lastLabel__=2;;}
var $17=__lastLabel__==2?$5:($9);var $cmp8=((($17))|0)>0;if($cmp8){__label__=6;;}else{__label__=12;;}
$if_then$$if_end26$9:do{if(__label__==6){$nbytes=0;;while(1){var $18=$nbytes;var $19=$word2;var $arrayidx10=(($19+$18)&4294967295);var $20=HEAPU8[($arrayidx10)];$c=$20;var $conv11=((($20))&255);var $cmp12=((($conv11))|0)!=0;if(!($cmp12)){__label__=10;break;}
var $21=$c;var $conv14=((($21))&255);var $cmp15=((($conv14))|0)!=32;if(!($cmp15)){__label__=10;break;}
var $22=$nbytes;var $inc18=((($22)+1)&4294967295);$nbytes=$inc18;__label__=7;continue;}
var $23=$length;var $arrayidx20=(($word+$23)&4294967295);var $24=$word2;var $25=$nbytes;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$24;$dest$=$arrayidx20;$stop$=$src$+$25;if(($dest$%4)==($src$%4)&&$25>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $26=$length;var $27=$nbytes;var $add21=((($27)+($26))&4294967295);var $arrayidx22=(($word+$add21)&4294967295);HEAP8[($arrayidx22)]=0;var $28=$tr_addr;var $arraydecay=(($word)&4294967295);var $29=$word2;var $30=$ph_out_addr;var $31=$flags_addr;var $32=$end_flags_addr;var $33=$wtab_addr;var $call23=__ZL11LookupDict2P10TranslatorPKcS2_PcPjiP8WORD_TAB($28,$arraydecay,$29,$30,$31,$32,$33);$found=$call23;var $tobool=((($call23))|0)!=0;if(!($tobool)){__label__=12;break $if_then$$if_end26$9;}
var $34=$flags_addr;var $arrayidx25=(($34)&4294967295);var $35=HEAP32[(($arrayidx25)>>2)];var $or=($35)|128;HEAP32[(($arrayidx25)>>2)]=$or;var $36=$length;HEAP32[((_dictionary_skipwords)>>2)]=$36;$retval=1;__label__=50;break $if_then$$if_end26$9;}}while(0);if(__label__==12){$length=0;__lastLabel__=12;;$for_cond$19:while(1){var $37=__lastLabel__==19?$inc45:(0);var $cmp27=((($37))|0)<159;if(!($cmp27)){__label__=20;break $for_cond$19;}
var $38=$word1;var $incdec_ptr=(($38+1)&4294967295);$word1=$incdec_ptr;var $39=HEAPU8[($38)];$c=$39;var $conv28=((($39))&255);var $cmp29=((($conv28))|0)==0;if($cmp29){__label__=20;break $for_cond$19;}
var $40=$c;var $conv30=((($40))&255);var $cmp31=((($conv30))|0)==32;if($cmp31){__label__=20;break $for_cond$19;}
var $41=$c;var $conv34=((($41))&255);var $cmp35=((($conv34))|0)==46;if($cmp35){__label__=17;;}else{__label__=19;;}
$land_lhs_true$$if_end43$24:do{if(__label__==17){var $42=$length;var $cmp36=((($42))|0)>0;if(!($cmp36)){__label__=19;break $land_lhs_true$$if_end43$24;}
var $43=$length;var $sub=((($43)-1)&4294967295);var $arrayidx38=(($word+$sub)&4294967295);var $44=HEAP8[($arrayidx38)];var $conv39=(tempInt=(($44)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp=((($conv39)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call40=((($isdigit))&1);var $tobool41=((($call40))|0)!=0;if($tobool41){__label__=20;break $for_cond$19;}}}while(0);var $45=$c;var $46=$length;var $arrayidx44=(($word+$46)&4294967295);HEAP8[($arrayidx44)]=$45;var $47=$length;var $inc45=((($47)+1)&4294967295);$length=$inc45;__lastLabel__=19;__label__=13;continue $for_cond$19;}
var $48=$length;var $arrayidx46=(($word+$48)&4294967295);HEAP8[($arrayidx46)]=0;var $49=$tr_addr;var $arraydecay47=(($word)&4294967295);var $50=$word1;var $51=$ph_out_addr;var $52=$flags_addr;var $53=$end_flags_addr;var $54=$wtab_addr;var $call48=__ZL11LookupDict2P10TranslatorPKcS2_PcPjiP8WORD_TAB($49,$arraydecay47,$50,$51,$52,$53,$54);$found=$call48;var $55=$flags_addr;var $arrayidx49=(($55)&4294967295);var $56=HEAP32[(($arrayidx49)>>2)];var $and=($56)&134217728;var $tobool50=((($and))|0)!=0;if($tobool50){__label__=21;;}else{__label__=25;;}
$if_then51$$if_else66$29:do{if(__label__==21){var $57=$ph_out_addr;var $58=$tr_addr;var $phonemes_repeat=(($58+632)&4294967295);var $arraydecay52=(($phonemes_repeat)&4294967295);var $call53=_strcmp($57,$arraydecay52);var $cmp54=((($call53))|0)==0;var $59=$tr_addr;if($cmp54){__label__=22;;}else{__label__=24;;}
if(__label__==22){var $phonemes_repeat_count=(($59+652)&4294967295);var $60=HEAP32[(($phonemes_repeat_count)>>2)];var $inc56=((($60)+1)&4294967295);HEAP32[(($phonemes_repeat_count)>>2)]=$inc56;var $61=$tr_addr;var $phonemes_repeat_count57=(($61+652)&4294967295);var $62=HEAP32[(($phonemes_repeat_count57)>>2)];var $cmp58=((($62))|0)>3;if(!($cmp58)){__label__=26;break $if_then51$$if_else66$29;}
var $63=$ph_out_addr;var $arrayidx60=(($63)&4294967295);HEAP8[($arrayidx60)]=0;;}
else if(__label__==24){var $phonemes_repeat62=(($59+632)&4294967295);var $arraydecay63=(($phonemes_repeat62)&4294967295);var $64=$ph_out_addr;__Z8strncpy0PcPKci($arraydecay63,$64,20);var $65=$tr_addr;var $phonemes_repeat_count64=(($65+652)&4294967295);HEAP32[(($phonemes_repeat_count64)>>2)]=1;;}}
else if(__label__==25){var $66=$tr_addr;var $phonemes_repeat_count67=(($66+652)&4294967295);HEAP32[(($phonemes_repeat_count67)>>2)]=0;;}}while(0);var $67=$found;var $cmp69=((($67))|0)==0;if($cmp69){__label__=27;;}else{__label__=39;;}
$land_lhs_true70$$if_end117thread_pre_split$37:do{if(__label__==27){var $68=$flags_addr;var $arrayidx71=(($68+4)&4294967295);var $69=HEAP32[(($arrayidx71)>>2)];var $and72=($69)&2048;var $tobool73=((($and72))|0)!=0;if($tobool73){__label__=28;;}else{__label__=31;;}
if(__label__==28){var $arraydecay75=(($word)&4294967295);$word2=$arraydecay75;var $70=$word2;var $71=HEAP8[($70)];var $conv76=(tempInt=(($71)),(tempInt>=128?tempInt-256:tempInt));var $cmp77=((($conv76))|0)==95;if($cmp77){__label__=29;;}else{__label__=30;;}
if(__label__==29){var $72=$word2;var $incdec_ptr79=(($72+1)&4294967295);$word2=$incdec_ptr79;;}
var $73=$word2;var $call81=__Z7utf8_inPiPKc($letter,$73);$len=$call81;var $74=$tr_addr;var $75=HEAP32[(($letter)>>2)];var $76=$ph_out_addr;__Z20LookupAccentedLetterP10TranslatorjPc($74,$75,$76);var $77=$word2;var $78=$len;var $add_ptr82=(($77+$78)&4294967295);$found=$add_ptr82;__lastLabel__=30;;}
else if(__label__==31){var $_pr=$found;__lastLabel__=31;;}
var $79=__lastLabel__==31?$_pr:($add_ptr82);var $cmp84=((($79))|0)==0;if(!($cmp84)){__label__=39;break $land_lhs_true70$$if_end117thread_pre_split$37;}
var $80=$ph_out_addr;var $arrayidx86=(($80)&4294967295);HEAP8[($arrayidx86)]=0;var $81=$end_flags_addr;var $and87=($81)&16;var $tobool88=((($and87))|0)!=0;if($tobool88){__label__=34;;}else{__label__=36;;}
$land_lhs_true89$$if_else99$47:do{if(__label__==34){var $82=$length;var $sub90=((($82)-1)&4294967295);var $arrayidx91=(($word+$sub90)&4294967295);var $83=HEAP8[($arrayidx91)];var $conv92=(tempInt=(($83)),(tempInt>=128?tempInt-256:tempInt));var $cmp93=((($conv92))|0)==101;if(!($cmp93)){__label__=36;break $land_lhs_true89$$if_else99$47;}
var $84=$length;var $sub95=((($84)-1)&4294967295);var $arrayidx96=(($word+$sub95)&4294967295);HEAP8[($arrayidx96)]=0;var $85=$tr_addr;var $arraydecay97=(($word)&4294967295);var $86=$word1;var $87=$ph_out_addr;var $88=$flags_addr;var $89=$end_flags_addr;var $90=$wtab_addr;var $call98=__ZL11LookupDict2P10TranslatorPKcS2_PcPjiP8WORD_TAB($85,$arraydecay97,$86,$87,$88,$89,$90);$found=$call98;__lastLabel__=35;__label__=40;break $land_lhs_true70$$if_end117thread_pre_split$37;}}while(0);var $91=$end_flags_addr;var $and100=($91)&4096;var $tobool101=((($and100))|0)!=0;if(!($tobool101)){__label__=39;break $land_lhs_true70$$if_end117thread_pre_split$37;}
var $92=$length;var $sub103=((($92)-1)&4294967295);var $arrayidx104=(($word+$sub103)&4294967295);var $93=HEAP8[($arrayidx104)];var $conv105=(tempInt=(($93)),(tempInt>=128?tempInt-256:tempInt));var $94=$length;var $sub106=((($94)-2)&4294967295);var $arrayidx107=(($word+$sub106)&4294967295);var $95=HEAP8[($arrayidx107)];var $conv108=(tempInt=(($95)),(tempInt>=128?tempInt-256:tempInt));var $cmp109=((($conv105))|0)==((($conv108))|0);if(!($cmp109)){__label__=39;break $land_lhs_true70$$if_end117thread_pre_split$37;}
var $96=$length;var $sub111=((($96)-1)&4294967295);var $arrayidx112=(($word+$sub111)&4294967295);HEAP8[($arrayidx112)]=0;var $97=$tr_addr;var $arraydecay113=(($word)&4294967295);var $98=$word1;var $99=$ph_out_addr;var $100=$flags_addr;var $101=$end_flags_addr;var $102=$wtab_addr;var $call114=__ZL11LookupDict2P10TranslatorPKcS2_PcPjiP8WORD_TAB($97,$arraydecay113,$98,$99,$100,$101,$102);$found=$call114;__lastLabel__=38;__label__=40;break $land_lhs_true70$$if_end117thread_pre_split$37;}}while(0);if(__label__==39){var $_pr2=$found;__lastLabel__=39;;}
var $103=__lastLabel__==39?$_pr2:(__lastLabel__==35?$call98:($call114));var $tobool118=((($103))|0)!=0;if($tobool118){__label__=41;;}else{__label__=49;;}
if(__label__==41){var $104=$tr_addr;var $langopts=(($104)&4294967295);var $textmode=(($langopts+252)&4294967295);var $105=HEAP8[($textmode)];var $tobool120=(tempInt=(($105)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool120){__label__=42;;}else{__label__=43;;}
if(__label__==42){var $106=$flags_addr;var $107=HEAP32[(($106)>>2)];var $xor=($107)^536870912;HEAP32[(($106)>>2)]=$xor;;}
var $108=$flags_addr;var $109=HEAP32[(($108)>>2)];var $and123=($109)&536870912;var $tobool124=((($and123))|0)!=0;if($tobool124){__label__=44;;}else{__label__=48;;}
if(__label__==44){var $110=$end_flags_addr;var $and126=($110)&2;var $tobool127=((($and126))|0)!=0;if($tobool127){__label__=45;;}else{__label__=47;;}
$if_then128$$if_end138$63:do{if(__label__==45){HEAP8[(((__ZZ14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TABE16word_replacement)&4294967295))]=0;HEAP8[(((__ZZ14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TABE16word_replacement+1)&4294967295))]=32;var $111=$ph_out_addr;var $call129=_sprintf(((__ZZ14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TABE16word_replacement+2)&4294967295),((__str15131)&4294967295),allocate([$111,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $112=$wordptr_addr;var $113=HEAP32[(($112)>>2)];$word1=$113;var $114=$wordptr_addr;HEAP32[(($114)>>2)]=((__ZZ14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TABE16word_replacement+2)&4294967295);var $115=HEAP32[((_option_phonemes)>>2)];var $cmp130=((($115))|0)==2;if(!($cmp130)){__label__=47;break $if_then128$$if_end138$63;}
var $116=$found;var $117=$word1;var $sub_ptr_lhs_cast=($116);var $sub_ptr_rhs_cast=($117);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$len=$sub_ptr_sub;var $arraydecay132=(($word)&4294967295);var $118=$word1;var $119=$len;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$118;$dest$=$arraydecay132;$stop$=$src$+$119;if(($dest$%4)==($src$%4)&&$119>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $120=$len;var $arrayidx133=(($word+$120)&4294967295);HEAP8[($arrayidx133)]=0;var $121=HEAP32[((_f_trans)>>2)];var $arraydecay134=(($word)&4294967295);var $122=$wordptr_addr;var $123=HEAP32[(($122)>>2)];var $call135=_fprintf($121,((__str16132)&4294967295),allocate([$arraydecay134,0,0,0,$123,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}}while(0);var $124=$ph_out_addr;var $arrayidx139=(($124)&4294967295);HEAP8[($arrayidx139)]=0;$retval=0;;}
else if(__label__==48){$retval=1;;}}
else if(__label__==49){var $125=$ph_out_addr;var $arrayidx142=(($125)&4294967295);HEAP8[($arrayidx142)]=0;$retval=0;;}}
var $126=$retval;STACKTOP=__stackBase__;return $126;return null;}
function __ZL11LookupDict2P10TranslatorPKcS2_PcPjiP8WORD_TAB($tr,$word,$word2,$phonetic,$flags,$end_flags,$wtab){var __stackBase__=STACKTOP;STACKTOP+=320;_memset(__stackBase__,0,320);var __label__;var $retval;var $tr_addr;var $word_addr;var $word2_addr;var $phonetic_addr;var $flags_addr;var $end_flags_addr;var $wtab_addr;var $p;var $next;var $hash;var $phoneme_len;var $wlen;var $flag;var $dictionary_flags;var $dictionary_flags2;var $condition_failed;var $n_chars;var $no_phonemes;var $skipwords;var $ix;var $word_end;var $word1;var $wflags;var $word_buf=__stackBase__;var $flags1259;var $ph_decoded=__stackBase__+160;var $textmode;$tr_addr=$tr;$word_addr=$word;$word2_addr=$word2;$phonetic_addr=$phonetic;$flags_addr=$flags;$end_flags_addr=$end_flags;$wtab_addr=$wtab;$condition_failed=0;$wflags=0;var $0=$wtab_addr;var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$wtab_addr;var $flags1=(($1)&4294967295);var $2=HEAP32[(($flags1)>>2)];$wflags=$2;;}
var $3=$word_addr;$word1=$3;var $4=$tr_addr;var $transpose_min=(($4+288)&4294967295);var $5=HEAP32[(($transpose_min)>>2)];var $cmp2=((($5))|0)>0;if($cmp2){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $arraydecay=(($word_buf)&4294967295);var $6=$word_addr;var $call=_strcpy($arraydecay,$6);var $7=$tr_addr;var $arraydecay4=(($word_buf)&4294967295);var $call5=__Z17TransposeAlphabetP10TranslatorPc($7,$arraydecay4);$wlen=$call5;var $arraydecay6=(($word_buf)&4294967295);$word_addr=$arraydecay6;;}
else if(__label__==4){var $8=$word_addr;var $call7=_strlen($8);$wlen=$call7;;}
var $9=$word_addr;var $call9=__Z14HashDictionaryPKc($9);$hash=$call9;var $10=$hash;var $11=$tr_addr;var $dict_hashtab=(($11+1056)&4294967295);var $arrayidx=(($dict_hashtab+$10*4)&4294967295);var $12=HEAP32[(($arrayidx)>>2)];$p=$12;var $cmp10=((($12))|0)==0;if($cmp10){__label__=6;;}else{__label__=9;;}
if(__label__==6){var $13=$flags_addr;var $cmp12=((($13))|0)!=0;if($cmp12){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $14=$flags_addr;HEAP32[(($14)>>2)]=0;;}
$retval=0;;}
else if(__label__==9){$while_cond$14:while(1){var $15=$p;var $16=HEAP8[($15)];var $conv=(tempInt=(($16)),(tempInt>=128?tempInt-256:tempInt));var $cmp16=((($conv))|0)!=0;if(!($cmp16)){__label__=95;break $while_cond$14;}
var $17=$p;var $18=$p;var $arrayidx17=(($18)&4294967295);var $19=HEAP8[($arrayidx17)];var $conv18=(tempInt=(($19)),(tempInt>=128?tempInt-256:tempInt));var $add_ptr=(($17+$conv18)&4294967295);$next=$add_ptr;var $20=$p;var $arrayidx19=(($20+1)&4294967295);var $21=HEAP8[($arrayidx19)];var $conv20=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));var $and=($conv20)&127;var $22=$wlen;var $cmp21=((($and))|0)!=((($22))|0);if($cmp21){__label__=12;;}else{__label__=11;;}
$if_then26$$lor_lhs_false$17:do{if(__label__==11){var $23=$word_addr;var $24=$p;var $arrayidx22=(($24+2)&4294967295);var $25=$wlen;var $and23=($25)&63;var $call24=_memcmp($23,$arrayidx22,$and23);var $cmp25=((($call24))|0)!=0;if($cmp25){__label__=12;break $if_then26$$lor_lhs_false$17;}
var $27=$word2_addr;$word_end=$27;$dictionary_flags=0;$dictionary_flags2=0;var $28=$p;var $arrayidx28=(($28+1)&4294967295);var $29=HEAP8[($arrayidx28)];var $conv29=(tempInt=(($29)),(tempInt>=128?tempInt-256:tempInt));var $and30=($conv29)&128;$no_phonemes=$and30;var $30=$p;var $arrayidx31=(($30+1)&4294967295);var $31=HEAP8[($arrayidx31)];var $conv32=(tempInt=(($31)),(tempInt>=128?tempInt-256:tempInt));var $and33=($conv32)&63;var $add=((($and33)+2)&4294967295);var $32=$p;var $add_ptr34=(($32+$add)&4294967295);$p=$add_ptr34;var $33=$no_phonemes;var $tobool=((($33))|0)!=0;var $34=$phonetic_addr;if($tobool){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $arrayidx36=(($34)&4294967295);HEAP8[($arrayidx36)]=0;$phoneme_len=0;;}
else if(__label__==15){var $35=$p;var $call38=_strcpy($34,$35);var $36=$p;var $call39=_strlen($36);$phoneme_len=$call39;var $37=$phoneme_len;var $add40=((($37)+1)&4294967295);var $38=$p;var $add_ptr41=(($38+$add40)&4294967295);$p=$add_ptr41;;}
$while_cond43$23:while(1){var $39=$p;var $40=$next;var $cmp44=((($39))>>>0)<((($40))>>>0);if(!($cmp44)){__label__=39;break $while_cond43$23;}
var $41=$p;var $incdec_ptr=(($41+1)&4294967295);$p=$incdec_ptr;var $42=HEAP8[($41)];$flag=$42;var $43=$flag;var $conv46=((($43))&255);var $cmp47=((($conv46))|0)>=100;var $44=$flag;var $conv49=((($44))&255);if($cmp47){__label__=18;;}else{__label__=23;;}
if(__label__==18){var $cmp50=((($conv49))|0)>=132;var $45=$tr_addr;var $dict_condition=(($45+692)&4294967295);var $46=HEAPU32[(($dict_condition)>>2)];var $47=$flag;var $conv52=((($47))&255);if($cmp50){__label__=19;;}else{__label__=21;;}
if(__label__==19){var $sub=((($conv52)-132)&4294967295);var $shl=1<<($sub);var $and53=($shl)&($46);var $cmp54=((($and53))|0)!=0;if(!($cmp54)){__label__=16;continue $while_cond43$23;}
$condition_failed=1;__label__=16;continue $while_cond43$23;}
else if(__label__==21){var $sub60=((($conv52)-100)&4294967295);var $shl61=1<<($sub60);var $and62=($shl61)&($46);var $cmp63=((($and62))|0)==0;if(!($cmp63)){__label__=16;continue $while_cond43$23;}
$condition_failed=1;__label__=16;continue $while_cond43$23;}}
else if(__label__==23){var $cmp69=((($conv49))|0)>80;if($cmp69){__label__=24;;}else{__label__=33;;}
if(__label__==24){var $48=$next;var $49=$p;var $sub_ptr_lhs_cast=($48);var $sub_ptr_rhs_cast=($49);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$n_chars=$sub_ptr_sub;var $50=$flag;var $conv71=((($50))&255);var $sub72=((($conv71)-80)&4294967295);$skipwords=$sub72;$ix=0;var $51=$ix;var $52=$skipwords;var $cmp732=((($51))|0)<=((($52))|0);if($cmp732){__label__=25;;}else{__label__=28;;}
$for_body$$for_end$36:do{if(__label__==25){while(1){var $53=$wflags;var $and74=($53)&3072;var $tobool75=((($and74))|0)!=0;if($tobool75){__label__=26;;}else{__label__=27;;}
if(__label__==26){$condition_failed=1;;}
var $54=$ix;var $inc=((($54)+1)&4294967295);$ix=$inc;var $55=$ix;var $56=$skipwords;var $cmp73=((($55))|0)<=((($56))|0);if($cmp73){__label__=25;continue;}else{__label__=28;break $for_body$$for_end$36;}}}}while(0);var $57=$word2_addr;var $58=$p;var $59=$n_chars;var $call78=_memcmp($57,$58,$59);var $cmp79=((($call78))|0)!=0;if($cmp79){__label__=29;break $while_cond43$23;}
var $_pr=$condition_failed;var $tobool82=((($_pr))|0)!=0;if($tobool82){__label__=31;break $while_cond43$23;}
var $61=$dictionary_flags;var $or=($61)|128;$dictionary_flags=$or;var $62=$skipwords;HEAP32[((_dictionary_skipwords)>>2)]=$62;var $63=$next;$p=$63;var $64=$word2_addr;var $65=$n_chars;var $add_ptr85=(($64+$65)&4294967295);$word_end=$add_ptr85;__label__=16;continue $while_cond43$23;}
else if(__label__==33){var $66=$flag;var $conv87=((($66))&255);var $cmp88=((($conv87))|0)>64;if($cmp88){__label__=34;;}else{__label__=36;;}
if(__label__==34){var $67=$dictionary_flags;var $and90=($67)&-16;var $68=$flag;var $conv91=((($68))&255);var $and92=($conv91)&15;var $or93=($and92)|($and90);$dictionary_flags=$or93;var $69=$flag;var $conv94=((($69))&255);var $and95=($conv94)&12;var $cmp96=((($and95))|0)==12;if(!($cmp96)){__label__=16;continue $while_cond43$23;}
var $70=$dictionary_flags;var $or98=($70)|2048;$dictionary_flags=$or98;__label__=16;continue $while_cond43$23;}
else if(__label__==36){var $71=$flag;var $conv101=((($71))&255);var $cmp102=((($conv101))|0)>=32;var $72=$flag;var $conv104=((($72))&255);if($cmp102){__label__=37;;}else{__label__=38;;}
if(__label__==37){var $sub105=((($conv104)-32)&4294967295);var $shl106=1<<($sub105);var $73=$dictionary_flags2;var $or107=($73)|($shl106);$dictionary_flags2=$or107;__label__=16;continue $while_cond43$23;}
else if(__label__==38){var $shl110=1<<($conv104);var $74=$dictionary_flags;var $or111=($74)|($shl110);$dictionary_flags=$or111;__label__=16;continue $while_cond43$23;}}}}}
$while_end$$if_end81_thread$$if_then83$53:do{if(__label__==29){$condition_failed=1;__label__=31;break $while_end$$if_end81_thread$$if_then83$53;}}while(0);if(__label__==31){var $60=$next;$p=$60;;}
var $75=$condition_failed;var $tobool116=((($75))|0)!=0;if($tobool116){__label__=40;;}else{__label__=41;;}
if(__label__==40){$condition_failed=0;__label__=9;continue $while_cond$14;}
else if(__label__==41){var $76=$end_flags_addr;var $and119=($76)&4;var $cmp120=((($and119))|0)==0;if($cmp120){__label__=42;;}else{__label__=43;;}
if(__label__==42){var $77=$dictionary_flags;var $and122=($77)&262144;var $tobool123=((($and122))|0)!=0;if($tobool123){__label__=9;continue $while_cond$14;}}
var $78=$end_flags_addr;var $and127=($78)&1024;var $tobool128=((($and127))|0)!=0;if($tobool128){__label__=44;;}else{__label__=45;;}
if(__label__==44){var $79=$dictionary_flags;var $and129=($79)&1536;var $tobool130=((($and129))|0)!=0;if($tobool130){__label__=9;continue $while_cond$14;}}
var $80=$end_flags_addr;var $and133=($80)&4;var $tobool134=((($and133))|0)!=0;if($tobool134){__label__=46;;}else{__label__=49;;}
$if_then135$$if_end147$67:do{if(__label__==46){var $81=$dictionary_flags;var $and136=($81)&512;var $tobool137=((($and136))|0)!=0;if($tobool137){__label__=9;continue $while_cond$14;}
var $82=$dictionary_flags;var $and140=($82)&1024;var $tobool141=((($and140))|0)!=0;if(!($tobool141)){__label__=49;break $if_then135$$if_end147$67;}
var $83=$end_flags_addr;var $and143=($83)&8;var $cmp144=((($and143))|0)==0;if($cmp144){__label__=9;continue $while_cond$14;}}}while(0);var $84=$dictionary_flags2;var $and148=($84)&4096;var $tobool149=((($and148))|0)!=0;if($tobool149){__label__=50;;}else{__label__=51;;}
if(__label__==50){var $85=$wflags;var $and151=($85)&16384;var $tobool152=((($and151))|0)!=0;if(!($tobool152)){__label__=9;continue $while_cond$14;}}
var $86=$dictionary_flags2;var $and156=($86)&512;var $tobool157=((($and156))|0)!=0;if($tobool157){__label__=52;;}else{__label__=53;;}
if(__label__==52){var $87=$wflags;var $and159=($87)&2;var $tobool160=((($and159))|0)!=0;if(!($tobool160)){__label__=9;continue $while_cond$14;}}
var $88=$dictionary_flags2;var $and164=($88)&1024;var $tobool165=((($and164))|0)!=0;if($tobool165){__label__=54;;}else{__label__=55;;}
if(__label__==54){var $89=$wflags;var $and167=($89)&1;var $tobool168=((($and167))|0)!=0;if(!($tobool168)){__label__=9;continue $while_cond$14;}}
var $90=$dictionary_flags;var $and172=($90)&33554432;var $tobool173=((($and172))|0)!=0;if($tobool173){__label__=56;;}else{__label__=57;;}
if(__label__==56){var $91=$wflags;var $and175=($91)&65536;var $tobool176=((($and175))|0)!=0;if(!($tobool176)){__label__=9;continue $while_cond$14;}}
var $92=$dictionary_flags;var $and180=($92)&16384;var $tobool181=((($and180))|0)!=0;if($tobool181){__label__=58;;}else{__label__=59;;}
if(__label__==58){var $93=$word_end;var $94=$tr_addr;var $clause_end=(($94+8292)&4294967295);var $95=HEAPU32[(($clause_end)>>2)];var $cmp183=((($93))>>>0)<((($95))>>>0);if($cmp183){__label__=9;continue $while_cond$14;}}
var $96=$dictionary_flags;var $and186=($96)&32768;var $tobool187=((($and186))|0)!=0;if($tobool187){__label__=60;;}else{__label__=61;;}
if(__label__==60){var $97=$wtab_addr;var $flags189=(($97)&4294967295);var $98=HEAP32[(($flags189)>>2)];var $and190=($98)&512;var $tobool191=((($and190))|0)!=0;if(!($tobool191)){__label__=9;continue $while_cond$14;}}
var $99=$dictionary_flags2;var $and194=($99)&8192;var $tobool195=((($and194))|0)!=0;if($tobool195){__label__=62;;}else{__label__=63;;}
if(__label__==62){var $100=$tr_addr;var $clause_terminator=(($100+8324)&4294967295);var $101=HEAP32[(($clause_terminator)>>2)];var $and197=($101)&524288;var $tobool198=((($and197))|0)!=0;if(!($tobool198)){__label__=9;continue $while_cond$14;}}
var $102=$dictionary_flags2;var $and201=($102)&16;var $tobool202=((($and201))|0)!=0;if($tobool202){__label__=64;;}else{__label__=67;;}
$if_then203$$if_end213$93:do{if(__label__==64){var $103=$tr_addr;var $expect_verb=(($103+8272)&4294967295);var $104=HEAP32[(($expect_verb)>>2)];var $tobool204=((($104))|0)!=0;if($tobool204){__label__=67;break $if_then203$$if_end213$93;}
var $105=$tr_addr;var $expect_verb_s=(($105+8280)&4294967295);var $106=HEAP32[(($expect_verb_s)>>2)];var $tobool206=((($106))|0)!=0;if(!($tobool206)){__label__=9;continue $while_cond$14;}
var $107=$end_flags_addr;var $and208=($107)&8;var $tobool209=((($and208))|0)!=0;if(!($tobool209)){__label__=9;continue $while_cond$14;}}}while(0);var $108=$dictionary_flags2;var $and214=($108)&64;var $tobool215=((($and214))|0)!=0;if($tobool215){__label__=68;;}else{__label__=69;;}
if(__label__==68){var $109=$tr_addr;var $expect_past=(($109+8276)&4294967295);var $110=HEAP32[(($expect_past)>>2)];var $tobool217=((($110))|0)!=0;if(!($tobool217)){__label__=9;continue $while_cond$14;}}
var $111=$dictionary_flags2;var $and221=($111)&32;var $tobool222=((($and221))|0)!=0;if($tobool222){__label__=70;;}else{__label__=71;;}
if(__label__==70){var $112=$tr_addr;var $expect_noun=(($112+8284)&4294967295);var $113=HEAP32[(($expect_noun)>>2)];var $tobool224=((($113))|0)!=0;if(!($tobool224)){__label__=9;continue $while_cond$14;}}
var $114=$dictionary_flags;var $and228=($114)&2097152;var $tobool229=((($and228))|0)!=0;if(!($tobool229)){__label__=74;break $while_cond$14;}
var $115=$tr_addr;var $translator_name=(($115+280)&4294967295);var $116=HEAP32[(($translator_name)>>2)];var $cmp231=((($116))|0)==26741;if(!($cmp231)){__label__=74;break $while_cond$14;}
var $117=$tr_addr;var $prev_dict_flags=(($117+8320)&4294967295);var $118=HEAP32[(($prev_dict_flags)>>2)];var $and233=($118)&1048576;var $tobool234=((($and233))|0)!=0;if($tobool234){__label__=74;break $while_cond$14;}else{__label__=9;continue $while_cond$14;}}}}while(0);var $26=$next;$p=$26;__label__=9;continue $while_cond$14;}
if(__label__==95){$retval=0;;}
else if(__label__==74){var $119=$flags_addr;var $cmp238=((($119))|0)!=0;if($cmp238){__label__=75;;}else{__label__=76;;}
if(__label__==75){var $120=$dictionary_flags;var $or240=($120)|1073741824;var $121=$flags_addr;var $arrayidx241=(($121)&4294967295);HEAP32[(($arrayidx241)>>2)]=$or240;var $122=$dictionary_flags2;var $123=$flags_addr;var $arrayidx242=(($123+4)&4294967295);HEAP32[(($arrayidx242)>>2)]=$122;;}
var $124=$phoneme_len;var $cmp244=((($124))|0)==0;if($cmp244){__label__=77;;}else{__label__=80;;}
if(__label__==77){var $125=HEAP32[((_option_phonemes)>>2)];var $cmp246=((($125))|0)==2;if($cmp246){__label__=78;;}else{__label__=79;;}
if(__label__==78){var $126=HEAP32[((_f_trans)>>2)];var $127=$word1;var $128=$flags_addr;var $call248=__Z22print_dictionary_flagsPj($128);var $call249=_fprintf($126,((__str28144)&4294967295),allocate([$127,0,0,0,((__ZZ22print_dictionary_flagsPjE3buf)&4294967295),0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
$retval=0;;}
else if(__label__==80){var $129=$flags_addr;var $cmp252=((($129))|0)!=0;if($cmp252){__label__=81;;}else{__label__=82;;}
if(__label__==81){var $130=$flags_addr;var $arrayidx254=(($130)&4294967295);var $131=HEAP32[(($arrayidx254)>>2)];var $or255=($131)|-2147483648;HEAP32[(($arrayidx254)>>2)]=$or255;;}
var $132=HEAP32[((_option_phonemes)>>2)];var $cmp257=((($132))|0)==2;if($cmp257){__label__=83;;}else{__label__=94;;}
$if_then258$$if_end296$122:do{if(__label__==83){$flags1259=0;var $133=$phonetic_addr;var $arraydecay260=(($ph_decoded)&4294967295);__Z14DecodePhonemesPKcPc($133,$arraydecay260);var $134=$flags_addr;var $cmp261=((($134))|0)!=0;if($cmp261){__label__=84;;}else{__label__=85;;}
if(__label__==84){var $135=$flags_addr;var $arrayidx263=(($135)&4294967295);var $136=HEAP32[(($arrayidx263)>>2)];$flags1259=$136;;}
var $137=$dictionary_flags;var $and265=($137)&536870912;var $cmp266=((($and265))|0)==0;if($cmp266){__label__=86;;}else{__label__=87;;}
if(__label__==86){$textmode=0;;}
else if(__label__==87){$textmode=1;;}
var $138=$textmode;var $139=HEAP32[((_translator)>>2)];var $langopts=(($139)&4294967295);var $textmode270=(($langopts+252)&4294967295);var $140=HEAP8[($textmode270)];var $conv271=(tempInt=(($140)),(tempInt>=128?tempInt-256:tempInt));var $cmp272=((($138))|0)==((($conv271))|0);if(!($cmp272)){__label__=94;break $if_then258$$if_end296$122;}
var $141=HEAP32[((_dictionary_skipwords)>>2)];var $tobool274=((($141))|0)!=0;if($tobool274){__label__=90;;}else{__label__=92;;}
$land_lhs_true275$$if_else289$132:do{if(__label__==90){var $142=$wtab_addr;var $cmp276=((($142))|0)!=0;if(!($cmp276)){__label__=92;break $land_lhs_true275$$if_else289$132;}
var $arraydecay278=(($word_buf)&4294967295);var $143=$word2_addr;var $144=$word_end;var $145=$word2_addr;var $sub_ptr_lhs_cast279=($144);var $sub_ptr_rhs_cast280=($145);var $sub_ptr_sub281=((($sub_ptr_lhs_cast279)-($sub_ptr_rhs_cast280))&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$143;$dest$=$arraydecay278;$stop$=$src$+$sub_ptr_sub281;if(($dest$%4)==($src$%4)&&$sub_ptr_sub281>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $146=$word_end;var $147=$word2_addr;var $sub_ptr_lhs_cast282=($146);var $sub_ptr_rhs_cast283=($147);var $sub_ptr_rhs_cast283_neg=(((-($sub_ptr_rhs_cast283)))&4294967295);var $sub_ptr_sub284=((($sub_ptr_lhs_cast282)-1)&4294967295);var $sub285=((($sub_ptr_sub284)+($sub_ptr_rhs_cast283_neg))&4294967295);var $arrayidx286=(($word_buf+$sub285)&4294967295);HEAP8[($arrayidx286)]=0;var $148=HEAP32[((_f_trans)>>2)];var $149=$word1;var $arraydecay287=(($word_buf)&4294967295);var $call288=_fprintf($148,((__str29145)&4294967295),allocate([$149,0,0,0,$arraydecay287,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));__label__=93;break $land_lhs_true275$$if_else289$132;}}while(0);if(__label__==92){var $150=HEAP32[((_f_trans)>>2)];var $151=$word1;var $call290=_fprintf($150,((__str30146)&4294967295),allocate([$151,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
var $152=HEAP32[((_f_trans)>>2)];var $arraydecay292=(($ph_decoded)&4294967295);var $153=$flags_addr;var $call293=__Z22print_dictionary_flagsPj($153);var $call294=_fprintf($152,((__str31147)&4294967295),allocate([$arraydecay292,0,0,0,((__ZZ22print_dictionary_flagsPjE3buf)&4294967295),0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}}while(0);var $154=$word_end;$retval=$154;;}}}
var $155=$retval;STACKTOP=__stackBase__;return $155;return null;}
function __Z11LookupFlagsP10TranslatorPKc($tr,$word){var __stackBase__=STACKTOP;STACKTOP+=104;_memset(__stackBase__,0,104);var __label__;var $tr_addr;var $word_addr;var $buf=__stackBase__;var $word1=__stackBase__+100;$tr_addr=$tr;$word_addr=$word;HEAP32[((((__ZZ11LookupFlagsP10TranslatorPKcE5flags+4)&4294967295))>>2)]=0;HEAP32[((((__ZZ11LookupFlagsP10TranslatorPKcE5flags)&4294967295))>>2)]=0;var $0=$word_addr;HEAP32[(($word1)>>2)]=$0;var $1=$tr_addr;var $arraydecay=(($buf)&4294967295);var $call=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($1,$word1,$arraydecay,((__ZZ11LookupFlagsP10TranslatorPKcE5flags)&4294967295),0,0);var $2=HEAP32[((((__ZZ11LookupFlagsP10TranslatorPKcE5flags)&4294967295))>>2)];STACKTOP=__stackBase__;return $2;return null;}
function __Z12RemoveEndingP10TranslatorPciS1_($tr,$word,$end_type,$word_copy){;var __label__;var __lastLabel__=null;var $tr_addr;var $word_addr;var $end_type_addr;var $word_copy_addr;var $i;var $word_end;var $len_ending;var $end_flags;var $p;var $len;$tr_addr=$tr;$word_addr=$word;$end_type_addr=$end_type;$word_copy_addr=$word_copy;var $0=$word_addr;$word_end=$0;var $1=$word_end;var $2=HEAP8[($1)];var $conv8=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));var $cmp10=((($conv8))|0)!=32;var $3=$word_end;if($cmp10){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=4;;}
$for_body$$for_end$2:do{if(__label__==1){while(1){var $4=__lastLabel__==3?$10:($3);var $5=HEAP8[($4)];var $conv1=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $cmp2=((($conv1))|0)==69;if($cmp2){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $6=$word_end;HEAP8[($6)]=101;;}
var $7=$word_end;var $incdec_ptr=(($7+1)&4294967295);$word_end=$incdec_ptr;var $8=$word_end;var $9=HEAP8[($8)];var $conv=(tempInt=(($9)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)!=32;var $10=$word_end;if($cmp){__lastLabel__=3;__label__=1;continue;}else{__lastLabel__=3;__label__=4;break $for_body$$for_end$2;}}}}while(0);var $_lcssa7=__lastLabel__==0?$3:($10);var $11=$word_addr;var $sub_ptr_lhs_cast=($_lcssa7);var $sub_ptr_rhs_cast=($11);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$i=$sub_ptr_sub;var $12=$word_copy_addr;var $13=$word_addr;var $14=$i;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$13;$dest$=$12;$stop$=$src$+$14;if(($dest$%4)==($src$%4)&&$14>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $15=$i;var $16=$word_copy_addr;var $arrayidx=(($16+$15)&4294967295);HEAP8[($arrayidx)]=0;var $17=$end_type_addr;var $and=($17)&63;$i=$and;$len_ending=$and;var $cmp46=((($and))|0)>0;if($cmp46){__label__=5;;}else{__label__=8;;}
$for_body5$$for_end12$9:do{if(__label__==5){$for_body5$10:while(1){var $18=$word_end;var $incdec_ptr6=(($18+-1)&4294967295);$word_end=$incdec_ptr6;var $19=$word_end;var $20=HEAP8[($19)];var $conv73=(tempInt=(($20)),(tempInt>=128?tempInt-256:tempInt));var $and84=($conv73)&192;var $cmp95=((($and84))|0)==128;if($cmp95){__label__=6;;}else{__label__=7;;}
$while_body$$for_inc11$12:do{if(__label__==6){while(1){var $21=$word_end;var $incdec_ptr10=(($21+-1)&4294967295);$word_end=$incdec_ptr10;var $22=$len_ending;var $inc=((($22)+1)&4294967295);$len_ending=$inc;var $23=$word_end;var $24=HEAP8[($23)];var $conv7=(tempInt=(($24)),(tempInt>=128?tempInt-256:tempInt));var $and8=($conv7)&192;var $cmp9=((($and8))|0)==128;if($cmp9){__label__=6;continue;}else{__label__=7;break $while_body$$for_inc11$12;}}}}while(0);var $25=$i;var $dec=((($25)-1)&4294967295);$i=$dec;var $cmp4=((($dec))|0)>0;if($cmp4){__label__=5;continue $for_body5$10;}else{__label__=8;break $for_body5$$for_end12$9;}}}}while(0);$i=0;var $26=$i;var $27=$len_ending;var $cmp142=((($26))|0)<((($27))|0);var $28=$i;if($cmp142){__lastLabel__=8;__label__=9;;}else{__lastLabel__=8;__label__=10;;}
$for_body15$$for_end21$17:do{if(__label__==9){while(1){var $29=__lastLabel__==9?$38:($28);var $30=$word_end;var $arrayidx16=(($30+$29)&4294967295);var $31=HEAP8[($arrayidx16)];var $32=$i;var $arrayidx17=((__ZZ12RemoveEndingP10TranslatorPciS1_E6ending+$32)&4294967295);HEAP8[($arrayidx17)]=$31;var $33=$i;var $34=$word_end;var $arrayidx18=(($34+$33)&4294967295);HEAP8[($arrayidx18)]=32;var $35=$i;var $inc20=((($35)+1)&4294967295);$i=$inc20;var $36=$i;var $37=$len_ending;var $cmp14=((($36))|0)<((($37))|0);var $38=$i;if($cmp14){__lastLabel__=9;__label__=9;continue;}else{__lastLabel__=9;__label__=10;break $for_body15$$for_end21$17;}}}}while(0);var $_lcssa=__lastLabel__==8?$28:($38);var $arrayidx22=((__ZZ12RemoveEndingP10TranslatorPciS1_E6ending+$_lcssa)&4294967295);HEAP8[($arrayidx22)]=0;var $39=$word_end;var $incdec_ptr23=(($39+-1)&4294967295);$word_end=$incdec_ptr23;var $40=$end_type_addr;var $and24=($40)&65520;var $or=($and24)|4;$end_flags=$or;var $41=$end_type_addr;var $and25=($41)&512;var $tobool=((($and25))|0)!=0;if($tobool){__label__=11;;}else{__label__=13;;}
$if_then26$$if_end33$21:do{if(__label__==11){var $42=$word_end;var $arrayidx27=(($42)&4294967295);var $43=HEAP8[($arrayidx27)];var $conv28=(tempInt=(($43)),(tempInt>=128?tempInt-256:tempInt));var $cmp29=((($conv28))|0)==105;if(!($cmp29)){__label__=13;break $if_then26$$if_end33$21;}
var $44=$word_end;var $arrayidx31=(($44)&4294967295);HEAP8[($arrayidx31)]=121;;}}while(0);var $45=$end_type_addr;var $and34=($45)&256;var $tobool35=((($and34))|0)!=0;if($tobool35){__label__=14;;}else{__label__=33;;}
$if_then36$$if_end98$25:do{if(__label__==14){var $46=$tr_addr;var $translator_name=(($46+280)&4294967295);var $47=HEAP32[(($translator_name)>>2)];var $cmp37=((($47))|0)==25966;var $48=$tr_addr;if($cmp37){__label__=15;;}else{__label__=28;;}
$if_then38$$if_else80$27:do{if(__label__==15){var $49=$word_end;var $arrayidx39=(($49+-1)&4294967295);var $50=HEAP8[($arrayidx39)];var $conv40=(tempInt=(($50)),(tempInt>=128?tempInt-256:tempInt));var $call=__ZL8IsLetterP10Translatorii($48,$conv40,7);var $tobool41=((($call))|0)!=0;if($tobool41){__label__=16;;}else{__label__=23;;}
$land_lhs_true$$if_else$29:do{if(__label__==16){var $51=$tr_addr;var $52=$word_end;var $arrayidx42=(($52)&4294967295);var $53=HEAP8[($arrayidx42)];var $conv43=(tempInt=(($53)),(tempInt>=128?tempInt-256:tempInt));var $call44=__ZL8IsLetterP10Translatorii($51,$conv43,1);var $tobool45=((($call44))|0)!=0;if(!($tobool45)){__label__=23;break $land_lhs_true$$if_else$29;}
$i=0;;while(1){var $54=$i;var $arrayidx48=((__ZZ12RemoveEndingP10TranslatorPciS1_E16add_e_exceptions+$54*4)&4294967295);var $55=HEAP32[(($arrayidx48)>>2)];$p=$55;var $cmp49=((($55))|0)!=0;if(!($cmp49)){__label__=22;break;}
var $56=$p;var $call51=_strlen($56);$len=$call51;var $57=$p;var $58=$len;var $sub=((1-($58))&4294967295);var $59=$word_end;var $arrayidx52=(($59+$sub)&4294967295);var $60=$len;var $call53=_memcmp($57,$arrayidx52,$60);var $cmp54=((($call53))|0)==0;if($cmp54){__label__=21;break;}
var $61=$i;var $inc58=((($61)+1)&4294967295);$i=$inc58;__label__=18;continue;}
if(__label__==21){var $_pr=$p;var $cmp60=((($_pr))|0)==0;if(!($cmp60)){__label__=30;break $if_then38$$if_else80$27;}}
var $62=$end_flags;var $or62=($62)|16;$end_flags=$or62;__label__=30;break $if_then38$$if_else80$27;}}while(0);$i=0;;while(1){var $63=$i;var $arrayidx65=((__ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions+$63*4)&4294967295);var $64=HEAP32[(($arrayidx65)>>2)];$p=$64;var $cmp66=((($64))|0)!=0;if(!($cmp66)){__label__=30;break $if_then38$$if_else80$27;}
var $65=$p;var $call68=_strlen($65);$len=$call68;var $66=$p;var $67=$len;var $sub69=((1-($67))&4294967295);var $68=$word_end;var $arrayidx70=(($68+$sub69)&4294967295);var $69=$len;var $call71=_memcmp($66,$arrayidx70,$69);var $cmp72=((($call71))|0)==0;if($cmp72){__label__=26;break;}
var $71=$i;var $inc77=((($71)+1)&4294967295);$i=$inc77;__label__=24;continue;}
var $70=$end_flags;var $or74=($70)|16;$end_flags=$or74;;}
else if(__label__==28){var $langopts=(($48)&4294967295);var $suffix_add_e=(($langopts+276)&4294967295);var $72=HEAP32[(($suffix_add_e)>>2)];var $cmp81=((($72))|0)!=0;if(!($cmp81)){__label__=30;break $if_then38$$if_else80$27;}
var $73=$end_flags;var $or83=($73)|16;$end_flags=$or83;;}}while(0);var $74=$end_flags;var $and86=($74)&16;var $tobool87=((($and86))|0)!=0;if(!($tobool87)){__label__=33;break $if_then36$$if_end98$25;}
var $75=$tr_addr;var $langopts89=(($75)&4294967295);var $suffix_add_e90=(($langopts89+276)&4294967295);var $76=HEAP32[(($suffix_add_e90)>>2)];var $77=$word_end;var $arrayidx91=(($77+1)&4294967295);var $call92=__Z8utf8_outjPc($76,$arrayidx91);var $78=HEAP32[((_option_phonemes)>>2)];var $cmp93=((($78))|0)==2;if(!($cmp93)){__label__=33;break $if_then36$$if_end98$25;}
var $79=HEAP32[((_f_trans)>>2)];var $80=_fwrite(((__str25141)&4294967295),6,1,$79);;}}while(0);var $81=$end_type_addr;var $and99=($81)&2048;var $tobool100=((($and99))|0)!=0;if($tobool100){__label__=34;;}else{__label__=36;;}
$land_lhs_true101$$if_end105$51:do{if(__label__==34){var $82=$tr_addr;var $expect_verb=(($82+8272)&4294967295);var $83=HEAP32[(($expect_verb)>>2)];var $cmp102=((($83))|0)==0;if(!($cmp102)){__label__=36;break $land_lhs_true101$$if_end105$51;}
var $84=$tr_addr;var $expect_verb104=(($84+8272)&4294967295);HEAP32[(($expect_verb104)>>2)]=1;;}}while(0);var $call106=_strcmp(((__ZZ12RemoveEndingP10TranslatorPciS1_E6ending)&4294967295),((__str5172)&4294967295));var $cmp107=((($call106))|0)==0;if($cmp107){__label__=38;;}else{__label__=37;;}
$if_then110$$lor_lhs_false$55:do{if(__label__==37){var $call108=_strcmp(((__ZZ12RemoveEndingP10TranslatorPciS1_E6ending)&4294967295),((__str27143)&4294967295));var $cmp109=((($call108))|0)==0;if($cmp109){__label__=38;break $if_then110$$lor_lhs_false$55;}else{__label__=39;break $if_then110$$lor_lhs_false$55;}}}while(0);if(__label__==38){var $85=$end_flags;var $or111=($85)|8;$end_flags=$or111;;}
var $86=HEAP8[(((__ZZ12RemoveEndingP10TranslatorPciS1_E6ending)&4294967295))];var $conv113=(tempInt=(($86)),(tempInt>=128?tempInt-256:tempInt));var $cmp114=((($conv113))|0)==39;if($cmp114){__label__=40;;}else{__label__=41;;}
if(__label__==40){var $87=$end_flags;var $and116=($87)&-5;$end_flags=$and116;;}
var $88=$end_flags;;return $88;return null;}
function __ZL13IsLetterGroupP10TranslatorPcii($tr,$word,$group,$pre){;var __label__;var $retval;var $tr_addr;var $word_addr;var $group_addr;var $pre_addr;var $p;var $w;var $len;$tr_addr=$tr;$word_addr=$word;$group_addr=$group;$pre_addr=$pre;$len=0;var $0=$group_addr;var $1=$tr_addr;var $letterGroups=(($1+5152)&4294967295);var $arrayidx=(($letterGroups+$0*4)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];$p=$2;var $3=$p;var $cmp=((($3))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){$while_cond$4:while(1){var $4=$p;var $5=HEAP8[($4)];var $conv=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $cmp1=((($conv))|0)!=7;if(!($cmp1)){__label__=13;break $while_cond$4;}
var $6=$pre_addr;var $tobool=((($6))|0)!=0;if($tobool){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $7=$p;var $call=_strlen($7);$len=$call;var $8=$word_addr;var $9=$len;var $idx_neg=(((-($9)))&4294967295);var $add_ptr=(($8+$idx_neg)&4294967295);var $add_ptr3=(($add_ptr+1)&4294967295);$w=$add_ptr3;;}
else if(__label__==5){var $10=$word_addr;$w=$10;;}
var $11=$p;var $12=HEAP8[($11)];var $conv61=(tempInt=(($12)),(tempInt>=128?tempInt-256:tempInt));var $13=$w;var $14=HEAP8[($13)];var $conv72=(tempInt=(($14)),(tempInt>=128?tempInt-256:tempInt));var $cmp83=((($conv61))|0)==((($conv72))|0);if($cmp83){__label__=7;;}else{__label__=8;;}
$while_body9$$while_end$11:do{if(__label__==7){while(1){var $15=$w;var $incdec_ptr=(($15+1)&4294967295);$w=$incdec_ptr;var $16=$p;var $incdec_ptr10=(($16+1)&4294967295);$p=$incdec_ptr10;var $17=$p;var $18=HEAP8[($17)];var $conv6=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));var $19=$w;var $20=HEAP8[($19)];var $conv7=(tempInt=(($20)),(tempInt>=128?tempInt-256:tempInt));var $cmp8=((($conv6))|0)==((($conv7))|0);if($cmp8){__label__=7;continue;}else{__label__=8;break $while_body9$$while_end$11;}}}}while(0);var $21=$p;var $22=HEAP8[($21)];var $conv11=(tempInt=(($22)),(tempInt>=128?tempInt-256:tempInt));var $cmp12=((($conv11))|0)==0;if($cmp12){__label__=9;break $while_cond$4;}
while(1){var $27=$p;var $incdec_ptr19=(($27+1)&4294967295);$p=$incdec_ptr19;var $28=HEAP8[($27)];var $conv20=(tempInt=(($28)),(tempInt>=128?tempInt-256:tempInt));var $cmp21=((($conv20))|0)!=0;if($cmp21){__label__=12;continue;}else{__label__=2;continue $while_cond$4;}}}
if(__label__==13){$retval=0;;}
else if(__label__==9){var $23=$pre_addr;var $tobool14=((($23))|0)!=0;if($tobool14){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $24=$len;$retval=$24;;}
else if(__label__==11){var $25=$w;var $26=$word_addr;var $sub_ptr_lhs_cast=($25);var $sub_ptr_rhs_cast=($26);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$retval=$sub_ptr_sub;;}}}
var $29=$retval;;return $29;return null;}
function __Z11CalcPitchesP10Translatori($tr,$clause_type){var __stackBase__=STACKTOP;STACKTOP+=6000;_memset(__stackBase__,0,6000);var __label__;var __lastLabel__=null;var $tr_addr;var $clause_type_addr;var $p;var $syl;var $ix;var $x;var $st_ix;var $n_st;var $option;var $group_tone;var $group_tone_emph;var $group_tone_comma;var $ph_start;var $st_start;var $st_clause_end;var $count;var $n_primary;var $count_primary;var $ph;var $ph_end;var $syllable_tab2=__stackBase__;$tr_addr=$tr;$clause_type_addr=$clause_type;$ph_start=0;var $0=HEAP32[((_n_phoneme_list)>>2)];$ph_end=$0;var $arraydecay=(($syllable_tab2)&4294967295);HEAP32[((__ZL12syllable_tab)>>2)]=$arraydecay;$n_st=0;$n_primary=0;$ix=0;var $1=$ix;var $2=HEAP32[((_n_phoneme_list)>>2)];var $sub4=((($2)-1)&4294967295);var $cmp5=((($1))|0)<((($sub4))|0);if($cmp5){__label__=1;;}else{__label__=8;;}
$for_body$$for_end$2:do{if(__label__==1){$for_body$3:while(1){var $3=$ix;var $arrayidx=((_phoneme_list+$3*24)&4294967295);$p=$arrayidx;var $4=$p;var $synthflags=(($4+4)&4294967295);var $5=HEAPU16[(($synthflags)>>1)];var $conv=((($5))&65535);var $and=($conv)&4;var $tobool=((($and))|0)!=0;if($tobool){__label__=2;;}else{__label__=4;;}
$if_then$$if_else$5:do{if(__label__==2){var $6=$n_st;var $7=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx1=(($7+6*$6)&4294967295);var $flags=(($arrayidx1+2)&4294967295);HEAP8[($flags)]=0;var $8=$n_st;var $9=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx2=(($9+6*$8)&4294967295);var $env=(($arrayidx2+1)&4294967295);HEAP8[($env)]=0;var $10=$ix;var $add=((($10)+1)&4294967295);var $arrayidx3=((_phoneme_list+$add*24)&4294967295);var $type=(($arrayidx3+15)&4294967295);var $11=HEAP8[($type)];var $12=$n_st;var $13=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx4=(($13+6*$12)&4294967295);var $nextph_type=(($arrayidx4+3)&4294967295);HEAP8[($nextph_type)]=$11;var $14=$p;var $stresslevel=(($14+1)&4294967295);var $15=HEAP8[($stresslevel)];var $16=$n_st;var $inc=((($16)+1)&4294967295);$n_st=$inc;var $17=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx5=(($17+6*$16)&4294967295);var $stress=(($arrayidx5)&4294967295);HEAP8[($stress)]=$15;var $18=$p;var $stresslevel6=(($18+1)&4294967295);var $19=HEAPU8[($stresslevel6)];var $conv7=((($19))&255);var $cmp8=((($conv7))|0)>=4;if(!($cmp8)){__label__=7;break $if_then$$if_else$5;}
var $20=$n_primary;var $inc10=((($20)+1)&4294967295);$n_primary=$inc10;;}
else if(__label__==4){var $21=$p;var $ph11=(($21+8)&4294967295);var $22=HEAP32[(($ph11)>>2)];var $code=(($22+10)&4294967295);var $23=HEAPU8[($code)];var $conv12=((($23))&255);var $cmp13=((($conv12))|0)==27;if(!($cmp13)){__label__=7;break $if_then$$if_else$5;}
var $24=$n_st;var $cmp14=((($24))|0)>0;if(!($cmp14)){__label__=7;break $if_then$$if_else$5;}
var $25=$n_st;var $sub16=((($25)-1)&4294967295);var $26=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx17=(($26+6*$sub16)&4294967295);var $flags18=(($arrayidx17+2)&4294967295);var $27=HEAP8[($flags18)];var $conv19=(tempInt=(($27)),(tempInt>=128?tempInt-256:tempInt));var $or=($conv19)|4;var $conv20=((($or))&255);HEAP8[($flags18)]=$conv20;;}}while(0);var $28=$ix;var $inc23=((($28)+1)&4294967295);$ix=$inc23;var $29=$ix;var $30=HEAP32[((_n_phoneme_list)>>2)];var $sub=((($30)-1)&4294967295);var $cmp=((($29))|0)<((($sub))|0);if($cmp){__label__=1;continue $for_body$3;}else{__label__=8;break $for_body$$for_end$2;}}}}while(0);var $31=$n_st;var $32=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx24=(($32+6*$31)&4294967295);var $stress25=(($arrayidx24)&4294967295);HEAP8[($stress25)]=0;var $33=$n_st;var $cmp26=((($33))|0)==0;if($cmp26){__label__=70;;}else{__label__=9;;}
$for_end258$$if_end28$13:do{if(__label__==9){var $34=$tr_addr;var $langopts=(($34)&4294967295);var $tone_language=(($langopts+224)&4294967295);var $35=HEAP32[(($tone_language)>>2)];var $cmp29=((($35))|0)==1;var $36=$tr_addr;if($cmp29){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $37=$clause_type_addr;__ZL16CalcPitches_ToneP10Translatori($36,$37);;}
else if(__label__==11){var $langopts32=(($36)&4294967295);var $intonation_group=(($langopts32+228)&4294967295);var $38=HEAP32[(($intonation_group)>>2)];$option=$38;var $39=$option;var $cmp33=((($39))|0)>=8;if($cmp33){__label__=12;;}else{__label__=13;;}
$if_end35_thread$$if_end35$18:do{if(__label__==12){$option=1;var $40=$clause_type_addr;__lastLabel__=12;__label__=15;break $if_end35_thread$$if_end35$18;}
else if(__label__==13){var $cmp36=((($39))|0)==0;var $41=$clause_type_addr;if($cmp36){__lastLabel__=13;;}else{__lastLabel__=13;__label__=15;break $if_end35_thread$$if_end35$18;}
var $42=$tr_addr;var $langopts38=(($42)&4294967295);var $tunes=(($langopts38+232)&4294967295);var $arrayidx39=(($tunes+$41)&4294967295);var $43=HEAPU8[($arrayidx39)];var $conv40=((($43))&255);$group_tone=$conv40;var $44=$tr_addr;var $langopts41=(($44)&4294967295);var $tunes42=(($langopts41+232)&4294967295);var $arrayidx43=(($tunes42+5)&4294967295);var $45=HEAPU8[($arrayidx43)];var $conv44=((($45))&255);$group_tone_emph=$conv44;var $46=$tr_addr;var $langopts45=(($46)&4294967295);var $tunes46=(($langopts45+232)&4294967295);var $arrayidx47=(($tunes46+1)&4294967295);var $47=HEAPU8[($arrayidx47)];var $conv48=((($47))&255);$group_tone_comma=$conv48;__label__=16;break $if_end35_thread$$if_end35$18;}}while(0);if(__label__==15){var $48=__lastLabel__==12?$40:($41);var $49=$option;var $50=$tr_addr;var $punct_to_tone=(($50+1000)&4294967295);var $arrayidx50=(($punct_to_tone+$49*6)&4294967295);var $arrayidx51=(($arrayidx50+$48)&4294967295);var $51=HEAPU8[($arrayidx51)];var $conv52=((($51))&255);$group_tone=$conv52;var $52=$option;var $53=$tr_addr;var $punct_to_tone53=(($53+1000)&4294967295);var $arrayidx54=(($punct_to_tone53+$52*6)&4294967295);var $arrayidx55=(($arrayidx54+5)&4294967295);var $54=HEAPU8[($arrayidx55)];var $conv56=((($54))&255);$group_tone_emph=$conv56;var $55=$option;var $56=$tr_addr;var $punct_to_tone57=(($56+1000)&4294967295);var $arrayidx58=(($punct_to_tone57+$55*6)&4294967295);var $arrayidx59=(($arrayidx58+1)&4294967295);var $57=HEAPU8[($arrayidx59)];var $conv60=((($57))&255);$group_tone_comma=$conv60;;}
var $58=$clause_type_addr;var $cmp62=((($58))|0)==4;if($cmp62){__label__=17;;}else{__label__=18;;}
if(__label__==17){HEAP8[(__ZL8no_tonic_b)]=1;;}
else if(__label__==18){HEAP8[(__ZL8no_tonic_b)]=0;;}
$st_start=0;$count_primary=0;$st_ix=0;var $59=$st_ix;var $60=$n_st;var $cmp673=((($59))|0)<((($60))|0);if($cmp673){__label__=20;;}else{__label__=54;;}
$for_body68$$for_end177$29:do{if(__label__==20){$for_body68$30:while(1){var $61=$st_ix;var $62=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx69=(($62+6*$61)&4294967295);$syl=$arrayidx69;var $63=$syl;var $stress70=(($63)&4294967295);var $64=HEAP8[($stress70)];var $conv71=(tempInt=(($64)),(tempInt>=128?tempInt-256:tempInt));var $cmp72=((($conv71))|0)>=4;if($cmp72){__label__=21;;}else{__label__=22;;}
if(__label__==21){var $65=$count_primary;var $inc74=((($65)+1)&4294967295);$count_primary=$inc74;;}
var $66=$syl;var $stress76=(($66)&4294967295);var $67=HEAP8[($stress76)];var $conv77=(tempInt=(($67)),(tempInt>=128?tempInt-256:tempInt));var $cmp78=((($conv77))|0)==6;if($cmp78){__label__=23;;}else{__label__=36;;}
$if_then79$$if_end124$35:do{if(__label__==23){var $68=$st_ix;var $sub80=((($68)-1)&4294967295);$ix=$sub80;;$for_cond81$37:while(1){var $69=$ix;var $70=$st_start;var $cmp82=((($69))|0)>=((($70))|0);if(!($cmp82)){__label__=30;break $for_cond81$37;}
var $71=$ix;var $72=$st_ix;var $sub83=((($72)-3)&4294967295);var $cmp84=((($71))|0)>=((($sub83))|0);if(!($cmp84)){__label__=30;break $for_cond81$37;}
var $73=$ix;var $74=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx86=(($74+6*$73)&4294967295);var $stress87=(($arrayidx86)&4294967295);var $75=HEAP8[($stress87)];var $conv88=(tempInt=(($75)),(tempInt>=128?tempInt-256:tempInt));var $cmp89=((($conv88))|0)==6;if($cmp89){__label__=30;break $for_cond81$37;}
var $76=$ix;var $77=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx92=(($77+6*$76)&4294967295);var $stress93=(($arrayidx92)&4294967295);var $78=HEAP8[($stress93)];var $conv94=(tempInt=(($78)),(tempInt>=128?tempInt-256:tempInt));var $cmp95=((($conv94))|0)==4;var $79=$ix;if($cmp95){__label__=28;break $for_cond81$37;}
var $dec=((($79)-1)&4294967295);$ix=$dec;__label__=24;continue $for_cond81$37;}
if(__label__==28){var $80=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx97=(($80+6*$79)&4294967295);var $stress98=(($arrayidx97)&4294967295);HEAP8[($stress98)]=3;;}
var $81=$st_ix;var $add102=((($81)+1)&4294967295);$ix=$add102;;while(1){var $82=$ix;var $83=$n_st;var $cmp104=((($82))|0)<((($83))|0);if(!($cmp104)){__label__=36;break $if_then79$$if_end124$35;}
var $84=$ix;var $85=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx106=(($85+6*$84)&4294967295);var $stress107=(($arrayidx106)&4294967295);var $86=HEAP8[($stress107)];var $conv108=(tempInt=(($86)),(tempInt>=128?tempInt-256:tempInt));var $cmp109=((($conv108))|0)==4;if($cmp109){__label__=36;break $if_then79$$if_end124$35;}
var $87=$ix;var $88=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx112=(($88+6*$87)&4294967295);var $stress113=(($arrayidx112)&4294967295);var $89=HEAP8[($stress113)];var $conv114=(tempInt=(($89)),(tempInt>=128?tempInt-256:tempInt));var $cmp115=((($conv114))|0)==6;if($cmp115){__label__=34;break;}
var $93=$ix;var $inc122=((($93)+1)&4294967295);$ix=$inc122;__label__=31;continue;}
var $90=$st_ix;var $91=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx117=(($91+6*$90)&4294967295);var $flags118=(($arrayidx117+2)&4294967295);HEAP8[($flags118)]=2;var $92=$syl;var $stress119=(($92)&4294967295);HEAP8[($stress119)]=5;;}}while(0);var $94=$syl;var $stress125=(($94)&4294967295);var $95=HEAP8[($stress125)];var $conv126=(tempInt=(($95)),(tempInt>=128?tempInt-256:tempInt));var $cmp127=((($conv126))|0)==6;if($cmp127){__label__=37;;}else{__label__=50;;}
if(__label__==37){var $96=$st_ix;var $97=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx129=(($97+6*$96)&4294967295);var $flags130=(($arrayidx129+2)&4294967295);HEAP8[($flags130)]=2;$count=0;var $98=$n_primary;var $99=$count_primary;var $sub131=((($98)-($99))&4294967295);var $cmp132=((($sub131))|0)>1;if($cmp132){__label__=38;;}else{__label__=39;;}
if(__label__==38){$count=1;;}
var $100=$st_ix;var $add135=((($100)+1)&4294967295);$ix=$add135;;$for_cond136$58:while(1){var $101=$ix;var $102=$n_st;var $cmp137=((($101))|0)<((($102))|0);if(!($cmp137)){__label__=45;break $for_cond136$58;}
var $103=$ix;var $104=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx139=(($104+6*$103)&4294967295);var $stress140=(($arrayidx139)&4294967295);var $105=HEAP8[($stress140)];var $conv141=(tempInt=(($105)),(tempInt>=128?tempInt-256:tempInt));var $cmp142=((($conv141))|0)>4;if($cmp142){__label__=45;break $for_cond136$58;}
var $106=$ix;var $107=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx145=(($107+6*$106)&4294967295);var $stress146=(($arrayidx145)&4294967295);var $108=HEAP8[($stress146)];var $conv147=(tempInt=(($108)),(tempInt>=128?tempInt-256:tempInt));var $cmp148=((($conv147))|0)==4;if($cmp148){__label__=43;;}else{__label__=44;;}
if(__label__==43){var $109=$count;var $inc150=((($109)+1)&4294967295);$count=$inc150;var $110=$count;var $cmp151=((($110))|0)>1;if($cmp151){__label__=45;break $for_cond136$58;}}
var $111=$ix;var $inc156=((($111)+1)&4294967295);$ix=$inc156;__label__=40;continue $for_cond136$58;}
var $112=$st_start;var $113=$ix;var $114=$n_st;__ZL18count_pitch_vowelsiii($112,$113,$114);var $115=$ix;var $116=$n_st;var $cmp158=((($115))|0)<((($116))|0);if($cmp158){__label__=47;;}else{__label__=46;;}
$if_then160$$lor_lhs_false$66:do{if(__label__==46){var $117=$clause_type_addr;var $cmp159=((($117))|0)==0;if($cmp159){__label__=47;break $if_then160$$lor_lhs_false$66;}
var $122=$option;var $123=$st_start;var $124=$ix;var $125=$group_tone;__ZL12calc_pitchesiiii($122,$123,$124,$125);__label__=49;break $if_then160$$lor_lhs_false$66;}}while(0);if(__label__==47){var $118=$option;var $119=$st_start;var $120=$ix;var $121=$group_tone_emph;__ZL12calc_pitchesiiii($118,$119,$120,$121);;}
var $126=$ix;$st_start=$126;;}
var $127=$st_start;var $128=$st_ix;var $cmp165=((($127))|0)<((($128))|0);if($cmp165){__label__=51;;}else{__label__=53;;}
$land_lhs_true166$$for_inc175$73:do{if(__label__==51){var $129=$syl;var $flags167=(($129+2)&4294967295);var $130=HEAP8[($flags167)];var $conv168=(tempInt=(($130)),(tempInt>=128?tempInt-256:tempInt));var $and169=($conv168)&4;var $tobool170=((($and169))|0)!=0;if(!($tobool170)){__label__=53;break $land_lhs_true166$$for_inc175$73;}
var $131=$st_ix;var $add172=((($131)+1)&4294967295);$st_clause_end=$add172;var $132=$st_start;var $133=$st_clause_end;var $134=$st_clause_end;__ZL18count_pitch_vowelsiii($132,$133,$134);var $135=$option;var $136=$st_start;var $137=$st_clause_end;var $138=$group_tone_comma;__ZL12calc_pitchesiiii($135,$136,$137,$138);var $139=$st_clause_end;$st_start=$139;;}}while(0);var $140=$st_ix;var $inc176=((($140)+1)&4294967295);$st_ix=$inc176;var $141=$st_ix;var $142=$n_st;var $cmp67=((($141))|0)<((($142))|0);if($cmp67){__label__=20;continue $for_body68$30;}else{__label__=54;break $for_body68$$for_end177$29;}}}}while(0);var $143=$st_start;var $144=$st_ix;var $cmp178=((($143))|0)<((($144))|0);if($cmp178){__label__=55;;}else{__label__=56;;}
if(__label__==55){var $145=$st_start;var $146=$st_ix;var $147=$n_st;__ZL18count_pitch_vowelsiii($145,$146,$147);var $148=$option;var $149=$st_start;var $150=$st_ix;var $151=$group_tone;__ZL12calc_pitchesiiii($148,$149,$150,$151);;}
$st_ix=0;var $152=$ph_start;$ix=$152;var $153=$ix;var $154=$ph_end;var $cmp1832=((($153))|0)<((($154))|0);if(!($cmp1832)){__label__=70;break $for_end258$$if_end28$13;}
$for_body184$81:while(1){var $155=$ix;var $arrayidx185=((_phoneme_list+$155*24)&4294967295);$p=$arrayidx185;var $156=$st_ix;var $157=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx186=(($157+6*$156)&4294967295);var $stress187=(($arrayidx186)&4294967295);var $158=HEAP8[($stress187)];var $159=$p;var $stresslevel188=(($159+1)&4294967295);HEAP8[($stresslevel188)]=$158;var $160=$p;var $synthflags189=(($160+4)&4294967295);var $161=HEAPU16[(($synthflags189)>>1)];var $conv190=((($161))&65535);var $and191=($conv190)&4;var $tobool192=((($and191))|0)!=0;if($tobool192){__label__=58;;}else{__label__=69;;}
if(__label__==58){var $162=$st_ix;var $163=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx194=(($163+6*$162)&4294967295);$syl=$arrayidx194;var $164=$syl;var $pitch1=(($164+4)&4294967295);var $165=HEAP8[($pitch1)];var $166=$p;var $pitch1195=(($166+20)&4294967295);HEAP8[($pitch1195)]=$165;var $167=$syl;var $pitch2=(($167+5)&4294967295);var $168=HEAP8[($pitch2)];var $169=$p;var $pitch2196=(($169+21)&4294967295);HEAP8[($pitch2196)]=$168;var $170=$p;var $env197=(($170+14)&4294967295);HEAP8[($env197)]=0;var $171=$syl;var $flags198=(($171+2)&4294967295);var $172=HEAP8[($flags198)];var $conv199=(tempInt=(($172)),(tempInt>=128?tempInt-256:tempInt));var $and200=($conv199)&1;var $tobool201=((($and200))|0)!=0;var $173=$p;if($tobool201){__label__=59;;}else{__label__=60;;}
$if_then202$$if_else204$85:do{if(__label__==59){var $env203=(($173+14)&4294967295);HEAP8[($env203)]=2;;}
else if(__label__==60){var $stresslevel205=(($173+1)&4294967295);var $174=HEAPU8[($stresslevel205)];var $conv206=((($174))&255);var $cmp207=((($conv206))|0)>5;if(!($cmp207)){__label__=62;break $if_then202$$if_else204$85;}
var $175=$syl;var $env209=(($175+1)&4294967295);var $176=HEAP8[($env209)];var $177=$p;var $env210=(($177+14)&4294967295);HEAP8[($env210)]=$176;;}}while(0);var $178=$p;var $pitch1213=(($178+20)&4294967295);var $179=HEAPU8[($pitch1213)];var $conv214=((($179))&255);var $180=$p;var $pitch2215=(($180+21)&4294967295);var $181=HEAPU8[($pitch2215)];var $conv216=((($181))&255);var $cmp217=((($conv214))|0)>((($conv216))|0);if($cmp217){__label__=63;;}else{__label__=64;;}
if(__label__==63){var $182=$p;var $pitch1219=(($182+20)&4294967295);var $183=HEAPU8[($pitch1219)];var $conv220=((($183))&255);$x=$conv220;var $184=$p;var $pitch2221=(($184+21)&4294967295);var $185=HEAP8[($pitch2221)];var $186=$p;var $pitch1222=(($186+20)&4294967295);HEAP8[($pitch1222)]=$185;var $187=$x;var $conv223=((($187))&255);var $188=$p;var $pitch2224=(($188+21)&4294967295);HEAP8[($pitch2224)]=$conv223;;}
var $189=$p;var $tone_ph=(($189+3)&4294967295);var $190=HEAP8[($tone_ph)];var $tobool226=(tempInt=(($190)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool226){__label__=65;;}else{__label__=66;;}
if(__label__==65){var $191=$p;var $tone_ph228=(($191+3)&4294967295);var $192=HEAPU8[($tone_ph228)];var $idxprom=((($192))&255);var $arrayidx229=((_phoneme_tab+$idxprom*4)&4294967295);var $193=HEAP32[(($arrayidx229)>>2)];$ph=$193;var $194=$p;var $pitch1230=(($194+20)&4294967295);var $195=HEAPU8[($pitch1230)];var $conv231=((($195))&255);var $196=$p;var $pitch2232=(($196+21)&4294967295);var $197=HEAPU8[($pitch2232)];var $conv233=((($197))&255);var $add234=((($conv233)+($conv231))&4294967295);var $div=((((($add234))|0)/2)|0);$x=$div;var $198=$x;var $199=$ph;var $end_type=(($199+13)&4294967295);var $200=HEAPU8[($end_type)];var $conv235=((($200))&255);var $add236=((($conv235)+($198))&4294967295);var $conv237=((($add236))&255);var $201=$p;var $pitch2238=(($201+21)&4294967295);HEAP8[($pitch2238)]=$conv237;var $202=$x;var $203=$ph;var $start_type=(($203+12)&4294967295);var $204=HEAPU8[($start_type)];var $conv239=((($204))&255);var $add240=((($conv239)+($202))&4294967295);var $conv241=((($add240))&255);var $205=$p;var $pitch1242=(($205+20)&4294967295);HEAP8[($pitch1242)]=$conv241;;}
var $206=$syl;var $flags244=(($206+2)&4294967295);var $207=HEAP8[($flags244)];var $conv245=(tempInt=(($207)),(tempInt>=128?tempInt-256:tempInt));var $and246=($conv245)&2;var $tobool247=((($and246))|0)!=0;if($tobool247){__label__=67;;}else{__label__=68;;}
if(__label__==67){var $208=$p;var $stresslevel249=(($208+1)&4294967295);var $209=HEAPU8[($stresslevel249)];var $conv250=((($209))&255);var $or251=($conv250)|8;var $conv252=((($or251))&255);HEAP8[($stresslevel249)]=$conv252;;}
var $210=$st_ix;var $inc254=((($210)+1)&4294967295);$st_ix=$inc254;;}
var $211=$ix;var $inc257=((($211)+1)&4294967295);$ix=$inc257;var $212=$ix;var $213=$ph_end;var $cmp183=((($212))|0)<((($213))|0);if($cmp183){__label__=57;continue $for_body184$81;}else{__label__=70;break $for_end258$$if_end28$13;}}}}}while(0);STACKTOP=__stackBase__;return;return;}
function __ZL16CalcPitches_ToneP10Translatori($tr,$clause_tone){;var __label__;var $tr_addr;var $clause_tone_addr;var $p;var $ix;var $count_stressed;var $final_stressed;var $tone_ph;var $pause;var $tone_promoted;var $tph;var $prev_tph;var $prevw_tph;var $prev2_tph;var $prev_p;var $pitch_adjust;var $pitch_decrement;var $pitch_low;var $pitch_high;$tr_addr=$tr;$clause_tone_addr=$clause_tone;$count_stressed=0;$final_stressed=0;$pitch_adjust=0;$pitch_decrement=0;$pitch_low=0;$pitch_high=0;$p=((_phoneme_list)&4294967295);$ix=0;var $0=$ix;var $1=HEAP32[((_n_phoneme_list)>>2)];var $cmp5=((($0))|0)<((($1))|0);if($cmp5){__label__=1;;}else{__label__=8;;}
$for_body$$for_end$2:do{if(__label__==1){$for_body$3:while(1){var $2=$p;var $type=(($2+15)&4294967295);var $3=HEAPU8[($type)];var $conv=((($3))&255);var $cmp1=((($conv))|0)==2;if($cmp1){__label__=2;;}else{__label__=7;;}
$land_lhs_true$$for_inc$5:do{if(__label__==2){var $4=$p;var $stresslevel=(($4+1)&4294967295);var $5=HEAPU8[($stresslevel)];var $conv2=((($5))&255);var $cmp3=((($conv2))|0)>=4;if(!($cmp3)){__label__=7;break $land_lhs_true$$for_inc$5;}
var $6=$count_stressed;var $cmp4=((($6))|0)==0;if($cmp4){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $7=$ix;$final_stressed=$7;;}
var $8=$p;var $stresslevel6=(($8+1)&4294967295);var $9=HEAPU8[($stresslevel6)];var $conv7=((($9))&255);var $cmp8=((($conv7))|0)>=4;if(!($cmp8)){__label__=7;break $land_lhs_true$$for_inc$5;}
var $10=$ix;$final_stressed=$10;var $11=$count_stressed;var $inc=((($11)+1)&4294967295);$count_stressed=$inc;;}}while(0);var $12=$ix;var $inc12=((($12)+1)&4294967295);$ix=$inc12;var $13=$p;var $incdec_ptr=(($13+24)&4294967295);$p=$incdec_ptr;var $14=$ix;var $15=HEAP32[((_n_phoneme_list)>>2)];var $cmp=((($14))|0)<((($15))|0);if($cmp){__label__=1;continue $for_body$3;}else{__label__=8;break $for_body$$for_end$2;}}}}while(0);var $16=$final_stressed;var $arrayidx=((_phoneme_list+$16*24)&4294967295);var $stresslevel13=(($arrayidx+1)&4294967295);HEAP8[($stresslevel13)]=7;var $17=$tr_addr;var $translator_name=(($17+280)&4294967295);var $18=HEAP32[(($translator_name)>>2)];var $cmp14=((($18))|0)==30313;if($cmp14){__label__=9;;}else{__label__=11;;}
$if_then15$$if_end24$14:do{if(__label__==9){var $19=$final_stressed;var $arrayidx16=((_phoneme_list+$19*24)&4294967295);$p=$arrayidx16;var $20=$p;var $tone_ph17=(($20+3)&4294967295);var $21=HEAPU8[($tone_ph17)];var $conv18=((($21))&255);var $cmp19=((($conv18))|0)==0;if(!($cmp19)){__label__=11;break $if_then15$$if_end24$14;}
var $call=__Z11PhonemeCodej(55);var $conv21=((($call))&255);var $22=$p;var $tone_ph22=(($22+3)&4294967295);HEAP8[($tone_ph22)]=$conv21;;}}while(0);$pause=1;$tone_promoted=0;$p=((_phoneme_list)&4294967295);$prev_p=((_phoneme_list)&4294967295);var $23=HEAP32[((((_phoneme_tab+36)&4294967295))>>2)];$prevw_tph=$23;$prev_tph=$23;$ix=0;var $24=$ix;var $25=HEAP32[((_n_phoneme_list)>>2)];var $cmp262=((($24))|0)<((($25))|0);if($cmp262){__label__=12;;}else{__label__=47;;}
$for_body27$$for_end127$18:do{if(__label__==12){$for_body27$19:while(1){var $26=$p;var $type28=(($26+15)&4294967295);var $27=HEAPU8[($type28)];var $conv29=((($27))&255);var $cmp30=((($conv29))|0)==0;if($cmp30){__label__=13;;}else{__label__=15;;}
$land_lhs_true31$$if_end35$21:do{if(__label__==13){var $28=$p;var $ph=(($28+8)&4294967295);var $29=HEAP32[(($ph)>>2)];var $std_length=(($29+14)&4294967295);var $30=HEAPU8[($std_length)];var $conv32=((($30))&255);var $cmp33=((($conv32))|0)>50;if(!($cmp33)){__label__=15;break $land_lhs_true31$$if_end35$21;}
$pause=1;var $31=HEAP32[((((_phoneme_tab+36)&4294967295))>>2)];$prevw_tph=$31;;}}while(0);var $32=$p;var $newword=(($32+19)&4294967295);var $33=HEAP8[($newword)];var $tobool=(tempInt=(($33)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $34=HEAP32[((((_phoneme_tab+36)&4294967295))>>2)];$prev_tph=$34;;}
var $35=$p;var $synthflags=(($35+4)&4294967295);var $36=HEAPU16[(($synthflags)>>1)];var $conv38=((($36))&65535);var $and=($conv38)&4;var $tobool39=((($and))|0)!=0;if($tobool39){__label__=18;;}else{__label__=46;;}
if(__label__==18){var $37=$p;var $tone_ph41=(($37+3)&4294967295);var $38=HEAPU8[($tone_ph41)];var $conv42=((($38))&255);$tone_ph=$conv42;var $39=$tone_ph;var $arrayidx43=((_phoneme_tab+$39*4)&4294967295);var $40=HEAP32[(($arrayidx43)>>2)];$tph=$40;var $41=$tr_addr;var $translator_name44=(($41+280)&4294967295);var $42=HEAP32[(($translator_name44)>>2)];var $cmp45=((($42))|0)==31336;if($cmp45){__label__=19;;}else{__label__=45;;}
$if_then46$$if_end122$30:do{if(__label__==19){var $43=$tone_ph;var $cmp47=((($43))|0)==0;if($cmp47){__label__=20;;}else{__label__=25;;}
if(__label__==20){var $44=$pause;var $tobool49=((($44))|0)!=0;if($tobool49){__label__=22;;}else{__label__=21;;}
$if_then51$$lor_lhs_false$34:do{if(__label__==21){var $45=$tone_promoted;var $tobool50=((($45))|0)!=0;if($tobool50){__label__=22;break $if_then51$$lor_lhs_false$34;}
var $call53=__Z11PhonemeCodej(12593);$tone_ph=$call53;__label__=24;break $if_then51$$lor_lhs_false$34;}}while(0);if(__label__==22){var $call52=__Z11PhonemeCodej(13621);$tone_ph=$call52;$tone_promoted=1;;}
var $46=$tone_ph;var $conv55=((($46))&255);var $47=$p;var $tone_ph56=(($47+3)&4294967295);HEAP8[($tone_ph56)]=$conv55;var $48=$tone_ph;var $arrayidx57=((_phoneme_tab+$48*4)&4294967295);var $49=HEAP32[(($arrayidx57)>>2)];$tph=$49;;}
else if(__label__==25){$tone_promoted=0;;}
var $50=$ix;var $51=$final_stressed;var $cmp60=((($50))|0)==((($51))|0);if($cmp60){__label__=27;;}else{__label__=30;;}
$if_then61$$if_end70$42:do{if(__label__==27){var $52=$tph;var $mnemonic=(($52)&4294967295);var $53=HEAP32[(($mnemonic)>>2)];var $cmp62=((($53))|0)==13621;if($cmp62){__label__=29;;}else{__label__=28;;}
if(__label__==28){var $54=$tph;var $mnemonic64=(($54)&4294967295);var $55=HEAP32[(($mnemonic64)>>2)];var $cmp65=((($55))|0)==12597;if(!($cmp65)){__label__=30;break $if_then61$$if_end70$42;}}
var $56=$final_stressed;var $arrayidx67=((_phoneme_list+$56*24)&4294967295);var $stresslevel68=(($arrayidx67+1)&4294967295);HEAP8[($stresslevel68)]=6;;}}while(0);var $57=$prevw_tph;var $mnemonic71=(($57)&4294967295);var $58=HEAP32[(($mnemonic71)>>2)];var $cmp72=((($58))|0)==3420466;if($cmp72){__label__=31;;}else{__label__=34;;}
if(__label__==31){var $59=$tph;var $mnemonic74=(($59)&4294967295);var $60=HEAP32[(($mnemonic74)>>2)];var $cmp75=((($60))|0)==3420466;if($cmp75){__label__=32;;}else{__label__=33;;}
if(__label__==32){var $call77=__Z11PhonemeCodej(13619);var $conv78=((($call77))&255);var $61=$prev_p;var $tone_ph79=(($61+3)&4294967295);HEAP8[($tone_ph79)]=$conv78;;}
else if(__label__==33){var $call81=__Z11PhonemeCodej(12594);var $conv82=((($call81))&255);var $62=$prev_p;var $tone_ph83=(($62+3)&4294967295);HEAP8[($tone_ph83)]=$conv82;;}}
var $63=$prev_tph;var $mnemonic86=(($63)&4294967295);var $64=HEAP32[(($mnemonic86)>>2)];var $cmp87=((($64))|0)==12597;if($cmp87){__label__=35;;}else{__label__=37;;}
$land_lhs_true88$$if_end95$54:do{if(__label__==35){var $65=$tph;var $mnemonic89=(($65)&4294967295);var $66=HEAP32[(($mnemonic89)>>2)];var $cmp90=((($66))|0)==12597;if(!($cmp90)){__label__=37;break $land_lhs_true88$$if_end95$54;}
var $call92=__Z11PhonemeCodej(13109);var $conv93=((($call92))&255);var $67=$prev_p;var $tone_ph94=(($67+3)&4294967295);HEAP8[($tone_ph94)]=$conv93;;}}while(0);var $68=$tph;var $mnemonic96=(($68)&4294967295);var $69=HEAP32[(($mnemonic96)>>2)];var $cmp97=((($69))|0)==12593;if(!($cmp97)){__label__=45;break $if_then46$$if_end122$30;}
var $70=$prevw_tph;var $mnemonic99=(($70)&4294967295);var $71=HEAP32[(($mnemonic99)>>2)];var $cmp100=((($71))|0)==13621;if($cmp100){__label__=39;;}else{__label__=40;;}
if(__label__==39){var $call102=__Z11PhonemeCodej(12850);var $conv103=((($call102))&255);var $72=$p;var $tone_ph104=(($72+3)&4294967295);HEAP8[($tone_ph104)]=$conv103;;}
var $73=$prevw_tph;var $mnemonic106=(($73)&4294967295);var $74=HEAP32[(($mnemonic106)>>2)];var $cmp107=((($74))|0)==13619;if($cmp107){__label__=41;;}else{__label__=42;;}
if(__label__==41){var $call109=__Z11PhonemeCodej(13107);var $conv110=((($call109))&255);var $75=$p;var $tone_ph111=(($75+3)&4294967295);HEAP8[($tone_ph111)]=$conv110;;}
var $76=$prevw_tph;var $mnemonic113=(($76)&4294967295);var $77=HEAP32[(($mnemonic113)>>2)];var $cmp114=((($77))|0)==3420466;if($cmp114){__label__=43;;}else{__label__=44;;}
if(__label__==43){var $call116=__Z11PhonemeCodej(13364);var $conv117=((($call116))&255);var $78=$p;var $tone_ph118=(($78+3)&4294967295);HEAP8[($tone_ph118)]=$conv117;;}
var $79=$p;var $stresslevel120=(($79+1)&4294967295);HEAP8[($stresslevel120)]=0;;}}while(0);var $80=$p;$prev_p=$80;var $81=$prevw_tph;$prev2_tph=$81;var $82=$tph;$prev_tph=$82;$prevw_tph=$82;$pause=0;;}
var $83=$ix;var $inc125=((($83)+1)&4294967295);$ix=$inc125;var $84=$p;var $incdec_ptr126=(($84+24)&4294967295);$p=$incdec_ptr126;var $85=$ix;var $86=HEAP32[((_n_phoneme_list)>>2)];var $cmp26=((($85))|0)<((($86))|0);if($cmp26){__label__=12;continue $for_body27$19;}else{__label__=47;break $for_body27$$for_end127$18;}}}}while(0);$p=((_phoneme_list)&4294967295);$ix=0;var $87=$ix;var $88=HEAP32[((_n_phoneme_list)>>2)];var $cmp1291=((($87))|0)<((($88))|0);if($cmp1291){__label__=48;;}else{__label__=58;;}
$for_body130$$for_end166$71:do{if(__label__==48){$for_body130$72:while(1){var $89=$p;var $synthflags131=(($89+4)&4294967295);var $90=HEAPU16[(($synthflags131)>>1)];var $conv132=((($90))&65535);var $and133=($conv132)&4;var $tobool134=((($and133))|0)!=0;if($tobool134){__label__=49;;}else{__label__=57;;}
if(__label__==49){var $91=$p;var $tone_ph136=(($91+3)&4294967295);var $92=HEAPU8[($tone_ph136)];var $conv137=((($92))&255);$tone_ph=$conv137;var $93=$p;var $stresslevel138=(($93+1)&4294967295);var $94=HEAPU8[($stresslevel138)];var $conv139=((($94))&255);var $cmp140=((($conv139))|0)!=0;if($cmp140){__label__=50;;}else{__label__=54;;}
$if_then141$$if_end149$76:do{if(__label__==50){var $95=$ix;var $96=$final_stressed;var $cmp142=((($95))|0)==((($96))|0);if($cmp142){__label__=51;;}else{__label__=52;;}
if(__label__==51){var $97=$pitch_low;$pitch_adjust=$97;;}
else if(__label__==52){var $98=$pitch_decrement;var $99=$pitch_adjust;var $sub=((($99)-($98))&4294967295);$pitch_adjust=$sub;var $100=$pitch_adjust;var $101=$pitch_low;var $cmp145=((($100))|0)<=((($101))|0);if(!($cmp145)){__label__=54;break $if_then141$$if_end149$76;}
var $102=$pitch_high;$pitch_adjust=$102;;}}}while(0);var $103=$tone_ph;var $cmp150=((($103))|0)==0;if($cmp150){__label__=55;;}else{__label__=56;;}
if(__label__==55){$tone_ph=17;var $104=$tone_ph;var $conv152=((($104))&255);var $105=$p;var $tone_ph153=(($105+3)&4294967295);HEAP8[($tone_ph153)]=$conv152;;}
var $106=$pitch_adjust;var $107=$tone_ph;var $arrayidx155=((_phoneme_tab+$107*4)&4294967295);var $108=HEAP32[(($arrayidx155)>>2)];var $start_type=(($108+12)&4294967295);var $109=HEAPU8[($start_type)];var $conv156=((($109))&255);var $add=((($conv156)+($106))&4294967295);var $conv157=((($add))&255);var $110=$p;var $pitch1=(($110+20)&4294967295);HEAP8[($pitch1)]=$conv157;var $111=$pitch_adjust;var $112=$tone_ph;var $arrayidx158=((_phoneme_tab+$112*4)&4294967295);var $113=HEAP32[(($arrayidx158)>>2)];var $end_type=(($113+13)&4294967295);var $114=HEAPU8[($end_type)];var $conv159=((($114))&255);var $add160=((($conv159)+($111))&4294967295);var $conv161=((($add160))&255);var $115=$p;var $pitch2=(($115+21)&4294967295);HEAP8[($pitch2)]=$conv161;;}
var $116=$ix;var $inc164=((($116)+1)&4294967295);$ix=$inc164;var $117=$p;var $incdec_ptr165=(($117+24)&4294967295);$p=$incdec_ptr165;var $118=$ix;var $119=HEAP32[((_n_phoneme_list)>>2)];var $cmp129=((($118))|0)<((($119))|0);if($cmp129){__label__=48;continue $for_body130$72;}else{__label__=58;break $for_body130$$for_end166$71;}}}}while(0);;return;return;}
function __ZL18count_pitch_vowelsiii($start,$end,$clause_end){;var __label__;var __lastLabel__=null;var $start_addr;var $end_addr;var $clause_end_addr;var $ix;var $stress;var $max_stress;var $max_stress_posn;var $max_stress_posn2;$start_addr=$start;$end_addr=$end;$clause_end_addr=$clause_end;$max_stress=0;$max_stress_posn=0;$max_stress_posn2=0;HEAP32[((__ZL10number_pre)>>2)]=-1;HEAP32[((__ZL11number_tail)>>2)]=0;HEAP32[((__ZL12last_primary)>>2)]=-1;var $0=$start_addr;$ix=$0;var $1=$ix;var $2=$end_addr;var $cmp1=((($1))|0)<((($2))|0);if($cmp1){__label__=1;;}else{__label__=11;;}
$for_body$$for_end$2:do{if(__label__==1){while(1){var $3=$ix;var $4=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx=(($4+6*$3)&4294967295);var $stress1=(($arrayidx)&4294967295);var $5=HEAP8[($stress1)];var $conv=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));$stress=$conv;var $6=$stress;var $7=$max_stress;var $cmp2=((($6))|0)>=((($7))|0);if($cmp2){__lastLabel__=1;__label__=2;;}else{__lastLabel__=1;__label__=6;;}
if(__label__==2){var $8=$stress;var $9=$max_stress;var $cmp3=((($8))|0)>((($9))|0);if($cmp3){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $10=$ix;$max_stress_posn2=$10;;}
else if(__label__==4){var $11=$max_stress_posn;$max_stress_posn2=$11;;}
var $12=$ix;$max_stress_posn=$12;var $13=$stress;$max_stress=$13;__lastLabel__=5;;}
var $14=__lastLabel__==5?$13:($6);var $cmp6=((($14))|0)>=4;if($cmp6){__label__=7;;}else{__label__=10;;}
if(__label__==7){var $15=HEAP32[((__ZL10number_pre)>>2)];var $cmp8=((($15))|0)<0;if($cmp8){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $16=$ix;var $17=$start_addr;var $sub=((($16)-($17))&4294967295);HEAP32[((__ZL10number_pre)>>2)]=$sub;;}
var $18=$ix;HEAP32[((__ZL12last_primary)>>2)]=$18;;}
var $19=$ix;var $inc=((($19)+1)&4294967295);$ix=$inc;var $20=$ix;var $21=$end_addr;var $cmp=((($20))|0)<((($21))|0);if($cmp){__label__=1;continue;}else{__label__=11;break $for_body$$for_end$2;}}}}while(0);var $22=HEAP32[((__ZL10number_pre)>>2)];var $cmp12=((($22))|0)<0;if($cmp12){__label__=12;;}else{__label__=13;;}
if(__label__==12){var $23=$end_addr;HEAP32[((__ZL10number_pre)>>2)]=$23;;}
var $24=$end_addr;var $25=$max_stress_posn;var $_neg=(((-($25)))&4294967295);var $sub15=((($24)-1)&4294967295);var $sub16=((($sub15)+($_neg))&4294967295);HEAP32[((__ZL11number_tail)>>2)]=$sub16;var $26=$max_stress_posn;HEAP32[((__ZL9tone_posn)>>2)]=$26;var $27=$max_stress_posn2;HEAP32[((__ZL10tone_posn2)>>2)]=$27;var $_b=HEAPU8[(__ZL8no_tonic_b)];var $28=((($_b))&1);var $tobool=((($28))|0)!=0;if($tobool){__label__=14;;}else{__label__=15;;}
$if_then17$$if_else18$22:do{if(__label__==14){var $29=$end_addr;HEAP32[((__ZL10tone_posn2)>>2)]=$29;HEAP32[((__ZL9tone_posn)>>2)]=$29;;}
else if(__label__==15){var $30=HEAP32[((__ZL12last_primary)>>2)];var $cmp19=((($30))|0)>=0;if($cmp19){__label__=16;;}else{__label__=18;;}
if(__label__==16){var $31=$end_addr;var $32=$clause_end_addr;var $cmp21=((($31))|0)==((($32))|0);if(!($cmp21)){__label__=19;break $if_then17$$if_else18$22;}
var $33=HEAP32[((__ZL12last_primary)>>2)];var $34=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx23=(($34+6*$33)&4294967295);var $stress24=(($arrayidx23)&4294967295);HEAP8[($stress24)]=7;;}
else if(__label__==18){var $35=HEAP32[((__ZL9tone_posn)>>2)];var $36=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx27=(($36+6*$35)&4294967295);var $stress28=(($arrayidx27)&4294967295);HEAP8[($stress28)]=7;;}}}while(0);;return;return;}
function __ZL12calc_pitchesiiii($control,$start,$end,$tune_number){;var __label__;var $retval;var $control_addr;var $start_addr;var $end_addr;var $tune_number_addr;var $ix;var $th;var $tn;var $drop;var $continuing;$control_addr=$control;$start_addr=$start;$end_addr=$end;$tune_number_addr=$tune_number;$continuing=0;var $0=$control_addr;var $cmp=((($0))|0)==0;var $1=$start_addr;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=$end_addr;var $3=$tune_number_addr;var $call=__ZL13calc_pitches2iii($1,$2,$3);$retval=$call;;}
else if(__label__==2){var $cmp1=((($1))|0)>0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){$continuing=1;;}
var $4=$tune_number_addr;var $arrayidx=((__ZL15tone_head_table+$4*16)&4294967295);$th=$arrayidx;var $5=$tune_number_addr;var $arrayidx4=((__ZL18tone_nucleus_table+$5*16)&4294967295);$tn=$arrayidx4;var $6=$start_addr;$ix=$6;var $7=$ix;var $8=$ix;var $9=HEAP32[((__ZL10number_pre)>>2)];var $add=((($9)+($8))&4294967295);var $10=$th;var $pre_start=(($10)&4294967295);var $11=HEAPU8[($pre_start)];var $conv=((($11))&255);var $12=$th;var $pre_end=(($12+1)&4294967295);var $13=HEAPU8[($pre_end)];var $conv5=((($13))&255);__ZL16SetPitchGradientiiii($7,$add,$conv,$conv5);var $14=HEAP32[((__ZL10number_pre)>>2)];var $15=$ix;var $add6=((($15)+($14))&4294967295);$ix=$add6;var $16=HEAP32[((_option_tone_flags)>>2)];var $and=($16)&512;var $tobool=((($and))|0)!=0;if($tobool){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $17=HEAP32[((__ZL10tone_posn2)>>2)];HEAP32[((__ZL9tone_posn)>>2)]=$17;;}
var $18=$ix;var $19=HEAP32[((__ZL9tone_posn)>>2)];var $20=$th;var $21=$tn;var $22=$continuing;var $call9=__ZL18calc_pitch_segmentiiP9TONE_HEADP12TONE_NUCLEUSii($18,$19,$20,$21,$22);$ix=$call9;var $_b=HEAPU8[(__ZL8no_tonic_b)];var $23=((($_b))&1);var $tobool10=((($23))|0)!=0;if($tobool10){__label__=7;;}else{__label__=8;;}
if(__label__==7){$retval=0;;}
else if(__label__==8){var $24=$tn;var $flags=(($24+14)&4294967295);var $25=HEAPU8[($flags)];var $conv13=((($25))&255);var $and14=($conv13)&1;var $tobool15=((($and14))|0)!=0;if($tobool15){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $26=$ix;var $27=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx17=(($27+6*$26)&4294967295);var $flags18=(($arrayidx17+2)&4294967295);var $28=HEAP8[($flags18)];var $conv19=(tempInt=(($28)),(tempInt>=128?tempInt-256:tempInt));var $or=($conv19)|2;var $conv20=((($or))&255);HEAP8[($flags18)]=$conv20;;}
var $29=HEAP32[((__ZL11number_tail)>>2)];var $cmp22=((($29))|0)==0;var $30=$tn;if($cmp22){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $pitch_env0=(($30)&4294967295);var $31=HEAPU8[($pitch_env0)];var $conv24=((($31))&255);HEAP32[((__ZL14tone_pitch_env)>>2)]=$conv24;var $32=$tn;var $tonic_max0=(($32+1)&4294967295);var $33=HEAPU8[($tonic_max0)];var $conv25=((($33))&255);var $34=$tn;var $tonic_min0=(($34+2)&4294967295);var $35=HEAPU8[($tonic_min0)];var $conv26=((($35))&255);var $sub=((($conv25)-($conv26))&4294967295);$drop=$sub;var $36=$ix;var $inc=((($36)+1)&4294967295);$ix=$inc;var $37=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx27=(($37+6*$36)&4294967295);var $38=$tn;var $tonic_min028=(($38+2)&4294967295);var $39=HEAPU8[($tonic_min028)];var $conv29=((($39))&255);var $40=$drop;__ZL9set_pitchP8SYLLABLEii($arrayidx27,$conv29,$40);;}
else if(__label__==12){var $pitch_env1=(($30+3)&4294967295);var $41=HEAPU8[($pitch_env1)];var $conv30=((($41))&255);HEAP32[((__ZL14tone_pitch_env)>>2)]=$conv30;var $42=$tn;var $tonic_max1=(($42+4)&4294967295);var $43=HEAPU8[($tonic_max1)];var $conv31=((($43))&255);var $44=$tn;var $tonic_min1=(($44+5)&4294967295);var $45=HEAPU8[($tonic_min1)];var $conv32=((($45))&255);var $sub33=((($conv31)-($conv32))&4294967295);$drop=$sub33;var $46=$ix;var $inc34=((($46)+1)&4294967295);$ix=$inc34;var $47=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx35=(($47+6*$46)&4294967295);var $48=$tn;var $tonic_min136=(($48+5)&4294967295);var $49=HEAPU8[($tonic_min136)];var $conv37=((($49))&255);var $50=$drop;__ZL9set_pitchP8SYLLABLEii($arrayidx35,$conv37,$50);;}
var $51=HEAP32[((__ZL14tone_pitch_env)>>2)];var $conv39=((($51))&255);var $52=HEAP32[((__ZL9tone_posn)>>2)];var $53=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx40=(($53+6*$52)&4294967295);var $env=(($arrayidx40+1)&4294967295);HEAP8[($env)]=$conv39;var $54=HEAP32[((__ZL9tone_posn)>>2)];var $55=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx41=(($55+6*$54)&4294967295);var $stress=(($arrayidx41)&4294967295);var $56=HEAP8[($stress)];var $conv42=(tempInt=(($56)),(tempInt>=128?tempInt-256:tempInt));var $cmp43=((($conv42))|0)==4;if($cmp43){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $57=HEAP32[((__ZL9tone_posn)>>2)];var $58=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx45=(($58+6*$57)&4294967295);var $stress46=(($arrayidx45)&4294967295);HEAP8[($stress46)]=6;;}
var $59=$ix;var $60=$end_addr;var $61=$tn;var $tail_start=(($61+12)&4294967295);var $62=HEAPU8[($tail_start)];var $conv48=((($62))&255);var $63=$tn;var $tail_end=(($63+13)&4294967295);var $64=HEAPU8[($tail_end)];var $conv49=((($64))&255);__ZL16SetPitchGradientiiii($59,$60,$conv48,$conv49);var $65=HEAP32[((__ZL14tone_pitch_env)>>2)];$retval=$65;;}};return;return;}
function __ZL13calc_pitches2iii($start,$end,$tune_number){;var __label__;var $retval;var $start_addr;var $end_addr;var $tune_number_addr;var $ix;var $tune;var $drop;var $continuing;$start_addr=$start;$end_addr=$end;$tune_number_addr=$tune_number;$continuing=0;var $0=$start_addr;var $cmp=((($0))|0)>0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$continuing=1;;}
var $1=$tune_number_addr;var $2=HEAP32[((_tunes)>>2)];var $arrayidx=(($2+68*$1)&4294967295);$tune=$arrayidx;var $3=$start_addr;$ix=$3;var $4=$ix;var $5=$ix;var $6=HEAP32[((__ZL10number_pre)>>2)];var $add=((($6)+($5))&4294967295);var $7=$tune;var $prehead_start=(($7+24)&4294967295);var $8=HEAPU8[($prehead_start)];var $conv=((($8))&255);var $9=$tune;var $prehead_end=(($9+25)&4294967295);var $10=HEAPU8[($prehead_end)];var $conv1=((($10))&255);__ZL16SetPitchGradientiiii($4,$add,$conv,$conv1);var $11=HEAP32[((__ZL10number_pre)>>2)];var $12=$ix;var $add2=((($12)+($11))&4294967295);$ix=$add2;var $13=HEAP32[((_option_tone_flags)>>2)];var $and=($13)&512;var $tobool=((($and))|0)!=0;if($tobool){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $14=HEAP32[((__ZL10tone_posn2)>>2)];HEAP32[((__ZL9tone_posn)>>2)]=$14;;}
var $15=$tune;var $16=$ix;var $17=HEAP32[((__ZL9tone_posn)>>2)];var $call=__ZL17SetHeadIntonationP4TUNEiii($15,$16,$17);$ix=$call;var $_b=HEAPU8[(__ZL8no_tonic_b)];var $18=((($_b))&1);var $tobool5=((($18))|0)!=0;if($tobool5){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=0;;}
else if(__label__==6){var $19=HEAP32[((__ZL11number_tail)>>2)];var $cmp8=((($19))|0)==0;var $20=$tune;if($cmp8){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $nucleus0_env=(($20+42)&4294967295);var $21=HEAPU8[($nucleus0_env)];var $conv10=((($21))&255);HEAP32[((__ZL14tone_pitch_env)>>2)]=$conv10;var $22=$tune;var $nucleus0_max=(($22+43)&4294967295);var $23=HEAPU8[($nucleus0_max)];var $conv11=((($23))&255);var $24=$tune;var $nucleus0_min=(($24+44)&4294967295);var $25=HEAPU8[($nucleus0_min)];var $conv12=((($25))&255);var $sub=((($conv11)-($conv12))&4294967295);$drop=$sub;var $26=$ix;var $inc=((($26)+1)&4294967295);$ix=$inc;var $27=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx13=(($27+6*$26)&4294967295);var $28=$tune;var $nucleus0_min14=(($28+44)&4294967295);var $29=HEAPU8[($nucleus0_min14)];var $conv15=((($29))&255);var $30=$drop;__ZL9set_pitchP8SYLLABLEii($arrayidx13,$conv15,$30);;}
else if(__label__==8){var $nucleus1_env=(($20+45)&4294967295);var $31=HEAPU8[($nucleus1_env)];var $conv16=((($31))&255);HEAP32[((__ZL14tone_pitch_env)>>2)]=$conv16;var $32=$tune;var $nucleus1_max=(($32+46)&4294967295);var $33=HEAPU8[($nucleus1_max)];var $conv17=((($33))&255);var $34=$tune;var $nucleus1_min=(($34+47)&4294967295);var $35=HEAPU8[($nucleus1_min)];var $conv18=((($35))&255);var $sub19=((($conv17)-($conv18))&4294967295);$drop=$sub19;var $36=$ix;var $inc20=((($36)+1)&4294967295);$ix=$inc20;var $37=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx21=(($37+6*$36)&4294967295);var $38=$tune;var $nucleus1_min22=(($38+47)&4294967295);var $39=HEAPU8[($nucleus1_min22)];var $conv23=((($39))&255);var $40=$drop;__ZL9set_pitchP8SYLLABLEii($arrayidx21,$conv23,$40);;}
var $41=HEAP32[((__ZL14tone_pitch_env)>>2)];var $conv25=((($41))&255);var $42=HEAP32[((__ZL9tone_posn)>>2)];var $43=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx26=(($43+6*$42)&4294967295);var $env=(($arrayidx26+1)&4294967295);HEAP8[($env)]=$conv25;var $44=HEAP32[((__ZL9tone_posn)>>2)];var $45=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx27=(($45+6*$44)&4294967295);var $stress=(($arrayidx27)&4294967295);var $46=HEAP8[($stress)];var $conv28=(tempInt=(($46)),(tempInt>=128?tempInt-256:tempInt));var $cmp29=((($conv28))|0)==4;if($cmp29){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $47=HEAP32[((__ZL9tone_posn)>>2)];var $48=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx31=(($48+6*$47)&4294967295);var $stress32=(($arrayidx31)&4294967295);HEAP8[($stress32)]=6;;}
var $49=$ix;var $50=$end_addr;var $51=$tune;var $tail_start=(($51+48)&4294967295);var $52=HEAPU8[($tail_start)];var $conv34=((($52))&255);var $53=$tune;var $tail_end=(($53+49)&4294967295);var $54=HEAPU8[($tail_end)];var $conv35=((($54))&255);__ZL16SetPitchGradientiiii($49,$50,$conv34,$conv35);var $55=HEAP32[((__ZL14tone_pitch_env)>>2)];$retval=$55;;}
var $56=$retval;;return $56;return null;}
function __ZL16SetPitchGradientiiii($start_ix,$end_ix,$start_pitch,$end_pitch){;var __label__;var __lastLabel__=null;var $start_ix_addr;var $end_ix_addr;var $start_pitch_addr;var $end_pitch_addr;var $ix;var $stress;var $pitch;var $increment;var $n_increments;var $drop;var $syl;$start_ix_addr=$start_ix;$end_ix_addr=$end_ix;$start_pitch_addr=$start_pitch;$end_pitch_addr=$end_pitch;var $0=$end_pitch_addr;var $1=$start_pitch_addr;var $sub=((($0)-($1))&4294967295);var $shl=($sub)<<8;$increment=$shl;var $2=$end_ix_addr;var $3=$start_ix_addr;var $sub1=((($2)-($3))&4294967295);$n_increments=$sub1;var $4=$n_increments;var $cmp=((($4))|0)<=0;if($cmp){__label__=12;;}else{__label__=1;;}
$for_end$$if_end$2:do{if(__label__==1){var $5=$n_increments;var $cmp2=((($5))|0)>1;if($cmp2){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $6=$increment;var $7=$n_increments;var $div=((((($6))|0)/((($7))|0))|0);$increment=$div;;}
var $8=$start_pitch_addr;var $shl5=($8)<<8;$pitch=$shl5;var $9=$start_ix_addr;$ix=$9;var $10=$ix;var $11=$end_ix_addr;var $cmp61=((($10))|0)<((($11))|0);if(!($cmp61)){__label__=12;break $for_end$$if_end$2;}
while(1){var $12=$ix;var $13=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx=(($13+6*$12)&4294967295);$syl=$arrayidx;var $14=$syl;var $stress7=(($14)&4294967295);var $15=HEAP8[($stress7)];var $conv=(tempInt=(($15)),(tempInt>=128?tempInt-256:tempInt));$stress=$conv;var $16=$increment;var $cmp8=((($16))|0)>0;if($cmp8){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $17=$syl;var $18=$pitch;var $shr=($18)>>8;var $19=$increment;var $shr10=($19)>>8;var $sub11=(((-($shr10)))&4294967295);__ZL9set_pitchP8SYLLABLEii($17,$shr,$sub11);var $20=$increment;var $21=$pitch;var $add=((($21)+($20))&4294967295);$pitch=$add;;}
else if(__label__==6){var $22=$increment;var $shr12=($22)>>8;var $sub13=(((-($shr12)))&4294967295);$drop=$sub13;var $23=$drop;var $24=$stress;var $arrayidx14=((__ZL8min_drop+$24*4)&4294967295);var $25=HEAP32[(($arrayidx14)>>2)];var $cmp15=((($23))|0)<((($25))|0);if($cmp15){__lastLabel__=6;__label__=7;;}else{__lastLabel__=6;__label__=8;;}
if(__label__==7){var $26=$stress;var $arrayidx17=((__ZL8min_drop+$26*4)&4294967295);var $27=HEAP32[(($arrayidx17)>>2)];$drop=$27;__lastLabel__=7;;}
var $28=__lastLabel__==7?$27:($23);var $29=$increment;var $30=$pitch;var $add19=((($30)+($29))&4294967295);$pitch=$add19;var $cmp20=((($28))|0)>18;if($cmp20){__label__=9;;}else{__label__=10;;}
if(__label__==9){$drop=18;;}
var $31=$syl;var $32=$pitch;var $shr23=($32)>>8;var $33=$drop;__ZL9set_pitchP8SYLLABLEii($31,$shr23,$33);;}
var $34=$ix;var $inc=((($34)+1)&4294967295);$ix=$inc;var $35=$ix;var $36=$end_ix_addr;var $cmp6=((($35))|0)<((($36))|0);if($cmp6){__label__=4;continue;}else{__label__=12;break $for_end$$if_end$2;}}}}while(0);;return;return;}
function __ZL18calc_pitch_segmentiiP9TONE_HEADP12TONE_NUCLEUSii($ix,$end_ix,$th,$tn,$continuing){;var __label__;var __lastLabel__=null;var $ix_addr;var $end_ix_addr;var $th_addr;var $tn_addr;var $min_stress_addr;var $continuing_addr;var $stress;var $pitch;var $increment;var $n_primary;var $n_steps;var $initial;var $overflow;var $n_overflow;var $pitch_range;var $pitch_range_abs;var $drops;var $overflow_tab;var $syl;$ix_addr=$ix;$end_ix_addr=$end_ix;$th_addr=$th;$tn_addr=$tn;$min_stress_addr=4;$continuing_addr=$continuing;$pitch=0;$increment=0;$n_primary=0;$n_steps=0;$overflow=0;var $0=$th_addr;var $body_drops=(($0+4)&4294967295);var $1=HEAP32[(($body_drops)>>2)];$drops=$1;var $2=$th_addr;var $body_end=(($2+3)&4294967295);var $3=HEAPU8[($body_end)];var $conv=((($3))&255);var $4=$th_addr;var $body_start=(($4+2)&4294967295);var $5=HEAPU8[($body_start)];var $conv1=((($5))&255);var $sub=((($conv)-($conv1))&4294967295);var $shl=($sub)<<8;$pitch_range=$shl;var $6=$pitch_range;var $ispos=((($6))|0)>-1;var $neg=(((-($6)))&4294967295);var $call=($ispos)?($6):($neg);$pitch_range_abs=$call;var $7=$continuing_addr;var $tobool=((($7))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){$initial=0;$overflow=0;$n_overflow=5;$overflow_tab=((__ZZL18calc_pitch_segmentiiP9TONE_HEADP12TONE_NUCLEUSiiE12continue_tab)&4294967295);var $8=$pitch_range;var $9=$th_addr;var $body_max_steps=(($9+8)&4294967295);var $10=HEAPU8[($body_max_steps)];var $conv2=((($10))&255);var $sub3=((($conv2)-1)&4294967295);var $div=((((($8))|0)/((($sub3))|0))|0);$increment=$div;;}
else if(__label__==2){var $11=$th_addr;var $n_overflow4=(($11+10)&4294967295);var $12=HEAPU8[($n_overflow4)];var $conv5=((($12))&255);$n_overflow=$conv5;var $13=$th_addr;var $overflow6=(($13+12)&4294967295);var $14=HEAP32[(($overflow6)>>2)];$overflow_tab=$14;$initial=1;;}
var $15=$ix_addr;var $16=$end_ix_addr;var $cmp4=((($15))|0)<((($16))|0);var $17=$ix_addr;if($cmp4){__lastLabel__=3;__label__=4;;}else{__lastLabel__=3;__label__=31;;}
$while_body$$while_end$6:do{if(__label__==4){$while_body$7:while(1){var $18=__lastLabel__==30?$90:($17);var $19=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx=(($19+6*$18)&4294967295);$syl=$arrayidx;var $20=$syl;var $stress7=(($20)&4294967295);var $21=HEAP8[($stress7)];var $conv8=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));$stress=$conv8;var $22=$initial;var $tobool9=((($22))|0)!=0;if($tobool9){__label__=8;;}else{__label__=5;;}
$if_then15$$lor_lhs_false$9:do{if(__label__==5){var $23=$stress;var $24=$min_stress_addr;var $cmp10=((($23))|0)>=((($24))|0);if($cmp10){__lastLabel__=5;;}else{__lastLabel__=5;__label__=23;break $if_then15$$lor_lhs_false$9;}
var $_pr=$initial;var $tobool12=((($_pr))|0)!=0;if($tobool12){__label__=8;break $if_then15$$lor_lhs_false$9;}
var $25=$stress;var $cmp14=((($25))|0)==5;if($cmp14){__label__=8;break $if_then15$$lor_lhs_false$9;}
var $39=$n_steps;var $cmp34=((($39))|0)>0;if($cmp34){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $40=$increment;var $41=$pitch;var $add=((($41)+($40))&4294967295);$pitch=$add;__label__=19;break $if_then15$$lor_lhs_false$9;}
else if(__label__==17){var $42=$th_addr;var $body_end37=(($42+3)&4294967295);var $43=HEAPU8[($body_end37)];var $conv38=((($43))&255);var $shl39=((($conv38)*256)&4294967295);var $44=$pitch_range_abs;var $45=$overflow;var $inc=((($45)+1)&4294967295);$overflow=$inc;var $46=$overflow_tab;var $arrayidx40=(($46+$45)&4294967295);var $47=HEAP8[($arrayidx40)];var $conv41=(tempInt=(($47)),(tempInt>=128?tempInt-256:tempInt));var $mul=((($conv41)*($44))&4294967295);var $div42=((((($mul))|0)/64)|0);var $add43=((($div42)+($shl39))&4294967295);$pitch=$add43;var $48=$overflow;var $49=$n_overflow;var $cmp44=((($48))|0)>=((($49))|0);if(!($cmp44)){__label__=19;break $if_then15$$lor_lhs_false$9;}
$overflow=0;var $50=$th_addr;var $overflow46=(($50+12)&4294967295);var $51=HEAP32[(($overflow46)>>2)];$overflow_tab=$51;__label__=19;break $if_then15$$lor_lhs_false$9;}}}while(0);$if_then15$$if_end49$$if_end59$18:do{if(__label__==8){$initial=0;$overflow=0;var $26=$ix_addr;var $27=$end_ix_addr;var $28=$min_stress_addr;var $call16=__ZL16count_incrementsiii($26,$27,$28);$n_primary=$call16;$n_steps=$call16;var $29=$n_steps;var $30=$th_addr;var $body_max_steps17=(($30+8)&4294967295);var $31=HEAPU8[($body_max_steps17)];var $conv18=((($31))&255);var $cmp19=((($29))|0)>((($conv18))|0);if($cmp19){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $32=$th_addr;var $body_max_steps21=(($32+8)&4294967295);var $33=HEAPU8[($body_max_steps21)];var $conv22=((($33))&255);$n_steps=$conv22;__lastLabel__=9;;}
else if(__label__==10){var $_pr2=$n_steps;__lastLabel__=10;;}
var $34=__lastLabel__==10?$_pr2:($conv22);var $cmp24=((($34))|0)>1;if($cmp24){__label__=12;;}else{__label__=13;;}
if(__label__==12){var $35=$pitch_range;var $36=$n_steps;var $sub26=((($36)-1)&4294967295);var $div27=((((($35))|0)/((($sub26))|0))|0);$increment=$div27;;}
else if(__label__==13){$increment=0;;}
var $37=$th_addr;var $body_start30=(($37+2)&4294967295);var $38=HEAPU8[($body_start30)];var $conv31=((($38))&255);var $shl32=($conv31)<<8;$pitch=$shl32;__label__=19;break $if_then15$$if_end49$$if_end59$18;}}while(0);if(__label__==19){var $52=$n_steps;var $dec=((($52)-1)&4294967295);$n_steps=$dec;var $53=$n_primary;var $dec50=((($53)-1)&4294967295);$n_primary=$dec50;var $54=$tn_addr;var $backwards=(($54+8)&4294967295);var $55=HEAP32[(($backwards)>>2)];var $tobool51=((($55))|0)!=0;if($tobool51){__label__=20;;}else{__label__=22;;}
$land_lhs_true$$if_end59thread_pre_split$30:do{if(__label__==20){var $56=$n_primary;var $cmp52=((($56))|0)<2;if(!($cmp52)){__label__=22;break $land_lhs_true$$if_end59thread_pre_split$30;}
var $57=$n_primary;var $58=$tn_addr;var $backwards54=(($58+8)&4294967295);var $59=HEAP32[(($backwards54)>>2)];var $arrayidx55=(($59+2*$57)&4294967295);var $60=HEAP16[(($arrayidx55)>>1)];var $conv56=(tempInt=(($60)),(tempInt>=32768?tempInt-65536:tempInt));var $shl57=($conv56)<<8;$pitch=$shl57;;}}while(0);var $_pr3=$stress;__lastLabel__=22;;}
var $61=__lastLabel__==22?$_pr3:($23);var $cmp60=((($61))|0)>=4;if($cmp60){__label__=24;;}else{__label__=25;;}
if(__label__==24){var $62=$syl;var $stress62=(($62)&4294967295);HEAP8[($stress62)]=6;var $63=$syl;var $64=$pitch;var $shr=($64)>>8;var $65=$stress;var $66=$drops;var $arrayidx63=(($66+4*$65)&4294967295);var $67=HEAP32[(($arrayidx63)>>2)];__ZL9set_pitchP8SYLLABLEii($63,$shr,$67);;}
else if(__label__==25){var $68=$stress;var $cmp65=((($68))|0)>=3;if($cmp65){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $69=$syl;var $70=$pitch;var $shr67=($70)>>8;var $71=$stress;var $72=$drops;var $arrayidx68=(($72+4*$71)&4294967295);var $73=HEAP32[(($arrayidx68)>>2)];__ZL9set_pitchP8SYLLABLEii($69,$shr67,$73);;}
else if(__label__==27){var $74=$ix_addr;var $sub70=((($74)-1)&4294967295);var $75=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx71=(($75+6*$sub70)&4294967295);var $stress72=(($arrayidx71)&4294967295);var $76=HEAP8[($stress72)];var $conv73=(tempInt=(($76)),(tempInt>=128?tempInt-256:tempInt));var $and=($conv73)&63;var $cmp74=((($and))|0)>=3;var $77=$syl;var $78=$pitch;var $shr76=($78)>>8;if($cmp74){__label__=28;;}else{__label__=29;;}
if(__label__==28){var $79=$th_addr;var $body_lower_u=(($79+9)&4294967295);var $80=HEAP8[($body_lower_u)];var $conv77=(tempInt=(($80)),(tempInt>=128?tempInt-256:tempInt));var $sub78=((($shr76)-($conv77))&4294967295);var $81=$stress;var $82=$drops;var $arrayidx79=(($82+4*$81)&4294967295);var $83=HEAP32[(($arrayidx79)>>2)];__ZL9set_pitchP8SYLLABLEii($77,$sub78,$83);;}
else if(__label__==29){var $84=$stress;var $85=$drops;var $arrayidx82=(($85+4*$84)&4294967295);var $86=HEAP32[(($arrayidx82)>>2)];__ZL9set_pitchP8SYLLABLEii($77,$shr76,$86);;}}}
var $87=$ix_addr;var $inc86=((($87)+1)&4294967295);$ix_addr=$inc86;var $88=$ix_addr;var $89=$end_ix_addr;var $cmp=((($88))|0)<((($89))|0);var $90=$ix_addr;if($cmp){__lastLabel__=30;__label__=4;continue $while_body$7;}else{__lastLabel__=30;__label__=31;break $while_body$$while_end$6;}}}}while(0);var $_lcssa=__lastLabel__==3?$17:($90);;return $_lcssa;return null;}
function __ZL9set_pitchP8SYLLABLEii($syl,$base,$drop){;var __label__;var __lastLabel__=null;var $syl_addr;var $base_addr;var $drop_addr;var $pitch1;var $pitch2;var $flags;$syl_addr=$syl;$base_addr=$base;$drop_addr=$drop;$flags=0;var $0=$base_addr;var $cmp=((($0))|0)<0;if($cmp){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=2;;}
if(__label__==1){$base_addr=0;var $_pr=$drop_addr;__lastLabel__=1;;}
var $1=__lastLabel__==1?$_pr:($drop);var $2=$base_addr;$pitch2=$2;var $cmp1=((($1))|0)<0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){$flags=1;var $3=$drop_addr;var $sub=(((-($3)))&4294967295);$drop_addr=$sub;;}
var $4=$pitch2;var $5=$drop_addr;var $add=((($5)+($4))&4294967295);$pitch1=$add;var $cmp4=((($add))|0)<0;if($cmp4){__label__=5;;}else{__label__=6;;}
$if_end6_thread$$if_end6$8:do{if(__label__==5){$pitch1=0;;}
else if(__label__==6){var $cmp7=((($add))|0)>254;if(!($cmp7)){__label__=8;break $if_end6_thread$$if_end6$8;}
$pitch1=254;;}}while(0);var $6=$pitch2;var $cmp10=((($6))|0)>254;if($cmp10){__label__=9;;}else{__label__=10;;}
if(__label__==9){$pitch2=254;;}
var $7=$pitch1;var $conv=((($7))&255);var $8=$syl_addr;var $pitch113=(($8+4)&4294967295);HEAP8[($pitch113)]=$conv;var $9=$pitch2;var $conv14=((($9))&255);var $10=$syl_addr;var $pitch215=(($10+5)&4294967295);HEAP8[($pitch215)]=$conv14;var $11=$flags;var $12=$syl_addr;var $flags16=(($12+2)&4294967295);var $13=HEAP8[($flags16)];var $conv17=(tempInt=(($13)),(tempInt>=128?tempInt-256:tempInt));var $or=($conv17)|($11);var $conv18=((($or))&255);HEAP8[($flags16)]=$conv18;;return;return;}
function __ZL16count_incrementsiii($ix,$end_ix,$min_stress){;var __label__;var $ix_addr;var $end_ix_addr;var $min_stress_addr;var $count;var $stress;$ix_addr=$ix;$end_ix_addr=$end_ix;$min_stress_addr=$min_stress;$count=0;;while(1){var $0=$ix_addr;var $1=$end_ix_addr;var $cmp=((($0))|0)<((($1))|0);if(!($cmp)){__label__=5;break;}
var $2=$ix_addr;var $inc=((($2)+1)&4294967295);$ix_addr=$inc;var $3=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx=(($3+6*$2)&4294967295);var $stress1=(($arrayidx)&4294967295);var $4=HEAP8[($stress1)];var $conv=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));$stress=$conv;var $5=$stress;var $cmp2=((($5))|0)>=7;if($cmp2){__label__=5;break;}
var $6=$stress;var $7=$min_stress_addr;var $cmp3=((($6))|0)>=((($7))|0);if(!($cmp3)){__label__=1;continue;}
var $8=$count;var $inc5=((($8)+1)&4294967295);$count=$inc5;__label__=1;continue;}
var $9=$count;;return $9;return null;}
function __ZL17SetHeadIntonationP4TUNEiii($tune,$syl_ix,$end_ix){;var __label__;var __lastLabel__=null;var $tune_addr;var $syl_ix_addr;var $end_ix_addr;var $control_addr;var $stress;var $syl;var $ix;var $pitch;var $increment;var $n_steps;var $stage;var $initial;var $overflow_ix;var $pitch_range;var $pitch_range_abs;var $drops;var $n_unstressed;var $unstressed_ix;var $unstressed_inc;var $used_onset;var $head_final;var $secondary;$tune_addr=$tune;$syl_ix_addr=$syl_ix;$end_ix_addr=$end_ix;$control_addr=0;$pitch=0;$increment=0;$n_steps=0;$overflow_ix=0;$n_unstressed=0;$unstressed_ix=0;$used_onset=0;var $0=$end_ix_addr;$head_final=$0;$secondary=2;var $1=$tune_addr;var $head_end=(($1+32)&4294967295);var $2=HEAPU8[($head_end)];var $conv=((($2))&255);var $3=$tune_addr;var $head_start=(($3+31)&4294967295);var $4=HEAPU8[($head_start)];var $conv1=((($4))&255);var $sub=((($conv)-($conv1))&4294967295);var $shl=($sub)<<8;$pitch_range=$shl;var $5=$pitch_range;var $ispos=((($5))|0)>-1;var $neg=(((-($5)))&4294967295);var $call=($ispos)?($5):($neg);$pitch_range_abs=$call;$drops=((__ZL7drops_0)&4294967295);$initial=1;$stage=0;var $6=$tune_addr;var $onset=(($6+30)&4294967295);var $7=HEAPU8[($onset)];var $conv2=((($7))&255);var $cmp=((($conv2))|0)==255;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$stage=1;;}
var $8=$tune_addr;var $head_last=(($8+33)&4294967295);var $9=HEAPU8[($head_last)];var $conv3=((($9))&255);var $cmp4=((($conv3))|0)!=255;if($cmp4){__label__=4;;}else{__label__=3;;}
$if_then5$$while_cond_preheader$5:do{if(__label__==4){var $13=$end_ix_addr;var $sub6=((($13)-1)&4294967295);$ix=$sub6;;while(1){var $14=$ix;var $15=$syl_ix_addr;var $cmp7=((($14))|0)>=((($15))|0);if(!($cmp7)){__label__=3;break $if_then5$$while_cond_preheader$5;}
var $16=$ix;var $17=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx=(($17+6*$16)&4294967295);var $stress8=(($arrayidx)&4294967295);var $18=HEAP8[($stress8)];var $conv9=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));var $cmp10=((($conv9))|0)>=4;var $19=$ix;if($cmp10){__label__=7;break;}
var $dec=((($19)-1)&4294967295);$ix=$dec;__label__=5;continue;}
$head_final=$19;;}}while(0);var $10=$syl_ix_addr;var $11=$end_ix_addr;var $cmp145=((($10))|0)<((($11))|0);var $12=$syl_ix_addr;if($cmp145){__lastLabel__=3;__label__=9;;}else{__lastLabel__=3;__label__=39;;}
$while_body$$while_end$13:do{if(__label__==9){$while_body$14:while(1){var $20=__lastLabel__==38?$108:($12);var $21=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx15=(($21+6*$20)&4294967295);$syl=$arrayidx15;var $22=$syl;var $stress16=(($22)&4294967295);var $23=HEAP8[($stress16)];var $conv17=(tempInt=(($23)),(tempInt>=128?tempInt-256:tempInt));$stress=$conv17;var $24=$initial;var $tobool=((($24))|0)!=0;if($tobool){__label__=13;;}else{__label__=10;;}
$if_then23$$lor_lhs_false$16:do{if(__label__==10){var $25=$stress;var $cmp18=((($25))|0)>=4;if(!($cmp18)){__label__=32;break $if_then23$$lor_lhs_false$16;}
var $_pr=$initial;var $tobool20=((($_pr))|0)!=0;if($tobool20){__label__=13;break $if_then23$$lor_lhs_false$16;}
var $26=$stress;var $cmp22=((($26))|0)==5;if($cmp22){__label__=13;break $if_then23$$lor_lhs_false$16;}
var $44=$syl_ix_addr;var $45=$head_final;var $cmp49=((($44))|0)==((($45))|0);if($cmp49){__label__=23;;}else{__label__=24;;}
if(__label__==23){var $46=$tune_addr;var $head_last51=(($46+33)&4294967295);var $47=HEAPU8[($head_last51)];var $conv52=((($47))&255);var $shl53=($conv52)<<8;$pitch=$shl53;$stage=2;__label__=30;break $if_then23$$lor_lhs_false$16;}
else if(__label__==24){var $48=$used_onset;var $tobool55=((($48))|0)!=0;if($tobool55){__label__=25;;}else{__label__=26;;}
if(__label__==25){$stage=1;$used_onset=0;var $49=$tune_addr;var $head_start57=(($49+31)&4294967295);var $50=HEAPU8[($head_start57)];var $conv58=((($50))&255);var $shl59=($conv58)<<8;$pitch=$shl59;var $51=$n_steps;var $inc=((($51)+1)&4294967295);$n_steps=$inc;__label__=30;break $if_then23$$lor_lhs_false$16;}
else if(__label__==26){var $52=$n_steps;var $cmp61=((($52))|0)>0;if($cmp61){__label__=27;;}else{__label__=28;;}
if(__label__==27){var $53=$increment;var $54=$pitch;var $add63=((($54)+($53))&4294967295);$pitch=$add63;__label__=30;break $if_then23$$lor_lhs_false$16;}
else if(__label__==28){var $55=$tune_addr;var $head_end65=(($55+32)&4294967295);var $56=HEAPU8[($head_end65)];var $conv66=((($56))&255);var $shl67=((($conv66)*256)&4294967295);var $57=$pitch_range_abs;var $58=$overflow_ix;var $inc68=((($58)+1)&4294967295);$overflow_ix=$inc68;var $59=$tune_addr;var $head_extend=(($59+16)&4294967295);var $arrayidx69=(($head_extend+$58)&4294967295);var $60=HEAP8[($arrayidx69)];var $conv70=(tempInt=(($60)),(tempInt>=128?tempInt-256:tempInt));var $mul=((($conv70)*($57))&4294967295);var $div71=((((($mul))|0)/64)|0);var $add72=((($div71)+($shl67))&4294967295);$pitch=$add72;var $61=$overflow_ix;var $62=$tune_addr;var $n_head_extend=(($62+35)&4294967295);var $63=HEAPU8[($n_head_extend)];var $conv73=((($63))&255);var $cmp74=((($61))|0)>=((($conv73))|0);if(!($cmp74)){__label__=30;break $if_then23$$lor_lhs_false$16;}
$overflow_ix=0;__label__=30;break $if_then23$$lor_lhs_false$16;}}}}}while(0);$if_then23$$if_end82$$if_else89$31:do{if(__label__==13){$initial=0;$overflow_ix=0;var $27=$tune_addr;var $onset24=(($27+30)&4294967295);var $28=HEAPU8[($onset24)];var $conv25=((($28))&255);var $cmp26=((($conv25))|0)==255;var $29=$syl_ix_addr;if($cmp26){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $30=$head_final;var $call28=__ZL16count_incrementsiii($29,$30,4);$n_steps=$call28;var $31=$tune_addr;var $head_start29=(($31+31)&4294967295);var $32=HEAPU8[($head_start29)];var $conv30=((($32))&255);var $shl31=($conv30)<<8;$pitch=$shl31;;}
else if(__label__==15){var $add=((($29)+1)&4294967295);var $33=$head_final;var $call32=__ZL16count_incrementsiii($add,$33,4);$n_steps=$call32;var $34=$tune_addr;var $onset33=(($34+30)&4294967295);var $35=HEAPU8[($onset33)];var $conv34=((($35))&255);var $shl35=($conv34)<<8;$pitch=$shl35;$used_onset=1;;}
var $36=$n_steps;var $37=$tune_addr;var $head_max_steps=(($37+34)&4294967295);var $38=HEAPU8[($head_max_steps)];var $conv37=((($38))&255);var $cmp38=((($36))|0)>((($conv37))|0);if($cmp38){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $39=$tune_addr;var $head_max_steps40=(($39+34)&4294967295);var $40=HEAPU8[($head_max_steps40)];var $conv41=((($40))&255);$n_steps=$conv41;__lastLabel__=17;;}
else if(__label__==18){var $_pr2=$n_steps;__lastLabel__=18;;}
var $41=__lastLabel__==18?$_pr2:($conv41);var $cmp43=((($41))|0)>1;if($cmp43){__label__=20;;}else{__label__=21;;}
if(__label__==20){var $42=$pitch_range;var $43=$n_steps;var $sub45=((($43)-1)&4294967295);var $div=((((($42))|0)/((($sub45))|0))|0);$increment=$div;__label__=30;break $if_then23$$if_end82$$if_else89$31;}
else if(__label__==21){$increment=0;__label__=30;break $if_then23$$if_end82$$if_else89$31;}}}while(0);$if_end82$$if_else89$44:do{if(__label__==30){var $64=$n_steps;var $dec81=((($64)-1)&4294967295);$n_steps=$dec81;var $_pr3=$stress;var $cmp83=((($_pr3))|0)>=4;if(!($cmp83)){__label__=32;break $if_end82$$if_else89$44;}
var $65=$syl_ix_addr;var $add85=((($65)+1)&4294967295);var $66=$end_ix_addr;var $67=$secondary;var $call86=__ZL15CountUnstressediii($add85,$66,$67);$n_unstressed=$call86;$unstressed_ix=0;var $68=$syl;var $stress87=(($68)&4294967295);HEAP8[($stress87)]=6;var $69=$tune_addr;var $stressed_env=(($69+26)&4294967295);var $70=HEAP8[($stressed_env)];var $71=$syl;var $env=(($71+1)&4294967295);HEAP8[($env)]=$70;var $72=$syl;var $73=$pitch;var $shr=($73)>>8;var $74=$tune_addr;var $stressed_drop=(($74+27)&4294967295);var $75=HEAPU8[($stressed_drop)];var $conv88=((($75))&255);__ZL9set_pitchP8SYLLABLEii($72,$shr,$conv88);__label__=38;break $if_end82$$if_else89$44;}}while(0);if(__label__==32){var $76=$stress;var $77=$secondary;var $cmp90=((($76))|0)>=((($77))|0);if($cmp90){__label__=33;;}else{__label__=34;;}
if(__label__==33){var $78=$syl_ix_addr;var $add92=((($78)+1)&4294967295);var $79=$end_ix_addr;var $80=$secondary;var $call93=__ZL15CountUnstressediii($add92,$79,$80);$n_unstressed=$call93;$unstressed_ix=0;var $81=$syl;var $82=$pitch;var $shr94=($82)>>8;var $83=$stress;var $84=$drops;var $arrayidx95=(($84+4*$83)&4294967295);var $85=HEAP32[(($arrayidx95)>>2)];__ZL9set_pitchP8SYLLABLEii($81,$shr94,$85);;}
else if(__label__==34){var $86=$n_unstressed;var $cmp97=((($86))|0)>1;if($cmp97){__label__=35;;}else{__label__=36;;}
if(__label__==35){var $87=$stage;var $88=$tune_addr;var $unstr_end=(($88+39)&4294967295);var $arrayidx99=(($unstr_end+$87)&4294967295);var $89=HEAP8[($arrayidx99)];var $conv100=(tempInt=(($89)),(tempInt>=128?tempInt-256:tempInt));var $90=$stage;var $91=$tune_addr;var $unstr_start=(($91+36)&4294967295);var $arrayidx101=(($unstr_start+$90)&4294967295);var $92=HEAP8[($arrayidx101)];var $conv102=(tempInt=(($92)),(tempInt>=128?tempInt-256:tempInt));var $sub103=((($conv100)-($conv102))&4294967295);var $93=$n_unstressed;var $sub104=((($93)-1)&4294967295);var $div105=((((($sub103))|0)/((($sub104))|0))|0);$unstressed_inc=$div105;;}
else if(__label__==36){$unstressed_inc=0;;}
var $94=$syl;var $95=$pitch;var $shr108=($95)>>8;var $96=$stage;var $97=$tune_addr;var $unstr_start109=(($97+36)&4294967295);var $arrayidx110=(($unstr_start109+$96)&4294967295);var $98=HEAP8[($arrayidx110)];var $conv111=(tempInt=(($98)),(tempInt>=128?tempInt-256:tempInt));var $99=$unstressed_inc;var $100=$unstressed_ix;var $mul113=((($100)*($99))&4294967295);var $add112=((($conv111)+($shr108))&4294967295);var $add114=((($add112)+($mul113))&4294967295);var $101=$stress;var $102=$drops;var $arrayidx115=(($102+4*$101)&4294967295);var $103=HEAP32[(($arrayidx115)>>2)];__ZL9set_pitchP8SYLLABLEii($94,$add114,$103);var $104=$unstressed_ix;var $inc116=((($104)+1)&4294967295);$unstressed_ix=$inc116;;}}
var $105=$syl_ix_addr;var $inc119=((($105)+1)&4294967295);$syl_ix_addr=$inc119;var $106=$syl_ix_addr;var $107=$end_ix_addr;var $cmp14=((($106))|0)<((($107))|0);var $108=$syl_ix_addr;if($cmp14){__lastLabel__=38;__label__=9;continue $while_body$14;}else{__lastLabel__=38;__label__=39;break $while_body$$while_end$13;}}}}while(0);var $_lcssa=__lastLabel__==3?$12:($108);;return $_lcssa;return null;}
function __ZL15CountUnstressediii($start,$end,$limit){;var __label__;var $start_addr;var $end_addr;var $limit_addr;var $ix;$start_addr=$start;$end_addr=$end;$limit_addr=$limit;var $0=$start_addr;$ix=$0;;while(1){var $1=$ix;var $2=$end_addr;var $cmp=((($1))|0)<=((($2))|0);if(!($cmp)){__label__=4;break;}
var $3=$ix;var $4=HEAP32[((__ZL12syllable_tab)>>2)];var $arrayidx=(($4+6*$3)&4294967295);var $stress=(($arrayidx)&4294967295);var $5=HEAP8[($stress)];var $conv=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $6=$limit_addr;var $cmp1=((($conv))|0)>=((($6))|0);if($cmp1){__label__=4;break;}
var $7=$ix;var $inc=((($7)+1)&4294967295);$ix=$inc;__label__=1;continue;}
var $8=$ix;var $9=$start_addr;var $sub=((($8)-($9))&4294967295);;return $sub;return null;}
function _iswalpha($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))>>>0)<256;var $1=$c_addr;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $call=_isalpha($1);$retval=$call;;}
else if(__label__==2){var $cmp1=((($1))>>>0)>12352;var $2=$c_addr;var $cmp2=((($2))>>>0)<=42752;var $or_cond=($cmp1)&($cmp2);if($or_cond){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=1;;}
else if(__label__==4){var $3=$c_addr;var $cmp5=((($3))>>>0)>563;if($cmp5){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=0;;}
else if(__label__==6){var $4=$c_addr;var $sub=((($4)-256)&4294967295);var $arrayidx=((_walpha_tab+$sub)&4294967295);var $5=HEAPU8[($arrayidx)];var $conv=((($5))&255);$retval=$conv;;}}}
var $6=$retval;;return $6;return null;}
function _iswdigit($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))>>>0)<256;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$c_addr;var $isdigittmp=((($1)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call=((($isdigit))&1);$retval=$call;;}
else if(__label__==2){$retval=0;;}
var $2=$retval;;return $2;return null;}
function _iswalnum($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $call=_iswdigit($0);var $tobool=((($call))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $1=$c_addr;var $call1=_iswalpha($1);$retval=$call1;;}
var $2=$retval;;return $2;return null;}
function _towlower($c){;var __label__;var $retval;var $c_addr;var $x;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))>>>0)<256;var $1=$c_addr;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){var $call=_tolower($1);$retval=$call;;}
else if(__label__==2){var $cmp1=((($1))>>>0)>563;if($cmp1){__label__=4;;}else{__label__=3;;}
$if_then3$$lor_lhs_false$5:do{if(__label__==3){var $2=$c_addr;var $sub=((($2)-256)&4294967295);var $arrayidx=((_walpha_tab+$sub)&4294967295);var $3=HEAPU8[($arrayidx)];var $conv=((($3))&255);$x=$conv;var $cmp2=((($conv))|0)==255;if($cmp2){__label__=4;break $if_then3$$lor_lhs_false$5;}
var $5=$x;var $cmp5=((($5))|0)==254;if($cmp5){__label__=6;;}else{__label__=8;;}
$if_then6$$if_end10$8:do{if(__label__==6){var $6=$c_addr;var $cmp7=((($6))|0)==304;if(!($cmp7)){__label__=8;break $if_then6$$if_end10$8;}
$retval=105;__label__=9;break $if_then$$if_end$2;}}while(0);var $7=$c_addr;var $8=$x;var $add=((($8)+($7))&4294967295);$retval=$add;__label__=9;break $if_then$$if_end$2;}}while(0);var $4=$c_addr;$retval=$4;;}}while(0);var $9=$retval;;return $9;return null;}
function _towupper($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $sub=((($0)-1)&4294967295);var $call=_tolower($sub);var $1=$c_addr;var $cmp=((($call))|0)==((($1))|0);var $2=$c_addr;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $sub1=((($2)-1)&4294967295);$retval=$sub1;;}
else if(__label__==2){$retval=$2;;}
var $3=$retval;;return $3;return null;}
function _iswupper($c){;var __label__;var $retval;var $c_addr;var $x;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))>>>0)<256;var $1=$c_addr;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){var $call=_isupper($1);$retval=$call;;}
else if(__label__==2){var $cmp1=((($1))>>>0)>563;if($cmp1){__label__=5;;}else{__label__=3;;}
$if_then5$$lor_lhs_false$5:do{if(__label__==3){var $2=$c_addr;var $sub=((($2)-256)&4294967295);var $arrayidx=((_walpha_tab+$sub)&4294967295);var $3=HEAPU8[($arrayidx)];var $conv=((($3))&255);$x=$conv;var $cmp2=((($conv))|0)==0;if($cmp2){__label__=5;break $if_then5$$lor_lhs_false$5;}
var $4=$x;var $cmp4=((($4))|0)==255;if($cmp4){__label__=5;break $if_then5$$lor_lhs_false$5;}
$retval=1;__label__=7;break $if_then$$if_end$2;}}while(0);$retval=0;;}}while(0);var $5=$retval;;return $5;return null;}
function _iswlower($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))>>>0)<256;var $1=$c_addr;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){var $call=_islower($1);$retval=$call;;}
else if(__label__==2){var $cmp1=((($1))>>>0)>563;if($cmp1){__label__=4;;}else{__label__=3;;}
$if_then3$$lor_lhs_false$5:do{if(__label__==3){var $2=$c_addr;var $sub=((($2)-256)&4294967295);var $arrayidx=((_walpha_tab+$sub)&4294967295);var $3=HEAPU8[($arrayidx)];var $conv=((($3))&255);var $cmp2=((($conv))|0)!=255;if($cmp2){__label__=4;break $if_then3$$lor_lhs_false$5;}
$retval=1;__label__=6;break $if_then$$if_end$2;}}while(0);$retval=0;;}}while(0);var $4=$retval;;return $4;return null;}
function _iswspace($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))>>>0)<256;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$c_addr;var $call=_isspace($1);$retval=$call;;}
else if(__label__==2){$retval=0;;}
var $2=$retval;;return $2;return null;}
function _iswpunct($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))>>>0)<256;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$c_addr;var $call=_ispunct($1);$retval=$call;;}
else if(__label__==2){$retval=0;;}
var $2=$retval;;return $2;return null;}
function _wcschr($str,$c){;var __label__;var $retval;var $str_addr;var $c_addr;$str_addr=$str;$c_addr=$c;;while(1){var $0=$str_addr;var $1=HEAP32[(($0)>>2)];var $cmp=((($1))|0)!=0;if(!($cmp)){__label__=5;break;}
var $2=$str_addr;var $3=HEAP32[(($2)>>2)];var $4=$c_addr;var $cmp1=((($3))|0)==((($4))|0);var $5=$str_addr;if($cmp1){__label__=3;break;}
var $incdec_ptr=(($5+4)&4294967295);$str_addr=$incdec_ptr;__label__=1;continue;}
if(__label__==5){$retval=0;;}
else if(__label__==3){$retval=$5;;}
var $6=$retval;;return $6;return null;}
function _wcslen($str){;var __label__;var __lastLabel__=null;var $str_addr;var $ix;$str_addr=$str;$ix=0;var $0=$str_addr;var $1=HEAP32[(($0)>>2)];var $cmp1=((($1))|0)!=0;var $2=$ix;if($cmp1){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=2;;}
$while_body$$while_end$2:do{if(__label__==1){while(1){var $3=__lastLabel__==1?$6:($2);var $inc=((($3)+1)&4294967295);$ix=$inc;var $4=$str_addr;var $5=HEAP32[(($4)>>2)];var $cmp=((($5))|0)!=0;var $6=$ix;if($cmp){__lastLabel__=1;__label__=1;continue;}else{__lastLabel__=1;__label__=2;break $while_body$$while_end$2;}}}}while(0);var $_lcssa=__lastLabel__==0?$2:($6);;return $_lcssa;return null;}
function _wcstod($str,$tailptr){var __stackBase__=STACKTOP;STACKTOP+=80;_memset(__stackBase__,0,80);var __label__;var __lastLabel__=null;var $str_addr;var $tailptr_addr;var $ix;var $buf=__stackBase__;$str_addr=$str;$tailptr_addr=$tailptr;var $0=$str_addr;var $1=HEAP32[(($0)>>2)];var $call1=_isspace($1);var $tobool2=((($call1))|0)!=0;if($tobool2){__label__=1;;}else{__label__=2;;}
$while_body$$while_end$2:do{if(__label__==1){while(1){var $2=$str_addr;var $incdec_ptr=(($2+4)&4294967295);$str_addr=$incdec_ptr;var $3=$str_addr;var $4=HEAP32[(($3)>>2)];var $call=_isspace($4);var $tobool=((($call))|0)!=0;if($tobool){__label__=1;continue;}else{__label__=2;break $while_body$$while_end$2;}}}}while(0);$ix=0;__lastLabel__=2;;while(1){var $5=__lastLabel__==5?$inc:(0);var $cmp=((($5))|0)<80;if(!($cmp)){__label__=6;break;}
var $6=$ix;var $7=$str_addr;var $arrayidx=(($7+4*$6)&4294967295);var $8=HEAP32[(($arrayidx)>>2)];var $conv=((($8))&255);var $9=$ix;var $arrayidx1=(($buf+$9)&4294967295);HEAP8[($arrayidx1)]=$conv;var $10=$ix;var $arrayidx2=(($buf+$10)&4294967295);var $11=HEAP8[($arrayidx2)];var $conv3=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $call4=_isspace($conv3);var $tobool5=((($call4))|0)!=0;if($tobool5){__label__=6;break;}
var $12=$ix;var $inc=((($12)+1)&4294967295);$ix=$inc;__lastLabel__=5;__label__=3;continue;}
var $13=$ix;var $14=$str_addr;var $arrayidx6=(($14+4*$13)&4294967295);var $15=$tailptr_addr;HEAP32[(($15)>>2)]=$arrayidx6;var $arraydecay=(($buf)&4294967295);var $call7=_atof($arraydecay);var $conv8=($call7);STACKTOP=__stackBase__;return $conv8;return null;}
function __Z9towlower2j($c){;var __label__;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))|0)==73;if($cmp){__label__=1;;}else{__label__=3;;}
$if_then$$if_end3$2:do{if(__label__==1){var $1=HEAP32[((_translator)>>2)];var $translator_name=(($1+280)&4294967295);var $2=HEAP32[(($translator_name)>>2)];var $cmp1=((($2))|0)==29810;if(!($cmp1)){__label__=3;break $if_then$$if_end3$2;}
$c_addr=305;;}}while(0);var $3=$c_addr;var $call=_towlower($3);;return $call;return null;}
function __Z3Eofv(){;var __label__;var $retval;var $0=HEAP32[((__ZL10ungot_char)>>2)];var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $1=HEAP32[((__ZL7f_input)>>2)];var $cmp1=((($1))|0)!=0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $2=HEAP32[((__ZL7f_input)>>2)];var $_flags=(($2+12)&4294967295);var $3=HEAP16[(($_flags)>>1)];var $conv=(tempInt=(($3)),(tempInt>=32768?tempInt-65536:tempInt));var $and=($conv)&32;var $cmp3=((($and))|0)!=0;var $conv4=((($cmp3))&1);$retval=$conv4;;}
else if(__label__==4){var $_b=HEAPU8[(__ZL12end_of_input_b)];var $4=((($_b))&1);$retval=$4;;}}
var $5=$retval;;return $5;return null;}
function __Z10Read4BytesP7__sFILE($f){;var __label__;var $f_addr;var $ix;var $c;var $acc;$f_addr=$f;$acc=0;$ix=0;;while(1){var $0=$f_addr;var $call=_fgetc($0);var $and=($call)&255;var $conv=((($and))&255);$c=$conv;var $1=$c;var $conv1=((($1))&255);var $2=$ix;var $mul=((($2)*8)&4294967295);var $shl=($conv1)<<($mul);var $3=$acc;var $add=((($shl)+($3))&4294967295);$acc=$add;var $4=$ix;var $inc=((($4)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<4;if($cmp){__label__=1;continue;}else{__label__=2;break;}}
var $5=$acc;;return $5;return null;}
function __Z11AddNameDataPKci($name,$wide){;var __label__;var $retval;var $name_addr;var $wide_addr;var $ix;var $len;var $vp;$name_addr=$name;$wide_addr=$wide;var $0=$wide_addr;var $tobool=((($0))|0)!=0;var $1=$name_addr;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=$1;var $call=_wcslen($2);var $add=((($call)+1)&4294967295);var $mul=((($add)*4)&4294967295);$len=$mul;var $3=HEAP32[((__ZL10n_namedata)>>2)];var $sub=((($3)+3)&4294967295);var $rem=((($sub))>>>0)%4;HEAP32[((__ZL10n_namedata)>>2)]=$rem;;}
else if(__label__==2){var $call2=_strlen($1);var $add3=((($call2)+1)&4294967295);$len=$add3;;}
var $4=HEAP32[((__ZL11namedata_ix)>>2)];var $5=$len;var $add4=((($5)+($4))&4294967295);var $6=HEAP32[((__ZL10n_namedata)>>2)];var $cmp=((($add4))|0)>=((($6))|0);if($cmp){__label__=4;;}else{__label__=7;;}
$if_then5$$if_end14$6:do{if(__label__==4){var $7=HEAP32[((_namedata)>>2)];var $8=HEAP32[((__ZL11namedata_ix)>>2)];var $9=$len;var $add6=((($8)+300)&4294967295);var $add7=((($add6)+($9))&4294967295);var $call8=_realloc($7,$add7);$vp=$call8;var $cmp9=((($call8))|0)==0;if($cmp9){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=-1;__label__=8;break $if_then5$$if_end14$6;}
else if(__label__==6){var $10=$vp;HEAP32[((_namedata)>>2)]=$10;var $11=HEAP32[((__ZL11namedata_ix)>>2)];var $12=$len;var $add12=((($11)+300)&4294967295);var $add13=((($add12)+($12))&4294967295);HEAP32[((__ZL10n_namedata)>>2)]=$add13;__label__=7;break $if_then5$$if_end14$6;}}}while(0);if(__label__==7){var $13=HEAP32[((__ZL11namedata_ix)>>2)];$ix=$13;var $14=HEAP32[((_namedata)>>2)];var $arrayidx=(($14+$13)&4294967295);var $15=$name_addr;var $16=$len;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$15;$dest$=$arrayidx;$stop$=$src$+$16;if(($dest$%4)==($src$%4)&&$16>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $17=$len;var $18=HEAP32[((__ZL11namedata_ix)>>2)];var $add15=((($18)+($17))&4294967295);HEAP32[((__ZL11namedata_ix)>>2)]=$add15;var $19=$ix;$retval=$19;;}
var $20=$retval;;return $20;return null;}
function __Z13SetVoiceStackP12espeak_VOICE($v){;var __label__;var $v_addr;var $sp;$v_addr=$v;$sp=((__ZL10ssml_stack)&4294967295);var $0=$v_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$sp;var $2=$1;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$2;$stop$=$dest$+76;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};;}
else if(__label__==2){var $3=$v_addr;var $languages=(($3+4)&4294967295);var $4=HEAP32[(($languages)>>2)];var $cmp1=((($4))|0)!=0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $5=$sp;var $language=(($5+56)&4294967295);var $arraydecay=(($language)&4294967295);var $6=$v_addr;var $languages3=(($6+4)&4294967295);var $7=HEAP32[(($languages3)>>2)];var $call=_strcpy($arraydecay,$7);;}
var $8=$v_addr;var $name=(($8)&4294967295);var $9=HEAP32[(($name)>>2)];var $cmp5=((($9))|0)!=0;if($cmp5){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $10=$sp;var $voice_name=(($10+16)&4294967295);var $arraydecay7=(($voice_name)&4294967295);var $11=$v_addr;var $name8=(($11)&4294967295);var $12=HEAP32[(($name8)>>2)];var $call9=_strcpy($arraydecay7,$12);;}
var $13=$v_addr;var $variant=(($13+14)&4294967295);var $14=HEAPU8[($variant)];var $conv=((($14))&255);var $15=$sp;var $voice_variant=(($15+4)&4294967295);HEAP32[(($voice_variant)>>2)]=$conv;var $16=$v_addr;var $age=(($16+13)&4294967295);var $17=HEAPU8[($age)];var $conv11=((($17))&255);var $18=$sp;var $voice_age=(($18+12)&4294967295);HEAP32[(($voice_age)>>2)]=$conv11;var $19=$v_addr;var $gender=(($19+12)&4294967295);var $20=HEAPU8[($gender)];var $conv12=((($20))&255);var $21=$sp;var $voice_gender=(($21+8)&4294967295);HEAP32[(($voice_gender)>>2)]=$conv12;;};return;return;}
function __Z10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_($tr,$f_in,$buf,$charix,$charix_top,$n_buf,$tone_type,$voice_change){var __stackBase__=STACKTOP;STACKTOP+=1136;_memset(__stackBase__,0,1136);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $f_in_addr;var $buf_addr;var $charix_addr;var $charix_top_addr;var $n_buf_addr;var $tone_type_addr;var $voice_change_addr;var $c1=__stackBase__;var $c2=__stackBase__+4;var $cprev;var $cprev2;var $c_next;var $parag;var $ix=__stackBase__+8;var $j;var $nl_count;var $linelength;var $phoneme_mode;var $n_xml_buf;var $terminator;var $punct;var $found;var $any_alnum;var $self_closing;var $punct_data;var $is_end_clause;var $announced_punctuation;var $prev_announced_punctuation;var $stressed_word;var $end_clause_after_tag;var $end_clause_index;var $xml_buf=__stackBase__+12;var $xml_buf2=__stackBase__+1040;var $p_word;var $text_buf=__stackBase__+1064;var $text_buf2=__stackBase__+1104;var $p2;$tr_addr=$tr;$f_in_addr=$f_in;$buf_addr=$buf;$charix_addr=$charix;$charix_top_addr=$charix_top;$n_buf_addr=$n_buf;$tone_type_addr=$tone_type;$voice_change_addr=$voice_change;HEAP32[(($c1)>>2)]=32;$cprev=32;$cprev2=32;HEAP32[(($ix)>>2)]=0;$linelength=0;$phoneme_mode=0;$any_alnum=0;$punct_data=0;$announced_punctuation=0;$stressed_word=0;$end_clause_after_tag=0;$end_clause_index=0;var $_b=HEAPU8[(__ZL19clear_skipping_text_b)];var $0=((($_b))&1);var $tobool=((($0))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((_skipping_text)>>2)]=0;HEAP8[(__ZL19clear_skipping_text_b)]=0;;}
var $1=$tr_addr;var $phonemes_repeat_count=(($1+652)&4294967295);HEAP32[(($phonemes_repeat_count)>>2)]=0;var $2=$tr_addr;var $clause_upper_count=(($2+8304)&4294967295);HEAP32[(($clause_upper_count)>>2)]=0;var $3=$tr_addr;var $clause_lower_count=(($3+8308)&4294967295);HEAP32[(($clause_lower_count)>>2)]=0;HEAP8[(__ZL12end_of_input_b)]=0;var $4=$tone_type_addr;HEAP32[(($4)>>2)]=0;var $5=$voice_change_addr;HEAP8[($5)]=0;var $6=$f_in_addr;HEAP32[((__ZL7f_input)>>2)]=$6;var $7=HEAP32[((__ZL10ungot_word)>>2)];var $cmp=((($7))|0)!=0;if($cmp){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $8=$buf_addr;var $9=HEAP32[((__ZL10ungot_word)>>2)];var $call=_strcpy($8,$9);var $10=HEAP32[((__ZL10ungot_word)>>2)];var $call2=_strlen($10);var $11=HEAP32[(($ix)>>2)];var $add=((($11)+($call2))&4294967295);HEAP32[(($ix)>>2)]=$add;HEAP32[((__ZL10ungot_word)>>2)]=0;;}
var $12=HEAP32[((__ZL11ungot_char2)>>2)];var $cmp4=((($12))|0)!=0;if($cmp4){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $13=HEAP32[((__ZL11ungot_char2)>>2)];HEAP32[(($c2)>>2)]=$13;;}
else if(__label__==6){var $call6=__ZL4GetCv();HEAP32[(($c2)>>2)]=$call6;;}
var $arrayidx82=(($xml_buf2)&4294967295);var $arrayidx86=(($xml_buf2)&4294967295);var $arrayidx90=(($xml_buf2+1)&4294967295);var $arrayidx94=(($xml_buf2+2)&4294967295);var $arrayidx97=(($xml_buf2+1)&4294967295);var $arraydecay=(($xml_buf2)&4294967295);var $arraydecay164=(($xml_buf)&4294967295);var $arraydecay324=(($text_buf2)&4294967295);var $arraydecay328=(($text_buf)&4294967295);var $arraydecay329=(($text_buf2)&4294967295);var $arraydecay331=(($text_buf)&4294967295);var $arraydecay337=(($text_buf)&4294967295);;$while_cond$12:while(1){var $call8=__Z3Eofv();var $tobool9=((($call8))|0)==0;var $14=HEAP32[((__ZL10ungot_char)>>2)];var $cmp10=((($14))|0)!=0;var $or_cond=($tobool9)|($cmp10);var $15=HEAP32[((__ZL11ungot_char2)>>2)];var $cmp12=((($15))|0)!=0;var $or_cond3=($or_cond)|($cmp12);var $16=HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)];var $cmp13=((($16))|0)>=0;var $or_cond19=($or_cond3)|($cmp13);if(!($or_cond19)){__label__=256;break $while_cond$12;}
var $17=HEAP32[(($c1)>>2)];var $call14=_iswalnum($17);var $tobool15=((($call14))|0)!=0;if($tobool15){__label__=16;;}else{__label__=10;;}
$if_end26$$if_then16$15:do{if(__label__==10){var $18=HEAP32[((_end_character_position)>>2)];var $cmp17=((($18))|0)>0;if($cmp17){__label__=11;;}else{__label__=13;;}
if(__label__==11){var $19=HEAP32[((_count_characters)>>2)];var $20=HEAP32[((_end_character_position)>>2)];var $cmp18=((($19))|0)>((($20))|0);if($cmp18){__label__=12;break $while_cond$12;}}
var $21=HEAP32[((_skip_characters)>>2)];var $cmp21=((($21))|0)>0;if(!($cmp21)){__label__=16;break $if_end26$$if_then16$15;}
var $22=HEAP32[((_count_characters)>>2)];var $23=HEAP32[((_skip_characters)>>2)];var $cmp23=((($22))|0)>((($23))|0);if($cmp23){__label__=15;break $while_cond$12;}}}while(0);var $25=$cprev;$cprev2=$25;var $26=HEAP32[(($c1)>>2)];$cprev=$26;var $27=HEAP32[(($c2)>>2)];HEAP32[(($c1)>>2)]=$27;var $28=HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)];var $cmp27=((($28))|0)>=0;if($cmp27){__label__=17;;}else{__label__=19;;}
$if_then28$$if_end32$22:do{if(__label__==17){var $29=HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)];var $arrayidx=((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E12ungot_string+$29)&4294967295);var $30=HEAP8[($arrayidx)];var $conv=(tempInt=(($30)),(tempInt>=128?tempInt-256:tempInt));var $cmp29=((($conv))|0)==0;if(!($cmp29)){__label__=19;break $if_then28$$if_end32$22;}
HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)]=-1;;}}while(0);var $31=HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)];var $cmp33=((($31))|0)==0;var $32=HEAP32[((__ZL11ungot_char2)>>2)];var $cmp35=((($32))|0)==0;var $or_cond4=($cmp33)&($cmp35);if($or_cond4){__lastLabel__=19;__label__=20;;}else{__lastLabel__=19;__label__=21;;}
if(__label__==20){var $33=HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)];var $inc=((($33)+1)&4294967295);HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)]=$inc;var $arrayidx37=((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E12ungot_string+$33)&4294967295);var $34=HEAP8[($arrayidx37)];var $conv38=(tempInt=(($34)),(tempInt>=128?tempInt-256:tempInt));HEAP32[(($c1)>>2)]=$conv38;__lastLabel__=20;;}
var $35=__lastLabel__==20?$inc:($31);var $cmp40=((($35))|0)>=0;if($cmp40){__label__=22;;}else{__label__=23;;}
$if_then41$$if_else45$29:do{if(__label__==22){var $36=HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)];var $inc42=((($36)+1)&4294967295);HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)]=$inc42;var $arrayidx43=((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E12ungot_string+$36)&4294967295);var $37=HEAP8[($arrayidx43)];var $conv44=(tempInt=(($37)),(tempInt>=128?tempInt-256:tempInt));HEAP32[(($c2)>>2)]=$conv44;;}
else if(__label__==23){var $call46=__ZL4GetCv();HEAP32[(($c2)>>2)]=$call46;var $call47=__Z3Eofv();var $tobool48=((($call47))|0)!=0;if(!($tobool48)){__label__=25;break $if_then41$$if_else45$29;}
HEAP32[(($c2)>>2)]=32;;}}while(0);HEAP32[((__ZL11ungot_char2)>>2)]=0;var $38=HEAP32[((_option_ssml)>>2)];var $tobool52=((($38))|0)!=0;if($tobool52){__label__=26;;}else{__label__=72;;}
$land_lhs_true53$$if_end184$34:do{if(__label__==26){var $39=$phoneme_mode;var $cmp54=((($39))|0)==0;if(!($cmp54)){__label__=72;break $land_lhs_true53$$if_end184$34;}
var $40=HEAP32[((__ZL19ssml_ignore_l_angle)>>2)];var $cmp56=((($40))|0)!=38;if($cmp56){__label__=28;;}else{__label__=50;;}
$land_lhs_true57$$if_else122$37:do{if(__label__==28){var $41=HEAP32[(($c1)>>2)];var $cmp58=((($41))|0)==38;if(!($cmp58)){__label__=50;break $land_lhs_true57$$if_else122$37;}
var $42=HEAP32[(($c2)>>2)];var $cmp60=((($42))|0)==35;if($cmp60){__label__=31;;}else{__label__=30;;}
if(__label__==30){var $43=HEAP32[(($c2)>>2)];var $cmp62=((($43))|0)>=97;var $44=HEAP32[(($c2)>>2)];var $cmp64=((($44))|0)<=122;var $or_cond5=($cmp62)&($cmp64);if(!($or_cond5)){__label__=50;break $land_lhs_true57$$if_else122$37;}}
$n_xml_buf=0;var $45=HEAP32[(($c2)>>2)];HEAP32[(($c1)>>2)]=$45;;$while_cond66$43:while(1){var $call67=__Z3Eofv();var $tobool68=((($call67))|0)!=0;if($tobool68){__label__=36;break $while_cond66$43;}
var $46=HEAP32[(($c1)>>2)];var $call70=_iswalnum($46);var $tobool71=((($call70))|0)!=0;var $47=HEAP32[(($c1)>>2)];var $cmp73=((($47))|0)==35;var $or_cond6=($tobool71)|($cmp73);if(!($or_cond6)){__label__=36;break $while_cond66$43;}
var $48=$n_xml_buf;var $cmp74=((($48))|0)<20;if(!($cmp74)){__label__=36;break $while_cond66$43;}
var $49=HEAP32[(($c1)>>2)];var $conv76=((($49))&255);var $50=$n_xml_buf;var $inc77=((($50)+1)&4294967295);$n_xml_buf=$inc77;var $arrayidx78=(($xml_buf2+$50)&4294967295);HEAP8[($arrayidx78)]=$conv76;var $call79=__ZL4GetCv();HEAP32[(($c1)>>2)]=$call79;__label__=32;continue $while_cond66$43;}
var $51=$n_xml_buf;var $arrayidx80=(($xml_buf2+$51)&4294967295);HEAP8[($arrayidx80)]=0;var $call81=__ZL4GetCv();HEAP32[(($c2)>>2)]=$call81;var $52=HEAP32[(($c1)>>2)];var $53=HEAP32[(($c2)>>2)];var $call83=_sprintf(((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E12ungot_string)&4294967295),((__str38205)&4294967295),allocate([$arrayidx82,0,0,0,$52,0,0,0,$53,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $54=HEAP32[(($c1)>>2)];var $cmp84=((($54))|0)==59;if($cmp84){__label__=37;;}else{__label__=44;;}
$if_then85$$if_else109$49:do{if(__label__==37){var $55=HEAP8[($arrayidx86)];var $conv87=(tempInt=(($55)),(tempInt>=128?tempInt-256:tempInt));var $cmp88=((($conv87))|0)==35;if($cmp88){__label__=38;;}else{__label__=41;;}
$if_then89$$if_else100$51:do{if(__label__==38){var $56=HEAP8[($arrayidx90)];var $conv91=(tempInt=(($56)),(tempInt>=128?tempInt-256:tempInt));var $cmp92=((($conv91))|0)==120;if($cmp92){__label__=39;;}else{__label__=40;;}
if(__label__==39){var $call95=_sscanf($arrayidx94,((__str10307)&4294967295),allocate([$c1,0,0,0],["i32*",0,0,0],ALLOC_STACK));$found=$call95;__lastLabel__=39;;}
else if(__label__==40){var $call98=_sscanf($arrayidx97,((__str63715)&4294967295),allocate([$c1,0,0,0],["i32*",0,0,0],ALLOC_STACK));$found=$call98;__lastLabel__=40;;}}
else if(__label__==41){var $call101=__Z10LookupMnemP8MNEM_TABPKc(((__ZL18xml_char_mnemonics)&4294967295),$arraydecay);$found=$call101;var $cmp102=((($call101))|0)!=-1;if(!($cmp102)){__label__=46;break $if_then85$$if_else109$49;}
var $57=$found;HEAP32[(($c1)>>2)]=$57;var $58=HEAP32[(($c2)>>2)];var $cmp104=((($58))|0)==0;if($cmp104){__lastLabel__=42;;}else{__lastLabel__=42;__label__=45;break $if_then89$$if_else100$51;}
HEAP32[(($c2)>>2)]=32;var $_pr=$found;__lastLabel__=43;;}}while(0);var $59=__lastLabel__==40?$call98:(__lastLabel__==39?$call95:(__lastLabel__==42?$57:($_pr)));var $cmp111=((($59))|0)<=0;if($cmp111){__label__=46;break $if_then85$$if_else109$49;}
var $_pr23=HEAP32[(($c1)>>2)];var $cmp114=((($_pr23))|0)<=32;if(!($cmp114)){__label__=72;break $land_lhs_true53$$if_end184$34;}
var $60=HEAP32[((__ZL10sayas_mode)>>2)];var $cmp116=((($60))|0)==20;var $61=HEAP32[((__ZL10sayas_mode)>>2)];var $cmp118=((($61))|0)==36;var $or_cond8=($cmp116)|($cmp118);if(!($or_cond8)){__label__=72;break $land_lhs_true53$$if_end184$34;}
var $62=HEAP32[(($c1)>>2)];var $add120=((($62)+57344)&4294967295);HEAP32[(($c1)>>2)]=$add120;__label__=72;break $land_lhs_true53$$if_end184$34;}
else if(__label__==44){$found=-1;;}}while(0);HEAP32[((__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix)>>2)]=0;HEAP32[(($c1)>>2)]=38;HEAP32[(($c2)>>2)]=32;__label__=72;break $land_lhs_true53$$if_end184$34;}}while(0);var $63=HEAP32[(($c1)>>2)];var $cmp123=((($63))|0)==60;var $64=HEAP32[((__ZL19ssml_ignore_l_angle)>>2)];var $cmp125=((($64))|0)!=60;var $or_cond9=($cmp123)&($cmp125);if(!($or_cond9)){__label__=72;break $land_lhs_true53$$if_end184$34;}
var $65=HEAP32[(($c2)>>2)];var $cmp127=((($65))|0)==33;if($cmp127){__label__=52;;}else{__label__=56;;}
if(__label__==52){while(1){var $call130=__Z3Eofv();var $tobool131=((($call130))|0)!=0;if($tobool131){__label__=55;break;}
var $66=HEAP32[(($c1)>>2)];var $cmp133=((($66))|0)!=62;if(!($cmp133)){__label__=55;break;}
var $call136=__ZL4GetCv();HEAP32[(($c1)>>2)]=$call136;__label__=52;continue;}
HEAP32[(($c2)>>2)]=32;;}
else if(__label__==56){var $67=HEAP32[(($c2)>>2)];var $cmp139=((($67))|0)==47;if($cmp139){__label__=58;;}else{__label__=57;;}
if(__label__==57){var $68=HEAP32[(($c2)>>2)];var $call141=_iswalpha($68);var $tobool142=((($call141))|0)!=0;if(!($tobool142)){__label__=72;break $land_lhs_true53$$if_end184$34;}}
$n_xml_buf=0;var $69=HEAP32[(($c2)>>2)];HEAP32[(($c1)>>2)]=$69;;while(1){var $call145=__Z3Eofv();var $tobool146=((($call145))|0)!=0;if($tobool146){__label__=63;break;}
var $70=HEAP32[(($c1)>>2)];var $cmp148=((($70))|0)!=62;if(!($cmp148)){__label__=63;break;}
var $71=$n_xml_buf;var $cmp150=((($71))|0)<256;if(!($cmp150)){__label__=63;break;}
var $72=HEAP32[(($c1)>>2)];var $73=$n_xml_buf;var $inc153=((($73)+1)&4294967295);$n_xml_buf=$inc153;var $arrayidx154=(($xml_buf+$73*4)&4294967295);HEAP32[(($arrayidx154)>>2)]=$72;var $call155=__ZL4GetCv();HEAP32[(($c1)>>2)]=$call155;__label__=59;continue;}
var $74=$n_xml_buf;var $arrayidx157=(($xml_buf+$74*4)&4294967295);HEAP32[(($arrayidx157)>>2)]=0;HEAP32[(($c2)>>2)]=32;$self_closing=0;var $75=$n_xml_buf;var $sub=((($75)-1)&4294967295);var $arrayidx158=(($xml_buf+$sub*4)&4294967295);var $76=HEAP32[(($arrayidx158)>>2)];var $cmp159=((($76))|0)==47;if($cmp159){__label__=64;;}else{__label__=65;;}
if(__label__==64){var $77=$n_xml_buf;var $sub161=((($77)-1)&4294967295);var $arrayidx162=(($xml_buf+$sub161*4)&4294967295);HEAP32[(($arrayidx162)>>2)]=32;$self_closing=1;;}
var $78=$buf_addr;var $79=$n_buf_addr;var $80=$self_closing;var $call165=__ZL14ProcessSsmlTagPwPcRiii($arraydecay164,$78,$ix,$79,$80);$terminator=$call165;var $cmp166=((($call165))|0)!=0;if($cmp166){__label__=66;break $while_cond$12;}
HEAP32[(($c1)>>2)]=32;var $call179=__ZL4GetCv();HEAP32[(($c2)>>2)]=$call179;__label__=8;continue $while_cond$12;}}}while(0);HEAP32[((__ZL19ssml_ignore_l_angle)>>2)]=0;var $_b1=HEAPU8[(__ZL11ignore_text_b)];var $90=((($_b1))&1);var $tobool185=((($90))|0)!=0;if($tobool185){__label__=8;continue $while_cond$12;}
var $91=HEAP32[(($c2)>>2)];var $cmp188=((($91))|0)==10;var $92=HEAP32[((_option_linelength)>>2)];var $cmp190=((($92))|0)==-1;var $or_cond11=($cmp188)&($cmp190);var $93=HEAPU32[(($c1)>>2)];if($or_cond11){__label__=74;break $while_cond$12;}
var $cmp208=((($93))|0)==1;if($cmp208){__label__=80;;}else{__label__=79;;}
$if_then212$$lor_lhs_false209$90:do{if(__label__==79){var $111=HEAP32[(($c1)>>2)];var $112=HEAP8[(_ctrl_embedded)];var $conv210=(tempInt=(($112)),(tempInt>=128?tempInt-256:tempInt));var $cmp211=((($111))|0)==((($conv210))|0);if($cmp211){__label__=80;break $if_then212$$lor_lhs_false209$90;}else{__label__=97;break $if_then212$$lor_lhs_false209$90;}}}while(0);$if_then212$$if_end267$92:do{if(__label__==80){var $113=HEAP32[(($c2)>>2)];var $cmp213=((($113))|0)==86;if($cmp213){__label__=81;break $while_cond$12;}
var $123=HEAP32[(($c2)>>2)];var $cmp236=((($123))|0)==66;if(!($cmp236)){__label__=97;break $if_then212$$if_end267$92;}
var $124=HEAP32[(($ix)>>2)];var $125=$buf_addr;var $arrayidx238=(($125+$124)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str41208)&4294967295);$dest$=$arrayidx238;$stop$=$src$+4;if(($dest$%4)==($src$%4)&&4>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $126=HEAP32[(($ix)>>2)];var $add240=((($126)+3)&4294967295);HEAP32[(($ix)>>2)]=$add240;var $call241=__ZL4GetCv();HEAP32[(($c2)>>2)]=$call241;var $cmp242=((($call241))|0)==48;if($cmp242){__label__=89;;}else{__label__=90;;}
$if_then243$$if_else244$96:do{if(__label__==89){HEAP32[((_option_punctuation)>>2)]=0;;}
else if(__label__==90){HEAP32[((_option_punctuation)>>2)]=1;HEAP32[((((_option_punctlist)&4294967295))>>2)]=0;var $127=HEAP32[(($c2)>>2)];var $cmp245=((($127))|0)!=49;if(!($cmp245)){__label__=96;break $if_then243$$if_else244$96;}
$j=0;;while(1){var $128=HEAP32[(($c2)>>2)];var $call248=_iswspace($128);var $tobool249=((($call248))|0)!=0;if($tobool249){__label__=95;break;}
var $call251=__Z3Eofv();var $tobool252=((($call251))|0)!=0;var $lnot=($tobool252)^1;if(!($lnot)){__label__=95;break;}
var $129=HEAP32[(($c2)>>2)];var $130=$j;var $inc255=((($130)+1)&4294967295);$j=$inc255;var $arrayidx256=((_option_punctlist+$130*4)&4294967295);HEAP32[(($arrayidx256)>>2)]=$129;var $call257=__ZL4GetCv();HEAP32[(($c2)>>2)]=$call257;var $131=HEAP32[(($ix)>>2)];var $inc258=((($131)+1)&4294967295);HEAP32[(($ix)>>2)]=$inc258;var $132=$buf_addr;var $arrayidx259=(($132+$131)&4294967295);HEAP8[($arrayidx259)]=32;__label__=92;continue;}
var $133=$j;var $arrayidx261=((_option_punctlist+$133*4)&4294967295);HEAP32[(($arrayidx261)>>2)]=0;HEAP32[((_option_punctuation)>>2)]=2;;}}while(0);var $call264=__ZL4GetCv();HEAP32[(($c2)>>2)]=$call264;__label__=8;continue $while_cond$12;}}while(0);var $134=$linelength;var $inc268=((($134)+1)&4294967295);$linelength=$inc268;var $135=HEAP32[(($c1)>>2)];var $call269=_iswalnum($135);var $tobool270=((($call269))|0)!=0;if($tobool270){__label__=98;;}else{__label__=99;;}
$if_then271$$if_else272$107:do{if(__label__==98){$any_alnum=1;;}
else if(__label__==99){var $136=$stressed_word;var $tobool273=((($136))|0)!=0;if($tobool273){__label__=100;;}else{__label__=101;;}
if(__label__==100){$stressed_word=0;HEAP32[(($c1)>>2)]=1328;var $137=HEAP32[(($c2)>>2)];__ZL6UngetCi($137);HEAP32[(($c2)>>2)]=32;;}
var $138=HEAP32[(($c1)>>2)];var $call276=__Z11lookupwcharPKti(((__ZL12chars_ignore)&4294967295),$138);var $tobool277=((($call276))|0)!=0;if($tobool277){__label__=8;continue $while_cond$12;}
var $139=HEAP32[(($c1)>>2)];var $call280=_iswspace($139);var $tobool281=((($call280))|0)!=0;if($tobool281){__label__=103;;}else{__label__=109;;}
$if_then282$$if_end304$114:do{if(__label__==103){var $140=$tr_addr;var $translator_name=(($140+280)&4294967295);var $141=HEAP32[(($translator_name)>>2)];var $cmp283=((($141))|0)==6972015;if(!($cmp283)){__label__=109;break $if_then282$$if_end304$114;}
var $142=HEAP32[(($ix)>>2)];var $sub285=((($142)-1)&4294967295);var $143=$buf_addr;var $arrayidx286=(($143+$sub285)&4294967295);$p_word=$arrayidx286;var $144=$p_word;var $arrayidx287=(($144)&4294967295);var $145=HEAP8[($arrayidx287)];var $conv288=(tempInt=(($145)),(tempInt>=128?tempInt-256:tempInt));var $cmp289=((($conv288))|0)==105;if(!($cmp289)){__label__=109;break $if_then282$$if_end304$114;}
var $146=$p_word;var $arrayidx291=(($146+-1)&4294967295);var $147=HEAP8[($arrayidx291)];var $conv292=(tempInt=(($147)),(tempInt>=128?tempInt-256:tempInt));var $cmp293=((($conv292))|0)==46;if($cmp293){__label__=106;;}else{__label__=107;;}
if(__label__==106){var $148=$p_word;var $incdec_ptr=(($148+-1)&4294967295);$p_word=$incdec_ptr;;}
var $149=$p_word;var $arrayidx296=(($149+-1)&4294967295);var $150=HEAP8[($arrayidx296)];var $conv297=(tempInt=(($150)),(tempInt>=128?tempInt-256:tempInt));var $cmp298=((($conv297))|0)==32;if($cmp298){__label__=108;break $while_cond$12;}}}while(0);var $153=HEAP32[(($c1)>>2)];var $cmp305=((($153))|0)==3405;if(!($cmp305)){__label__=112;break $if_then271$$if_else272$107;}
var $154=HEAP32[(($c2)>>2)];var $cmp307=((($154))|0)==8205;if(!($cmp307)){__label__=112;break $if_then271$$if_else272$107;}
HEAP32[(($c1)>>2)]=3406;;}}while(0);var $155=HEAP32[(($c1)>>2)];var $call312=_iswupper($155);var $tobool313=((($call312))|0)!=0;if($tobool313){__label__=113;;}else{__label__=118;;}
$if_then314$$if_else343$125:do{if(__label__==113){var $156=$tr_addr;var $clause_upper_count315=(($156+8304)&4294967295);var $157=HEAP32[(($clause_upper_count315)>>2)];var $inc316=((($157)+1)&4294967295);HEAP32[(($clause_upper_count315)>>2)]=$inc316;var $158=HEAP32[((_option_capitals)>>2)];var $cmp317=((($158))|0)==2;var $159=HEAP32[((__ZL10sayas_mode)>>2)];var $cmp319=((($159))|0)==0;var $or_cond13=($cmp317)&($cmp319);if(!($or_cond13)){__label__=120;break $if_then314$$if_else343$125;}
var $160=$cprev;var $call321=_iswupper($160);var $tobool322=((($call321))|0)!=0;if($tobool322){__label__=120;break $if_then314$$if_else343$125;}
var $161=$tr_addr;var $call325=__ZL13LookupSpecialP10TranslatorPKcPc($161,$arraydecay324);var $cmp326=((($call325))|0)!=0;if(!($cmp326)){__label__=120;break $if_then314$$if_else343$125;}
var $strlen=_strlen($arraydecay329);var $leninc=((($strlen)+1)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay329;$dest$=$arraydecay328;$stop$=$src$+$leninc;if(($dest$%4)==($src$%4)&&$leninc>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $call332=_strlen($arraydecay331);$j=$call332;var $162=HEAP32[(($ix)>>2)];var $163=$j;var $add333=((($163)+($162))&4294967295);var $164=$n_buf_addr;var $cmp334=((($add333))|0)<((($164))|0);if(!($cmp334)){__label__=120;break $if_then314$$if_else343$125;}
var $165=HEAP32[(($ix)>>2)];var $166=$buf_addr;var $arrayidx336=(($166+$165)&4294967295);var $call338=_strcpy($arrayidx336,$arraydecay337);var $167=$j;var $168=HEAP32[(($ix)>>2)];var $add339=((($168)+($167))&4294967295);HEAP32[(($ix)>>2)]=$add339;;}
else if(__label__==118){var $169=HEAP32[(($c1)>>2)];var $call344=_iswalpha($169);var $tobool345=((($call344))|0)!=0;if(!($tobool345)){__label__=120;break $if_then314$$if_else343$125;}
var $170=$tr_addr;var $clause_lower_count347=(($170+8308)&4294967295);var $171=HEAP32[(($clause_lower_count347)>>2)];var $inc348=((($171)+1)&4294967295);HEAP32[(($clause_lower_count347)>>2)]=$inc348;;}}while(0);var $172=HEAP32[((_option_phoneme_input)>>2)];var $tobool351=((($172))|0)!=0;if($tobool351){__label__=121;;}else{__label__=130;;}
$if_then352$$if_end368$134:do{if(__label__==121){var $173=$phoneme_mode;var $cmp353=((($173))|0)>0;if($cmp353){__label__=122;;}else{__label__=123;;}
if(__label__==122){var $174=$phoneme_mode;var $dec=((($174)-1)&4294967295);$phoneme_mode=$dec;;}
else if(__label__==123){var $175=HEAP32[(($c1)>>2)];var $cmp356=((($175))|0)==91;if($cmp356){__lastLabel__=123;__label__=124;;}else{__lastLabel__=123;__label__=127;;}
if(__label__==124){var $176=HEAP32[(($c2)>>2)];var $cmp358=((($176))|0)==91;if($cmp358){__label__=125;;}else{__label__=126;;}
if(__label__==125){$phoneme_mode=-1;__label__=130;break $if_then352$$if_end368$134;}
else if(__label__==126){var $_pr25=HEAP32[(($c1)>>2)];__lastLabel__=126;;}}
var $177=__lastLabel__==126?$_pr25:($175);var $cmp361=((($177))|0)==93;if(!($cmp361)){__label__=130;break $if_then352$$if_end368$134;}
var $178=HEAP32[(($c2)>>2)];var $cmp363=((($178))|0)==93;if(!($cmp363)){__label__=130;break $if_then352$$if_end368$134;}
$phoneme_mode=2;;}}}while(0);var $179=HEAP32[(($c1)>>2)];var $cmp369=((($179))|0)==10;if($cmp369){__label__=131;;}else{__label__=148;;}
if(__label__==131){$parag=0;;while(1){var $call372=__Z3Eofv();var $tobool373=((($call372))|0)!=0;if($tobool373){__label__=137;break;}
var $180=HEAP32[(($c2)>>2)];var $call375=_iswspace($180);var $tobool376=((($call375))|0)!=0;if(!($tobool376)){__label__=137;break;}
var $181=HEAP32[(($c2)>>2)];var $cmp379=((($181))|0)==10;if($cmp379){__label__=135;;}else{__label__=136;;}
if(__label__==135){var $182=$parag;var $inc381=((($182)+1)&4294967295);$parag=$inc381;;}
var $call383=__ZL4GetCv();HEAP32[(($c2)>>2)]=$call383;__label__=132;continue;}
var $183=$parag;var $cmp385=((($183))|0)>0;if($cmp385){__label__=138;break $while_cond$12;}
var $195=$linelength;var $196=HEAP32[((_option_linelength)>>2)];var $cmp402=((($195))|0)<=((($196))|0);if($cmp402){__label__=146;break $while_cond$12;}
$linelength=0;;}
var $202=$announced_punctuation;$prev_announced_punctuation=$202;$announced_punctuation=0;var $203=$phoneme_mode;var $cmp409=((($203))|0)==0;var $204=HEAP32[((__ZL10sayas_mode)>>2)];var $cmp411=((($204))|0)==0;var $or_cond14=($cmp409)&($cmp411);if($or_cond14){__label__=149;;}else{__label__=238;;}
$if_then412$$if_end643$161:do{if(__label__==149){$is_end_clause=0;var $205=$end_clause_after_tag;var $tobool413=((($205))|0)!=0;if($tobool413){__label__=150;;}else{__label__=155;;}
$if_then414$$if_end429$163:do{if(__label__==150){var $206=HEAP32[(($c1)>>2)];var $call415=_iswspace($206);var $tobool416=((($call415))|0)!=0;if($tobool416){__label__=155;break $if_then414$$if_end429$163;}
var $207=HEAP32[(($c1)>>2)];var $call418=__Z7IsAlphaj($207);var $tobool419=((($call418))|0)!=0;if(!($tobool419)){__label__=153;break $while_cond$12;}
var $208=HEAP32[(($c1)>>2)];var $call421=_iswlower($208);var $tobool422=((($call421))|0)!=0;if(!($tobool422)){__label__=153;break $while_cond$12;}
$end_clause_after_tag=0;;}}while(0);var $216=HEAP32[(($c1)>>2)];var $cmp430=((($216))|0)==46;if($cmp430){__label__=156;;}else{__label__=162;;}
$land_lhs_true431$$if_end443$169:do{if(__label__==156){var $217=HEAP32[(($c2)>>2)];var $cmp432=((($217))|0)==46;if(!($cmp432)){__label__=162;break $land_lhs_true431$$if_end443$169;}
var $call43538=__ZL4GetCv();$c_next=$call43538;var $cmp43639=((($call43538))|0)==46;if($cmp43639){__label__=158;;}else{__label__=159;;}
$while_body437$$while_end438$172:do{if(__label__==158){while(1){HEAP32[(($c1)>>2)]=8230;HEAP32[(($c2)>>2)]=32;var $call435=__ZL4GetCv();$c_next=$call435;var $cmp436=((($call435))|0)==46;if($cmp436){__label__=158;continue;}else{__label__=159;break $while_body437$$while_end438$172;}}}}while(0);var $218=HEAP32[(($c1)>>2)];var $cmp439=((($218))|0)==8230;var $219=$c_next;if($cmp439){__label__=160;;}else{__label__=161;;}
if(__label__==160){HEAP32[(($c2)>>2)]=$219;;}
else if(__label__==161){__ZL6UngetCi($219);;}}}while(0);$punct_data=0;var $220=HEAP32[(($c1)>>2)];var $call444=__Z11lookupwcharPKti(((__ZL11punct_chars)&4294967295),$220);$punct=$call444;var $cmp445=((($call444))|0)!=0;if($cmp445){__label__=163;;}else{__label__=171;;}
$if_then446$$if_end471$180:do{if(__label__==163){var $221=$punct;var $arrayidx447=((__ZL16punct_attributes+$221*4)&4294967295);var $222=HEAP32[(($arrayidx447)>>2)];$punct_data=$222;var $223=$punct_data;var $and448=($223)&1048576;var $tobool449=((($and448))|0)!=0;if($tobool449){__label__=164;;}else{__label__=165;;}
if(__label__==164){$stressed_word=1;var $224=$punct_data;var $shr=($224)>>12;var $and451=($shr)&15;var $225=$tone_type_addr;HEAP32[(($225)>>2)]=$and451;__label__=8;continue $while_cond$12;}
else if(__label__==165){var $226=HEAP32[(($c2)>>2)];var $call453=_iswspace($226);var $tobool454=((($call453))|0)!=0;if($tobool454){__label__=170;;}else{__label__=166;;}
$if_then469$$lor_lhs_false455$185:do{if(__label__==166){var $227=$punct_data;var $and456=($227)&32768;var $tobool457=((($and456))|0)!=0;if($tobool457){__label__=170;break $if_then469$$lor_lhs_false455$185;}
var $228=HEAP32[(($c2)>>2)];var $call459=__Z9IsBracketi($228);var $tobool460=((($call459))|0)!=0;var $229=HEAP32[(($c2)>>2)];var $cmp462=((($229))|0)==63;var $or_cond15=($tobool460)|($cmp462);if($or_cond15){__label__=170;break $if_then469$$lor_lhs_false455$185;}
var $call464=__Z3Eofv();var $tobool465=((($call464))|0)!=0;if($tobool465){__label__=170;break $if_then469$$lor_lhs_false455$185;}
var $230=HEAP32[(($c2)>>2)];var $231=HEAP8[(_ctrl_embedded)];var $conv467=(tempInt=(($231)),(tempInt>=128?tempInt-256:tempInt));var $cmp468=((($230))|0)==((($conv467))|0);if(!($cmp468)){__label__=171;break $if_then446$$if_end471$180;}}}while(0);$is_end_clause=1;;}}}while(0);var $232=HEAP32[(($c1)>>2)];var $cmp472=((($232))|0)==57404;if($cmp472){__label__=172;;}else{__label__=173;;}
if(__label__==172){HEAP32[(($c1)>>2)]=60;;}
var $233=HEAP32[((_option_punctuation)>>2)];var $tobool475=((($233))|0)!=0;if($tobool475){__label__=174;;}else{__label__=181;;}
$land_lhs_true476$$if_end493$195:do{if(__label__==174){var $234=HEAP32[(($c1)>>2)];var $call477=_iswpunct($234);var $tobool478=((($call477))|0)!=0;if(!($tobool478)){__label__=181;break $land_lhs_true476$$if_end493$195;}
var $_b2=HEAPU8[(__ZL10audio_text_b)];var $235=((($_b2))&1);var $cmp480=((($235))|0)==0;if(!($cmp480)){__label__=181;break $land_lhs_true476$$if_end493$195;}
var $236=HEAP32[((_option_punctuation)>>2)];var $cmp482=((($236))|0)==1;if($cmp482){__label__=178;;}else{__label__=177;;}
if(__label__==177){var $237=HEAP32[(($c1)>>2)];var $call484=_wcschr(((_option_punctlist)&4294967295),$237);var $cmp485=((($call484))|0)!=0;if(!($cmp485)){__label__=181;break $land_lhs_true476$$if_end493$195;}}
var $238=$tr_addr;var $phonemes_repeat_count487=(($238+652)&4294967295);HEAP32[(($phonemes_repeat_count487)>>2)]=0;var $239=$tr_addr;var $240=HEAP32[(($c1)>>2)];var $241=$buf_addr;var $242=$is_end_clause;var $call488=__ZL19AnnouncePunctuationP10TranslatoriPiPcS1_i($239,$240,$c2,$241,$ix,$242);$terminator=$call488;var $cmp489=((($call488))|0)>=0;if($cmp489){__label__=179;break $while_cond$12;}
var $244=HEAP32[(($c1)>>2)];$announced_punctuation=$244;;}}while(0);var $245=$punct_data;var $and494=($245)&2097152;var $tobool495=((($and494))|0)!=0;if($tobool495){__label__=182;;}else{__label__=185;;}
$land_lhs_true496$$if_end510$204:do{if(__label__==182){var $246=$announced_punctuation;var $cmp497=((($246))|0)==0;if(!($cmp497)){__label__=185;break $land_lhs_true496$$if_end510$204;}
var $247=HEAP32[(($ix)>>2)];var $248=$buf_addr;var $arrayidx499=(($248+$247)&4294967295);$p2=$arrayidx499;var $249=$p2;var $250=$tr_addr;var $251=HEAP32[(($c1)>>2)];__ZL14LookupCharNameP10Translatorii($250,$251,1);var $strlen20=_strlen(((__ZZL14LookupCharNameP10TranslatoriiE3buf)&4294967295));var $leninc21=((($strlen20)+1)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__ZZL14LookupCharNameP10TranslatoriiE3buf)&4294967295);$dest$=$249;$stop$=$src$+$leninc21;if(($dest$%4)==($src$%4)&&$leninc21>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $252=$p2;var $arrayidx502=(($252)&4294967295);var $253=HEAP8[($arrayidx502)];var $conv503=(tempInt=(($253)),(tempInt>=128?tempInt-256:tempInt));var $cmp504=((($conv503))|0)!=0;if(!($cmp504)){__label__=185;break $land_lhs_true496$$if_end510$204;}
var $254=$p2;var $call506=_strlen($254);var $255=HEAP32[(($ix)>>2)];var $add507=((($255)+($call506))&4294967295);HEAP32[(($ix)>>2)]=$add507;var $256=HEAP32[(($c1)>>2)];$announced_punctuation=$256;var $257=$punct_data;var $and508=($257)&-28673;$punct_data=$and508;;}}while(0);var $258=$is_end_clause;var $tobool511=((($258))|0)!=0;if(!($tobool511)){__label__=238;break $if_then412$$if_end643$161;}
$nl_count=0;var $259=HEAP32[(($c2)>>2)];$c_next=$259;var $260=$c_next;var $call513=_iswspace($260);var $tobool514=((($call513))|0)!=0;if($tobool514){__label__=187;;}else{__label__=192;;}
$while_cond516$$if_end530$210:do{if(__label__==187){while(1){var $call517=__Z3Eofv();var $tobool518=((($call517))|0)!=0;if($tobool518){__label__=192;break $while_cond516$$if_end530$210;}
var $261=$c_next;var $call520=_iswspace($261);var $tobool521=((($call520))|0)!=0;if(!($tobool521)){__label__=192;break $while_cond516$$if_end530$210;}
var $262=$c_next;var $cmp524=((($262))|0)==10;if($cmp524){__label__=190;;}else{__label__=191;;}
if(__label__==190){var $263=$nl_count;var $inc526=((($263)+1)&4294967295);$nl_count=$inc526;;}
var $call528=__ZL4GetCv();$c_next=$call528;__label__=187;continue;}}}while(0);var $264=HEAP32[(($c1)>>2)];var $cmp531=((($264))|0)==46;if($cmp531){__label__=193;;}else{__label__=195;;}
$land_lhs_true532$$if_end535$219:do{if(__label__==193){var $265=$nl_count;var $cmp533=((($265))|0)<2;if(!($cmp533)){__label__=226;break $land_lhs_true532$$if_end535$219;}
var $266=$punct_data;var $or=($266)|4194304;$punct_data=$or;__label__=195;break $land_lhs_true532$$if_end535$219;}}while(0);$if_end535$$if_end609$222:do{if(__label__==195){var $_pr26=$nl_count;var $cmp536=((($_pr26))|0)==0;if(!($cmp536)){__label__=226;break $if_end535$$if_end609$222;}
var $267=HEAP32[(($c1)>>2)];var $cmp538=((($267))|0)==44;if($cmp538){__lastLabel__=196;__label__=197;;}else{__lastLabel__=196;__label__=204;;}
$land_lhs_true539$$if_end554$225:do{if(__label__==197){var $268=$cprev;var $cmp540=((($268))|0)==46;if($cmp540){__label__=198;;}else{__label__=203;;}
$land_lhs_true541$$if_end554thread_pre_split$227:do{if(__label__==198){var $269=$tr_addr;var $translator_name542=(($269+280)&4294967295);var $270=HEAP32[(($translator_name542)>>2)];var $cmp543=((($270))|0)==26741;if(!($cmp543)){__label__=203;break $land_lhs_true541$$if_end554thread_pre_split$227;}
var $271=$cprev2;var $call545=_iswdigit($271);var $tobool546=((($call545))|0)!=0;if(!($tobool546)){__label__=203;break $land_lhs_true541$$if_end554thread_pre_split$227;}
var $272=$c_next;var $call548=_iswdigit($272);var $tobool549=((($call548))|0)!=0;if($tobool549){__label__=202;;}else{__label__=201;;}
if(__label__==201){var $273=$c_next;var $call551=_iswlower($273);var $tobool552=((($call551))|0)!=0;if(!($tobool552)){__label__=203;break $land_lhs_true541$$if_end554thread_pre_split$227;}}
HEAP32[(($c1)>>2)]=1367;$is_end_clause=0;__label__=220;break $land_lhs_true539$$if_end554$225;}}while(0);var $_pr28=HEAP32[(($c1)>>2)];__lastLabel__=203;__label__=204;break $land_lhs_true539$$if_end554$225;}}while(0);$if_else595$$if_end554$235:do{if(__label__==204){var $274=__lastLabel__==203?$_pr28:($267);var $cmp555=((($274))|0)==46;if(!($cmp555)){__label__=220;break $if_else595$$if_end554$235;}
var $275=$tr_addr;var $langopts=(($275)&4294967295);var $numbers=(($langopts+184)&4294967295);var $276=HEAP32[(($numbers)>>2)];var $and557=($276)&65536;var $tobool558=((($and557))|0)!=0;if($tobool558){__label__=206;;}else{__label__=214;;}
$land_lhs_true559$$if_else583$238:do{if(__label__==206){var $277=$cprev;var $call560=_iswdigit($277);var $tobool561=((($call560))|0)!=0;if($tobool561){__label__=210;;}else{__label__=207;;}
$if_then571$$lor_lhs_false562$240:do{if(__label__==207){var $278=$cprev;var $call563=__ZL8IsRomanUj($278);var $tobool564=((($call563))|0)!=0;if(!($tobool564)){__label__=214;break $land_lhs_true559$$if_else583$238;}
var $279=$cprev2;var $call566=__ZL8IsRomanUj($279);var $tobool567=((($call566))|0)!=0;if($tobool567){__label__=210;break $if_then571$$lor_lhs_false562$240;}
var $280=$cprev2;var $call569=_iswspace($280);var $tobool570=((($call569))|0)!=0;if(!($tobool570)){__label__=214;break $land_lhs_true559$$if_else583$238;}}}while(0);var $281=$cprev;var $call572=_iswdigit($281);var $tobool573=((($call572))|0)!=0;if($tobool573){__label__=212;;}else{__label__=211;;}
if(__label__==212){var $282=$c_next;var $call576=_iswlower($282);var $tobool577=((($call576))|0)!=0;var $283=$c_next;var $cmp579=((($283))|0)==45;var $or_cond16=($tobool577)|($cmp579);if(!($or_cond16)){__label__=216;break $land_lhs_true559$$if_else583$238;}
$is_end_clause=0;__label__=216;break $land_lhs_true559$$if_else583$238;}
else if(__label__==211){$is_end_clause=0;__label__=216;break $land_lhs_true559$$if_else583$238;}}}while(0);$if_end587$$if_else583$249:do{if(__label__==214){var $284=$c_next;var $cmp584=((($284))|0)==39;if(!($cmp584)){__label__=216;break $if_end587$$if_else583$249;}
$is_end_clause=0;;}}while(0);var $285=$c_next;var $call588=_iswlower($285);var $tobool589=((($call588))|0)!=0;if($tobool589){__label__=217;;}else{__label__=218;;}
if(__label__==217){$is_end_clause=0;;}
var $286=$any_alnum;var $cmp592=((($286))|0)==0;if(!($cmp592)){__label__=222;break $if_else595$$if_end554$235;}
HEAP32[(($c1)>>2)]=32;$is_end_clause=0;__label__=235;break $if_end535$$if_end609$222;}}while(0);$if_else595$$if_end599$257:do{if(__label__==220){var $287=$any_alnum;var $cmp596=((($287))|0)==0;if(!($cmp596)){__label__=222;break $if_else595$$if_end599$257;}
$is_end_clause=0;__label__=235;break $if_end535$$if_end609$222;}}while(0);var $_pr30=$is_end_clause;var $tobool600=((($_pr30))|0)!=0;if(!($tobool600)){__label__=235;break $if_end535$$if_end609$222;}
var $288=HEAP32[(($c1)>>2)];var $cmp602=((($288))|0)==46;if(!($cmp602)){__label__=226;break $if_end535$$if_end609$222;}
var $289=$c_next;var $cmp604=((($289))|0)==60;var $290=HEAP32[((_option_ssml)>>2)];var $tobool606=((($290))|0)!=0;var $or_cond17=($cmp604)&($tobool606);if(!($or_cond17)){__label__=226;break $if_end535$$if_end609$222;}
$is_end_clause=0;var $291=HEAP32[(($ix)>>2)];$end_clause_index=$291;var $292=$punct_data;$end_clause_after_tag=$292;__label__=235;break $if_end535$$if_end609$222;}}while(0);if(__label__==226){var $_pr32_pr=$is_end_clause;var $tobool610=((($_pr32_pr))|0)!=0;if($tobool610){__label__=227;break $while_cond$12;}}
var $call633=__Z3Eofv();var $tobool634=((($call633))|0)!=0;if($tobool634){__label__=238;break $if_then412$$if_end643$161;}
var $305=HEAP32[(($c2)>>2)];var $call636=_iswspace($305);var $tobool637=((($call636))|0)!=0;if(!($tobool637)){__label__=238;break $if_then412$$if_end643$161;}
var $306=$c_next;__ZL6UngetCi($306);;}}while(0);var $307=HEAP32[((((__ZL17speech_parameters)&4294967295))>>2)];var $cmp644=((($307))|0)==1;if($cmp644){__label__=8;continue $while_cond$12;}
var $308=HEAP32[(($c1)>>2)];var $309=$announced_punctuation;var $cmp647=((($308))|0)==((($309))|0);if($cmp647){__label__=240;;}else{__label__=245;;}
$if_then648$$if_end657$271:do{if(__label__==240){var $310=HEAP32[(($c1)>>2)];var $call649=__Z9IsBracketi($310);var $tobool650=((($call649))|0)!=0;if($tobool650){__label__=241;;}else{__label__=242;;}
$if_then651$$if_else652$273:do{if(__label__==241){HEAP32[(($c1)>>2)]=57384;;}
else if(__label__==242){var $311=HEAP32[(($c1)>>2)];var $cmp653=((($311))|0)!=45;if(!($cmp653)){__label__=244;break $if_then651$$if_else652$273;}
HEAP32[(($c1)>>2)]=32;;}}while(0);var $312=HEAP32[(($ix)>>2)];var $add65834=((($312)+1)&4294967295);$j=$add65834;;}
else if(__label__==245){var $313=HEAP32[(($ix)>>2)];var $add658=((($313)+1)&4294967295);$j=$add658;var $cmp659=((($308))|0)==57404;if(!($cmp659)){__label__=247;break $if_then648$$if_end657$271;}
HEAP32[(($c1)>>2)]=60;;}}while(0);var $314=HEAP32[(($c1)>>2)];var $315=HEAP32[(($ix)>>2)];var $316=$buf_addr;var $arrayidx662=(($316+$315)&4294967295);var $call663=__Z8utf8_outjPc($314,$arrayidx662);var $317=HEAP32[(($ix)>>2)];var $add664=((($317)+($call663))&4294967295);HEAP32[(($ix)>>2)]=$add664;var $318=HEAP32[(($c1)>>2)];var $call665=_iswspace($318);var $tobool666=((($call665))|0)!=0;if($tobool666){__label__=251;;}else{__label__=248;;}
$if_end680$$land_lhs_true667$281:do{if(__label__==248){var $319=HEAP32[(($c1)>>2)];var $call668=__Z9IsBracketi($319);var $tobool669=((($call668))|0)!=0;if($tobool669){__label__=251;break $if_end680$$land_lhs_true667$281;}
var $320=HEAP32[((_count_characters)>>2)];var $321=HEAP32[((_clause_start_char)>>2)];var $sub671=((($320)-($321))&4294967295);var $conv672=((($sub671))&65535);var $322=HEAP32[(($ix)>>2)];var $323=$charix_addr;var $arrayidx673=(($323+2*$322)&4294967295);HEAP16[(($arrayidx673)>>1)]=$conv672;var $324=$j;var $325=HEAP32[(($ix)>>2)];var $cmp67537=((($324))|0)<((($325))|0);if(!($cmp67537)){__label__=251;break $if_end680$$land_lhs_true667$281;}
while(1){var $326=$j;var $inc677=((($326)+1)&4294967295);$j=$inc677;var $327=$charix_addr;var $arrayidx678=(($327+2*$326)&4294967295);HEAP16[(($arrayidx678)>>1)]=-1;var $328=$j;var $329=HEAP32[(($ix)>>2)];var $cmp675=((($328))|0)<((($329))|0);if($cmp675){__label__=250;continue;}else{__label__=251;break $if_end680$$land_lhs_true667$281;}}}}while(0);var $330=HEAP32[(($ix)>>2)];var $331=$charix_top_addr;HEAP32[(($331)>>2)]=$330;var $332=HEAP32[(($ix)>>2)];var $333=$n_buf_addr;var $sub681=((($333)-20)&4294967295);var $cmp682=((($332))|0)>((($sub681))|0);if($cmp682){__label__=252;;}else{__label__=254;;}
$land_lhs_true683$$lor_lhs_false689$287:do{if(__label__==252){var $334=HEAP32[(($c1)>>2)];var $call684=__Z7IsAlphaj($334);var $tobool685=((($call684))|0)!=0;if($tobool685){__label__=254;break $land_lhs_true683$$lor_lhs_false689$287;}
var $335=HEAP32[(($c1)>>2)];var $call687=_iswdigit($335);var $tobool688=((($call687))|0)!=0;if(!($tobool688)){__label__=255;break $while_cond$12;}}}while(0);var $336=HEAP32[(($ix)>>2)];var $337=$n_buf_addr;var $sub690=((($337)-2)&4294967295);var $cmp691=((($336))|0)>=((($sub690))|0);if($cmp691){__label__=255;break $while_cond$12;}else{__label__=8;continue $while_cond$12;}}
if(__label__==256){var $343=$stressed_word;var $tobool698=((($343))|0)!=0;if($tobool698){__label__=257;;}else{__label__=258;;}
if(__label__==257){var $344=HEAP32[(($ix)>>2)];var $345=$buf_addr;var $arrayidx700=(($345+$344)&4294967295);var $call701=__Z8utf8_outjPc(1328,$arrayidx700);var $346=HEAP32[(($ix)>>2)];var $add702=((($346)+($call701))&4294967295);HEAP32[(($ix)>>2)]=$add702;;}
var $347=$end_clause_after_tag;var $tobool704=((($347))|0)!=0;if($tobool704){__label__=259;;}else{__label__=260;;}
if(__label__==259){var $348=$end_clause_index;var $349=$buf_addr;var $arrayidx706=(($349+$348)&4294967295);__ZL10RemoveCharPc($arrayidx706);;}
var $350=HEAP32[(($ix)>>2)];var $351=$buf_addr;var $arrayidx708=(($351+$350)&4294967295);HEAP8[($arrayidx708)]=32;var $352=HEAP32[(($ix)>>2)];var $add709=((($352)+1)&4294967295);var $353=$buf_addr;var $arrayidx710=(($353+$add709)&4294967295);HEAP8[($arrayidx710)]=0;$retval=589864;;}
else if(__label__==12){HEAP8[(__ZL12end_of_input_b)]=1;$retval=589864;;}
else if(__label__==15){HEAP8[(__ZL19clear_skipping_text_b)]=1;HEAP32[((_skip_characters)>>2)]=0;var $24=HEAP32[(($c2)>>2)];__ZL6UngetCi($24);$retval=16384;;}
else if(__label__==66){var $81=$end_clause_after_tag;var $tobool168=((($81))|0)!=0;if($tobool168){__label__=67;;}else{__label__=68;;}
if(__label__==67){var $82=$end_clause_index;HEAP32[(($ix)>>2)]=$82;;}
var $83=HEAP32[(($ix)>>2)];var $84=$buf_addr;var $arrayidx171=(($84+$83)&4294967295);HEAP8[($arrayidx171)]=32;var $85=HEAP32[(($ix)>>2)];var $inc172=((($85)+1)&4294967295);HEAP32[(($ix)>>2)]=$inc172;var $86=$buf_addr;var $arrayidx173=(($86+$85)&4294967295);HEAP8[($arrayidx173)]=0;var $87=$terminator;var $and=($87)&131072;var $tobool174=((($and))|0)!=0;if($tobool174){__label__=69;;}else{__label__=70;;}
if(__label__==69){var $88=$voice_change_addr;var $call176=_strcpy($88,((__ZL16current_voice_id)&4294967295));;}
var $89=$terminator;$retval=$89;;}
else if(__label__==74){var $call192=__Z11lookupwcharPKti(((__ZL11punct_chars)&4294967295),$93);$punct=$call192;var $cmp193=((($call192))|0)==0;if($cmp193){__label__=75;;}else{__label__=76;;}
if(__label__==75){var $94=HEAP32[((_count_characters)>>2)];var $95=HEAP32[((_clause_start_char)>>2)];var $sub195=((($94)-($95))&4294967295);var $conv196=((($sub195))&65535);var $96=HEAP32[(($ix)>>2)];var $97=$charix_addr;var $arrayidx197=(($97+2*$96)&4294967295);HEAP16[(($arrayidx197)>>1)]=$conv196;var $98=HEAP32[(($ix)>>2)];var $99=$charix_top_addr;HEAP32[(($99)>>2)]=$98;var $100=HEAP32[(($c1)>>2)];var $101=HEAP32[(($ix)>>2)];var $102=$buf_addr;var $arrayidx198=(($102+$101)&4294967295);var $call199=__Z8utf8_outjPc($100,$arrayidx198);var $103=HEAP32[(($ix)>>2)];var $add200=((($103)+($call199))&4294967295);HEAP32[(($ix)>>2)]=$add200;$terminator=524328;;}
else if(__label__==76){var $104=$punct;var $arrayidx202=((__ZL16punct_attributes+$104*4)&4294967295);var $105=HEAP32[(($arrayidx202)>>2)];$terminator=$105;;}
var $106=HEAP32[(($ix)>>2)];var $107=$buf_addr;var $arrayidx204=(($107+$106)&4294967295);HEAP8[($arrayidx204)]=32;var $108=HEAP32[(($ix)>>2)];var $add205=((($108)+1)&4294967295);var $109=$buf_addr;var $arrayidx206=(($109+$add205)&4294967295);HEAP8[($arrayidx206)]=0;var $110=$terminator;$retval=$110;;}
else if(__label__==81){var $114=HEAP32[(($ix)>>2)];var $inc215=((($114)+1)&4294967295);HEAP32[(($ix)>>2)]=$inc215;var $115=$buf_addr;var $arrayidx216=(($115+$114)&4294967295);HEAP8[($arrayidx216)]=0;;while(1){var $call218=__ZL4GetCv();HEAP32[(($c1)>>2)]=$call218;var $call219=_iswspace($call218);var $tobool220=((($call219))|0)!=0;if($tobool220){__label__=86;break;}
var $call222=__Z3Eofv();var $tobool223=((($call222))|0)!=0;if($tobool223){__label__=86;break;}
var $116=HEAP32[(($ix)>>2)];var $117=$n_buf_addr;var $sub225=((($117)-1)&4294967295);var $cmp226=((($116))|0)<((($sub225))|0);if(!($cmp226)){__label__=86;break;}
var $118=HEAP32[(($c1)>>2)];var $conv229=((($118))&255);var $119=HEAP32[(($ix)>>2)];var $inc230=((($119)+1)&4294967295);HEAP32[(($ix)>>2)]=$inc230;var $120=$buf_addr;var $arrayidx231=(($120+$119)&4294967295);HEAP8[($arrayidx231)]=$conv229;__label__=82;continue;}
var $121=HEAP32[(($ix)>>2)];var $inc233=((($121)+1)&4294967295);HEAP32[(($ix)>>2)]=$inc233;var $122=$buf_addr;var $arrayidx234=(($122+$121)&4294967295);HEAP8[($arrayidx234)]=0;$retval=147456;;}
else if(__label__==108){HEAP32[((__ZL10ungot_word)>>2)]=((__str42209)&4294967295);var $151=HEAP32[(($c2)>>2)];__ZL6UngetCi($151);var $152=$p_word;var $arrayidx300=(($152)&4294967295);HEAP8[($arrayidx300)]=0;$retval=524328;;}
else if(__label__==138){var $184=HEAP32[(($c2)>>2)];__ZL6UngetCi($184);var $185=$end_clause_after_tag;var $tobool387=((($185))|0)!=0;if($tobool387){__label__=139;;}else{__label__=140;;}
if(__label__==139){var $186=$end_clause_index;var $187=$buf_addr;var $arrayidx389=(($187+$186)&4294967295);__ZL10RemoveCharPc($arrayidx389);;}
var $188=HEAP32[(($ix)>>2)];var $189=$buf_addr;var $arrayidx391=(($189+$188)&4294967295);HEAP8[($arrayidx391)]=32;var $190=HEAP32[(($ix)>>2)];var $add392=((($190)+1)&4294967295);var $191=$buf_addr;var $arrayidx393=(($191+$add392)&4294967295);HEAP8[($arrayidx393)]=0;var $192=$parag;var $cmp394=((($192))|0)>3;if($cmp394){__label__=141;;}else{__label__=142;;}
if(__label__==141){$parag=3;;}
var $193=HEAP32[((_option_ssml)>>2)];var $tobool397=((($193))|0)!=0;if($tobool397){__label__=143;;}else{__label__=144;;}
if(__label__==143){$parag=1;;}
var $194=$parag;var $mul=((($194)*30)&4294967295);var $add400=((($mul)+524328)&4294967295);$retval=$add400;;}
else if(__label__==146){var $197=HEAP32[(($c2)>>2)];__ZL6UngetCi($197);var $198=HEAP32[(($ix)>>2)];var $199=$buf_addr;var $arrayidx404=(($199+$198)&4294967295);HEAP8[($arrayidx404)]=32;var $200=HEAP32[(($ix)>>2)];var $add405=((($200)+1)&4294967295);var $201=$buf_addr;var $arrayidx406=(($201+$add405)&4294967295);HEAP8[($arrayidx406)]=0;$retval=262174;;}
else if(__label__==153){var $209=HEAP32[(($c2)>>2)];__ZL6UngetCi($209);var $210=HEAP32[(($c1)>>2)];HEAP32[((__ZL11ungot_char2)>>2)]=$210;var $211=$end_clause_index;var $212=$buf_addr;var $arrayidx424=(($212+$211)&4294967295);HEAP8[($arrayidx424)]=32;var $213=$end_clause_index;var $add425=((($213)+1)&4294967295);var $214=$buf_addr;var $arrayidx426=(($214+$add425)&4294967295);HEAP8[($arrayidx426)]=0;var $215=$end_clause_after_tag;$retval=$215;;}
else if(__label__==179){var $243=$terminator;$retval=$243;;}
else if(__label__==227){var $293=$c_next;__ZL6UngetCi($293);var $294=HEAP32[(($ix)>>2)];var $295=$buf_addr;var $arrayidx612=(($295+$294)&4294967295);HEAP8[($arrayidx612)]=32;var $296=HEAP32[(($ix)>>2)];var $add613=((($296)+1)&4294967295);var $297=$buf_addr;var $arrayidx614=(($297+$add613)&4294967295);HEAP8[($arrayidx614)]=0;var $298=$cprev;var $call615=_iswdigit($298);var $tobool616=((($call615))|0)!=0;if($tobool616){__label__=228;;}else{__label__=230;;}
$land_lhs_true617$$if_end622$335:do{if(__label__==228){var $299=$c_next;var $call618=__Z7IsAlphaj($299);var $tobool619=((($call618))|0)!=0;if($tobool619){__label__=230;break $land_lhs_true617$$if_end622$335;}
var $300=$punct_data;var $and621=($300)&-4194305;$punct_data=$and621;;}}while(0);var $301=$nl_count;var $cmp623=((($301))|0)>1;var $302=$punct_data;if($cmp623){__label__=231;;}else{__label__=234;;}
if(__label__==231){var $cmp625=((($302))|0)==532520;var $303=$punct_data;var $cmp627=((($303))|0)==536621;var $or_cond18=($cmp625)|($cmp627);if($or_cond18){__label__=232;;}else{__label__=233;;}
if(__label__==232){var $304=$punct_data;var $add629=((($304)+35)&4294967295);$retval=$add629;;}
else if(__label__==233){$retval=524358;;}}
else if(__label__==234){$retval=$302;;}}
else if(__label__==255){var $338=HEAP32[(($ix)>>2)];var $339=$buf_addr;var $arrayidx693=(($339+$338)&4294967295);HEAP8[($arrayidx693)]=32;var $340=HEAP32[(($ix)>>2)];var $add694=((($340)+1)&4294967295);var $341=$buf_addr;var $arrayidx695=(($341+$add694)&4294967295);HEAP8[($arrayidx695)]=0;var $342=HEAP32[(($c2)>>2)];__ZL6UngetCi($342);$retval=16384;;}
var $354=$retval;STACKTOP=__stackBase__;return $354;return null;}
function __ZL4GetCv(){var __stackBase__=STACKTOP;STACKTOP+=16;_memset(__stackBase__,0,16);var __label__;var __lastLabel__=null;var $retval;var $c;var $c1;var $c2;var $cbuf=__stackBase__;var $ix;var $n_bytes;var $m;var $0=HEAP32[((__ZL10ungot_char)>>2)];$c1=$0;var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){HEAP32[((__ZL10ungot_char)>>2)]=0;var $1=$c1;$retval=$1;;}
else if(__label__==2){var $2=HEAP32[((__ZZL4GetCvE6ungot2)>>2)];var $cmp1=((($2))|0)!=0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $3=HEAP32[((__ZZL4GetCvE6ungot2)>>2)];$c1=$3;HEAP32[((__ZZL4GetCvE6ungot2)>>2)]=0;;}
else if(__label__==4){var $call=__ZL8GetC_getv();$c1=$call;;}
var $4=HEAP32[((_option_multibyte)>>2)];var $cmp4=((($4))|0)==3;var $5=HEAP32[((_option_multibyte)>>2)];var $cmp5=((($5))|0)==4;var $or_cond=($cmp4)|($cmp5);if($or_cond){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $6=HEAP32[((_count_characters)>>2)];var $inc=((($6)+1)&4294967295);HEAP32[((_count_characters)>>2)]=$inc;var $7=$c1;$retval=$7;;}
else if(__label__==7){var $8=HEAP32[((_option_multibyte)>>2)];var $cmp8=((($8))|0)<2;if($cmp8){__label__=8;;}else{__label__=36;;}
$land_lhs_true$$if_end65thread_pre_split$12:do{if(__label__==8){var $9=$c1;var $and=($9)&128;var $tobool=((($and))|0)!=0;if($tobool){__lastLabel__=8;;}else{__lastLabel__=8;__label__=37;break $land_lhs_true$$if_end65thread_pre_split$12;}
$n_bytes=0;var $10=$c1;var $and10=($10)&224;var $cmp11=((($and10))|0)==192;if($cmp11){__label__=10;;}else{__label__=12;;}
$land_lhs_true12$$if_else16$15:do{if(__label__==10){var $11=$c1;var $and13=($11)&30;var $cmp14=((($and13))|0)!=0;if(!($cmp14)){__label__=12;break $land_lhs_true12$$if_else16$15;}
$n_bytes=1;__lastLabel__=11;__label__=17;break $land_lhs_true12$$if_else16$15;}}while(0);$if_end29_thread$$if_else16$18:do{if(__label__==12){var $12=$c1;var $and17=($12)&240;var $cmp18=((($and17))|0)==224;if($cmp18){__label__=13;;}else{__label__=14;;}
if(__label__==13){$n_bytes=2;__lastLabel__=13;__label__=17;break $if_end29_thread$$if_else16$18;}
else if(__label__==14){var $13=$c1;var $and21=($13)&248;var $cmp22=((($and21))|0)==240;if($cmp22){__label__=15;;}else{__label__=18;;}
$land_lhs_true23$$if_end29$23:do{if(__label__==15){var $14=$c1;var $and24=($14)&15;var $cmp25=((($and24))|0)<=4;if(!($cmp25)){__label__=18;break $land_lhs_true23$$if_end29$23;}
$n_bytes=3;__lastLabel__=16;__label__=17;break $if_end29_thread$$if_else16$18;}}while(0);var $_pr=$n_bytes;$ix=$_pr;var $cmp30=((($_pr))|0)>0;if($cmp30){__label__=19;break $if_end29_thread$$if_else16$18;}else{__label__=33;break $if_end29_thread$$if_else16$18;}}}}while(0);$if_end29_thread$$if_then31$$if_end58$27:do{if(__label__==17){var $_ph=__lastLabel__==13?2:(__lastLabel__==16?3:(1));$ix=$_ph;__label__=19;break $if_end29_thread$$if_then31$$if_end58$27;}}while(0);$if_then31$$if_end58$29:do{if(__label__==19){var $15=$c1;var $16=$ix;var $arrayidx=((__ZZ8utf8_in2PiPKciE4mask+$16)&4294967295);var $17=HEAPU8[($arrayidx)];var $conv=((($17))&255);var $and32=($conv)&($15);$c=$and32;var $18=$ix;var $arrayidx33=((__ZZL4GetCvE5mask2+$18)&4294967295);var $19=HEAP8[($arrayidx33)];$m=$19;__lastLabel__=19;;$while_cond$31:while(1){var $20=__lastLabel__==30?$dec:($18);var $cmp34=((($20))|0)>0;if(!($cmp34)){__label__=31;break $while_cond$31;}
var $call35=__ZL8GetC_getv();var $21=$ix;var $arrayidx36=(($cbuf+$21*4)&4294967295);HEAP32[(($arrayidx36)>>2)]=$call35;$c2=$call35;var $cmp37=((($call35))|0)==0;if($cmp37){__label__=22;break $while_cond$31;}
var $23=$c2;var $and43=($23)&192;var $cmp44=((($and43))|0)!=128;if($cmp44){__label__=26;break $while_cond$31;}
$m=-128;var $28=$c;var $shl=((($28)*64)&4294967295);var $29=$c2;var $and53=($29)&63;var $add=((($and53)+($shl))&4294967295);$c=$add;var $30=$ix;var $dec=((($30)-1)&4294967295);$ix=$dec;__lastLabel__=30;__label__=20;continue $while_cond$31;}
if(__label__==22){var $22=HEAP32[((_option_multibyte)>>2)];var $cmp39=((($22))|0)==0;if($cmp39){__label__=23;;}else{__label__=24;;}
if(__label__==23){HEAP32[((_option_multibyte)>>2)]=2;;}
__ZL10GetC_ungeti(32);;}
else if(__label__==26){var $24=$n_bytes;var $cmp46=((($24))|0)==2;if($cmp46){__label__=27;;}else{__label__=29;;}
$land_lhs_true47$$if_end51$42:do{if(__label__==27){var $25=$ix;var $cmp48=((($25))|0)==1;if(!($cmp48)){__label__=29;break $land_lhs_true47$$if_end51$42;}
var $arrayidx50=(($cbuf+8)&4294967295);var $26=HEAP32[(($arrayidx50)>>2)];HEAP32[((__ZZL4GetCvE6ungot2)>>2)]=$26;;}}while(0);var $27=$c2;__ZL10GetC_ungeti($27);;}
var $31=$ix;var $cmp54=((($31))|0)==0;if(!($cmp54)){__label__=33;break $if_then31$$if_end58$29;}
var $32=HEAP32[((_count_characters)>>2)];var $inc56=((($32)+1)&4294967295);HEAP32[((_count_characters)>>2)]=$inc56;var $33=$c;$retval=$33;__label__=40;break $if_then$$if_end$2;}}while(0);var $34=HEAP32[((_option_multibyte)>>2)];var $cmp59=((($34))|0)==0;if(!($cmp59)){__label__=36;break $land_lhs_true$$if_end65thread_pre_split$12;}
var $call61=__Z3Eofv();var $tobool62=((($call61))|0)!=0;if($tobool62){__label__=36;break $land_lhs_true$$if_end65thread_pre_split$12;}
HEAP32[((_option_multibyte)>>2)]=2;__label__=36;break $land_lhs_true$$if_end65thread_pre_split$12;}}while(0);if(__label__==36){var $_pr2=$c1;__lastLabel__=36;;}
var $35=__lastLabel__==36?$_pr2:($9);var $36=HEAP32[((_count_characters)>>2)];var $inc66=((($36)+1)&4294967295);HEAP32[((_count_characters)>>2)]=$inc66;var $cmp67=((($35))|0)>=160;var $37=$c1;if($cmp67){__label__=38;;}else{__label__=39;;}
if(__label__==38){var $sub=((($37)-160)&4294967295);var $38=HEAP32[((_translator)>>2)];var $charset_a0=(($38+696)&4294967295);var $39=HEAP32[(($charset_a0)>>2)];var $arrayidx69=(($39+2*$sub)&4294967295);var $40=HEAPU16[(($arrayidx69)>>1)];var $conv70=((($40))&65535);$retval=$conv70;;}
else if(__label__==39){$retval=$37;;}}}}while(0);var $41=$retval;STACKTOP=__stackBase__;return $41;return null;}
function __ZL6UngetCi($c){;var __label__;var $c_addr;$c_addr=$c;var $0=$c_addr;HEAP32[((__ZL10ungot_char)>>2)]=$0;;return;return;}
function __ZL14ProcessSsmlTagPwPcRiii($xml_buf,$outbuf,$outix,$n_outbuf,$self_closing){var __stackBase__=STACKTOP;STACKTOP+=376;_memset(__stackBase__,0,376);var __label__;var __lastLabel__=null;var $retval;var $xml_buf_addr;var $outbuf_addr;var $outix_addr;var $n_outbuf_addr;var $self_closing_addr;var $ix;var $index;var $c;var $tag_type;var $value;var $value2;var $value3;var $voice_change_flag;var $px;var $attr1;var $attr2;var $attr3;var $terminator;var $uri;var $param_type;var $tag_name=__stackBase__;var $buf=__stackBase__+40;var $sp;var $ssml_sp;var $fname=__stackBase__+120;$xml_buf_addr=$xml_buf;$outbuf_addr=$outbuf;$outix_addr=$outix;$n_outbuf_addr=$n_outbuf;$self_closing_addr=$self_closing;$ix=0;__lastLabel__=0;;$for_cond$2:while(1){var $0=__lastLabel__==4?$inc:(0);var $cmp=((($0))>>>0)<39;if(!($cmp)){__label__=5;break $for_cond$2;}
var $1=$ix;var $2=$xml_buf_addr;var $arrayidx=(($2+4*$1)&4294967295);var $3=HEAP32[(($arrayidx)>>2)];$c=$3;var $cmp1=((($3))|0)==0;if($cmp1){__label__=5;break $for_cond$2;}
var $4=$c;var $call=_iswspace($4);var $tobool=((($call))|0)!=0;if($tobool){__label__=5;break $for_cond$2;}
var $5=$c;var $conv=((($5))&255);var $conv2=(tempInt=(($conv)),(tempInt>=128?tempInt-256:tempInt));var $call3=_tolower($conv2);var $conv4=((($call3))&255);var $6=$ix;var $arrayidx5=(($tag_name+$6)&4294967295);HEAP8[($arrayidx5)]=$conv4;var $7=$ix;var $inc=((($7)+1)&4294967295);$ix=$inc;__lastLabel__=4;__label__=1;continue $for_cond$2;}
var $8=$ix;var $arrayidx6=(($tag_name+$8)&4294967295);HEAP8[($arrayidx6)]=0;var $9=$ix;var $10=$xml_buf_addr;var $arrayidx7=(($10+4*$9)&4294967295);$px=$arrayidx7;var $arrayidx8=(($tag_name)&4294967295);var $11=HEAP8[($arrayidx8)];var $conv9=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $cmp10=((($conv9))|0)==47;if($cmp10){__label__=6;;}else{__label__=9;;}
$if_then11$$if_else$8:do{if(__label__==6){var $arrayidx12=(($tag_name+1)&4294967295);var $call13=__Z10LookupMnemP8MNEM_TABPKc(((__ZL8ssmltags)&4294967295),$arrayidx12);$tag_type=$call13;var $cmp14=((($call13))|0)!=16;if($cmp14){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $12=$outix_addr;var $13=HEAP32[(($12)>>2)];var $inc16=((($13)+1)&4294967295);HEAP32[(($12)>>2)]=$inc16;var $14=$outbuf_addr;var $arrayidx17=(($14+$13)&4294967295);HEAP8[($arrayidx17)]=32;;}
var $15=$tag_type;var $add=((($15)+32)&4294967295);$tag_type=$add;__lastLabel__=8;__label__=14;break $if_then11$$if_else$8;}
else if(__label__==9){var $arraydecay=(($tag_name)&4294967295);var $call19=__Z10LookupMnemP8MNEM_TABPKc(((__ZL8ssmltags)&4294967295),$arraydecay);$tag_type=$call19;var $cmp20=((($call19))|0)!=16;if($cmp20){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $16=$outix_addr;var $17=HEAP32[(($16)>>2)];var $inc22=((($17)+1)&4294967295);HEAP32[(($16)>>2)]=$inc22;var $18=$outbuf_addr;var $arrayidx23=(($18+$17)&4294967295);HEAP8[($arrayidx23)]=32;;}
var $19=$self_closing_addr;var $tobool25=((($19))|0)!=0;var $20=$tag_type;if($tobool25){__lastLabel__=11;;}else{__lastLabel__=11;__label__=14;break $if_then11$$if_else$8;}
var $arrayidx26=((__ZL22ignore_if_self_closing+$20)&4294967295);var $21=HEAP8[($arrayidx26)];var $tobool27=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool27){__lastLabel__=12;;}else{__lastLabel__=12;__label__=14;break $if_then11$$if_else$8;}
$retval=0;__label__=113;break $if_then11$$if_else$8;}}while(0);$if_end30$$return$19:do{if(__label__==14){var $22=__lastLabel__==12?$20:(__lastLabel__==8?$add:($20));$voice_change_flag=0;$terminator=16384;var $23=HEAPU32[((__ZL12n_ssml_stack)>>2)];var $sub=((($23)-1)&4294967295);var $arrayidx31=((__ZL10ssml_stack+$sub*76)&4294967295);$ssml_sp=$arrayidx31;if($22==10){__lastLabel__=14;__label__=15;;}
else if($22==3){__lastLabel__=14;__label__=20;;}
else if($22==12){__lastLabel__=14;__label__=25;;}
else if($22==42){__lastLabel__=14;__label__=31;;}
else if($22==35){__lastLabel__=14;__label__=31;;}
else if($22==44){__lastLabel__=14;__label__=31;;}
else if($22==4){__lastLabel__=14;__label__=32;;}
else if($22==36){__lastLabel__=14;__label__=39;;}
else if($22==9){__lastLabel__=14;__label__=42;;}
else if($22==14){__lastLabel__=14;__label__=44;;}
else if($22==41){__lastLabel__=14;__label__=45;;}
else if($22==46){__lastLabel__=14;__label__=45;;}
else if($22==5){__lastLabel__=14;__label__=46;;}
else if($22==11){__lastLabel__=14;__label__=51;;}
else if($22==43){__lastLabel__=14;__label__=66;;}
else if($22==13){__lastLabel__=14;__label__=67;;}
else if($22==1){__lastLabel__=14;__label__=79;;}
else if($22==2){__lastLabel__=14;__label__=85;;}
else if($22==33){__lastLabel__=14;__label__=88;;}
else if($22==34){__lastLabel__=14;__label__=92;;}
else if($22==15){__lastLabel__=14;__label__=96;;}
else if($22==47){__lastLabel__=14;__label__=96;;}
else if($22==6){__lastLabel__=14;__label__=97;;}
else if($22==7){__lastLabel__=14;__label__=100;;}
else if($22==38){__lastLabel__=14;__label__=105;;}
else if($22==39){__lastLabel__=14;__label__=108;;}
else{__lastLabel__=14;__label__=112;;}
$sw_epilog$$sw_bb$$sw_bb49$$sw_bb62$$sw_bb83$$sw_bb84$$sw_bb110$$sw_bb120$$sw_bb129$$sw_bb130$$sw_bb131$$sw_bb156$$sw_bb220$$sw_bb221$$sw_bb249$$sw_bb266$$while_cond$$while_cond280$$sw_bb293$$sw_bb294$$sw_bb302$$sw_bb317$$sw_bb324$21:do{if(__label__==15){var $24=$tag_type;var $call32=__ZL14PushParamStacki($24);$sp=$call32;var $25=$px;var $call33=__ZL16GetSsmlAttributePwPKc($25,((__str83250)&4294967295));$attr1=$call33;var $26=$px;var $call34=__ZL16GetSsmlAttributePwPKc($26,((__str84251)&4294967295));$attr2=$call34;var $27=$attr1;var $call35=__ZL7attrcmpPKwPKc($27,((__str85252)&4294967295));var $cmp36=((($call35))|0)==0;if($cmp36){__label__=16;;}else{__label__=17;;}
$if_then37$$if_else40$23:do{if(__label__==16){var $28=$attr2;var $call38=__ZL10attrlookupPKwPK8MNEM_TAB($28,((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_punct)&4294967295));$value=$call38;var $29=$value;var $30=$sp;var $parameter=(($30+4)&4294967295);var $arrayidx39=(($parameter+20)&4294967295);HEAP32[(($arrayidx39)>>2)]=$29;;}
else if(__label__==17){var $31=$attr1;var $call41=__ZL7attrcmpPKwPKc($31,((__str86253)&4294967295));var $cmp42=((($call41))|0)==0;if(!($cmp42)){__label__=19;break $if_then37$$if_else40$23;}
var $32=$attr2;var $call44=__ZL10attrlookupPKwPK8MNEM_TAB($32,((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_capitals)&4294967295));$value=$call44;var $33=$value;var $34=$sp;var $parameter45=(($34+4)&4294967295);var $arrayidx46=(($parameter45+24)&4294967295);HEAP32[(($arrayidx46)>>2)]=$33;;}}while(0);var $35=$outbuf_addr;var $36=$outix_addr;__ZL17ProcessParamStackPcRi($35,$36);;}
else if(__label__==20){var $37=$tag_type;var $call50=__ZL14PushParamStacki($37);$sp=$call50;$param_type=1;;while(1){var $38=$px;var $39=$param_type;var $arrayidx54=((__ZZL14ProcessSsmlTagPwPcRiiiE12prosody_attr+$39*4)&4294967295);var $40=HEAP32[(($arrayidx54)>>2)];var $call55=__ZL16GetSsmlAttributePwPKc($38,$40);$attr1=$call55;var $cmp56=((($call55))|0)!=0;if($cmp56){__label__=22;;}else{__label__=23;;}
if(__label__==22){var $41=$param_type;var $42=$attr1;var $43=$sp;__ZL19SetProsodyParameteriPwP11PARAM_STACK($41,$42,$43);;}
var $44=$param_type;var $inc60=((($44)+1)&4294967295);$param_type=$inc60;var $cmp52=((($inc60))|0)<=4;if($cmp52){__label__=21;continue;}else{__label__=24;break;}}
var $45=$outbuf_addr;var $46=$outix_addr;__ZL17ProcessParamStackPcRi($45,$46);;}
else if(__label__==25){var $47=$tag_type;var $call63=__ZL14PushParamStacki($47);$sp=$call63;$value=3;var $48=$px;var $call64=__ZL16GetSsmlAttributePwPKc($48,((__str87254)&4294967295));$attr1=$call64;var $cmp65=((($call64))|0)!=0;if($cmp65){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $49=$attr1;var $call67=__ZL10attrlookupPKwPK8MNEM_TAB($49,((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_emphasis)&4294967295));$value=$call67;;}
var $50=HEAP32[((_translator)>>2)];var $langopts=(($50)&4294967295);var $tone_language=(($langopts+224)&4294967295);var $51=HEAP32[(($tone_language)>>2)];var $cmp69=((($51))|0)==1;var $52=$value;if($cmp69){__label__=28;;}else{__label__=29;;}
if(__label__==28){var $arrayidx71=((__ZZL14ProcessSsmlTagPwPcRiiiE23emphasis_to_pitch_range+$52)&4294967295);var $53=HEAPU8[($arrayidx71)];var $conv72=((($53))&255);var $54=$sp;var $parameter73=(($54+4)&4294967295);var $arrayidx74=(($parameter73+16)&4294967295);HEAP32[(($arrayidx74)>>2)]=$conv72;var $55=$value;var $arrayidx75=((__ZZL14ProcessSsmlTagPwPcRiiiE18emphasis_to_volume+$55)&4294967295);var $56=HEAPU8[($arrayidx75)];var $conv76=((($56))&255);var $57=$sp;var $parameter77=(($57+4)&4294967295);var $arrayidx78=(($parameter77+8)&4294967295);HEAP32[(($arrayidx78)>>2)]=$conv76;;}
else if(__label__==29){var $58=$sp;var $parameter80=(($58+4)&4294967295);var $arrayidx81=(($parameter80+48)&4294967295);HEAP32[(($arrayidx81)>>2)]=$52;;}
var $59=$outbuf_addr;var $60=$outix_addr;__ZL17ProcessParamStackPcRi($59,$60);;}
else if(__label__==31){var $61=$tag_type;var $62=$outbuf_addr;var $63=$outix_addr;__ZL13PopParamStackiPcRi($61,$62,$63);;}
else if(__label__==32){var $64=$px;var $call85=__ZL16GetSsmlAttributePwPKc($64,((__str88255)&4294967295));$attr1=$call85;var $65=$px;var $call86=__ZL16GetSsmlAttributePwPKc($65,((__str89256)&4294967295));$attr2=$call86;var $66=$px;var $call87=__ZL16GetSsmlAttributePwPKc($66,((__str90257)&4294967295));$attr3=$call87;var $67=$attr1;var $call88=__ZL10attrlookupPKwPK8MNEM_TAB($67,((__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_interpret_as)&4294967295));$value=$call88;var $68=$attr2;var $call89=__ZL10attrlookupPKwPK8MNEM_TAB($68,((__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_sayas_format)&4294967295));$value2=$call89;var $69=$value2;var $cmp90=((($69))|0)==1;if($cmp90){__label__=33;;}else{__label__=34;;}
if(__label__==33){$value=19;;}
var $70=$attr3;var $call93=__ZL10attrnumberPKwii($70,0,0);$value3=$call93;var $71=$value;var $cmp94=((($71))|0)==64;if($cmp94){__label__=35;;}else{__label__=38;;}
if(__label__==35){var $72=$value3;var $cmp96=((($72))|0)<=1;if($cmp96){__label__=36;;}else{__label__=37;;}
if(__label__==36){$value=193;;}
else if(__label__==37){var $73=$value3;var $add99=((($73)+64)&4294967295);$value=$add99;;}}
var $arraydecay102=(($buf)&4294967295);var $74=$value;var $call103=_sprintf($arraydecay102,((__str91258)&4294967295),allocate([1,0,0,0,$74,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $75=$outix_addr;var $76=HEAP32[(($75)>>2)];var $77=$outbuf_addr;var $arrayidx104=(($77+$76)&4294967295);var $arraydecay105=(($buf)&4294967295);var $call106=_strcpy($arrayidx104,$arraydecay105);var $arraydecay107=(($buf)&4294967295);var $call108=_strlen($arraydecay107);var $78=$outix_addr;var $79=HEAP32[(($78)>>2)];var $add109=((($79)+($call108))&4294967295);HEAP32[(($78)>>2)]=$add109;var $80=$outix_addr;var $81=HEAP32[(($80)>>2)];HEAP32[((__ZL11sayas_start)>>2)]=$81;var $82=$value;HEAP32[((__ZL10sayas_mode)>>2)]=$82;;}
else if(__label__==39){var $83=HEAP32[((__ZL10sayas_mode)>>2)];var $cmp111=((($83))|0)==36;if($cmp111){__label__=40;;}else{__label__=41;;}
if(__label__==40){var $84=$outix_addr;var $85=HEAP32[(($84)>>2)];var $86=$outbuf_addr;var $arrayidx113=(($86+$85)&4294967295);HEAP8[($arrayidx113)]=0;var $87=$outbuf_addr;var $88=HEAP32[((__ZL11sayas_start)>>2)];var $89=$outix_addr;__ZL14ReplaceKeyNamePciRi($87,$88,$89);;}
var $90=$outix_addr;var $91=HEAP32[(($90)>>2)];var $inc116=((($91)+1)&4294967295);HEAP32[(($90)>>2)]=$inc116;var $92=$outbuf_addr;var $arrayidx117=(($92+$91)&4294967295);HEAP8[($arrayidx117)]=1;var $93=$outix_addr;var $94=HEAP32[(($93)>>2)];var $inc118=((($94)+1)&4294967295);HEAP32[(($93)>>2)]=$inc118;var $95=$outbuf_addr;var $arrayidx119=(($95+$94)&4294967295);HEAP8[($arrayidx119)]=89;HEAP32[((__ZL10sayas_mode)>>2)]=0;;}
else if(__label__==42){var $96=$px;var $call121=__ZL16GetSsmlAttributePwPKc($96,((__str92259)&4294967295));$attr1=$call121;var $cmp122=((($call121))|0)!=0;if(!($cmp122)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb49$$sw_bb62$$sw_bb83$$sw_bb84$$sw_bb110$$sw_bb120$$sw_bb129$$sw_bb130$$sw_bb131$$sw_bb156$$sw_bb220$$sw_bb221$$sw_bb249$$sw_bb266$$while_cond$$while_cond280$$sw_bb293$$sw_bb294$$sw_bb302$$sw_bb317$$sw_bb324$21;}
HEAP8[(__ZL11ignore_text_b)]=1;var $97=$outix_addr;var $98=HEAP32[(($97)>>2)];var $99=$outbuf_addr;var $arrayidx124=(($99+$98)&4294967295);var $100=$attr1;var $101=$n_outbuf_addr;var $102=$outix_addr;var $103=HEAP32[(($102)>>2)];var $sub125=((($101)-($103))&4294967295);var $call126=__ZL13attrcopy_utf8PcPKwi($arrayidx124,$100,$sub125);var $104=$outix_addr;var $105=HEAP32[(($104)>>2)];var $add127=((($105)+($call126))&4294967295);HEAP32[(($104)>>2)]=$add127;;}
else if(__label__==44){HEAP8[(__ZL11ignore_text_b)]=1;;}
else if(__label__==45){HEAP8[(__ZL11ignore_text_b)]=0;;}
else if(__label__==46){var $106=$px;var $call132=__ZL16GetSsmlAttributePwPKc($106,((__str5655)&4294967295));$attr1=$call132;var $cmp133=((($call132))|0)!=0;if(!($cmp133)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb49$$sw_bb62$$sw_bb83$$sw_bb84$$sw_bb110$$sw_bb120$$sw_bb129$$sw_bb130$$sw_bb131$$sw_bb156$$sw_bb220$$sw_bb221$$sw_bb249$$sw_bb266$$while_cond$$while_cond280$$sw_bb293$$sw_bb294$$sw_bb302$$sw_bb317$$sw_bb324$21;}
var $arraydecay135=(($buf)&4294967295);var $107=$attr1;var $call136=__ZL13attrcopy_utf8PcPKwi($arraydecay135,$107,80);var $arraydecay137=(($buf)&4294967295);var $call138=_strcmp(((_skip_marker)&4294967295),$arraydecay137);var $cmp139=((($call138))|0)==0;if($cmp139){__label__=48;;}else{__label__=49;;}
if(__label__==48){HEAP8[(__ZL19clear_skipping_text_b)]=1;HEAP8[(((_skip_marker)&4294967295))]=0;$retval=16384;__label__=113;break $if_end30$$return$19;}
else if(__label__==49){var $arraydecay142=(($buf)&4294967295);var $call143=__Z11AddNameDataPKci($arraydecay142,0);$index=$call143;var $cmp144=((($call143))|0)>=0;if(!($cmp144)){__label__=112;break $sw_epilog$$sw_bb$$sw_bb49$$sw_bb62$$sw_bb83$$sw_bb84$$sw_bb110$$sw_bb120$$sw_bb129$$sw_bb130$$sw_bb131$$sw_bb156$$sw_bb220$$sw_bb221$$sw_bb249$$sw_bb266$$while_cond$$while_cond280$$sw_bb293$$sw_bb294$$sw_bb302$$sw_bb317$$sw_bb324$21;}
var $arraydecay146=(($buf)&4294967295);var $108=$index;var $call147=_sprintf($arraydecay146,((__str94261)&4294967295),allocate([1,0,0,0,$108,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $109=$outix_addr;var $110=HEAP32[(($109)>>2)];var $111=$outbuf_addr;var $arrayidx148=(($111+$110)&4294967295);var $arraydecay149=(($buf)&4294967295);var $call150=_strcpy($arrayidx148,$arraydecay149);var $arraydecay151=(($buf)&4294967295);var $call152=_strlen($arraydecay151);var $112=$outix_addr;var $113=HEAP32[(($112)>>2)];var $add153=((($113)+($call152))&4294967295);HEAP32[(($112)>>2)]=$add153;;}}
else if(__label__==51){var $114=$tag_type;var $call157=__ZL14PushParamStacki($114);$sp=$call157;var $115=$px;var $call158=__ZL16GetSsmlAttributePwPKc($115,((__str95262)&4294967295));$attr1=$call158;var $cmp159=((($call158))|0)!=0;if($cmp159){__label__=52;;}else{__label__=62;;}
$if_then160$$if_end215$69:do{if(__label__==52){var $arraydecay161=(($buf)&4294967295);var $116=$attr1;var $call162=__ZL13attrcopy_utf8PcPKwi($arraydecay161,$116,80);var $117=HEAP32[((_uri_callback)>>2)];var $cmp163=((($117))|0)==0;if($cmp163){__label__=53;;}else{__label__=59;;}
if(__label__==53){var $118=HEAP32[((__ZL7xmlbase)>>2)];var $cmp165=((($118))|0)!=0;if($cmp165){__label__=54;;}else{__label__=56;;}
$land_lhs_true166$$if_else176$73:do{if(__label__==54){var $arrayidx167=(($buf)&4294967295);var $119=HEAP8[($arrayidx167)];var $conv168=(tempInt=(($119)),(tempInt>=128?tempInt-256:tempInt));var $cmp169=((($conv168))|0)!=47;if(!($cmp169)){__label__=56;break $land_lhs_true166$$if_else176$73;}
var $arraydecay171=(($fname)&4294967295);var $120=HEAP32[((__ZL7xmlbase)>>2)];var $arraydecay172=(($buf)&4294967295);var $call173=_sprintf($arraydecay171,((__str96263)&4294967295),allocate([$120,0,0,0,$arraydecay172,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay174=(($fname)&4294967295);var $call175=__ZL14LoadSoundFile2PKc($arraydecay174);$index=$call175;__lastLabel__=55;__label__=57;break $land_lhs_true166$$if_else176$73;}}while(0);if(__label__==56){var $arraydecay177=(($buf)&4294967295);var $call178=__ZL14LoadSoundFile2PKc($arraydecay177);$index=$call178;__lastLabel__=56;;}
var $121=__lastLabel__==56?$call178:($call175);var $cmp180=((($121))|0)>=0;if(!($cmp180)){__label__=62;break $if_then160$$if_end215$69;}
var $arraydecay182=(($buf)&4294967295);var $122=$index;var $call183=_sprintf($arraydecay182,((__str97264)&4294967295),allocate([1,0,0,0,$122,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $123=$outix_addr;var $124=HEAP32[(($123)>>2)];var $125=$outbuf_addr;var $arrayidx184=(($125+$124)&4294967295);var $arraydecay185=(($buf)&4294967295);var $call186=_strcpy($arrayidx184,$arraydecay185);var $arraydecay187=(($buf)&4294967295);var $call188=_strlen($arraydecay187);var $126=$outix_addr;var $127=HEAP32[(($126)>>2)];var $add189=((($127)+($call188))&4294967295);HEAP32[(($126)>>2)]=$add189;var $128=$sp;var $parameter190=(($128+4)&4294967295);var $arrayidx191=(($parameter190)&4294967295);HEAP32[(($arrayidx191)>>2)]=1;;}
else if(__label__==59){var $arraydecay194=(($buf)&4294967295);var $call195=__Z11AddNameDataPKci($arraydecay194,0);$index=$call195;var $cmp196=((($call195))|0)>=0;if(!($cmp196)){__label__=62;break $if_then160$$if_end215$69;}
var $129=$index;var $130=HEAP32[((_namedata)>>2)];var $arrayidx198=(($130+$129)&4294967295);$uri=$arrayidx198;var $131=HEAP32[((_uri_callback)>>2)];var $132=$uri;var $133=HEAP32[((__ZL7xmlbase)>>2)];var $call199=FUNCTION_TABLE[$131](1,$132,$133);var $cmp200=((($call199))|0)==0;if(!($cmp200)){__label__=62;break $if_then160$$if_end215$69;}
var $arraydecay202=(($buf)&4294967295);var $134=$index;var $call203=_sprintf($arraydecay202,((__str98265)&4294967295),allocate([1,0,0,0,$134,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $135=$outix_addr;var $136=HEAP32[(($135)>>2)];var $137=$outbuf_addr;var $arrayidx204=(($137+$136)&4294967295);var $arraydecay205=(($buf)&4294967295);var $call206=_strcpy($arrayidx204,$arraydecay205);var $arraydecay207=(($buf)&4294967295);var $call208=_strlen($arraydecay207);var $138=$outix_addr;var $139=HEAP32[(($138)>>2)];var $add209=((($139)+($call208))&4294967295);HEAP32[(($138)>>2)]=$add209;var $140=$sp;var $parameter210=(($140+4)&4294967295);var $arrayidx211=(($parameter210)&4294967295);HEAP32[(($arrayidx211)>>2)]=1;;}}}while(0);var $141=$outbuf_addr;var $142=$outix_addr;__ZL17ProcessParamStackPcRi($141,$142);var $143=$self_closing_addr;var $tobool216=((($143))|0)!=0;if($tobool216){__label__=63;;}else{__label__=64;;}
if(__label__==63){var $144=$tag_type;var $145=$outbuf_addr;var $146=$outix_addr;__ZL13PopParamStackiPcRi($144,$145,$146);;}
else if(__label__==64){HEAP8[(__ZL10audio_text_b)]=1;;}
$retval=16384;__label__=113;break $if_end30$$return$19;}
else if(__label__==66){var $147=$tag_type;var $148=$outbuf_addr;var $149=$outix_addr;__ZL13PopParamStackiPcRi($147,$148,$149);HEAP8[(__ZL10audio_text_b)]=0;$retval=16384;__label__=113;break $if_end30$$return$19;}
else if(__label__==67){$value=21;$terminator=16384;var $150=$px;var $call222=__ZL16GetSsmlAttributePwPKc($150,((__str99266)&4294967295));$attr1=$call222;var $cmp223=((($call222))|0)!=0;if($cmp223){__label__=68;;}else{__label__=71;;}
if(__label__==68){var $151=$attr1;var $call225=__ZL10attrlookupPKwPK8MNEM_TAB($151,((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_break)&4294967295));$value=$call225;var $152=$value;var $cmp226=((($152))|0)<3;if($cmp226){__label__=69;;}else{__label__=70;;}
if(__label__==69){var $153=$outix_addr;var $154=HEAP32[(($153)>>2)];var $155=$outbuf_addr;var $arrayidx228=(($155+$154)&4294967295);var $156=$value;var $call229=_sprintf($arrayidx228,((__str100267)&4294967295),allocate([1,0,0,0,$156,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $157=$outix_addr;var $158=HEAP32[(($157)>>2)];var $add230=((($158)+3)&4294967295);HEAP32[(($157)>>2)]=$add230;$terminator=0;;}
var $159=$value;var $arrayidx232=((__ZZL14ProcessSsmlTagPwPcRiiiE11break_value+$159*4)&4294967295);var $160=HEAP32[(($arrayidx232)>>2)];$value=$160;;}
var $161=$px;var $call234=__ZL16GetSsmlAttributePwPKc($161,((__str101268)&4294967295));$attr2=$call234;var $cmp235=((($call234))|0)!=0;if($cmp235){__label__=72;;}else{__label__=74;;}
$if_then236$$if_end241$96:do{if(__label__==72){var $162=$attr2;var $call237=__ZL10attrnumberPKwii($162,0,1);var $mul=((($call237)*25)&4294967295);var $163=HEAP32[((((_speed)&4294967295))>>2)];var $div=((((($mul))|0)/((($163))|0))|0);$value=$div;var $164=$terminator;var $cmp238=((($164))|0)==0;if($cmp238){__lastLabel__=72;;}else{__lastLabel__=72;__label__=76;break $if_then236$$if_end241$96;}
$terminator=16384;__label__=75;break $if_then236$$if_end241$96;}
else if(__label__==74){var $_pr1=$terminator;var $tobool242=((($_pr1))|0)!=0;if($tobool242){__label__=75;break $if_then236$$if_end241$96;}else{__label__=112;break $sw_epilog$$sw_bb$$sw_bb49$$sw_bb62$$sw_bb83$$sw_bb84$$sw_bb110$$sw_bb120$$sw_bb129$$sw_bb130$$sw_bb131$$sw_bb156$$sw_bb220$$sw_bb221$$sw_bb249$$sw_bb266$$while_cond$$while_cond280$$sw_bb293$$sw_bb294$$sw_bb302$$sw_bb317$$sw_bb324$21;}}}while(0);if(__label__==75){var $_pr3=$value;__lastLabel__=75;;}
var $165=__lastLabel__==75?$_pr3:($div);var $cmp244=((($165))|0)>4095;if($cmp244){__label__=77;;}else{__label__=78;;}
if(__label__==77){$value=4095;;}
var $166=$terminator;var $167=$value;var $add247=((($167)+($166))&4294967295);$retval=$add247;__label__=113;break $if_end30$$return$19;}
else if(__label__==79){var $168=$px;var $call250=__ZL16GetSsmlAttributePwPKc($168,((__str102269)&4294967295));$attr1=$call250;var $cmp251=((($call250))|0)!=0;if($cmp251){__label__=80;;}else{__label__=82;;}
$if_then252$$if_end261$107:do{if(__label__==80){var $arraydecay253=(($buf)&4294967295);var $169=$attr1;var $call254=__ZL13attrcopy_utf8PcPKwi($arraydecay253,$169,80);var $arraydecay255=(($buf)&4294967295);var $call256=__Z11AddNameDataPKci($arraydecay255,0);$index=$call256;var $cmp257=((($call256))|0)>=0;if(!($cmp257)){__label__=82;break $if_then252$$if_end261$107;}
var $170=$index;var $171=HEAP32[((_namedata)>>2)];var $arrayidx259=(($171+$170)&4294967295);HEAP32[((__ZL7xmlbase)>>2)]=$arrayidx259;;}}while(0);var $172=$px;var $173=$tag_type;var $call262=__ZL18GetVoiceAttributesPwi($172,$173);var $cmp263=((($call262))|0)==0;if($cmp263){__label__=83;;}else{__label__=84;;}
if(__label__==83){$retval=0;__label__=113;break $if_end30$$return$19;}
else if(__label__==84){$retval=147456;__label__=113;break $if_end30$$return$19;}}
else if(__label__==85){var $174=$px;var $175=$tag_type;var $call267=__ZL18GetVoiceAttributesPwi($174,$175);var $cmp268=((($call267))|0)==0;if($cmp268){__label__=86;;}else{__label__=87;;}
if(__label__==86){$retval=0;__label__=113;break $if_end30$$return$19;}
else if(__label__==87){$retval=147456;__label__=113;break $if_end30$$return$19;}}
else if(__label__==88){while(1){var $176=__lastLabel__==90?$dec:($23);var $cmp272=((($176))|0)>1;if(!($cmp272)){__label__=91;break;}
var $177=HEAP32[((__ZL12n_ssml_stack)>>2)];var $sub273=((($177)-1)&4294967295);var $arrayidx274=((__ZL10ssml_stack+$sub273*76)&4294967295);var $tag_type275=(($arrayidx274)&4294967295);var $178=HEAP32[(($tag_type275)>>2)];var $cmp276=((($178))|0)!=1;if(!($cmp276)){__label__=91;break;}
var $179=HEAP32[((__ZL12n_ssml_stack)>>2)];var $dec=((($179)-1)&4294967295);HEAP32[((__ZL12n_ssml_stack)>>2)]=$dec;__lastLabel__=90;__label__=88;continue;}
var $180=$px;var $181=$tag_type;var $call277=__ZL18GetVoiceAttributesPwi($180,$181);var $add278=((($call277)+524328)&4294967295);$retval=$add278;__label__=113;break $if_end30$$return$19;}
else if(__label__==92){while(1){var $182=__lastLabel__==94?$dec289:($23);var $cmp281=((($182))|0)>1;if(!($cmp281)){__label__=95;break;}
var $183=HEAP32[((__ZL12n_ssml_stack)>>2)];var $sub283=((($183)-1)&4294967295);var $arrayidx284=((__ZL10ssml_stack+$sub283*76)&4294967295);var $tag_type285=(($arrayidx284)&4294967295);var $184=HEAP32[(($tag_type285)>>2)];var $cmp286=((($184))|0)!=2;if(!($cmp286)){__label__=95;break;}
var $185=HEAP32[((__ZL12n_ssml_stack)>>2)];var $dec289=((($185)-1)&4294967295);HEAP32[((__ZL12n_ssml_stack)>>2)]=$dec289;__lastLabel__=94;__label__=92;continue;}
$terminator=0;var $186=$terminator;var $187=$px;var $188=$tag_type;var $call291=__ZL18GetVoiceAttributesPwi($187,$188);var $add292=((($call291)+($186))&4294967295);$retval=$add292;__label__=113;break $if_end30$$return$19;}
else if(__label__==96){$retval=262174;__label__=113;break $if_end30$$return$19;}
else if(__label__==97){var $189=$ssml_sp;var $tag_type295=(($189)&4294967295);var $190=HEAP32[(($tag_type295)>>2)];var $cmp296=((($190))|0)==6;if($cmp296){__label__=98;;}else{__label__=99;;}
if(__label__==98){var $191=$px;var $call298=__ZL18GetVoiceAttributesPwi($191,38);$voice_change_flag=$call298;;}
var $192=$px;var $193=$tag_type;var $call300=__ZL18GetVoiceAttributesPwi($192,$193);var $194=$voice_change_flag;var $or=($194)|($call300);$voice_change_flag=$or;var $195=$voice_change_flag;var $add301=((($195)+524358)&4294967295);$retval=$add301;__label__=113;break $if_end30$$return$19;}
else if(__label__==100){var $196=$ssml_sp;var $tag_type303=(($196)&4294967295);var $197=HEAP32[(($tag_type303)>>2)];var $cmp304=((($197))|0)==6;if($cmp304){__label__=101;;}else{__label__=102;;}
if(__label__==101){var $198=$px;var $call306=__ZL18GetVoiceAttributesPwi($198,38);$voice_change_flag=$call306;;}
var $199=$ssml_sp;var $tag_type308=(($199)&4294967295);var $200=HEAP32[(($tag_type308)>>2)];var $cmp309=((($200))|0)==7;if($cmp309){__label__=103;;}else{__label__=104;;}
if(__label__==103){var $201=$px;var $call311=__ZL18GetVoiceAttributesPwi($201,39);var $202=$voice_change_flag;var $or312=($202)|($call311);$voice_change_flag=$or312;;}
var $203=$px;var $204=$tag_type;var $call314=__ZL18GetVoiceAttributesPwi($203,$204);var $205=$voice_change_flag;var $or315=($205)|($call314);$voice_change_flag=$or315;var $206=$voice_change_flag;var $add316=((($206)+524358)&4294967295);$retval=$add316;__label__=113;break $if_end30$$return$19;}
else if(__label__==105){var $207=$ssml_sp;var $tag_type318=(($207)&4294967295);var $208=HEAP32[(($tag_type318)>>2)];var $cmp319=((($208))|0)==6;if($cmp319){__label__=106;;}else{__label__=107;;}
if(__label__==106){var $209=$px;var $210=$tag_type;var $call321=__ZL18GetVoiceAttributesPwi($209,$210);$voice_change_flag=$call321;;}
var $211=$voice_change_flag;var $add323=((($211)+524328)&4294967295);$retval=$add323;__label__=113;break $if_end30$$return$19;}
else if(__label__==108){var $212=$ssml_sp;var $tag_type325=(($212)&4294967295);var $213=HEAP32[(($tag_type325)>>2)];var $cmp326=((($213))|0)==6;if($cmp326){__label__=110;;}else{__label__=109;;}
$if_then330$$lor_lhs_false327$145:do{if(__label__==109){var $214=$ssml_sp;var $tag_type328=(($214)&4294967295);var $215=HEAP32[(($tag_type328)>>2)];var $cmp329=((($215))|0)==7;if($cmp329){__label__=110;break $if_then330$$lor_lhs_false327$145;}
$retval=524358;__label__=113;break $if_end30$$return$19;}}while(0);var $216=$px;var $217=$tag_type;var $call331=__ZL18GetVoiceAttributesPwi($216,$217);var $add332=((($call331)+524358)&4294967295);$retval=$add332;__label__=113;break $if_end30$$return$19;}}while(0);$retval=0;;}}while(0);var $218=$retval;STACKTOP=__stackBase__;return $218;return null;}
function __ZL13LookupSpecialP10TranslatorPKcPc($tr,$text_out){var __stackBase__=STACKTOP;STACKTOP+=124;_memset(__stackBase__,0,124);var __label__;var $retval;var $tr_addr;var $string_addr;var $text_out_addr;var $flags=__stackBase__;var $phonemes=__stackBase__+8;var $phonemes2=__stackBase__+64;var $string1=__stackBase__+120;$tr_addr=$tr;$string_addr=((__str6303)&4294967295);$text_out_addr=$text_out;var $0=$string_addr;HEAP32[(($string1)>>2)]=$0;var $arrayidx=(($flags+4)&4294967295);HEAP32[(($arrayidx)>>2)]=0;var $arrayidx1=(($flags)&4294967295);HEAP32[(($arrayidx1)>>2)]=0;var $1=$tr_addr;var $arraydecay=(($phonemes)&4294967295);var $arraydecay2=(($flags)&4294967295);var $call=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($1,$string1,$arraydecay,$arraydecay2,0,0);var $tobool=((($call))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=$tr_addr;var $arraydecay3=(($phonemes)&4294967295);var $arraydecay4=(($flags)&4294967295);__Z13SetWordStressP10TranslatorPcPjii($2,$arraydecay3,$arraydecay4,-1,0);var $arraydecay5=(($phonemes)&4294967295);var $arraydecay6=(($phonemes2)&4294967295);__Z14DecodePhonemesPKcPc($arraydecay5,$arraydecay6);var $3=$text_out_addr;var $arraydecay7=(($phonemes2)&4294967295);var $call8=_sprintf($3,((__str60227)&4294967295),allocate([$arraydecay7,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $4=$text_out_addr;$retval=$4;;}
else if(__label__==2){$retval=0;;}
var $5=$retval;STACKTOP=__stackBase__;return $5;return null;}
function __ZL10RemoveCharPc($p){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $p_addr;var $c=__stackBase__;$p_addr=$p;var $0=$p_addr;var $1=$p_addr;var $call=__Z7utf8_inPiPKc($c,$1);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$0;$stop$=$dest$+$call;$value4$=32;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=32;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=32;};STACKTOP=__stackBase__;return;return;}
function __ZL19AnnouncePunctuationP10TranslatoriPiPcS1_i($tr,$c1,$c2_ptr,$output,$bufix,$end_clause){var __stackBase__=STACKTOP;STACKTOP+=280;_memset(__stackBase__,0,280);var __label__;var $retval;var $tr_addr;var $c1_addr;var $c2_ptr_addr;var $output_addr;var $bufix_addr;var $end_clause_addr;var $punct_count;var $punctname;var $found;var $soundicon;var $attributes;var $short_pause;var $c2;var $len;var $bufix1;var $buf=__stackBase__;var $buf2=__stackBase__+200;$tr_addr=$tr;$c1_addr=$c1;$c2_ptr_addr=$c2_ptr;$output_addr=$output;$bufix_addr=$bufix;$end_clause_addr=$end_clause;$found=0;var $0=$c2_ptr_addr;var $1=HEAP32[(($0)>>2)];$c2=$1;var $arrayidx=(($buf)&4294967295);HEAP8[($arrayidx)]=0;var $2=$c1_addr;var $call=__ZL15LookupSoundiconi($2);$soundicon=$call;var $cmp=((($call))|0)>=0;if($cmp){__label__=1;;}else{__label__=2;;}
$if_end63_thread$$if_else$2:do{if(__label__==1){var $arraydecay=(($buf)&4294967295);var $3=$soundicon;var $call1=_sprintf($arraydecay,((__str50217)&4294967295),allocate([$3,0,0,0],["i32",0,0,0],ALLOC_STACK));var $4=$c2;__ZL6UngetCi($4);$found=1;__label__=26;break $if_end63_thread$$if_else$2;}
else if(__label__==2){var $5=$tr_addr;var $6=$c1_addr;__ZL14LookupCharNameP10Translatorii($5,$6,0);$punctname=((__ZZL14LookupCharNameP10TranslatoriiE3buf)&4294967295);$found=1;var $7=$bufix_addr;var $8=HEAP32[(($7)>>2)];var $cmp5=((($8))|0)==0;if($cmp5){__label__=5;;}else{__label__=3;;}
$if_then9$$lor_lhs_false$5:do{if(__label__==3){var $9=$end_clause_addr;var $cmp6=((($9))|0)==0;if($cmp6){__label__=5;break $if_then9$$lor_lhs_false$5;}
var $10=$tr_addr;var $langopts=(($10)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx8=(($param+68)&4294967295);var $11=HEAP32[(($arrayidx8)>>2)];var $and=($11)&2;var $tobool=((($and))|0)!=0;if($tobool){__label__=5;break $if_then9$$lor_lhs_false$5;}
var $34=$c2;__ZL6UngetCi($34);var $35=HEAP32[((_option_ssml)>>2)];var $tobool51=((($35))|0)!=0;if($tobool51){__label__=21;;}else{__label__=23;;}
$if_then52$$if_end58$9:do{if(__label__==21){var $36=$c1_addr;var $cmp53=((($36))|0)==60;var $37=$c1_addr;var $cmp55=((($37))|0)==38;var $or_cond=($cmp53)|($cmp55);if(!($or_cond)){__label__=23;break $if_then52$$if_end58$9;}
var $38=$c1_addr;HEAP32[((__ZL19ssml_ignore_l_angle)>>2)]=$38;;}}while(0);var $39=$c1_addr;HEAP32[((__ZL11ungot_char2)>>2)]=$39;var $arrayidx59=(($buf)&4294967295);HEAP8[($arrayidx59)]=32;var $arrayidx60=(($buf+1)&4294967295);HEAP8[($arrayidx60)]=0;__label__=24;break $if_then9$$lor_lhs_false$5;}}while(0);$if_then9$$if_end63$13:do{if(__label__==5){$punct_count=1;var $12=$c2;var $13=$c1_addr;var $cmp105=((($12))|0)==((($13))|0);var $14=$c1_addr;var $cmp116=((($14))|0)!=60;var $or_cond17=($cmp105)&($cmp116);if($or_cond17){__label__=6;;}else{__label__=7;;}
$while_body$$while_end$15:do{if(__label__==6){while(1){var $15=$punct_count;var $inc=((($15)+1)&4294967295);$punct_count=$inc;var $call12=__ZL4GetCv();$c2=$call12;var $16=$c2;var $17=$c1_addr;var $cmp10=((($16))|0)==((($17))|0);var $18=$c1_addr;var $cmp11=((($18))|0)!=60;var $or_cond1=($cmp10)&($cmp11);if($or_cond1){__label__=6;continue;}else{__label__=7;break $while_body$$while_end$15;}}}}while(0);var $19=$c2;var $20=$c2_ptr_addr;HEAP32[(($20)>>2)]=$19;var $21=$end_clause_addr;var $tobool13=((($21))|0)!=0;if($tobool13){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $22=$c2;__ZL6UngetCi($22);;}
var $23=$punct_count;var $cmp15=((($23))|0)==1;if($cmp15){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $arraydecay17=(($buf)&4294967295);var $24=$punctname;var $call18=_sprintf($arraydecay17,((__str51218)&4294967295),allocate([$24,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==11){var $25=$punct_count;var $cmp20=((($25))|0)<4;var $arrayidx22=(($buf)&4294967295);if($cmp20){__label__=12;;}else{__label__=19;;}
if(__label__==12){HEAP8[($arrayidx22)]=0;var $26=HEAP32[((((_embedded_value+8)&4294967295))>>2)];var $cmp23=((($26))|0)<300;if($cmp23){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $arraydecay25=(($buf)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str52219)&4294967295);$dest$=$arraydecay25;$stop$=$src$+6;if(($dest$%4)==($src$%4)&&6>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}
var $27=$punct_count;var $dec3=((($27)-1)&4294967295);$punct_count=$dec3;var $cmp294=((($27))|0)>0;if($cmp294){__label__=15;;}else{__label__=17;;}
$while_body30_lr_ph$$while_end36$30:do{if(__label__==15){var $arraydecay31=(($buf2)&4294967295);var $arraydecay33=(($buf)&4294967295);var $arraydecay34=(($buf2)&4294967295);;while(1){var $28=$punctname;var $call32=_sprintf($arraydecay31,((__str51218)&4294967295),allocate([$28,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $call35=_strcat($arraydecay33,$arraydecay34);var $29=$punct_count;var $dec=((($29)-1)&4294967295);$punct_count=$dec;var $cmp29=((($29))|0)>0;if($cmp29){__label__=16;continue;}else{__label__=17;break $while_body30_lr_ph$$while_end36$30;}}}}while(0);var $30=HEAP32[((((_embedded_value+8)&4294967295))>>2)];var $cmp37=((($30))|0)<300;if(!($cmp37)){__label__=24;break $if_then9$$if_end63$13;}
var $arraydecay39=(($buf2)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str53220)&4294967295);$dest$=$arraydecay39;$stop$=$src$+7;if(($dest$%4)==($src$%4)&&7>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $arraydecay41=(($buf)&4294967295);var $arraydecay42=(($buf2)&4294967295);var $call43=_strcat($arraydecay41,$arraydecay42);;}
else if(__label__==19){var $31=$punctname;var $32=$punct_count;var $33=$punctname;var $call47=_sprintf($arrayidx22,((__str54221)&4294967295),allocate([$31,0,0,0,$32,0,0,0,$33,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}}}}while(0);var $_pr=$found;var $cmp64=((($_pr))|0)==0;if(!($cmp64)){__label__=26;break $if_end63_thread$$if_else$2;}
$retval=-1;__label__=40;break $if_end63_thread$$if_else$2;}}while(0);$if_end66$$return$39:do{if(__label__==26){var $40=$bufix_addr;var $41=HEAP32[(($40)>>2)];$bufix1=$41;var $arraydecay67=(($buf)&4294967295);var $call68=_strlen($arraydecay67);$len=$call68;var $42=$bufix_addr;var $43=HEAP32[(($42)>>2)];var $44=$output_addr;var $arrayidx69=(($44+$43)&4294967295);var $arraydecay70=(($buf)&4294967295);var $call71=_strcpy($arrayidx69,$arraydecay70);var $45=$len;var $46=$bufix_addr;var $47=HEAP32[(($46)>>2)];var $add=((($47)+($45))&4294967295);HEAP32[(($46)>>2)]=$add;var $48=$end_clause_addr;var $cmp72=((($48))|0)==0;if($cmp72){__label__=27;;}else{__label__=28;;}
if(__label__==27){$retval=-1;;}
else if(__label__==28){var $49=$c1_addr;var $cmp75=((($49))|0)==45;if($cmp75){__label__=29;;}else{__label__=30;;}
if(__label__==29){$retval=16384;;}
else if(__label__==30){var $50=$c1_addr;var $call78=__Z11lookupwcharPKti(((__ZL11punct_chars)&4294967295),$50);var $arrayidx79=((__ZL16punct_attributes+$call78*4)&4294967295);var $51=HEAP32[(($arrayidx79)>>2)];$attributes=$51;$short_pause=262148;var $52=$attributes;var $and80=($52)&28672;var $cmp81=((($and80))|0)==4096;if($cmp81){__label__=31;;}else{__label__=32;;}
if(__label__==31){$short_pause=266244;;}
var $53=$bufix1;var $cmp84=((($53))|0)>0;if($cmp84){__label__=33;;}else{__label__=37;;}
$land_lhs_true$$if_end95$50:do{if(__label__==33){var $54=$tr_addr;var $langopts85=(($54)&4294967295);var $param86=(($langopts85+24)&4294967295);var $arrayidx87=(($param86+68)&4294967295);var $55=HEAP32[(($arrayidx87)>>2)];var $and88=($55)&2;var $tobool89=((($and88))|0)!=0;if($tobool89){__label__=37;break $land_lhs_true$$if_end95$50;}
var $56=$attributes;var $and91=($56)&-32769;var $cmp92=((($and91))|0)==266270;if($cmp92){__label__=35;;}else{__label__=36;;}
if(__label__==35){$retval=262148;__label__=40;break $if_end66$$return$39;}
else if(__label__==36){var $57=$short_pause;$retval=$57;__label__=40;break $if_end66$$return$39;}}}while(0);var $58=$attributes;var $and96=($58)&524288;var $tobool97=((($and96))|0)!=0;if($tobool97){__label__=38;;}else{__label__=39;;}
if(__label__==38){var $59=$attributes;$retval=$59;;}
else if(__label__==39){var $60=$short_pause;$retval=$60;;}}}}}while(0);var $61=$retval;STACKTOP=__stackBase__;return $61;return null;}
function __ZL14LookupCharNameP10Translatorii($tr,$c,$only){var __stackBase__=STACKTOP;STACKTOP+=156;_memset(__stackBase__,0,156);var __label__;var $tr_addr;var $c_addr;var $only_addr;var $ix;var $flags=__stackBase__;var $single_letter=__stackBase__+8;var $phonemes=__stackBase__+32;var $phonemes2=__stackBase__+92;var $lang_name;var $string=__stackBase__+152;$tr_addr=$tr;$c_addr=$c;$only_addr=$only;$lang_name=0;HEAP8[(((__ZZL14LookupCharNameP10TranslatoriiE3buf)&4294967295))]=0;var $arrayidx=(($flags)&4294967295);HEAP32[(($arrayidx)>>2)]=0;var $arrayidx1=(($flags+4)&4294967295);HEAP32[(($arrayidx1)>>2)]=0;var $arrayidx2=(($single_letter)&4294967295);HEAP8[($arrayidx2)]=0;var $arrayidx3=(($single_letter+1)&4294967295);HEAP8[($arrayidx3)]=95;var $0=$c_addr;var $arrayidx4=(($single_letter+2)&4294967295);var $call=__Z8utf8_outjPc($0,$arrayidx4);$ix=$call;var $1=$ix;var $add=((($1)+2)&4294967295);var $arrayidx5=(($single_letter+$add)&4294967295);HEAP8[($arrayidx5)]=0;var $2=$only_addr;var $tobool=((($2))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
$if_then$$if_else$2:do{if(__label__==1){var $arrayidx6=(($single_letter+2)&4294967295);HEAP32[(($string)>>2)]=$arrayidx6;var $3=$tr_addr;var $arraydecay=(($phonemes)&4294967295);var $arraydecay7=(($flags)&4294967295);var $call8=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($3,$string,$arraydecay,$arraydecay7,0,0);;}
else if(__label__==2){var $arrayidx9=(($single_letter+1)&4294967295);HEAP32[(($string)>>2)]=$arrayidx9;var $4=$tr_addr;var $arraydecay10=(($phonemes)&4294967295);var $arraydecay11=(($flags)&4294967295);var $call12=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($4,$string,$arraydecay10,$arraydecay11,0,0);var $cmp=((($call12))|0)==0;if(!($cmp)){__label__=5;break $if_then$$if_else$2;}
var $arrayidx14=(($single_letter+2)&4294967295);HEAP32[(($string)>>2)]=$arrayidx14;var $5=$tr_addr;var $arraydecay15=(($phonemes)&4294967295);var $arraydecay16=(($flags)&4294967295);var $call17=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($5,$string,$arraydecay15,$arraydecay16,0,0);var $cmp18=((($call17))|0)==0;if(!($cmp18)){__label__=5;break $if_then$$if_else$2;}
var $arrayidx20=(($single_letter+1)&4294967295);HEAP8[($arrayidx20)]=32;var $6=$tr_addr;var $arrayidx21=(($single_letter+2)&4294967295);var $arraydecay22=(($phonemes)&4294967295);var $call23=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($6,$arrayidx21,$arraydecay22,60,0,0,0);;}}while(0);var $7=$only_addr;var $cmp26=((($7))|0)==0;if($cmp26){__label__=6;;}else{__label__=13;;}
$land_lhs_true$$if_end50$8:do{if(__label__==6){var $arrayidx27=(($phonemes)&4294967295);var $8=HEAP8[($arrayidx27)];var $conv=(tempInt=(($8)),(tempInt>=128?tempInt-256:tempInt));var $cmp28=((($conv))|0)==0;if(!($cmp28)){__label__=13;break $land_lhs_true$$if_end50$8;}
var $9=$tr_addr;var $translator_name=(($9+280)&4294967295);var $10=HEAP32[(($translator_name)>>2)];var $cmp30=((($10))|0)!=25966;if(!($cmp30)){__label__=13;break $land_lhs_true$$if_end50$8;}
var $call32=__Z14SetTranslator2PKc(((__str52704)&4294967295));var $arrayidx33=(($single_letter+1)&4294967295);HEAP32[(($string)>>2)]=$arrayidx33;var $arrayidx34=(($single_letter+1)&4294967295);HEAP8[($arrayidx34)]=95;var $11=HEAP32[((_translator2)>>2)];var $arraydecay35=(($phonemes)&4294967295);var $arraydecay36=(($flags)&4294967295);var $call37=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($11,$string,$arraydecay35,$arraydecay36,0,0);var $cmp38=((($call37))|0)==0;if($cmp38){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $arrayidx40=(($single_letter+2)&4294967295);HEAP32[(($string)>>2)]=$arrayidx40;var $12=HEAP32[((_translator2)>>2)];var $arraydecay41=(($phonemes)&4294967295);var $arraydecay42=(($flags)&4294967295);var $call43=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($12,$string,$arraydecay41,$arraydecay42,0,0);;}
var $arrayidx45=(($phonemes)&4294967295);var $13=HEAP8[($arrayidx45)];var $tobool46=(tempInt=(($13)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool46){__label__=11;;}else{__label__=12;;}
if(__label__==11){$lang_name=((__str52704)&4294967295);;}
else if(__label__==12){var $14=HEAP32[((_voice)>>2)];var $phoneme_tab_ix=(($14+40)&4294967295);var $15=HEAP32[(($phoneme_tab_ix)>>2)];__Z18SelectPhonemeTablei($15);;}}}while(0);var $arrayidx51=(($phonemes)&4294967295);var $16=HEAP8[($arrayidx51)];var $tobool52=(tempInt=(($16)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool52){__label__=14;;}else{__label__=17;;}
$if_then53$$if_else73$19:do{if(__label__==14){var $17=$lang_name;var $tobool54=((($17))|0)!=0;if($tobool54){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $18=HEAP32[((_translator2)>>2)];var $arraydecay56=(($phonemes)&4294967295);var $arraydecay57=(($flags)&4294967295);__Z13SetWordStressP10TranslatorPcPjii($18,$arraydecay56,$arraydecay57,-1,0);var $arraydecay58=(($phonemes)&4294967295);var $arraydecay59=(($phonemes2)&4294967295);__Z14DecodePhonemesPKcPc($arraydecay58,$arraydecay59);var $arraydecay60=(($phonemes2)&4294967295);var $19=$tr_addr;var $translator_name61=(($19+280)&4294967295);var $20=HEAP32[(($translator_name61)>>2)];__ZL13WordToString2j($20);var $call63=_sprintf(((__ZZL14LookupCharNameP10TranslatoriiE3buf)&4294967295),((__str47214)&4294967295),allocate([((__str52704)&4294967295),0,0,0,$arraydecay60,0,0,0,((__ZZL13WordToString2jE3buf)&4294967295),0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $21=HEAP32[((_voice)>>2)];var $phoneme_tab_ix64=(($21+40)&4294967295);var $22=HEAP32[(($phoneme_tab_ix64)>>2)];__Z18SelectPhonemeTablei($22);;}
else if(__label__==16){var $23=$tr_addr;var $arraydecay66=(($phonemes)&4294967295);var $arraydecay67=(($flags)&4294967295);__Z13SetWordStressP10TranslatorPcPjii($23,$arraydecay66,$arraydecay67,-1,0);var $arraydecay68=(($phonemes)&4294967295);var $arraydecay69=(($phonemes2)&4294967295);__Z14DecodePhonemesPKcPc($arraydecay68,$arraydecay69);var $arraydecay70=(($phonemes2)&4294967295);var $call71=_sprintf(((__ZZL14LookupCharNameP10TranslatoriiE3buf)&4294967295),((__str48215)&4294967295),allocate([$arraydecay70,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}}
else if(__label__==17){var $24=$only_addr;var $cmp74=((($24))|0)==0;if(!($cmp74)){__label__=19;break $if_then53$$if_else73$19;}
var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str49216)&4294967295);$dest$=((__ZZL14LookupCharNameP10TranslatoriiE3buf)&4294967295);$stop$=$src$+17;if(($dest$%4)==($src$%4)&&17>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}}while(0);STACKTOP=__stackBase__;return;return;}
function __ZL8IsRomanUj($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))|0)==73;var $1=$c_addr;var $cmp1=((($1))|0)==86;var $or_cond=($cmp)|($cmp1);var $2=$c_addr;var $cmp3=((($2))|0)==88;var $or_cond1=($or_cond)|($cmp3);var $3=$c_addr;var $cmp5=((($3))|0)==76;var $or_cond2=($or_cond1)|($cmp5);if($or_cond2){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){$retval=0;;}
var $4=$retval;;return $4;return null;}
function __Z12InitNamedatav(){;var __label__;HEAP32[((__ZL11namedata_ix)>>2)]=0;var $0=HEAP32[((_namedata)>>2)];var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=HEAP32[((_namedata)>>2)];;HEAP32[((_namedata)>>2)]=0;HEAP32[((__ZL10n_namedata)>>2)]=0;;};return;return;}
function __Z9InitText2v(){;var __label__;var $param;HEAP32[((__ZL10ungot_char)>>2)]=0;HEAP32[((__ZL11ungot_char2)>>2)]=0;HEAP32[((__ZL12n_ssml_stack)>>2)]=1;HEAP32[((__ZL13n_param_stack)>>2)]=1;HEAP32[((((__ZL10ssml_stack)&4294967295))>>2)]=0;$param=0;;while(1){var $0=$param;var $arrayidx=((((_param_stack+4)&4294967295)+$0*4)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];var $2=$param;var $arrayidx1=((__ZL17speech_parameters+$2*4)&4294967295);HEAP32[(($arrayidx1)>>2)]=$1;var $3=$param;var $inc=((($3)+1)&4294967295);$param=$inc;var $cmp=((($inc))|0)<15;if($cmp){__label__=1;continue;}else{__label__=2;break;}}
var $4=HEAP32[((((__ZL17speech_parameters+20)&4294967295))>>2)];HEAP32[((_option_punctuation)>>2)]=$4;var $5=HEAP32[((((__ZL17speech_parameters+24)&4294967295))>>2)];HEAP32[((_option_capitals)>>2)]=$5;HEAP8[(((__ZL16current_voice_id)&4294967295))]=0;HEAP8[(__ZL11ignore_text_b)]=0;HEAP8[(__ZL10audio_text_b)]=0;HEAP8[(__ZL19clear_skipping_text_b)]=0;HEAP32[((_count_characters)>>2)]=-1;HEAP32[((__ZL10sayas_mode)>>2)]=0;HEAP32[((__ZL7xmlbase)>>2)]=0;;return;return;}
function __ZL13WordToString2j($word){;var __label__;var $word_addr;var $ix;var $p;$word_addr=$word;$p=((__ZZL13WordToString2jE3buf)&4294967295);$ix=3;;while(1){var $0=$word_addr;var $1=$ix;var $mul=((($1)*8)&4294967295);var $shr=($0)>>>((($mul))>>>0);var $conv=((($shr))&255);var $2=$p;HEAP8[($2)]=$conv;var $conv1=(tempInt=(($conv)),(tempInt>=128?tempInt-256:tempInt));var $cmp2=((($conv1))|0)!=0;if($cmp2){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $3=$p;var $incdec_ptr=(($3+1)&4294967295);$p=$incdec_ptr;;}
var $4=$ix;var $dec=((($4)-1)&4294967295);$ix=$dec;var $cmp=((($dec))|0)>=0;if($cmp){__label__=1;continue;}else{__label__=4;break;}}
var $5=$p;HEAP8[($5)]=0;;return;return;}
function __ZL15LookupSoundiconi($c){;var __label__;var $retval;var $c_addr;var $ix;$c_addr=$c;$ix=4;;$for_cond$2:while(1){var $0=$ix;var $1=HEAP32[((_n_soundicon_tab)>>2)];var $cmp=((($0))|0)<((($1))|0);if(!($cmp)){__label__=8;break $for_cond$2;}
var $2=$ix;var $arrayidx=((_soundicon_tab+$2*16)&4294967295);var $name=(($arrayidx)&4294967295);var $3=HEAP32[(($name)>>2)];var $4=$c_addr;var $cmp1=((($3))|0)==((($4))|0);var $5=$ix;if($cmp1){__label__=3;break $for_cond$2;}
var $inc=((($5)+1)&4294967295);$ix=$inc;__label__=1;continue $for_cond$2;}
$for_end$$if_then$6:do{if(__label__==8){$retval=-1;;}
else if(__label__==3){var $arrayidx2=((_soundicon_tab+$5*16)&4294967295);var $length=(($arrayidx2+4)&4294967295);var $6=HEAP32[(($length)>>2)];var $cmp3=((($6))|0)==0;if($cmp3){__label__=4;;}else{__label__=6;;}
$if_then4$$if_end7$9:do{if(__label__==4){var $7=$ix;var $call=__ZL13LoadSoundFilePKci(0,$7);var $cmp5=((($call))|0)!=0;if(!($cmp5)){__label__=6;break $if_then4$$if_end7$9;}
$retval=-1;__label__=9;break $for_end$$if_then$6;}}while(0);var $8=$ix;$retval=$8;;}}while(0);var $9=$retval;;return $9;return null;}
function __ZL13LoadSoundFilePKci($fname,$index){var __stackBase__=STACKTOP;STACKTOP+=764;_memset(__stackBase__,0,764);var __label__;var $retval;var $fname_addr;var $index_addr;var $f;var $p;var $ip;var $length;var $fname_temp=__stackBase__;var $fname2=__stackBase__+100;var $ix;var $fd_temp;var $resample;var $header=__stackBase__+304;var $command=__stackBase__+316;$fname_addr=$fname;$index_addr=$index;var $0=$fname_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=3;;}
$if_end$$if_end3$2:do{if(__label__==1){var $1=$index_addr;var $arrayidx=((_soundicon_tab+$1*16)&4294967295);var $filename=(($arrayidx+12)&4294967295);var $2=HEAP32[(($filename)>>2)];$fname_addr=$2;var $cmp1=((($2))|0)==0;if(!($cmp1)){__label__=3;break $if_end$$if_end3$2;}
$retval=1;__label__=23;break $if_end$$if_end3$2;}}while(0);$return$$if_end3$5:do{if(__label__==3){var $3=$fname_addr;var $arrayidx4=(($3)&4294967295);var $4=HEAP8[($arrayidx4)];var $conv=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $cmp5=((($conv))|0)!=47;if($cmp5){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $arraydecay=(($fname2)&4294967295);var $5=$fname_addr;var $call=_sprintf($arraydecay,((__str55222)&4294967295),allocate([((_path_home)&4294967295),0,0,0,47,0,0,0,47,0,0,0,$5,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay7=(($fname2)&4294967295);$fname_addr=$arraydecay7;;}
$f=0;var $6=$fname_addr;var $call9=_fopen($6,((__str18429)&4294967295));$f=$call9;var $cmp10=((($call9))|0)!=0;if($cmp10){__label__=6;;}else{__label__=18;;}
$if_then11$$if_then49$10:do{if(__label__==6){var $7=$f;var $call12=_fseek($7,20,0);$ix=0;;$for_body$12:while(1){var $8=$f;var $call14=__Z10Read4BytesP7__sFILE($8);var $9=$ix;var $arrayidx15=(($header+$9*4)&4294967295);HEAP32[(($arrayidx15)>>2)]=$call14;var $10=$ix;var $inc=((($10)+1)&4294967295);$ix=$inc;var $cmp13=((($inc))|0)<3;if($cmp13){__label__=7;continue $for_body$12;}else{__label__=8;break $for_body$12;}}
var $arrayidx16=(($header)&4294967295);var $11=HEAP32[(($arrayidx16)>>2)];var $cmp17=((($11))|0)!=65537;if($cmp17){__label__=11;;}else{__label__=9;;}
$if_then23$$lor_lhs_false$15:do{if(__label__==9){var $arrayidx18=(($header+4)&4294967295);var $12=HEAP32[(($arrayidx18)>>2)];var $13=HEAP32[((_samplerate)>>2)];var $cmp19=((($12))|0)!=((($13))|0);if($cmp19){__label__=11;break $if_then23$$lor_lhs_false$15;}
var $arrayidx21=(($header+8)&4294967295);var $14=HEAP32[(($arrayidx21)>>2)];var $15=HEAP32[((_samplerate)>>2)];var $mul=((($15)*2)&4294967295);var $cmp22=((($14))|0)!=((($mul))|0);if($cmp22){__label__=11;break $if_then23$$lor_lhs_false$15;}else{__label__=17;break $if_then23$$lor_lhs_false$15;}}}while(0);$if_then23$$if_end47$18:do{if(__label__==11){var $16=$f;var $call24=_fclose($16);$f=0;var $arrayidx25=(($header+8)&4294967295);var $17=HEAP32[(($arrayidx25)>>2)];var $18=HEAP32[((_samplerate)>>2)];var $cmp26=((($17))|0)==((($18))|0);if($cmp26){__label__=12;;}else{__label__=13;;}
if(__label__==12){$resample=((__str13643)&4294967295);;}
else if(__label__==13){$resample=((__str57224)&4294967295);;}
var $arraydecay29=(($fname_temp)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str58225)&4294967295);$dest$=$arraydecay29;$stop$=$src$+18;if(($dest$%4)==($src$%4)&&18>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $arraydecay31=(($fname_temp)&4294967295);var $call32=_mkstemp($arraydecay31);$fd_temp=$call32;var $cmp33=((($call32))|0)>=0;if(!($cmp33)){__label__=17;break $if_then23$$if_end47$18;}
var $19=$fd_temp;var $call35=_close($19);var $arraydecay36=(($command)&4294967295);var $20=$fname_addr;var $21=HEAP32[((_samplerate)>>2)];var $arraydecay37=(($fname_temp)&4294967295);var $22=$resample;var $call38=_sprintf($arraydecay36,((__str59226)&4294967295),allocate([$20,0,0,0,$21,0,0,0,$arraydecay37,0,0,0,$22,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay39=(($command)&4294967295);var $call40=_system($arraydecay39);var $cmp41=((($call40))|0)==0;if(!($cmp41)){__label__=17;break $if_then23$$if_end47$18;}
var $arraydecay43=(($fname_temp)&4294967295);$fname_addr=$arraydecay43;;}}while(0);var $_pr=$f;var $cmp48=((($_pr))|0)==0;if($cmp48){__label__=18;break $if_then11$$if_then49$10;}else{__label__=20;break $if_then11$$if_then49$10;}}}while(0);$if_then49$$if_end54$27:do{if(__label__==18){var $23=$fname_addr;var $call50=_fopen($23,((__str18429)&4294967295));$f=$call50;var $cmp51=((($call50))|0)==0;if(!($cmp51)){__label__=20;break $if_then49$$if_end54$27;}
$retval=3;__label__=23;break $return$$if_end3$5;}}while(0);var $24=$fname_addr;var $call55=__Z13GetFileLengthPKc($24);$length=$call55;var $25=$f;var $call56=_fseek($25,0,0);var $26=$index_addr;var $arrayidx57=((_soundicon_tab+$26*16)&4294967295);var $data=(($arrayidx57+8)&4294967295);var $27=HEAP32[(($data)>>2)];var $28=$length;var $call58=_realloc($27,$28);$p=$call58;var $cmp59=((($call58))|0)==0;if($cmp59){__label__=21;;}else{__label__=22;;}
if(__label__==21){var $29=$f;var $call61=_fclose($29);$retval=4;;}
else if(__label__==22){var $30=$p;var $31=$length;var $32=$f;var $call63=_fread($30,1,$31,$32);$length=$call63;var $33=$f;var $call64=_fclose($33);var $arraydecay65=(($fname_temp)&4294967295);var $call66=_remove($arraydecay65);var $34=$p;var $arrayidx67=(($34+40)&4294967295);var $35=$arrayidx67;$ip=$35;var $36=$ip;var $37=HEAP32[(($36)>>2)];var $div=((((($37))|0)/2)|0);var $38=$index_addr;var $arrayidx68=((_soundicon_tab+$38*16)&4294967295);var $length69=(($arrayidx68+4)&4294967295);HEAP32[(($length69)>>2)]=$div;var $39=$p;var $40=$index_addr;var $arrayidx70=((_soundicon_tab+$40*16)&4294967295);var $data71=(($arrayidx70+8)&4294967295);HEAP32[(($data71)>>2)]=$39;$retval=0;;}}}while(0);var $41=$retval;STACKTOP=__stackBase__;return $41;return null;}
function __ZL14PushParamStacki($tag_type){;var __label__;var $tag_type_addr;var $ix;var $sp;$tag_type_addr=$tag_type;var $0=HEAP32[((__ZL13n_param_stack)>>2)];var $arrayidx=((_param_stack+$0*64)&4294967295);$sp=$arrayidx;var $cmp=((($0))|0)<19;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=HEAP32[((__ZL13n_param_stack)>>2)];var $inc=((($1)+1)&4294967295);HEAP32[((__ZL13n_param_stack)>>2)]=$inc;;}
var $2=$tag_type_addr;var $3=$sp;var $type=(($3)&4294967295);HEAP32[(($type)>>2)]=$2;$ix=0;;while(1){var $4=$ix;var $5=$sp;var $parameter=(($5+4)&4294967295);var $arrayidx2=(($parameter+$4*4)&4294967295);HEAP32[(($arrayidx2)>>2)]=-1;var $6=$ix;var $inc3=((($6)+1)&4294967295);$ix=$inc3;var $cmp1=((($inc3))|0)<15;if($cmp1){__label__=3;continue;}else{__label__=4;break;}}
var $7=$sp;;return $7;return null;}
function __ZL16GetSsmlAttributePwPKc($pw,$name){;var __label__;var __lastLabel__=null;var $retval;var $pw_addr;var $name_addr;var $ix;$pw_addr=$pw;$name_addr=$name;;$while_cond$2:while(1){var $0=$pw_addr;var $1=HEAP32[(($0)>>2)];var $cmp=((($1))|0)!=0;if(!($cmp)){__label__=17;break $while_cond$2;}
var $2=$pw_addr;var $arrayidx=(($2+-4)&4294967295);var $3=HEAP32[(($arrayidx)>>2)];var $call=_iswspace($3);var $tobool=((($call))|0)!=0;if($tobool){__label__=3;;}else{__label__=16;;}
if(__label__==3){$ix=0;var $4=$pw_addr;var $5=HEAP32[(($4)>>2)];var $6=$ix;var $7=$name_addr;var $arrayidx27=(($7+$6)&4294967295);var $8=HEAP8[($arrayidx27)];var $conv8=(tempInt=(($8)),(tempInt>=128?tempInt-256:tempInt));var $cmp39=((($5))|0)==((($conv8))|0);if($cmp39){__label__=4;;}else{__label__=5;;}
$while_body4$$while_end$7:do{if(__label__==4){while(1){var $9=$pw_addr;var $incdec_ptr=(($9+4)&4294967295);$pw_addr=$incdec_ptr;var $10=$ix;var $inc=((($10)+1)&4294967295);$ix=$inc;var $11=$pw_addr;var $12=HEAP32[(($11)>>2)];var $13=$ix;var $14=$name_addr;var $arrayidx2=(($14+$13)&4294967295);var $15=HEAP8[($arrayidx2)];var $conv=(tempInt=(($15)),(tempInt>=128?tempInt-256:tempInt));var $cmp3=((($12))|0)==((($conv))|0);if($cmp3){__label__=4;continue;}else{__label__=5;break $while_body4$$while_end$7;}}}}while(0);var $16=$ix;var $17=$name_addr;var $arrayidx5=(($17+$16)&4294967295);var $18=HEAP8[($arrayidx5)];var $conv6=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));var $cmp7=((($conv6))|0)==0;if($cmp7){__label__=6;break $while_cond$2;}}
var $39=$pw_addr;var $incdec_ptr29=(($39+4)&4294967295);$pw_addr=$incdec_ptr29;__label__=1;continue $while_cond$2;}
$while_end30$$while_cond9_preheader$12:do{if(__label__==17){$retval=0;;}
else if(__label__==6){var $19=$pw_addr;var $20=HEAP32[(($19)>>2)];var $call104=_iswspace($20);var $tobool115=((($call104))|0)!=0;var $21=$pw_addr;if($tobool115){__lastLabel__=6;__label__=7;;}else{__lastLabel__=6;__label__=8;;}
$while_body12$$while_end14$15:do{if(__label__==7){while(1){var $22=__lastLabel__==7?$25:($21);var $incdec_ptr13=(($22+4)&4294967295);$pw_addr=$incdec_ptr13;var $23=$pw_addr;var $24=HEAP32[(($23)>>2)];var $call10=_iswspace($24);var $tobool11=((($call10))|0)!=0;var $25=$pw_addr;if($tobool11){__lastLabel__=7;__label__=7;continue;}else{__lastLabel__=7;__label__=8;break $while_body12$$while_end14$15;}}}}while(0);var $_lcssa3=__lastLabel__==6?$21:($25);var $26=HEAP32[(($_lcssa3)>>2)];var $cmp15=((($26))|0)==61;if($cmp15){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $27=$pw_addr;var $incdec_ptr17=(($27+4)&4294967295);$pw_addr=$incdec_ptr17;;}
var $28=$pw_addr;var $29=HEAP32[(($28)>>2)];var $call191=_iswspace($29);var $tobool202=((($call191))|0)!=0;var $30=$pw_addr;if($tobool202){__lastLabel__=10;__label__=11;;}else{__lastLabel__=10;__label__=12;;}
$while_body21$$while_end23$22:do{if(__label__==11){while(1){var $31=__lastLabel__==11?$34:($30);var $incdec_ptr22=(($31+4)&4294967295);$pw_addr=$incdec_ptr22;var $32=$pw_addr;var $33=HEAP32[(($32)>>2)];var $call19=_iswspace($33);var $tobool20=((($call19))|0)!=0;var $34=$pw_addr;if($tobool20){__lastLabel__=11;__label__=11;continue;}else{__lastLabel__=11;__label__=12;break $while_body21$$while_end23$22;}}}}while(0);var $_lcssa=__lastLabel__==10?$30:($34);var $35=HEAP32[(($_lcssa)>>2)];var $cmp24=((($35))|0)==34;if($cmp24){__label__=14;;}else{__label__=13;;}
$if_then26$$lor_lhs_false$26:do{if(__label__==13){var $36=$pw_addr;var $37=HEAP32[(($36)>>2)];var $cmp25=((($37))|0)==39;if($cmp25){__label__=14;break $if_then26$$lor_lhs_false$26;}
$retval=((__ZZL16GetSsmlAttributePwPKcE5empty)&4294967295);__label__=18;break $while_end30$$while_cond9_preheader$12;}}while(0);var $38=$pw_addr;var $add_ptr=(($38+4)&4294967295);$retval=$add_ptr;;}}while(0);var $40=$retval;;return $40;return null;}
function __ZL7attrcmpPKwPKc($string1,$string2){;var __label__;var $retval;var $string1_addr;var $string2_addr;var $ix;$string1_addr=$string1;$string2_addr=$string2;var $0=$string1_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){$retval=1;;}
else if(__label__==2){$ix=0;;$for_cond$5:while(1){var $1=$ix;var $2=$string1_addr;var $arrayidx=(($2+4*$1)&4294967295);var $3=HEAP32[(($arrayidx)>>2)];var $4=$ix;var $5=$string2_addr;var $arrayidx1=(($5+$4)&4294967295);var $6=HEAP8[($arrayidx1)];var $conv=(tempInt=(($6)),(tempInt>=128?tempInt-256:tempInt));var $cmp2=((($3))|0)==((($conv))|0);if(!($cmp2)){__label__=6;break $for_cond$5;}
var $7=$ix;var $8=$string1_addr;var $arrayidx3=(($8+4*$7)&4294967295);var $9=HEAP32[(($arrayidx3)>>2)];var $cmp4=((($9))|0)!=0;if(!($cmp4)){__label__=6;break $for_cond$5;}
var $10=$ix;var $inc=((($10)+1)&4294967295);$ix=$inc;__label__=3;continue $for_cond$5;}
var $11=$ix;var $12=$string1_addr;var $arrayidx5=(($12+4*$11)&4294967295);var $13=HEAP32[(($arrayidx5)>>2)];var $cmp6=((($13))|0)==34;if($cmp6){__label__=8;;}else{__label__=7;;}
$land_lhs_true$$lor_lhs_false$10:do{if(__label__==7){var $14=$ix;var $15=$string1_addr;var $arrayidx7=(($15+4*$14)&4294967295);var $16=HEAP32[(($arrayidx7)>>2)];var $cmp8=((($16))|0)==39;if($cmp8){__label__=8;break $land_lhs_true$$lor_lhs_false$10;}else{__label__=10;break $land_lhs_true$$lor_lhs_false$10;}}}while(0);$land_lhs_true$$if_end13$12:do{if(__label__==8){var $17=$ix;var $18=$string2_addr;var $arrayidx9=(($18+$17)&4294967295);var $19=HEAP8[($arrayidx9)];var $conv10=(tempInt=(($19)),(tempInt>=128?tempInt-256:tempInt));var $cmp11=((($conv10))|0)==0;if(!($cmp11)){__label__=10;break $land_lhs_true$$if_end13$12;}
$retval=0;__label__=11;break $if_then$$if_end$2;}}while(0);$retval=1;;}}while(0);var $20=$retval;;return $20;return null;}
function __ZL10attrlookupPKwPK8MNEM_TAB($string1,$mtab){;var __label__;var $retval;var $string1_addr;var $mtab_addr;var $ix;$string1_addr=$string1;$mtab_addr=$mtab;$ix=0;;while(1){var $0=$ix;var $1=$mtab_addr;var $arrayidx=(($1+8*$0)&4294967295);var $mnem=(($arrayidx)&4294967295);var $2=HEAP32[(($mnem)>>2)];var $cmp=((($2))|0)!=0;if(!($cmp)){__label__=5;break;}
var $3=$string1_addr;var $4=$ix;var $5=$mtab_addr;var $arrayidx1=(($5+8*$4)&4294967295);var $mnem2=(($arrayidx1)&4294967295);var $6=HEAP32[(($mnem2)>>2)];var $call=__ZL7attrcmpPKwPKc($3,$6);var $cmp3=((($call))|0)==0;var $7=$ix;if($cmp3){__label__=3;break;}
var $inc=((($7)+1)&4294967295);$ix=$inc;__label__=1;continue;}
if(__label__==5){var $10=$ix;var $11=$mtab_addr;var $arrayidx5=(($11+8*$10)&4294967295);var $value6=(($arrayidx5+4)&4294967295);var $12=HEAP32[(($value6)>>2)];$retval=$12;;}
else if(__label__==3){var $8=$mtab_addr;var $arrayidx4=(($8+8*$7)&4294967295);var $value=(($arrayidx4+4)&4294967295);var $9=HEAP32[(($value)>>2)];$retval=$9;;}
var $13=$retval;;return $13;return null;}
function __ZL17ProcessParamStackPcRi($outbuf,$outix){var __stackBase__=STACKTOP;STACKTOP+=80;_memset(__stackBase__,0,80);var __label__;var $outbuf_addr;var $outix_addr;var $param;var $ix;var $value;var $buf=__stackBase__;var $new_parameters=__stackBase__+20;$outbuf_addr=$outbuf;$outix_addr=$outix;$param=0;;$for_body$2:while(1){var $0=$param;var $arrayidx=(($new_parameters+$0*4)&4294967295);HEAP32[(($arrayidx)>>2)]=-1;var $1=$param;var $inc=((($1)+1)&4294967295);$param=$inc;var $cmp=((($inc))|0)<15;if($cmp){__label__=1;continue $for_body$2;}else{__label__=2;break $for_body$2;}}
$ix=0;var $2=$ix;var $3=HEAP32[((__ZL13n_param_stack)>>2)];var $cmp22=((($2))|0)<((($3))|0);$param=0;if($cmp22){__label__=4;;}else{__label__=3;;}
$for_body6$$for_cond20_preheader$5:do{if(__label__==4){while(1){var $4=$param;var $5=$ix;var $arrayidx7=((_param_stack+$5*64)&4294967295);var $parameter=(($arrayidx7+4)&4294967295);var $arrayidx8=(($parameter+$4*4)&4294967295);var $6=HEAP32[(($arrayidx8)>>2)];var $cmp9=((($6))|0)>=0;if($cmp9){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $7=$param;var $8=$ix;var $arrayidx10=((_param_stack+$8*64)&4294967295);var $parameter11=(($arrayidx10+4)&4294967295);var $arrayidx12=(($parameter11+$7*4)&4294967295);var $9=HEAP32[(($arrayidx12)>>2)];var $10=$param;var $arrayidx13=(($new_parameters+$10*4)&4294967295);HEAP32[(($arrayidx13)>>2)]=$9;;}
var $11=$param;var $inc15=((($11)+1)&4294967295);$param=$inc15;var $cmp5=((($inc15))|0)<15;if($cmp5){__label__=4;continue;}
var $12=$ix;var $inc18=((($12)+1)&4294967295);$ix=$inc18;var $13=$ix;var $14=HEAP32[((__ZL13n_param_stack)>>2)];var $cmp2=((($13))|0)<((($14))|0);$param=0;if($cmp2){__label__=4;continue;}else{__label__=3;break $for_body6$$for_cond20_preheader$5;}}}}while(0);var $arrayidx27=(($buf)&4294967295);var $arraydecay34=(($buf)&4294967295);var $arraydecay36=(($buf)&4294967295);var $arraydecay=(($buf)&4294967295);;while(1){var $15=$param;var $arrayidx23=(($new_parameters+$15*4)&4294967295);var $16=HEAP32[(($arrayidx23)>>2)];$value=$16;var $17=$param;var $arrayidx24=((__ZL17speech_parameters+$17*4)&4294967295);var $18=HEAP32[(($arrayidx24)>>2)];var $cmp25=((($16))|0)!=((($18))|0);if($cmp25){__label__=9;;}else{__label__=14;;}
if(__label__==9){HEAP8[($arrayidx27)]=0;var $19=$param;if($19==5){__label__=10;;}
else if($19==6){__label__=11;;}
else if($19==1){__label__=12;;}
else if($19==2){__label__=12;;}
else if($19==3){__label__=12;;}
else if($19==4){__label__=12;;}
else if($19==12){__label__=12;;}
else{__label__=13;;}
if(__label__==10){var $20=$value;var $sub=((($20)-1)&4294967295);HEAP32[((_option_punctuation)>>2)]=$sub;;}
else if(__label__==11){var $21=$value;HEAP32[((_option_capitals)>>2)]=$21;;}
else if(__label__==12){var $22=$value;var $23=$param;var $arrayidx30=((__ZZL17ProcessParamStackPcRiE10cmd_letter+$23)&4294967295);var $24=HEAP8[($arrayidx30)];var $conv=(tempInt=(($24)),(tempInt>=128?tempInt-256:tempInt));var $call=_sprintf($arraydecay,((__str128)&4294967295),allocate([1,0,0,0,$22,0,0,0,$conv,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STACK));;}
var $25=$param;var $arrayidx31=(($new_parameters+$25*4)&4294967295);var $26=HEAP32[(($arrayidx31)>>2)];var $27=$param;var $arrayidx32=((__ZL17speech_parameters+$27*4)&4294967295);HEAP32[(($arrayidx32)>>2)]=$26;var $28=$outix_addr;var $29=HEAP32[(($28)>>2)];var $30=$outbuf_addr;var $arrayidx33=(($30+$29)&4294967295);var $call35=_strcpy($arrayidx33,$arraydecay34);var $call37=_strlen($arraydecay36);var $31=$outix_addr;var $32=HEAP32[(($31)>>2)];var $add=((($32)+($call37))&4294967295);HEAP32[(($31)>>2)]=$add;;}
var $33=$param;var $inc40=((($33)+1)&4294967295);$param=$inc40;var $cmp21=((($inc40))|0)<15;if($cmp21){__label__=8;continue;}else{__label__=15;break;}}
STACKTOP=__stackBase__;return;return;}
function __ZL19SetProsodyParameteriPwP11PARAM_STACK($param_type,$attr1,$sp){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $param_type_addr;var $attr1_addr;var $sp_addr;var $value=__stackBase__;var $sign;$param_type_addr=$param_type;$attr1_addr=$attr1;$sp_addr=$sp;var $0=$attr1_addr;var $1=$param_type_addr;var $arrayidx=((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_tabs+$1*4)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];var $call=__ZL10attrlookupPKwPK8MNEM_TAB($0,$2);HEAP32[(($value)>>2)]=$call;var $cmp=((($call))|0)>=0;var $3=$param_type_addr;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $arrayidx1=((((_param_stack+4)&4294967295)+$3*4)&4294967295);var $4=HEAP32[(($arrayidx1)>>2)];var $5=HEAP32[(($value)>>2)];var $mul=((($5)*($4))&4294967295);var $div=((((($mul))|0)/100)|0);var $6=$param_type_addr;var $7=$sp_addr;var $parameter=(($7+4)&4294967295);var $arrayidx2=(($parameter+$6*4)&4294967295);HEAP32[(($arrayidx2)>>2)]=$div;;}
else if(__label__==2){var $8=$attr1_addr;var $call3=__ZL18attr_prosody_valueiPKwPi($3,$8,$value);$sign=$call3;var $9=$sign;var $cmp4=((($9))|0)==0;if($cmp4){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $10=HEAP32[(($value)>>2)];var $11=$param_type_addr;var $12=$sp_addr;var $parameter6=(($12+4)&4294967295);var $arrayidx7=(($parameter6+$11*4)&4294967295);HEAP32[(($arrayidx7)>>2)]=$10;;}
else if(__label__==4){var $13=$sign;var $cmp9=((($13))|0)==2;var $14=$param_type_addr;var $arrayidx11=((__ZL17speech_parameters+$14*4)&4294967295);var $15=HEAP32[(($arrayidx11)>>2)];var $16=HEAP32[(($value)>>2)];if($cmp9){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $mul12=((($16)*($15))&4294967295);var $div13=((((($mul12))|0)/100)|0);var $17=$param_type_addr;var $18=$sp_addr;var $parameter14=(($18+4)&4294967295);var $arrayidx15=(($parameter14+$17*4)&4294967295);HEAP32[(($arrayidx15)>>2)]=$div13;;}
else if(__label__==6){var $19=$sign;var $mul18=((($19)*($16))&4294967295);var $add=((($mul18)+($15))&4294967295);var $20=$param_type_addr;var $21=$sp_addr;var $parameter19=(($21+4)&4294967295);var $arrayidx20=(($parameter19+$20*4)&4294967295);HEAP32[(($arrayidx20)>>2)]=$add;;}}}
STACKTOP=__stackBase__;return;return;}
function __ZL13PopParamStackiPcRi($tag_type,$outbuf,$outix){;var __label__;var $tag_type_addr;var $outbuf_addr;var $outix_addr;var $ix;var $top;$tag_type_addr=$tag_type;$outbuf_addr=$outbuf;$outix_addr=$outix;$top=0;var $0=$tag_type_addr;var $cmp=((($0))|0)>=32;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$tag_type_addr;var $sub=((($1)-32)&4294967295);$tag_type_addr=$sub;;}
$ix=0;var $2=$ix;var $3=HEAP32[((__ZL13n_param_stack)>>2)];var $cmp11=((($2))|0)<((($3))|0);if($cmp11){__label__=3;;}else{__label__=6;;}
$for_body$$for_end$5:do{if(__label__==3){while(1){var $4=$ix;var $arrayidx=((_param_stack+$4*64)&4294967295);var $type=(($arrayidx)&4294967295);var $5=HEAP32[(($type)>>2)];var $6=$tag_type_addr;var $cmp2=((($5))|0)==((($6))|0);if($cmp2){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $7=$ix;$top=$7;;}
var $8=$ix;var $inc=((($8)+1)&4294967295);$ix=$inc;var $9=$ix;var $10=HEAP32[((__ZL13n_param_stack)>>2)];var $cmp1=((($9))|0)<((($10))|0);if($cmp1){__label__=3;continue;}else{__label__=6;break $for_body$$for_end$5;}}}}while(0);var $11=$top;var $cmp5=((($11))|0)>0;if($cmp5){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $12=$top;HEAP32[((__ZL13n_param_stack)>>2)]=$12;;}
var $13=$outbuf_addr;var $14=$outix_addr;__ZL17ProcessParamStackPcRi($13,$14);;return;return;}
function __ZL10attrnumberPKwii($pw,$default_value,$type){;var __label__;var $retval;var $pw_addr;var $default_value_addr;var $type_addr;var $value;$pw_addr=$pw;$default_value_addr=$default_value;$type_addr=$type;$value=0;var $0=$pw_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=3;;}else{__label__=1;;}
$if_then$$lor_lhs_false$2:do{if(__label__==1){var $1=$pw_addr;var $2=HEAP32[(($1)>>2)];var $isdigittmp=((($2)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call=((($isdigit))&1);var $tobool=((($call))|0)!=0;if(!($tobool)){__label__=3;break $if_then$$lor_lhs_false$2;}
var $3=$pw_addr;var $4=HEAP32[(($3)>>2)];var $isdigittmp13=((($4)-48)&4294967295);var $isdigit24=((($isdigittmp13))>>>0)<10;if($isdigit24){__label__=4;;}else{__label__=5;;}
$while_body$$while_end$5:do{if(__label__==4){while(1){var $6=$value;var $mul=((($6)*10)&4294967295);var $7=$pw_addr;var $incdec_ptr=(($7+4)&4294967295);$pw_addr=$incdec_ptr;var $8=HEAP32[(($7)>>2)];var $add=((($mul)-48)&4294967295);var $sub=((($add)+($8))&4294967295);$value=$sub;var $9=$pw_addr;var $10=HEAP32[(($9)>>2)];var $isdigittmp1=((($10)-48)&4294967295);var $isdigit2=((($isdigittmp1))>>>0)<10;var $call1=((($isdigit2))&1);var $tobool2=((($call1))|0)!=0;if($tobool2){__label__=4;continue;}else{__label__=5;break $while_body$$while_end$5;}}}}while(0);var $11=$type_addr;var $cmp3=((($11))|0)==1;if($cmp3){__label__=6;;}else{__label__=8;;}
$land_lhs_true$$if_end8$9:do{if(__label__==6){var $12=$pw_addr;var $13=HEAP32[(($12)>>2)];var $call4=_towlower($13);var $cmp5=((($call4))|0)==115;if(!($cmp5)){__label__=8;break $land_lhs_true$$if_end8$9;}
var $14=$value;var $mul7=((($14)*1000)&4294967295);$value=$mul7;;}}while(0);var $15=$value;$retval=$15;__label__=9;break $if_then$$lor_lhs_false$2;}}while(0);if(__label__==3){var $5=$default_value_addr;$retval=$5;;}
var $16=$retval;;return $16;return null;}
function __ZL14ReplaceKeyNamePciRi($outbuf,$index,$outix){var __stackBase__=STACKTOP;STACKTOP+=40;_memset(__stackBase__,0,40);var __label__;var $retval;var $outbuf_addr;var $index_addr;var $outix_addr;var $keynames=__stackBase__;var $ix;var $letter;var $p;$outbuf_addr=$outbuf;$index_addr=$index;$outix_addr=$outix;var $0=$keynames;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=__ZZL14ReplaceKeyNamePciRiE8keynames;$dest$=$0;$stop$=$src$+40;if(($dest$%4)==($src$%4)&&40>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $1=$index_addr;var $2=$outbuf_addr;var $arrayidx=(($2+$1)&4294967295);$p=$arrayidx;var $arraydecay=(($keynames)&4294967295);var $3=$p;var $call=__Z10LookupMnemP8MNEM_TABPKc($arraydecay,$3);$letter=$call;var $cmp=((($call))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $4=$letter;var $5=$p;var $call1=__Z8utf8_outjPc($4,$5);$ix=$call1;var $6=$index_addr;var $7=$ix;var $add=((($7)+($6))&4294967295);var $8=$outix_addr;HEAP32[(($8)>>2)]=$add;var $9=$letter;$retval=$9;;}
else if(__label__==2){$retval=0;;}
STACKTOP=__stackBase__;return;return;}
function __ZL13attrcopy_utf8PcPKwi($buf,$pw,$len){;var __label__;var $buf_addr;var $pw_addr;var $len_addr;var $c;var $ix;var $n;var $prev_c;$buf_addr=$buf;$pw_addr=$pw;$len_addr=$len;$ix=0;$prev_c=0;var $0=$pw_addr;var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=6;;}
$while_cond$$if_end6$2:do{if(__label__==1){while(1){var $1=$ix;var $2=$len_addr;var $sub=((($2)-4)&4294967295);var $cmp1=((($1))|0)<((($sub))|0);if(!($cmp1)){__label__=6;break $while_cond$$if_end6$2;}
var $3=$pw_addr;var $incdec_ptr=(($3+4)&4294967295);$pw_addr=$incdec_ptr;var $4=HEAP32[(($3)>>2)];$c=$4;var $cmp2=((($4))|0)!=0;if(!($cmp2)){__label__=6;break $while_cond$$if_end6$2;}
var $5=$c;var $cmp3=((($5))|0)==34;if($cmp3){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $6=$prev_c;var $cmp4=((($6))|0)!=92;if($cmp4){__label__=6;break $while_cond$$if_end6$2;}}
var $7=$c;var $8=$ix;var $9=$buf_addr;var $arrayidx=(($9+$8)&4294967295);var $call=__Z8utf8_outjPc($7,$arrayidx);$n=$call;var $10=$n;var $11=$ix;var $add=((($11)+($10))&4294967295);$ix=$add;var $12=$c;$prev_c=$12;__label__=1;continue;}}}while(0);var $13=$ix;var $14=$buf_addr;var $arrayidx7=(($14+$13)&4294967295);HEAP8[($arrayidx7)]=0;var $15=$ix;;return $15;return null;}
function __ZL14LoadSoundFile2PKc($fname){;var __label__;var $retval;var $fname_addr;var $ix;$fname_addr=$fname;$ix=0;;while(1){var $0=$ix;var $1=HEAP32[((_n_soundicon_tab)>>2)];var $cmp=((($0))|0)<((($1))|0);if(!($cmp)){__label__=6;break;}
var $2=$ix;var $arrayidx=((_soundicon_tab+$2*16)&4294967295);var $filename=(($arrayidx+12)&4294967295);var $3=HEAP32[(($filename)>>2)];var $cmp1=((($3))|0)!=0;if($cmp1){__label__=3;;}else{__label__=5;;}
if(__label__==3){var $4=$fname_addr;var $5=$ix;var $arrayidx2=((_soundicon_tab+$5*16)&4294967295);var $filename3=(($arrayidx2+12)&4294967295);var $6=HEAP32[(($filename3)>>2)];var $call=_strcmp($4,$6);var $cmp4=((($call))|0)==0;if($cmp4){__label__=4;break;}}
var $8=$ix;var $inc=((($8)+1)&4294967295);$ix=$inc;__label__=1;continue;}
if(__label__==6){var $9=HEAP32[((__ZZL14LoadSoundFile2PKcE4slot)>>2)];var $inc5=((($9)+1)&4294967295);HEAP32[((__ZZL14LoadSoundFile2PKcE4slot)>>2)]=$inc5;var $10=HEAP32[((__ZZL14LoadSoundFile2PKcE4slot)>>2)];var $cmp6=((($10))|0)>=4;if($cmp6){__label__=7;;}else{__label__=8;;}
if(__label__==7){HEAP32[((__ZZL14LoadSoundFile2PKcE4slot)>>2)]=0;;}
var $11=$fname_addr;var $12=HEAP32[((__ZZL14LoadSoundFile2PKcE4slot)>>2)];var $call9=__ZL13LoadSoundFilePKci($11,$12);var $cmp10=((($call9))|0)!=0;if($cmp10){__label__=9;;}else{__label__=10;;}
if(__label__==9){$retval=-1;;}
else if(__label__==10){var $13=$ix;var $arrayidx13=((_soundicon_tab+$13*16)&4294967295);var $filename14=(($arrayidx13+12)&4294967295);var $14=HEAP32[(($filename14)>>2)];var $15=$fname_addr;var $call15=_strlen($15);var $add=((($call15)+1)&4294967295);var $call16=_realloc($14,$add);var $16=HEAP32[((__ZZL14LoadSoundFile2PKcE4slot)>>2)];var $arrayidx17=((_soundicon_tab+$16*16)&4294967295);var $filename18=(($arrayidx17+12)&4294967295);HEAP32[(($filename18)>>2)]=$call16;var $17=HEAP32[((__ZZL14LoadSoundFile2PKcE4slot)>>2)];var $arrayidx19=((_soundicon_tab+$17*16)&4294967295);var $filename20=(($arrayidx19+12)&4294967295);var $18=HEAP32[(($filename20)>>2)];var $19=$fname_addr;var $call21=_strcpy($18,$19);var $20=HEAP32[((__ZZL14LoadSoundFile2PKcE4slot)>>2)];$retval=$20;;}}
else if(__label__==4){var $7=$ix;$retval=$7;;}
var $21=$retval;;return $21;return null;}
function __ZL18GetVoiceAttributesPwi($pw,$tag_type){;var __label__;var $retval;var $pw_addr;var $tag_type_addr;var $lang;var $gender;var $name;var $age;var $variant;var $new_voice_id;var $ssml_sp;$pw_addr=$pw;$tag_type_addr=$tag_type;var $0=$tag_type_addr;var $and=($0)&32;var $tobool=((($and))|0)!=0;if($tobool){__label__=1;;}else{__label__=3;;}
$if_then$$if_else$2:do{if(__label__==1){var $1=HEAP32[((__ZL12n_ssml_stack)>>2)];var $cmp=((($1))|0)>1;if(!($cmp)){__label__=10;break $if_then$$if_else$2;}
var $2=HEAP32[((__ZL12n_ssml_stack)>>2)];var $dec=((($2)-1)&4294967295);HEAP32[((__ZL12n_ssml_stack)>>2)]=$dec;__label__=10;break $if_then$$if_else$2;}
else if(__label__==3){var $3=$pw_addr;var $call=__ZL16GetSsmlAttributePwPKc($3,((__str106273)&4294967295));$lang=$call;var $4=$tag_type_addr;var $cmp2=((($4))|0)!=2;if($cmp2){__label__=4;;}else{__label__=5;;}
if(__label__==4){$name=0;$variant=0;$age=0;$gender=0;;}
else if(__label__==5){var $5=$pw_addr;var $call5=__ZL16GetSsmlAttributePwPKc($5,((__str5655)&4294967295));$name=$call5;var $6=$pw_addr;var $call6=__ZL16GetSsmlAttributePwPKc($6,((__str55707)&4294967295));$variant=$call6;var $7=$pw_addr;var $call7=__ZL16GetSsmlAttributePwPKc($7,((__str108275)&4294967295));$age=$call7;var $8=$pw_addr;var $call8=__ZL16GetSsmlAttributePwPKc($8,((__str7657)&4294967295));$gender=$call8;;}
var $9=$tag_type_addr;var $cmp10=((($9))|0)!=2;if($cmp10){__label__=7;;}else{__label__=9;;}
$land_lhs_true$$if_end13$10:do{if(__label__==7){var $10=$lang;var $cmp11=((($10))|0)==0;if(!($cmp11)){__label__=9;break $land_lhs_true$$if_end13$10;}
$retval=0;__label__=13;break $if_then$$if_else$2;}}while(0);var $11=HEAP32[((__ZL12n_ssml_stack)>>2)];var $inc=((($11)+1)&4294967295);HEAP32[((__ZL12n_ssml_stack)>>2)]=$inc;var $arrayidx=((__ZL10ssml_stack+$11*76)&4294967295);$ssml_sp=$arrayidx;var $12=$ssml_sp;var $language=(($12+56)&4294967295);var $arraydecay=(($language)&4294967295);var $13=$lang;var $call14=__ZL13attrcopy_utf8PcPKwi($arraydecay,$13,20);var $14=$ssml_sp;var $voice_name=(($14+16)&4294967295);var $arraydecay15=(($voice_name)&4294967295);var $15=$name;var $call16=__ZL13attrcopy_utf8PcPKwi($arraydecay15,$15,40);var $16=$variant;var $call17=__ZL10attrnumberPKwii($16,1,0);var $sub=((($call17)-1)&4294967295);var $17=$ssml_sp;var $voice_variant=(($17+4)&4294967295);HEAP32[(($voice_variant)>>2)]=$sub;var $18=$age;var $call18=__ZL10attrnumberPKwii($18,0,0);var $19=$ssml_sp;var $voice_age=(($19+12)&4294967295);HEAP32[(($voice_age)>>2)]=$call18;var $20=$gender;var $call19=__ZL10attrlookupPKwPK8MNEM_TAB($20,((__ZZL18GetVoiceAttributesPwiE11mnem_gender)&4294967295));var $21=$ssml_sp;var $voice_gender=(($21+8)&4294967295);HEAP32[(($voice_gender)>>2)]=$call19;var $22=$tag_type_addr;var $23=$ssml_sp;var $tag_type20=(($23)&4294967295);HEAP32[(($tag_type20)>>2)]=$22;__label__=10;break $if_then$$if_else$2;}}while(0);if(__label__==10){var $call22=__ZL14VoiceFromStackv();$new_voice_id=$call22;var $24=$new_voice_id;var $call23=_strcmp($24,((__ZL16current_voice_id)&4294967295));var $cmp24=((($call23))|0)!=0;if($cmp24){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $25=$new_voice_id;var $call26=_strcpy(((__ZL16current_voice_id)&4294967295),$25);$retval=131072;;}
else if(__label__==12){$retval=0;;}}
var $26=$retval;;return $26;return null;}
function __ZL14VoiceFromStackv(){var __stackBase__=STACKTOP;STACKTOP+=108;_memset(__stackBase__,0,108);var __label__;var $retval;var $ix;var $sp;var $v_id;var $voice_name_specified;var $voice_found=__stackBase__;var $voice_select=__stackBase__+4;var $voice_name=__stackBase__+28;var $language=__stackBase__+68;var $arraydecay=(($voice_name)&4294967295);var $call=_strcpy($arraydecay,((__ZL10ssml_stack+16)&4294967295));var $arraydecay1=(($language)&4294967295);var $call2=_strcpy($arraydecay1,((__ZL10ssml_stack+56)&4294967295));var $0=HEAP32[((((__ZL10ssml_stack+12)&4294967295))>>2)];var $conv=((($0))&255);var $age=(($voice_select+13)&4294967295);HEAP8[($age)]=$conv;var $1=HEAP32[((((__ZL10ssml_stack+8)&4294967295))>>2)];var $conv3=((($1))&255);var $gender=(($voice_select+12)&4294967295);HEAP8[($gender)]=$conv3;var $2=HEAP32[((((__ZL10ssml_stack+4)&4294967295))>>2)];var $conv4=((($2))&255);var $variant=(($voice_select+14)&4294967295);HEAP8[($variant)]=$conv4;var $identifier=(($voice_select+8)&4294967295);HEAP32[(($identifier)>>2)]=0;$ix=0;var $3=$ix;var $4=HEAP32[((__ZL12n_ssml_stack)>>2)];var $cmp1=((($3))|0)<((($4))|0);if($cmp1){__label__=1;;}else{__label__=15;;}
$for_body_lr_ph$$for_end$2:do{if(__label__==1){var $arraydecay13=(($voice_name)&4294967295);var $arrayidx17=(($language)&4294967295);var $gender18=(($voice_select+12)&4294967295);var $age19=(($voice_select+13)&4294967295);var $variant20=(($voice_select+14)&4294967295);var $arraydecay26=(($language)&4294967295);var $arrayidx32=(($voice_name)&4294967295);var $gender39=(($voice_select+12)&4294967295);var $age45=(($voice_select+13)&4294967295);var $variant51=(($voice_select+14)&4294967295);;$for_body$4:while(1){var $5=$ix;var $arrayidx=((__ZL10ssml_stack+$5*76)&4294967295);$sp=$arrayidx;$voice_name_specified=0;var $6=$sp;var $voice_name5=(($6+16)&4294967295);var $arrayidx6=(($voice_name5)&4294967295);var $7=HEAP8[($arrayidx6)];var $conv7=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $cmp8=((($conv7))|0)!=0;if($cmp8){__label__=3;;}else{__label__=5;;}
$land_lhs_true$$if_end$6:do{if(__label__==3){var $8=$sp;var $voice_name9=(($8+16)&4294967295);var $arraydecay10=(($voice_name9)&4294967295);var $call11=__Z17SelectVoiceByNamePP12espeak_VOICEPKc(0,$arraydecay10);var $cmp12=((($call11))|0)!=0;if(!($cmp12)){__label__=5;break $land_lhs_true$$if_end$6;}
$voice_name_specified=1;var $9=$sp;var $voice_name14=(($9+16)&4294967295);var $arraydecay15=(($voice_name14)&4294967295);var $call16=_strcpy($arraydecay13,$arraydecay15);HEAP8[($arrayidx17)]=0;HEAP8[($gender18)]=0;HEAP8[($age19)]=0;HEAP8[($variant20)]=0;;}}while(0);var $10=$sp;var $language21=(($10+56)&4294967295);var $arrayidx22=(($language21)&4294967295);var $11=HEAP8[($arrayidx22)];var $conv23=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $cmp24=((($conv23))|0)!=0;if($cmp24){__label__=6;;}else{__label__=8;;}
$if_then25$$if_end34$10:do{if(__label__==6){var $12=$sp;var $language27=(($12+56)&4294967295);var $arraydecay28=(($language27)&4294967295);var $call29=_strcpy($arraydecay26,$arraydecay28);var $13=$voice_name_specified;var $cmp30=((($13))|0)==0;if(!($cmp30)){__label__=8;break $if_then25$$if_end34$10;}
HEAP8[($arrayidx32)]=0;;}}while(0);var $14=$sp;var $voice_gender=(($14+8)&4294967295);var $15=HEAP32[(($voice_gender)>>2)];var $cmp35=((($15))|0)!=0;if($cmp35){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $16=$sp;var $voice_gender37=(($16+8)&4294967295);var $17=HEAP32[(($voice_gender37)>>2)];var $conv38=((($17))&255);HEAP8[($gender39)]=$conv38;;}
var $18=$sp;var $voice_age=(($18+12)&4294967295);var $19=HEAP32[(($voice_age)>>2)];var $cmp41=((($19))|0)!=0;if($cmp41){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $20=$sp;var $voice_age43=(($20+12)&4294967295);var $21=HEAP32[(($voice_age43)>>2)];var $conv44=((($21))&255);HEAP8[($age45)]=$conv44;;}
var $22=$sp;var $voice_variant=(($22+4)&4294967295);var $23=HEAP32[(($voice_variant)>>2)];var $cmp47=((($23))|0)!=0;if($cmp47){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $24=$sp;var $voice_variant49=(($24+4)&4294967295);var $25=HEAP32[(($voice_variant49)>>2)];var $conv50=((($25))&255);HEAP8[($variant51)]=$conv50;;}
var $26=$ix;var $inc=((($26)+1)&4294967295);$ix=$inc;var $27=$ix;var $28=HEAP32[((__ZL12n_ssml_stack)>>2)];var $cmp=((($27))|0)<((($28))|0);if($cmp){__label__=2;continue $for_body$4;}else{__label__=15;break $for_body_lr_ph$$for_end$2;}}}}while(0);var $arraydecay53=(($voice_name)&4294967295);var $name=(($voice_select)&4294967295);HEAP32[(($name)>>2)]=$arraydecay53;var $arraydecay54=(($language)&4294967295);var $languages=(($voice_select+4)&4294967295);HEAP32[(($languages)>>2)]=$arraydecay54;var $call55=__Z11SelectVoiceP12espeak_VOICEPi($voice_select,$voice_found);$v_id=$call55;var $cmp56=((($call55))|0)==0;if($cmp56){__label__=16;;}else{__label__=17;;}
if(__label__==16){$retval=((__str45697)&4294967295);;}
else if(__label__==17){var $29=$v_id;$retval=$29;;}
var $30=$retval;STACKTOP=__stackBase__;return $30;return null;}
function __ZL18attr_prosody_valueiPKwPi($param_type,$pw,$value_out){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var __lastLabel__=null;var $retval;var $param_type_addr;var $pw_addr;var $value_out_addr;var $sign;var $tail=__stackBase__;var $value;var $x;$param_type_addr=$param_type;$pw_addr=$pw;$value_out_addr=$value_out;$sign=0;var $0=$pw_addr;var $1=HEAP32[(($0)>>2)];var $call1=_iswspace($1);var $tobool2=((($call1))|0)!=0;var $2=$pw_addr;if($tobool2){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=2;;}
$while_body$$while_end$2:do{if(__label__==1){while(1){var $3=__lastLabel__==1?$6:($2);var $incdec_ptr=(($3+4)&4294967295);$pw_addr=$incdec_ptr;var $4=$pw_addr;var $5=HEAP32[(($4)>>2)];var $call=_iswspace($5);var $tobool=((($call))|0)!=0;var $6=$pw_addr;if($tobool){__lastLabel__=1;__label__=1;continue;}else{__lastLabel__=1;__label__=2;break $while_body$$while_end$2;}}}}while(0);var $_lcssa=__lastLabel__==0?$2:($6);var $7=HEAP32[(($_lcssa)>>2)];var $cmp=((($7))|0)==43;if($cmp){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $8=$pw_addr;var $incdec_ptr1=(($8+4)&4294967295);$pw_addr=$incdec_ptr1;$sign=1;;}
var $9=$pw_addr;var $10=HEAP32[(($9)>>2)];var $cmp2=((($10))|0)==45;if($cmp2){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $11=$pw_addr;var $incdec_ptr4=(($11+4)&4294967295);$pw_addr=$incdec_ptr4;$sign=-1;;}
var $12=$pw_addr;var $call6=_wcstod($12,$tail);var $conv=($call6);$value=$conv;var $13=HEAP32[(($tail)>>2)];var $14=$pw_addr;var $cmp7=((($13))|0)==((($14))|0);if($cmp7){__label__=7;;}else{__label__=8;;}
$if_then8$$if_end9$12:do{if(__label__==7){var $15=$value_out_addr;HEAP32[(($15)>>2)]=100;$retval=2;;}
else if(__label__==8){var $16=HEAP32[(($tail)>>2)];var $17=HEAP32[(($16)>>2)];var $cmp10=((($17))|0)==37;if($cmp10){__label__=9;;}else{__label__=12;;}
if(__label__==9){var $18=$sign;var $cmp12=((($18))|0)!=0;if($cmp12){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $19=$sign;var $conv14=((($19))|0);var $20=$value;var $mul=($conv14)*($20);var $add=100+($mul);$value=$add;;}
var $21=$value;var $conv16=((($21))|0);var $22=$value_out_addr;HEAP32[(($22)>>2)]=$conv16;$retval=2;;}
else if(__label__==12){var $23=HEAP32[(($tail)>>2)];var $arrayidx=(($23)&4294967295);var $24=HEAP32[(($arrayidx)>>2)];var $cmp18=((($24))|0)==115;if($cmp18){__label__=13;;}else{__label__=15;;}
$land_lhs_true$$if_end26$21:do{if(__label__==13){var $25=HEAP32[(($tail)>>2)];var $arrayidx19=(($25+4)&4294967295);var $26=HEAP32[(($arrayidx19)>>2)];var $cmp20=((($26))|0)==116;if(!($cmp20)){__label__=15;break $land_lhs_true$$if_end26$21;}
var $27=$value;var $28=$sign;var $conv22=((($28))|0);var $mul23=($27)*($conv22);var $div=($mul23)/12;var $exp2=_exp2($div);var $mul24=($exp2)*100;$x=$mul24;var $29=$x;var $conv25=((($29))|0);var $30=$value_out_addr;HEAP32[(($30)>>2)]=$conv25;$retval=2;__label__=21;break $if_then8$$if_end9$12;}}while(0);var $31=$param_type_addr;var $cmp27=((($31))|0)==1;if($cmp27){__label__=16;;}else{__label__=20;;}
if(__label__==16){var $32=$sign;var $cmp29=((($32))|0)==0;if($cmp29){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $33=$value;var $mul31=($33)*100;var $conv32=((($mul31))|0);var $34=$value_out_addr;HEAP32[(($34)>>2)]=$conv32;;}
else if(__label__==18){var $35=$sign;var $conv33=((($35))|0);var $36=$value;var $mul34=($conv33)*($36);var $mul35=($mul34)*100;var $conv36=((($mul35))|0);var $add37=((($conv36)+100)&4294967295);var $37=$value_out_addr;HEAP32[(($37)>>2)]=$add37;;}
$retval=2;;}
else if(__label__==20){var $38=$value;var $conv40=((($38))|0);var $39=$value_out_addr;HEAP32[(($39)>>2)]=$conv40;var $40=$sign;$retval=$40;;}}}}while(0);var $41=$retval;STACKTOP=__stackBase__;return $41;return null;}
function __ZL8GetC_getv(){;var __label__;var $retval;var $c;var $c2;var $0=HEAP32[((__ZL7f_input)>>2)];var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=8;;}
$if_then$$if_end13$2:do{if(__label__==1){var $1=HEAP32[((__ZL7f_input)>>2)];var $call=_fgetc($1);$c=$call;var $2=HEAP32[((__ZL7f_input)>>2)];var $_flags=(($2+12)&4294967295);var $3=HEAP16[(($_flags)>>1)];var $conv=(tempInt=(($3)),(tempInt>=32768?tempInt-65536:tempInt));var $and=($conv)&32;var $cmp1=((($and))|0)!=0;if($cmp1){__label__=2;;}else{__label__=3;;}
if(__label__==2){$c=32;;}
var $4=HEAP32[((_option_multibyte)>>2)];var $cmp3=((($4))|0)==4;if($cmp3){__label__=4;;}else{__label__=7;;}
if(__label__==4){var $5=HEAP32[((__ZL7f_input)>>2)];var $call5=_fgetc($5);$c2=$call5;var $6=HEAP32[((__ZL7f_input)>>2)];var $_flags6=(($6+12)&4294967295);var $7=HEAP16[(($_flags6)>>1)];var $conv7=(tempInt=(($7)),(tempInt>=32768?tempInt-65536:tempInt));var $and8=($conv7)&32;var $cmp9=((($and8))|0)!=0;if($cmp9){__label__=5;;}else{__label__=6;;}
if(__label__==5){$c2=0;;}
var $8=$c;var $9=$c2;var $shl=((($9)*256)&4294967295);var $add=((($shl)+($8))&4294967295);$c=$add;;}
var $10=$c;$retval=$10;;}
else if(__label__==8){var $11=HEAP32[((_option_multibyte)>>2)];var $cmp14=((($11))|0)==3;if($cmp14){__label__=9;;}else{__label__=13;;}
$if_then15$$if_else$14:do{if(__label__==9){var $12=HEAP32[((_p_wchar_input)>>2)];var $13=HEAP32[(($12)>>2)];var $cmp16=((($13))|0)==0;if($cmp16){__label__=10;;}else{__label__=11;;}
if(__label__==10){HEAP8[(__ZL12end_of_input_b)]=1;$retval=0;__label__=20;break $if_then$$if_end13$2;}
else if(__label__==11){var $_b1=HEAPU8[(__ZL12end_of_input_b)];var $14=((($_b1))&1);var $tobool=((($14))|0)!=0;if($tobool){__label__=19;break $if_then15$$if_else$14;}
var $15=HEAP32[((_p_wchar_input)>>2)];var $incdec_ptr=(($15+4)&4294967295);HEAP32[((_p_wchar_input)>>2)]=$incdec_ptr;var $16=HEAP32[(($15)>>2)];$retval=$16;__label__=20;break $if_then$$if_end13$2;}}
else if(__label__==13){var $17=HEAP32[((_p_textinput)>>2)];var $18=HEAPU8[($17)];var $conv21=((($18))&255);var $cmp22=((($conv21))|0)==0;if($cmp22){__label__=14;;}else{__label__=15;;}
if(__label__==14){HEAP8[(__ZL12end_of_input_b)]=1;$retval=0;__label__=20;break $if_then$$if_end13$2;}
else if(__label__==15){var $_b=HEAPU8[(__ZL12end_of_input_b)];var $19=((($_b))&1);var $tobool25=((($19))|0)!=0;if($tobool25){__label__=19;break $if_then15$$if_else$14;}
var $20=HEAP32[((_option_multibyte)>>2)];var $cmp27=((($20))|0)==4;var $21=HEAPU32[((_p_textinput)>>2)];if($cmp27){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $arrayidx=(($21)&4294967295);var $22=HEAPU8[($arrayidx)];var $conv29=((($22))&255);var $23=HEAP32[((_p_textinput)>>2)];var $arrayidx30=(($23+1)&4294967295);var $24=HEAPU8[($arrayidx30)];var $conv31=((($24))&255);var $shl32=((($conv31)*256)&4294967295);var $add33=((($shl32)+($conv29))&4294967295);$c=$add33;var $25=HEAP32[((_p_textinput)>>2)];var $add_ptr=(($25+2)&4294967295);HEAP32[((_p_textinput)>>2)]=$add_ptr;var $26=$c;$retval=$26;__label__=20;break $if_then$$if_end13$2;}
else if(__label__==18){var $incdec_ptr35=(($21+1)&4294967295);HEAP32[((_p_textinput)>>2)]=$incdec_ptr35;var $27=HEAPU8[($21)];var $conv36=((($27))&255);var $and37=($conv36)&255;$retval=$and37;__label__=20;break $if_then$$if_end13$2;}}}}while(0);$retval=0;;}}while(0);var $28=$retval;;return $28;return null;}
function __ZL10GetC_ungeti($c){;var __label__;var $c_addr;$c_addr=$c;var $0=HEAP32[((__ZL7f_input)>>2)];var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$c_addr;var $2=HEAP32[((__ZL7f_input)>>2)];var $call=_ungetc($1,$2);;}
else if(__label__==2){var $3=HEAP32[((_p_textinput)>>2)];var $incdec_ptr=(($3+-1)&4294967295);HEAP32[((_p_textinput)>>2)]=$incdec_ptr;var $4=$c_addr;var $conv=((($4))&255);var $5=HEAP32[((_p_textinput)>>2)];HEAP8[($5)]=$conv;HEAP8[(__ZL12end_of_input_b)]=0;;};return;return;}
function __Z8SetSpeedi($control){;var __label__;var __lastLabel__=null;var $control_addr;var $x;var $s1;var $wpm;var $wpm2;var $wpm_value;var $sonic;$control_addr=$control;HEAP32[((((_speed+28)&4294967295))>>2)]=0;HEAP32[((((_speed+24)&4294967295))>>2)]=450;HEAP32[((((_speed+16)&4294967295))>>2)]=110;HEAP32[((((_speed+20)&4294967295))>>2)]=100;HEAP32[((((_speed+8)&4294967295))>>2)]=5;var $0=HEAP32[((((_embedded_value+8)&4294967295))>>2)];$wpm=$0;var $1=$control_addr;var $cmp=((($1))|0)==2;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=HEAP32[((((_embedded_value+32)&4294967295))>>2)];$wpm=$2;;}
var $3=$wpm;$wpm_value=$3;var $4=HEAP32[((_voice)>>2)];var $speed_percent=(($4+64)&4294967295);var $5=HEAP32[(($speed_percent)>>2)];var $cmp1=((($5))|0)>0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $6=$wpm;var $7=HEAP32[((_voice)>>2)];var $speed_percent3=(($7+64)&4294967295);var $8=HEAP32[(($speed_percent3)>>2)];var $mul=((($8)*($6))&4294967295);var $div=((((($mul))|0)/100)|0);$wpm=$div;;}
var $9=$control_addr;var $and=($9)&2;var $tobool=((($and))|0)!=0;if($tobool){__label__=5;;}else{__label__=6;;}
if(__label__==5){__Z12DoSonicSpeedi(1024);;}
var $10=$wpm_value;var $cmp7=((($10))|0)>450;if($cmp7){__label__=10;;}else{__label__=7;;}
$if_then10$$lor_lhs_false$11:do{if(__label__==7){var $11=$wpm_value;var $12=HEAP32[((((_speed+32)&4294967295))>>2)];var $cmp8=((($11))|0)>((($12))|0);var $13=$wpm;if($cmp8){__label__=8;;}else{__label__=14;;}
$land_lhs_true$$if_end29$13:do{if(__label__==8){var $cmp9=((($13))|0)>350;if($cmp9){__label__=10;break $if_then10$$lor_lhs_false$11;}
var $_pr2=$wpm;__lastLabel__=9;__label__=16;break $land_lhs_true$$if_end29$13;}
else if(__label__==14){var $cmp30=((($13))|0)>450;if($cmp30){__lastLabel__=14;;}else{__lastLabel__=14;__label__=16;break $land_lhs_true$$if_end29$13;}
$wpm=450;__label__=17;break $land_lhs_true$$if_end29$13;}}while(0);$if_end32$$if_then34$18:do{if(__label__==16){var $29=__lastLabel__==9?$_pr2:($13);var $cmp33=((($29))|0)>360;if($cmp33){__label__=17;break $if_end32$$if_then34$18;}else{__label__=18;break $if_end32$$if_then34$18;}}}while(0);if(__label__==17){var $30=$wpm;var $sub=((($30)-360)&4294967295);var $div35=((((($sub))|0)/8)|0);HEAP32[((((_speed+28)&4294967295))>>2)]=$div35;;}
var $31=$wpm;$wpm2=$31;var $cmp37=((($31))|0)>359;if($cmp37){__lastLabel__=18;__label__=19;;}else{__lastLabel__=18;__label__=20;;}
if(__label__==19){$wpm2=359;var $_pr4=$wpm;__lastLabel__=19;;}
var $32=__lastLabel__==19?$_pr4:($31);var $cmp40=((($32))|0)<80;if($cmp40){__label__=21;;}else{__label__=22;;}
if(__label__==21){$wpm2=80;;}
var $33=$wpm2;var $sub43=((($33)-80)&4294967295);var $arrayidx=((__ZL12speed_lookup+$sub43)&4294967295);var $34=HEAPU8[($arrayidx)];var $conv44=((($34))&255);$x=$conv44;var $35=$wpm;var $cmp45=((($35))|0)>=380;if($cmp45){__label__=23;;}else{__label__=25;;}
$if_end47$$if_end50$29:do{if(__label__==23){$x=7;var $_pr5=$wpm;var $cmp48=((($_pr5))|0)>=400;if(!($cmp48)){__label__=25;break $if_end47$$if_end50$29;}
$x=6;;}}while(0);var $36=$control_addr;var $and51=($36)&1;var $tobool52=((($and51))|0)!=0;if($tobool52){__label__=26;;}else{__label__=28;;}
$if_then53$$if_end67$33:do{if(__label__==26){var $37=$x;var $38=HEAP32[((_voice)>>2)];var $speedf154=(($38+52)&4294967295);var $39=HEAP32[(($speedf154)>>2)];var $mul55=((($39)*($37))&4294967295);var $div56=((((($mul55))|0)/256)|0);HEAP32[((__ZL6speed1)>>2)]=$div56;var $40=$x;var $41=HEAP32[((_voice)>>2)];var $speedf257=(($41+56)&4294967295);var $42=HEAP32[(($speedf257)>>2)];var $mul58=((($42)*($40))&4294967295);var $div59=((((($mul58))|0)/256)|0);HEAP32[((__ZL6speed2)>>2)]=$div59;var $43=$x;var $44=HEAP32[((_voice)>>2)];var $speedf360=(($44+60)&4294967295);var $45=HEAP32[(($speedf360)>>2)];var $mul61=((($45)*($43))&4294967295);var $div62=((((($mul61))|0)/256)|0);HEAP32[((__ZL6speed3)>>2)]=$div62;var $46=$x;var $cmp63=((($46))|0)<=7;if(!($cmp63)){__label__=28;break $if_then53$$if_end67$33;}
var $47=$x;HEAP32[((__ZL6speed1)>>2)]=$47;var $48=$x;var $sub65=((($48)-1)&4294967295);HEAP32[((__ZL6speed3)>>2)]=$sub65;HEAP32[((__ZL6speed2)>>2)]=$sub65;;}}while(0);var $49=$control_addr;var $and68=($49)&2;var $tobool69=((($and68))|0)!=0;if(!($tobool69)){__label__=51;break $if_then10$$lor_lhs_false$11;}
var $50=$wpm;var $cmp71=((($50))|0)>350;var $51=$wpm;if($cmp71){__label__=30;;}else{__label__=31;;}
$if_then72$$if_else$38:do{if(__label__==30){var $sub73=((($51)-350)&4294967295);var $div74=((((($sub73))|0)/3)|0);var $sub75=((85-($div74))&4294967295);HEAP32[((((_speed+16)&4294967295))>>2)]=$sub75;var $52=$wpm;var $sub76=((($52)-350)&4294967295);var $div77=((((($sub76))|0)/8)|0);var $sub78=((60-($div77))&4294967295);HEAP32[((((_speed+20)&4294967295))>>2)]=$sub78;;}
else if(__label__==31){var $cmp79=((($51))|0)>250;if(!($cmp79)){__label__=33;break $if_then72$$if_else$38;}
var $53=$wpm;var $sub81=((($53)-250)&4294967295);var $div82=((((($sub81))|0)/4)|0);var $sub83=((110-($div82))&4294967295);HEAP32[((((_speed+16)&4294967295))>>2)]=$sub83;var $54=$wpm;var $sub84=((($54)-250)&4294967295);var $div85=((((($sub84))|0)/2)|0);var $sub86=((110-($div85))&4294967295);HEAP32[((((_speed+20)&4294967295))>>2)]=$sub86;;}}while(0);var $55=$x;var $56=HEAP32[((_voice)>>2)];var $speedf189=(($56+52)&4294967295);var $57=HEAP32[(($speedf189)>>2)];var $mul90=((($57)*($55))&4294967295);var $div91=((((($mul90))|0)/256)|0);$s1=$div91;var $58=$wpm;var $cmp92=((($58))|0)>=170;var $59=$s1;if($cmp92){__label__=34;;}else{__label__=35;;}
if(__label__==34){var $mul94=((($59)*150)&4294967295);var $div95=((((($mul94))|0)/128)|0);var $add=((($div95)+110)&4294967295);HEAP32[((((_speed+12)&4294967295))>>2)]=$add;;}
else if(__label__==35){var $mul97=((($59)*128)&4294967295);var $div98=((((($mul97))|0)/130)|0);var $add99=((($div98)+128)&4294967295);HEAP32[((((_speed+12)&4294967295))>>2)]=$add99;;}
var $60=$wpm;var $cmp101=((($60))|0)>=350;if($cmp101){__label__=37;;}else{__label__=40;;}
$if_end106$$if_end117$47:do{if(__label__==37){var $61=$wpm;var $sub103=((($61)-350)&4294967295);var $arrayidx104=((__ZL14wav_factor_350+$sub103)&4294967295);var $62=HEAPU8[($arrayidx104)];var $conv105=((($62))&255);HEAP32[((((_speed+12)&4294967295))>>2)]=$conv105;var $_pr7=$wpm;var $cmp107=((($_pr7))|0)>=390;if(!($cmp107)){__label__=40;break $if_end106$$if_end117$47;}
var $63=$wpm;var $sub109=((($63)-400)&4294967295);var $div110=((((($sub109))|0)/2)|0);var $sub111=((450-($div110))&4294967295);HEAP32[((((_speed+24)&4294967295))>>2)]=$sub111;var $64=$wpm;var $cmp112=((($64))|0)>440;if(!($cmp112)){__label__=40;break $if_end106$$if_end117$47;}
var $65=$wpm;var $_neg=(((-($65)))&4294967295);var $sub115=((($_neg)+860)&4294967295);HEAP32[((((_speed+24)&4294967295))>>2)]=$sub115;;}}while(0);var $66=$s1;var $mul118=((($66)*256)&4294967295);var $div119=((((($mul118))|0)/115)|0);HEAP32[((((_speed)&4294967295))>>2)]=$div119;HEAP32[((((_speed+4)&4294967295))>>2)]=0;var $67=$wpm;var $cmp120=((($67))|0)>430;if($cmp120){__label__=41;;}else{__label__=42;;}
$if_then121$$if_else122$52:do{if(__label__==41){HEAP32[((((_speed)&4294967295))>>2)]=12;;}
else if(__label__==42){var $68=$wpm;var $cmp123=((($68))|0)>400;if($cmp123){__label__=43;;}else{__label__=44;;}
if(__label__==43){HEAP32[((((_speed)&4294967295))>>2)]=13;;}
else if(__label__==44){var $69=$wpm;var $cmp126=((($69))|0)>374;if($cmp126){__label__=45;;}else{__label__=46;;}
if(__label__==45){HEAP32[((((_speed)&4294967295))>>2)]=14;;}
else if(__label__==46){var $70=$wpm;var $cmp129=((($70))|0)>350;if(!($cmp129)){__label__=48;break $if_then121$$if_else122$52;}
var $71=$wpm;var $sub131=((($71)-350)&4294967295);var $arrayidx132=((__ZL16pause_factor_350+$sub131)&4294967295);var $72=HEAPU8[($arrayidx132)];var $conv133=((($72))&255);HEAP32[((((_speed)&4294967295))>>2)]=$conv133;;}}}}while(0);var $73=HEAP32[((((_speed+4)&4294967295))>>2)];var $cmp138=((($73))|0)==0;if(!($cmp138)){__label__=51;break $if_then10$$lor_lhs_false$11;}
var $74=HEAP32[((((_speed)&4294967295))>>2)];HEAP32[((((_speed+4)&4294967295))>>2)]=$74;var $cmp140=((($74))|0)<16;if(!($cmp140)){__label__=51;break $if_then10$$lor_lhs_false$11;}
HEAP32[((((_speed+4)&4294967295))>>2)]=16;__label__=51;break $if_then10$$lor_lhs_false$11;}}while(0);$if_then10$$if_end144$65:do{if(__label__==10){var $14=$wpm;$wpm2=$14;$wpm=175;$x=73;var $15=$control_addr;var $and11=($15)&1;var $tobool12=((($and11))|0)!=0;if($tobool12){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $16=$x;var $17=HEAP32[((_voice)>>2)];var $speedf1=(($17+52)&4294967295);var $18=HEAP32[(($speedf1)>>2)];var $mul14=((($18)*($16))&4294967295);var $div15=((((($mul14))|0)/256)|0);HEAP32[((__ZL6speed1)>>2)]=$div15;var $19=$x;var $20=HEAP32[((_voice)>>2)];var $speedf2=(($20+56)&4294967295);var $21=HEAP32[(($speedf2)>>2)];var $mul16=((($21)*($19))&4294967295);var $div17=((((($mul16))|0)/256)|0);HEAP32[((__ZL6speed2)>>2)]=$div17;var $22=$x;var $23=HEAP32[((_voice)>>2)];var $speedf3=(($23+60)&4294967295);var $24=HEAP32[(($speedf3)>>2)];var $mul18=((($24)*($22))&4294967295);var $div19=((((($mul18))|0)/256)|0);HEAP32[((__ZL6speed3)>>2)]=$div19;;}
var $25=$control_addr;var $and21=($25)&2;var $tobool22=((($and21))|0)!=0;if(!($tobool22)){__label__=51;break $if_then10$$if_end144$65;}
var $26=$wpm2;var $conv=((($26))|0);var $27=$wpm;var $conv24=((($27))|0);var $div25=($conv)/($conv24);$sonic=$div25;var $28=$sonic;var $mul26=($28)*1024;var $conv27=((($mul26))|0);__Z12DoSonicSpeedi($conv27);HEAP32[((((_speed)&4294967295))>>2)]=85;HEAP32[((((_speed+4)&4294967295))>>2)]=80;HEAP32[((((_speed+8)&4294967295))>>2)]=22;HEAP32[((((_speed+24)&4294967295))>>2)]=900;HEAP32[((((_speed+12)&4294967295))>>2)]=211;HEAP32[((((_speed+16)&4294967295))>>2)]=210;HEAP32[((((_speed+20)&4294967295))>>2)]=170;;}}while(0);;return;return;}
function __Z12SetParameteriii($parameter,$value,$relative){;var __label__;var $parameter_addr;var $value_addr;var $relative_addr;var $new_value;var $default_value;$parameter_addr=$parameter;$value_addr=$value;$relative_addr=$relative;var $0=$value_addr;$new_value=$0;var $1=$relative_addr;var $tobool=((($1))|0)!=0;if($tobool){__label__=1;;}else{__label__=3;;}
$if_then$$if_end2$2:do{if(__label__==1){var $2=$parameter_addr;var $cmp=((($2))|0)<5;if(!($cmp)){__label__=3;break $if_then$$if_end2$2;}
var $3=$parameter_addr;var $arrayidx=((_param_defaults+$3*4)&4294967295);var $4=HEAP32[(($arrayidx)>>2)];$default_value=$4;var $5=$default_value;var $6=$default_value;var $7=$value_addr;var $mul=((($7)*($6))&4294967295);var $div=((((($mul))|0)/100)|0);var $add=((($div)+($5))&4294967295);$new_value=$add;;}}while(0);var $8=$new_value;var $9=$parameter_addr;var $arrayidx3=((((_param_stack+4)&4294967295)+$9*4)&4294967295);HEAP32[(($arrayidx3)>>2)]=$8;var $10=$parameter_addr;if($10==1){__label__=4;;}
else if($10==2){__label__=5;;}
else if($10==3){__label__=6;;}
else if($10==4){__label__=11;;}
else if($10==13){__label__=14;;}
else if($10==7){__label__=15;;}
else if($10==9){__label__=16;;}
else{__label__=19;;}
if(__label__==4){var $11=$new_value;HEAP32[((((_embedded_value+8)&4294967295))>>2)]=$11;var $12=$new_value;HEAP32[((((_embedded_value+32)&4294967295))>>2)]=$12;__Z8SetSpeedi(3);;}
else if(__label__==5){var $13=$new_value;HEAP32[((((_embedded_value+12)&4294967295))>>2)]=$13;var $call=__Z12GetAmplitudev();;}
else if(__label__==6){var $14=$new_value;var $cmp6=((($14))|0)>99;if($cmp6){__label__=7;;}else{__label__=8;;}
$if_end8_thread$$if_end8$10:do{if(__label__==7){$new_value=99;;}
else if(__label__==8){var $cmp9=((($14))|0)<0;if(!($cmp9)){__label__=10;break $if_end8_thread$$if_end8$10;}
$new_value=0;;}}while(0);var $15=$new_value;HEAP32[((((_embedded_value+4)&4294967295))>>2)]=$15;;}
else if(__label__==11){var $16=$new_value;var $cmp13=((($16))|0)>99;if($cmp13){__label__=12;;}else{__label__=13;;}
if(__label__==12){$new_value=99;;}
var $17=$new_value;HEAP32[((((_embedded_value+16)&4294967295))>>2)]=$17;;}
else if(__label__==14){var $18=$new_value;HEAP32[((_option_linelength)>>2)]=$18;;}
else if(__label__==15){var $19=$new_value;HEAP32[((_option_wordgap)>>2)]=$19;;}
else if(__label__==16){var $20=$new_value;var $and=($20)&255;var $cmp19=((($and))|0)!=0;if($cmp19){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $21=$new_value;var $and21=($21)&255;var $22=HEAP32[((_translator)>>2)];var $langopts=(($22)&4294967295);var $intonation_group=(($langopts+228)&4294967295);HEAP32[(($intonation_group)>>2)]=$and21;;}
var $23=$new_value;HEAP32[((_option_tone_flags)>>2)]=$23;;};return;return;}
function __Z11CalcLengthsP10Translator($tr){var __stackBase__=STACKTOP;STACKTOP+=156;_memset(__stackBase__,0,156);var __label__;var __lastLabel__=null;var $tr_addr;var $ix;var $ix2;var $prev;var $next;var $next2;var $next3;var $p;var $p2;var $stress;var $type;var $pre_sonorant;var $pre_voiced;var $last_pitch;var $pitch_start;var $length_mod;var $len;var $env2;var $end_of_clause;var $embedded_ix=__stackBase__;var $min_drop;var $pitch1;var $emphasized;var $tone_mod;var $pitch_env;var $phdata_tone=__stackBase__+4;$tr_addr=$tr;$pre_sonorant=0;$pre_voiced=0;$last_pitch=0;HEAP32[(($embedded_ix)>>2)]=0;$pitch_env=0;$ix=1;var $0=$ix;var $1=HEAP32[((_n_phoneme_list)>>2)];var $cmp7=((($0))|0)<((($1))|0);if($cmp7){__label__=1;;}else{__label__=193;;}
$for_body_lr_ph$$for_end733$2:do{if(__label__==1){var $pitch_env595=(($phdata_tone+124)&4294967295);;$for_body$4:while(1){var $2=$ix;var $sub=((($2)-1)&4294967295);var $arrayidx=((_phoneme_list+$sub*24)&4294967295);$prev=$arrayidx;var $3=$ix;var $arrayidx1=((_phoneme_list+$3*24)&4294967295);$p=$arrayidx1;var $4=$p;var $stresslevel=(($4+1)&4294967295);var $5=HEAPU8[($stresslevel)];var $conv=((($5))&255);var $and=($conv)&7;$stress=$and;var $6=$p;var $stresslevel2=(($6+1)&4294967295);var $7=HEAPU8[($stresslevel2)];var $conv3=((($7))&255);var $and4=($conv3)&8;$emphasized=$and4;var $8=$ix;var $add=((($8)+1)&4294967295);var $arrayidx5=((_phoneme_list+$add*24)&4294967295);$next=$arrayidx5;var $9=$p;var $synthflags=(($9+4)&4294967295);var $10=HEAPU16[(($synthflags)>>1)];var $conv6=((($10))&65535);var $and7=($conv6)&2;var $tobool=((($and7))|0)!=0;if($tobool){__label__=3;;}else{__label__=4;;}
if(__label__==3){__ZL11DoEmbedded2Pi($embedded_ix);;}
var $11=$p;var $type8=(($11+15)&4294967295);var $12=HEAPU8[($type8)];var $conv9=((($12))&255);$type=$conv9;var $13=$p;var $synthflags10=(($13+4)&4294967295);var $14=HEAPU16[(($synthflags10)>>1)];var $conv11=((($14))&65535);var $and12=($conv11)&4;var $tobool13=((($and12))|0)!=0;if($tobool13){__label__=5;;}else{__label__=6;;}
$if_end15_thread$$if_end15$9:do{if(__label__==5){$type=2;__label__=98;break $if_end15_thread$$if_end15$9;}
else if(__label__==6){var $_pr=$type;if($_pr==0){__label__=7;;}
else if($_pr==4){__label__=8;;}
else if($_pr==7){__label__=23;;}
else if($_pr==6){__label__=23;;}
else if($_pr==5){__label__=49;;}
else if($_pr==3){__label__=74;;}
else if($_pr==8){__label__=74;;}
else if($_pr==2){__label__=98;break $if_end15_thread$$if_end15$9;}
else{__label__=192;break $if_end15_thread$$if_end15$9;}
if(__label__==7){$last_pitch=0;__label__=192;break $if_end15_thread$$if_end15$9;}
else if(__label__==8){$last_pitch=0;var $15=$prev;var $type17=(($15+15)&4294967295);var $16=HEAPU8[($type17)];var $conv18=((($16))&255);var $cmp19=((($conv18))|0)==6;if($cmp19){__label__=9;;}else{__label__=10;;}
$if_then20$$if_else$15:do{if(__label__==9){var $17=$p;var $prepause=(($17+16)&4294967295);HEAP8[($prepause)]=25;;}
else if(__label__==10){var $18=HEAP32[((__ZZ11CalcLengthsP10TranslatorE14more_syllables)>>2)];var $cmp21=((($18))|0)>0;if($cmp21){__label__=12;;}else{__label__=11;;}
$if_then23$$lor_lhs_false$18:do{if(__label__==11){var $19=$stress;var $cmp22=((($19))|0)<4;if($cmp22){__label__=12;break $if_then23$$lor_lhs_false$18;}
var $21=$p;var $prepause26=(($21+16)&4294967295);HEAP8[($prepause26)]=60;__label__=14;break $if_then20$$if_else$15;}}while(0);var $20=$p;var $prepause24=(($20+16)&4294967295);HEAP8[($prepause24)]=48;;}}while(0);var $22=$prev;var $type29=(($22+15)&4294967295);var $23=HEAPU8[($type29)];var $conv30=((($23))&255);var $cmp31=((($conv30))|0)==4;if($cmp31){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $24=$p;var $prepause33=(($24+16)&4294967295);HEAP8[($prepause33)]=60;;}
var $25=$tr_addr;var $langopts=(($25)&4294967295);var $word_gap=(($langopts)&4294967295);var $26=HEAP32[(($word_gap)>>2)];var $and35=($26)&16;var $tobool36=((($and35))|0)!=0;if($tobool36){__label__=17;;}else{__label__=19;;}
$land_lhs_true$$if_end40$26:do{if(__label__==17){var $27=$p;var $newword=(($27+19)&4294967295);var $28=HEAP8[($newword)];var $tobool37=(tempInt=(($28)),(tempInt>=128?tempInt-256:tempInt))!=0;if(!($tobool37)){__label__=19;break $land_lhs_true$$if_end40$26;}
var $29=$p;var $prepause39=(($29+16)&4294967295);HEAP8[($prepause39)]=60;;}}while(0);var $30=$p;var $ph=(($30+8)&4294967295);var $31=HEAP32[(($ph)>>2)];var $phflags=(($31+4)&4294967295);var $32=HEAP32[(($phflags)>>2)];var $and41=($32)&4194304;var $tobool42=((($and41))|0)!=0;if($tobool42){__label__=20;;}else{__label__=21;;}
if(__label__==20){var $33=$p;var $prepause44=(($33+16)&4294967295);var $34=HEAPU8[($prepause44)];var $conv45=((($34))&255);var $add46=((($conv45)+30)&4294967295);var $conv47=((($add46))&255);HEAP8[($prepause44)]=$conv47;;}
var $35=$p;var $synthflags49=(($35+4)&4294967295);var $36=HEAPU16[(($synthflags49)>>1)];var $conv50=((($36))&65535);var $and51=($conv50)&8;var $tobool52=((($and51))|0)!=0;if(!($tobool52)){__label__=192;break $if_end15_thread$$if_end15$9;}
var $37=$tr_addr;var $langopts54=(($37)&4294967295);var $long_stop=(($langopts54+240)&4294967295);var $38=HEAP32[(($long_stop)>>2)];var $39=$p;var $prepause55=(($39+16)&4294967295);var $40=HEAPU8[($prepause55)];var $conv56=((($40))&255);var $add57=((($conv56)+($38))&4294967295);var $conv58=((($add57))&255);HEAP8[($prepause55)]=$conv58;__label__=192;break $if_end15_thread$$if_end15$9;}
else if(__label__==23){var $41=$p;var $newword61=(($41+19)&4294967295);var $42=HEAP8[($newword61)];var $tobool62=(tempInt=(($42)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool62){__label__=24;;}else{__label__=27;;}
$if_then63$$if_end76$35:do{if(__label__==24){var $43=$prev;var $type64=(($43+15)&4294967295);var $44=HEAPU8[($type64)];var $conv65=((($44))&255);var $cmp66=((($conv65))|0)==2;if($cmp66){__label__=25;;}else{__label__=26;;}
if(__label__==25){var $45=$p;var $ph68=(($45+8)&4294967295);var $46=HEAP32[(($ph68)>>2)];var $phflags69=(($46+4)&4294967295);var $47=HEAP32[(($phflags69)>>2)];var $and70=($47)&16777216;var $tobool71=((($and70))|0)!=0;if($tobool71){__label__=27;break $if_then63$$if_end76$35;}}
var $48=$p;var $prepause74=(($48+16)&4294967295);HEAP8[($prepause74)]=15;;}}while(0);var $49=$next;var $type77=(($49+15)&4294967295);var $50=HEAPU8[($type77)];var $conv78=((($50))&255);var $cmp79=((($conv78))|0)==0;if($cmp79){__label__=28;;}else{__label__=31;;}
$land_lhs_true80$$if_end91$41:do{if(__label__==28){var $51=$prev;var $type81=(($51+15)&4294967295);var $52=HEAPU8[($type81)];var $conv82=((($52))&255);var $cmp83=((($conv82))|0)==8;if(!($cmp83)){__label__=31;break $land_lhs_true80$$if_end91$41;}
var $53=$p;var $ph85=(($53+8)&4294967295);var $54=HEAP32[(($ph85)>>2)];var $phflags86=(($54+4)&4294967295);var $55=HEAP32[(($phflags86)>>2)];var $and87=($55)&8;var $tobool88=((($and87))|0)!=0;if($tobool88){__label__=31;break $land_lhs_true80$$if_end91$41;}
var $56=$p;var $prepause90=(($56+16)&4294967295);HEAP8[($prepause90)]=25;;}}while(0);var $57=$prev;var $ph92=(($57+8)&4294967295);var $58=HEAP32[(($ph92)>>2)];var $phflags93=(($58+4)&4294967295);var $59=HEAP32[(($phflags93)>>2)];var $and94=($59)&16384;var $tobool95=((($and94))|0)!=0;if($tobool95){__label__=32;;}else{__label__=33;;}
if(__label__==32){var $60=$p;var $prepause97=(($60+16)&4294967295);HEAP8[($prepause97)]=30;;}
var $61=$tr_addr;var $langopts99=(($61)&4294967295);var $word_gap100=(($langopts99)&4294967295);var $62=HEAP32[(($word_gap100)>>2)];var $and101=($62)&16;var $tobool102=((($and101))|0)!=0;if($tobool102){__label__=34;;}else{__label__=36;;}
$land_lhs_true103$$if_end108$49:do{if(__label__==34){var $63=$p;var $newword104=(($63+19)&4294967295);var $64=HEAP8[($newword104)];var $tobool105=(tempInt=(($64)),(tempInt>=128?tempInt-256:tempInt))!=0;if(!($tobool105)){__label__=36;break $land_lhs_true103$$if_end108$49;}
var $65=$p;var $prepause107=(($65+16)&4294967295);HEAP8[($prepause107)]=30;;}}while(0);var $66=$p;var $ph109=(($66+8)&4294967295);var $67=HEAP32[(($ph109)>>2)];var $phflags110=(($67+4)&4294967295);var $68=HEAP32[(($phflags110)>>2)];var $and111=($68)&32;var $tobool112=((($and111))|0)!=0;if($tobool112){__label__=37;;}else{__label__=42;;}
$land_lhs_true113$$if_else128$53:do{if(__label__==37){var $69=$next;var $type114=(($69+15)&4294967295);var $70=HEAPU8[($type114)];var $conv115=((($70))&255);var $cmp116=((($conv115))|0)==4;if(!($cmp116)){__label__=42;break $land_lhs_true113$$if_else128$53;}
var $71=$next;var $newword118=(($71+19)&4294967295);var $72=HEAP8[($newword118)];var $tobool119=(tempInt=(($72)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool119){__label__=42;break $land_lhs_true113$$if_else128$53;}
var $73=$prev;var $type121=(($73+15)&4294967295);var $74=HEAPU8[($type121)];var $conv122=((($74))&255);var $cmp123=((($conv122))|0)==2;var $75=$p;var $length=(($75+12)&4294967295);if($cmp123){__label__=40;;}else{__label__=41;;}
if(__label__==40){HEAP16[(($length)>>1)]=200;__label__=43;break $land_lhs_true113$$if_else128$53;}
else if(__label__==41){HEAP16[(($length)>>1)]=150;__label__=43;break $land_lhs_true113$$if_else128$53;}}}while(0);if(__label__==42){var $76=$p;var $length129=(($76+12)&4294967295);HEAP16[(($length129)>>1)]=256;;}
var $77=$type;var $cmp131=((($77))|0)==7;if(!($cmp131)){__label__=192;break $if_end15_thread$$if_end15$9;}
var $78=$next;var $type133=(($78+15)&4294967295);var $79=HEAPU8[($type133)];var $conv134=((($79))&255);var $cmp135=((($conv134))|0)==2;if($cmp135){__label__=45;;}else{__label__=46;;}
if(__label__==45){$pre_voiced=1;;}
var $80=$prev;var $type138=(($80+15)&4294967295);var $81=HEAPU8[($type138)];var $conv139=((($81))&255);var $cmp140=((($conv139))|0)==2;if($cmp140){__label__=48;;}else{__label__=47;;}
if(__label__==47){var $82=$prev;var $type142=(($82+15)&4294967295);var $83=HEAPU8[($type142)];var $conv143=((($83))&255);var $cmp144=((($conv143))|0)==3;if(!($cmp144)){__label__=192;break $if_end15_thread$$if_end15$9;}}
var $84=$prev;var $length146=(($84+12)&4294967295);var $85=HEAP16[(($length146)>>1)];var $conv147=(tempInt=(($85)),(tempInt>=32768?tempInt-65536:tempInt));var $add148=((($conv147)+255)&4294967295);var $div=((((($add148))|0)/2)|0);var $conv149=((($div))&65535);var $86=$p;var $length150=(($86+12)&4294967295);HEAP16[(($length150)>>1)]=$conv149;__label__=192;break $if_end15_thread$$if_end15$9;}
else if(__label__==49){var $87=$prev;var $type154=(($87+15)&4294967295);var $88=HEAPU8[($type154)];var $conv155=((($88))&255);var $cmp156=((($conv155))|0)==7;if($cmp156){__label__=53;;}else{__label__=50;;}
$if_then170$$lor_lhs_false157$71:do{if(__label__==50){var $89=$prev;var $type158=(($89+15)&4294967295);var $90=HEAPU8[($type158)];var $conv159=((($90))&255);var $cmp160=((($conv159))|0)==6;if($cmp160){__label__=53;break $if_then170$$lor_lhs_false157$71;}
var $91=$prev;var $ph162=(($91+8)&4294967295);var $92=HEAP32[(($ph162)>>2)];var $phflags163=(($92+4)&4294967295);var $93=HEAP32[(($phflags163)>>2)];var $and164=($93)&32;var $tobool165=((($and164))|0)!=0;if($tobool165){__label__=53;break $if_then170$$lor_lhs_false157$71;}
var $94=$prev;var $type167=(($94+15)&4294967295);var $95=HEAPU8[($type167)];var $conv168=((($95))&255);var $cmp169=((($conv168))|0)==3;if($cmp169){__label__=53;break $if_then170$$lor_lhs_false157$71;}else{__label__=54;break $if_then170$$lor_lhs_false157$71;}}}while(0);if(__label__==53){var $96=$p;var $prepause171=(($96+16)&4294967295);HEAP8[($prepause171)]=30;;}
var $97=$next;var $type173=(($97+15)&4294967295);var $98=HEAPU8[($type173)];var $conv174=((($98))&255);var $cmp175=((($conv174))|0)==2;if($cmp175){__label__=56;;}else{__label__=55;;}
$if_then180$$lor_lhs_false176$78:do{if(__label__==55){var $99=$next;var $type177=(($99+15)&4294967295);var $100=HEAPU8[($type177)];var $conv178=((($100))&255);var $cmp179=((($conv178))|0)==3;if($cmp179){__label__=56;break $if_then180$$lor_lhs_false176$78;}else{__label__=70;break $if_then180$$lor_lhs_false176$78;}}}while(0);$if_then180$$if_end229$80:do{if(__label__==56){var $101=$next;var $type181=(($101+15)&4294967295);var $102=HEAPU8[($type181)];var $conv182=((($102))&255);var $cmp183=((($conv182))|0)==2;if($cmp183){__label__=58;;}else{__label__=57;;}
$if_then187$$lor_lhs_false184$82:do{if(__label__==57){var $103=$next;var $newword185=(($103+19)&4294967295);var $104=HEAP8[($newword185)];var $tobool186=(tempInt=(($104)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool186){__label__=59;break $if_then187$$lor_lhs_false184$82;}else{__label__=58;break $if_then187$$lor_lhs_false184$82;}}}while(0);if(__label__==58){$pre_voiced=1;;}
var $105=$p;var $prepause189=(($105+16)&4294967295);HEAP8[($prepause189)]=40;var $106=$prev;var $type190=(($106+15)&4294967295);var $107=HEAPU8[($type190)];var $conv191=((($107))&255);var $cmp192=((($conv191))|0)==0;if($cmp192){__label__=61;;}else{__label__=60;;}
$if_then197$$lor_lhs_false193$87:do{if(__label__==60){var $108=$prev;var $type194=(($108+15)&4294967295);var $109=HEAPU8[($type194)];var $conv195=((($109))&255);var $cmp196=((($conv195))|0)==2;if($cmp196){__label__=61;break $if_then197$$lor_lhs_false193$87;}
var $111=$p;var $newword200=(($111+19)&4294967295);var $112=HEAPU8[($newword200)];var $conv201=((($112))&255);var $cmp202=((($conv201))|0)==0;if(!($cmp202)){__label__=70;break $if_then180$$if_end229$80;}
var $113=$prev;var $type204=(($113+15)&4294967295);var $114=HEAPU8[($type204)];var $conv205=((($114))&255);var $cmp206=((($conv205))|0)==3;if($cmp206){__label__=64;;}else{__label__=65;;}
if(__label__==64){var $115=$p;var $prepause208=(($115+16)&4294967295);HEAP8[($prepause208)]=20;;}
var $116=$prev;var $type210=(($116+15)&4294967295);var $117=HEAPU8[($type210)];var $conv211=((($117))&255);var $cmp212=((($conv211))|0)==8;if($cmp212){__label__=66;;}else{__label__=67;;}
if(__label__==66){var $118=$p;var $prepause214=(($118+16)&4294967295);HEAP8[($prepause214)]=12;;}
var $119=$prev;var $type216=(($119+15)&4294967295);var $120=HEAPU8[($type216)];var $conv217=((($120))&255);var $cmp218=((($conv217))|0)==4;if(!($cmp218)){__label__=70;break $if_then180$$if_end229$80;}
var $121=$prev;var $ph220=(($121+8)&4294967295);var $122=HEAP32[(($ph220)>>2)];var $phflags221=(($122+4)&4294967295);var $123=HEAP32[(($phflags221)>>2)];var $and222=($123)&8;var $tobool223=((($and222))|0)!=0;if($tobool223){__label__=70;break $if_then180$$if_end229$80;}
var $124=$p;var $prepause225=(($124+16)&4294967295);HEAP8[($prepause225)]=0;__label__=70;break $if_then180$$if_end229$80;}}while(0);var $110=$p;var $prepause198=(($110+16)&4294967295);HEAP8[($prepause198)]=0;;}}while(0);var $125=$tr_addr;var $langopts230=(($125)&4294967295);var $word_gap231=(($langopts230)&4294967295);var $126=HEAP32[(($word_gap231)>>2)];var $and232=($126)&16;var $tobool233=((($and232))|0)!=0;if(!($tobool233)){__label__=192;break $if_end15_thread$$if_end15$9;}
var $127=$p;var $newword235=(($127+19)&4294967295);var $128=HEAP8[($newword235)];var $tobool236=(tempInt=(($128)),(tempInt>=128?tempInt-256:tempInt))!=0;if(!($tobool236)){__label__=192;break $if_end15_thread$$if_end15$9;}
var $129=$p;var $prepause238=(($129+16)&4294967295);var $130=HEAPU8[($prepause238)];var $conv239=((($130))&255);var $cmp240=((($conv239))|0)<20;if(!($cmp240)){__label__=192;break $if_end15_thread$$if_end15$9;}
var $131=$p;var $prepause242=(($131+16)&4294967295);HEAP8[($prepause242)]=20;__label__=192;break $if_end15_thread$$if_end15$9;}
else if(__label__==74){var $132=$tr_addr;var $stress_amps=(($132+660)&4294967295);var $arrayidx245=(($stress_amps)&4294967295);var $133=HEAP8[($arrayidx245)];var $134=$p;var $amp=(($134+18)&4294967295);HEAP8[($amp)]=$133;var $135=$p;var $length246=(($135+12)&4294967295);HEAP16[(($length246)>>1)]=256;$min_drop=0;var $136=$p;var $newword247=(($136+19)&4294967295);var $137=HEAP8[($newword247)];var $tobool248=(tempInt=(($137)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool248){__label__=75;;}else{__label__=80;;}
$if_then249$$if_end268$105:do{if(__label__==75){var $138=$prev;var $type250=(($138+15)&4294967295);var $139=HEAPU8[($type250)];var $conv251=((($139))&255);var $cmp252=((($conv251))|0)==3;if($cmp252){__label__=76;;}else{__label__=77;;}
if(__label__==76){var $140=$p;var $prepause254=(($140+16)&4294967295);HEAP8[($prepause254)]=25;;}
var $141=$prev;var $type256=(($141+15)&4294967295);var $142=HEAPU8[($type256)];var $conv257=((($142))&255);var $cmp258=((($conv257))|0)==2;if(!($cmp258)){__label__=80;break $if_then249$$if_end268$105;}
var $143=$p;var $ph260=(($143+8)&4294967295);var $144=HEAP32[(($ph260)>>2)];var $phflags261=(($144+4)&4294967295);var $145=HEAP32[(($phflags261)>>2)];var $and262=($145)&16777216;var $tobool263=((($and262))|0)!=0;if($tobool263){__label__=80;break $if_then249$$if_end268$105;}
var $146=$p;var $prepause265=(($146+16)&4294967295);HEAP8[($prepause265)]=12;;}}while(0);var $147=$next;var $type269=(($147+15)&4294967295);var $148=HEAPU8[($type269)];var $conv270=((($148))&255);var $cmp271=((($conv270))|0)==2;if($cmp271){__label__=81;;}else{__label__=82;;}
if(__label__==81){$pre_sonorant=1;__label__=192;break $if_end15_thread$$if_end15$9;}
else if(__label__==82){var $149=$last_pitch;var $conv274=((($149))&255);var $150=$p;var $pitch2=(($150+21)&4294967295);HEAP8[($pitch2)]=$conv274;var $151=$prev;var $type275=(($151+15)&4294967295);var $152=HEAPU8[($type275)];var $conv276=((($152))&255);var $cmp277=((($conv276))|0)==2;if($cmp277){__label__=84;;}else{__label__=83;;}
$if_then282$$lor_lhs_false278$116:do{if(__label__==83){var $153=$prev;var $type279=(($153+15)&4294967295);var $154=HEAPU8[($type279)];var $conv280=((($154))&255);var $cmp281=((($conv280))|0)==3;if($cmp281){__label__=84;break $if_then282$$lor_lhs_false278$116;}
var $172=$ix;$ix2=$172;;while(1){var $173=$ix2;var $174=HEAP32[((_n_phoneme_list)>>2)];var $cmp315=((($173))|0)<((($174))|0);if(!($cmp315)){__label__=95;break $if_then282$$lor_lhs_false278$116;}
var $175=$ix2;var $arrayidx317=((_phoneme_list+$175*24)&4294967295);var $type318=(($arrayidx317+15)&4294967295);var $176=HEAPU8[($type318)];var $conv319=((($176))&255);var $cmp320=((($conv319))|0)==2;var $177=$ix2;if($cmp320){__label__=93;break;}
var $inc=((($177)+1)&4294967295);$ix2=$inc;__label__=91;continue;}
var $arrayidx322=((_phoneme_list+$177*24)&4294967295);var $pitch2323=(($arrayidx322+21)&4294967295);var $178=HEAP8[($pitch2323)];var $179=$p;var $pitch2324=(($179+21)&4294967295);HEAP8[($pitch2324)]=$178;__label__=95;break $if_then282$$lor_lhs_false278$116;}}while(0);$if_then282$$if_end326$124:do{if(__label__==84){var $155=$prev;var $length283=(($155+12)&4294967295);var $156=HEAP16[(($length283)>>1)];var $157=$p;var $length284=(($157+12)&4294967295);HEAP16[(($length284)>>1)]=$156;var $158=$p;var $type285=(($158+15)&4294967295);var $159=HEAPU8[($type285)];var $conv286=((($159))&255);var $cmp287=((($conv286))|0)==3;if($cmp287){__label__=85;;}else{__label__=86;;}
if(__label__==85){var $160=HEAP32[((__ZL6speed1)>>2)];var $conv289=((($160))&65535);var $161=$p;var $length290=(($161+12)&4294967295);HEAP16[(($length290)>>1)]=$conv289;;}
var $162=$next;var $type292=(($162+15)&4294967295);var $163=HEAPU8[($type292)];var $conv293=((($163))&255);var $cmp294=((($conv293))|0)==5;if($cmp294){__label__=87;;}else{__label__=88;;}
if(__label__==87){var $164=$p;var $length296=(($164+12)&4294967295);var $165=HEAP16[(($length296)>>1)];var $conv297=(tempInt=(($165)),(tempInt>=32768?tempInt-65536:tempInt));var $mul=((($conv297)*160)&4294967295);var $div298=((((($mul))|0)/100)|0);var $conv299=((($div298))&65535);var $166=$p;var $length300=(($166+12)&4294967295);HEAP16[(($length300)>>1)]=$conv299;;}
var $167=$next;var $type302=(($167+15)&4294967295);var $168=HEAPU8[($type302)];var $conv303=((($168))&255);var $cmp304=((($conv303))|0)==7;if(!($cmp304)){__label__=95;break $if_then282$$if_end326$124;}
var $169=$p;var $length306=(($169+12)&4294967295);var $170=HEAP16[(($length306)>>1)];var $conv307=(tempInt=(($170)),(tempInt>=32768?tempInt-65536:tempInt));var $mul308=((($conv307)*120)&4294967295);var $div309=((((($mul308))|0)/100)|0);var $conv310=((($div309))&65535);var $171=$p;var $length311=(($171+12)&4294967295);HEAP16[(($length311)>>1)]=$conv310;;}}while(0);var $180=$p;var $pitch2327=(($180+21)&4294967295);var $181=HEAPU8[($pitch2327)];var $conv328=((($181))&255);var $sub329=((($conv328)-16)&4294967295);var $conv330=((($sub329))&255);var $182=$p;var $pitch1331=(($182+20)&4294967295);HEAP8[($pitch1331)]=$conv330;var $183=$p;var $pitch2332=(($183+21)&4294967295);var $184=HEAPU8[($pitch2332)];var $conv333=((($184))&255);var $cmp334=((($conv333))|0)<16;if($cmp334){__label__=96;;}else{__label__=97;;}
if(__label__==96){var $185=$p;var $pitch1336=(($185+20)&4294967295);HEAP8[($pitch1336)]=0;;}
var $186=$p;var $env=(($186+14)&4294967295);HEAP8[($env)]=0;$pre_voiced=0;__label__=192;break $if_end15_thread$$if_end15$9;}}}}while(0);if(__label__==98){$min_drop=0;var $187=$ix;var $add340=((($187)+2)&4294967295);var $arrayidx341=((_phoneme_list+$add340*24)&4294967295);$next2=$arrayidx341;var $188=$ix;var $add342=((($188)+3)&4294967295);var $arrayidx343=((_phoneme_list+$add342*24)&4294967295);$next3=$arrayidx343;var $189=$stress;var $cmp344=((($189))|0)>7;if($cmp344){__label__=99;;}else{__label__=100;;}
$if_end346_thread$$if_end346$139:do{if(__label__==99){$stress=7;;}
else if(__label__==100){var $cmp347=((($189))|0)<=1;if(!($cmp347)){__label__=102;break $if_end346_thread$$if_end346$139;}
var $190=$stress;var $xor=($190)^1;$stress=$xor;;}}while(0);var $191=$pre_sonorant;var $tobool350=((($191))|0)!=0;var $192=$stress;var $193=$tr_addr;var $stress_amps352=(($193+660)&4294967295);var $arrayidx353=(($stress_amps352+$192)&4294967295);var $194=HEAPU8[($arrayidx353)];if($tobool350){__label__=103;;}else{__label__=104;;}
if(__label__==103){var $conv354=((($194))&255);var $sub355=((($conv354)-1)&4294967295);var $conv356=((($sub355))&255);var $195=$p;var $amp357=(($195+18)&4294967295);HEAP8[($amp357)]=$conv356;;}
else if(__label__==104){var $196=$p;var $amp361=(($196+18)&4294967295);HEAP8[($amp361)]=$194;;}
var $197=$emphasized;var $tobool363=((($197))|0)!=0;if($tobool363){__label__=106;;}else{__label__=107;;}
if(__label__==106){var $198=$p;var $amp365=(($198+18)&4294967295);HEAP8[($amp365)]=25;;}
var $199=$ix;var $200=HEAP32[((_n_phoneme_list)>>2)];var $sub367=((($200)-3)&4294967295);var $cmp368=((($199))|0)>=((($sub367))|0);if($cmp368){__label__=108;;}else{__label__=110;;}
$if_then369$$if_end382$151:do{if(__label__==108){var $201=$p;var $amp370=(($201+18)&4294967295);var $202=HEAPU8[($amp370)];var $conv371=((($202))&255);var $203=$tr_addr;var $langopts372=(($203)&4294967295);var $param=(($langopts372+24)&4294967295);var $arrayidx373=(($param+36)&4294967295);var $204=HEAP32[(($arrayidx373)>>2)];var $cmp374=((($conv371))|0)>((($204))|0);if(!($cmp374)){__label__=110;break $if_then369$$if_end382$151;}
var $205=$tr_addr;var $langopts376=(($205)&4294967295);var $param377=(($langopts376+24)&4294967295);var $arrayidx378=(($param377+36)&4294967295);var $206=HEAP32[(($arrayidx378)>>2)];var $conv379=((($206))&255);var $207=$p;var $amp380=(($207+18)&4294967295);HEAP8[($amp380)]=$conv379;;}}while(0);HEAP32[((__ZZ11CalcLengthsP10TranslatorE14more_syllables)>>2)]=0;$end_of_clause=0;var $208=$p;var $add_ptr=(($208+24)&4294967295);$p2=$add_ptr;var $209=$p2;var $newword3843=(($209+19)&4294967295);var $210=HEAPU8[($newword3843)];var $conv3854=((($210))&255);var $cmp3865=((($conv3854))|0)==0;var $211=$p2;if($cmp3865){__lastLabel__=110;__label__=111;;}else{__lastLabel__=110;__label__=117;;}
$for_body387$$for_end405$155:do{if(__label__==111){$for_body387$156:while(1){var $212=__lastLabel__==116?$224:($211);var $type388=(($212+15)&4294967295);var $213=HEAPU8[($type388)];var $conv389=((($213))&255);var $cmp390=((($conv389))|0)==2;if($cmp390){__label__=112;;}else{__label__=114;;}
$land_lhs_true391$$if_end398$158:do{if(__label__==112){var $214=$p2;var $ph392=(($214+8)&4294967295);var $215=HEAP32[(($ph392)>>2)];var $phflags393=(($215+4)&4294967295);var $216=HEAP32[(($phflags393)>>2)];var $and394=($216)&1048576;var $tobool395=((($and394))|0)!=0;if($tobool395){__label__=114;break $land_lhs_true391$$if_end398$158;}
var $217=HEAP32[((__ZZ11CalcLengthsP10TranslatorE14more_syllables)>>2)];var $inc397=((($217)+1)&4294967295);HEAP32[((__ZZ11CalcLengthsP10TranslatorE14more_syllables)>>2)]=$inc397;;}}while(0);var $218=$p2;var $ph399=(($218+8)&4294967295);var $219=HEAP32[(($ph399)>>2)];var $code=(($219+10)&4294967295);var $220=HEAPU8[($code)];var $conv400=((($220))&255);var $cmp401=((($conv400))|0)==27;if($cmp401){__label__=115;;}else{__label__=116;;}
if(__label__==115){$end_of_clause=2;;}
var $221=$p2;var $incdec_ptr=(($221+24)&4294967295);$p2=$incdec_ptr;var $222=$p2;var $newword384=(($222+19)&4294967295);var $223=HEAPU8[($newword384)];var $conv385=((($223))&255);var $cmp386=((($conv385))|0)==0;var $224=$p2;if($cmp386){__lastLabel__=116;__label__=111;continue $for_body387$156;}else{__lastLabel__=116;__label__=117;break $for_body387$$for_end405$155;}}}}while(0);var $_lcssa=__lastLabel__==110?$211:($224);var $ph406=(($_lcssa+8)&4294967295);var $225=HEAP32[(($ph406)>>2)];var $code407=(($225+10)&4294967295);var $226=HEAPU8[($code407)];var $conv408=((($226))&255);var $cmp409=((($conv408))|0)==27;if($cmp409){__label__=118;;}else{__label__=119;;}
if(__label__==118){$end_of_clause=2;;}
var $227=$p2;var $newword412=(($227+19)&4294967295);var $228=HEAPU8[($newword412)];var $conv413=((($228))&255);var $and414=($conv413)&2;var $tobool415=((($and414))|0)!=0;var $229=HEAP32[((__ZZ11CalcLengthsP10TranslatorE14more_syllables)>>2)];var $cmp417=((($229))|0)==0;var $or_cond=($tobool415)&($cmp417);if($or_cond){__label__=120;;}else{__label__=121;;}
if(__label__==120){$end_of_clause=2;;}
var $230=$next;var $ph420=(($230+8)&4294967295);var $231=HEAP32[(($ph420)>>2)];var $code421=(($231+10)&4294967295);var $232=HEAPU8[($code421)];var $conv422=((($232))&255);var $cmp423=((($conv422))|0)==23;if($cmp423){__label__=122;;}else{__label__=124;;}
$land_lhs_true424$$if_end431$172:do{if(__label__==122){var $233=$next2;var $type425=(($233+15)&4294967295);var $234=HEAPU8[($type425)];var $conv426=((($234))&255);var $cmp427=((($conv426))|0)==0;if(!($cmp427)){__label__=124;break $land_lhs_true424$$if_end431$172;}
var $235=$next2;$next=$235;var $236=$next3;$next2=$236;var $237=$ix;var $add429=((($237)+4)&4294967295);var $arrayidx430=((_phoneme_list+$add429*24)&4294967295);$next3=$arrayidx430;;}}while(0);var $238=HEAP32[((__ZZ11CalcLengthsP10TranslatorE14more_syllables)>>2)];var $cmp432=((($238))|0)==0;var $239=$next2;var $ph434=(($239+8)&4294967295);var $240=HEAP32[(($ph434)>>2)];var $length_mod435=(($240+15)&4294967295);var $241=HEAPU8[($length_mod435)];var $conv436=((($241))&255);var $mul437=((($conv436)*10)&4294967295);var $242=$next;var $ph438=(($242+8)&4294967295);var $243=HEAP32[(($ph438)>>2)];var $length_mod439=(($243+15)&4294967295);var $244=HEAPU8[($length_mod439)];var $conv440=((($244))&255);var $add441=((($conv440)+($mul437))&4294967295);var $245=$tr_addr;var $langopts442=(($245)&4294967295);if($cmp432){__label__=125;;}else{__label__=129;;}
$if_then433$$if_else466$176:do{if(__label__==125){var $length_mods0=(($langopts442+180)&4294967295);var $246=HEAP32[(($length_mods0)>>2)];var $arrayidx443=(($246+$add441)&4294967295);var $247=HEAPU8[($arrayidx443)];var $conv444=((($247))&255);$len=$conv444;var $248=$next;var $newword445=(($248+19)&4294967295);var $249=HEAP8[($newword445)];var $tobool446=(tempInt=(($249)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool446){__label__=126;;}else{__label__=128;;}
$land_lhs_true447$$if_else464$178:do{if(__label__==126){var $250=$tr_addr;var $langopts448=(($250)&4294967295);var $word_gap449=(($langopts448)&4294967295);var $251=HEAP32[(($word_gap449)>>2)];var $and450=($251)&32;var $tobool451=((($and450))|0)!=0;if(!($tobool451)){__label__=128;break $land_lhs_true447$$if_else464$178;}
var $252=$len;var $253=$next;var $ph453=(($253+8)&4294967295);var $254=HEAP32[(($ph453)>>2)];var $length_mod454=(($254+15)&4294967295);var $255=HEAPU8[($length_mod454)];var $conv455=((($255))&255);var $mul456=((($conv455)*10)&4294967295);var $add457=((($mul456)+1)&4294967295);var $256=$tr_addr;var $langopts458=(($256)&4294967295);var $length_mods0459=(($langopts458+180)&4294967295);var $257=HEAP32[(($length_mods0459)>>2)];var $arrayidx460=(($257+$add457)&4294967295);var $258=HEAPU8[($arrayidx460)];var $conv461=((($258))&255);var $add462=((($conv461)+($252))&4294967295);var $div463=((((($add462))|0)/2)|0);$length_mod=$div463;__label__=134;break $if_then433$$if_else466$176;}}while(0);var $259=$len;$length_mod=$259;;}
else if(__label__==129){var $length_mods=(($langopts442+176)&4294967295);var $260=HEAP32[(($length_mods)>>2)];var $arrayidx476=(($260+$add441)&4294967295);var $261=HEAPU8[($arrayidx476)];var $conv477=((($261))&255);$length_mod=$conv477;var $262=$next;var $type478=(($262+15)&4294967295);var $263=HEAPU8[($type478)];var $conv479=((($263))&255);var $cmp480=((($conv479))|0)==8;if(!($cmp480)){__label__=134;break $if_then433$$if_else466$176;}
var $264=$next2;var $type482=(($264+15)&4294967295);var $265=HEAPU8[($type482)];var $conv483=((($265))&255);var $cmp484=((($conv483))|0)==4;if($cmp484){__label__=132;;}else{__label__=131;;}
if(__label__==131){var $266=$next2;var $type486=(($266+15)&4294967295);var $267=HEAPU8[($type486)];var $conv487=((($267))&255);var $cmp488=((($conv487))|0)==5;if(!($cmp488)){__label__=134;break $if_then433$$if_else466$176;}}
var $268=$next3;var $ph490=(($268+8)&4294967295);var $269=HEAP32[(($ph490)>>2)];var $phflags491=(($269+4)&4294967295);var $270=HEAP32[(($phflags491)>>2)];var $and492=($270)&8;var $tobool493=((($and492))|0)!=0;if(!($tobool493)){__label__=134;break $if_then433$$if_else466$176;}
var $271=$length_mod;var $sub495=((($271)-15)&4294967295);$length_mod=$sub495;;}}while(0);var $272=HEAP32[((__ZZ11CalcLengthsP10TranslatorE14more_syllables)>>2)];var $cmp498=((($272))|0)==0;if($cmp498){__label__=135;;}else{__label__=136;;}
if(__label__==135){var $273=HEAP32[((__ZL6speed1)>>2)];var $274=$length_mod;var $mul500=((($274)*($273))&4294967295);$length_mod=$mul500;;}
else if(__label__==136){var $275=HEAP32[((__ZZ11CalcLengthsP10TranslatorE14more_syllables)>>2)];var $cmp502=((($275))|0)==1;if($cmp502){__label__=137;;}else{__label__=138;;}
if(__label__==137){var $276=HEAP32[((__ZL6speed2)>>2)];var $277=$length_mod;var $mul504=((($277)*($276))&4294967295);$length_mod=$mul504;;}
else if(__label__==138){var $278=HEAP32[((__ZL6speed3)>>2)];var $279=$length_mod;var $mul506=((($279)*($278))&4294967295);$length_mod=$mul506;;}}
var $280=$length_mod;var $div509=((((($280))|0)/128)|0);$length_mod=$div509;var $cmp510=((($div509))|0)<8;if($cmp510){__label__=140;;}else{__label__=141;;}
if(__label__==140){$length_mod=8;;}
var $281=$stress;var $cmp513=((($281))|0)>=7;if($cmp513){__label__=142;;}else{__label__=144;;}
$if_then514$$if_else520$199:do{if(__label__==142){var $282=$length_mod;var $add515=((($282)+20)&4294967295);$length_mod=$add515;var $283=$emphasized;var $tobool516=((($283))|0)!=0;if(!($tobool516)){__label__=146;break $if_then514$$if_else520$199;}
var $284=$length_mod;var $add518=((($284)+10)&4294967295);$length_mod=$add518;;}
else if(__label__==144){var $285=$emphasized;var $tobool521=((($285))|0)!=0;if(!($tobool521)){__label__=146;break $if_then514$$if_else520$199;}
var $286=$length_mod;var $add523=((($286)+20)&4294967295);$length_mod=$add523;;}}while(0);var $287=$stress;var $288=$tr_addr;var $stress_lengths=(($288+676)&4294967295);var $arrayidx526=(($stress_lengths+$287*2)&4294967295);var $289=HEAP16[(($arrayidx526)>>1)];var $conv527=(tempInt=(($289)),(tempInt>=32768?tempInt-65536:tempInt));$len=$conv527;var $cmp528=((($conv527))|0)==0;if($cmp528){__label__=147;;}else{__label__=148;;}
if(__label__==147){var $290=$tr_addr;var $stress_lengths530=(($290+676)&4294967295);var $arrayidx531=(($stress_lengths530+12)&4294967295);var $291=HEAP16[(($arrayidx531)>>1)];var $conv532=(tempInt=(($291)),(tempInt>=32768?tempInt-65536:tempInt));$len=$conv532;;}
var $292=$length_mod;var $293=$len;var $mul534=((($293)*($292))&4294967295);$length_mod=$mul534;var $294=$p;var $tone_ph=(($294+3)&4294967295);var $295=HEAPU8[($tone_ph)];var $conv535=((($295))&255);var $cmp536=((($conv535))|0)!=0;if($cmp536){__label__=149;;}else{__label__=151;;}
$if_then537$$if_end546$208:do{if(__label__==149){var $296=$p;var $tone_ph538=(($296+3)&4294967295);var $297=HEAPU8[($tone_ph538)];var $idxprom=((($297))&255);var $arrayidx539=((_phoneme_tab+$idxprom*4)&4294967295);var $298=HEAP32[(($arrayidx539)>>2)];var $std_length=(($298+14)&4294967295);var $299=HEAPU8[($std_length)];var $conv540=((($299))&255);$tone_mod=$conv540;var $cmp541=((($conv540))|0)>0;if(!($cmp541)){__label__=151;break $if_then537$$if_end546$208;}
var $300=$length_mod;var $301=$tone_mod;var $mul543=((($301)*($300))&4294967295);var $div544=((((($mul543))|0)/100)|0);$length_mod=$div544;;}}while(0);var $302=$end_of_clause;var $cmp547=((($302))|0)==2;if($cmp547){__label__=152;;}else{__label__=155;;}
if(__label__==152){var $303=$p;var $ph549=(($303+8)&4294967295);var $304=HEAP32[(($ph549)>>2)];var $std_length550=(($304+14)&4294967295);var $305=HEAPU8[($std_length550)];var $conv551=((($305))&255);var $mul552=((($conv551)*2)&4294967295);$len=$mul552;var $306=$tr_addr;var $langopts553=(($306)&4294967295);var $stress_flags=(($langopts553+12)&4294967295);var $307=HEAP32[(($stress_flags)>>2)];var $and554=($307)&262144;var $tobool555=((($and554))|0)!=0;if($tobool555){__label__=153;;}else{__label__=154;;}
if(__label__==153){$len=200;;}
var $308=$length_mod;var $309=$len;var $sub558=((280-($309))&4294967295);var $div559=((((($sub558))|0)/3)|0);var $add560=((($div559)+256)&4294967295);var $mul561=((($add560)*($308))&4294967295);var $div562=((((($mul561))|0)/256)|0);$length_mod=$div562;;}
var $310=$length_mod;var $311=$tr_addr;var $langopts564=(($311)&4294967295);var $max_lengthmod=(($langopts564+272)&4294967295);var $312=HEAP32[(($max_lengthmod)>>2)];var $313=HEAP32[((__ZL6speed1)>>2)];var $mul565=((($313)*($312))&4294967295);var $cmp566=((($310))|0)>((($mul565))|0);if($cmp566){__label__=156;;}else{__label__=157;;}
if(__label__==156){var $314=$tr_addr;var $langopts568=(($314)&4294967295);var $max_lengthmod569=(($langopts568+272)&4294967295);var $315=HEAP32[(($max_lengthmod569)>>2)];var $316=HEAP32[((__ZL6speed1)>>2)];var $mul570=((($316)*($315))&4294967295);$length_mod=$mul570;;}
var $317=$length_mod;var $div572=((((($317))|0)/128)|0);$length_mod=$div572;var $318=$p;var $type573=(($318+15)&4294967295);var $319=HEAPU8[($type573)];var $conv574=((($319))&255);var $cmp575=((($conv574))|0)!=2;if($cmp575){__label__=158;;}else{__label__=159;;}
if(__label__==158){$length_mod=256;$min_drop=16;;}
var $320=$length_mod;var $conv578=((($320))&65535);var $321=$p;var $length579=(($321+12)&4294967295);HEAP16[(($length579)>>1)]=$conv578;var $322=$p;var $env580=(($322+14)&4294967295);var $323=HEAPU8[($env580)];var $conv581=((($323))&255);var $cmp582=((($conv581))|0)>=19;if($cmp582){__label__=160;;}else{__label__=161;;}
if(__label__==160){var $324=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($324+12)&4294967295);var $325=HEAP32[(($_stderr)>>2)];var $326=_fwrite(((__str294)&4294967295),28,1,$325);var $327=$p;var $env584=(($327+14)&4294967295);HEAP8[($env584)]=0;;}
var $328=$p;var $env586=(($328+14)&4294967295);var $329=HEAPU8[($env586)];var $conv587=((($329))&255);var $add588=((($conv587)+1)&4294967295);$env2=$add588;var $330=$p;var $tone_ph589=(($330+3)&4294967295);var $331=HEAPU8[($tone_ph589)];var $conv590=((($331))&255);var $cmp591=((($conv590))|0)!=0;if($cmp591){__label__=162;;}else{__label__=163;;}
if(__label__==162){var $332=$p;var $tone_ph593=(($332+3)&4294967295);var $333=HEAPU8[($tone_ph593)];var $conv594=((($333))&255);__Z17InterpretPhoneme2iP12PHONEME_DATA($conv594,$phdata_tone);var $334=HEAP32[(($pitch_env595)>>2)];var $call596=__Z11GetEnvelopei($334);$pitch_env=$call596;;}
else if(__label__==163){var $335=$env2;var $arrayidx598=((_envelope_data+$335*4)&4294967295);var $336=HEAP32[(($arrayidx598)>>2)];$pitch_env=$336;;}
var $337=$p;var $pitch1600=(($337+20)&4294967295);var $338=HEAPU8[($pitch1600)];var $conv601=((($338))&255);var $339=$p;var $pitch2602=(($339+21)&4294967295);var $340=HEAPU8[($pitch2602)];var $conv603=((($340))&255);var $341=$p;var $pitch1604=(($341+20)&4294967295);var $342=HEAPU8[($pitch1604)];var $conv605=((($342))&255);var $sub606=((($conv603)-($conv605))&4294967295);var $343=$pitch_env;var $arrayidx607=(($343)&4294967295);var $344=HEAPU8[($arrayidx607)];var $conv608=((($344))&255);var $mul609=((($conv608)*($sub606))&4294967295);var $div610=((((($mul609))|0)/256)|0);var $add611=((($div610)+($conv601))&4294967295);$pitch_start=$add611;var $345=$pre_sonorant;var $tobool612=((($345))|0)!=0;if($tobool612){__lastLabel__=164;__label__=167;;}else{__lastLabel__=164;__label__=165;;}
$if_then615$$lor_lhs_false613$231:do{if(__label__==165){var $346=$pre_voiced;var $tobool614=((($346))|0)!=0;if(!($tobool614)){__label__=177;break $if_then615$$lor_lhs_false613$231;}
var $_pr2=$pitch_start;__lastLabel__=166;__label__=167;break $if_then615$$lor_lhs_false613$231;}}while(0);$if_then615$$if_end650$234:do{if(__label__==167){var $347=__lastLabel__==166?$_pr2:($add611);var $cmp616=((($347))|0)==255;if($cmp616){__label__=168;;}else{__label__=169;;}
if(__label__==168){var $348=$pitch_start;$last_pitch=$348;;}
var $349=$pitch_start;var $350=$last_pitch;var $sub619=((($349)-($350))&4294967295);var $cmp620=((($sub619))|0)>16;if($cmp620){__label__=170;;}else{__label__=171;;}
if(__label__==170){var $351=$pitch_start;var $sub622=((($351)-16)&4294967295);$last_pitch=$sub622;;}
var $352=$last_pitch;var $conv624=((($352))&255);var $353=$prev;var $pitch1625=(($353+20)&4294967295);HEAP8[($pitch1625)]=$conv624;var $354=$pitch_start;var $conv626=((($354))&255);var $355=$prev;var $pitch2627=(($355+21)&4294967295);HEAP8[($pitch2627)]=$conv626;var $356=$last_pitch;var $357=$pitch_start;var $cmp628=((($356))|0)<((($357))|0);var $358=$prev;var $env630=(($358+14)&4294967295);if($cmp628){__label__=172;;}else{__label__=173;;}
if(__label__==172){HEAP8[($env630)]=2;var $359=$env2;var $conv631=((($359))&255);var $360=$p;var $env632=(($360+14)&4294967295);HEAP8[($env632)]=$conv631;;}
else if(__label__==173){HEAP8[($env630)]=0;;}
var $361=$length_mod;var $conv636=((($361))&65535);var $362=$prev;var $length637=(($362+12)&4294967295);HEAP16[(($length637)>>1)]=$conv636;var $363=$p;var $amp638=(($363+18)&4294967295);var $364=HEAP8[($amp638)];var $365=$prev;var $amp639=(($365+18)&4294967295);HEAP8[($amp639)]=$364;var $366=$prev;var $type640=(($366+15)&4294967295);var $367=HEAPU8[($type640)];var $conv641=((($367))&255);var $cmp642=((($conv641))|0)!=3;if(!($cmp642)){__label__=177;break $if_then615$$if_end650$234;}
var $368=$prev;var $amp644=(($368+18)&4294967295);var $369=HEAPU8[($amp644)];var $conv645=((($369))&255);var $cmp646=((($conv645))|0)>18;if(!($cmp646)){__label__=177;break $if_then615$$if_end650$234;}
var $370=$prev;var $amp648=(($370+18)&4294967295);HEAP8[($amp648)]=18;;}}while(0);var $371=$next;var $synthflags651=(($371+4)&4294967295);var $372=HEAPU16[(($synthflags651)>>1)];var $conv652=((($372))&65535);var $and653=($conv652)&-2;var $conv654=((($and653))&65535);HEAP16[(($synthflags651)>>1)]=$conv654;var $373=$next;var $type655=(($373+15)&4294967295);var $374=HEAPU8[($type655)];var $conv656=((($374))&255);var $cmp657=((($conv656))|0)==8;if($cmp657){__label__=178;;}else{__label__=180;;}
$land_lhs_true658$$if_end666$249:do{if(__label__==178){var $375=$next2;var $type659=(($375+15)&4294967295);var $376=HEAPU8[($type659)];var $conv660=((($376))&255);var $cmp661=((($conv660))|0)!=2;if(!($cmp661)){__label__=180;break $land_lhs_true658$$if_end666$249;}
var $377=$next;var $synthflags663=(($377+4)&4294967295);var $378=HEAPU16[(($synthflags663)>>1)];var $conv664=((($378))&65535);var $or=($conv664)|1;var $conv665=((($or))&65535);HEAP16[(($synthflags663)>>1)]=$conv665;;}}while(0);var $379=$next;var $type667=(($379+15)&4294967295);var $380=HEAPU8[($type667)];var $conv668=((($380))&255);var $cmp669=((($conv668))|0)==3;if($cmp669){__label__=181;;}else{__label__=186;;}
$if_then670$$if_end697$253:do{if(__label__==181){var $381=$next;var $synthflags671=(($381+4)&4294967295);var $382=HEAPU16[(($synthflags671)>>1)];var $conv672=((($382))&65535);var $or673=($conv672)|1;var $conv674=((($or673))&65535);HEAP16[(($synthflags671)>>1)]=$conv674;var $383=$next2;var $type675=(($383+15)&4294967295);var $384=HEAPU8[($type675)];var $conv676=((($384))&255);var $cmp677=((($conv676))|0)==2;if($cmp677){__label__=182;;}else{__label__=183;;}
if(__label__==182){var $385=$next;var $synthflags679=(($385+4)&4294967295);var $386=HEAPU16[(($synthflags679)>>1)];var $conv680=((($386))&65535);var $and681=($conv680)&-2;var $conv682=((($and681))&65535);HEAP16[(($synthflags679)>>1)]=$conv682;;}
var $387=$next2;var $type684=(($387+15)&4294967295);var $388=HEAPU8[($type684)];var $conv685=((($388))&255);var $cmp686=((($conv685))|0)!=2;if(!($cmp686)){__label__=186;break $if_then670$$if_end697$253;}
var $389=$next;var $ph688=(($389+8)&4294967295);var $390=HEAP32[(($ph688)>>2)];var $mnemonic=(($390)&4294967295);var $391=HEAP32[(($mnemonic)>>2)];var $cmp689=((($391))|0)==12146;if(!($cmp689)){__label__=186;break $if_then670$$if_end697$253;}
var $392=$next;var $synthflags691=(($392+4)&4294967295);var $393=HEAPU16[(($synthflags691)>>1)];var $conv692=((($393))&65535);var $and693=($conv692)&-2;var $conv694=((($and693))&65535);HEAP16[(($synthflags691)>>1)]=$conv694;;}}while(0);var $394=$min_drop;var $cmp698=((($394))|0)>0;if($cmp698){__label__=187;;}else{__label__=191;;}
$land_lhs_true699$$if_end715$261:do{if(__label__==187){var $395=$p;var $pitch2700=(($395+21)&4294967295);var $396=HEAPU8[($pitch2700)];var $conv701=((($396))&255);var $397=$p;var $pitch1702=(($397+20)&4294967295);var $398=HEAPU8[($pitch1702)];var $conv703=((($398))&255);var $sub704=((($conv701)-($conv703))&4294967295);var $399=$min_drop;var $cmp705=((($sub704))|0)<((($399))|0);if(!($cmp705)){__label__=191;break $land_lhs_true699$$if_end715$261;}
var $400=$p;var $pitch2707=(($400+21)&4294967295);var $401=HEAPU8[($pitch2707)];var $conv708=((($401))&255);var $402=$min_drop;var $sub709=((($conv708)-($402))&4294967295);$pitch1=$sub709;var $403=$pitch1;var $cmp710=((($403))|0)<0;if($cmp710){__label__=189;;}else{__label__=190;;}
if(__label__==189){$pitch1=0;;}
var $404=$pitch1;var $conv713=((($404))&255);var $405=$p;var $pitch1714=(($405+20)&4294967295);HEAP8[($pitch1714)]=$conv713;;}}while(0);var $406=$p;var $pitch1716=(($406+20)&4294967295);var $407=HEAPU8[($pitch1716)];var $conv717=((($407))&255);var $408=$p;var $pitch2718=(($408+21)&4294967295);var $409=HEAPU8[($pitch2718)];var $conv719=((($409))&255);var $410=$p;var $pitch1720=(($410+20)&4294967295);var $411=HEAPU8[($pitch1720)];var $conv721=((($411))&255);var $sub722=((($conv719)-($conv721))&4294967295);var $412=$p;var $env723=(($412+14)&4294967295);var $413=HEAPU8[($env723)];var $idxprom724=((($413))&255);var $arrayidx725=((_envelope_data+$idxprom724*4)&4294967295);var $414=HEAP32[(($arrayidx725)>>2)];var $arrayidx726=(($414+127)&4294967295);var $415=HEAPU8[($arrayidx726)];var $conv727=((($415))&255);var $mul728=((($conv727)*($sub722))&4294967295);var $div729=((((($mul728))|0)/256)|0);var $add730=((($div729)+($conv717))&4294967295);$last_pitch=$add730;$pre_sonorant=0;$pre_voiced=0;;}
var $416=$ix;var $inc732=((($416)+1)&4294967295);$ix=$inc732;var $417=$ix;var $418=HEAP32[((_n_phoneme_list)>>2)];var $cmp=((($417))|0)<((($418))|0);if($cmp){__label__=2;continue $for_body$4;}else{__label__=193;break $for_body_lr_ph$$for_end733$2;}}}}while(0);STACKTOP=__stackBase__;return;return;}
function __ZL11DoEmbedded2Pi($embix){;var __label__;var $embix_addr;var $word;$embix_addr=$embix;;while(1){var $0=$embix_addr;var $1=HEAP32[(($0)>>2)];var $inc=((($1)+1)&4294967295);HEAP32[(($0)>>2)]=$inc;var $arrayidx=((_embedded_list+$1*4)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];$word=$2;var $3=$word;var $and=($3)&31;var $cmp=((($and))|0)==2;if($cmp){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $4=$word;var $and1=($4)&127;var $5=$word;var $shr=($5)>>>8;__Z11SetEmbeddedii($and1,$shr);__Z8SetSpeedi(1);;}
var $6=$word;var $and2=($6)&128;var $cmp3=((($and2))|0)==0;if($cmp3){__label__=1;continue;}else{__label__=4;break;}};return;return;}
function __Z20LookupAccentedLetterP10TranslatorjPc($tr,$letter,$ph_buf){var __stackBase__=STACKTOP;STACKTOP+=128;_memset(__stackBase__,0,128);var __label__;var __lastLabel__=null;var $tr_addr;var $letter_addr;var $ph_buf_addr;var $accent_data;var $accent1;var $accent2;var $basic_letter;var $letter2;var $ph_letter1=__stackBase__;var $ph_letter2=__stackBase__+32;var $ph_accent1=__stackBase__+64;var $ph_accent2=__stackBase__+96;$tr_addr=$tr;$letter_addr=$letter;$ph_buf_addr=$ph_buf;$accent_data=0;$accent1=0;$accent2=0;$letter2=0;var $arrayidx=(($ph_accent2)&4294967295);HEAP8[($arrayidx)]=0;var $0=$letter_addr;var $cmp=((($0))>>>0)>=224;var $1=$letter_addr;var $cmp1=((($1))>>>0)<383;var $or_cond=($cmp)&($cmp1);var $2=$letter_addr;if($or_cond){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $sub=((($2)-224)&4294967295);var $arrayidx2=((__ZL18letter_accents_0e0+$sub*2)&4294967295);var $3=HEAPU16[(($arrayidx2)>>1)];var $conv=((($3))&65535);$accent_data=$conv;__lastLabel__=1;;}
else if(__label__==2){var $cmp3=((($2))>>>0)>=592;var $4=$letter_addr;var $cmp5=((($4))>>>0)<=680;var $or_cond1=($cmp3)&($cmp5);if($or_cond1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $5=$letter_addr;var $sub7=((($5)-592)&4294967295);var $arrayidx8=((__ZL18letter_accents_250+$sub7*2)&4294967295);var $6=HEAPU16[(($arrayidx8)>>1)];var $conv9=((($6))&65535);$accent_data=$conv9;__lastLabel__=3;;}
else if(__label__==4){var $_pr=$accent_data;__lastLabel__=4;;}}
var $7=__lastLabel__==4?$_pr:(__lastLabel__==3?$conv9:($conv));var $cmp11=((($7))|0)!=0;if($cmp11){__label__=6;;}else{__label__=24;;}
$if_then12$$if_end91$9:do{if(__label__==6){var $8=$accent_data;var $and=($8)&63;var $add=((($and)+59)&4294967295);$basic_letter=$add;var $9=$basic_letter;var $cmp13=((($9))|0)<97;if($cmp13){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $10=$basic_letter;var $sub15=((($10)-59)&4294967295);var $arrayidx16=((__ZL13non_ascii_tab+$sub15*2)&4294967295);var $11=HEAP16[(($arrayidx16)>>1)];var $conv17=(tempInt=(($11)),(tempInt>=32768?tempInt-65536:tempInt));$basic_letter=$conv17;;}
var $12=$accent_data;var $and19=($12)&32768;var $tobool=((($and19))|0)!=0;var $13=$accent_data;var $shr=($13)>>6;if($tobool){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $and21=($shr)&63;$letter2=$and21;var $14=$letter2;var $add22=((($14)+59)&4294967295);$letter2=$add22;var $15=$accent_data;var $shr23=($15)>>12;var $and24=($shr23)&7;$accent2=$and24;;}
else if(__label__==10){var $and27=($shr)&31;$accent1=$and27;var $16=$accent_data;var $shr28=($16)>>11;var $and29=($shr28)&15;$accent2=$and29;;}
var $17=$tr_addr;var $18=$accent1;var $arrayidx31=((__ZL11accents_tab+$18*8)&4294967295);var $name=(($arrayidx31)&4294967295);var $19=HEAP32[(($name)>>2)];var $arraydecay=(($ph_accent1)&4294967295);var $call=__Z6LookupP10TranslatorPKcPc($17,$19,$arraydecay);var $cmp32=((($call))|0)!=0;if(!($cmp32)){__label__=24;break $if_then12$$if_end91$9;}
var $20=$tr_addr;var $21=$basic_letter;var $arraydecay34=(($ph_letter1)&4294967295);var $call35=__ZL13LookupLetter2P10TranslatorjPc($20,$21,$arraydecay34);var $cmp36=((($call35))|0)!=0;if(!($cmp36)){__label__=24;break $if_then12$$if_end91$9;}
var $22=$accent2;var $cmp38=((($22))|0)!=0;if($cmp38){__label__=14;;}else{__label__=16;;}
$if_then39$$if_end56$20:do{if(__label__==14){var $23=$tr_addr;var $24=$accent2;var $arrayidx40=((__ZL11accents_tab+$24*8)&4294967295);var $name41=(($arrayidx40)&4294967295);var $25=HEAP32[(($name41)>>2)];var $arraydecay42=(($ph_accent2)&4294967295);var $call43=__Z6LookupP10TranslatorPKcPc($23,$25,$arraydecay42);var $26=$accent2;var $arrayidx47=((__ZL11accents_tab+$26*8)&4294967295);var $flags=(($arrayidx47+4)&4294967295);var $27=HEAP32[(($flags)>>2)];var $and48=($27)&1;var $tobool49=((($and48))|0)!=0;if(!($tobool49)){__label__=16;break $if_then39$$if_end56$20;}
var $28=$ph_buf_addr;var $arraydecay51=(($ph_accent2)&4294967295);var $call52=_strcpy($28,$arraydecay51);var $29=$ph_buf_addr;var $call53=_strlen($29);var $30=$ph_buf_addr;var $add_ptr=(($30+$call53)&4294967295);$ph_buf_addr=$add_ptr;var $arrayidx54=(($ph_accent2)&4294967295);HEAP8[($arrayidx54)]=0;;}}while(0);var $31=$letter2;var $cmp57=((($31))|0)!=0;if($cmp57){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $32=$tr_addr;var $33=$letter2;var $arraydecay59=(($ph_letter2)&4294967295);var $call60=__ZL13LookupLetter2P10TranslatorjPc($32,$33,$arraydecay59);var $34=$ph_buf_addr;var $arraydecay61=(($ph_accent1)&4294967295);var $arraydecay62=(($ph_letter1)&4294967295);var $arraydecay63=(($ph_letter2)&4294967295);var $arraydecay64=(($ph_accent2)&4294967295);var $call65=_sprintf($34,((__str297)&4294967295),allocate([$arraydecay61,0,0,0,23,0,0,0,$arraydecay62,0,0,0,6,0,0,0,$arraydecay63,0,0,0,$arraydecay64,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==18){var $35=$accent1;var $cmp67=((($35))|0)==0;if($cmp67){__label__=19;;}else{__label__=20;;}
if(__label__==19){var $36=$ph_buf_addr;var $arraydecay69=(($ph_letter1)&4294967295);var $call70=_strcpy($36,$arraydecay69);;}
else if(__label__==20){var $37=$tr_addr;var $langopts=(($37)&4294967295);var $accents=(($langopts+220)&4294967295);var $38=HEAP32[(($accents)>>2)];var $and72=($38)&1;var $tobool73=((($and72))|0)!=0;if($tobool73){__label__=22;;}else{__label__=21;;}
$if_then78$$lor_lhs_false$30:do{if(__label__==21){var $39=$accent1;var $arrayidx74=((__ZL11accents_tab+$39*8)&4294967295);var $flags75=(($arrayidx74+4)&4294967295);var $40=HEAP32[(($flags75)>>2)];var $and76=($40)&1;var $tobool77=((($and76))|0)!=0;if($tobool77){__label__=22;break $if_then78$$lor_lhs_false$30;}
var $42=$ph_buf_addr;var $arraydecay83=(($ph_letter1)&4294967295);var $arraydecay84=(($ph_accent1)&4294967295);var $call85=_sprintf($42,((__str2299)&4294967295),allocate([4,0,0,0,$arraydecay83,0,0,0,23,0,0,0,$arraydecay84,0,0,0,23,0,0,0],["i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));__label__=24;break $if_then12$$if_end91$9;}}while(0);var $41=$ph_buf_addr;var $arraydecay79=(($ph_accent1)&4294967295);var $arraydecay80=(($ph_letter1)&4294967295);var $call81=_sprintf($41,((__str1298)&4294967295),allocate([$arraydecay79,0,0,0,23,0,0,0,6,0,0,0,$arraydecay80,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}}}}while(0);STACKTOP=__stackBase__;return;return;}
function __ZL13LookupLetter2P10TranslatorjPc($tr,$letter,$ph_buf){var __stackBase__=STACKTOP;STACKTOP+=12;_memset(__stackBase__,0,12);var __label__;var $tr_addr;var $letter_addr;var $ph_buf_addr;var $len;var $single_letter=__stackBase__;$tr_addr=$tr;$letter_addr=$letter;$ph_buf_addr=$ph_buf;var $arrayidx=(($single_letter)&4294967295);HEAP8[($arrayidx)]=0;var $arrayidx1=(($single_letter+1)&4294967295);HEAP8[($arrayidx1)]=95;var $0=$letter_addr;var $arrayidx2=(($single_letter+2)&4294967295);var $call=__Z8utf8_outjPc($0,$arrayidx2);$len=$call;var $1=$len;var $add=((($1)+2)&4294967295);var $arrayidx3=(($single_letter+$add)&4294967295);HEAP8[($arrayidx3)]=32;var $2=$len;var $add4=((($2)+3)&4294967295);var $arrayidx5=(($single_letter+$add4)&4294967295);HEAP8[($arrayidx5)]=0;var $3=$tr_addr;var $arrayidx6=(($single_letter+1)&4294967295);var $4=$ph_buf_addr;var $call7=__Z6LookupP10TranslatorPKcPc($3,$arrayidx6,$4);var $cmp=((($call7))|0)==0;if($cmp){__label__=1;;}else{__label__=3;;}
$if_then$$if_end15$2:do{if(__label__==1){var $arrayidx8=(($single_letter+1)&4294967295);HEAP8[($arrayidx8)]=32;var $5=$tr_addr;var $arrayidx9=(($single_letter+2)&4294967295);var $6=$ph_buf_addr;var $call10=__Z6LookupP10TranslatorPKcPc($5,$arrayidx9,$6);var $cmp11=((($call10))|0)==0;if(!($cmp11)){__label__=3;break $if_then$$if_end15$2;}
var $7=$tr_addr;var $arrayidx13=(($single_letter+2)&4294967295);var $8=$ph_buf_addr;var $call14=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($7,$arrayidx13,$8,20,0,0,0);;}}while(0);var $9=$ph_buf_addr;var $arrayidx16=(($9)&4294967295);var $10=HEAP8[($arrayidx16)];var $conv=(tempInt=(($10)),(tempInt>=128?tempInt-256:tempInt));STACKTOP=__stackBase__;return $conv;return null;}
function __Z12LookupLetterP10TranslatorjiPci($tr,$letter,$next_byte,$ph_buf1,$control){var __stackBase__=STACKTOP;STACKTOP+=48;_memset(__stackBase__,0,48);var __label__;var $tr_addr;var $letter_addr;var $next_byte_addr;var $ph_buf1_addr;var $control_addr;var $len;var $dict_flags=__stackBase__;var $ph_buf3=__stackBase__+8;var $ptr;$tr_addr=$tr;$letter_addr=$letter;$next_byte_addr=$next_byte;$ph_buf1_addr=$ph_buf1;$control_addr=$control;var $0=$ph_buf1_addr;var $arrayidx=(($0)&4294967295);HEAP8[($arrayidx)]=0;var $1=$letter_addr;var $call=__Z8utf8_outjPc($1,((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+2)&4294967295));$len=$call;var $2=$len;var $add=((($2)+2)&4294967295);var $arrayidx1=((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+$add)&4294967295);HEAP8[($arrayidx1)]=32;var $3=$next_byte_addr;var $cmp=((($3))|0)==-1;if($cmp){__label__=1;;}else{__label__=7;;}
$if_then$$if_end19$2:do{if(__label__==1){var $4=$tr_addr;var $5=$ph_buf1_addr;var $call2=__Z6LookupP10TranslatorPKcPc($4,((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+2)&4294967295),$5);var $cmp3=((($call2))|0)!=0;if($cmp3){__label__=20;break $if_then$$if_end19$2;}
HEAP8[(((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+1)&4294967295))]=95;var $6=$tr_addr;var $arraydecay=(($ph_buf3)&4294967295);var $call5=__Z6LookupP10TranslatorPKcPc($6,((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+1)&4294967295),$arraydecay);var $cmp6=((($call5))|0)!=0;if($cmp6){__label__=20;break $if_then$$if_end19$2;}
var $7=$tr_addr;var $translator_name=(($7+280)&4294967295);var $8=HEAP32[(($translator_name)>>2)];var $cmp9=((($8))|0)==25966;if($cmp9){__label__=20;break $if_then$$if_end19$2;}
var $call12=__Z14SetTranslator2PKc(((__str52704)&4294967295));var $9=HEAP32[((_translator2)>>2)];var $arraydecay13=(($ph_buf3)&4294967295);var $call14=__Z6LookupP10TranslatorPKcPc($9,((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+2)&4294967295),$arraydecay13);var $cmp15=((($call14))|0)!=0;if($cmp15){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $10=$ph_buf1_addr;HEAP8[($10)]=21;var $nul=(($10+1)&4294967295);HEAP8[($nul)]=0;;}
var $11=HEAP32[((_voice)>>2)];var $phoneme_tab_ix=(($11+40)&4294967295);var $12=HEAP32[(($phoneme_tab_ix)>>2)];__Z18SelectPhonemeTablei($12);;}
else if(__label__==7){var $13=$letter_addr;var $cmp20=((($13))>>>0)<=32;if($cmp20){__label__=9;;}else{__label__=8;;}
$if_then22$$lor_lhs_false$11:do{if(__label__==8){var $14=$letter_addr;var $call21=_iswspace($14);var $tobool=((($call21))|0)!=0;if($tobool){__label__=9;break $if_then22$$lor_lhs_false$11;}
var $18=$next_byte_addr;var $cmp26=((($18))|0)!=32;if($cmp26){__label__=11;;}else{__label__=12;;}
if(__label__==11){$next_byte_addr=31;;}
var $19=$next_byte_addr;var $conv=((($19))&255);var $20=$len;var $add29=((($20)+3)&4294967295);var $arrayidx30=((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+$add29)&4294967295);HEAP8[($arrayidx30)]=$conv;HEAP8[(((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+1)&4294967295))]=95;var $arrayidx31=(($dict_flags+4)&4294967295);HEAP32[(($arrayidx31)>>2)]=0;$ptr=((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+1)&4294967295);var $21=$tr_addr;var $arraydecay32=(($ph_buf3)&4294967295);var $call33=__Z6LookupP10TranslatorPKcPc($21,((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+1)&4294967295),$arraydecay32);var $cmp34=((($call33))|0)==0;if($cmp34){__label__=13;;}else{__label__=15;;}
$if_then35$$if_end43$17:do{if(__label__==13){HEAP8[(((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+1)&4294967295))]=32;var $22=$tr_addr;var $arraydecay36=(($ph_buf3)&4294967295);var $call37=__Z6LookupP10TranslatorPKcPc($22,((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+2)&4294967295),$arraydecay36);var $cmp38=((($call37))|0)==0;if(!($cmp38)){__label__=15;break $if_then35$$if_end43$17;}
var $23=$tr_addr;var $arraydecay40=(($ph_buf3)&4294967295);var $call41=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($23,((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+2)&4294967295),$arraydecay40,40,0,268435456,0);;}}while(0);var $arrayidx44=(($ph_buf3)&4294967295);var $24=HEAP8[($arrayidx44)];var $conv45=(tempInt=(($24)),(tempInt>=128?tempInt-256:tempInt));var $cmp46=((($conv45))|0)==0;if($cmp46){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $25=$tr_addr;var $26=$letter_addr;var $arraydecay48=(($ph_buf3)&4294967295);__Z20LookupAccentedLetterP10TranslatorjPc($25,$26,$arraydecay48);;}
var $27=$ph_buf1_addr;var $arraydecay50=(($ph_buf3)&4294967295);var $call51=_strcpy($27,$arraydecay50);var $28=$ph_buf1_addr;var $arrayidx52=(($28)&4294967295);var $29=HEAP8[($arrayidx52)];var $conv53=(tempInt=(($29)),(tempInt>=128?tempInt-256:tempInt));var $cmp54=((($conv53))|0)==0;if($cmp54){__label__=20;break $if_then$$if_end19$2;}
var $30=$ph_buf1_addr;var $arrayidx56=(($30)&4294967295);var $31=HEAP8[($arrayidx56)];var $conv57=(tempInt=(($31)),(tempInt>=128?tempInt-256:tempInt));var $cmp58=((($conv57))|0)==21;if($cmp58){__label__=20;break $if_then$$if_end19$2;}
var $arrayidx61=(($dict_flags)&4294967295);HEAP32[(($arrayidx61)>>2)]=0;var $arrayidx62=(($dict_flags+4)&4294967295);HEAP32[(($arrayidx62)>>2)]=0;var $32=$tr_addr;var $33=$ph_buf1_addr;var $arraydecay63=(($dict_flags)&4294967295);var $34=$control_addr;var $and=($34)&1;__Z13SetWordStressP10TranslatorPcPjii($32,$33,$arraydecay63,-1,$and);__label__=20;break $if_then$$if_end19$2;}}while(0);var $15=$letter_addr;var $call23=_sprintf(((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+1)&4294967295),((__str5302)&4294967295),allocate([$15,0,0,0],["i32",0,0,0],ALLOC_STACK));var $16=$tr_addr;var $17=$ph_buf1_addr;var $call24=__Z6LookupP10TranslatorPKcPc($16,((__ZZ12LookupLetterP10TranslatorjiPciE13single_letter+1)&4294967295),$17);;}}while(0);STACKTOP=__stackBase__;return;return;}
function __Z15TranslateLetterP10TranslatorPcS1_i($tr,$word,$phonemes,$control){var __stackBase__=STACKTOP;STACKTOP+=152;_memset(__stackBase__,0,152);var __label__;var $retval;var $tr_addr;var $word_addr;var $phonemes_addr;var $control_addr;var $n_bytes;var $letter=__stackBase__;var $len;var $save_option_phonemes;var $p2;var $pbuf;var $capital=__stackBase__+4;var $ph_buf=__stackBase__+24;var $ph_buf2=__stackBase__+84;var $hexbuf=__stackBase__+144;$tr_addr=$tr;$word_addr=$word;$phonemes_addr=$phonemes;$control_addr=$control;var $arrayidx=(($ph_buf)&4294967295);HEAP8[($arrayidx)]=0;var $arrayidx1=(($capital)&4294967295);HEAP8[($arrayidx1)]=0;var $0=$word_addr;var $call=__Z7utf8_inPiPKc($letter,$0);$n_bytes=$call;var $1=HEAP32[(($letter)>>2)];var $and=($1)&1048320;var $cmp=((($and))|0)==57344;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=HEAP32[(($letter)>>2)];var $and2=($2)&255;HEAP32[(($letter)>>2)]=$and2;;}
var $3=$control_addr;var $and3=($3)&2;var $tobool=((($and3))|0)!=0;if($tobool){__label__=3;;}else{__label__=5;;}
$if_then4$$if_end10$5:do{if(__label__==3){var $4=HEAP32[(($letter)>>2)];var $call5=_iswupper($4);var $tobool6=((($call5))|0)!=0;if(!($tobool6)){__label__=5;break $if_then4$$if_end10$5;}
var $5=$tr_addr;var $arraydecay=(($capital)&4294967295);var $call8=__Z6LookupP10TranslatorPKcPc($5,((__str6303)&4294967295),$arraydecay);;}}while(0);var $6=HEAP32[(($letter)>>2)];var $call11=__Z9towlower2j($6);HEAP32[(($letter)>>2)]=$call11;var $7=$tr_addr;var $8=HEAP32[(($letter)>>2)];var $9=$n_bytes;var $10=$word_addr;var $arrayidx12=(($10+$9)&4294967295);var $11=HEAP8[($arrayidx12)];var $conv=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $arraydecay13=(($ph_buf)&4294967295);var $12=$control_addr;var $and14=($12)&1;__Z12LookupLetterP10TranslatorjiPci($7,$8,$conv,$arraydecay13,$and14);var $arrayidx15=(($ph_buf)&4294967295);var $13=HEAP8[($arrayidx15)];var $conv16=(tempInt=(($13)),(tempInt>=128?tempInt-256:tempInt));var $cmp17=((($conv16))|0)==21;if($cmp17){__label__=6;;}else{__label__=7;;}
$if_then18$$if_end21$9:do{if(__label__==6){var $14=$phonemes_addr;var $arraydecay19=(($ph_buf)&4294967295);var $call20=_strcpy($14,$arraydecay19);$retval=0;;}
else if(__label__==7){var $arrayidx22=(($ph_buf)&4294967295);var $15=HEAP8[($arrayidx22)];var $conv23=(tempInt=(($15)),(tempInt>=128?tempInt-256:tempInt));var $cmp24=((($conv23))|0)==0;if($cmp24){__label__=8;;}else{__label__=11;;}
$land_lhs_true$$if_end38$12:do{if(__label__==8){var $16=$tr_addr;var $translator_name=(($16+280)&4294967295);var $17=HEAP32[(($translator_name)>>2)];var $cmp25=((($17))|0)!=25966;if(!($cmp25)){__label__=11;break $land_lhs_true$$if_end38$12;}
var $call27=__Z14SetTranslator2PKc(((__str52704)&4294967295));var $18=HEAP32[((_option_phonemes)>>2)];$save_option_phonemes=$18;HEAP32[((_option_phonemes)>>2)]=0;var $19=HEAP32[((_translator2)>>2)];var $20=HEAP32[(($letter)>>2)];var $21=$n_bytes;var $22=$word_addr;var $arrayidx28=(($22+$21)&4294967295);var $23=HEAP8[($arrayidx28)];var $conv29=(tempInt=(($23)),(tempInt>=128?tempInt-256:tempInt));var $arraydecay30=(($ph_buf)&4294967295);var $24=$control_addr;var $and31=($24)&1;__Z12LookupLetterP10TranslatorjiPci($19,$20,$conv29,$arraydecay30,$and31);var $25=HEAP32[((_voice)>>2)];var $phoneme_tab_ix=(($25+40)&4294967295);var $26=HEAP32[(($phoneme_tab_ix)>>2)];__Z18SelectPhonemeTablei($26);var $27=$save_option_phonemes;HEAP32[((_option_phonemes)>>2)]=$27;var $arrayidx32=(($ph_buf)&4294967295);var $28=HEAP8[($arrayidx32)];var $conv33=(tempInt=(($28)),(tempInt>=128?tempInt-256:tempInt));var $cmp34=((($conv33))|0)!=0;if(!($cmp34)){__label__=11;break $land_lhs_true$$if_end38$12;}
var $29=$phonemes_addr;var $call36=_sprintf($29,((__str7304)&4294967295),allocate([21,0,0,0],["i32",0,0,0],ALLOC_STACK));$retval=0;__label__=26;break $if_then18$$if_end21$9;}}while(0);var $arrayidx39=(($ph_buf)&4294967295);var $30=HEAP8[($arrayidx39)];var $conv40=(tempInt=(($30)),(tempInt>=128?tempInt-256:tempInt));var $cmp41=((($conv40))|0)==0;if($cmp41){__label__=12;;}else{__label__=20;;}
$if_then42$$if_end73$17:do{if(__label__==12){var $31=HEAP32[(($letter)>>2)];var $call43=_iswalpha($31);var $tobool44=((($call43))|0)!=0;if($tobool44){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $32=$tr_addr;var $arraydecay46=(($ph_buf)&4294967295);var $call47=__Z6LookupP10TranslatorPKcPc($32,((__str8305)&4294967295),$arraydecay46);;}
var $arrayidx49=(($ph_buf)&4294967295);var $33=HEAP8[($arrayidx49)];var $conv50=(tempInt=(($33)),(tempInt>=128?tempInt-256:tempInt));var $cmp51=((($conv50))|0)==0;if($cmp51){__label__=15;;}else{__label__=17;;}
$land_lhs_true52$$if_end58$22:do{if(__label__==15){var $34=HEAP32[(($letter)>>2)];var $call53=_iswspace($34);var $tobool54=((($call53))|0)!=0;if($tobool54){__label__=17;break $land_lhs_true52$$if_end58$22;}
var $35=$tr_addr;var $arraydecay56=(($ph_buf)&4294967295);var $call57=__Z6LookupP10TranslatorPKcPc($35,((__str9306)&4294967295),$arraydecay56);;}}while(0);var $arrayidx59=(($ph_buf)&4294967295);var $36=HEAP8[($arrayidx59)];var $conv60=(tempInt=(($36)),(tempInt>=128?tempInt-256:tempInt));var $cmp61=((($conv60))|0)!=0;if(!($cmp61)){__label__=20;break $if_then42$$if_end73$17;}
var $arraydecay63=(($hexbuf)&4294967295);var $37=HEAP32[(($letter)>>2)];var $call64=_sprintf($arraydecay63,((__str10307)&4294967295),allocate([$37,0,0,0],["i32",0,0,0],ALLOC_STACK));var $arraydecay65=(($ph_buf)&4294967295);$pbuf=$arraydecay65;var $arraydecay66=(($hexbuf)&4294967295);$p2=$arraydecay66;var $38=$p2;var $39=HEAP8[($38)];var $conv671=(tempInt=(($39)),(tempInt>=128?tempInt-256:tempInt));var $cmp682=((($conv671))|0)!=0;if(!($cmp682)){__label__=20;break $if_then42$$if_end73$17;}
while(1){var $40=$pbuf;var $call69=_strlen($40);var $41=$pbuf;var $add_ptr=(($41+$call69)&4294967295);$pbuf=$add_ptr;var $42=$pbuf;var $incdec_ptr=(($42+1)&4294967295);$pbuf=$incdec_ptr;HEAP8[($42)]=23;var $43=$tr_addr;var $44=$p2;var $45=HEAP8[($44)];var $conv70=(tempInt=(($45)),(tempInt>=128?tempInt-256:tempInt));var $46=$pbuf;__Z12LookupLetterP10TranslatorjiPci($43,$conv70,0,$46,1);var $47=$p2;var $incdec_ptr71=(($47+1)&4294967295);$p2=$incdec_ptr71;var $48=$p2;var $49=HEAP8[($48)];var $conv67=(tempInt=(($49)),(tempInt>=128?tempInt-256:tempInt));var $cmp68=((($conv67))|0)!=0;if($cmp68){__label__=19;continue;}else{__label__=20;break $if_then42$$if_end73$17;}}}}while(0);var $50=$phonemes_addr;var $call74=_strlen($50);$len=$call74;var $51=$tr_addr;var $langopts=(($51)&4294967295);var $accents=(($langopts+220)&4294967295);var $52=HEAP32[(($accents)>>2)];var $and75=($52)&2;var $tobool76=((($and75))|0)!=0;var $arraydecay78=(($ph_buf2)&4294967295);if($tobool76){__label__=21;;}else{__label__=22;;}
if(__label__==21){var $arraydecay79=(($ph_buf)&4294967295);var $arraydecay80=(($capital)&4294967295);var $call81=_sprintf($arraydecay78,((__str11308)&4294967295),allocate([255,0,0,0,$arraydecay79,0,0,0,$arraydecay80,0,0,0],["i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==22){var $arraydecay83=(($capital)&4294967295);var $arraydecay84=(($ph_buf)&4294967295);var $call85=_sprintf($arraydecay78,((__str11308)&4294967295),allocate([255,0,0,0,$arraydecay83,0,0,0,$arraydecay84,0,0,0],["i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
var $53=$len;var $arraydecay87=(($ph_buf2)&4294967295);var $call88=_strlen($arraydecay87);var $add=((($call88)+($53))&4294967295);var $cmp89=((($add))>>>0)<160;if($cmp89){__label__=24;;}else{__label__=25;;}
if(__label__==24){var $54=$len;var $55=$phonemes_addr;var $arrayidx91=(($55+$54)&4294967295);var $arraydecay92=(($ph_buf2)&4294967295);var $call93=_strcpy($arrayidx91,$arraydecay92);;}
var $56=$n_bytes;$retval=$56;;}}while(0);var $57=$retval;STACKTOP=__stackBase__;return $57;return null;}
function __Z17SetSpellingStressP10TranslatorPcii($tr,$phonemes,$control,$n_chars){var __stackBase__=STACKTOP;STACKTOP+=160;_memset(__stackBase__,0,160);var __label__;var __lastLabel__=null;var $tr_addr;var $phonemes_addr;var $control_addr;var $n_chars_addr;var $ix;var $c;var $n_stress;var $count;var $buf=__stackBase__;$tr_addr=$tr;$phonemes_addr=$phonemes;$control_addr=$control;$n_chars_addr=$n_chars;$n_stress=0;$ix=0;var $0=$ix;var $1=$phonemes_addr;var $arrayidx4=(($1+$0)&4294967295);var $2=HEAP8[($arrayidx4)];var $conv5=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));$c=$conv5;var $cmp6=((($conv5))|0)!=0;if($cmp6){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=4;;}
$for_body$$for_end$2:do{if(__label__==1){while(1){var $3=__lastLabel__==0?$conv5:($conv);var $cmp1=((($3))|0)==6;if($cmp1){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $4=$n_stress;var $inc=((($4)+1)&4294967295);$n_stress=$inc;;}
var $5=$c;var $conv2=((($5))&255);var $6=$ix;var $arrayidx3=(($buf+$6)&4294967295);HEAP8[($arrayidx3)]=$conv2;var $7=$ix;var $inc4=((($7)+1)&4294967295);$ix=$inc4;var $8=$ix;var $9=$phonemes_addr;var $arrayidx=(($9+$8)&4294967295);var $10=HEAP8[($arrayidx)];var $conv=(tempInt=(($10)),(tempInt>=128?tempInt-256:tempInt));$c=$conv;var $cmp=((($conv))|0)!=0;if($cmp){__lastLabel__=3;__label__=1;continue;}else{__lastLabel__=3;__label__=4;break $for_body$$for_end$2;}}}}while(0);var $11=$ix;var $arrayidx5=(($buf+$11)&4294967295);HEAP8[($arrayidx5)]=0;$count=0;$ix=0;var $12=$ix;var $arrayidx71=(($buf+$12)&4294967295);var $13=HEAPU8[($arrayidx71)];var $conv82=((($13))&255);$c=$conv82;var $cmp93=((($conv82))|0)!=0;if($cmp93){__lastLabel__=4;__label__=5;;}else{__lastLabel__=4;__label__=26;;}
$for_body10$$for_end52$9:do{if(__label__==5){$for_body10$10:while(1){var $14=__lastLabel__==4?$conv82:($conv8);var $cmp11=((($14))|0)==6;if($cmp11){__lastLabel__=5;__label__=6;;}else{__lastLabel__=5;__label__=15;;}
$land_lhs_true$$if_else29$12:do{if(__label__==6){var $15=$n_chars_addr;var $cmp12=((($15))|0)>1;if($cmp12){__label__=7;;}else{__label__=14;;}
if(__label__==7){var $16=$count;var $inc14=((($16)+1)&4294967295);$count=$inc14;var $17=$tr_addr;var $langopts=(($17)&4294967295);var $spelling_stress=(($langopts+249)&4294967295);var $18=HEAP8[($spelling_stress)];var $conv15=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));var $cmp16=((($conv15))|0)==1;var $19=$count;if($cmp16){__label__=8;;}else{__label__=10;;}
if(__label__==8){var $cmp18=((($19))|0)>1;if(!($cmp18)){__label__=24;break $land_lhs_true$$if_else29$12;}
$c=5;__label__=24;break $land_lhs_true$$if_else29$12;}
else if(__label__==10){var $20=$n_stress;var $cmp21=((($19))|0)!=((($20))|0);if(!($cmp21)){__label__=24;break $land_lhs_true$$if_else29$12;}
var $21=$count;var $rem=((($21))|0)%3;var $cmp23=((($rem))|0)!=0;if($cmp23){__label__=13;;}else{__label__=12;;}
if(__label__==12){var $22=$count;var $23=$n_stress;var $sub=((($23)-1)&4294967295);var $cmp24=((($22))|0)==((($sub))|0);if(!($cmp24)){__label__=24;break $land_lhs_true$$if_else29$12;}}
$c=5;__label__=24;break $land_lhs_true$$if_else29$12;}}
else if(__label__==14){var $_pr=$c;__lastLabel__=14;__label__=15;break $land_lhs_true$$if_else29$12;}}}while(0);$if_end48$$if_else29$25:do{if(__label__==15){var $24=__lastLabel__==14?$_pr:($14);var $cmp30=((($24))|0)==255;if(!($cmp30)){__label__=24;break $if_end48$$if_else29$25;}
var $25=$control_addr;var $cmp32=((($25))|0)<2;if($cmp32){__label__=25;break $if_end48$$if_else29$25;}
var $26=$ix;var $cmp34=((($26))|0)==0;if($cmp34){__label__=25;break $if_end48$$if_else29$25;}
var $27=$control_addr;var $cmp37=((($27))|0)==4;if($cmp37){__label__=19;;}else{__label__=20;;}
if(__label__==19){$c=9;;}
var $28=$count;var $rem40=((($28))|0)%3;var $cmp41=((($rem40))|0)==0;if($cmp41){__label__=22;;}else{__label__=21;;}
$if_then44$$lor_lhs_false42$33:do{if(__label__==21){var $29=$control_addr;var $cmp43=((($29))|0)>2;if($cmp43){__label__=22;break $if_then44$$lor_lhs_false42$33;}
$c=23;__label__=24;break $if_end48$$if_else29$25;}}while(0);$c=11;__label__=24;break $if_end48$$if_else29$25;}}while(0);if(__label__==24){var $30=$c;var $conv49=((($30))&255);var $31=$phonemes_addr;var $incdec_ptr=(($31+1)&4294967295);$phonemes_addr=$incdec_ptr;HEAP8[($31)]=$conv49;;}
var $32=$ix;var $inc51=((($32)+1)&4294967295);$ix=$inc51;var $33=$ix;var $arrayidx7=(($buf+$33)&4294967295);var $34=HEAPU8[($arrayidx7)];var $conv8=((($34))&255);$c=$conv8;var $cmp9=((($conv8))|0)!=0;if($cmp9){__lastLabel__=25;__label__=5;continue $for_body10$10;}else{__lastLabel__=25;__label__=26;break $for_body10$$for_end52$9;}}}}while(0);var $35=$control_addr;var $cmp53=((($35))|0)>=2;if($cmp53){__label__=27;;}else{__label__=28;;}
if(__label__==27){var $36=$phonemes_addr;var $incdec_ptr55=(($36+1)&4294967295);$phonemes_addr=$incdec_ptr55;HEAP8[($36)]=11;;}
var $37=$phonemes_addr;HEAP8[($37)]=0;STACKTOP=__stackBase__;return;return;}
function __Z14TranslateRomanP10TranslatorPcS1_P8WORD_TAB($tr,$word,$ph_out,$wtab){var __stackBase__=STACKTOP;STACKTOP+=200;_memset(__stackBase__,0,200);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $word_addr;var $ph_out_addr;var $wtab_addr;var $c;var $p;var $p2;var $acc;var $prev;var $value;var $subtract;var $repeat;var $n_digits;var $word_start;var $num_control;var $flags=__stackBase__;var $ph_roman=__stackBase__+8;var $number_chars=__stackBase__+40;$tr_addr=$tr;$word_addr=$word;$ph_out_addr=$ph_out;$wtab_addr=$wtab;$repeat=0;$n_digits=0;$num_control=0;$acc=0;$prev=0;$subtract=32767;var $0=$ph_out_addr;var $arrayidx=(($0)&4294967295);HEAP8[($arrayidx)]=0;var $arrayidx1=(($flags)&4294967295);HEAP32[(($arrayidx1)>>2)]=0;var $arrayidx2=(($flags+4)&4294967295);HEAP32[(($arrayidx2)>>2)]=0;var $1=$tr_addr;var $langopts=(($1)&4294967295);var $numbers=(($langopts+184)&4294967295);var $2=HEAP32[(($numbers)>>2)];var $and=($2)&33554432;var $tobool=((($and))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
$land_lhs_true$$lor_lhs_false$2:do{if(__label__==1){var $3=$wtab_addr;var $arrayidx3=(($3)&4294967295);var $flags4=(($arrayidx3)&4294967295);var $4=HEAP32[(($flags4)>>2)];var $and5=($4)&1;var $tobool6=((($and5))|0)!=0;if($tobool6){__label__=2;break $land_lhs_true$$lor_lhs_false$2;}else{__label__=3;break $land_lhs_true$$lor_lhs_false$2;}}}while(0);$lor_lhs_false$$if_then$4:do{if(__label__==2){var $5=$word_addr;var $arrayidx7=(($5+-2)&4294967295);var $6=HEAP8[($arrayidx7)];var $conv=(tempInt=(($6)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp=((($conv)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call=((($isdigit))&1);var $tobool8=((($call))|0)!=0;if($tobool8){__label__=3;break $lor_lhs_false$$if_then$4;}
var $7=$word_addr;$word_start=$7;;$while_cond$7:while(1){var $8=$word_addr;var $incdec_ptr=(($8+1)&4294967295);$word_addr=$incdec_ptr;var $9=HEAP8[($8)];var $conv9=(tempInt=(($9)),(tempInt>=128?tempInt-256:tempInt));$c=$conv9;var $cmp=((($conv9))|0)!=32;if(!($cmp)){__label__=25;break $while_cond$7;}
var $10=$c;var $memchr=_memchr(((__str12309)&4294967295),$10,8);$p2=$memchr;var $cmp11=((($memchr))|0)==0;if($cmp11){__label__=7;break $while_cond$7;}
var $11=$p2;var $sub_ptr_lhs_cast=($11);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-(__str12309))&4294967295);var $arrayidx14=((__ZZ14TranslateRomanP10TranslatorPcS1_P8WORD_TABE12roman_values+$sub_ptr_sub*4)&4294967295);var $12=HEAP32[(($arrayidx14)>>2)];$value=$12;var $13=$value;var $14=$prev;var $cmp15=((($13))|0)==((($14))|0);if($cmp15){__label__=9;;}else{__label__=11;;}
if(__label__==9){var $15=$repeat;var $inc=((($15)+1)&4294967295);$repeat=$inc;var $16=$repeat;var $cmp17=((($16))|0)>=3;if($cmp17){__label__=10;break $while_cond$7;}}
else if(__label__==11){$repeat=0;;}
var $17=$prev;var $cmp21=((($17))|0)>1;var $18=$prev;var $cmp23=((($18))|0)!=10;var $or_cond=($cmp21)&($cmp23);var $19=$prev;var $cmp25=((($19))|0)!=100;var $or_cond1=($or_cond)&($cmp25);if($or_cond1){__lastLabel__=12;__label__=13;;}else{__lastLabel__=12;__label__=15;;}
if(__label__==13){var $20=$value;var $21=$prev;var $cmp27=((($20))|0)>=((($21))|0);if($cmp27){__lastLabel__=13;__label__=14;break $while_cond$7;}else{__lastLabel__=13;;}}
var $22=__lastLabel__==13?$21:($19);var $cmp31=((($22))|0)!=0;if($cmp31){__label__=16;;}else{__label__=21;;}
$land_lhs_true32$$if_else40$18:do{if(__label__==16){var $23=$prev;var $24=$value;var $cmp33=((($23))|0)<((($24))|0);if(!($cmp33)){__label__=21;break $land_lhs_true32$$if_else40$18;}
var $25=$acc;var $rem=((($25))|0)%10;var $cmp35=((($rem))|0)!=0;if($cmp35){__label__=19;break $while_cond$7;}
var $26=$prev;var $mul=((($26)*10)&4294967295);var $27=$value;var $cmp37=((($mul))|0)<((($27))|0);if($cmp37){__label__=19;break $while_cond$7;}
var $28=$prev;$subtract=$28;var $29=$subtract;var $30=$value;var $sub=((($30)-($29))&4294967295);$value=$sub;__label__=24;break $land_lhs_true32$$if_else40$18;}}while(0);if(__label__==21){var $31=$value;var $32=$subtract;var $cmp41=((($31))|0)>=((($32))|0);if($cmp41){__label__=22;break $while_cond$7;}
var $33=$prev;var $34=$acc;var $add=((($34)+($33))&4294967295);$acc=$add;;}
var $35=$value;$prev=$35;var $36=$n_digits;var $inc46=((($36)+1)&4294967295);$n_digits=$inc46;__label__=5;continue $while_cond$7;}
if(__label__==25){var $37=$word_addr;var $arrayidx47=(($37)&4294967295);var $38=HEAP8[($arrayidx47)];var $conv48=(tempInt=(($38)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp2=((($conv48)-48)&4294967295);var $isdigit3=((($isdigittmp2))>>>0)<10;var $call49=((($isdigit3))&1);var $tobool50=((($call49))|0)!=0;if($tobool50){__label__=26;;}else{__label__=27;;}
if(__label__==26){$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}
else if(__label__==27){var $39=$prev;var $40=$acc;var $add53=((($40)+($39))&4294967295);$acc=$add53;var $41=$acc;var $42=$tr_addr;var $langopts54=(($42)&4294967295);var $min_roman=(($langopts54+200)&4294967295);var $43=HEAP32[(($min_roman)>>2)];var $cmp55=((($41))|0)<((($43))|0);if($cmp55){__label__=28;;}else{__label__=29;;}
if(__label__==28){$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}
else if(__label__==29){var $44=$acc;var $45=$tr_addr;var $langopts58=(($45)&4294967295);var $max_roman=(($langopts58+196)&4294967295);var $46=HEAP32[(($max_roman)>>2)];var $cmp59=((($44))|0)>((($46))|0);if($cmp59){__label__=30;;}else{__label__=31;;}
if(__label__==30){$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}
else if(__label__==31){var $47=$tr_addr;var $arraydecay=(($ph_roman)&4294967295);var $call62=__Z6LookupP10TranslatorPKcPc($47,((__str13310)&4294967295),$arraydecay);var $48=$ph_out_addr;var $arrayidx63=(($48)&4294967295);$p=$arrayidx63;var $49=$tr_addr;var $langopts64=(($49)&4294967295);var $numbers65=(($langopts64+184)&4294967295);var $50=HEAP32[(($numbers65)>>2)];var $and66=($50)&67108864;var $cmp67=((($and66))|0)==0;if($cmp67){__label__=32;;}else{__label__=33;;}
if(__label__==32){var $51=$ph_out_addr;var $arraydecay69=(($ph_roman)&4294967295);var $call70=_strcpy($51,$arraydecay69);var $arraydecay71=(($ph_roman)&4294967295);var $call72=_strlen($arraydecay71);var $52=$ph_out_addr;var $arrayidx73=(($52+$call72)&4294967295);$p=$arrayidx73;;}
var $arraydecay75=(($number_chars)&4294967295);var $53=$acc;var $call76=_sprintf($arraydecay75,((__str14311)&4294967295),allocate([$53,0,0,0],["i32",0,0,0],ALLOC_STACK));var $54=$word_addr;var $arrayidx77=(($54)&4294967295);var $55=HEAP8[($arrayidx77)];var $conv78=(tempInt=(($55)),(tempInt>=128?tempInt-256:tempInt));var $cmp79=((($conv78))|0)==46;if($cmp79){__label__=34;;}else{__label__=35;;}
if(__label__==34){$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}
else if(__label__==35){var $56=$tr_addr;var $57=$word_start;var $58=$word_addr;var $59=$wtab_addr;var $call82=__ZL15CheckDotOrdinalP10TranslatorPcS1_P8WORD_TABi($56,$57,$58,$59,1);var $tobool83=((($call82))|0)!=0;if($tobool83){__label__=36;;}else{__label__=37;;}
if(__label__==36){var $60=$wtab_addr;var $arrayidx85=(($60)&4294967295);var $flags86=(($arrayidx85)&4294967295);var $61=HEAP32[(($flags86)>>2)];var $or=($61)|32768;HEAP32[(($flags86)>>2)]=$or;;}
var $62=$tr_addr;var $langopts88=(($62)&4294967295);var $numbers89=(($langopts88+184)&4294967295);var $63=HEAP32[(($numbers89)>>2)];var $and90=($63)&134217728;var $tobool91=((($and90))|0)!=0;if($tobool91){__label__=38;;}else{__label__=45;;}
$if_then92$$if_end117$47:do{if(__label__==38){var $64=$tr_addr;var $translator_name=(($64+280)&4294967295);var $65=HEAP32[(($translator_name)>>2)];var $cmp93=((($65))|0)==26741;var $66=$wtab_addr;var $arrayidx95=(($66)&4294967295);var $flags96=(($arrayidx95)&4294967295);var $67=HEAP32[(($flags96)>>2)];if($cmp93){__label__=39;;}else{__label__=44;;}
if(__label__==39){var $and97=($67)&32768;var $tobool98=((($and97))|0)!=0;if($tobool98){__label__=45;break $if_then92$$if_end117$47;}
var $68=$wtab_addr;var $arrayidx100=(($68)&4294967295);var $flags101=(($arrayidx100)&4294967295);var $69=HEAP32[(($flags101)>>2)];var $and102=($69)&16384;var $tobool103=((($and102))|0)!=0;if($tobool103){__label__=41;;}else{__label__=43;;}
$land_lhs_true104$$if_else109$52:do{if(__label__==41){var $70=$word_addr;var $71=$acc;var $call105=__ZL11hu_number_ePKcii($70,0,$71);var $tobool106=((($call105))|0)!=0;if(!($tobool106)){__label__=43;break $land_lhs_true104$$if_else109$52;}
var $72=$num_control;var $or108=($72)|1;$num_control=$or108;__label__=45;break $if_then92$$if_end117$47;}}while(0);$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}
else if(__label__==44){var $or115=($67)|32768;HEAP32[(($flags96)>>2)]=$or115;;}}}while(0);var $73=$tr_addr;var $prev_dict_flags=(($73+8320)&4294967295);HEAP32[(($prev_dict_flags)>>2)]=0;var $74=$tr_addr;var $arrayidx118=(($number_chars+2)&4294967295);var $75=$p;var $arraydecay119=(($flags)&4294967295);var $76=$wtab_addr;var $77=$num_control;var $call120=__Z15TranslateNumberP10TranslatorPcS1_PjP8WORD_TABi($74,$arrayidx118,$75,$arraydecay119,$76,$77);var $78=$tr_addr;var $langopts121=(($78)&4294967295);var $numbers122=(($langopts121+184)&4294967295);var $79=HEAP32[(($numbers122)>>2)];var $and123=($79)&67108864;var $tobool124=((($and123))|0)!=0;if($tobool124){__label__=46;;}else{__label__=47;;}
if(__label__==46){var $80=$ph_out_addr;var $arraydecay126=(($ph_roman)&4294967295);var $call127=_strcat($80,$arraydecay126);;}
$retval=1;__label__=48;break $lor_lhs_false$$if_then$4;}}}}}
else if(__label__==7){$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}
else if(__label__==10){$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}
else if(__label__==14){$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}
else if(__label__==19){$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}
else if(__label__==22){$retval=0;__label__=48;break $lor_lhs_false$$if_then$4;}}}while(0);if(__label__==3){$retval=0;;}
var $81=$retval;STACKTOP=__stackBase__;return $81;return null;}
function __ZL15CheckDotOrdinalP10TranslatorPcS1_P8WORD_TABi($tr,$word,$word_end,$wtab,$roman){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $tr_addr;var $word_addr;var $word_end_addr;var $wtab_addr;var $roman_addr;var $ordinal;var $c2=__stackBase__;var $nextflags;$tr_addr=$tr;$word_addr=$word;$word_end_addr=$word_end;$wtab_addr=$wtab;$roman_addr=$roman;$ordinal=0;var $0=$tr_addr;var $langopts=(($0)&4294967295);var $numbers=(($langopts+184)&4294967295);var $1=HEAP32[(($numbers)>>2)];var $and=($1)&65536;var $tobool=((($and))|0)!=0;if($tobool){__label__=1;;}else{__label__=32;;}
$land_lhs_true$$if_end92$2:do{if(__label__==1){var $2=$word_end_addr;var $arrayidx=(($2)&4294967295);var $3=HEAP8[($arrayidx)];var $conv=(tempInt=(($3)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)==46;if($cmp){__label__=3;;}else{__label__=2;;}
if(__label__==2){var $4=$wtab_addr;var $arrayidx1=(($4)&4294967295);var $flags=(($arrayidx1)&4294967295);var $5=HEAP32[(($flags)>>2)];var $and2=($5)&65536;var $tobool3=((($and2))|0)!=0;if(!($tobool3)){__label__=32;break $land_lhs_true$$if_end92$2;}}
var $6=$wtab_addr;var $arrayidx5=(($6+12)&4294967295);var $flags6=(($arrayidx5)&4294967295);var $7=HEAP32[(($flags6)>>2)];var $and7=($7)&256;var $tobool8=((($and7))|0)!=0;if($tobool8){__label__=32;break $land_lhs_true$$if_end92$2;}
var $8=$roman_addr;var $tobool9=((($8))|0)!=0;if($tobool9){__label__=6;;}else{__label__=5;;}
if(__label__==5){var $9=$wtab_addr;var $arrayidx11=(($9+12)&4294967295);var $flags12=(($arrayidx11)&4294967295);var $10=HEAP32[(($flags12)>>2)];var $and13=($10)&2;var $tobool14=((($and13))|0)!=0;if($tobool14){__label__=32;break $land_lhs_true$$if_end92$2;}}
var $11=$word_end_addr;var $arrayidx16=(($11)&4294967295);var $12=HEAP8[($arrayidx16)];var $conv17=(tempInt=(($12)),(tempInt>=128?tempInt-256:tempInt));var $cmp18=((($conv17))|0)==46;var $13=$word_end_addr;if($cmp18){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $arrayidx20=(($13+2)&4294967295);var $call=__Z7utf8_inPiPKc($c2,$arrayidx20);;}
else if(__label__==8){var $arrayidx21=(($13)&4294967295);var $call22=__Z7utf8_inPiPKc($c2,$arrayidx21);;}
var $14=$word_end_addr;var $arrayidx23=(($14)&4294967295);var $15=HEAP8[($arrayidx23)];var $conv24=(tempInt=(($15)),(tempInt>=128?tempInt-256:tempInt));var $cmp25=((($conv24))|0)!=0;if(!($cmp25)){__label__=32;break $land_lhs_true$$if_end92$2;}
var $16=$word_end_addr;var $arrayidx27=(($16+1)&4294967295);var $17=HEAP8[($arrayidx27)];var $conv28=(tempInt=(($17)),(tempInt>=128?tempInt-256:tempInt));var $cmp29=((($conv28))|0)!=0;if(!($cmp29)){__label__=32;break $land_lhs_true$$if_end92$2;}
var $18=HEAP32[(($c2)>>2)];var $cmp31=((($18))|0)==0;if($cmp31){__label__=14;;}else{__label__=12;;}
$if_then40$$lor_lhs_false32$17:do{if(__label__==12){var $19=$wtab_addr;var $arrayidx33=(($19)&4294967295);var $flags34=(($arrayidx33)&4294967295);var $20=HEAP32[(($flags34)>>2)];var $and35=($20)&131072;var $tobool36=((($and35))|0)!=0;if($tobool36){__label__=14;break $if_then40$$lor_lhs_false32$17;}
var $21=HEAP32[(($c2)>>2)];var $call38=__Z7IsAlphaj($21);var $tobool39=((($call38))|0)!=0;if(!($tobool39)){__label__=32;break $land_lhs_true$$if_end92$2;}}}while(0);$ordinal=2;var $22=$word_end_addr;var $arrayidx41=(($22)&4294967295);var $23=HEAP8[($arrayidx41)];var $conv42=(tempInt=(($23)),(tempInt>=128?tempInt-256:tempInt));var $cmp43=((($conv42))|0)==46;if($cmp43){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $24=$word_end_addr;var $arrayidx45=(($24)&4294967295);HEAP8[($arrayidx45)]=32;;}
var $25=$roman_addr;var $cmp47=((($25))|0)==0;if(!($cmp47)){__label__=32;break $land_lhs_true$$if_end92$2;}
var $26=$tr_addr;var $translator_name=(($26+280)&4294967295);var $27=HEAP32[(($translator_name)>>2)];var $cmp49=((($27))|0)==26741;if(!($cmp49)){__label__=32;break $land_lhs_true$$if_end92$2;}
$nextflags=0;var $28=HEAP32[(($c2)>>2)];var $call51=__Z7IsAlphaj($28);var $tobool52=((($call51))|0)!=0;if($tobool52){__label__=19;;}else{__label__=20;;}
if(__label__==19){var $29=$tr_addr;var $30=$word_end_addr;var $arrayidx54=(($30+2)&4294967295);var $call55=__Z13TranslateWordP10TranslatorPciP8WORD_TAB($29,$arrayidx54,0,0);$nextflags=$call55;;}
var $31=$tr_addr;var $prev_dict_flags=(($31+8320)&4294967295);var $32=HEAP32[(($prev_dict_flags)>>2)];var $and57=($32)&1048576;var $tobool58=((($and57))|0)!=0;if($tobool58){__label__=21;;}else{__label__=25;;}
$land_lhs_true59$$if_end70$29:do{if(__label__==21){var $33=HEAP32[(($c2)>>2)];var $cmp60=((($33))|0)==0;if($cmp60){__label__=24;;}else{__label__=22;;}
$if_then69$$lor_lhs_false61$31:do{if(__label__==22){var $34=$wtab_addr;var $arrayidx62=(($34)&4294967295);var $flags63=(($arrayidx62)&4294967295);var $35=HEAP32[(($flags63)>>2)];var $and64=($35)&131072;var $tobool65=((($and64))|0)!=0;if($tobool65){__label__=24;break $if_then69$$lor_lhs_false61$31;}
var $36=HEAP32[(($c2)>>2)];var $call67=_iswdigit($36);var $tobool68=((($call67))|0)!=0;if(!($tobool68)){__label__=25;break $land_lhs_true59$$if_end70$29;}}}while(0);$ordinal=0;;}}while(0);var $37=$nextflags;var $and71=($37)&1048576;var $tobool72=((($and71))|0)!=0;if($tobool72){__label__=26;;}else{__label__=27;;}
if(__label__==26){$ordinal=0;;}
var $38=$nextflags;var $and75=($38)&4194304;var $tobool76=((($and75))|0)!=0;if(!($tobool76)){__label__=32;break $land_lhs_true$$if_end92$2;}
var $39=$word_addr;var $arrayidx78=(($39+-2)&4294967295);var $40=HEAP8[($arrayidx78)];var $conv79=(tempInt=(($40)),(tempInt>=128?tempInt-256:tempInt));var $cmp80=((($conv79))|0)==45;if($cmp80){__label__=29;;}else{__label__=30;;}
if(__label__==29){$ordinal=0;;}
var $41=$tr_addr;var $prev_dict_flags83=(($41+8320)&4294967295);var $42=HEAP32[(($prev_dict_flags83)>>2)];var $and84=($42)&5242880;var $tobool85=((($and84))|0)!=0;if(!($tobool85)){__label__=32;break $land_lhs_true$$if_end92$2;}
$ordinal=34;;}}while(0);var $43=$ordinal;STACKTOP=__stackBase__;return $43;return null;}
function __ZL11hu_number_ePKcii($word,$thousandplex,$value){;var __label__;var $retval;var $word_addr;var $thousandplex_addr;var $value_addr;$word_addr=$word;$thousandplex_addr=$thousandplex;$value_addr=$value;var $0=$word_addr;var $arrayidx=(($0)&4294967295);var $1=HEAP8[($arrayidx)];var $conv=(tempInt=(($1)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)==97;if($cmp){__label__=2;;}else{__label__=1;;}
$if_then$$lor_lhs_false$2:do{if(__label__==1){var $2=$word_addr;var $arrayidx1=(($2)&4294967295);var $3=HEAP8[($arrayidx1)];var $conv2=(tempInt=(($3)),(tempInt>=128?tempInt-256:tempInt));var $cmp3=((($conv2))|0)==101;if($cmp3){__label__=2;break $if_then$$lor_lhs_false$2;}
$retval=0;__label__=13;break $if_then$$lor_lhs_false$2;}}while(0);$if_then$$return$5:do{if(__label__==2){var $4=$word_addr;var $arrayidx4=(($4+1)&4294967295);var $5=HEAP8[($arrayidx4)];var $conv5=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $cmp6=((($conv5))|0)==32;if($cmp6){__label__=6;;}else{__label__=3;;}
$if_then18$$lor_lhs_false7$7:do{if(__label__==3){var $6=$word_addr;var $arrayidx8=(($6+1)&4294967295);var $7=HEAP8[($arrayidx8)];var $conv9=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $cmp10=((($conv9))|0)==122;if($cmp10){__label__=6;break $if_then18$$lor_lhs_false7$7;}
var $8=$word_addr;var $arrayidx12=(($8+1)&4294967295);var $9=HEAP8[($arrayidx12)];var $conv13=(tempInt=(($9)),(tempInt>=128?tempInt-256:tempInt));var $cmp14=((($conv13))|0)==116;if($cmp14){__label__=5;;}else{__label__=7;;}
if(__label__==5){var $10=$word_addr;var $arrayidx15=(($10+2)&4294967295);var $11=HEAP8[($arrayidx15)];var $conv16=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $cmp17=((($conv16))|0)==116;if($cmp17){__label__=6;break $if_then18$$lor_lhs_false7$7;}}
var $12=$thousandplex_addr;var $cmp19=((($12))|0)==1;if($cmp19){__label__=9;;}else{__label__=8;;}
$land_lhs_true22$$lor_lhs_false20$13:do{if(__label__==8){var $13=$value_addr;var $rem=((($13))|0)%1000;var $cmp21=((($rem))|0)==0;if($cmp21){__label__=9;break $land_lhs_true22$$lor_lhs_false20$13;}else{__label__=11;break $land_lhs_true22$$lor_lhs_false20$13;}}}while(0);$land_lhs_true22$$if_end27$15:do{if(__label__==9){var $14=$word_addr;var $arrayidx23=(($14+1)&4294967295);var $15=HEAP8[($arrayidx23)];var $conv24=(tempInt=(($15)),(tempInt>=128?tempInt-256:tempInt));var $cmp25=((($conv24))|0)==108;if(!($cmp25)){__label__=11;break $land_lhs_true22$$if_end27$15;}
$retval=0;__label__=13;break $if_then$$return$5;}}while(0);$retval=1;__label__=13;break $if_then$$return$5;}}while(0);$retval=0;;}}while(0);var $16=$retval;;return $16;return null;}
function __Z15TranslateNumberP10TranslatorPcS1_PjP8WORD_TABi($tr,$word1,$ph_out,$flags,$wtab,$control){;var __label__;var $retval;var $tr_addr;var $word1_addr;var $ph_out_addr;var $flags_addr;var $wtab_addr;var $control_addr;$tr_addr=$tr;$word1_addr=$word1;$ph_out_addr=$ph_out;$flags_addr=$flags;$wtab_addr=$wtab;$control_addr=$control;var $0=HEAP32[((_option_sayas)>>2)];var $cmp=((($0))|0)==193;if($cmp){__label__=2;;}else{__label__=1;;}
$if_then$$lor_lhs_false$2:do{if(__label__==1){var $1=$wtab_addr;var $arrayidx=(($1)&4294967295);var $flags1=(($arrayidx)&4294967295);var $2=HEAP32[(($flags1)>>2)];var $and=($2)&524288;var $tobool=((($and))|0)!=0;if($tobool){__label__=2;break $if_then$$lor_lhs_false$2;}
var $3=$tr_addr;var $langopts=(($3)&4294967295);var $numbers=(($langopts+184)&4294967295);var $4=HEAP32[(($numbers)>>2)];var $cmp2=((($4))|0)!=0;if($cmp2){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $5=$tr_addr;var $6=$word1_addr;var $7=$ph_out_addr;var $8=$flags_addr;var $9=$wtab_addr;var $10=$control_addr;var $call=__ZL17TranslateNumber_1P10TranslatorPcS1_PjP8WORD_TABi($5,$6,$7,$8,$9,$10);$retval=$call;__label__=6;break $if_then$$lor_lhs_false$2;}
else if(__label__==5){$retval=0;__label__=6;break $if_then$$lor_lhs_false$2;}}}while(0);if(__label__==2){$retval=0;;}
var $11=$retval;;return $11;return null;}
function __ZL17TranslateNumber_1P10TranslatorPcS1_PjP8WORD_TABi($tr,$word,$ph_out,$flags,$wtab,$control){var __stackBase__=STACKTOP;STACKTOP+=560;_memset(__stackBase__,0,560);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $word_addr;var $ph_out_addr;var $flags_addr;var $wtab_addr;var $control_addr;var $n_digits;var $value;var $ix;var $digix;var $c;var $suppress_null;var $decimal_point;var $thousandplex;var $thousands_exact;var $thousands_inc;var $prev_thousands;var $ordinal;var $dot_ordinal;var $this_value;var $decimal_count;var $max_decimal_count;var $decimal_mode;var $hyphen;var $suffix_ix;var $skipwords;var $p=__stackBase__;var $string=__stackBase__+4;var $buf1=__stackBase__+24;var $ph_append=__stackBase__+124;var $ph_buf=__stackBase__+176;var $ph_buf2=__stackBase__+376;var $ph_zeros=__stackBase__+428;var $suffix=__stackBase__+480;var $buf_digit_lookup=__stackBase__+500;var $p2=__stackBase__+552;var $next_char=__stackBase__+556;var $p562;$tr_addr=$tr;$word_addr=$word;$ph_out_addr=$ph_out;$flags_addr=$flags;$wtab_addr=$wtab;$control_addr=$control;$suppress_null=0;$decimal_point=0;$thousandplex=0;$thousands_exact=1;$thousands_inc=0;$prev_thousands=0;$ordinal=0;$skipwords=0;var $0=$flags_addr;HEAP32[(($0)>>2)]=0;HEAP32[((__ZL14n_digit_lookup)>>2)]=0;var $arrayidx=(($buf_digit_lookup)&4294967295);HEAP8[($arrayidx)]=0;var $arraydecay=(($buf_digit_lookup)&4294967295);HEAP32[((__ZL12digit_lookup)>>2)]=$arraydecay;var $1=$control_addr;HEAP32[((__ZL14number_control)>>2)]=$1;$ix=0;var $2=$ix;var $3=$word_addr;var $arrayidx167=(($3+$2)&4294967295);var $4=HEAP8[($arrayidx167)];var $conv68=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp69=((($conv68)-48)&4294967295);var $isdigit70=((($isdigittmp69))>>>0)<10;var $5=$ix;if($isdigit70){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=2;;}
$for_inc$$for_end$2:do{if(__label__==1){while(1){var $6=__lastLabel__==1?$10:($5);var $inc=((($6)+1)&4294967295);$ix=$inc;var $7=$ix;var $8=$word_addr;var $arrayidx1=(($8+$7)&4294967295);var $9=HEAP8[($arrayidx1)];var $conv=(tempInt=(($9)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp=((($conv)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call=((($isdigit))&1);var $tobool=((($call))|0)!=0;var $10=$ix;if($tobool){__lastLabel__=1;__label__=1;continue;}else{__lastLabel__=1;__label__=2;break $for_inc$$for_end$2;}}}}while(0);var $_lcssa65=__lastLabel__==0?$5:($10);$n_digits=$_lcssa65;var $11=$word_addr;var $call2=_atoi($11);$this_value=$call2;$value=$call2;var $cmp=((($_lcssa65))|0)==3;if($cmp){__label__=3;;}else{__label__=6;;}
$land_lhs_true$$if_else$6:do{if(__label__==3){var $12=$word_addr;var $arrayidx3=(($12+-2)&4294967295);var $13=HEAP8[($arrayidx3)];var $conv4=(tempInt=(($13)),(tempInt>=128?tempInt-256:tempInt));var $14=$tr_addr;var $langopts=(($14)&4294967295);var $thousands_sep=(($langopts+204)&4294967295);var $15=HEAP32[(($thousands_sep)>>2)];var $cmp5=((($conv4))|0)==((($15))|0);if(!($cmp5)){__label__=6;break $land_lhs_true$$if_else$6;}
var $16=$word_addr;var $arrayidx7=(($16+-3)&4294967295);var $17=HEAP8[($arrayidx7)];var $conv8=(tempInt=(($17)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp6=((($conv8)-48)&4294967295);var $isdigit7=((($isdigittmp6))>>>0)<10;var $call9=((($isdigit7))&1);var $tobool10=((($call9))|0)!=0;if(!($tobool10)){__label__=6;break $land_lhs_true$$if_else$6;}
$prev_thousands=1;__label__=14;break $land_lhs_true$$if_else$6;}}while(0);$if_end32$$if_else$10:do{if(__label__==6){var $18=$tr_addr;var $langopts11=(($18)&4294967295);var $thousands_sep12=(($langopts11+204)&4294967295);var $19=HEAP32[(($thousands_sep12)>>2)];var $cmp13=((($19))|0)==32;if($cmp13){__label__=8;;}else{__label__=7;;}
$if_then16$$lor_lhs_false$12:do{if(__label__==7){var $20=$tr_addr;var $langopts14=(($20)&4294967295);var $numbers=(($langopts14+184)&4294967295);var $21=HEAP32[(($numbers)>>2)];var $and=($21)&4096;var $tobool15=((($and))|0)!=0;if($tobool15){__label__=8;break $if_then16$$lor_lhs_false$12;}else{__label__=12;break $if_then16$$lor_lhs_false$12;}}}while(0);$if_then16$$if_end29$14:do{if(__label__==8){var $22=$n_digits;var $cmp17=((($22))|0)==3;if(!($cmp17)){__label__=12;break $if_then16$$if_end29$14;}
var $23=$wtab_addr;var $flags19=(($23)&4294967295);var $24=HEAP32[(($flags19)>>2)];var $and20=($24)&262144;var $tobool21=((($and20))|0)!=0;if($tobool21){__label__=12;break $if_then16$$if_end29$14;}
var $25=$word_addr;var $arrayidx23=(($25+-2)&4294967295);var $26=HEAP8[($arrayidx23)];var $conv24=(tempInt=(($26)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp8=((($conv24)-48)&4294967295);var $isdigit9=((($isdigittmp8))>>>0)<10;var $call25=((($isdigit9))&1);var $tobool26=((($call25))|0)!=0;if(!($tobool26)){__label__=12;break $if_then16$$if_end29$14;}
$prev_thousands=1;__label__=14;break $if_end32$$if_else$10;}}while(0);var $_pr=$prev_thousands;var $cmp30=((($_pr))|0)==0;if(!($cmp30)){__label__=14;break $if_end32$$if_else$10;}
HEAP32[((__ZL23speak_missing_thousands)>>2)]=0;;}}while(0);HEAP8[(((__ZL11ph_ordinal2)&4294967295))]=0;var $arrayidx33=(($ph_zeros)&4294967295);HEAP8[($arrayidx33)]=0;var $27=$prev_thousands;var $tobool34=((($27))|0)!=0;if($tobool34){__label__=16;;}else{__label__=15;;}
$if_then39$$lor_lhs_false35$22:do{if(__label__==15){var $28=$word_addr;var $arrayidx36=(($28)&4294967295);var $29=HEAP8[($arrayidx36)];var $conv37=(tempInt=(($29)),(tempInt>=128?tempInt-256:tempInt));var $cmp38=((($conv37))|0)!=48;if($cmp38){__label__=16;break $if_then39$$lor_lhs_false35$22;}else{__label__=18;break $if_then39$$lor_lhs_false35$22;}}}while(0);$if_then39$$if_end45$24:do{if(__label__==16){var $30=$tr_addr;var $31=$word_addr;var $32=$ix;var $33=$word_addr;var $arrayidx40=(($33+$32)&4294967295);var $34=$wtab_addr;var $call41=__ZL15CheckDotOrdinalP10TranslatorPcS1_P8WORD_TABi($30,$31,$arrayidx40,$34,0);$ordinal=$call41;var $cmp42=((($call41))|0)!=0;if(!($cmp42)){__label__=18;break $if_then39$$if_end45$24;}
$dot_ordinal=1;;}}while(0);var $35=$ix;var $36=$word_addr;var $arrayidx46=(($36+$35)&4294967295);var $37=HEAP8[($arrayidx46)];var $conv47=(tempInt=(($37)),(tempInt>=128?tempInt-256:tempInt));var $cmp48=((($conv47))|0)==46;if($cmp48){__label__=19;;}else{__label__=23;;}
$land_lhs_true49$$if_end67$28:do{if(__label__==19){var $38=$ix;var $add=((($38)+1)&4294967295);var $39=$word_addr;var $arrayidx50=(($39+$add)&4294967295);var $40=HEAP8[($arrayidx50)];var $conv51=(tempInt=(($40)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp10=((($conv51)-48)&4294967295);var $isdigit11=((($isdigittmp10))>>>0)<10;var $call52=((($isdigit11))&1);var $tobool53=((($call52))|0)!=0;if($tobool53){__label__=23;break $land_lhs_true49$$if_end67$28;}
var $41=$ix;var $add55=((($41)+2)&4294967295);var $42=$word_addr;var $arrayidx56=(($42+$add55)&4294967295);var $43=HEAP8[($arrayidx56)];var $conv57=(tempInt=(($43)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp12=((($conv57)-48)&4294967295);var $isdigit13=((($isdigittmp12))>>>0)<10;var $call58=((($isdigit13))&1);var $tobool59=((($call58))|0)!=0;if($tobool59){__label__=23;break $land_lhs_true49$$if_end67$28;}
var $44=$wtab_addr;var $arrayidx61=(($44+12)&4294967295);var $flags62=(($arrayidx61)&4294967295);var $45=HEAP32[(($flags62)>>2)];var $and63=($45)&256;var $tobool64=((($and63))|0)!=0;if($tobool64){__label__=23;break $land_lhs_true49$$if_end67$28;}
var $46=$ix;var $47=$word_addr;var $arrayidx66=(($47+$46)&4294967295);HEAP8[($arrayidx66)]=0;;}}while(0);var $48=$ordinal;var $cmp68=((($48))|0)==0;if($cmp68){__label__=25;;}else{__label__=24;;}
$if_then71$$lor_lhs_false69$34:do{if(__label__==24){var $49=$tr_addr;var $translator_name=(($49+280)&4294967295);var $50=HEAP32[(($translator_name)>>2)];var $cmp70=((($50))|0)==26741;if($cmp70){__label__=25;break $if_then71$$lor_lhs_false69$34;}else{__label__=38;break $if_then71$$lor_lhs_false69$34;}}}while(0);$if_then71$$if_end123$36:do{if(__label__==25){var $51=$ix;var $inc72=((($51)+1)&4294967295);$ix=$inc72;$hyphen=0;var $arraydecay73=(($suffix)&4294967295);HEAP32[(($p)>>2)]=$arraydecay73;var $52=$wtab_addr;var $arrayidx74=(($52)&4294967295);var $flags75=(($arrayidx74)&4294967295);var $53=HEAP32[(($flags75)>>2)];var $and76=($53)&16384;var $tobool77=((($and76))|0)!=0;if($tobool77){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $54=HEAP32[(($p)>>2)];var $incdec_ptr=(($54+1)&4294967295);HEAP32[(($p)>>2)]=$incdec_ptr;HEAP8[($54)]=45;$hyphen=1;var $55=$ix;var $inc79=((($55)+1)&4294967295);$ix=$inc79;;}
$while_cond$40:while(1){var $56=$ix;var $57=$word_addr;var $arrayidx81=(($57+$56)&4294967295);var $58=HEAP8[($arrayidx81)];var $conv82=(tempInt=(($58)),(tempInt>=128?tempInt-256:tempInt));var $cmp83=((($conv82))|0)!=0;if(!($cmp83)){__label__=31;break $while_cond$40;}
var $59=$ix;var $60=$word_addr;var $arrayidx85=(($60+$59)&4294967295);var $61=HEAP8[($arrayidx85)];var $conv86=(tempInt=(($61)),(tempInt>=128?tempInt-256:tempInt));var $cmp87=((($conv86))|0)!=32;if(!($cmp87)){__label__=31;break $while_cond$40;}
var $62=$ix;var $cmp88=((($62))|0)<19;if(!($cmp88)){__label__=31;break $while_cond$40;}
var $63=$ix;var $inc89=((($63)+1)&4294967295);$ix=$inc89;var $64=$word_addr;var $arrayidx90=(($64+$63)&4294967295);var $65=HEAP8[($arrayidx90)];var $66=HEAP32[(($p)>>2)];var $incdec_ptr91=(($66+1)&4294967295);HEAP32[(($p)>>2)]=$incdec_ptr91;HEAP8[($66)]=$65;__label__=27;continue $while_cond$40;}
var $67=HEAP32[(($p)>>2)];HEAP8[($67)]=0;var $arrayidx92=(($suffix)&4294967295);var $68=HEAP8[($arrayidx92)];var $conv93=(tempInt=(($68)),(tempInt>=128?tempInt-256:tempInt));var $cmp94=((($conv93))|0)!=0;if(!($cmp94)){__label__=38;break $if_then71$$if_end123$36;}
var $69=$tr_addr;var $langopts96=(($69)&4294967295);var $ordinal_indicator=(($langopts96+216)&4294967295);var $70=HEAP32[(($ordinal_indicator)>>2)];var $cmp97=((($70))|0)!=0;if($cmp97){__label__=33;;}else{__label__=35;;}
$land_lhs_true98$$if_else105$47:do{if(__label__==33){var $arraydecay99=(($suffix)&4294967295);var $71=$tr_addr;var $langopts100=(($71)&4294967295);var $ordinal_indicator101=(($langopts100+216)&4294967295);var $72=HEAP32[(($ordinal_indicator101)>>2)];var $call102=_strcmp($arraydecay99,$72);var $cmp103=((($call102))|0)==0;if(!($cmp103)){__label__=35;break $land_lhs_true98$$if_else105$47;}
$ordinal=2;__label__=38;break $if_then71$$if_end123$36;}}while(0);var $arrayidx106=(($suffix)&4294967295);var $73=HEAP8[($arrayidx106)];var $conv107=(tempInt=(($73)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp14=((($conv107)-48)&4294967295);var $isdigit15=((($isdigittmp14))>>>0)<10;var $call108=((($isdigit15))&1);var $tobool109=((($call108))|0)!=0;if($tobool109){__label__=38;break $if_then71$$if_end123$36;}
var $arraydecay111=(($string)&4294967295);var $arraydecay112=(($suffix)&4294967295);var $call113=_sprintf($arraydecay111,((__str15312)&4294967295),allocate([$arraydecay112,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $74=$tr_addr;var $arraydecay114=(($string)&4294967295);var $call115=__Z6LookupP10TranslatorPKcPc($74,$arraydecay114,((__ZL11ph_ordinal2)&4294967295));var $tobool116=((($call115))|0)!=0;if(!($tobool116)){__label__=38;break $if_then71$$if_end123$36;}
$ordinal=2;var $75=$flags_addr;var $arrayidx118=(($75)&4294967295);var $76=HEAP32[(($arrayidx118)>>2)];var $or=($76)|128;HEAP32[(($arrayidx118)>>2)]=$or;$skipwords=1;;}}while(0);var $77=$wtab_addr;var $arrayidx124=(($77)&4294967295);var $flags125=(($arrayidx124)&4294967295);var $78=HEAP32[(($flags125)>>2)];var $and126=($78)&32768;var $tobool127=((($and126))|0)!=0;if($tobool127){__label__=39;;}else{__label__=40;;}
if(__label__==39){$ordinal=2;;}
var $arrayidx130=(($ph_append)&4294967295);HEAP8[($arrayidx130)]=0;var $arrayidx131=(($ph_buf2)&4294967295);HEAP8[($arrayidx131)]=0;var $79=$word_addr;var $arrayidx132=(($79)&4294967295);var $80=HEAP8[($arrayidx132)];var $conv133=(tempInt=(($80)),(tempInt>=128?tempInt-256:tempInt));var $cmp134=((($conv133))|0)==48;if($cmp134){__label__=41;;}else{__label__=55;;}
$land_lhs_true135$$if_end185$57:do{if(__label__==41){var $81=$prev_thousands;var $cmp136=((($81))|0)==0;if(!($cmp136)){__label__=55;break $land_lhs_true135$$if_end185$57;}
var $82=$word_addr;var $arrayidx138=(($82+1)&4294967295);var $83=HEAP8[($arrayidx138)];var $conv139=(tempInt=(($83)),(tempInt>=128?tempInt-256:tempInt));var $cmp140=((($conv139))|0)!=32;if(!($cmp140)){__label__=55;break $land_lhs_true135$$if_end185$57;}
var $84=$word_addr;var $arrayidx142=(($84+1)&4294967295);var $85=HEAP8[($arrayidx142)];var $conv143=(tempInt=(($85)),(tempInt>=128?tempInt-256:tempInt));var $86=$tr_addr;var $langopts144=(($86)&4294967295);var $decimal_sep=(($langopts144+208)&4294967295);var $87=HEAP32[(($decimal_sep)>>2)];var $cmp145=((($conv143))|0)!=((($87))|0);if(!($cmp145)){__label__=55;break $land_lhs_true135$$if_end185$57;}
var $88=$n_digits;var $cmp147=((($88))|0)==2;if($cmp147){__lastLabel__=44;__label__=45;;}else{__lastLabel__=44;__label__=49;;}
if(__label__==45){var $89=$word_addr;var $arrayidx149=(($89+3)&4294967295);var $90=HEAP8[($arrayidx149)];var $conv150=(tempInt=(($90)),(tempInt>=128?tempInt-256:tempInt));var $cmp151=((($conv150))|0)==58;if($cmp151){__label__=46;;}else{__label__=48;;}
$land_lhs_true152$$if_else163thread_pre_split$64:do{if(__label__==46){var $91=$word_addr;var $arrayidx153=(($91+5)&4294967295);var $92=HEAP8[($arrayidx153)];var $conv154=(tempInt=(($92)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp16=((($conv154)-48)&4294967295);var $isdigit17=((($isdigittmp16))>>>0)<10;var $call155=((($isdigit17))&1);var $tobool156=((($call155))|0)!=0;if(!($tobool156)){__label__=48;break $land_lhs_true152$$if_else163thread_pre_split$64;}
var $93=$word_addr;var $arrayidx158=(($93+7)&4294967295);var $94=HEAP8[($arrayidx158)];var $conv159=(tempInt=(($94)),(tempInt>=128?tempInt-256:tempInt));var $call160=_isspace($conv159);var $tobool161=((($call160))|0)!=0;if($tobool161){__label__=55;break $land_lhs_true135$$if_end185$57;}}}while(0);var $_pr43=$n_digits;__lastLabel__=48;;}
var $95=__lastLabel__==48?$_pr43:($88);var $cmp164=((($95))|0)>3;if($cmp164){__label__=50;;}else{__label__=51;;}
if(__label__==50){var $96=$flags_addr;var $arrayidx166=(($96)&4294967295);var $97=HEAP32[(($arrayidx166)>>2)];var $and167=($97)&-129;HEAP32[(($arrayidx166)>>2)]=$and167;$retval=0;__label__=157;break $land_lhs_true135$$if_end185$57;}
else if(__label__==51){$ix=0;var $arraydecay177=(($ph_zeros)&4294967295);;while(1){var $98=$ix;var $99=$word_addr;var $arrayidx170=(($99+$98)&4294967295);var $100=HEAP8[($arrayidx170)];var $conv171=(tempInt=(($100)),(tempInt>=128?tempInt-256:tempInt));var $cmp172=((($conv171))|0)==48;if(!($cmp172)){__label__=55;break $land_lhs_true135$$if_end185$57;}
var $101=$ix;var $102=$n_digits;var $sub=((($102)-1)&4294967295);var $cmp174=((($101))|0)<((($sub))|0);if(!($cmp174)){__label__=55;break $land_lhs_true135$$if_end185$57;}
var $103=$tr_addr;var $call178=_strlen($arraydecay177);var $arrayidx179=(($ph_zeros+$call178)&4294967295);var $call180=__Z6LookupP10TranslatorPKcPc($103,((__str16313)&4294967295),$arrayidx179);var $104=$ix;var $inc182=((($104)+1)&4294967295);$ix=$inc182;__label__=52;continue;}}}}while(0);if(__label__==55){var $105=$tr_addr;var $langopts186=(($105)&4294967295);var $numbers187=(($langopts186+184)&4294967295);var $106=HEAP32[(($numbers187)>>2)];var $and188=($106)&4096;var $tobool189=((($and188))|0)!=0;if($tobool189){__label__=56;;}else{__label__=58;;}
$land_lhs_true190$$if_else195$78:do{if(__label__==56){var $107=$n_digits;var $108=$word_addr;var $arrayidx191=(($108+$107)&4294967295);var $109=HEAP8[($arrayidx191)];var $conv192=(tempInt=(($109)),(tempInt>=128?tempInt-256:tempInt));var $cmp193=((($conv192))|0)==32;if(!($cmp193)){__label__=58;break $land_lhs_true190$$if_else195$78;}
$thousands_inc=1;__label__=60;break $land_lhs_true190$$if_else195$78;}}while(0);$if_end203_thread$$if_else195$81:do{if(__label__==58){var $110=$n_digits;var $111=$word_addr;var $arrayidx196=(($111+$110)&4294967295);var $112=HEAP8[($arrayidx196)];var $conv197=(tempInt=(($112)),(tempInt>=128?tempInt-256:tempInt));var $113=$tr_addr;var $langopts198=(($113)&4294967295);var $thousands_sep199=(($langopts198+204)&4294967295);var $114=HEAP32[(($thousands_sep199)>>2)];var $cmp200=((($conv197))|0)==((($114))|0);if($cmp200){__label__=59;;}else{__label__=61;;}
if(__label__==59){$thousands_inc=2;__label__=60;break $if_end203_thread$$if_else195$81;}
else if(__label__==61){var $_pr44=$thousands_inc;var $116=$n_digits;var $add204=((($116)+2)&4294967295);$suffix_ix=$add204;var $cmp205=((($_pr44))|0)>0;if($cmp205){__label__=62;break $if_end203_thread$$if_else195$81;}else{__label__=77;break $if_end203_thread$$if_else195$81;}}}}while(0);$if_end203_thread$$if_then206$$if_end282$86:do{if(__label__==60){var $115=$n_digits;var $add20445=((($115)+2)&4294967295);$suffix_ix=$add20445;__label__=62;break $if_end203_thread$$if_then206$$if_end282$86;}}while(0);$if_then206$$if_end282$88:do{if(__label__==62){var $117=$n_digits;var $118=$thousands_inc;var $add207=((($118)+($117))&4294967295);$digix=$add207;;$while_cond208$90:while(1){var $119=$thousandplex;var $add209=((($119)+1)&4294967295);var $120=$wtab_addr;var $arrayidx210=(($120+12*$add209)&4294967295);var $flags211=(($arrayidx210)&4294967295);var $121=HEAP32[(($flags211)>>2)];var $and212=($121)&262144;var $cmp213=((($and212))|0)==0;if(!($cmp213)){__label__=77;break $if_then206$$if_end282$88;}
var $122=$digix;var $123=$word_addr;var $arrayidx215=(($123+$122)&4294967295);var $124=HEAP8[($arrayidx215)];var $conv216=(tempInt=(($124)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp18=((($conv216)-48)&4294967295);var $isdigit19=((($isdigittmp18))>>>0)<10;var $call217=((($isdigit19))&1);var $tobool218=((($call217))|0)!=0;if(!($tobool218)){__label__=77;break $if_then206$$if_end282$88;}
var $125=$digix;var $add220=((($125)+1)&4294967295);var $126=$word_addr;var $arrayidx221=(($126+$add220)&4294967295);var $127=HEAP8[($arrayidx221)];var $conv222=(tempInt=(($127)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp20=((($conv222)-48)&4294967295);var $isdigit21=((($isdigittmp20))>>>0)<10;var $call223=((($isdigit21))&1);var $tobool224=((($call223))|0)!=0;if(!($tobool224)){__label__=77;break $if_then206$$if_end282$88;}
var $128=$digix;var $add226=((($128)+2)&4294967295);var $129=$word_addr;var $arrayidx227=(($129+$add226)&4294967295);var $130=HEAP8[($arrayidx227)];var $conv228=(tempInt=(($130)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp22=((($conv228)-48)&4294967295);var $isdigit23=((($isdigittmp22))>>>0)<10;var $call229=((($isdigit23))&1);var $tobool230=((($call229))|0)!=0;if(!($tobool230)){__label__=77;break $if_then206$$if_end282$88;}
var $131=$digix;var $add232=((($131)+3)&4294967295);var $132=$word_addr;var $arrayidx233=(($132+$add232)&4294967295);var $133=HEAP8[($arrayidx233)];var $conv234=(tempInt=(($133)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp24=((($conv234)-48)&4294967295);var $isdigit25=((($isdigittmp24))>>>0)<10;var $call235=((($isdigit25))&1);var $tobool236=((($call235))|0)!=0;if($tobool236){__label__=77;break $if_then206$$if_end282$88;}
var $134=$digix;var $sub238=((($134)-1)&4294967295);var $135=$word_addr;var $arrayidx239=(($135+$sub238)&4294967295);var $136=HEAP8[($arrayidx239)];var $conv240=(tempInt=(($136)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp26=((($conv240)-48)&4294967295);var $isdigit27=((($isdigittmp26))>>>0)<10;var $call241=((($isdigit27))&1);var $tobool242=((($call241))|0)!=0;var $lnot=($tobool242)^1;if(!($lnot)){__label__=77;break $if_then206$$if_end282$88;}
var $137=$digix;var $138=$word_addr;var $arrayidx245=(($138+$137)&4294967295);var $139=HEAP8[($arrayidx245)];var $conv246=(tempInt=(($139)),(tempInt>=128?tempInt-256:tempInt));var $cmp247=((($conv246))|0)!=48;if($cmp247){__label__=72;;}else{__label__=70;;}
$if_then258$$lor_lhs_false248$98:do{if(__label__==70){var $140=$digix;var $add249=((($140)+1)&4294967295);var $141=$word_addr;var $arrayidx250=(($141+$add249)&4294967295);var $142=HEAP8[($arrayidx250)];var $conv251=(tempInt=(($142)),(tempInt>=128?tempInt-256:tempInt));var $cmp252=((($conv251))|0)!=48;if($cmp252){__label__=72;break $if_then258$$lor_lhs_false248$98;}
var $143=$digix;var $add254=((($143)+2)&4294967295);var $144=$word_addr;var $arrayidx255=(($144+$add254)&4294967295);var $145=HEAP8[($arrayidx255)];var $conv256=(tempInt=(($145)),(tempInt>=128?tempInt-256:tempInt));var $cmp257=((($conv256))|0)!=48;if($cmp257){__label__=72;break $if_then258$$lor_lhs_false248$98;}else{__label__=73;break $if_then258$$lor_lhs_false248$98;}}}while(0);if(__label__==72){$thousands_exact=0;;}
var $146=$thousandplex;var $inc260=((($146)+1)&4294967295);$thousandplex=$inc260;var $147=$digix;var $add261=((($147)+3)&4294967295);$digix=$add261;var $148=$digix;var $149=$word_addr;var $arrayidx262=(($149+$148)&4294967295);var $150=HEAP8[($arrayidx262)];var $conv263=(tempInt=(($150)),(tempInt>=128?tempInt-256:tempInt));var $151=$tr_addr;var $langopts264=(($151)&4294967295);var $thousands_sep265=(($langopts264+204)&4294967295);var $152=HEAP32[(($thousands_sep265)>>2)];var $cmp266=((($conv263))|0)==((($152))|0);if($cmp266){__label__=76;;}else{__label__=74;;}
if(__label__==74){var $153=$tr_addr;var $langopts268=(($153)&4294967295);var $numbers269=(($langopts268+184)&4294967295);var $154=HEAP32[(($numbers269)>>2)];var $and270=($154)&4096;var $tobool271=((($and270))|0)!=0;if(!($tobool271)){__label__=77;break $if_then206$$if_end282$88;}
var $155=$digix;var $156=$word_addr;var $arrayidx273=(($156+$155)&4294967295);var $157=HEAP8[($arrayidx273)];var $conv274=(tempInt=(($157)),(tempInt>=128?tempInt-256:tempInt));var $cmp275=((($conv274))|0)==32;if(!($cmp275)){__label__=77;break $if_then206$$if_end282$88;}}
var $158=$digix;var $add277=((($158)+2)&4294967295);$suffix_ix=$add277;var $159=$thousands_inc;var $160=$digix;var $add278=((($160)+($159))&4294967295);$digix=$add278;__label__=63;continue $while_cond208$90;}}}while(0);var $161=$value;var $cmp283=((($161))|0)==0;if($cmp283){__label__=78;;}else{__label__=80;;}
$land_lhs_true284$$if_end287$109:do{if(__label__==78){var $162=$prev_thousands;var $tobool285=((($162))|0)!=0;if(!($tobool285)){__label__=80;break $land_lhs_true284$$if_end287$109;}
$suppress_null=1;;}}while(0);var $163=$tr_addr;var $translator_name288=(($163+280)&4294967295);var $164=HEAP32[(($translator_name288)>>2)];var $cmp289=((($164))|0)==26741;if($cmp289){__label__=81;;}else{__label__=85;;}
$if_then290$$if_end304$113:do{if(__label__==81){var $165=$thousandplex;var $166=$wtab_addr;var $arrayidx291=(($166+12*$165)&4294967295);var $flags292=(($arrayidx291)&4294967295);var $167=HEAP32[(($flags292)>>2)];var $and293=($167)&16384;var $tobool294=((($and293))|0)!=0;if(!($tobool294)){__label__=85;break $if_then290$$if_end304$113;}
var $168=$thousands_exact;var $cmp296=((($168))|0)==1;if(!($cmp296)){__label__=85;break $if_then290$$if_end304$113;}
var $169=$suffix_ix;var $170=$word_addr;var $arrayidx298=(($170+$169)&4294967295);var $171=$thousandplex;var $172=$value;var $call299=__ZL11hu_number_ePKcii($arrayidx298,$171,$172);var $tobool300=((($call299))|0)!=0;if(!($tobool300)){__label__=85;break $if_then290$$if_end304$113;}
var $173=HEAP32[((__ZL14number_control)>>2)];var $or302=($173)|1;HEAP32[((__ZL14number_control)>>2)]=$or302;;}}while(0);var $174=$n_digits;var $175=$word_addr;var $arrayidx305=(($175+$174)&4294967295);var $176=HEAP8[($arrayidx305)];var $conv306=(tempInt=(($176)),(tempInt>=128?tempInt-256:tempInt));var $177=$tr_addr;var $langopts307=(($177)&4294967295);var $decimal_sep308=(($langopts307+208)&4294967295);var $178=HEAP32[(($decimal_sep308)>>2)];var $cmp309=((($conv306))|0)==((($178))|0);if($cmp309){__label__=86;;}else{__label__=88;;}
$land_lhs_true310$$if_else319$119:do{if(__label__==86){var $179=$n_digits;var $add311=((($179)+1)&4294967295);var $180=$word_addr;var $arrayidx312=(($180+$add311)&4294967295);var $181=HEAP8[($arrayidx312)];var $conv313=(tempInt=(($181)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp28=((($conv313)-48)&4294967295);var $isdigit29=((($isdigittmp28))>>>0)<10;var $call314=((($isdigit29))&1);var $tobool315=((($call314))|0)!=0;if(!($tobool315)){__label__=88;break $land_lhs_true310$$if_else319$119;}
var $182=$tr_addr;var $arraydecay317=(($ph_append)&4294967295);var $call318=__Z6LookupP10TranslatorPKcPc($182,((__str17314)&4294967295),$arraydecay317);$decimal_point=1;__label__=98;break $land_lhs_true310$$if_else319$119;}}while(0);$if_end356$$if_else319$122:do{if(__label__==88){var $183=$suppress_null;var $cmp320=((($183))|0)==0;if($cmp320){__label__=89;;}else{__label__=95;;}
if(__label__==89){var $184=$thousands_inc;var $cmp322=((($184))|0)>0;if(!($cmp322)){__label__=98;break $if_end356$$if_else319$122;}
var $185=$thousandplex;var $cmp324=((($185))|0)>0;if(!($cmp324)){__label__=98;break $if_end356$$if_else319$122;}
var $186=$value;var $cmp326=((($186))|0)<1000;if(!($cmp326)){__label__=98;break $if_end356$$if_else319$122;}
var $187=$suppress_null;var $cmp328=((($187))|0)==0;if(!($cmp328)){__label__=98;break $if_end356$$if_else319$122;}
var $188=$tr_addr;var $189=$value;var $190=$thousandplex;var $191=$thousands_exact;var $arraydecay330=(($ph_append)&4294967295);var $call331=__ZL15LookupThousandsP10TranslatoriiiPc($188,$189,$190,$191,$arraydecay330);var $tobool332=((($call331))|0)!=0;if(!($tobool332)){__label__=98;break $if_end356$$if_else319$122;}
$value=0;$suppress_null=1;;}
else if(__label__==95){var $192=HEAP32[((__ZL23speak_missing_thousands)>>2)];var $cmp338=((($192))|0)==1;if(!($cmp338)){__label__=98;break $if_end356$$if_else319$122;}
var $arraydecay340=(($string)&4294967295);var $193=$thousandplex;var $add341=((($193)+1)&4294967295);var $call342=_sprintf($arraydecay340,((__str18315)&4294967295),allocate([$add341,0,0,0],["i32",0,0,0],ALLOC_STACK));var $194=$tr_addr;var $arraydecay343=(($string)&4294967295);var $arraydecay344=(($buf1)&4294967295);var $call345=__Z6LookupP10TranslatorPKcPc($194,$arraydecay343,$arraydecay344);var $cmp346=((($call345))|0)==0;if(!($cmp346)){__label__=98;break $if_end356$$if_else319$122;}
var $arraydecay348=(($string)&4294967295);var $195=$thousandplex;var $call349=_sprintf($arraydecay348,((__str18315)&4294967295),allocate([$195,0,0,0],["i32",0,0,0],ALLOC_STACK));var $196=$tr_addr;var $arraydecay350=(($string)&4294967295);var $arraydecay351=(($ph_append)&4294967295);var $call352=__Z6LookupP10TranslatorPKcPc($196,$arraydecay350,$arraydecay351);;}}}while(0);var $arrayidx357=(($ph_append)&4294967295);var $197=HEAP8[($arrayidx357)];var $conv358=(tempInt=(($197)),(tempInt>=128?tempInt-256:tempInt));var $cmp359=((($conv358))|0)==0;if($cmp359){__label__=99;;}else{__label__=102;;}
$land_lhs_true360$$if_end369$135:do{if(__label__==99){var $198=$n_digits;var $199=$word_addr;var $arrayidx361=(($199+$198)&4294967295);var $200=HEAP8[($arrayidx361)];var $conv362=(tempInt=(($200)),(tempInt>=128?tempInt-256:tempInt));var $cmp363=((($conv362))|0)==46;if(!($cmp363)){__label__=102;break $land_lhs_true360$$if_end369$135;}
var $201=$thousandplex;var $cmp365=((($201))|0)==0;if(!($cmp365)){__label__=112;break $land_lhs_true360$$if_end369$135;}
var $202=$tr_addr;var $arraydecay367=(($ph_append)&4294967295);var $call368=__Z6LookupP10TranslatorPKcPc($202,((__str19316)&4294967295),$arraydecay367);__label__=102;break $land_lhs_true360$$if_end369$135;}}while(0);$if_end369$$if_end404$139:do{if(__label__==102){var $_pr47=$thousandplex;var $cmp370=((($_pr47))|0)==0;if(!($cmp370)){__label__=112;break $if_end369$$if_end404$139;}
var $203=$word_addr;HEAP32[(($p)>>2)]=$203;var $204=HEAP32[(($p)>>2)];var $arrayidx37360=(($204+1)&4294967295);var $205=HEAP8[($arrayidx37360)];var $conv37461=(tempInt=(($205)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp3062=((($conv37461)-48)&4294967295);var $isdigit3163=((($isdigittmp3062))>>>0)<10;var $206=HEAPU32[(($p)>>2)];if($isdigit3163){__lastLabel__=103;__label__=104;;}else{__lastLabel__=103;__label__=105;;}
$while_body377$$while_end379$142:do{if(__label__==104){while(1){var $207=__lastLabel__==104?$210:($206);var $incdec_ptr378=(($207+1)&4294967295);HEAP32[(($p)>>2)]=$incdec_ptr378;var $208=HEAP32[(($p)>>2)];var $arrayidx373=(($208+1)&4294967295);var $209=HEAP8[($arrayidx373)];var $conv374=(tempInt=(($209)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp30=((($conv374)-48)&4294967295);var $isdigit31=((($isdigittmp30))>>>0)<10;var $call375=((($isdigit31))&1);var $tobool376=((($call375))|0)!=0;var $210=HEAPU32[(($p)>>2)];if($tobool376){__lastLabel__=104;__label__=104;continue;}else{__lastLabel__=104;__label__=105;break $while_body377$$while_end379$142;}}}}while(0);var $_lcssa=__lastLabel__==103?$206:($210);var $arrayidx380=(($_lcssa+-1)&4294967295);var $211=HEAP8[($arrayidx380)];var $conv381=(tempInt=(($211)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp32=((($conv381)-48)&4294967295);var $isdigit33=((($isdigittmp32))>>>0)<10;var $call382=((($isdigit33))&1);var $tobool383=((($call382))|0)!=0;if($tobool383){__label__=106;;}else{__label__=108;;}
$if_then384$$if_end390$146:do{if(__label__==106){var $212=HEAP32[(($p)>>2)];var $add_ptr=(($212+-1)&4294967295);HEAP32[(($p2)>>2)]=$add_ptr;var $213=$tr_addr;var $arraydecay385=(($buf_digit_lookup)&4294967295);var $214=$flags_addr;var $215=$wtab_addr;var $call386=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($213,$p2,$arraydecay385,$214,4,$215);var $tobool387=((($call386))|0)!=0;if(!($tobool387)){__label__=108;break $if_then384$$if_end390$146;}
HEAP32[((__ZL14n_digit_lookup)>>2)]=2;;}}while(0);var $arrayidx391=(($buf_digit_lookup)&4294967295);var $216=HEAP8[($arrayidx391)];var $conv392=(tempInt=(($216)),(tempInt>=128?tempInt-256:tempInt));var $cmp393=((($conv392))|0)==0;if(!($cmp393)){__label__=112;break $if_end369$$if_end404$139;}
var $217=HEAP32[(($p)>>2)];var $218=HEAP8[($217)];var $conv395=(tempInt=(($218)),(tempInt>=128?tempInt-256:tempInt));var $cmp396=((($conv395))|0)!=48;if(!($cmp396)){__label__=112;break $if_end369$$if_end404$139;}
var $219=$tr_addr;var $arraydecay398=(($buf_digit_lookup)&4294967295);var $220=$flags_addr;var $221=$wtab_addr;var $call399=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($219,$p,$arraydecay398,$220,4,$221);var $tobool400=((($call399))|0)!=0;if(!($tobool400)){__label__=112;break $if_end369$$if_end404$139;}
HEAP32[((__ZL14n_digit_lookup)>>2)]=1;;}}while(0);var $222=$tr_addr;var $223=$value;var $arraydecay405=(($ph_buf)&4294967295);var $224=$suppress_null;var $225=$thousandplex;var $226=$prev_thousands;var $227=$ordinal;var $or406=($227)|($226);__ZL10LookupNum3P10TranslatoriPciii($222,$223,$arraydecay405,$224,$225,$or406);var $228=$thousandplex;var $cmp408=((($228))|0)>0;if($cmp408){__label__=113;;}else{__label__=115;;}
$land_lhs_true409$$if_else419$154:do{if(__label__==113){var $229=$tr_addr;var $langopts410=(($229)&4294967295);var $numbers2=(($langopts410+188)&4294967295);var $230=HEAP32[(($numbers2)>>2)];var $and411=($230)&512;var $tobool412=((($and411))|0)!=0;if(!($tobool412)){__label__=115;break $land_lhs_true409$$if_else419$154;}
var $231=$ph_out_addr;var $arraydecay414=(($ph_zeros)&4294967295);var $arraydecay415=(($ph_append)&4294967295);var $arraydecay416=(($ph_buf2)&4294967295);var $arraydecay417=(($ph_buf)&4294967295);var $call418=_sprintf($231,((__str20317)&4294967295),allocate([$arraydecay414,0,0,0,$arraydecay415,0,0,0,$arraydecay416,0,0,0,$arraydecay417,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));__label__=116;break $land_lhs_true409$$if_else419$154;}}while(0);if(__label__==115){var $232=$ph_out_addr;var $arraydecay420=(($ph_zeros)&4294967295);var $arraydecay421=(($ph_buf2)&4294967295);var $arraydecay422=(($ph_buf)&4294967295);var $arraydecay423=(($ph_append)&4294967295);var $call424=_sprintf($232,((__str20317)&4294967295),allocate([$arraydecay420,0,0,0,$arraydecay421,0,0,0,$arraydecay422,0,0,0,$arraydecay423,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
var $arraydecay472=(($ph_buf)&4294967295);var $arraydecay480=(($string)&4294967295);var $arraydecay482=(($string)&4294967295);var $arraydecay483=(($buf1)&4294967295);var $arraydecay488=(($ph_buf)&4294967295);var $arraydecay489=(($buf1)&4294967295);var $arraydecay492=(($ph_buf)&4294967295);var $arraydecay504=(($buf1)&4294967295);var $arraydecay506=(($buf1)&4294967295);var $arraydecay463=(($buf1)&4294967295);var $arraydecay465=(($buf1)&4294967295);var $arraydecay448=(($buf1)&4294967295);var $arraydecay450=(($buf1)&4294967295);var $arraydecay524=(($buf1)&4294967295);var $arraydecay526=(($buf1)&4294967295);var $arraydecay529=(($buf1)&4294967295);var $arraydecay533=(($buf1)&4294967295);var $arraydecay547=(($buf1)&4294967295);var $arraydecay549=(($buf1)&4294967295);;$while_cond426thread_pre_split$160:while(1){var $_pr49=$decimal_point;__lastLabel__=117;;$while_cond426$162:while(1){var $233=__lastLabel__==117?$_pr49:(0);var $tobool427=((($233))|0)!=0;if(!($tobool427)){__label__=145;break $while_cond426thread_pre_split$160;}
var $234=$n_digits;var $inc429=((($234)+1)&4294967295);$n_digits=$inc429;$decimal_count=0;var $235=$n_digits;var $236=$decimal_count;var $add43153=((($236)+($235))&4294967295);var $237=$word_addr;var $arrayidx43254=(($237+$add43153)&4294967295);var $238=HEAP8[($arrayidx43254)];var $conv43355=(tempInt=(($238)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp3456=((($conv43355)-48)&4294967295);var $isdigit3557=((($isdigittmp3456))>>>0)<10;var $call43458=((($isdigit3557))&1);var $tobool43559=((($call43458))|0)!=0;if($tobool43559){__label__=120;;}else{__label__=121;;}
$while_body436$$while_end438$165:do{if(__label__==120){while(1){var $239=$decimal_count;var $inc437=((($239)+1)&4294967295);$decimal_count=$inc437;var $240=$n_digits;var $241=$decimal_count;var $add431=((($241)+($240))&4294967295);var $242=$word_addr;var $arrayidx432=(($242+$add431)&4294967295);var $243=HEAP8[($arrayidx432)];var $conv433=(tempInt=(($243)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp34=((($conv433)-48)&4294967295);var $isdigit35=((($isdigittmp34))>>>0)<10;var $call434=((($isdigit35))&1);var $tobool435=((($call434))|0)!=0;if($tobool435){__label__=120;continue;}else{__label__=121;break $while_body436$$while_end438$165;}}}}while(0);$max_decimal_count=2;var $244=$tr_addr;var $langopts439=(($244)&4294967295);var $numbers440=(($langopts439+184)&4294967295);var $245=HEAP32[(($numbers440)>>2)];var $and441=($245)&57344;$decimal_mode=$and441;if($and441==32768){__label__=122;;}
else if($and441==16384){__label__=123;;}
else if($and441==8192){__label__=128;;}
else if($and441==40960){__label__=128;;}
else if($and441==24576){__label__=133;;}
else{__label__=136;;}
$while_cond510$$sw_bb$$while_cond443_preheader$$sw_bb469$$sw_bb495$169:do{if(__label__==122){$max_decimal_count=5;__label__=123;break $while_cond510$$sw_bb$$while_cond443_preheader$$sw_bb469$$sw_bb495$169;}
else if(__label__==128){var $267=$tr_addr;var $268=$n_digits;var $269=$word_addr;var $arrayidx470=(($269+$268)&4294967295);var $call471=_atoi($arrayidx470);__ZL10LookupNum3P10TranslatoriPciii($267,$call471,$arraydecay472,0,0,0);var $270=$n_digits;var $271=$word_addr;var $arrayidx474=(($271+$270)&4294967295);var $272=HEAP8[($arrayidx474)];var $conv475=(tempInt=(($272)),(tempInt>=128?tempInt-256:tempInt));var $cmp476=((($conv475))|0)==48;if($cmp476){__label__=130;;}else{__label__=129;;}
$if_then479$$lor_lhs_false477$172:do{if(__label__==129){var $273=$decimal_mode;var $cmp478=((($273))|0)==40960;if($cmp478){__label__=130;break $if_then479$$lor_lhs_false477$172;}else{__label__=132;break $if_then479$$lor_lhs_false477$172;}}}while(0);if(__label__==130){var $274=$decimal_count;var $call481=_sprintf($arraydecay480,((__str21318)&4294967295),allocate([$274,0,0,0],["i32",0,0,0],ALLOC_STACK));var $275=$tr_addr;var $call484=__Z6LookupP10TranslatorPKcPc($275,$arraydecay482,$arraydecay483);var $cmp485=((($call484))|0)==0;if($cmp485){__label__=136;break $while_cond510$$sw_bb$$while_cond443_preheader$$sw_bb469$$sw_bb495$169;}
var $call490=_strcat($arraydecay488,$arraydecay489);;}
var $276=$ph_out_addr;var $call493=_strcat($276,$arraydecay492);var $277=$decimal_count;var $278=$n_digits;var $add494=((($278)+($277))&4294967295);$n_digits=$add494;__label__=136;break $while_cond510$$sw_bb$$while_cond443_preheader$$sw_bb469$$sw_bb495$169;}
else if(__label__==133){var $279=$decimal_count;var $cmp496=((($279))|0)<=4;if(!($cmp496)){__label__=136;break $while_cond510$$sw_bb$$while_cond443_preheader$$sw_bb469$$sw_bb495$169;}
var $280=$n_digits;var $281=$word_addr;var $arrayidx498=(($281+$280)&4294967295);var $282=HEAP8[($arrayidx498)];var $conv499=(tempInt=(($282)),(tempInt>=128?tempInt-256:tempInt));var $cmp500=((($conv499))|0)!=48;if(!($cmp500)){__label__=136;break $while_cond510$$sw_bb$$while_cond443_preheader$$sw_bb469$$sw_bb495$169;}
var $283=$tr_addr;var $284=$n_digits;var $285=$word_addr;var $arrayidx502=(($285+$284)&4294967295);var $call503=_atoi($arrayidx502);__ZL10LookupNum3P10TranslatoriPciii($283,$call503,$arraydecay504,0,0,0);var $286=$ph_out_addr;var $call507=_strcat($286,$arraydecay506);var $287=$decimal_count;var $288=$n_digits;var $add508=((($288)+($287))&4294967295);$n_digits=$add508;__label__=136;break $while_cond510$$sw_bb$$while_cond443_preheader$$sw_bb469$$sw_bb495$169;}}while(0);$while_cond510$$while_cond443_preheader$181:do{if(__label__==123){var $246=$n_digits;var $247=$word_addr;var $arrayidx44450=(($247+$246)&4294967295);var $248=HEAP8[($arrayidx44450)];var $conv44551=(tempInt=(($248)),(tempInt>=128?tempInt-256:tempInt));var $cmp44652=((($conv44551))|0)==48;if($cmp44652){__label__=124;;}else{__label__=125;;}
$while_body447$$while_end453$183:do{if(__label__==124){while(1){var $249=$tr_addr;var $call449=__Z6LookupP10TranslatorPKcPc($249,((__str16313)&4294967295),$arraydecay448);var $250=$ph_out_addr;var $call451=_strcat($250,$arraydecay450);var $251=$decimal_count;var $dec=((($251)-1)&4294967295);$decimal_count=$dec;var $252=$n_digits;var $inc452=((($252)+1)&4294967295);$n_digits=$inc452;var $253=$n_digits;var $254=$word_addr;var $arrayidx444=(($254+$253)&4294967295);var $255=HEAP8[($arrayidx444)];var $conv445=(tempInt=(($255)),(tempInt>=128?tempInt-256:tempInt));var $cmp446=((($conv445))|0)==48;if($cmp446){__label__=124;continue;}else{__label__=125;break $while_body447$$while_end453$183;}}}}while(0);var $256=$decimal_count;var $257=$max_decimal_count;var $cmp454=((($256))|0)<=((($257))|0);if(!($cmp454)){__label__=136;break $while_cond510$$while_cond443_preheader$181;}
var $258=$n_digits;var $259=$word_addr;var $arrayidx456=(($259+$258)&4294967295);var $260=HEAP8[($arrayidx456)];var $conv457=(tempInt=(($260)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp36=((($conv457)-48)&4294967295);var $isdigit37=((($isdigittmp36))>>>0)<10;var $call458=((($isdigit37))&1);var $tobool459=((($call458))|0)!=0;if(!($tobool459)){__label__=136;break $while_cond510$$while_cond443_preheader$181;}
var $261=$tr_addr;var $262=$n_digits;var $263=$word_addr;var $arrayidx461=(($263+$262)&4294967295);var $call462=_atoi($arrayidx461);__ZL10LookupNum3P10TranslatoriPciii($261,$call462,$arraydecay463,0,0,0);var $264=$ph_out_addr;var $call466=_strcat($264,$arraydecay465);var $265=$decimal_count;var $266=$n_digits;var $add467=((($266)+($265))&4294967295);$n_digits=$add467;;}}while(0);while(1){var $289=$n_digits;var $290=$word_addr;var $arrayidx511=(($290+$289)&4294967295);var $291=HEAPU8[($arrayidx511)];$c=$291;var $conv512=((($291))&255);var $isdigittmp38=((($conv512)-48)&4294967295);var $isdigit39=((($isdigittmp38))>>>0)<10;var $call513=((($isdigit39))&1);var $tobool514=((($call513))|0)!=0;if(!($tobool514)){__label__=139;break;}
var $292=$ph_out_addr;var $call516=_strlen($292);var $cmp517=((($call516))>>>0)<150;if(!($cmp517)){__label__=139;break;}
var $293=$n_digits;var $inc520=((($293)+1)&4294967295);$n_digits=$inc520;var $294=$word_addr;var $arrayidx521=(($294+$293)&4294967295);var $295=HEAP8[($arrayidx521)];var $conv522=(tempInt=(($295)),(tempInt>=128?tempInt-256:tempInt));var $sub523=((($conv522)-48)&4294967295);$value=$sub523;var $296=$tr_addr;var $297=$value;var $call525=__ZL10LookupNum2P10TranslatoriiPc($296,$297,2,$arraydecay524);var $298=$ph_out_addr;var $call527=_strcat($298,$arraydecay526);__label__=136;continue;}
var $299=$tr_addr;var $call530=__Z6LookupP10TranslatorPKcPc($299,((__str22319)&4294967295),$arraydecay529);var $tobool531=((($call530))|0)!=0;if($tobool531){__label__=140;;}else{__label__=141;;}
if(__label__==140){var $300=$ph_out_addr;var $call534=_strcat($300,$arraydecay533);;}
var $301=$c;var $conv536=((($301))&255);var $302=$tr_addr;var $langopts537=(($302)&4294967295);var $decimal_sep538=(($langopts537+208)&4294967295);var $303=HEAP32[(($decimal_sep538)>>2)];var $cmp539=((($conv536))|0)==((($303))|0);if($cmp539){__label__=142;;}else{__label__=144;;}
if(__label__==142){var $304=$n_digits;var $add541=((($304)+1)&4294967295);var $305=$word_addr;var $arrayidx542=(($305+$add541)&4294967295);var $306=HEAP8[($arrayidx542)];var $conv543=(tempInt=(($306)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp40=((($conv543)-48)&4294967295);var $isdigit41=((($isdigittmp40))>>>0)<10;var $call544=((($isdigit41))&1);var $tobool545=((($call544))|0)!=0;if($tobool545){__label__=143;break $while_cond426$162;}}
$decimal_point=0;__lastLabel__=144;__label__=118;continue $while_cond426$162;}
var $307=$tr_addr;var $call548=__Z6LookupP10TranslatorPKcPc($307,((__str17314)&4294967295),$arraydecay547);var $308=$ph_out_addr;var $call550=_strcat($308,$arraydecay549);__label__=117;continue $while_cond426thread_pre_split$160;}
var $309=$ph_out_addr;var $arrayidx554=(($309)&4294967295);var $310=HEAP8[($arrayidx554)];var $conv555=(tempInt=(($310)),(tempInt>=128?tempInt-256:tempInt));var $cmp556=((($conv555))|0)!=0;if($cmp556){__label__=146;;}else{__label__=154;;}
$land_lhs_true557$$if_end588$202:do{if(__label__==146){var $311=$ph_out_addr;var $arrayidx558=(($311)&4294967295);var $312=HEAP8[($arrayidx558)];var $conv559=(tempInt=(($312)),(tempInt>=128?tempInt-256:tempInt));var $cmp560=((($conv559))|0)!=21;if(!($cmp560)){__label__=154;break $land_lhs_true557$$if_end588$202;}
var $313=$n_digits;var $add563=((($313)+1)&4294967295);var $314=$word_addr;var $arrayidx564=(($314+$add563)&4294967295);$p562=$arrayidx564;var $315=$p562;var $call565=__Z7utf8_inPiPKc($next_char,$315);var $316=$p562;var $add_ptr566=(($316+$call565)&4294967295);$p562=$add_ptr566;var $317=$tr_addr;var $langopts567=(($317)&4294967295);var $numbers568=(($langopts567+184)&4294967295);var $318=HEAP32[(($numbers568)>>2)];var $and569=($318)&131072;var $tobool570=((($and569))|0)!=0;if($tobool570){__label__=148;;}else{__label__=150;;}
$land_lhs_true571$$if_end575$205:do{if(__label__==148){var $319=HEAP32[(($next_char)>>2)];var $cmp572=((($319))|0)==32;if(!($cmp572)){__label__=150;break $land_lhs_true571$$if_end575$205;}
var $320=$p562;var $call574=__Z7utf8_inPiPKc($next_char,$320);;}}while(0);var $321=HEAP32[(($next_char)>>2)];var $call576=_iswalpha($321);var $tobool577=((($call576))|0)!=0;if($tobool577){__label__=154;break $land_lhs_true557$$if_end588$202;}
var $322=$thousandplex;var $323=$wtab_addr;var $arrayidx579=(($323+12*$322)&4294967295);var $flags580=(($arrayidx579)&4294967295);var $324=HEAP32[(($flags580)>>2)];var $and581=($324)&16384;var $tobool582=((($and581))|0)!=0;if($tobool582){__label__=152;;}else{__label__=153;;}
if(__label__==152){var $325=$thousands_exact;var $cmp584=((($325))|0)!=0;if($cmp584){__label__=154;break $land_lhs_true557$$if_end588$202;}}
var $326=$ph_out_addr;var $strlen=_strlen($326);var $endptr=(($326+$strlen)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__ZZL17TranslateNumber_1P10TranslatorPcS1_PjP8WORD_TABiE9str_pause)&4294967295);$dest$=$endptr;$stop$=$src$+2;if(($dest$%4)==($src$%4)&&2>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}}while(0);var $327=$flags_addr;var $328=HEAP32[(($327)>>2)];var $or589=($328)|-2147483648;HEAP32[(($327)>>2)]=$or589;var $329=HEAP32[((__ZL23speak_missing_thousands)>>2)];var $dec590=((($329)-1)&4294967295);HEAP32[((__ZL23speak_missing_thousands)>>2)]=$dec590;var $330=$skipwords;var $tobool591=((($330))|0)!=0;if($tobool591){__label__=155;;}else{__label__=156;;}
if(__label__==155){var $331=$skipwords;HEAP32[((_dictionary_skipwords)>>2)]=$331;;}
$retval=1;;}
var $332=$retval;STACKTOP=__stackBase__;return $332;return null;}
function __ZL15LookupThousandsP10TranslatoriiiPc($tr,$value,$thousandplex,$thousands_exact,$ph_out){var __stackBase__=STACKTOP;STACKTOP+=104;_memset(__stackBase__,0,104);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $value_addr;var $thousandplex_addr;var $thousands_exact_addr;var $ph_out_addr;var $found;var $found_value;var $string=__stackBase__;var $ph_of=__stackBase__+12;var $ph_thousands=__stackBase__+24;var $ph_buf=__stackBase__+64;$tr_addr=$tr;$value_addr=$value;$thousandplex_addr=$thousandplex;$thousands_exact_addr=$thousands_exact;$ph_out_addr=$ph_out;$found_value=0;var $arrayidx=(($ph_of)&4294967295);HEAP8[($arrayidx)]=0;var $0=$value_addr;var $cmp=((($0))|0)>0;if($cmp){__label__=1;;}else{__label__=12;;}
$if_then$$if_end36thread_pre_split$2:do{if(__label__==1){var $1=$thousands_exact_addr;var $and=($1)&1;var $tobool=((($and))|0)!=0;if($tobool){__label__=2;;}else{__label__=9;;}
$if_then1$$if_end27thread_pre_split$4:do{if(__label__==2){var $2=$thousands_exact_addr;var $and2=($2)&2;var $tobool3=((($and2))|0)!=0;if($tobool3){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $arraydecay=(($string)&4294967295);var $3=$value_addr;var $4=$thousandplex_addr;var $call=_sprintf($arraydecay,((__str42339)&4294967295),allocate([$3,0,0,0,$4,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $5=$tr_addr;var $arraydecay5=(($string)&4294967295);var $arraydecay6=(($ph_thousands)&4294967295);var $call7=__Z6LookupP10TranslatorPKcPc($5,$arraydecay5,$arraydecay6);$found_value=$call7;;}
var $6=$found_value;var $tobool8=((($6))|0)!=0;var $lnot=($tobool8)^1;var $conv=((($lnot))&1);var $7=HEAP32[((__ZL14number_control)>>2)];var $and9=($7)&1;var $and10=($and9)&($conv);var $tobool11=((($and10))|0)!=0;if($tobool11){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $arraydecay13=(($string)&4294967295);var $8=$value_addr;var $9=$thousandplex_addr;var $call14=_sprintf($arraydecay13,((__str43340)&4294967295),allocate([$8,0,0,0,$9,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $10=$tr_addr;var $arraydecay15=(($string)&4294967295);var $arraydecay16=(($ph_thousands)&4294967295);var $call17=__Z6LookupP10TranslatorPKcPc($10,$arraydecay15,$arraydecay16);$found_value=$call17;__lastLabel__=5;;}
else if(__label__==6){var $_pr=$found_value;__lastLabel__=6;;}
var $11=__lastLabel__==6?$_pr:($call17);var $tobool19=((($11))|0)!=0;if($tobool19){__label__=9;break $if_then1$$if_end27thread_pre_split$4;}
var $arraydecay21=(($string)&4294967295);var $12=$value_addr;var $13=$thousandplex_addr;var $call22=_sprintf($arraydecay21,((__str44341)&4294967295),allocate([$12,0,0,0,$13,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $14=$tr_addr;var $arraydecay23=(($string)&4294967295);var $arraydecay24=(($ph_thousands)&4294967295);var $call25=__Z6LookupP10TranslatorPKcPc($14,$arraydecay23,$arraydecay24);$found_value=$call25;__lastLabel__=8;__label__=10;break $if_then1$$if_end27thread_pre_split$4;}}while(0);if(__label__==9){var $_pr1=$found_value;__lastLabel__=9;;}
var $15=__lastLabel__==9?$_pr1:($call25);var $cmp28=((($15))|0)==0;if(!($cmp28)){__label__=12;break $if_then$$if_end36thread_pre_split$2;}
var $arraydecay30=(($string)&4294967295);var $16=$value_addr;var $17=$thousandplex_addr;var $call31=_sprintf($arraydecay30,((__str45342)&4294967295),allocate([$16,0,0,0,$17,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $18=$tr_addr;var $arraydecay32=(($string)&4294967295);var $arraydecay33=(($ph_thousands)&4294967295);var $call34=__Z6LookupP10TranslatorPKcPc($18,$arraydecay32,$arraydecay33);$found_value=$call34;__lastLabel__=11;__label__=13;break $if_then$$if_end36thread_pre_split$2;}}while(0);if(__label__==12){var $_pr2=$found_value;__lastLabel__=12;;}
var $19=__lastLabel__==12?$_pr2:($call34);var $cmp37=((($19))|0)==0;if($cmp37){__label__=14;;}else{__label__=36;;}
$if_then38$$if_end118$21:do{if(__label__==14){var $20=$value_addr;var $rem=((($20))|0)%100;var $cmp39=((($rem))|0)>=20;if($cmp39){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $21=$tr_addr;var $arraydecay41=(($ph_of)&4294967295);var $call42=__Z6LookupP10TranslatorPKcPc($21,((__str46343)&4294967295),$arraydecay41);;}
$found=0;var $22=$thousands_exact_addr;var $and44=($22)&1;var $tobool45=((($and44))|0)!=0;if($tobool45){__label__=17;;}else{__label__=28;;}
if(__label__==17){var $23=$thousands_exact_addr;var $and47=($23)&2;var $tobool48=((($and47))|0)!=0;if($tobool48){__label__=18;;}else{__label__=19;;}
if(__label__==18){var $arraydecay50=(($string)&4294967295);var $24=$value_addr;var $call51=__ZL9M_Varianti($24);var $25=$thousandplex_addr;var $call52=_sprintf($arraydecay50,((__str47344)&4294967295),allocate([$call51,0,0,0,$25,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));var $26=$tr_addr;var $arraydecay53=(($string)&4294967295);var $arraydecay54=(($ph_thousands)&4294967295);var $call55=__Z6LookupP10TranslatorPKcPc($26,$arraydecay53,$arraydecay54);$found=$call55;__lastLabel__=18;;}
else if(__label__==19){var $_pr3=$found;__lastLabel__=19;;}
var $27=__lastLabel__==19?$_pr3:($call55);var $tobool57=((($27))|0)!=0;if($tobool57){__label__=23;;}else{__label__=21;;}
$if_end67thread_pre_split$$land_lhs_true$32:do{if(__label__==21){var $28=HEAP32[((__ZL14number_control)>>2)];var $and58=($28)&1;var $tobool59=((($and58))|0)!=0;if(!($tobool59)){__label__=23;break $if_end67thread_pre_split$$land_lhs_true$32;}
var $arraydecay61=(($string)&4294967295);var $29=$value_addr;var $call62=__ZL9M_Varianti($29);var $30=$thousandplex_addr;var $call63=_sprintf($arraydecay61,((__str48345)&4294967295),allocate([$call62,0,0,0,$30,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));var $31=$tr_addr;var $arraydecay64=(($string)&4294967295);var $arraydecay65=(($ph_thousands)&4294967295);var $call66=__Z6LookupP10TranslatorPKcPc($31,$arraydecay64,$arraydecay65);$found=$call66;__lastLabel__=22;__label__=24;break $if_end67thread_pre_split$$land_lhs_true$32;}}while(0);if(__label__==23){var $_pr4=$found;__lastLabel__=23;;}
var $32=__lastLabel__==23?$_pr4:($call66);var $tobool68=((($32))|0)!=0;if($tobool68){__label__=26;;}else{__label__=25;;}
if(__label__==26){var $_pr5=$found;__lastLabel__=26;;}
else if(__label__==25){var $arraydecay70=(($string)&4294967295);var $33=$value_addr;var $call71=__ZL9M_Varianti($33);var $34=$thousandplex_addr;var $call72=_sprintf($arraydecay70,((__str49346)&4294967295),allocate([$call71,0,0,0,$34,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));var $35=$tr_addr;var $arraydecay73=(($string)&4294967295);var $arraydecay74=(($ph_thousands)&4294967295);var $call75=__Z6LookupP10TranslatorPKcPc($35,$arraydecay73,$arraydecay74);$found=$call75;__lastLabel__=25;;}
var $36=__lastLabel__==26?$_pr5:($call75);var $cmp78=((($36))|0)==0;if(!($cmp78)){__label__=36;break $if_then38$$if_end118$21;}}
var $arraydecay80=(($string)&4294967295);var $37=$value_addr;var $call81=__ZL9M_Varianti($37);var $38=$thousandplex_addr;var $call82=_sprintf($arraydecay80,((__str50347)&4294967295),allocate([$call81,0,0,0,$38,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));var $39=$tr_addr;var $arraydecay83=(($string)&4294967295);var $arraydecay84=(($ph_thousands)&4294967295);var $call85=__Z6LookupP10TranslatorPKcPc($39,$arraydecay83,$arraydecay84);var $cmp86=((($call85))|0)==0;if(!($cmp86)){__label__=36;break $if_then38$$if_end118$21;}
var $40=$thousandplex_addr;var $cmp88=((($40))|0)>3;if($cmp88){__label__=30;;}else{__label__=32;;}
$if_then89$$if_end100$44:do{if(__label__==30){var $arraydecay90=(($string)&4294967295);var $41=$thousandplex_addr;var $sub=((($41)-1)&4294967295);var $call91=_sprintf($arraydecay90,((__str18315)&4294967295),allocate([$sub,0,0,0],["i32",0,0,0],ALLOC_STACK));var $42=$tr_addr;var $arraydecay92=(($string)&4294967295);var $arraydecay93=(($ph_buf)&4294967295);var $call94=__Z6LookupP10TranslatorPKcPc($42,$arraydecay92,$arraydecay93);var $cmp95=((($call94))|0)==0;if(!($cmp95)){__label__=32;break $if_then89$$if_end100$44;}
var $43=$tr_addr;var $arraydecay97=(($ph_thousands)&4294967295);var $call98=__Z6LookupP10TranslatorPKcPc($43,((__str51348)&4294967295),$arraydecay97);HEAP32[((__ZL23speak_missing_thousands)>>2)]=3;;}}while(0);var $arrayidx101=(($ph_thousands)&4294967295);var $44=HEAP8[($arrayidx101)];var $conv102=(tempInt=(($44)),(tempInt>=128?tempInt-256:tempInt));var $cmp103=((($conv102))|0)==0;if(!($cmp103)){__label__=36;break $if_then38$$if_end118$21;}
var $arraydecay105=(($string)&4294967295);var $45=$value_addr;var $call106=_sprintf($arraydecay105,((__str52349)&4294967295),allocate([$45,0,0,0],["i32",0,0,0],ALLOC_STACK));var $46=$tr_addr;var $arraydecay107=(($string)&4294967295);var $arraydecay108=(($ph_thousands)&4294967295);var $call109=__Z6LookupP10TranslatorPKcPc($46,$arraydecay107,$arraydecay108);$found_value=$call109;var $cmp110=((($call109))|0)==0;if($cmp110){__label__=34;;}else{__label__=35;;}
if(__label__==34){var $47=$tr_addr;var $arraydecay112=(($ph_thousands)&4294967295);var $call113=__Z6LookupP10TranslatorPKcPc($47,((__str53350)&4294967295),$arraydecay112);;}
HEAP32[((__ZL23speak_missing_thousands)>>2)]=2;;}}while(0);var $48=$ph_out_addr;var $arraydecay119=(($ph_of)&4294967295);var $arraydecay120=(($ph_thousands)&4294967295);var $call121=_sprintf($48,((__str47699)&4294967295),allocate([$arraydecay119,0,0,0,$arraydecay120,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $49=$value_addr;var $cmp122=((($49))|0)==1;if($cmp122){__label__=37;;}else{__label__=40;;}
$land_lhs_true123$$if_end129$53:do{if(__label__==37){var $50=$thousandplex_addr;var $cmp124=((($50))|0)==1;if(!($cmp124)){__label__=40;break $land_lhs_true123$$if_end129$53;}
var $51=$tr_addr;var $langopts=(($51)&4294967295);var $numbers=(($langopts+184)&4294967295);var $52=HEAP32[(($numbers)>>2)];var $and126=($52)&2097152;var $tobool127=((($and126))|0)!=0;if(!($tobool127)){__label__=40;break $land_lhs_true123$$if_end129$53;}
$retval=1;__label__=41;break $land_lhs_true123$$if_end129$53;}}while(0);if(__label__==40){var $53=$found_value;$retval=$53;;}
var $54=$retval;STACKTOP=__stackBase__;return $54;return null;}
function __ZL10LookupNum3P10TranslatoriPciii($tr,$value,$ph_out,$suppress_null,$thousandplex,$control){var __stackBase__=STACKTOP;STACKTOP+=380;_memset(__stackBase__,0,380);var __label__;var __lastLabel__=null;var $tr_addr;var $value_addr;var $ph_out_addr;var $suppress_null_addr;var $thousandplex_addr;var $control_addr;var $found;var $hundreds;var $tensunits;var $x;var $ix;var $exact;var $ordinal;var $say_zero_hundred;var $string=__stackBase__;var $buf1=__stackBase__+12;var $buf2=__stackBase__+112;var $ph_100=__stackBase__+212;var $ph_10T=__stackBase__+232;var $ph_digits=__stackBase__+252;var $ph_thousands=__stackBase__+304;var $ph_hundred_and=__stackBase__+356;var $ph_thousand_and=__stackBase__+368;$tr_addr=$tr;$value_addr=$value;$ph_out_addr=$ph_out;$suppress_null_addr=$suppress_null;$thousandplex_addr=$thousandplex;$control_addr=$control;$say_zero_hundred=0;var $0=$control_addr;var $and=($0)&34;$ordinal=$and;var $1=$value_addr;var $div=((((($1))|0)/100)|0);$hundreds=$div;var $2=$value_addr;var $rem=((($2))|0)%100;$tensunits=$rem;var $arrayidx=(($buf1)&4294967295);HEAP8[($arrayidx)]=0;var $arrayidx1=(($ph_thousands)&4294967295);HEAP8[($arrayidx1)]=0;var $arrayidx2=(($ph_thousand_and)&4294967295);HEAP8[($arrayidx2)]=0;var $3=$tr_addr;var $langopts=(($3)&4294967295);var $numbers=(($langopts+184)&4294967295);var $4=HEAP32[(($numbers)>>2)];var $and3=($4)&4194304;var $tobool=((($and3))|0)!=0;if($tobool){__label__=1;;}else{__label__=4;;}
$land_lhs_true$$if_endthread_pre_split$2:do{if(__label__==1){var $5=$control_addr;var $and4=($5)&1;var $tobool5=((($and4))|0)!=0;if($tobool5){__label__=3;;}else{__label__=2;;}
if(__label__==2){var $6=$hundreds;var $cmp=((($6))|0)>=10;if($cmp){__lastLabel__=2;;}else{__lastLabel__=2;__label__=5;break $land_lhs_true$$if_endthread_pre_split$2;}}
$say_zero_hundred=1;__label__=4;break $land_lhs_true$$if_endthread_pre_split$2;}}while(0);if(__label__==4){var $_pr=$hundreds;__lastLabel__=4;;}
var $7=__lastLabel__==4?$_pr:($6);var $cmp6=((($7))|0)>0;if($cmp6){__label__=7;;}else{__label__=6;;}
$if_then9$$lor_lhs_false7$10:do{if(__label__==6){var $8=$say_zero_hundred;var $tobool8=((($8))|0)!=0;if($tobool8){__label__=7;break $if_then9$$lor_lhs_false7$10;}else{__label__=61;break $if_then9$$lor_lhs_false7$10;}}}while(0);if(__label__==7){$found=0;var $9=$ordinal;var $tobool10=((($9))|0)!=0;if($tobool10){__label__=8;;}else{__label__=12;;}
$land_lhs_true11$$if_then16$14:do{if(__label__==8){var $10=$tensunits;var $cmp12=((($10))|0)==0;if($cmp12){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $11=$tr_addr;var $arraydecay=(($ph_100)&4294967295);var $call=__Z6LookupP10TranslatorPKcPc($11,((__str35332)&4294967295),$arraydecay);$found=$call;__lastLabel__=9;;}
else if(__label__==10){var $_pr1=$found;__lastLabel__=10;;}
var $12=__lastLabel__==10?$_pr1:($call);var $cmp15=((($12))|0)==0;if($cmp15){__label__=12;break $land_lhs_true11$$if_then16$14;}else{__label__=17;break $land_lhs_true11$$if_then16$14;}}}while(0);$if_then16$$if_end27$20:do{if(__label__==12){var $13=$tensunits;var $cmp17=((($13))|0)==0;if($cmp17){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $14=$tr_addr;var $arraydecay19=(($ph_100)&4294967295);var $call20=__Z6LookupP10TranslatorPKcPc($14,((__str36333)&4294967295),$arraydecay19);$found=$call20;__lastLabel__=13;;}
else if(__label__==14){var $_pr3=$found;__lastLabel__=14;;}
var $15=__lastLabel__==14?$_pr3:($call20);var $tobool22=((($15))|0)!=0;if($tobool22){__label__=17;break $if_then16$$if_end27$20;}
var $16=$tr_addr;var $arraydecay24=(($ph_100)&4294967295);var $call25=__Z6LookupP10TranslatorPKcPc($16,((__str37334)&4294967295),$arraydecay24);;}}while(0);var $17=$tr_addr;var $langopts28=(($17)&4294967295);var $numbers29=(($langopts28+184)&4294967295);var $18=HEAP32[(($numbers29)>>2)];var $and30=($18)&2048;var $cmp31=((($and30))|0)!=0;var $19=$hundreds;if($cmp31){__label__=18;;}else{__label__=19;;}
$land_lhs_true32$$if_else$28:do{if(__label__==18){var $cmp33=((($19))|0)!=19;var $20=$hundreds;var $cmp35=((($20))|0)>=10;var $or_cond=($cmp33)&($cmp35);if($or_cond){__label__=20;break $land_lhs_true32$$if_else$28;}else{__label__=33;break $land_lhs_true32$$if_else$28;}}
else if(__label__==19){var $cmp35_old=((($19))|0)>=10;if($cmp35_old){__label__=20;break $land_lhs_true32$$if_else$28;}else{__label__=33;break $land_lhs_true32$$if_else$28;}}}while(0);if(__label__==20){var $arrayidx37=(($ph_digits)&4294967295);HEAP8[($arrayidx37)]=0;$exact=0;var $21=$value_addr;var $rem38=((($21))|0)%1000;var $cmp39=((($rem38))|0)==0;if($cmp39){__label__=21;;}else{__label__=22;;}
if(__label__==21){$exact=1;;}
var $22=$tr_addr;var $23=$hundreds;var $div42=((((($23))|0)/10)|0);var $24=$thousandplex_addr;var $add=((($24)+1)&4294967295);var $25=$exact;var $26=$ordinal;var $or=($26)|($25);var $arraydecay43=(($ph_10T)&4294967295);var $call44=__ZL15LookupThousandsP10TranslatoriiiPc($22,$div42,$add,$or,$arraydecay43);var $cmp45=((($call44))|0)==0;if($cmp45){__label__=23;;}else{__label__=26;;}
if(__label__==23){$x=0;var $27=$tr_addr;var $langopts47=(($27)&4294967295);var $numbers2=(($langopts47+188)&4294967295);var $28=HEAP32[(($numbers2)>>2)];var $29=$thousandplex_addr;var $add48=((($29)+1)&4294967295);var $shl=1<<($add48);var $and49=($shl)&($28);var $tobool50=((($and49))|0)!=0;if($tobool50){__label__=24;;}else{__label__=25;;}
if(__label__==24){$x=8;;}
var $30=$tr_addr;var $31=$hundreds;var $div53=((((($31))|0)/10)|0);var $32=$x;var $arraydecay54=(($ph_digits)&4294967295);var $call55=__ZL10LookupNum2P10TranslatoriiPc($30,$div53,$32,$arraydecay54);;}
var $33=$tr_addr;var $langopts57=(($33)&4294967295);var $numbers258=(($langopts57+188)&4294967295);var $34=HEAP32[(($numbers258)>>2)];var $and59=($34)&512;var $tobool60=((($and59))|0)!=0;var $arraydecay62=(($ph_thousands)&4294967295);if($tobool60){__label__=27;;}else{__label__=28;;}
if(__label__==27){var $arraydecay63=(($ph_10T)&4294967295);var $arraydecay64=(($ph_digits)&4294967295);var $call65=_sprintf($arraydecay62,((__str47699)&4294967295),allocate([$arraydecay63,0,0,0,$arraydecay64,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==28){var $arraydecay68=(($ph_digits)&4294967295);var $arraydecay69=(($ph_10T)&4294967295);var $call70=_sprintf($arraydecay62,((__str47699)&4294967295),allocate([$arraydecay68,0,0,0,$arraydecay69,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
var $35=$hundreds;var $rem72=((($35))|0)%10;$hundreds=$rem72;var $cmp73=((($rem72))|0)==0;if($cmp73){__label__=30;;}else{__label__=32;;}
$land_lhs_true74$$if_end78$46:do{if(__label__==30){var $36=$say_zero_hundred;var $cmp75=((($36))|0)==0;if(!($cmp75)){__label__=32;break $land_lhs_true74$$if_end78$46;}
var $arrayidx77=(($ph_100)&4294967295);HEAP8[($arrayidx77)]=0;;}}while(0);$suppress_null_addr=1;;}
var $arrayidx81=(($ph_digits)&4294967295);HEAP8[($arrayidx81)]=0;var $37=$hundreds;var $cmp82=((($37))|0)>0;if($cmp82){__label__=35;;}else{__label__=34;;}
$if_then85$$lor_lhs_false83$51:do{if(__label__==34){var $38=$say_zero_hundred;var $tobool84=((($38))|0)!=0;if($tobool84){__label__=35;break $if_then85$$lor_lhs_false83$51;}else{__label__=60;break $if_then85$$lor_lhs_false83$51;}}}while(0);$if_then85$$if_end166$53:do{if(__label__==35){var $39=$tr_addr;var $langopts86=(($39)&4294967295);var $numbers87=(($langopts86+184)&4294967295);var $40=HEAP32[(($numbers87)>>2)];var $and88=($40)&262144;var $tobool89=((($and88))|0)!=0;if($tobool89){__label__=36;;}else{__label__=39;;}
$land_lhs_true90$$if_end99$55:do{if(__label__==36){var $41=$control_addr;var $and91=($41)&1;var $tobool92=((($and91))|0)!=0;if($tobool92){__label__=38;;}else{__label__=37;;}
if(__label__==37){var $arrayidx94=(($ph_thousands)&4294967295);var $42=HEAP8[($arrayidx94)];var $conv=(tempInt=(($42)),(tempInt>=128?tempInt-256:tempInt));var $cmp95=((($conv))|0)!=0;if(!($cmp95)){__label__=39;break $land_lhs_true90$$if_end99$55;}}
var $43=$tr_addr;var $arraydecay97=(($ph_thousand_and)&4294967295);var $call98=__Z6LookupP10TranslatorPKcPc($43,((__str33330)&4294967295),$arraydecay97);;}}while(0);$suppress_null_addr=1;$found=0;var $44=$ordinal;var $tobool100=((($44))|0)!=0;if($tobool100){__label__=40;;}else{__label__=45;;}
$land_lhs_true101$$if_end124$61:do{if(__label__==40){var $45=$tensunits;var $cmp102=((($45))|0)==0;if($cmp102){__label__=42;;}else{__label__=41;;}
if(__label__==41){var $46=$tr_addr;var $langopts104=(($46)&4294967295);var $numbers2105=(($langopts104+188)&4294967295);var $47=HEAP32[(($numbers2105)>>2)];var $and106=($47)&4096;var $tobool107=((($and106))|0)!=0;if(!($tobool107)){__label__=45;break $land_lhs_true101$$if_end124$61;}}
var $arraydecay109=(($string)&4294967295);var $48=$hundreds;var $call110=_sprintf($arraydecay109,((__str39336)&4294967295),allocate([$48,0,0,0],["i32",0,0,0],ALLOC_STACK));var $49=$tr_addr;var $arraydecay111=(($string)&4294967295);var $arraydecay112=(($ph_digits)&4294967295);var $call113=__Z6LookupP10TranslatorPKcPc($49,$arraydecay111,$arraydecay112);$found=$call113;var $50=$tr_addr;var $langopts114=(($50)&4294967295);var $numbers2115=(($langopts114+188)&4294967295);var $51=HEAP32[(($numbers2115)>>2)];var $and116=($51)&4096;var $tobool117=((($and116))|0)!=0;if(!($tobool117)){__label__=45;break $land_lhs_true101$$if_end124$61;}
var $52=$tensunits;var $cmp119=((($52))|0)>0;if(!($cmp119)){__label__=45;break $land_lhs_true101$$if_end124$61;}
var $arraydecay121=(($ph_digits)&4294967295);var $call122=_strcat($arraydecay121,((__ZL11ph_ordinal2)&4294967295));;}}while(0);var $53=$hundreds;var $cmp125=((($53))|0)==0;if($cmp125){__label__=46;;}else{__label__=48;;}
$land_lhs_true126$$if_else131$69:do{if(__label__==46){var $54=$say_zero_hundred;var $tobool127=((($54))|0)!=0;if(!($tobool127)){__label__=48;break $land_lhs_true126$$if_else131$69;}
var $55=$tr_addr;var $arraydecay129=(($ph_digits)&4294967295);var $call130=__Z6LookupP10TranslatorPKcPc($55,((__str16313)&4294967295),$arraydecay129);__label__=60;break $if_then85$$if_end166$53;}}while(0);var $56=$found;var $tobool132=((($56))|0)!=0;if($tobool132){__label__=54;;}else{__label__=49;;}
$if_end149thread_pre_split$$land_lhs_true133$73:do{if(__label__==49){var $57=$tensunits;var $cmp134=((($57))|0)==0;if($cmp134){__label__=50;;}else{__label__=51;;}
if(__label__==50){var $arraydecay136=(($string)&4294967295);var $58=$hundreds;var $call137=_sprintf($arraydecay136,((__str40337)&4294967295),allocate([$58,0,0,0],["i32",0,0,0],ALLOC_STACK));var $59=$tr_addr;var $arraydecay138=(($string)&4294967295);var $arraydecay139=(($ph_digits)&4294967295);var $call140=__Z6LookupP10TranslatorPKcPc($59,$arraydecay138,$arraydecay139);$found=$call140;__lastLabel__=50;;}
else if(__label__==51){var $_pr4=$found;__lastLabel__=51;;}
var $60=__lastLabel__==51?$_pr4:($call140);var $tobool142=((($60))|0)!=0;if($tobool142){__label__=54;break $if_end149thread_pre_split$$land_lhs_true133$73;}
var $arraydecay144=(($string)&4294967295);var $61=$hundreds;var $call145=_sprintf($arraydecay144,((__str41338)&4294967295),allocate([$61,0,0,0],["i32",0,0,0],ALLOC_STACK));var $62=$tr_addr;var $arraydecay146=(($string)&4294967295);var $arraydecay147=(($ph_digits)&4294967295);var $call148=__Z6LookupP10TranslatorPKcPc($62,$arraydecay146,$arraydecay147);$found=$call148;__lastLabel__=53;__label__=55;break $if_end149thread_pre_split$$land_lhs_true133$73;}}while(0);if(__label__==54){var $_pr6=$found;__lastLabel__=54;;}
var $63=__lastLabel__==54?$_pr6:($call148);var $tobool150=((($63))|0)!=0;if($tobool150){__label__=56;;}else{__label__=57;;}
if(__label__==56){var $arrayidx152=(($ph_100)&4294967295);HEAP8[($arrayidx152)]=0;;}
else if(__label__==57){var $64=$hundreds;var $cmp154=((($64))|0)>1;if($cmp154){__label__=59;;}else{__label__=58;;}
if(__label__==58){var $65=$tr_addr;var $langopts156=(($65)&4294967295);var $numbers157=(($langopts156+184)&4294967295);var $66=HEAP32[(($numbers157)>>2)];var $and158=($66)&1024;var $cmp159=((($and158))|0)==0;if(!($cmp159)){__label__=60;break $if_then85$$if_end166$53;}}
var $67=$tr_addr;var $68=$hundreds;var $arraydecay161=(($ph_digits)&4294967295);var $call162=__ZL10LookupNum2P10TranslatoriiPc($67,$68,0,$arraydecay161);;}}}while(0);var $arraydecay167=(($buf1)&4294967295);var $arraydecay168=(($ph_thousands)&4294967295);var $arraydecay169=(($ph_thousand_and)&4294967295);var $arraydecay170=(($ph_digits)&4294967295);var $arraydecay171=(($ph_100)&4294967295);var $call172=_sprintf($arraydecay167,((__str20317)&4294967295),allocate([$arraydecay168,0,0,0,$arraydecay169,0,0,0,$arraydecay170,0,0,0,$arraydecay171,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
var $arrayidx174=(($ph_hundred_and)&4294967295);HEAP8[($arrayidx174)]=0;var $69=$tensunits;var $cmp175=((($69))|0)>0;if($cmp175){__label__=62;;}else{__label__=74;;}
$if_then176$$if_end217$91:do{if(__label__==62){var $70=$value_addr;var $cmp177=((($70))|0)>100;if($cmp177){__label__=65;;}else{__label__=63;;}
$if_then183$$lor_lhs_false178$93:do{if(__label__==63){var $71=$control_addr;var $and179=($71)&1;var $tobool180=((($and179))|0)!=0;if(!($tobool180)){__label__=69;break $if_then183$$lor_lhs_false178$93;}
var $72=$thousandplex_addr;var $cmp182=((($72))|0)==0;if($cmp182){__label__=65;break $if_then183$$lor_lhs_false178$93;}else{__label__=69;break $if_then183$$lor_lhs_false178$93;}}}while(0);$if_then183$$if_end199$96:do{if(__label__==65){var $73=$tr_addr;var $langopts184=(($73)&4294967295);var $numbers185=(($langopts184+184)&4294967295);var $74=HEAP32[(($numbers185)>>2)];var $and186=($74)&64;var $tobool187=((($and186))|0)!=0;if($tobool187){__label__=68;;}else{__label__=66;;}
if(__label__==66){var $75=$tr_addr;var $langopts189=(($75)&4294967295);var $numbers190=(($langopts189+184)&4294967295);var $76=HEAP32[(($numbers190)>>2)];var $and191=($76)&8388608;var $tobool192=((($and191))|0)!=0;if(!($tobool192)){__label__=69;break $if_then183$$if_end199$96;}
var $77=$tensunits;var $cmp194=((($77))|0)<10;if(!($cmp194)){__label__=69;break $if_then183$$if_end199$96;}}
var $78=$tr_addr;var $arraydecay196=(($ph_hundred_and)&4294967295);var $call197=__Z6LookupP10TranslatorPKcPc($78,((__str33330)&4294967295),$arraydecay196);;}}while(0);var $79=$tr_addr;var $langopts200=(($79)&4294967295);var $numbers201=(($langopts200+184)&4294967295);var $80=HEAP32[(($numbers201)>>2)];var $and202=($80)&524288;var $tobool203=((($and202))|0)!=0;if(!($tobool203)){__label__=74;break $if_then176$$if_end217$91;}
var $81=$hundreds;var $cmp205=((($81))|0)==0;if(!($cmp205)){__label__=74;break $if_then176$$if_end217$91;}
var $82=$control_addr;var $and207=($82)&1;var $tobool208=((($and207))|0)!=0;if($tobool208){__label__=73;;}else{__label__=72;;}
if(__label__==72){var $arrayidx210=(($ph_thousands)&4294967295);var $83=HEAP8[($arrayidx210)];var $conv211=(tempInt=(($83)),(tempInt>=128?tempInt-256:tempInt));var $cmp212=((($conv211))|0)!=0;if(!($cmp212)){__label__=74;break $if_then176$$if_end217$91;}}
var $84=$tr_addr;var $arraydecay214=(($ph_hundred_and)&4294967295);var $call215=__Z6LookupP10TranslatorPKcPc($84,((__str33330)&4294967295),$arraydecay214);;}}while(0);var $arrayidx218=(($buf2)&4294967295);HEAP8[($arrayidx218)]=0;var $85=$tensunits;var $cmp219=((($85))|0)!=0;if($cmp219){__label__=76;;}else{__label__=75;;}
$if_then222$$lor_lhs_false220$109:do{if(__label__==75){var $86=$suppress_null_addr;var $cmp221=((($86))|0)==0;if($cmp221){__label__=76;break $if_then222$$lor_lhs_false220$109;}
var $102=HEAP8[(((__ZL11ph_ordinal2)&4294967295))];var $conv262=(tempInt=(($102)),(tempInt>=128?tempInt-256:tempInt));var $cmp263=((($conv262))|0)!=0;if(!($cmp263)){__label__=94;break $if_then222$$lor_lhs_false220$109;}
var $arraydecay265=(($buf1)&4294967295);var $call266=_strlen($arraydecay265);$ix=$call266;var $103=$ix;var $cmp267=((($103))|0)>0;if($cmp267){__label__=91;;}else{__label__=93;;}
$land_lhs_true268$$if_end275$113:do{if(__label__==91){var $104=$ix;var $sub=((($104)-1)&4294967295);var $arrayidx269=(($buf1+$sub)&4294967295);var $105=HEAP8[($arrayidx269)];var $conv270=(tempInt=(($105)),(tempInt>=128?tempInt-256:tempInt));var $cmp271=((($conv270))|0)==10;if(!($cmp271)){__label__=93;break $land_lhs_true268$$if_end275$113;}
var $106=$ix;var $sub273=((($106)-1)&4294967295);var $arrayidx274=(($buf1+$sub273)&4294967295);HEAP8[($arrayidx274)]=0;;}}while(0);var $arraydecay276=(($buf2)&4294967295);var $call277=_strcpy($arraydecay276,((__ZL11ph_ordinal2)&4294967295));__label__=94;break $if_then222$$lor_lhs_false220$109;}}while(0);$if_then222$$if_end279$117:do{if(__label__==76){$x=0;var $87=$thousandplex_addr;var $cmp223=((($87))|0)==0;if($cmp223){__label__=77;;}else{__label__=84;;}
$if_then224$$if_else240$119:do{if(__label__==77){$x=2;var $88=$ordinal;var $tobool225=((($88))|0)!=0;if($tobool225){__label__=78;;}else{__label__=79;;}
if(__label__==78){$x=3;;}
var $89=$value_addr;var $cmp228=((($89))|0)<100;if($cmp228){__label__=80;;}else{__label__=82;;}
$land_lhs_true229$$if_end234$124:do{if(__label__==80){var $90=$control_addr;var $and230=($90)&1;var $tobool231=((($and230))|0)!=0;if($tobool231){__label__=82;break $land_lhs_true229$$if_end234$124;}
var $91=$x;var $or233=($91)|4;$x=$or233;;}}while(0);var $92=$ordinal;var $and235=($92)&32;var $tobool236=((($and235))|0)!=0;if(!($tobool236)){__label__=86;break $if_then224$$if_else240$119;}
var $93=$x;var $or238=($93)|32;$x=$or238;;}
else if(__label__==84){var $94=$tr_addr;var $langopts241=(($94)&4294967295);var $numbers2242=(($langopts241+188)&4294967295);var $95=HEAP32[(($numbers2242)>>2)];var $96=$thousandplex_addr;var $shl243=1<<($96);var $and244=($shl243)&($95);var $tobool245=((($and244))|0)!=0;if(!($tobool245)){__label__=86;break $if_then224$$if_else240$119;}
$x=8;;}}while(0);var $97=$tr_addr;var $98=$tensunits;var $99=$x;var $arraydecay249=(($buf2)&4294967295);var $call250=__ZL10LookupNum2P10TranslatoriiPc($97,$98,$99,$arraydecay249);var $cmp251=((($call250))|0)!=0;if(!($cmp251)){__label__=94;break $if_then222$$if_end279$117;}
var $100=$tr_addr;var $langopts253=(($100)&4294967295);var $numbers254=(($langopts253+184)&4294967295);var $101=HEAP32[(($numbers254)>>2)];var $and255=($101)&128;var $tobool256=((($and255))|0)!=0;if(!($tobool256)){__label__=94;break $if_then222$$if_end279$117;}
var $arrayidx258=(($ph_hundred_and)&4294967295);HEAP8[($arrayidx258)]=0;;}}while(0);var $107=$ph_out_addr;var $arraydecay280=(($buf1)&4294967295);var $arraydecay281=(($ph_hundred_and)&4294967295);var $arraydecay282=(($buf2)&4294967295);var $call283=_sprintf($107,((__str6549)&4294967295),allocate([$arraydecay280,0,0,0,$arraydecay281,0,0,0,$arraydecay282,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));STACKTOP=__stackBase__;return;return;}
function __ZL10LookupNum2P10TranslatoriiPc($tr,$value,$control,$ph_out){var __stackBase__=STACKTOP;STACKTOP+=148;_memset(__stackBase__,0,148);var __label__;var __lastLabel__=null;var $tr_addr;var $value_addr;var $control_addr;var $ph_out_addr;var $found;var $ix;var $units;var $tens;var $used_and;var $found_ordinal;var $next_phtype;var $ord_type;var $string=__stackBase__;var $ph_ordinal=__stackBase__+12;var $ph_tens=__stackBase__+32;var $ph_digits=__stackBase__+84;var $ph_and=__stackBase__+136;$tr_addr=$tr;$value_addr=$value;$control_addr=$control;$ph_out_addr=$ph_out;$used_and=0;$found_ordinal=0;$ord_type=111;var $0=$value_addr;var $rem=((($0))|0)%10;$units=$rem;var $1=$value_addr;var $div=((((($1))|0)/10)|0);$tens=$div;$found=0;var $arrayidx=(($ph_ordinal)&4294967295);HEAP8[($arrayidx)]=0;var $arrayidx1=(($ph_tens)&4294967295);HEAP8[($arrayidx1)]=0;var $arrayidx2=(($ph_digits)&4294967295);HEAP8[($arrayidx2)]=0;var $arrayidx3=(($ph_and)&4294967295);HEAP8[($arrayidx3)]=0;var $2=$control_addr;var $and=($2)&32;var $tobool=((($and))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){$ord_type=113;;}
var $3=$control_addr;var $and4=($3)&2;var $tobool5=((($and4))|0)!=0;var $4=HEAP32[((__ZL14n_digit_lookup)>>2)];var $cmp=((($4))|0)==2;var $or_cond=($tobool5)&($cmp);if($or_cond){__label__=3;;}else{__label__=4;;}
$if_then6$$if_else$5:do{if(__label__==3){var $5=$ph_out_addr;var $6=HEAP32[((__ZL12digit_lookup)>>2)];var $call=_strcpy($5,$6);;}
else if(__label__==4){var $7=HEAP32[((__ZL12digit_lookup)>>2)];var $arrayidx7=(($7)&4294967295);var $8=HEAP8[($arrayidx7)];var $conv=(tempInt=(($8)),(tempInt>=128?tempInt-256:tempInt));var $cmp8=((($conv))|0)==0;if($cmp8){__label__=5;;}else{__label__=23;;}
$if_then9$$if_end72$8:do{if(__label__==5){var $9=$control_addr;var $and10=($9)&8;var $tobool11=((($and10))|0)!=0;if($tobool11){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $arraydecay=(($string)&4294967295);var $10=$value_addr;var $call13=_sprintf($arraydecay,((__str23320)&4294967295),allocate([$10,0,0,0],["i32",0,0,0],ALLOC_STACK));var $11=$tr_addr;var $arraydecay14=(($string)&4294967295);var $arraydecay15=(($ph_digits)&4294967295);var $call16=__Z6LookupP10TranslatorPKcPc($11,$arraydecay14,$arraydecay15);$found=$call16;__lastLabel__=6;;}
else if(__label__==7){var $12=$control_addr;var $and18=($12)&1;var $tobool19=((($and18))|0)!=0;if($tobool19){__label__=8;;}else{__label__=14;;}
if(__label__==8){var $arraydecay21=(($ph_ordinal)&4294967295);var $call22=_strcpy($arraydecay21,((__ZL11ph_ordinal2)&4294967295));var $13=$control_addr;var $and23=($13)&4;var $tobool24=((($and23))|0)!=0;if($tobool24){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $arraydecay26=(($string)&4294967295);var $14=$value_addr;var $15=$ord_type;var $call27=_sprintf($arraydecay26,((__str24321)&4294967295),allocate([$14,0,0,0,$15,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $16=$tr_addr;var $arraydecay28=(($string)&4294967295);var $arraydecay29=(($ph_digits)&4294967295);var $call30=__Z6LookupP10TranslatorPKcPc($16,$arraydecay28,$arraydecay29);$found=$call30;__lastLabel__=9;;}
else if(__label__==10){var $_pr=$found;__lastLabel__=10;;}
var $17=__lastLabel__==10?$_pr:($call30);var $cmp32=((($17))|0)==0;if($cmp32){__label__=12;;}else{__label__=13;;}
if(__label__==12){var $arraydecay34=(($string)&4294967295);var $18=$value_addr;var $19=$ord_type;var $call35=_sprintf($arraydecay34,((__str25322)&4294967295),allocate([$18,0,0,0,$19,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $20=$tr_addr;var $arraydecay36=(($string)&4294967295);var $arraydecay37=(($ph_digits)&4294967295);var $call38=__Z6LookupP10TranslatorPKcPc($20,$arraydecay36,$arraydecay37);$found=$call38;;}
var $21=$found;$found_ordinal=$21;__lastLabel__=13;;}
else if(__label__==14){var $_pr1=$found;__lastLabel__=14;;}}
var $22=__lastLabel__==14?$_pr1:(__lastLabel__==13?$21:($call16));var $cmp42=((($22))|0)==0;if(!($cmp42)){__label__=23;break $if_then9$$if_end72$8;}
var $23=$control_addr;var $and44=($23)&2;var $tobool45=((($and44))|0)!=0;if($tobool45){__label__=17;;}else{__label__=19;;}
if(__label__==17){var $24=HEAP32[((__ZL14number_control)>>2)];var $and47=($24)&1;var $tobool48=((($and47))|0)!=0;if($tobool48){__label__=18;;}else{__label__=20;;}
if(__label__==18){var $arraydecay50=(($string)&4294967295);var $25=$value_addr;var $call51=_sprintf($arraydecay50,((__str26323)&4294967295),allocate([$25,0,0,0],["i32",0,0,0],ALLOC_STACK));var $26=$tr_addr;var $arraydecay52=(($string)&4294967295);var $arraydecay53=(($ph_digits)&4294967295);var $call54=__Z6LookupP10TranslatorPKcPc($26,$arraydecay52,$arraydecay53);$found=$call54;__lastLabel__=18;;}
else if(__label__==20){var $_pr2=$found;__lastLabel__=20;;}}
else if(__label__==19){var $arraydecay57=(($string)&4294967295);var $27=$value_addr;var $call58=_sprintf($arraydecay57,((__str27324)&4294967295),allocate([$27,0,0,0],["i32",0,0,0],ALLOC_STACK));var $28=$tr_addr;var $arraydecay59=(($string)&4294967295);var $arraydecay60=(($ph_digits)&4294967295);var $call61=__Z6LookupP10TranslatorPKcPc($28,$arraydecay59,$arraydecay60);$found=$call61;__lastLabel__=19;;}
var $29=__lastLabel__==20?$_pr2:(__lastLabel__==18?$call54:($call61));var $tobool63=((($29))|0)!=0;if($tobool63){__label__=23;break $if_then9$$if_end72$8;}
var $arraydecay65=(($string)&4294967295);var $30=$value_addr;var $call66=_sprintf($arraydecay65,((__str28325)&4294967295),allocate([$30,0,0,0],["i32",0,0,0],ALLOC_STACK));var $31=$tr_addr;var $arraydecay67=(($string)&4294967295);var $arraydecay68=(($ph_digits)&4294967295);var $call69=__Z6LookupP10TranslatorPKcPc($31,$arraydecay67,$arraydecay68);$found=$call69;;}}while(0);var $32=$control_addr;var $and73=($32)&16;var $tobool74=((($and73))|0)!=0;if($tobool74){__label__=24;;}else{__label__=26;;}
$land_lhs_true75$$if_else80$34:do{if(__label__==24){var $33=$value_addr;var $cmp76=((($33))|0)<10;if(!($cmp76)){__label__=26;break $land_lhs_true75$$if_else80$34;}
var $34=$tr_addr;var $arraydecay78=(($ph_tens)&4294967295);var $call79=__Z6LookupP10TranslatorPKcPc($34,((__str16313)&4294967295),$arraydecay78);__label__=61;break $land_lhs_true75$$if_else80$34;}}while(0);$if_end221$$if_else80$37:do{if(__label__==26){var $35=$found;var $tobool81=((($35))|0)!=0;if($tobool81){__label__=27;;}else{__label__=28;;}
if(__label__==27){var $arrayidx83=(($ph_tens)&4294967295);HEAP8[($arrayidx83)]=0;;}
else if(__label__==28){var $36=$control_addr;var $and85=($36)&1;var $tobool86=((($and85))|0)!=0;if($tobool86){__label__=29;;}else{__label__=36;;}
$land_lhs_true87$$if_end114$42:do{if(__label__==29){var $37=$units;var $cmp88=((($37))|0)==0;if($cmp88){__label__=32;;}else{__label__=30;;}
$if_then95$$lor_lhs_false$44:do{if(__label__==30){var $38=$tr_addr;var $langopts=(($38)&4294967295);var $numbers=(($langopts+184)&4294967295);var $39=HEAP32[(($numbers)>>2)];var $and89=($39)&16;var $tobool90=((($and89))|0)!=0;if($tobool90){__label__=32;break $if_then95$$lor_lhs_false$44;}
var $40=$tr_addr;var $langopts92=(($40)&4294967295);var $numbers2=(($langopts92+188)&4294967295);var $41=HEAP32[(($numbers2)>>2)];var $and93=($41)&4096;var $tobool94=((($and93))|0)!=0;if(!($tobool94)){__label__=36;break $land_lhs_true87$$if_end114$42;}}}while(0);var $arraydecay96=(($string)&4294967295);var $42=$tens;var $43=$ord_type;var $call97=_sprintf($arraydecay96,((__str29326)&4294967295),allocate([$42,0,0,0,$43,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $44=$tr_addr;var $arraydecay98=(($string)&4294967295);var $arraydecay99=(($ph_tens)&4294967295);var $call100=__Z6LookupP10TranslatorPKcPc($44,$arraydecay98,$arraydecay99);var $cmp101=((($call100))|0)!=0;if(!($cmp101)){__label__=36;break $land_lhs_true87$$if_end114$42;}
$found_ordinal=1;var $45=$units;var $cmp103=((($45))|0)!=0;if(!($cmp103)){__label__=38;break $land_lhs_true87$$if_end114$42;}
var $46=$tr_addr;var $langopts105=(($46)&4294967295);var $numbers2106=(($langopts105+188)&4294967295);var $47=HEAP32[(($numbers2106)>>2)];var $and107=($47)&4096;var $tobool108=((($and107))|0)!=0;if(!($tobool108)){__label__=36;break $land_lhs_true87$$if_end114$42;}
var $arraydecay110=(($ph_tens)&4294967295);var $call111=_strcat($arraydecay110,((__ZL11ph_ordinal2)&4294967295));__label__=36;break $land_lhs_true87$$if_end114$42;}}while(0);$if_end114$$if_end122$51:do{if(__label__==36){var $_pr3=$found_ordinal;var $cmp115=((($_pr3))|0)==0;if(!($cmp115)){__label__=38;break $if_end114$$if_end122$51;}
var $arraydecay117=(($string)&4294967295);var $48=$tens;var $call118=_sprintf($arraydecay117,((__str30327)&4294967295),allocate([$48,0,0,0],["i32",0,0,0],ALLOC_STACK));var $49=$tr_addr;var $arraydecay119=(($string)&4294967295);var $arraydecay120=(($ph_tens)&4294967295);var $call121=__Z6LookupP10TranslatorPKcPc($49,$arraydecay119,$arraydecay120);;}}while(0);var $arrayidx123=(($ph_tens)&4294967295);var $50=HEAP8[($arrayidx123)];var $conv124=(tempInt=(($50)),(tempInt>=128?tempInt-256:tempInt));var $cmp125=((($conv124))|0)==0;if($cmp125){__label__=39;;}else{__label__=41;;}
$land_lhs_true126$$if_end139$55:do{if(__label__==39){var $51=$tr_addr;var $langopts127=(($51)&4294967295);var $numbers128=(($langopts127+184)&4294967295);var $52=HEAP32[(($numbers128)>>2)];var $and129=($52)&1048576;var $tobool130=((($and129))|0)!=0;if(!($tobool130)){__label__=41;break $land_lhs_true126$$if_end139$55;}
var $53=$value_addr;var $rem132=((($53))|0)%20;$units=$rem132;var $arraydecay133=(($string)&4294967295);var $54=$tens;var $and134=($54)&254;var $call135=_sprintf($arraydecay133,((__str30327)&4294967295),allocate([$and134,0,0,0],["i32",0,0,0],ALLOC_STACK));var $55=$tr_addr;var $arraydecay136=(($string)&4294967295);var $arraydecay137=(($ph_tens)&4294967295);var $call138=__Z6LookupP10TranslatorPKcPc($55,$arraydecay136,$arraydecay137);;}}while(0);var $arrayidx140=(($ph_digits)&4294967295);HEAP8[($arrayidx140)]=0;var $56=$units;var $cmp141=((($56))|0)>0;if(!($cmp141)){__label__=61;break $if_end221$$if_else80$37;}
$found=0;var $57=$control_addr;var $and143=($57)&2;var $tobool144=((($and143))|0)!=0;if($tobool144){__label__=43;;}else{__label__=45;;}
$land_lhs_true145$$if_else153$60:do{if(__label__==43){var $58=HEAP32[((__ZL12digit_lookup)>>2)];var $arrayidx146=(($58)&4294967295);var $59=HEAP8[($arrayidx146)];var $conv147=(tempInt=(($59)),(tempInt>=128?tempInt-256:tempInt));var $cmp148=((($conv147))|0)!=0;if(!($cmp148)){__label__=45;break $land_lhs_true145$$if_else153$60;}
var $arraydecay150=(($ph_digits)&4294967295);var $60=HEAP32[((__ZL12digit_lookup)>>2)];var $call151=_strcpy($arraydecay150,$60);$found_ordinal=1;var $arrayidx152=(($ph_ordinal)&4294967295);HEAP8[($arrayidx152)]=0;__label__=61;break $if_end221$$if_else80$37;}}while(0);var $61=$control_addr;var $and154=($61)&8;var $tobool155=((($and154))|0)!=0;if($tobool155){__label__=46;;}else{__label__=47;;}
if(__label__==46){var $arraydecay157=(($string)&4294967295);var $62=$units;var $call158=_sprintf($arraydecay157,((__str23320)&4294967295),allocate([$62,0,0,0],["i32",0,0,0],ALLOC_STACK));var $63=$tr_addr;var $arraydecay159=(($string)&4294967295);var $arraydecay160=(($ph_digits)&4294967295);var $call161=__Z6LookupP10TranslatorPKcPc($63,$arraydecay159,$arraydecay160);$found=$call161;;}
var $64=$control_addr;var $and163=($64)&1;var $tobool164=((($and163))|0)!=0;if($tobool164){__label__=48;;}else{__label__=51;;}
$land_lhs_true165$$if_end179$67:do{if(__label__==48){var $65=$tr_addr;var $langopts166=(($65)&4294967295);var $numbers167=(($langopts166+184)&4294967295);var $66=HEAP32[(($numbers167)>>2)];var $and168=($66)&16;var $cmp169=((($and168))|0)==0;if(!($cmp169)){__label__=51;break $land_lhs_true165$$if_end179$67;}
var $arraydecay171=(($string)&4294967295);var $67=$units;var $68=$ord_type;var $call172=_sprintf($arraydecay171,((__str25322)&4294967295),allocate([$67,0,0,0,$68,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $69=$tr_addr;var $arraydecay173=(($string)&4294967295);var $arraydecay174=(($ph_digits)&4294967295);var $call175=__Z6LookupP10TranslatorPKcPc($69,$arraydecay173,$arraydecay174);$found=$call175;var $cmp176=((($call175))|0)!=0;if(!($cmp176)){__label__=52;break $land_lhs_true165$$if_end179$67;}
$found_ordinal=1;__label__=51;break $land_lhs_true165$$if_end179$67;}}while(0);if(__label__==51){var $_pr5=$found;var $cmp180=((($_pr5))|0)==0;if(!($cmp180)){__label__=61;break $if_end221$$if_else80$37;}}
var $70=HEAP32[((__ZL14number_control)>>2)];var $and182=($70)&1;var $tobool183=((($and182))|0)!=0;if($tobool183){__label__=53;;}else{__label__=55;;}
$land_lhs_true184$$if_else193$74:do{if(__label__==53){var $71=$control_addr;var $and185=($71)&2;var $tobool186=((($and185))|0)!=0;if(!($tobool186)){__label__=55;break $land_lhs_true184$$if_else193$74;}
var $arraydecay188=(($string)&4294967295);var $72=$units;var $call189=_sprintf($arraydecay188,((__str26323)&4294967295),allocate([$72,0,0,0],["i32",0,0,0],ALLOC_STACK));var $73=$tr_addr;var $arraydecay190=(($string)&4294967295);var $arraydecay191=(($ph_digits)&4294967295);var $call192=__Z6LookupP10TranslatorPKcPc($73,$arraydecay190,$arraydecay191);$found=$call192;__lastLabel__=54;__label__=59;break $land_lhs_true184$$if_else193$74;}}while(0);$if_end209$$if_else193$77:do{if(__label__==55){var $74=$control_addr;var $and194=($74)&2;var $cmp195=((($and194))|0)==0;if($cmp195){__label__=57;;}else{__label__=56;;}
$if_then201$$lor_lhs_false196$79:do{if(__label__==56){var $75=$tr_addr;var $langopts197=(($75)&4294967295);var $numbers198=(($langopts197+184)&4294967295);var $76=HEAP32[(($numbers198)>>2)];var $and199=($76)&16;var $cmp200=((($and199))|0)!=0;if($cmp200){__label__=57;break $if_then201$$lor_lhs_false196$79;}
var $_pr7=$found;__lastLabel__=58;__label__=59;break $if_end209$$if_else193$77;}}while(0);var $arraydecay202=(($string)&4294967295);var $77=$units;var $call203=_sprintf($arraydecay202,((__str27324)&4294967295),allocate([$77,0,0,0],["i32",0,0,0],ALLOC_STACK));var $78=$tr_addr;var $arraydecay204=(($string)&4294967295);var $arraydecay205=(($ph_digits)&4294967295);var $call206=__Z6LookupP10TranslatorPKcPc($78,$arraydecay204,$arraydecay205);$found=$call206;__lastLabel__=57;;}}while(0);var $79=__lastLabel__==58?$_pr7:(__lastLabel__==54?$call192:($call206));var $cmp210=((($79))|0)==0;if(!($cmp210)){__label__=61;break $if_end221$$if_else80$37;}
var $arraydecay212=(($string)&4294967295);var $80=$units;var $call213=_sprintf($arraydecay212,((__str28325)&4294967295),allocate([$80,0,0,0],["i32",0,0,0],ALLOC_STACK));var $81=$tr_addr;var $arraydecay214=(($string)&4294967295);var $arraydecay215=(($ph_digits)&4294967295);var $call216=__Z6LookupP10TranslatorPKcPc($81,$arraydecay214,$arraydecay215);;}}}while(0);var $82=$control_addr;var $and222=($82)&1;var $tobool223=((($and222))|0)!=0;if($tobool223){__label__=62;;}else{__label__=70;;}
$land_lhs_true224$$if_end251$86:do{if(__label__==62){var $83=$found_ordinal;var $cmp225=((($83))|0)==0;if(!($cmp225)){__label__=70;break $land_lhs_true224$$if_end251$86;}
var $arrayidx227=(($ph_ordinal)&4294967295);var $84=HEAP8[($arrayidx227)];var $conv228=(tempInt=(($84)),(tempInt>=128?tempInt-256:tempInt));var $cmp229=((($conv228))|0)==0;if(!($cmp229)){__label__=70;break $land_lhs_true224$$if_end251$86;}
var $85=$value_addr;var $cmp231=((($85))|0)>=20;if($cmp231){__label__=65;;}else{__label__=68;;}
$land_lhs_true232$$if_end243$90:do{if(__label__==65){var $86=$value_addr;var $rem233=((($86))|0)%10;var $cmp234=((($rem233))|0)==0;if($cmp234){__label__=67;;}else{__label__=66;;}
if(__label__==66){var $87=$tr_addr;var $langopts236=(($87)&4294967295);var $numbers237=(($langopts236+184)&4294967295);var $88=HEAP32[(($numbers237)>>2)];var $and238=($88)&16;var $tobool239=((($and238))|0)!=0;if(!($tobool239)){__label__=68;break $land_lhs_true232$$if_end243$90;}}
var $89=$tr_addr;var $arraydecay241=(($ph_ordinal)&4294967295);var $call242=__Z6LookupP10TranslatorPKcPc($89,((__str31328)&4294967295),$arraydecay241);;}}while(0);var $arrayidx244=(($ph_ordinal)&4294967295);var $90=HEAP8[($arrayidx244)];var $conv245=(tempInt=(($90)),(tempInt>=128?tempInt-256:tempInt));var $cmp246=((($conv245))|0)==0;if(!($cmp246)){__label__=70;break $land_lhs_true224$$if_end251$86;}
var $91=$tr_addr;var $arraydecay248=(($ph_ordinal)&4294967295);var $call249=__Z6LookupP10TranslatorPKcPc($91,((__str32329)&4294967295),$arraydecay248);;}}while(0);var $92=$tr_addr;var $langopts252=(($92)&4294967295);var $numbers253=(($langopts252+184)&4294967295);var $93=HEAP32[(($numbers253)>>2)];var $and254=($93)&48;var $tobool255=((($and254))|0)!=0;if($tobool255){__label__=71;;}else{__label__=79;;}
$land_lhs_true256$$if_else291$98:do{if(__label__==71){var $arrayidx257=(($ph_tens)&4294967295);var $94=HEAP8[($arrayidx257)];var $conv258=(tempInt=(($94)),(tempInt>=128?tempInt-256:tempInt));var $cmp259=((($conv258))|0)!=0;if(!($cmp259)){__label__=79;break $land_lhs_true256$$if_else291$98;}
var $arrayidx261=(($ph_digits)&4294967295);var $95=HEAP8[($arrayidx261)];var $conv262=(tempInt=(($95)),(tempInt>=128?tempInt-256:tempInt));var $cmp263=((($conv262))|0)!=0;if(!($cmp263)){__label__=79;break $land_lhs_true256$$if_else291$98;}
var $96=$tr_addr;var $arraydecay265=(($ph_and)&4294967295);var $call266=__Z6LookupP10TranslatorPKcPc($96,((__str33330)&4294967295),$arraydecay265);var $97=$tr_addr;var $langopts267=(($97)&4294967295);var $numbers2268=(($langopts267+188)&4294967295);var $98=HEAP32[(($numbers2268)>>2)];var $and269=($98)&4096;var $tobool270=((($and269))|0)!=0;if($tobool270){__label__=74;;}else{__label__=75;;}
if(__label__==74){var $arrayidx272=(($ph_and)&4294967295);HEAP8[($arrayidx272)]=0;;}
var $99=$tr_addr;var $langopts274=(($99)&4294967295);var $numbers275=(($langopts274+184)&4294967295);var $100=HEAP32[(($numbers275)>>2)];var $and276=($100)&16;var $tobool277=((($and276))|0)!=0;var $101=$ph_out_addr;if($tobool277){__label__=76;;}else{__label__=77;;}
if(__label__==76){var $arraydecay279=(($ph_digits)&4294967295);var $arraydecay280=(($ph_and)&4294967295);var $arraydecay281=(($ph_tens)&4294967295);var $arraydecay282=(($ph_ordinal)&4294967295);var $call283=_sprintf($101,((__str20317)&4294967295),allocate([$arraydecay279,0,0,0,$arraydecay280,0,0,0,$arraydecay281,0,0,0,$arraydecay282,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==77){var $arraydecay285=(($ph_tens)&4294967295);var $arraydecay286=(($ph_and)&4294967295);var $arraydecay287=(($ph_digits)&4294967295);var $arraydecay288=(($ph_ordinal)&4294967295);var $call289=_sprintf($101,((__str20317)&4294967295),allocate([$arraydecay285,0,0,0,$arraydecay286,0,0,0,$arraydecay287,0,0,0,$arraydecay288,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
$used_and=1;__label__=88;break $if_then6$$if_else$5;}}while(0);var $102=$tr_addr;var $langopts292=(($102)&4294967295);var $numbers293=(($langopts292+184)&4294967295);var $103=HEAP32[(($numbers293)>>2)];var $and294=($103)&512;var $tobool295=((($and294))|0)!=0;if($tobool295){__label__=80;;}else{__label__=87;;}
$if_then296$$if_end329$110:do{if(__label__==80){var $arraydecay297=(($ph_tens)&4294967295);var $call298=_strlen($arraydecay297);var $sub=((($call298)-1)&4294967295);$ix=$sub;var $cmp299=((($sub))|0)>=0;if(!($cmp299)){__label__=87;break $if_then296$$if_end329$110;}
var $arrayidx301=(($ph_digits)&4294967295);var $104=HEAP8[($arrayidx301)];var $conv302=(tempInt=(($104)),(tempInt>=128?tempInt-256:tempInt));var $cmp303=((($conv302))|0)!=0;if(!($cmp303)){__label__=87;break $if_then296$$if_end329$110;}
var $arrayidx305=(($ph_digits)&4294967295);var $105=HEAP8[($arrayidx305)];var $conv306=(tempInt=(($105)),(tempInt>=128?tempInt-256:tempInt));var $arrayidx307=((_phoneme_tab+$conv306*4)&4294967295);var $106=HEAP32[(($arrayidx307)>>2)];var $type=(($106+11)&4294967295);var $107=HEAPU8[($type)];var $conv308=((($107))&255);$next_phtype=$conv308;var $cmp309=((($conv308))|0)==1;if($cmp309){__label__=83;;}else{__label__=84;;}
if(__label__==83){var $arrayidx311=(($ph_digits+1)&4294967295);var $108=HEAP8[($arrayidx311)];var $conv312=(tempInt=(($108)),(tempInt>=128?tempInt-256:tempInt));var $arrayidx313=((_phoneme_tab+$conv312*4)&4294967295);var $109=HEAP32[(($arrayidx313)>>2)];var $type314=(($109+11)&4294967295);var $110=HEAPU8[($type314)];var $conv315=((($110))&255);$next_phtype=$conv315;;}
var $111=$ix;var $arrayidx317=(($ph_tens+$111)&4294967295);var $112=HEAP8[($arrayidx317)];var $conv318=(tempInt=(($112)),(tempInt>=128?tempInt-256:tempInt));var $arrayidx319=((_phoneme_tab+$conv318*4)&4294967295);var $113=HEAP32[(($arrayidx319)>>2)];var $type320=(($113+11)&4294967295);var $114=HEAPU8[($type320)];var $conv321=((($114))&255);var $cmp322=((($conv321))|0)==2;if(!($cmp322)){__label__=87;break $if_then296$$if_end329$110;}
var $115=$next_phtype;var $cmp324=((($115))|0)==2;if(!($cmp324)){__label__=87;break $if_then296$$if_end329$110;}
var $116=$ix;var $arrayidx326=(($ph_tens+$116)&4294967295);HEAP8[($arrayidx326)]=0;;}}while(0);var $117=$ph_out_addr;var $arraydecay330=(($ph_tens)&4294967295);var $arraydecay331=(($ph_digits)&4294967295);var $arraydecay332=(($ph_ordinal)&4294967295);var $call333=_sprintf($117,((__str6549)&4294967295),allocate([$arraydecay330,0,0,0,$arraydecay331,0,0,0,$arraydecay332,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}}while(0);var $118=$tr_addr;var $langopts336=(($118)&4294967295);var $numbers337=(($langopts336+184)&4294967295);var $119=HEAP32[(($numbers337)>>2)];var $and338=($119)&256;var $tobool339=((($and338))|0)!=0;if($tobool339){__label__=89;;}else{__label__=95;;}
$if_then340$$if_end354$121:do{if(__label__==89){$found=0;var $120=$ph_out_addr;var $call341=_strlen($120);var $sub342=((($call341)-1)&4294967295);$ix=$sub342;var $cmp3439=((($sub342))|0)>=0;if(!($cmp3439)){__label__=95;break $if_then340$$if_end354$121;}
while(1){var $121=$ix;var $122=$ph_out_addr;var $arrayidx344=(($122+$121)&4294967295);var $123=HEAP8[($arrayidx344)];var $conv345=(tempInt=(($123)),(tempInt>=128?tempInt-256:tempInt));var $cmp346=((($conv345))|0)==6;if($cmp346){__label__=91;;}else{__label__=94;;}
if(__label__==91){var $124=$found;var $tobool348=((($124))|0)!=0;if($tobool348){__label__=92;;}else{__label__=93;;}
if(__label__==92){var $125=$ix;var $126=$ph_out_addr;var $arrayidx350=(($126+$125)&4294967295);HEAP8[($arrayidx350)]=5;;}
else if(__label__==93){$found=1;;}}
var $127=$ix;var $dec=((($127)-1)&4294967295);$ix=$dec;var $cmp343=((($dec))|0)>=0;if($cmp343){__label__=90;continue;}else{__label__=95;break $if_then340$$if_end354$121;}}}}while(0);var $128=$used_and;STACKTOP=__stackBase__;return $128;return null;}
function __ZL9M_Varianti($value){;var __label__;var $retval;var $value_addr;$value_addr=$value;var $0=HEAP32[((_translator)>>2)];var $langopts=(($0)&4294967295);var $numbers2=(($langopts+188)&4294967295);var $1=HEAP32[(($numbers2)>>2)];var $and=($1)&256;var $tobool=((($and))|0)!=0;if($tobool){__label__=1;;}else{__label__=3;;}
$land_lhs_true$$if_else$2:do{if(__label__==1){var $2=$value_addr;var $cmp=((($2))|0)>=2;var $3=$value_addr;var $cmp2=((($3))|0)<=4;var $or_cond=($cmp)&($cmp2);if(!($or_cond)){__label__=3;break $land_lhs_true$$if_else$2;}
$retval=((__str54351)&4294967295);__label__=13;break $land_lhs_true$$if_else$2;}}while(0);$return$$if_else$5:do{if(__label__==3){var $4=$value_addr;var $rem=((($4))|0)%100;var $cmp3=((($rem))|0)<10;if($cmp3){__label__=5;;}else{__label__=4;;}
$if_then6$$lor_lhs_false$7:do{if(__label__==4){var $5=$value_addr;var $rem4=((($5))|0)%100;var $cmp5=((($rem4))|0)>20;if($cmp5){__label__=5;break $if_then6$$lor_lhs_false$7;}else{__label__=12;break $if_then6$$lor_lhs_false$7;}}}while(0);$if_then6$$if_end28$9:do{if(__label__==5){var $6=HEAP32[((_translator)>>2)];var $langopts7=(($6)&4294967295);var $numbers28=(($langopts7+188)&4294967295);var $7=HEAP32[(($numbers28)>>2)];var $and9=($7)&64;var $tobool10=((($and9))|0)!=0;if($tobool10){__label__=6;;}else{__label__=9;;}
$land_lhs_true11$$if_end$11:do{if(__label__==6){var $8=$value_addr;var $rem12=((($8))|0)%10;var $cmp13=((($rem12))|0)>=2;if(!($cmp13)){__label__=9;break $land_lhs_true11$$if_end$11;}
var $9=$value_addr;var $rem15=((($9))|0)%10;var $cmp16=((($rem15))|0)<=4;if(!($cmp16)){__label__=9;break $land_lhs_true11$$if_end$11;}
$retval=((__str54351)&4294967295);__label__=13;break $return$$if_else$5;}}while(0);var $10=HEAP32[((_translator)>>2)];var $langopts18=(($10)&4294967295);var $numbers219=(($langopts18+188)&4294967295);var $11=HEAP32[(($numbers219)>>2)];var $and20=($11)&128;var $tobool21=((($and20))|0)!=0;if(!($tobool21)){__label__=12;break $if_then6$$if_end28$9;}
var $12=$value_addr;var $rem23=((($12))|0)%10;var $cmp24=((($rem23))|0)==1;if(!($cmp24)){__label__=12;break $if_then6$$if_end28$9;}
$retval=((__str55352)&4294967295);__label__=13;break $return$$if_else$5;}}while(0);$retval=((__str56353)&4294967295);;}}while(0);var $13=$retval;;return $13;return null;}
function __Z15LoadMbrolaTablePKcS0_i($mbrola_voice,$phtrans,$srate){var __stackBase__=STACKTOP;STACKTOP+=168;_memset(__stackBase__,0,168);var __label__;var $retval;var $mbrola_voice_addr;var $phtrans_addr;var $srate_addr;var $size;var $ix;var $pw;var $f_in;var $path=__stackBase__;$mbrola_voice_addr=$mbrola_voice;$phtrans_addr=$phtrans;$srate_addr=$srate;HEAP8[(((_mbrola_name)&4294967295))]=0;HEAP32[((_mbrola_delay)>>2)]=0;HEAP32[((__ZL15mbr_name_prefix)>>2)]=0;var $0=$mbrola_voice_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=HEAP32[((_samplerate_native)>>2)];HEAP32[((_samplerate)>>2)]=$1;__Z12SetParameteriii(14,0,0);$retval=0;;}
else if(__label__==2){var $arraydecay=(($path)&4294967295);var $2=$mbrola_voice_addr;var $call=_sprintf($arraydecay,((__str382)&4294967295),allocate([((_path_home)&4294967295),0,0,0,$2,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay1=(($path)&4294967295);var $call2=__Z13GetFileLengthPKc($arraydecay1);var $cmp3=((($call2))|0)<=0;if($cmp3){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $arraydecay5=(($path)&4294967295);var $3=$mbrola_voice_addr;var $call6=_sprintf($arraydecay5,((__str1383)&4294967295),allocate([$3,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
var $arraydecay8=(($path)&4294967295);var $call9=__Z13GetFileLengthPKc($arraydecay8);var $cmp10=((($call9))|0)<=0;if($cmp10){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $arraydecay12=(($path)&4294967295);var $4=$mbrola_voice_addr;var $5=$mbrola_voice_addr;var $call13=_sprintf($arraydecay12,((__str2384)&4294967295),allocate([$4,0,0,0,$5,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
var $arraydecay15=(($path)&4294967295);var $call16=__Z13GetFileLengthPKc($arraydecay15);var $cmp17=((($call16))|0)<=0;if($cmp17){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $arraydecay19=(($path)&4294967295);var $6=$mbrola_voice_addr;var $call20=_sprintf($arraydecay19,((__str3385)&4294967295),allocate([$6,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
var $arraydecay22=(($path)&4294967295);var $call23=_init_MBR($arraydecay22);var $cmp24=((($call23))|0)!=0;if($cmp24){__label__=9;;}else{__label__=10;;}
if(__label__==9){$retval=2;;}
else if(__label__==10){_setNoError_MBR();var $arraydecay27=(($path)&4294967295);var $7=$phtrans_addr;var $call28=_sprintf($arraydecay27,((__str4386)&4294967295),allocate([((_path_home)&4294967295),0,0,0,$7,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay29=(($path)&4294967295);var $call30=__Z13GetFileLengthPKc($arraydecay29);$size=$call30;var $arraydecay31=(($path)&4294967295);var $call32=_fopen($arraydecay31,((__str18429)&4294967295));$f_in=$call32;var $cmp33=((($call32))|0)==0;if($cmp33){__label__=11;;}else{__label__=12;;}
if(__label__==11){_close_MBR();$retval=2;;}
else if(__label__==12){var $8=HEAP32[((__ZL10mbrola_tab)>>2)];var $9=$8;var $10=$size;var $call36=_realloc($9,$10);var $11=$call36;HEAP32[((__ZL10mbrola_tab)>>2)]=$11;var $cmp37=((($11))|0)==0;var $12=$f_in;if($cmp37){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $call39=_fclose($12);_close_MBR();$retval=-1;;}
else if(__label__==14){var $call41=__Z10Read4BytesP7__sFILE($12);HEAP32[((__ZL14mbrola_control)>>2)]=$call41;var $13=HEAP32[((__ZL10mbrola_tab)>>2)];var $14=$13;$pw=$14;$ix=4;var $15=$ix;var $16=$size;var $cmp421=((($15))|0)<((($16))|0);if($cmp421){__label__=15;;}else{__label__=16;;}
$for_body$$for_end$23:do{if(__label__==15){while(1){var $17=$f_in;var $call43=__Z10Read4BytesP7__sFILE($17);var $18=$pw;var $incdec_ptr=(($18+4)&4294967295);$pw=$incdec_ptr;HEAP32[(($18)>>2)]=$call43;var $19=$ix;var $add=((($19)+4)&4294967295);$ix=$add;var $20=$ix;var $21=$size;var $cmp42=((($20))|0)<((($21))|0);if($cmp42){__label__=15;continue;}else{__label__=16;break $for_body$$for_end$23;}}}}while(0);var $22=HEAP32[((__ZL10mbrola_tab)>>2)];var $23=$22;var $24=$size;var $25=$f_in;var $call44=_fread($23,1,$24,$25);$size=$call44;var $26=$f_in;var $call45=_fclose($26);var $27=HEAP32[((__ZL14mbrola_control)>>2)];var $and=($27)&255;var $conv=((($and))|0);var $div=($conv)/16;_setVolumeRatio_MBR($div);var $28=$srate_addr;HEAP32[((_samplerate)>>2)]=$28;var $cmp46=((($28))|0)==22050;if($cmp46){__label__=17;;}else{__label__=18;;}
if(__label__==17){__Z12SetParameteriii(14,0,0);;}
else if(__label__==18){__Z12SetParameteriii(14,1,0);;}
var $29=$mbrola_voice_addr;var $call49=_strcpy(((_mbrola_name)&4294967295),$29);HEAP32[((_mbrola_delay)>>2)]=1000;$retval=0;;}}}}
var $30=$retval;STACKTOP=__stackBase__;return $30;return null;}
function _setNoError_MBR(){;var __label__;;return;return;}
function __Z15MbrolaTranslateP12PHONEME_LISTiiP7__sFILE($plist,$n_phonemes,$resume,$f_mbrola){var __stackBase__=STACKTOP;STACKTOP+=332;_memset(__stackBase__,0,332);var __label__;var __lastLabel__=null;var $retval;var $plist_addr;var $n_phonemes_addr;var $resume_addr;var $f_mbrola_addr;var $name;var $len;var $len1;var $ph;var $ph_next;var $ph_prev;var $p;var $next;var $prev;var $phdata=__stackBase__;var $fmtp=__stackBase__+152;var $pause;var $released;var $name2=__stackBase__+200;var $control=__stackBase__+204;var $done;var $len_percent=__stackBase__+208;var $final_pitch;var $ptr;var $mbr_buf=__stackBase__+212;var $pitch;var $pitch101;var $res;$plist_addr=$plist;$n_phonemes_addr=$n_phonemes;$resume_addr=$resume;$f_mbrola_addr=$f_mbrola;$pause=0;var $0=$resume_addr;var $tobool=((($0))|0)!=0;if($tobool){__label__=2;;}else{__label__=1;;}
if(__label__==1){HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)]=1;HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE11embedded_ix)>>2)]=0;HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE10word_count)>>2)]=0;;}
var $arraydecay=(($mbr_buf)&4294967295);var $arraydecay233=(($mbr_buf)&4294967295);var $arraydecay234=(($mbr_buf)&4294967295);var $sub_ptr_rhs_cast=($arraydecay234);var $1=$fmtp;var $sound_addr=(($phdata+68)&4294967295);var $arrayidx176=(($sound_addr)&4294967295);var $fmt_addr=(($fmtp+8)&4294967295);;$while_cond$5:while(1){var $2=HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)];var $3=$n_phonemes_addr;var $cmp=((($2))|0)<((($3))|0);if(!($cmp)){__label__=64;break $while_cond$5;}
var $call=__Z9WcmdqFreev();var $cmp1=((($call))|0)<22;if($cmp1){__label__=5;break $while_cond$5;}
$ptr=$arraydecay;var $4=HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)];var $5=$plist_addr;var $arrayidx=(($5+24*$4)&4294967295);$p=$arrayidx;var $6=HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)];var $add=((($6)+1)&4294967295);var $7=$plist_addr;var $arrayidx4=(($7+24*$add)&4294967295);$next=$arrayidx4;var $8=HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)];var $sub=((($8)-1)&4294967295);var $9=$plist_addr;var $arrayidx5=(($9+24*$sub)&4294967295);$prev=$arrayidx5;var $10=$p;var $ph6=(($10+8)&4294967295);var $11=HEAP32[(($ph6)>>2)];$ph=$11;var $12=HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)];var $sub7=((($12)-1)&4294967295);var $13=$plist_addr;var $arrayidx8=(($13+24*$sub7)&4294967295);var $ph9=(($arrayidx8+8)&4294967295);var $14=HEAP32[(($ph9)>>2)];$ph_prev=$14;var $15=HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)];var $add10=((($15)+1)&4294967295);var $16=$plist_addr;var $arrayidx11=(($16+24*$add10)&4294967295);var $ph12=(($arrayidx11+8)&4294967295);var $17=HEAP32[(($ph12)>>2)];$ph_next=$17;var $18=$p;var $synthflags=(($18+4)&4294967295);var $19=HEAPU16[(($synthflags)>>1)];var $conv=((($19))&65535);var $and=($conv)&2;var $tobool13=((($and))|0)!=0;if($tobool13){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $20=$p;var $sourceix=(($20+6)&4294967295);var $21=HEAPU16[(($sourceix)>>1)];var $conv15=((($21))&65535);__Z10DoEmbeddedPii(__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE11embedded_ix,$conv15);;}
var $22=$p;var $newword=(($22+19)&4294967295);var $23=HEAPU8[($newword)];var $conv17=((($23))&255);var $and18=($conv17)&4;var $tobool19=((($and18))|0)!=0;if($tobool19){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $24=$p;var $sourceix21=(($24+6)&4294967295);var $25=HEAPU16[(($sourceix21)>>1)];var $conv22=((($25))&65535);var $and23=($conv22)&2047;var $26=HEAP32[((_clause_start_char)>>2)];var $add24=((($and23)+($26))&4294967295);var $27=HEAP32[((_count_sentences)>>2)];__Z8DoMarkeriiii(2,$add24,0,$27);;}
var $28=$p;var $newword26=(($28+19)&4294967295);var $29=HEAPU8[($newword26)];var $conv27=((($29))&255);var $and28=($conv27)&1;var $tobool29=((($and28))|0)!=0;if($tobool29){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $30=$p;var $sourceix31=(($30+6)&4294967295);var $31=HEAPU16[(($sourceix31)>>1)];var $conv32=((($31))&65535);var $and33=($conv32)&2047;var $32=HEAP32[((_clause_start_char)>>2)];var $add34=((($and33)+($32))&4294967295);var $33=$p;var $sourceix35=(($33+6)&4294967295);var $34=HEAPU16[(($sourceix35)>>1)];var $conv36=((($34))&65535);var $shr=($conv36)>>11;var $35=HEAP32[((_clause_start_word)>>2)];var $36=HEAPU32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE10word_count)>>2)];var $inc=((($36)+1)&4294967295);HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE10word_count)>>2)]=$inc;var $add37=((($36)+($35))&4294967295);__Z8DoMarkeriiii(1,$add34,$shr,$add37);;}
var $37=$p;var $38=$ph;var $39=$ph_prev;var $40=$ph_next;var $call39=__ZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_($37,$38,$39,$40,$name2,$len_percent,$control);$name=$call39;var $41=HEAP32[(($control)>>2)];var $and40=($41)&1;var $tobool41=((($and40))|0)!=0;if($tobool41){__lastLabel__=12;__label__=13;;}else{__lastLabel__=12;__label__=14;;}
if(__label__==13){var $42=HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)];var $inc43=((($42)+1)&4294967295);HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)]=$inc43;var $_pr=$name;__lastLabel__=13;;}
var $43=__lastLabel__==13?$_pr:($call39);var $cmp45=((($43))|0)==0;if($cmp45){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $44=HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)];var $inc47=((($44)+1)&4294967295);HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)]=$inc47;__label__=3;continue $while_cond$5;}
else if(__label__==16){var $45=$ph;var $type=(($45+11)&4294967295);var $46=HEAPU8[($type)];var $conv49=((($46))&255);var $cmp50=((($conv49))|0)==0;if($cmp50){__label__=17;;}else{__label__=20;;}
$land_lhs_true$$if_else$24:do{if(__label__==17){var $47=$name;var $48=$ph;var $mnemonic=(($48)&4294967295);var $49=HEAP32[(($mnemonic)>>2)];var $cmp51=((($47))|0)==((($49))|0);if(!($cmp51)){__label__=20;break $land_lhs_true$$if_else$24;}
$name=95;var $50=$p;var $length=(($50+12)&4294967295);var $51=HEAP16[(($length)>>1)];var $conv53=(tempInt=(($51)),(tempInt>=32768?tempInt-65536:tempInt));var $52=HEAP32[((((_speed)&4294967295))>>2)];var $mul=((($conv53)*($52))&4294967295);var $div=((((($mul))|0)/256)|0);$len=$div;var $53=$len;var $cmp54=((($53))|0)==0;if(!($cmp54)){__label__=21;break $land_lhs_true$$if_else$24;}
$len=1;__label__=21;break $land_lhs_true$$if_else$24;}}while(0);if(__label__==20){var $54=HEAP32[((((_speed+12)&4294967295))>>2)];var $mul57=((($54)*80)&4294967295);var $div58=((((($mul57))|0)/256)|0);$len=$div58;;}
var $55=$p;var $sourceix60=(($55+6)&4294967295);var $56=HEAPU16[(($sourceix60)>>1)];var $conv61=((($56))&65535);var $and62=($conv61)&2047;var $57=HEAP32[((_clause_start_char)>>2)];var $add63=((($and62)+($57))&4294967295);var $58=$ph;var $mnemonic64=(($58)&4294967295);var $59=HEAP32[(($mnemonic64)>>2)];__Z8DoMarkeriiii(7,$add63,0,$59);var $60=$ptr;var $61=$name;var $call65=__Z12WordToStringj($61);var $call66=_sprintf($60,((__str6388)&4294967295),allocate([((__ZZ12WordToStringjE3buf)&4294967295),0,0,0],["i8*",0,0,0],ALLOC_STACK));var $62=$ptr;var $add_ptr=(($62+$call66)&4294967295);$ptr=$add_ptr;var $63=HEAP32[(($name2)>>2)];var $cmp67=((($63))|0)==95;if($cmp67){__label__=22;;}else{__label__=23;;}
if(__label__==22){var $64=HEAP32[(($len_percent)>>2)];$pause=$64;HEAP32[(($name2)>>2)]=0;;}
$done=0;$final_pitch=((__str13643)&4294967295);var $65=$ph;var $type70=(($65+11)&4294967295);var $66=HEAPU8[($type70)];var $conv71=((($66))&255);if($conv71==2){__label__=24;;}
else if($conv71==4){__label__=32;;}
else if($conv71==5){__label__=40;;}
else if($conv71==6){__label__=41;;}
else if($conv71==8){__label__=44;;}
else if($conv71==3){__label__=48;;}
else{__label__=50;;}
$sw_epilog$$sw_bb$$sw_bb126$$sw_bb152$$sw_bb155$$sw_bb171$$sw_bb195$34:do{if(__label__==24){var $67=$ph;var $std_length=(($67+14)&4294967295);var $68=HEAPU8[($std_length)];var $conv72=((($68))&255);$len=$conv72;var $69=$p;var $synthflags73=(($69+4)&4294967295);var $70=HEAPU16[(($synthflags73)>>1)];var $conv74=((($70))&65535);var $and75=($conv74)&8;var $tobool76=((($and75))|0)!=0;if($tobool76){__label__=25;;}else{__label__=26;;}
if(__label__==25){var $71=HEAP32[((((_phoneme_tab+48)&4294967295))>>2)];var $std_length78=(($71+14)&4294967295);var $72=HEAPU8[($std_length78)];var $conv79=((($72))&255);var $73=$len;var $add80=((($73)+($conv79))&4294967295);$len=$add80;;}
var $74=$ph_next;var $type82=(($74+11)&4294967295);var $75=HEAPU8[($type82)];var $conv83=((($75))&255);var $cmp84=((($conv83))|0)==0;if($cmp84){__label__=27;;}else{__label__=28;;}
if(__label__==27){var $76=$len;var $add86=((($76)+50)&4294967295);$len=$add86;;}
var $77=$len;var $78=$p;var $length88=(($78+12)&4294967295);var $79=HEAP16[(($length88)>>1)];var $conv89=(tempInt=(($79)),(tempInt>=32768?tempInt-65536:tempInt));var $mul90=((($conv89)*($77))&4294967295);var $div91=((((($mul90))|0)/256)|0);$len=$div91;var $80=HEAP32[(($name2)>>2)];var $cmp92=((($80))|0)==0;var $81=$p;var $env=(($81+14)&4294967295);var $82=HEAPU8[($env)];var $conv94=((($82))&255);var $83=$p;var $pitch1=(($83+20)&4294967295);var $84=HEAPU8[($pitch1)];var $conv95=((($84))&255);var $85=$p;var $pitch2=(($85+21)&4294967295);var $86=HEAPU8[($pitch2)];var $conv96=((($86))&255);if($cmp92){__label__=29;;}else{__label__=30;;}
if(__label__==29){__ZL10WritePitchiiiii($conv94,$conv95,$conv96,0,0);$pitch=((__ZZL10WritePitchiiiiiE6output)&4294967295);var $87=$ptr;var $88=$len;var $89=$pitch;var $call98=_sprintf($87,((__str8390)&4294967295),allocate([$88,0,0,0,$89,0,0,0],["i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $90=$ptr;var $add_ptr99=(($90+$call98)&4294967295);$ptr=$add_ptr99;;}
else if(__label__==30){var $91=HEAP32[(($len_percent)>>2)];__ZL10WritePitchiiiii($conv94,$conv95,$conv96,$91,0);$pitch101=((__ZZL10WritePitchiiiiiE6output)&4294967295);var $92=$len;var $93=HEAP32[(($len_percent)>>2)];var $mul109=((($93)*($92))&4294967295);var $div110=((((($mul109))|0)/100)|0);$len1=$div110;var $94=$ptr;var $95=$len1;var $96=$pitch101;var $call111=_sprintf($94,((__str8390)&4294967295),allocate([$95,0,0,0,$96,0,0,0],["i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $97=$ptr;var $add_ptr112=(($97+$call111)&4294967295);$ptr=$add_ptr112;var $98=$p;var $env113=(($98+14)&4294967295);var $99=HEAPU8[($env113)];var $conv114=((($99))&255);var $100=$p;var $pitch1115=(($100+20)&4294967295);var $101=HEAPU8[($pitch1115)];var $conv116=((($101))&255);var $102=$p;var $pitch2117=(($102+21)&4294967295);var $103=HEAPU8[($pitch2117)];var $conv118=((($103))&255);var $104=HEAP32[(($len_percent)>>2)];var $sub119=(((-($104)))&4294967295);__ZL10WritePitchiiiii($conv114,$conv116,$conv118,$sub119,0);$pitch101=((__ZZL10WritePitchiiiiiE6output)&4294967295);var $105=$ptr;var $106=HEAP32[(($name2)>>2)];var $call121=__Z12WordToStringj($106);var $107=$len;var $108=$len1;var $sub122=((($107)-($108))&4294967295);var $109=$pitch101;var $call123=_sprintf($105,((__str9391)&4294967295),allocate([((__ZZ12WordToStringjE3buf)&4294967295),0,0,0,$sub122,0,0,0,$109,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $110=$ptr;var $add_ptr124=(($110+$call123)&4294967295);$ptr=$add_ptr124;;}
$done=1;__label__=54;break $sw_epilog$$sw_bb$$sw_bb126$$sw_bb152$$sw_bb155$$sw_bb171$$sw_bb195$34;}
else if(__label__==32){$released=0;var $111=$next;var $type127=(($111+15)&4294967295);var $112=HEAPU8[($type127)];var $conv128=((($112))&255);var $cmp129=((($conv128))|0)==2;if($cmp129){__label__=33;;}else{__label__=34;;}
if(__label__==33){$released=1;;}
var $113=$next;var $type132=(($113+15)&4294967295);var $114=HEAPU8[($type132)];var $conv133=((($114))&255);var $cmp134=((($conv133))|0)==3;if($cmp134){__label__=35;;}else{__label__=37;;}
$land_lhs_true135$$if_end139$50:do{if(__label__==35){var $115=$next;var $newword136=(($115+19)&4294967295);var $116=HEAP8[($newword136)];var $tobool137=(tempInt=(($116)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool137){__label__=37;break $land_lhs_true135$$if_end139$50;}
$released=1;__label__=39;break $land_lhs_true135$$if_end139$50;}}while(0);$if_end139$$if_end145$53:do{if(__label__==37){var $_pr1=$released;var $cmp140=((($_pr1))|0)==0;if(!($cmp140)){__label__=39;break $if_end139$$if_end145$53;}
var $117=$p;var $synthflags142=(($117+4)&4294967295);var $118=HEAPU16[(($synthflags142)>>1)];var $conv143=((($118))&65535);var $or=($conv143)|8192;var $conv144=((($or))&65535);HEAP16[(($synthflags142)>>1)]=$conv144;;}}while(0);var $119=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$119,$phdata);var $call146=__Z9DoSample3P12PHONEME_DATAii($phdata,0,-1);$len=$call146;var $120=$len;var $mul147=((($120)*1000)&4294967295);var $121=HEAP32[((_samplerate)>>2)];var $div148=((((($mul147))|0)/((($121))|0))|0);$len=$div148;var $122=$p;var $prepause=(($122+16)&4294967295);var $123=HEAPU8[($prepause)];var $conv149=((($123))&255);var $call150=__Z11PauseLengthii($conv149,1);var $124=$len;var $add151=((($124)+($call150))&4294967295);$len=$add151;__label__=50;break $sw_epilog$$sw_bb$$sw_bb126$$sw_bb152$$sw_bb155$$sw_bb171$$sw_bb195$34;}
else if(__label__==40){var $125=HEAP32[((((_speed+12)&4294967295))>>2)];var $mul153=((($125)*80)&4294967295);var $div154=((((($mul153))|0)/256)|0);$len=$div154;__label__=50;break $sw_epilog$$sw_bb$$sw_bb126$$sw_bb152$$sw_bb155$$sw_bb171$$sw_bb195$34;}
else if(__label__==41){$len=0;var $126=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$126,$phdata);var $127=$p;var $synthflags156=(($127+4)&4294967295);var $128=HEAPU16[(($synthflags156)>>1)];var $conv157=((($128))&65535);var $and158=($conv157)&8;var $tobool159=((($and158))|0)!=0;if($tobool159){__label__=42;;}else{__label__=43;;}
if(__label__==42){var $129=$p;var $length161=(($129+12)&4294967295);var $130=HEAP16[(($length161)>>1)];var $conv162=(tempInt=(($130)),(tempInt>=32768?tempInt-65536:tempInt));var $call163=__Z9DoSample3P12PHONEME_DATAii($phdata,$conv162,-1);$len=$call163;;}
var $131=$p;var $length165=(($131+12)&4294967295);var $132=HEAP16[(($length165)>>1)];var $conv166=(tempInt=(($132)),(tempInt>=32768?tempInt-65536:tempInt));var $call167=__Z9DoSample3P12PHONEME_DATAii($phdata,$conv166,-1);var $133=$len;var $add168=((($133)+($call167))&4294967295);$len=$add168;var $134=$len;var $mul169=((($134)*1000)&4294967295);var $135=HEAP32[((_samplerate)>>2)];var $div170=((((($mul169))|0)/((($135))|0))|0);$len=$div170;__label__=50;break $sw_epilog$$sw_bb$$sw_bb126$$sw_bb152$$sw_bb155$$sw_bb171$$sw_bb195$34;}
else if(__label__==44){var $136=$next;var $type172=(($136+15)&4294967295);var $137=HEAPU8[($type172)];var $conv173=((($137))&255);var $cmp174=((($conv173))|0)!=2;if(!($cmp174)){__label__=50;break $sw_epilog$$sw_bb$$sw_bb126$$sw_bb152$$sw_bb155$$sw_bb171$$sw_bb195$34;}
var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$1;$stop$=$dest$+48;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $138=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$138,$phdata);var $139=HEAP32[(($arrayidx176)>>2)];HEAP32[(($fmt_addr)>>2)]=$139;var $140=$p;var $ph177=(($140+8)&4294967295);var $141=HEAP32[(($ph177)>>2)];var $142=$p;var $call178=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($141,0,$fmtp,$142,-1);$len=$call178;var $143=$len;var $mul179=((($143)*1000)&4294967295);var $144=HEAP32[((_samplerate)>>2)];var $div180=((((($mul179))|0)/((($144))|0))|0);$len=$div180;var $145=$next;var $type181=(($145+15)&4294967295);var $146=HEAPU8[($type181)];var $conv182=((($146))&255);var $cmp183=((($conv182))|0)==0;if($cmp183){__label__=46;;}else{__label__=47;;}
if(__label__==46){var $147=$len;var $add185=((($147)+50)&4294967295);$len=$add185;;}
var $148=$p;var $env187=(($148+14)&4294967295);var $149=HEAPU8[($env187)];var $conv188=((($149))&255);var $150=$p;var $pitch1189=(($150+20)&4294967295);var $151=HEAPU8[($pitch1189)];var $conv190=((($151))&255);var $152=$p;var $pitch2191=(($152+21)&4294967295);var $153=HEAPU8[($pitch2191)];var $conv192=((($153))&255);__ZL10WritePitchiiiii($conv188,$conv190,$conv192,0,1);$final_pitch=((__ZZL10WritePitchiiiiiE6output)&4294967295);__label__=50;break $sw_epilog$$sw_bb$$sw_bb126$$sw_bb152$$sw_bb155$$sw_bb171$$sw_bb195$34;}
else if(__label__==48){var $154=$next;var $type196=(($154+15)&4294967295);var $155=HEAPU8[($type196)];var $conv197=((($155))&255);var $cmp198=((($conv197))|0)==0;if(!($cmp198)){__label__=50;break $sw_epilog$$sw_bb$$sw_bb126$$sw_bb152$$sw_bb155$$sw_bb171$$sw_bb195$34;}
var $156=$len;var $add200=((($156)+50)&4294967295);$len=$add200;var $157=$p;var $env201=(($157+14)&4294967295);var $158=HEAPU8[($env201)];var $conv202=((($158))&255);var $159=$p;var $pitch1203=(($159+20)&4294967295);var $160=HEAPU8[($pitch1203)];var $conv204=((($160))&255);var $161=$p;var $pitch2205=(($161+21)&4294967295);var $162=HEAPU8[($pitch2205)];var $conv206=((($162))&255);__ZL10WritePitchiiiii($conv202,$conv204,$conv206,0,1);$final_pitch=((__ZZL10WritePitchiiiiiE6output)&4294967295);__label__=50;break $sw_epilog$$sw_bb$$sw_bb126$$sw_bb152$$sw_bb155$$sw_bb171$$sw_bb195$34;}}while(0);$sw_epilog$$if_end222$69:do{if(__label__==50){var $_pr3=$done;var $tobool209=((($_pr3))|0)!=0;if($tobool209){__label__=54;break $sw_epilog$$if_end222$69;}
var $163=HEAP32[(($name2)>>2)];var $cmp211=((($163))|0)!=0;if($cmp211){__label__=52;;}else{__label__=53;;}
if(__label__==52){var $164=$len;var $165=HEAP32[(($len_percent)>>2)];var $mul213=((($165)*($164))&4294967295);var $div214=((((($mul213))|0)/100)|0);$len1=$div214;var $166=$ptr;var $167=$len1;var $168=HEAP32[(($name2)>>2)];var $call215=__Z12WordToStringj($168);var $call216=_sprintf($166,((__str10392)&4294967295),allocate([$167,0,0,0,((__ZZ12WordToStringjE3buf)&4294967295),0,0,0],["i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $169=$ptr;var $add_ptr217=(($169+$call216)&4294967295);$ptr=$add_ptr217;var $170=$len1;var $171=$len;var $sub218=((($171)-($170))&4294967295);$len=$sub218;;}
var $172=$ptr;var $173=$len;var $174=$final_pitch;var $call220=_sprintf($172,((__str11393)&4294967295),allocate([$173,0,0,0,$174,0,0,0],["i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $175=$ptr;var $add_ptr221=(($175+$call220)&4294967295);$ptr=$add_ptr221;;}}while(0);var $176=$pause;var $tobool223=((($176))|0)!=0;if($tobool223){__label__=55;;}else{__label__=56;;}
if(__label__==55){var $177=$pause;var $call225=__Z11PauseLengthii($177,0);var $178=$len;var $add226=((($178)+($call225))&4294967295);$len=$add226;var $179=$ptr;var $180=$pause;var $call227=__Z11PauseLengthii($180,0);var $call228=_sprintf($179,((__str12394)&4294967295),allocate([$call227,0,0,0],["i32",0,0,0],ALLOC_STACK));var $181=$ptr;var $add_ptr229=(($181+$call228)&4294967295);$ptr=$add_ptr229;$pause=0;;}
var $182=$f_mbrola_addr;var $tobool231=((($182))|0)!=0;if($tobool231){__label__=57;;}else{__label__=58;;}
if(__label__==57){var $183=$ptr;var $sub_ptr_lhs_cast=($183);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);var $184=$f_mbrola_addr;var $call235=_fwrite($arraydecay233,1,$sub_ptr_sub,$184);;}
else if(__label__==58){var $call238=_write_MBR($arraydecay233);$res=$call238;var $185=$res;var $cmp239=((($185))|0)<0;if($cmp239){__label__=59;break $while_cond$5;}
var $186=$res;var $cmp242=((($186))|0)==0;if($cmp242){__label__=61;break $while_cond$5;}
var $187=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx245=((_wcmdq+$187*16)&4294967295);var $arrayidx246=(($arrayidx245)&4294967295);HEAP32[(($arrayidx246)>>2)]=13;var $188=$len;var $189=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx247=((_wcmdq+$189*16)&4294967295);var $arrayidx248=(($arrayidx247+4)&4294967295);HEAP32[(($arrayidx248)>>2)]=$188;__Z8WcmdqIncv();;}
var $190=HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)];var $inc250=((($190)+1)&4294967295);HEAP32[((__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix)>>2)]=$inc250;__label__=3;continue $while_cond$5;}}
if(__label__==64){var $191=$f_mbrola_addr;var $tobool251=((($191))|0)!=0;if($tobool251){__label__=66;;}else{__label__=65;;}
if(__label__==65){var $call253=_flush_MBR();var $192=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx254=((_wcmdq+$192*16)&4294967295);var $arrayidx255=(($arrayidx254)&4294967295);HEAP32[(($arrayidx255)>>2)]=13;var $193=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx256=((_wcmdq+$193*16)&4294967295);var $arrayidx257=(($arrayidx256+4)&4294967295);HEAP32[(($arrayidx257)>>2)]=500;__Z8WcmdqIncv();;}
$retval=0;;}
else if(__label__==5){$retval=1;;}
else if(__label__==59){$retval=0;;}
else if(__label__==61){$retval=1;;}
var $194=$retval;STACKTOP=__stackBase__;return $194;return null;}
function __ZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_($plist,$ph,$ph_prev,$ph_next,$name2,$split,$control){;var __label__;var $retval;var $plist_addr;var $ph_addr;var $ph_prev_addr;var $ph_next_addr;var $name2_addr;var $split_addr;var $control_addr;var $pr;var $other_ph;var $found;$plist_addr=$plist;$ph_addr=$ph;$ph_prev_addr=$ph_prev;$ph_next_addr=$ph_next;$name2_addr=$name2;$split_addr=$split;$control_addr=$control;$found=0;var $0=$name2_addr;HEAP32[(($0)>>2)]=0;var $1=$split_addr;HEAP32[(($1)>>2)]=0;var $2=$control_addr;HEAP32[(($2)>>2)]=0;var $3=$ph_addr;var $mnemonic=(($3)&4294967295);var $4=HEAP32[(($mnemonic)>>2)];HEAP32[((__ZZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_E4mnem)>>2)]=$4;var $5=HEAP32[((__ZL10mbrola_tab)>>2)];$pr=$5;;$while_cond$2:while(1){var $6=$pr;var $name=(($6)&4294967295);var $7=HEAP32[(($name)>>2)];var $cmp=((($7))|0)!=0;if(!($cmp)){__label__=28;break $while_cond$2;}
var $8=HEAP32[((__ZZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_E4mnem)>>2)];var $9=$pr;var $name1=(($9)&4294967295);var $10=HEAP32[(($name1)>>2)];var $cmp2=((($8))|0)==((($10))|0);if($cmp2){__label__=3;;}else{__label__=27;;}
$if_then$$if_end60$5:do{if(__label__==3){var $11=$pr;var $next_phoneme=(($11+4)&4294967295);var $12=HEAP32[(($next_phoneme)>>2)];var $cmp3=((($12))|0)==0;if($cmp3){__label__=4;;}else{__label__=5;;}
$if_then4$$if_else$7:do{if(__label__==4){$found=1;;}
else if(__label__==5){var $13=$pr;var $next_phoneme5=(($13+4)&4294967295);var $14=HEAP32[(($next_phoneme5)>>2)];var $cmp6=((($14))|0)==58;if($cmp6){__label__=6;;}else{__label__=8;;}
$land_lhs_true$$if_else8$10:do{if(__label__==6){var $15=$plist_addr;var $synthflags=(($15+4)&4294967295);var $16=HEAPU16[(($synthflags)>>1)];var $conv=((($16))&65535);var $and=($conv)&8;var $tobool=((($and))|0)!=0;if(!($tobool)){__label__=8;break $land_lhs_true$$if_else8$10;}
$found=1;__label__=20;break $if_then4$$if_else$7;}}while(0);var $17=$pr;var $control9=(($17+20)&4294967295);var $18=HEAP32[(($control9)>>2)];var $and10=($18)&2;var $tobool11=((($and10))|0)!=0;if($tobool11){__label__=9;;}else{__label__=10;;}
$if_then12$$if_else13$14:do{if(__label__==9){var $19=$ph_prev_addr;$other_ph=$19;;}
else if(__label__==10){var $20=$pr;var $control14=(($20+20)&4294967295);var $21=HEAP32[(($control14)>>2)];var $and15=($21)&8;var $tobool16=((($and15))|0)!=0;if($tobool16){__label__=11;;}else{__label__=13;;}
$land_lhs_true17$$if_else20$17:do{if(__label__==11){var $22=$plist_addr;var $add_ptr=(($22+24)&4294967295);var $newword=(($add_ptr+19)&4294967295);var $23=HEAP8[($newword)];var $tobool18=(tempInt=(($23)),(tempInt>=128?tempInt-256:tempInt))!=0;if(!($tobool18)){__label__=13;break $land_lhs_true17$$if_else20$17;}
var $24=HEAP32[((((_phoneme_tab)&4294967295))>>2)];$other_ph=$24;__label__=14;break $if_then12$$if_else13$14;}}while(0);var $25=$ph_next_addr;$other_ph=$25;;}}while(0);var $26=$pr;var $next_phoneme22=(($26+4)&4294967295);var $27=HEAP32[(($next_phoneme22)>>2)];var $28=$other_ph;var $mnemonic23=(($28)&4294967295);var $29=HEAP32[(($mnemonic23)>>2)];var $cmp24=((($27))|0)==((($29))|0);if($cmp24){__label__=19;;}else{__label__=15;;}
$if_then37$$lor_lhs_false$22:do{if(__label__==15){var $30=$pr;var $next_phoneme25=(($30+4)&4294967295);var $31=HEAP32[(($next_phoneme25)>>2)];var $cmp26=((($31))|0)==2;if($cmp26){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $32=$other_ph;var $type=(($32+11)&4294967295);var $33=HEAPU8[($type)];var $conv28=((($33))&255);var $cmp29=((($conv28))|0)==2;if($cmp29){__label__=19;break $if_then37$$lor_lhs_false$22;}}
var $34=$pr;var $next_phoneme31=(($34+4)&4294967295);var $35=HEAP32[(($next_phoneme31)>>2)];var $cmp32=((($35))|0)==95;if(!($cmp32)){__label__=20;break $if_then4$$if_else$7;}
var $36=$other_ph;var $type34=(($36+11)&4294967295);var $37=HEAPU8[($type34)];var $conv35=((($37))&255);var $cmp36=((($conv35))|0)==0;if(!($cmp36)){__label__=20;break $if_then4$$if_else$7;}}}while(0);$found=1;;}}while(0);var $38=$pr;var $control41=(($38+20)&4294967295);var $39=HEAP32[(($control41)>>2)];var $and42=($39)&4;var $tobool43=((($and42))|0)!=0;if($tobool43){__label__=21;;}else{__label__=23;;}
$land_lhs_true44$$if_end49$30:do{if(__label__==21){var $40=$plist_addr;var $newword45=(($40+19)&4294967295);var $41=HEAPU8[($newword45)];var $conv46=((($41))&255);var $cmp47=((($conv46))|0)==0;if(!($cmp47)){__label__=23;break $land_lhs_true44$$if_end49$30;}
$found=0;__label__=27;break $if_then$$if_end60$5;}}while(0);var $_pr=$found;var $tobool50=((($_pr))|0)!=0;if($tobool50){__label__=24;break $while_cond$2;}}}while(0);var $55=$pr;var $incdec_ptr=(($55+24)&4294967295);$pr=$incdec_ptr;__label__=1;continue $while_cond$2;}
$while_end$$if_then51$35:do{if(__label__==24){var $42=$pr;var $mbr_name2=(($42+12)&4294967295);var $43=HEAP32[(($mbr_name2)>>2)];var $44=$name2_addr;HEAP32[(($44)>>2)]=$43;var $45=$pr;var $percent=(($45+16)&4294967295);var $46=HEAP32[(($percent)>>2)];var $47=$split_addr;HEAP32[(($47)>>2)]=$46;var $48=$pr;var $control52=(($48+20)&4294967295);var $49=HEAP32[(($control52)>>2)];var $50=$control_addr;HEAP32[(($50)>>2)]=$49;var $51=$pr;var $control53=(($51+20)&4294967295);var $52=HEAP32[(($control53)>>2)];var $and54=($52)&16;var $tobool55=((($and54))|0)!=0;var $53=$pr;var $mbr_name=(($53+8)&4294967295);var $54=HEAP32[(($mbr_name)>>2)];if($tobool55){__label__=25;;}else{__label__=26;;}
if(__label__==25){HEAP32[((__ZL15mbr_name_prefix)>>2)]=$54;$retval=0;__label__=31;break $while_end$$if_then51$35;}
else if(__label__==26){HEAP32[((__ZZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_E4mnem)>>2)]=$54;__label__=28;break $while_end$$if_then51$35;}}}while(0);if(__label__==28){var $56=HEAP32[((__ZL15mbr_name_prefix)>>2)];var $cmp61=((($56))|0)!=0;if($cmp61){__label__=29;;}else{__label__=30;;}
if(__label__==29){var $57=HEAP32[((__ZZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_E4mnem)>>2)];var $shl=($57)<<8;var $58=HEAP32[((__ZL15mbr_name_prefix)>>2)];var $and63=($58)&255;var $or=($and63)|($shl);HEAP32[((__ZZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_E4mnem)>>2)]=$or;;}
HEAP32[((__ZL15mbr_name_prefix)>>2)]=0;var $59=HEAP32[((__ZZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_E4mnem)>>2)];$retval=$59;;}
var $60=$retval;;return $60;return null;}
function __ZL10WritePitchiiiii($env,$pitch1,$pitch2,$split,$final){var __stackBase__=STACKTOP;STACKTOP+=76;_memset(__stackBase__,0,76);var __label__;var __lastLabel__=null;var $env_addr;var $pitch1_addr;var $pitch2_addr;var $split_addr;var $final_addr;var $x;var $ix;var $pitch_base=__stackBase__;var $pitch_range=__stackBase__+4;var $p1;var $p2;var $p_end;var $pitch_env;var $max;var $min;var $y_max;var $y_min;var $env100;var $y2;var $y=__stackBase__+8;var $env_split;var $buf=__stackBase__+24;$env_addr=$env;$pitch1_addr=$pitch1;$pitch2_addr=$pitch2;$split_addr=$split;$final_addr=$final;$max=-1;$min=999;$y_max=0;$y_min=0;$env100=80;HEAP8[(((__ZZL10WritePitchiiiiiE6output)&4294967295))]=0;var $0=$env_addr;var $arrayidx=((_envelope_data+$0*4)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];$pitch_env=$1;var $2=HEAP32[((_voice)>>2)];var $3=$pitch1_addr;var $4=$pitch2_addr;__Z9SetPitch2P7voice_tiiPiS1_($2,$3,$4,$pitch_base,$pitch_range);var $5=$split_addr;var $mul=((($5)*128)&4294967295);var $div=((((($mul))|0)/100)|0);$env_split=$div;var $6=$env_split;var $cmp=((($6))|0)<0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $7=$env_split;var $sub=(((-($7)))&4294967295);$env_split=$sub;;}
$x=0;;$for_body$5:while(1){var $8=$x;var $9=$pitch_env;var $arrayidx2=(($9+$8)&4294967295);var $10=HEAPU8[($arrayidx2)];var $conv=((($10))&255);var $11=$max;var $cmp3=((($conv))|0)>((($11))|0);if($cmp3){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $12=$x;var $13=$pitch_env;var $arrayidx5=(($13+$12)&4294967295);var $14=HEAPU8[($arrayidx5)];var $conv6=((($14))&255);$max=$conv6;var $15=$x;$y_max=$15;;}
var $16=$x;var $17=$pitch_env;var $arrayidx8=(($17+$16)&4294967295);var $18=HEAPU8[($arrayidx8)];var $conv9=((($18))&255);var $19=$min;var $cmp10=((($conv9))|0)<((($19))|0);if($cmp10){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $20=$x;var $21=$pitch_env;var $arrayidx12=(($21+$20)&4294967295);var $22=HEAPU8[($arrayidx12)];var $conv13=((($22))&255);$min=$conv13;var $23=$x;$y_min=$23;;}
var $24=$x;var $inc=((($24)+1)&4294967295);$x=$inc;var $cmp1=((($inc))|0)<128;if($cmp1){__label__=3;continue $for_body$5;}else{__label__=8;break $for_body$5;}}
var $arrayidx15=(($y+8)&4294967295);HEAP32[(($arrayidx15)>>2)]=64;var $25=$y_max;var $cmp16=((($25))|0)>0;var $26=$y_max;var $cmp17=((($26))|0)<127;var $or_cond=($cmp16)&($cmp17);if($or_cond){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $27=$y_max;var $arrayidx19=(($y+8)&4294967295);HEAP32[(($arrayidx19)>>2)]=$27;;}
var $28=$y_min;var $cmp21=((($28))|0)>0;var $29=$y_min;var $cmp23=((($29))|0)<127;var $or_cond1=($cmp21)&($cmp23);if($or_cond1){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $30=$y_min;var $arrayidx25=(($y+8)&4294967295);HEAP32[(($arrayidx25)>>2)]=$30;;}
var $arrayidx27=(($y+8)&4294967295);var $31=HEAP32[(($arrayidx27)>>2)];var $div28=((((($31))|0)/2)|0);var $arrayidx29=(($y+4)&4294967295);HEAP32[(($arrayidx29)>>2)]=$div28;var $arrayidx30=(($y+8)&4294967295);var $32=HEAP32[(($arrayidx30)>>2)];var $arrayidx31=(($y+8)&4294967295);var $33=HEAP32[(($arrayidx31)>>2)];var $sub32=((127-($33))&4294967295);var $div33=((((($sub32))|0)/2)|0);var $add=((($div33)+($32))&4294967295);var $arrayidx34=(($y+12)&4294967295);HEAP32[(($arrayidx34)>>2)]=$add;var $34=$pitch_env;var $arrayidx35=(($34)&4294967295);var $35=HEAPU8[($arrayidx35)];var $conv36=((($35))&255);var $36=HEAP32[(($pitch_range)>>2)];var $mul37=((($conv36)*($36))&4294967295);var $shr=($mul37)>>8;var $37=HEAP32[(($pitch_base)>>2)];var $add38=((($shr)+($37))&4294967295);$p1=$add38;var $38=$pitch_env;var $arrayidx39=(($38+127)&4294967295);var $39=HEAPU8[($arrayidx39)];var $conv40=((($39))&255);var $40=HEAP32[(($pitch_range)>>2)];var $mul41=((($conv40)*($40))&4294967295);var $shr42=($mul41)>>8;var $41=HEAP32[(($pitch_base)>>2)];var $add43=((($shr42)+($41))&4294967295);$p_end=$add43;var $42=$split_addr;var $cmp44=((($42))|0)>=0;if($cmp44){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $arraydecay=(($buf)&4294967295);var $43=$p1;var $div46=((((($43))|0)/4096)|0);var $call=_sprintf($arraydecay,((__str13395)&4294967295),allocate([$div46,0,0,0],["i32",0,0,0],ALLOC_STACK));var $arraydecay47=(($buf)&4294967295);var $call48=_strcat(((__ZZL10WritePitchiiiiiE6output)&4294967295),$arraydecay47);;}
var $44=$env_addr;var $cmp50=((($44))|0)>1;if($cmp50){__label__=15;;}else{__label__=25;;}
$if_then51$$if_end91$23:do{if(__label__==15){$ix=1;var $arraydecay82=(($buf)&4294967295);var $arraydecay85=(($buf)&4294967295);;$for_body54$25:while(1){var $45=$ix;var $arrayidx55=(($y+$45*4)&4294967295);var $46=HEAP32[(($arrayidx55)>>2)];var $47=$pitch_env;var $arrayidx56=(($47+$46)&4294967295);var $48=HEAPU8[($arrayidx56)];var $conv57=((($48))&255);var $49=HEAP32[(($pitch_range)>>2)];var $mul58=((($conv57)*($49))&4294967295);var $shr59=($mul58)>>8;var $50=HEAP32[(($pitch_base)>>2)];var $add60=((($shr59)+($50))&4294967295);$p2=$add60;var $51=$split_addr;var $cmp61=((($51))|0)>0;if($cmp61){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $52=$ix;var $arrayidx63=(($y+$52*4)&4294967295);var $53=HEAP32[(($arrayidx63)>>2)];var $54=$env100;var $mul64=((($54)*($53))&4294967295);var $55=$env_split;var $div65=((((($mul64))|0)/((($55))|0))|0);$y2=$div65;__lastLabel__=17;;}
else if(__label__==18){var $56=$split_addr;var $cmp66=((($56))|0)<0;var $57=$ix;var $arrayidx68=(($y+$57*4)&4294967295);var $58=HEAP32[(($arrayidx68)>>2)];if($cmp66){__label__=19;;}else{__label__=20;;}
if(__label__==19){var $59=$env_split;var $sub69=((($58)-($59))&4294967295);var $60=$env100;var $mul70=((($sub69)*($60))&4294967295);var $61=$env_split;var $div71=((((($mul70))|0)/((($61))|0))|0);$y2=$div71;__lastLabel__=19;;}
else if(__label__==20){var $62=$env100;var $mul74=((($62)*($58))&4294967295);var $div75=((((($mul74))|0)/128)|0);$y2=$div75;__lastLabel__=20;;}}
var $63=__lastLabel__==19?$div71:(__lastLabel__==20?$div75:($div65));var $cmp78=((($63))|0)>0;if($cmp78){__label__=22;;}else{__label__=24;;}
$land_lhs_true79$$for_inc88$34:do{if(__label__==22){var $64=$y2;var $65=$env100;var $cmp80=((($64))|0)<=((($65))|0);if(!($cmp80)){__label__=24;break $land_lhs_true79$$for_inc88$34;}
var $66=$y2;var $67=$p2;var $div83=((((($67))|0)/4096)|0);var $call84=_sprintf($arraydecay82,((__str14396)&4294967295),allocate([$66,0,0,0,$div83,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $call86=_strcat(((__ZZL10WritePitchiiiiiE6output)&4294967295),$arraydecay85);;}}while(0);var $68=$ix;var $inc89=((($68)+1)&4294967295);$ix=$inc89;var $cmp53=((($inc89))|0)<4;if($cmp53){__label__=16;continue $for_body54$25;}else{__label__=25;break $if_then51$$if_end91$23;}}}}while(0);var $69=$p_end;var $div92=((((($69))|0)/4096)|0);$p_end=$div92;var $70=$split_addr;var $cmp93=((($70))|0)<=0;if($cmp93){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $arraydecay95=(($buf)&4294967295);var $71=$env100;var $72=$p_end;var $call96=_sprintf($arraydecay95,((__str14396)&4294967295),allocate([$71,0,0,0,$72,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $arraydecay97=(($buf)&4294967295);var $call98=_strcat(((__ZZL10WritePitchiiiiiE6output)&4294967295),$arraydecay97);;}
var $73=$env100;var $cmp100=((($73))|0)<100;if($cmp100){__label__=28;;}else{__label__=29;;}
if(__label__==28){var $arraydecay102=(($buf)&4294967295);var $74=$p_end;var $call103=_sprintf($arraydecay102,((__str14396)&4294967295),allocate([100,0,0,0,$74,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $arraydecay104=(($buf)&4294967295);var $call105=_strcat(((__ZZL10WritePitchiiiiiE6output)&4294967295),$arraydecay104);;}
var $strlen=_strlen(((__ZZL10WritePitchiiiiiE6output)&4294967295));var $endptr=((((__ZZL10WritePitchiiiiiE6output)&4294967295)+$strlen)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str15397)&4294967295);$dest$=$endptr;$stop$=$src$+2;if(($dest$%4)==($src$%4)&&2>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $75=$final_addr;var $tobool=((($75))|0)!=0;if($tobool){__label__=30;;}else{__label__=31;;}
if(__label__==30){var $76=$p_end;var $call109=_sprintf(((__ZZL10WritePitchiiiiiE6output)&4294967295),((__str16398)&4294967295),allocate([$76,0,0,0],["i32",0,0,0],ALLOC_STACK));;}
STACKTOP=__stackBase__;return;return;}
function __Z14MbrolaGenerateP12PHONEME_LISTPii($phoneme_list,$n_ph,$resume){;var __label__;var $retval;var $phoneme_list_addr;var $n_ph_addr;var $resume_addr;var $f_mbrola;var $again;$phoneme_list_addr=$phoneme_list;$n_ph_addr=$n_ph;$resume_addr=$resume;$f_mbrola=0;var $0=$n_ph_addr;var $1=HEAP32[(($0)>>2)];var $cmp=((($1))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $2=HEAP32[((_option_mbrola_phonemes)>>2)];var $tobool=((($2))|0)!=0;if($tobool){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $3=HEAP32[((_f_trans)>>2)];$f_mbrola=$3;;}
var $4=$phoneme_list_addr;var $5=$n_ph_addr;var $6=HEAP32[(($5)>>2)];var $7=$resume_addr;var $8=$f_mbrola;var $call=__Z15MbrolaTranslateP12PHONEME_LISTiiP7__sFILE($4,$6,$7,$8);$again=$call;var $tobool3=((($call))|0)!=0;if($tobool3){__label__=6;;}else{__label__=5;;}
if(__label__==5){var $9=$n_ph_addr;HEAP32[(($9)>>2)]=0;;}
var $10=$again;$retval=$10;;}
var $11=$retval;;return $11;return null;}
function __Z10MbrolaFillii($length,$resume){;var __label__;var $retval;var $length_addr;var $resume_addr;var $req_samples;var $result;$length_addr=$length;$resume_addr=$resume;var $0=$resume_addr;var $tobool=((($0))|0)!=0;if($tobool){__label__=2;;}else{__label__=1;;}
if(__label__==1){var $1=HEAP32[((_samplerate)>>2)];var $2=$length_addr;var $mul=((($2)*($1))&4294967295);var $div=((((($mul))|0)/1000)|0);HEAP32[((__ZZ10MbrolaFilliiE9n_samples)>>2)]=$div;;}
var $3=HEAP32[((_out_end)>>2)];var $4=HEAP32[((_out_ptr)>>2)];var $sub_ptr_lhs_cast=($3);var $sub_ptr_rhs_cast=($4);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);var $div1=((((($sub_ptr_sub))|0)/2)|0);$req_samples=$div1;var $5=$req_samples;var $6=HEAP32[((__ZZ10MbrolaFilliiE9n_samples)>>2)];var $cmp=((($5))|0)>((($6))|0);if($cmp){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $7=HEAP32[((__ZZ10MbrolaFilliiE9n_samples)>>2)];$req_samples=$7;;}
var $8=HEAP32[((_out_ptr)>>2)];var $9=$8;var $10=$9;var $11=$req_samples;var $call=_read_MBR($10,$11);$result=$call;var $cmp4=((($call))|0)<=0;if($cmp4){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=0;;}
else if(__label__==6){var $12=$result;var $mul7=((($12)*2)&4294967295);var $13=HEAP32[((_out_ptr)>>2)];var $add_ptr=(($13+$mul7)&4294967295);HEAP32[((_out_ptr)>>2)]=$add_ptr;var $14=$result;var $15=HEAP32[((__ZZ10MbrolaFilliiE9n_samples)>>2)];var $sub=((($15)-($14))&4294967295);HEAP32[((__ZZ10MbrolaFilliiE9n_samples)>>2)]=$sub;var $16=HEAP32[((__ZZ10MbrolaFilliiE9n_samples)>>2)];var $tobool8=((($16))|0)!=0;var $cond=($tobool8)?1:0;$retval=$cond;;}
var $17=$retval;;return $17;return null;}
function __Z11MbrolaResetv(){;var __label__;var $call=_reset_MBR();;return;return;}
function __Z10LoadPhDatav(){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $retval;var $ix;var $n_phonemes;var $version;var $result;var $length=__stackBase__;var $p;var $pw;$result=1;var $0=HEAP32[((__ZL16phoneme_tab_data)>>2)];var $call=__ZL10ReadPhFilePvPKcPi($0,((__str1412)&4294967295),0);HEAP32[((__ZL16phoneme_tab_data)>>2)]=$call;var $cmp=((($call))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=-1;;}
else if(__label__==2){var $1=HEAP32[((_phoneme_index)>>2)];var $2=$1;var $call1=__ZL10ReadPhFilePvPKcPi($2,((__str2413)&4294967295),0);var $3=$call1;HEAP32[((_phoneme_index)>>2)]=$3;var $cmp2=((($3))|0)==0;if($cmp2){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=-1;;}
else if(__label__==4){var $4=HEAP32[((_phondata_ptr)>>2)];var $call5=__ZL10ReadPhFilePvPKcPi($4,((__str3414)&4294967295),0);HEAP32[((_phondata_ptr)>>2)]=$call5;var $cmp6=((($call5))|0)==0;if($cmp6){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=-1;;}
else if(__label__==6){var $5=HEAP32[((_tunes)>>2)];var $6=$5;var $call9=__ZL10ReadPhFilePvPKcPi($6,((__str4415)&4294967295),$length);var $7=$call9;HEAP32[((_tunes)>>2)]=$7;var $cmp10=((($7))|0)==0;if($cmp10){__label__=7;;}else{__label__=8;;}
if(__label__==7){$retval=-1;;}
else if(__label__==8){var $8=HEAP32[((_phondata_ptr)>>2)];HEAP32[((_wavefile_data)>>2)]=$8;var $9=HEAPU32[(($length)>>2)];var $div=Math.floor(((($9))>>>0)/68);HEAP32[((_n_tunes)>>2)]=$div;$version=0;$ix=0;;$for_body$14:while(1){var $10=$ix;var $11=HEAP32[((_wavefile_data)>>2)];var $arrayidx=(($11+$10)&4294967295);var $12=HEAPU8[($arrayidx)];var $conv=((($12))&255);var $13=$ix;var $mul=((($13)*8)&4294967295);var $shl=($conv)<<($mul);var $14=$version;var $add=((($shl)+($14))&4294967295);$version=$add;var $15=$ix;var $inc=((($15)+1)&4294967295);$ix=$inc;var $cmp13=((($inc))|0)<4;if($cmp13){__label__=9;continue $for_body$14;}else{__label__=10;break $for_body$14;}}
var $16=$version;var $cmp14=((($16))|0)!=83200;if($cmp14){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $17=$version;$result=$17;;}
var $18=HEAP32[((__ZL16phoneme_tab_data)>>2)];$p=$18;var $19=$p;var $arrayidx17=(($19)&4294967295);var $20=HEAPU8[($arrayidx17)];var $conv18=((($20))&255);HEAP32[((_n_phoneme_tables)>>2)]=$conv18;var $21=$p;var $add_ptr=(($21+4)&4294967295);$p=$add_ptr;$ix=0;var $22=$ix;var $23=HEAP32[((_n_phoneme_tables)>>2)];var $cmp201=((($22))|0)<((($23))|0);if($cmp201){__label__=13;;}else{__label__=14;;}
$for_body21$$for_end42$20:do{if(__label__==13){while(1){var $24=$p;var $arrayidx22=(($24)&4294967295);var $25=HEAPU8[($arrayidx22)];var $conv23=((($25))&255);$n_phonemes=$conv23;var $26=$p;var $arrayidx24=(($26)&4294967295);var $27=HEAPU8[($arrayidx24)];var $conv25=((($27))&255);var $28=$ix;var $arrayidx26=((_phoneme_tab_list+$28*48)&4294967295);var $n_phonemes27=(($arrayidx26+36)&4294967295);HEAP32[(($n_phonemes27)>>2)]=$conv25;var $29=$p;var $arrayidx28=(($29+1)&4294967295);var $30=HEAPU8[($arrayidx28)];var $conv29=((($30))&255);var $31=$ix;var $arrayidx30=((_phoneme_tab_list+$31*48)&4294967295);var $includes=(($arrayidx30+40)&4294967295);HEAP32[(($includes)>>2)]=$conv29;var $32=$p;var $33=$32;$pw=$33;var $34=$pw;var $arrayidx31=(($34+4)&4294967295);var $35=HEAP32[(($arrayidx31)>>2)];var $call32=__Z13Reverse4Bytesi($35);var $36=$ix;var $arrayidx33=((_phoneme_tab_list+$36*48)&4294967295);var $equivalence_tables=(($arrayidx33+44)&4294967295);HEAP32[(($equivalence_tables)>>2)]=$call32;var $37=$p;var $add_ptr34=(($37+8)&4294967295);$p=$add_ptr34;var $38=$ix;var $arrayidx35=((_phoneme_tab_list+$38*48)&4294967295);var $name=(($arrayidx35)&4294967295);var $arraydecay=(($name)&4294967295);var $39=$p;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$39;$dest$=$arraydecay;$stop$=$src$+32;if(($dest$%4)==($src$%4)&&32>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $40=$p;var $add_ptr36=(($40+32)&4294967295);$p=$add_ptr36;var $41=$p;var $42=$41;var $43=$ix;var $arrayidx37=((_phoneme_tab_list+$43*48)&4294967295);var $phoneme_tab_ptr=(($arrayidx37+32)&4294967295);HEAP32[(($phoneme_tab_ptr)>>2)]=$42;var $44=$n_phonemes;var $mul38=((($44)*16)&4294967295);var $45=$p;var $add_ptr39=(($45+$mul38)&4294967295);$p=$add_ptr39;var $46=$ix;var $inc41=((($46)+1)&4294967295);$ix=$inc41;var $47=$ix;var $48=HEAP32[((_n_phoneme_tables)>>2)];var $cmp20=((($47))|0)<((($48))|0);if($cmp20){__label__=13;continue;}else{__label__=14;break $for_body21$$for_end42$20;}}}}while(0);var $49=HEAP32[((_phoneme_tab_number)>>2)];var $50=HEAP32[((_n_phoneme_tables)>>2)];var $cmp43=((($49))|0)>=((($50))|0);if($cmp43){__label__=15;;}else{__label__=16;;}
if(__label__==15){HEAP32[((_phoneme_tab_number)>>2)]=0;;}
var $51=$result;$retval=$51;;}}}}
var $52=$retval;STACKTOP=__stackBase__;return $52;return null;}
function __ZL10ReadPhFilePvPKcPi($ptr,$fname,$size){var __stackBase__=STACKTOP;STACKTOP+=192;_memset(__stackBase__,0,192);var __label__;var $retval;var $ptr_addr;var $fname_addr;var $size_addr;var $f_in;var $p;var $length;var $buf=__stackBase__;$ptr_addr=$ptr;$fname_addr=$fname;$size_addr=$size;var $arraydecay=(($buf)&4294967295);var $0=$fname_addr;var $call=_sprintf($arraydecay,((__str74726)&4294967295),allocate([((_path_home)&4294967295),0,0,0,47,0,0,0,$0,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay1=(($buf)&4294967295);var $call2=__Z13GetFileLengthPKc($arraydecay1);$length=$call2;var $arraydecay3=(($buf)&4294967295);var $call4=_fopen($arraydecay3,((__str18429)&4294967295));$f_in=$call4;var $cmp=((($call4))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($1+12)&4294967295);var $2=HEAP32[(($_stderr)>>2)];var $arraydecay5=(($buf)&4294967295);var $call6=_fprintf($2,((__str19430)&4294967295),allocate([$arraydecay5,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=0;;}
else if(__label__==2){var $3=$ptr_addr;var $cmp7=((($3))|0)!=0;if($cmp7){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $4=$ptr_addr;__Z4FreePv($4);;}
var $5=$length;var $call10=__Z5Alloci($5);$p=$call10;var $cmp11=((($call10))|0)==0;if($cmp11){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $6=$f_in;var $call13=_fclose($6);$retval=0;;}
else if(__label__==6){var $7=$p;var $8=$length;var $9=$f_in;var $call15=_fread($7,1,$8,$9);var $10=$length;var $cmp16=((($call15))|0)!=((($10))|0);var $11=$f_in;var $call18=_fclose($11);if($cmp16){__label__=7;;}else{__label__=8;;}
if(__label__==7){$retval=0;;}
else if(__label__==8){var $12=$size_addr;var $cmp21=((($12))|0)!=0;if($cmp21){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $13=$length;var $14=$size_addr;HEAP32[(($14)>>2)]=$13;;}
var $15=$p;$retval=$15;;}}}
var $16=$retval;STACKTOP=__stackBase__;return $16;return null;}
function __Z10FreePhDatav(){;var __label__;var $0=HEAP32[((__ZL16phoneme_tab_data)>>2)];__Z4FreePv($0);var $1=HEAP32[((_phoneme_index)>>2)];var $2=$1;__Z4FreePv($2);var $3=HEAP32[((_phondata_ptr)>>2)];__Z4FreePv($3);HEAP32[((__ZL16phoneme_tab_data)>>2)]=0;HEAP32[((_phoneme_index)>>2)]=0;HEAP32[((_phondata_ptr)>>2)]=0;;return;return;}
function __Z11PhonemeCodej($mnem){;var __label__;var $retval;var $mnem_addr;var $ix;$mnem_addr=$mnem;$ix=0;;while(1){var $0=$ix;var $1=HEAP32[((_n_phoneme_tab)>>2)];var $cmp=((($0))|0)<((($1))|0);if(!($cmp)){__label__=6;break;}
var $2=$ix;var $arrayidx=((_phoneme_tab+$2*4)&4294967295);var $3=HEAP32[(($arrayidx)>>2)];var $cmp1=((($3))|0)==0;if($cmp1){__label__=5;;}else{__label__=3;;}
if(__label__==3){var $4=$ix;var $arrayidx2=((_phoneme_tab+$4*4)&4294967295);var $5=HEAP32[(($arrayidx2)>>2)];var $mnemonic=(($5)&4294967295);var $6=HEAP32[(($mnemonic)>>2)];var $7=$mnem_addr;var $cmp3=((($6))|0)==((($7))|0);if($cmp3){__label__=4;break;}}
var $11=$ix;var $inc=((($11)+1)&4294967295);$ix=$inc;__label__=1;continue;}
if(__label__==6){$retval=0;;}
else if(__label__==4){var $8=$ix;var $arrayidx5=((_phoneme_tab+$8*4)&4294967295);var $9=HEAP32[(($arrayidx5)>>2)];var $code=(($9+10)&4294967295);var $10=HEAPU8[($code)];var $conv=((($10))&255);$retval=$conv;;}
var $12=$retval;;return $12;return null;}
function __Z19LookupPhonemeStringPKc($string){;var __label__;var __lastLabel__=null;var $string_addr;var $ix;var $c;var $mnem;$string_addr=$string;$mnem=0;$ix=0;__lastLabel__=0;;while(1){var $0=__lastLabel__==3?$inc:(0);var $cmp=((($0))|0)<4;if(!($cmp)){__label__=4;break;}
var $1=$ix;var $2=$string_addr;var $arrayidx=(($2+$1)&4294967295);var $3=HEAP8[($arrayidx)];var $conv=(tempInt=(($3)),(tempInt>=128?tempInt-256:tempInt));var $cmp1=((($conv))|0)==0;if($cmp1){__label__=4;break;}
var $4=$ix;var $5=$string_addr;var $arrayidx2=(($5+$4)&4294967295);var $6=HEAP8[($arrayidx2)];$c=$6;var $7=$c;var $conv3=((($7))&255);var $8=$ix;var $mul=((($8)*8)&4294967295);var $shl=($conv3)<<($mul);var $9=$mnem;var $or=($shl)|($9);$mnem=$or;var $10=$ix;var $inc=((($10)+1)&4294967295);$ix=$inc;__lastLabel__=3;__label__=1;continue;}
var $11=$mnem;var $call=__Z11PhonemeCodej($11);;return $call;return null;}
function __Z11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LIST($this_ph,$which,$fmt_params,$n_frames,$plist){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var __lastLabel__=null;var $this_ph_addr;var $which_addr;var $fmt_params_addr;var $n_frames_addr;var $plist_addr;var $ix;var $nf=__stackBase__;var $nf1;var $seq_break;var $frames;var $length1;var $length_std;var $length_factor;var $seq;var $seq2;var $seqk;var $seqk2;var $frame;$this_ph_addr=$this_ph;$which_addr=$which;$fmt_params_addr=$fmt_params;$n_frames_addr=$n_frames;$plist_addr=$plist;var $0=$fmt_params_addr;var $fmt_addr=(($0+8)&4294967295);var $1=HEAP32[(($fmt_addr)>>2)];var $2=HEAP32[((_phondata_ptr)>>2)];var $arrayidx=(($2+$1)&4294967295);var $3=$arrayidx;$seq=$3;var $4=$seq;var $5=$4;$seqk=$5;var $6=$seq;var $n_frames1=(($6+2)&4294967295);var $7=HEAPU8[($n_frames1)];var $conv=((($7))&255);HEAP32[(($nf)>>2)]=$conv;var $8=HEAP32[(($nf)>>2)];var $cmp=((($8))|0)>=25;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[(($nf)>>2)]=24;;}
var $9=$fmt_params_addr;var $fmt2_lenadj=(($9+24)&4294967295);var $10=HEAP32[(($fmt2_lenadj)>>2)];var $11=$fmt_params_addr;var $fmt_length=(($11+12)&4294967295);var $12=HEAP32[(($fmt_length)>>2)];var $add=((($12)+($10))&4294967295);HEAP32[((_seq_len_adjust)>>2)]=$add;$seq_break=0;$ix=0;var $13=$ix;var $14=HEAP32[(($nf)>>2)];var $cmp29=((($13))|0)<((($14))|0);if($cmp29){__label__=4;;}else{__label__=3;;}
$for_body$$for_end_thread$5:do{if(__label__==4){while(1){var $15=$seq;var $frame3=(($15+4)&4294967295);var $arrayidx4=(($frame3)&4294967295);var $frflags=(($arrayidx4)&4294967295);var $16=HEAP16[(($frflags)>>1)];var $conv5=(tempInt=(($16)),(tempInt>=32768?tempInt-65536:tempInt));var $and=($conv5)&1;var $tobool=((($and))|0)!=0;var $17=$ix;if($tobool){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $18=$seqk;var $frame7=(($18+4)&4294967295);var $arrayidx8=(($frame7+$17*64)&4294967295);$frame=$arrayidx8;;}
else if(__label__==6){var $19=$seq;var $frame9=(($19+4)&4294967295);var $arrayidx10=(($frame9+$17*44)&4294967295);var $20=$arrayidx10;$frame=$20;;}
var $21=$frame;var $22=$ix;var $arrayidx12=((__ZZ11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LISTE10frames_buf+$22*8)&4294967295);var $frame13=(($arrayidx12+4)&4294967295);HEAP32[(($frame13)>>2)]=$21;var $23=$frame;var $frflags14=(($23)&4294967295);var $24=HEAP16[(($frflags14)>>1)];var $25=$ix;var $arrayidx15=((__ZZ11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LISTE10frames_buf+$25*8)&4294967295);var $frflags16=(($arrayidx15+2)&4294967295);HEAP16[(($frflags16)>>1)]=$24;var $26=$frame;var $length=(($26+16)&4294967295);var $27=HEAPU8[($length)];var $conv17=((($27))&255);var $28=$ix;var $arrayidx18=((__ZZ11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LISTE10frames_buf+$28*8)&4294967295);var $length19=(($arrayidx18)&4294967295);HEAP16[(($length19)>>1)]=$conv17;var $29=$frame;var $frflags20=(($29)&4294967295);var $30=HEAP16[(($frflags20)>>1)];var $conv21=(tempInt=(($30)),(tempInt>=32768?tempInt-65536:tempInt));var $and22=($conv21)&2;var $tobool23=((($and22))|0)!=0;if($tobool23){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $31=$ix;$seq_break=$31;;}
var $32=$ix;var $inc=((($32)+1)&4294967295);$ix=$inc;var $33=$ix;var $34=HEAP32[(($nf)>>2)];var $cmp2=((($33))|0)<((($34))|0);if($cmp2){__label__=4;continue;}else{__label__=10;break;}}
var $_pr10=$seq_break;$frames=((__ZZ11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LISTE10frames_buf)&4294967295);var $cmp26=((($_pr10))|0)>0;if(!($cmp26)){__label__=14;break $for_body$$for_end_thread$5;}
var $35=$which_addr;var $cmp28=((($35))|0)==1;var $36=$seq_break;if($cmp28){__label__=12;;}else{__label__=13;;}
if(__label__==12){var $add30=((($36)+1)&4294967295);HEAP32[(($nf)>>2)]=$add30;;}
else if(__label__==13){var $arrayidx32=((__ZZ11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LISTE10frames_buf+$36*8)&4294967295);$frames=$arrayidx32;var $37=$seq_break;var $38=HEAP32[(($nf)>>2)];var $sub=((($38)-($37))&4294967295);HEAP32[(($nf)>>2)]=$sub;;}}
else if(__label__==3){$frames=((__ZZ11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LISTE10frames_buf)&4294967295);;}}while(0);var $39=$this_ph_addr;var $type=(($39+11)&4294967295);var $40=HEAPU8[($type)];var $conv35=((($40))&255);var $cmp36=((($conv35))|0)==2;if($cmp36){__label__=15;;}else{__label__=18;;}
$land_lhs_true$$if_end42$22:do{if(__label__==15){var $41=$fmt_params_addr;var $fmt2_addr=(($41+20)&4294967295);var $42=HEAP32[(($fmt2_addr)>>2)];var $cmp37=((($42))|0)==0;if(!($cmp37)){__label__=18;break $land_lhs_true$$if_end42$22;}
var $43=$fmt_params_addr;var $use_vowelin=(($43+4)&4294967295);var $44=HEAP32[(($use_vowelin)>>2)];var $tobool39=((($44))|0)!=0;if(!($tobool39)){__label__=18;break $land_lhs_true$$if_end42$22;}
var $45=$frames;var $46=$fmt_params_addr;var $transition0=(($46+36)&4294967295);var $47=HEAP32[(($transition0)>>2)];var $48=$fmt_params_addr;var $transition1=(($48+40)&4294967295);var $49=HEAP32[(($transition1)>>2)];var $50=$which_addr;var $call=__Z18FormantTransition2P10frameref_tRijjP11PHONEME_TABi($45,$nf,$47,$49,0,$50);var $51=HEAP32[((_seq_len_adjust)>>2)];var $add41=((($51)+($call))&4294967295);HEAP32[((_seq_len_adjust)>>2)]=$add41;;}}while(0);$length1=0;var $52=HEAP32[(($nf)>>2)];var $sub43=((($52)-1)&4294967295);$nf1=$sub43;$ix=0;var $53=$ix;var $54=$nf1;var $cmp457=((($53))|0)<((($54))|0);if($cmp457){__label__=19;;}else{__label__=20;;}
$for_body46$$for_end53$27:do{if(__label__==19){while(1){var $55=$ix;var $56=$frames;var $arrayidx47=(($56+8*$55)&4294967295);var $length48=(($arrayidx47)&4294967295);var $57=HEAP16[(($length48)>>1)];var $conv49=(tempInt=(($57)),(tempInt>=32768?tempInt-65536:tempInt));var $58=$length1;var $add50=((($58)+($conv49))&4294967295);$length1=$add50;var $59=$ix;var $inc52=((($59)+1)&4294967295);$ix=$inc52;var $60=$ix;var $61=$nf1;var $cmp45=((($60))|0)<((($61))|0);if($cmp45){__label__=19;continue;}else{__label__=20;break $for_body46$$for_end53$27;}}}}while(0);var $62=$fmt_params_addr;var $fmt2_addr54=(($62+20)&4294967295);var $63=HEAP32[(($fmt2_addr54)>>2)];var $cmp55=((($63))|0)!=0;if($cmp55){__label__=21;;}else{__label__=29;;}
if(__label__==21){var $64=$fmt_params_addr;var $fmt2_addr57=(($64+20)&4294967295);var $65=HEAP32[(($fmt2_addr57)>>2)];var $66=HEAP32[((_phondata_ptr)>>2)];var $arrayidx58=(($66+$65)&4294967295);var $67=$arrayidx58;$seq2=$67;var $68=$seq2;var $69=$68;$seqk2=$69;var $70=HEAP32[(($nf)>>2)];var $dec=((($70)-1)&4294967295);HEAP32[(($nf)>>2)]=$dec;$ix=0;var $71=$ix;var $72=$seq2;var $n_frames604=(($72+2)&4294967295);var $73=HEAPU8[($n_frames604)];var $conv615=((($73))&255);var $cmp626=((($71))|0)<((($conv615))|0);if($cmp626){__label__=22;;}else{__label__=28;;}
$for_body63$$for_end92$33:do{if(__label__==22){while(1){var $74=$seq2;var $frame64=(($74+4)&4294967295);var $arrayidx65=(($frame64)&4294967295);var $frflags66=(($arrayidx65)&4294967295);var $75=HEAP16[(($frflags66)>>1)];var $conv67=(tempInt=(($75)),(tempInt>=32768?tempInt-65536:tempInt));var $and68=($conv67)&1;var $tobool69=((($and68))|0)!=0;var $76=$ix;if($tobool69){__label__=23;;}else{__label__=24;;}
if(__label__==23){var $77=$seqk2;var $frame71=(($77+4)&4294967295);var $arrayidx72=(($frame71+$76*64)&4294967295);$frame=$arrayidx72;;}
else if(__label__==24){var $78=$seq2;var $frame74=(($78+4)&4294967295);var $arrayidx75=(($frame74+$76*44)&4294967295);var $79=$arrayidx75;$frame=$79;;}
var $80=$frame;var $length77=(($80+16)&4294967295);var $81=HEAPU8[($length77)];var $conv78=((($81))&255);var $82=HEAP32[(($nf)>>2)];var $83=$frames;var $arrayidx79=(($83+8*$82)&4294967295);var $length80=(($arrayidx79)&4294967295);HEAP16[(($length80)>>1)]=$conv78;var $84=$ix;var $cmp81=((($84))|0)>0;if($cmp81){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $85=$frame;var $86=HEAP32[(($nf)>>2)];var $87=$frames;var $arrayidx83=(($87+8*$86)&4294967295);var $frame84=(($arrayidx83+4)&4294967295);HEAP32[(($frame84)>>2)]=$85;var $88=$frame;var $frflags85=(($88)&4294967295);var $89=HEAP16[(($frflags85)>>1)];var $90=HEAP32[(($nf)>>2)];var $91=$frames;var $arrayidx86=(($91+8*$90)&4294967295);var $frflags87=(($arrayidx86+2)&4294967295);HEAP16[(($frflags87)>>1)]=$89;;}
var $92=HEAP32[(($nf)>>2)];var $inc89=((($92)+1)&4294967295);HEAP32[(($nf)>>2)]=$inc89;var $93=$ix;var $inc91=((($93)+1)&4294967295);$ix=$inc91;var $94=$ix;var $95=$seq2;var $n_frames60=(($95+2)&4294967295);var $96=HEAPU8[($n_frames60)];var $conv61=((($96))&255);var $cmp62=((($94))|0)<((($conv61))|0);if($cmp62){__label__=22;continue;}else{__label__=28;break $for_body63$$for_end92$33;}}}}while(0);HEAP32[((_wavefile_ix)>>2)]=0;;}
var $97=$length1;var $cmp94=((($97))|0)>0;if($cmp94){__label__=30;;}else{__label__=47;;}
$if_then95$$if_end175$45:do{if(__label__==30){var $98=$which_addr;var $cmp96=((($98))|0)==2;if($cmp96){__label__=31;;}else{__label__=37;;}
if(__label__==31){var $99=$fmt_params_addr;var $std_length=(($99+44)&4294967295);var $100=HEAP32[(($std_length)>>2)];var $101=HEAP32[((_seq_len_adjust)>>2)];var $add98=((($100)-45)&4294967295);var $sub99=((($add98)+($101))&4294967295);$length_std=$sub99;var $102=$length_std;var $cmp100=((($102))|0)<10;if($cmp100){__label__=32;;}else{__label__=33;;}
if(__label__==32){$length_std=10;;}
var $103=$plist_addr;var $synthflags=(($103+4)&4294967295);var $104=HEAPU16[(($synthflags)>>1)];var $conv103=((($104))&65535);var $and104=($conv103)&8;var $tobool105=((($and104))|0)!=0;if($tobool105){__label__=34;;}else{__label__=35;;}
if(__label__==34){var $105=HEAP32[((((_phoneme_tab+48)&4294967295))>>2)];var $std_length107=(($105+14)&4294967295);var $106=HEAPU8[($std_length107)];var $conv108=((($106))&255);var $mul=((($conv108)*2)&4294967295);var $107=$length_std;var $add109=((($mul)+($107))&4294967295);$length_std=$add109;;}
var $108=$length_std;var $mul111=((($108)*256)&4294967295);var $109=$length1;var $div=((((($mul111))|0)/((($109))|0))|0);$length_factor=$div;$ix=0;var $110=$ix;var $111=$nf1;var $cmp1133=((($110))|0)<((($111))|0);if(!($cmp1133)){__label__=47;break $if_then95$$if_end175$45;}
while(1){var $112=$ix;var $113=$frames;var $arrayidx115=(($113+8*$112)&4294967295);var $length116=(($arrayidx115)&4294967295);var $114=HEAP16[(($length116)>>1)];var $conv117=(tempInt=(($114)),(tempInt>=32768?tempInt-65536:tempInt));var $115=$length_factor;var $mul118=((($conv117)*($115))&4294967295);var $div119=((((($mul118))|0)/256)|0);var $conv120=((($div119))&65535);var $116=$ix;var $117=$frames;var $arrayidx121=(($117+8*$116)&4294967295);var $length122=(($arrayidx121)&4294967295);HEAP16[(($length122)>>1)]=$conv120;var $118=$ix;var $inc124=((($118)+1)&4294967295);$ix=$inc124;var $119=$ix;var $120=$nf1;var $cmp113=((($119))|0)<((($120))|0);if($cmp113){__label__=36;continue;}else{__label__=47;break $if_then95$$if_end175$45;}}}
else if(__label__==37){var $121=$which_addr;var $cmp127=((($121))|0)==1;var $122=$fmt_params_addr;if($cmp127){__label__=38;;}else{__label__=41;;}
$if_then128$$if_else145$58:do{if(__label__==38){var $fmt_control=(($122)&4294967295);var $123=HEAP32[(($fmt_control)>>2)];var $cmp129=((($123))|0)==1;if(!($cmp129)){__label__=43;break $if_then128$$if_else145$58;}
var $124=$fmt_params_addr;var $std_length131=(($124+44)&4294967295);var $125=HEAP32[(($std_length131)>>2)];var $cmp132=((($125))|0)<130;if(!($cmp132)){__label__=43;break $if_then128$$if_else145$58;}
var $126=$frames;var $arrayidx134=(($126)&4294967295);var $length135=(($arrayidx134)&4294967295);var $127=HEAP16[(($length135)>>1)];var $conv136=(tempInt=(($127)),(tempInt>=32768?tempInt-65536:tempInt));var $128=$fmt_params_addr;var $std_length137=(($128+44)&4294967295);var $129=HEAP32[(($std_length137)>>2)];var $mul138=((($129)*($conv136))&4294967295);var $div139=((((($mul138))|0)/130)|0);var $conv140=((($div139))&65535);var $130=$frames;var $arrayidx141=(($130)&4294967295);var $length142=(($arrayidx141)&4294967295);HEAP16[(($length142)>>1)]=$conv140;__label__=43;break $if_then128$$if_else145$58;}
else if(__label__==41){var $std_length146=(($122+44)&4294967295);var $131=HEAP32[(($std_length146)>>2)];var $cmp147=((($131))|0)>0;if(!($cmp147)){__label__=43;break $if_then128$$if_else145$58;}
var $132=$fmt_params_addr;var $std_length149=(($132+44)&4294967295);var $133=HEAP32[(($std_length149)>>2)];var $134=$length1;var $sub150=((($133)-($134))&4294967295);var $135=HEAP32[((_seq_len_adjust)>>2)];var $add151=((($135)+($sub150))&4294967295);HEAP32[((_seq_len_adjust)>>2)]=$add151;__lastLabel__=42;__label__=44;break $if_then128$$if_else145$58;}}while(0);if(__label__==43){var $_pr=HEAP32[((_seq_len_adjust)>>2)];__lastLabel__=43;;}
var $136=__lastLabel__==43?$_pr:($add151);var $cmp154=((($136))|0)!=0;if(!($cmp154)){__label__=47;break $if_then95$$if_end175$45;}
var $137=$length1;var $138=HEAP32[((_seq_len_adjust)>>2)];var $add156=((($138)+($137))&4294967295);var $mul157=((($add156)*256)&4294967295);var $139=$length1;var $div158=((((($mul157))|0)/((($139))|0))|0);$length_factor=$div158;$ix=0;var $140=$ix;var $141=$nf1;var $cmp1601=((($140))|0)<((($141))|0);if(!($cmp1601)){__label__=47;break $if_then95$$if_end175$45;}
while(1){var $142=$ix;var $143=$frames;var $arrayidx162=(($143+8*$142)&4294967295);var $length163=(($arrayidx162)&4294967295);var $144=HEAP16[(($length163)>>1)];var $conv164=(tempInt=(($144)),(tempInt>=32768?tempInt-65536:tempInt));var $145=$length_factor;var $mul165=((($conv164)*($145))&4294967295);var $div166=((((($mul165))|0)/256)|0);var $conv167=((($div166))&65535);var $146=$ix;var $147=$frames;var $arrayidx168=(($147+8*$146)&4294967295);var $length169=(($arrayidx168)&4294967295);HEAP16[(($length169)>>1)]=$conv167;var $148=$ix;var $inc171=((($148)+1)&4294967295);$ix=$inc171;var $149=$ix;var $150=$nf1;var $cmp160=((($149))|0)<((($150))|0);if($cmp160){__label__=46;continue;}else{__label__=47;break $if_then95$$if_end175$45;}}}}}while(0);var $151=HEAP32[(($nf)>>2)];var $152=$n_frames_addr;HEAP32[(($152)>>2)]=$151;var $153=$frames;STACKTOP=__stackBase__;return $153;return null;}
function __Z11GetEnvelopei($index){;var __label__;var $retval;var $index_addr;$index_addr=$index;var $0=$index_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($1+12)&4294967295);var $2=HEAP32[(($_stderr)>>2)];var $3=_fwrite(((__str5416)&4294967295),20,1,$2);var $4=HEAP32[((((_envelope_data)&4294967295))>>2)];$retval=$4;;}
else if(__label__==2){var $5=$index_addr;var $6=HEAP32[((_phondata_ptr)>>2)];var $arrayidx=(($6+$5)&4294967295);$retval=$arrayidx;;}
var $7=$retval;;return $7;return null;}
function __Z18SelectPhonemeTablei($number){;var __label__;var $number_addr;$number_addr=$number;HEAP32[((_n_phoneme_tab)>>2)]=0;var $0=$number_addr;__ZL17SetUpPhonemeTableii($0,0);var $1=HEAP32[((_n_phoneme_tab)>>2)];var $inc=((($1)+1)&4294967295);HEAP32[((_n_phoneme_tab)>>2)]=$inc;var $2=$number_addr;HEAP32[((_current_phoneme_table)>>2)]=$2;;return;return;}
function __ZL17SetUpPhonemeTableii($number,$recursing){;var __label__;var $number_addr;var $recursing_addr;var $ix;var $includes;var $ph_code;var $phtab;$number_addr=$number;$recursing_addr=$recursing;var $0=$recursing_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=((_phoneme_tab_flags)&4294967295);$stop$=$dest$+256;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};;}
var $1=$number_addr;var $arrayidx=((_phoneme_tab_list+$1*48)&4294967295);var $includes1=(($arrayidx+40)&4294967295);var $2=HEAP32[(($includes1)>>2)];$includes=$2;var $cmp2=((($2))|0)>0;if($cmp2){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $3=$includes;var $sub=((($3)-1)&4294967295);__ZL17SetUpPhonemeTableii($sub,1);;}
var $4=$number_addr;var $arrayidx5=((_phoneme_tab_list+$4*48)&4294967295);var $phoneme_tab_ptr=(($arrayidx5+32)&4294967295);var $5=HEAP32[(($phoneme_tab_ptr)>>2)];$phtab=$5;$ix=0;var $6=$ix;var $7=$number_addr;var $arrayidx61=((_phoneme_tab_list+$7*48)&4294967295);var $n_phonemes2=(($arrayidx61+36)&4294967295);var $8=HEAP32[(($n_phonemes2)>>2)];var $cmp73=((($6))|0)<((($8))|0);if($cmp73){__label__=5;;}else{__label__=10;;}
$for_body$$for_end$8:do{if(__label__==5){while(1){var $9=$ix;var $10=$phtab;var $arrayidx8=(($10+16*$9)&4294967295);var $code=(($arrayidx8+10)&4294967295);var $11=HEAPU8[($code)];var $conv=((($11))&255);$ph_code=$conv;var $12=$ix;var $13=$phtab;var $arrayidx9=(($13+16*$12)&4294967295);var $14=$ph_code;var $arrayidx10=((_phoneme_tab+$14*4)&4294967295);HEAP32[(($arrayidx10)>>2)]=$arrayidx9;var $15=$ph_code;var $16=HEAP32[((_n_phoneme_tab)>>2)];var $cmp11=((($15))|0)>((($16))|0);if($cmp11){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $17=$ph_code;HEAP32[((_n_phoneme_tab)>>2)]=$17;;}
var $18=$recursing_addr;var $cmp14=((($18))|0)==0;if($cmp14){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $19=$ph_code;var $arrayidx16=((_phoneme_tab_flags+$19)&4294967295);var $20=HEAPU8[($arrayidx16)];var $conv17=((($20))&255);var $or=($conv17)|1;var $conv18=((($or))&255);HEAP8[($arrayidx16)]=$conv18;;}
var $21=$ix;var $inc=((($21)+1)&4294967295);$ix=$inc;var $22=$ix;var $23=$number_addr;var $arrayidx6=((_phoneme_tab_list+$23*48)&4294967295);var $n_phonemes=(($arrayidx6+36)&4294967295);var $24=HEAP32[(($n_phonemes)>>2)];var $cmp7=((($22))|0)<((($24))|0);if($cmp7){__label__=5;continue;}else{__label__=10;break $for_body$$for_end$8;}}}}while(0);;return;return;}
function __Z18LookupPhonemeTablePKc($name){;var __label__;var $retval;var $name_addr;var $ix;$name_addr=$name;$ix=0;;while(1){var $0=$ix;var $1=HEAP32[((_n_phoneme_tables)>>2)];var $cmp=((($0))|0)<((($1))|0);if(!($cmp)){__label__=5;break;}
var $2=$name_addr;var $3=$ix;var $arrayidx=((_phoneme_tab_list+$3*48)&4294967295);var $name1=(($arrayidx)&4294967295);var $arraydecay=(($name1)&4294967295);var $call=_strcmp($2,$arraydecay);var $cmp2=((($call))|0)==0;var $4=$ix;if($cmp2){__label__=3;break;}
var $inc=((($4)+1)&4294967295);$ix=$inc;__label__=1;continue;}
if(__label__==3){HEAP32[((_phoneme_tab_number)>>2)]=$4;;}
var $5=$ix;var $6=HEAP32[((_n_phoneme_tables)>>2)];var $cmp3=((($5))|0)==((($6))|0);if($cmp3){__label__=6;;}else{__label__=7;;}
if(__label__==6){$retval=-1;;}
else if(__label__==7){var $7=$ix;$retval=$7;;}
var $8=$retval;;return $8;return null;}
function __Z22SelectPhonemeTableNamePKc($name){;var __label__;var $retval;var $name_addr;var $ix;$name_addr=$name;var $0=$name_addr;var $call=__Z18LookupPhonemeTablePKc($0);$ix=$call;var $cmp=((($call))|0)==-1;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=-1;;}
else if(__label__==2){var $1=$ix;__Z18SelectPhonemeTablei($1);var $2=$ix;$retval=$2;;}
var $3=$retval;;return $3;return null;}
function __Z10LoadConfigv(){var __stackBase__=STACKTOP;STACKTOP+=364;_memset(__stackBase__,0,364);var __label__;var $buf=__stackBase__;var $f;var $ix;var $c1=__stackBase__+160;var $p;var $string=__stackBase__+164;HEAP32[((_logging_type)>>2)]=0;$ix=0;;$for_body$2:while(1){var $0=$ix;var $arrayidx=((_soundicon_tab+$0*16)&4294967295);var $filename=(($arrayidx+12)&4294967295);HEAP32[(($filename)>>2)]=0;var $1=$ix;var $arrayidx1=((_soundicon_tab+$1*16)&4294967295);var $data=(($arrayidx1+8)&4294967295);HEAP32[(($data)>>2)]=0;var $2=$ix;var $inc=((($2)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<4;if($cmp){__label__=1;continue $for_body$2;}else{__label__=2;break $for_body$2;}}
var $arraydecay=(($buf)&4294967295);var $call=_sprintf($arraydecay,((__str74726)&4294967295),allocate([((_path_home)&4294967295),0,0,0,47,0,0,0,((__str7418)&4294967295),0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay2=(($buf)&4294967295);var $call3=_fopen($arraydecay2,((__str51703)&4294967295));$f=$call3;var $cmp4=((($call3))|0)==0;if($cmp4){__label__=17;;}else{__label__=3;;}
$while_end$$while_cond_preheader$5:do{if(__label__==3){var $arraydecay5=(($buf)&4294967295);var $3=$f;var $call61=_fgets($arraydecay5,160,$3);var $cmp72=((($call61))|0)!=0;if(!($cmp72)){__label__=17;break $while_end$$while_cond_preheader$5;}
var $arrayidx8=(($buf)&4294967295);var $arraydecay12=(($buf)&4294967295);var $arrayidx16=(($buf+4)&4294967295);var $arraydecay17=(($string)&4294967295);var $arraydecay21=(($string)&4294967295);var $arraydecay24=(($buf)&4294967295);var $arrayidx28=(($buf+5)&4294967295);var $arraydecay30=(($buf)&4294967295);var $arrayidx34=(($buf+10)&4294967295);var $arraydecay37=(($buf)&4294967295);var $arrayidx41=(($buf+10)&4294967295);var $arraydecay42=(($string)&4294967295);var $arraydecay48=(($string)&4294967295);var $arraydecay51=(($string)&4294967295);;$while_body$8:while(1){var $4=HEAP8[($arrayidx8)];var $conv=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $cmp9=((($conv))|0)==47;if($cmp9){__label__=6;;}else{__label__=7;;}
$while_cond_backedge$$if_end11$10:do{if(__label__==7){var $call13=_memcmp($arraydecay12,((__str9420)&4294967295),3);var $cmp14=((($call13))|0)==0;if($cmp14){__label__=8;;}else{__label__=10;;}
if(__label__==8){var $call18=_sscanf($arrayidx16,((__str10421)&4294967295),allocate([_logging_type,0,0,0,$arraydecay17,0,0,0],["i32*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $cmp19=((($call18))|0)==2;if(!($cmp19)){__label__=6;break $while_cond_backedge$$if_end11$10;}
var $call22=_fopen($arraydecay21,((__str11422)&4294967295));HEAP32[((_f_logespeak)>>2)]=$call22;;}
else if(__label__==10){var $call25=_memcmp($arraydecay24,((__str27677)&4294967295),4);var $cmp26=((($call25))|0)==0;if($cmp26){__label__=11;;}else{__label__=12;;}
if(__label__==11){__Z14ReadTonePointsPcPi($arrayidx28,((_tone_points)&4294967295));;}
else if(__label__==12){var $call31=_memcmp($arraydecay30,((__str13424)&4294967295),9);var $cmp32=((($call31))|0)==0;if($cmp32){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $call35=_sscanf($arrayidx34,((__str63715)&4294967295),allocate([_option_device_number,0,0,0],["i32*",0,0,0],ALLOC_STACK));;}
else if(__label__==14){var $call38=_memcmp($arraydecay37,((__str15426)&4294967295),9);var $cmp39=((($call38))|0)==0;if(!($cmp39)){__label__=6;break $while_cond_backedge$$if_end11$10;}
var $call43=_sscanf($arrayidx41,((__str16427)&4294967295),allocate([$c1,0,0,0,$arraydecay42,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));$ix=$call43;var $6=$ix;var $cmp44=((($6))|0)==2;if(!($cmp44)){__label__=6;break $while_cond_backedge$$if_end11$10;}
var $7=HEAP8[($c1)];var $conv46=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $8=HEAP32[((_n_soundicon_tab)>>2)];var $arrayidx47=((_soundicon_tab+$8*16)&4294967295);var $name=(($arrayidx47)&4294967295);HEAP32[(($name)>>2)]=$conv46;var $call49=_strlen($arraydecay48);var $add=((($call49)+1)&4294967295);var $call50=__Z5Alloci($add);$p=$call50;var $9=$p;var $call52=_strcpy($9,$arraydecay51);var $10=$p;var $11=HEAP32[((_n_soundicon_tab)>>2)];var $arrayidx53=((_soundicon_tab+$11*16)&4294967295);var $filename54=(($arrayidx53+12)&4294967295);HEAP32[(($filename54)>>2)]=$10;var $12=HEAP32[((_n_soundicon_tab)>>2)];var $inc55=((($12)+1)&4294967295);HEAP32[((_n_soundicon_tab)>>2)]=$inc55;var $arrayidx56=((_soundicon_tab+$12*16)&4294967295);var $length=(($arrayidx56+4)&4294967295);HEAP32[(($length)>>2)]=0;;}}}}}while(0);var $5=$f;var $call6=_fgets($arraydecay5,160,$5);var $cmp7=((($call6))|0)!=0;if($cmp7){__label__=5;continue $while_body$8;}else{__label__=17;break $while_end$$while_cond_preheader$5;}}}}while(0);STACKTOP=__stackBase__;return;return;}
function __Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA($tr,$control,$plist,$phdata){var __stackBase__=STACKTOP;STACKTOP+=44;_memset(__stackBase__,0,44);var __label__;var __lastLabel__=null;var $tr_addr;var $control_addr;var $plist_addr;var $phdata_addr;var $ph;var $prog=__stackBase__;var $instn;var $instn2;var $or_flag;var $truth;var $data;var $end_flag;var $ix;var $param_sc;var $n_return;var $return_addr=__stackBase__+4;$tr_addr=$tr;$control_addr=$control;$plist_addr=$plist;$phdata_addr=$phdata;$n_return=0;var $0=$plist_addr;var $ph1=(($0+8)&4294967295);var $1=HEAP32[(($ph1)>>2)];$ph=$1;var $2=$phdata_addr;var $3=$2;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$3;$stop$=$dest$+152;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $4=$ph;var $std_length=(($4+14)&4294967295);var $5=HEAPU8[($std_length)];var $conv=((($5))&255);var $6=$phdata_addr;var $pd_param=(($6+4)&4294967295);var $arrayidx=(($pd_param+40)&4294967295);HEAP32[(($arrayidx)>>2)]=$conv;var $7=$ph;var $length_mod=(($7+15)&4294967295);var $8=HEAPU8[($length_mod)];var $conv2=((($8))&255);var $9=$phdata_addr;var $pd_param3=(($9+4)&4294967295);var $arrayidx4=(($pd_param3+36)&4294967295);HEAP32[(($arrayidx4)>>2)]=$conv2;var $10=$ph;var $program=(($10+8)&4294967295);var $11=HEAPU16[(($program)>>1)];var $conv5=((($11))&65535);var $cmp=((($conv5))|0)==0;if($cmp){__label__=69;;}else{__label__=1;;}
$for_end237$$if_end$2:do{if(__label__==1){$end_flag=0;var $12=$ph;var $program6=(($12+8)&4294967295);var $13=HEAPU16[(($program6)>>1)];var $idxprom=((($13))&65535);var $14=HEAP32[((_phoneme_index)>>2)];var $arrayidx7=(($14+2*$idxprom)&4294967295);HEAP32[(($prog)>>2)]=$arrayidx7;var $15=$end_flag;var $cmp89=((($15))|0)!=1;if(!($cmp89)){__label__=69;break $for_end237$$if_end$2;}
$for_body$4:while(1){var $16=HEAP32[(($prog)>>2)];var $17=HEAP16[(($16)>>1)];$instn=$17;var $18=$instn;var $conv9=((($18))&65535);var $shr=($conv9)>>8;var $and=($shr)&15;$instn2=$and;$or_flag=0;var $19=$instn;var $conv10=((($19))&65535);var $shr11=($conv10)>>12;if($shr11==0){__label__=3;;}
else if($shr11==1){__label__=21;;}
else if($shr11==2){__label__=25;;}
else if($shr11==3){__label__=25;;}
else if($shr11==6){__label__=40;;}
else if($shr11==9){__label__=44;;}
else if($shr11==10){__label__=49;;}
else if($shr11==11){__label__=53;;}
else if($shr11==12){__label__=53;;}
else if($shr11==13){__label__=53;;}
else if($shr11==14){__label__=53;;}
else if($shr11==15){__label__=53;;}
else{__label__=61;;}
$sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6:do{if(__label__==61){var $153=$ph;var $154=$instn;var $conv222=((($154))&65535);__ZL12InvalidInstnP11PHONEME_TABi($153,$conv222);;}
else if(__label__==3){var $20=$instn;var $conv12=((($20))&65535);var $and13=($conv12)&255;$data=$and13;var $21=$instn2;var $cmp14=((($21))|0)==0;if($cmp14){__label__=4;;}else{__label__=7;;}
if(__label__==4){var $22=$data;if($22==1){__label__=5;;}
else if($22==2){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
else{__label__=6;;}
if(__label__==6){var $23=$ph;var $24=$instn;var $conv17=((($24))&65535);__ZL12InvalidInstnP11PHONEME_TABi($23,$conv17);;}
else if(__label__==5){$end_flag=1;;}}
else if(__label__==7){var $25=$instn2;var $cmp18=((($25))|0)==5;if($cmp18){__label__=8;;}else{__label__=10;;}
if(__label__==8){var $26=$plist_addr;var $arrayidx20=(($26+24)&4294967295);var $phcode=(($arrayidx20)&4294967295);var $27=HEAPU8[($phcode)];var $idxprom21=((($27))&255);var $arrayidx22=((_phoneme_tab+$idxprom21*4)&4294967295);var $28=HEAP32[(($arrayidx22)>>2)];var $type=(($28+11)&4294967295);var $29=HEAPU8[($type)];var $conv23=((($29))&255);var $cmp24=((($conv23))|0)==2;if(!($cmp24)){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
var $30=$data;var $31=$phdata_addr;var $pd_param26=(($31+4)&4294967295);var $arrayidx27=(($pd_param26+16)&4294967295);HEAP32[(($arrayidx27)>>2)]=$30;;}
else if(__label__==10){var $32=$instn2;var $cmp30=((($32))|0)==13;if($cmp30){__label__=11;;}else{__label__=14;;}
if(__label__==11){$ix=0;var $33=$ix;var $34=$data;var $cmp333=((($33))|0)<((($34))|0);var $35=$ix;var $cmp344=((($35))|0)<16;var $or_cond15=($cmp333)&($cmp344);if($or_cond15){__label__=12;;}else{__label__=13;;}
$for_body35$$for_end$21:do{if(__label__==12){while(1){var $36=HEAP32[(($prog)>>2)];var $incdec_ptr=(($36+2)&4294967295);HEAP32[(($prog)>>2)]=$incdec_ptr;var $37=HEAP32[(($prog)>>2)];var $arrayidx36=(($37)&4294967295);var $38=HEAPU16[(($arrayidx36)>>1)];var $conv37=((($38))&65535);var $shr38=($conv37)>>8;var $conv39=((($shr38))&255);var $39=$ix;var $40=$phdata_addr;var $ipa_string=(($40+132)&4294967295);var $arrayidx40=(($ipa_string+$39)&4294967295);HEAP8[($arrayidx40)]=$conv39;var $41=HEAP32[(($prog)>>2)];var $arrayidx41=(($41)&4294967295);var $42=HEAPU16[(($arrayidx41)>>1)];var $conv42=((($42))&65535);var $and43=($conv42)&255;var $conv44=((($and43))&255);var $43=$ix;var $add=((($43)+1)&4294967295);var $44=$phdata_addr;var $ipa_string45=(($44+132)&4294967295);var $arrayidx46=(($ipa_string45+$add)&4294967295);HEAP8[($arrayidx46)]=$conv44;var $45=$ix;var $add47=((($45)+2)&4294967295);$ix=$add47;var $46=$ix;var $47=$data;var $cmp33=((($46))|0)<((($47))|0);var $48=$ix;var $cmp34=((($48))|0)<16;var $or_cond1=($cmp33)&($cmp34);if($or_cond1){__label__=12;continue;}else{__label__=13;break $for_body35$$for_end$21;}}}}while(0);var $49=$ix;var $50=$phdata_addr;var $ipa_string48=(($50+132)&4294967295);var $arrayidx49=(($ipa_string48+$49)&4294967295);HEAP8[($arrayidx49)]=0;;}
else if(__label__==14){var $51=$instn2;var $cmp51=((($51))|0)<16;if($cmp51){__label__=15;;}else{__label__=20;;}
if(__label__==15){var $52=$instn2;var $cmp53=((($52))|0)==12;if($cmp53){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $53=$data;var $54=$phdata_addr;var $pd_param55=(($54+4)&4294967295);var $arrayidx56=(($pd_param55+4)&4294967295);HEAP32[(($arrayidx56)>>2)]=$53;;}
var $55=$data;var $56=$instn2;var $57=$phdata_addr;var $pd_param58=(($57+4)&4294967295);var $arrayidx59=(($pd_param58+$56*4)&4294967295);HEAP32[(($arrayidx59)>>2)]=$55;var $58=$instn2;var $cmp60=((($58))|0)==1;if(!($cmp60)){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
var $59=$control_addr;var $and61=($59)&256;var $tobool=((($and61))|0)!=0;if(!($tobool)){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
$end_flag=1;;}
else if(__label__==20){var $60=$ph;var $61=$instn;var $conv65=((($61))&65535);__ZL12InvalidInstnP11PHONEME_TABi($60,$conv65);;}}}}}
else if(__label__==21){var $62=$tr_addr;var $cmp71=((($62))|0)==0;if($cmp71){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
var $63=$instn2;var $cmp74=((($63))|0)<8;if(!($cmp74)){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
var $64=$tr_addr;var $65=$plist_addr;var $66=$instn2;var $and76=($66)&7;var $call=__ZL15StressConditionP10TranslatorP12PHONEME_LISTii($64,$65,$and76,1);if(!($call)){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
var $67=$instn;var $conv78=((($67))&65535);var $and79=($conv78)&255;var $68=$phdata_addr;var $pd_param80=(($68+4)&4294967295);var $arrayidx81=(($pd_param80+4)&4294967295);HEAP32[(($arrayidx81)>>2)]=$and79;$end_flag=1;;}
else if(__label__==25){$or_flag=0;$truth=1;var $69=$instn;var $conv856=((($69))&65535);var $and867=($conv856)&57344;var $cmp878=((($and867))|0)==8192;if($cmp878){__label__=26;;}else{__label__=34;;}
$while_body$$while_end$39:do{if(__label__==26){while(1){var $70=$or_flag;var $tobool88=((($70))|0)!=0;var $71=$truth;var $tobool90=((($71))&1);if($tobool88){__label__=27;;}else{__label__=30;;}
if(__label__==27){if($tobool90){__lastLabel__=27;__label__=29;;}else{__lastLabel__=27;__label__=28;;}
if(__label__==28){var $72=$tr_addr;var $73=$control_addr;var $74=$plist_addr;var $75=$instn;var $conv91=((($75))&65535);var $and92=($conv91)&4095;var $call93=__ZL18InterpretConditionP10TranslatoriP12PHONEME_LISTi($72,$73,$74,$and92);__lastLabel__=28;;}
var $76=__lastLabel__==27?1:($call93);var $frombool=((($76))&1);$truth=$frombool;;}
else if(__label__==30){if($tobool90){__lastLabel__=30;__label__=31;;}else{__lastLabel__=30;__label__=32;;}
if(__label__==31){var $77=$tr_addr;var $78=$control_addr;var $79=$plist_addr;var $80=$instn;var $conv97=((($80))&65535);var $and98=($conv97)&4095;var $call99=__ZL18InterpretConditionP10TranslatoriP12PHONEME_LISTi($77,$78,$79,$and98);__lastLabel__=31;;}
var $81=__lastLabel__==30?0:($call99);var $frombool101=((($81))&1);$truth=$frombool101;;}
var $82=$instn;var $conv103=((($82))&65535);var $and104=($conv103)&4096;$or_flag=$and104;var $83=HEAP32[(($prog)>>2)];var $incdec_ptr105=(($83+2)&4294967295);HEAP32[(($prog)>>2)]=$incdec_ptr105;var $84=HEAP16[(($incdec_ptr105)>>1)];$instn=$84;var $85=$instn;var $conv85=((($85))&65535);var $and86=($conv85)&57344;var $cmp87=((($and86))|0)==8192;if($cmp87){__label__=26;continue;}else{__label__=34;break $while_body$$while_end$39;}}}}while(0);var $86=$truth;var $tobool106=((($86))&1);var $conv107=((($tobool106))&1);var $cmp108=((($conv107))|0)==0;if($cmp108){__label__=35;;}else{__label__=39;;}
$if_then109$$if_end127$53:do{if(__label__==35){var $87=$instn;var $conv110=((($87))&65535);var $and111=($conv110)&63488;var $cmp112=((($and111))|0)==26624;if($cmp112){__label__=36;;}else{__label__=37;;}
if(__label__==36){var $88=$instn;var $conv114=((($88))&65535);var $and115=($conv114)&255;var $89=HEAP32[(($prog)>>2)];var $add_ptr=(($89+2*$and115)&4294967295);HEAP32[(($prog)>>2)]=$add_ptr;;}
else if(__label__==37){var $90=HEAP32[(($prog)>>2)];var $call117=__ZL13NumInstnWordsPt($90);var $91=HEAP32[(($prog)>>2)];var $add_ptr118=(($91+2*$call117)&4294967295);HEAP32[(($prog)>>2)]=$add_ptr118;var $92=HEAP32[(($prog)>>2)];var $arrayidx119=(($92)&4294967295);var $93=HEAPU16[(($arrayidx119)>>1)];var $conv120=((($93))&65535);var $and121=($conv120)&65024;var $cmp122=((($and121))|0)==24576;if(!($cmp122)){__label__=39;break $if_then109$$if_end127$53;}
var $94=HEAP32[(($prog)>>2)];var $incdec_ptr124=(($94+2)&4294967295);HEAP32[(($prog)>>2)]=$incdec_ptr124;;}}}while(0);var $95=HEAP32[(($prog)>>2)];var $incdec_ptr128=(($95+-2)&4294967295);HEAP32[(($prog)>>2)]=$incdec_ptr128;;}
else if(__label__==40){var $96=$instn2;var $shr130=($96)>>1;if($shr130==0){__label__=41;;}
else if($shr130==6){__label__=43;;}
else if($shr130==5){__label__=42;;}
else{__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
if(__label__==41){var $97=$instn;var $conv132=((($97))&65535);var $and133=($conv132)&255;var $sub=((($and133)-1)&4294967295);var $98=HEAP32[(($prog)>>2)];var $add_ptr134=(($98+2*$sub)&4294967295);HEAP32[(($prog)>>2)]=$add_ptr134;;}
else if(__label__==43){var $101=$plist_addr;var $102=$phdata_addr;__ZL15SwitchVowelTypeP12PHONEME_LISTP12PHONEME_DATAPPti($101,$102,$prog,3);;}
else if(__label__==42){var $99=$plist_addr;var $100=$phdata_addr;__ZL15SwitchVowelTypeP12PHONEME_LISTP12PHONEME_DATAPPti($99,$100,$prog,2);;}}
else if(__label__==44){var $103=$instn;var $conv139=((($103))&65535);var $and140=($conv139)&15;var $shl=((($and140)*65536)&4294967295);var $104=HEAP32[(($prog)>>2)];var $arrayidx141=(($104+2)&4294967295);var $105=HEAPU16[(($arrayidx141)>>1)];var $conv142=((($105))&65535);var $add143=((($shl)+($conv142))&4294967295);$data=$add143;var $106=HEAP32[(($prog)>>2)];var $incdec_ptr144=(($106+2)&4294967295);HEAP32[(($prog)>>2)]=$incdec_ptr144;var $107=$instn2;if($107==1){__label__=45;;}
else if($107==2){__label__=47;;}
else if($107==3){__label__=48;;}
else{__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
if(__label__==45){var $108=$n_return;var $cmp146=((($108))|0)<10;if(!($cmp146)){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
var $109=HEAP32[(($prog)>>2)];var $110=$n_return;var $inc=((($110)+1)&4294967295);$n_return=$inc;var $arrayidx148=(($return_addr+$110*4)&4294967295);HEAP32[(($arrayidx148)>>2)]=$109;var $111=$data;var $112=HEAP32[((_phoneme_index)>>2)];var $arrayidx149=(($112+2*$111)&4294967295);var $add_ptr150=(($arrayidx149+-2)&4294967295);HEAP32[(($prog)>>2)]=$add_ptr150;;}
else if(__label__==47){var $113=$data;var $114=$phdata_addr;var $pitch_env=(($114+124)&4294967295);HEAP32[(($pitch_env)>>2)]=$113;;}
else if(__label__==48){var $115=$data;var $116=$phdata_addr;var $amp_env=(($116+128)&4294967295);HEAP32[(($amp_env)>>2)]=$115;;}}
else if(__label__==49){var $117=$instn2;var $cmp156=((($117))|0)==1;if($cmp156){__label__=50;;}else{__label__=51;;}
if(__label__==50){$ix=0;;}
else if(__label__==51){$ix=2;;}
var $118=HEAP32[(($prog)>>2)];var $arrayidx160=(($118)&4294967295);var $119=HEAPU16[(($arrayidx160)>>1)];var $conv161=((($119))&65535);var $and162=($conv161)&255;var $shl163=((($and162)*65536)&4294967295);var $120=HEAP32[(($prog)>>2)];var $arrayidx164=(($120+2)&4294967295);var $121=HEAPU16[(($arrayidx164)>>1)];var $conv165=((($121))&65535);var $add166=((($shl163)+($conv165))&4294967295);var $122=$ix;var $123=$phdata_addr;var $vowel_transition=(($123+108)&4294967295);var $arrayidx167=(($vowel_transition+$122*4)&4294967295);HEAP32[(($arrayidx167)>>2)]=$add166;var $124=HEAP32[(($prog)>>2)];var $arrayidx168=(($124+4)&4294967295);var $125=HEAPU16[(($arrayidx168)>>1)];var $conv169=((($125))&65535);var $shl170=((($conv169)*65536)&4294967295);var $126=HEAP32[(($prog)>>2)];var $arrayidx171=(($126+6)&4294967295);var $127=HEAPU16[(($arrayidx171)>>1)];var $conv172=((($127))&65535);var $add173=((($conv172)+($shl170))&4294967295);var $128=$ix;var $add174=((($128)+1)&4294967295);var $129=$phdata_addr;var $vowel_transition175=(($129+108)&4294967295);var $arrayidx176=(($vowel_transition175+$add174*4)&4294967295);HEAP32[(($arrayidx176)>>2)]=$add173;var $130=HEAP32[(($prog)>>2)];var $add_ptr177=(($130+6)&4294967295);HEAP32[(($prog)>>2)]=$add_ptr177;;}
else if(__label__==53){var $131=$instn;var $conv179=((($131))&65535);var $shr180=($conv179)>>12;var $sub181=((($shr180)-11)&4294967295);$instn2=$sub181;var $132=$instn;var $conv182=((($132))&65535);var $and183=($conv182)&15;var $shl184=((($and183)*262144)&4294967295);var $133=HEAP32[(($prog)>>2)];var $arrayidx185=(($133+2)&4294967295);var $134=HEAPU16[(($arrayidx185)>>1)];var $conv186=((($134))&65535);var $shl187=((($conv186)*4)&4294967295);var $add188=((($shl187)+($shl184))&4294967295);var $135=$instn2;var $136=$phdata_addr;var $sound_addr=(($136+68)&4294967295);var $arrayidx189=(($sound_addr+$135*4)&4294967295);HEAP32[(($arrayidx189)>>2)]=$add188;var $137=$instn;var $conv190=((($137))&65535);var $shr191=($conv190)>>4;var $and192=($shr191)&255;var $138=$instn2;var $139=$phdata_addr;var $sound_param=(($139+88)&4294967295);var $arrayidx193=(($sound_param+$138*4)&4294967295);HEAP32[(($arrayidx193)>>2)]=$and192;var $conv194=((($and192))&255);$param_sc=$conv194;var $140=HEAP32[(($prog)>>2)];var $incdec_ptr195=(($140+2)&4294967295);HEAP32[(($prog)>>2)]=$incdec_ptr195;var $141=HEAP32[(($prog)>>2)];var $arrayidx196=(($141+2)&4294967295);var $142=HEAPU16[(($arrayidx196)>>1)];var $conv197=((($142))&65535);var $cmp198=((($conv197))|0)!=2;if(!($cmp198)){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
var $143=$instn2;var $cmp200=((($143))|0)<2;if($cmp200){__label__=55;;}else{__label__=57;;}
$if_then201$$if_else208$78:do{if(__label__==55){$end_flag=1;var $144=HEAP32[(($prog)>>2)];var $arrayidx202=(($144+2)&4294967295);var $145=HEAPU16[(($arrayidx202)>>1)];var $conv203=((($145))&65535);var $shr204=($conv203)>>12;var $cmp205=((($shr204))|0)==15;if(!($cmp205)){__label__=59;break $if_then201$$if_else208$78;}
$end_flag=2;;}
else if(__label__==57){var $146=$instn2;var $cmp209=((($146))|0)==4;if(!($cmp209)){__label__=59;break $if_then201$$if_else208$78;}
var $147=$end_flag;var $dec=((($147)-1)&4294967295);$end_flag=$dec;;}}while(0);var $148=$instn2;var $cmp213=((($148))|0)==2;var $149=$instn2;var $cmp214=((($149))|0)==3;var $or_cond=($cmp213)|($cmp214);if(!($or_cond)){__label__=62;break $sw_default221$$sw_bb$$sw_bb70$$sw_bb84$$sw_bb129$$sw_bb138$$sw_bb155$$sw_bb178$6;}
var $150=$param_sc;var $conv216=(tempInt=(($150)),(tempInt>=128?tempInt-256:tempInt));var $151=$instn2;var $152=$phdata_addr;var $sound_param217=(($152+88)&4294967295);var $arrayidx218=(($sound_param217+$151*4)&4294967295);HEAP32[(($arrayidx218)>>2)]=$conv216;;}}while(0);var $155=$ph;var $phflags=(($155+4)&4294967295);var $156=HEAP32[(($phflags)>>2)];var $and224=($156)&4096;var $tobool225=((($and224))|0)!=0;if($tobool225){__label__=63;;}else{__label__=64;;}
$if_end227_thread$$if_end227$86:do{if(__label__==63){$end_flag=1;;}
else if(__label__==64){var $_pr=$end_flag;var $cmp228=((($_pr))|0)==1;if($cmp228){__label__=66;break $if_end227_thread$$if_end227$86;}
var $157=HEAP32[(($prog)>>2)];var $incdec_ptr23611=(($157+2)&4294967295);HEAP32[(($prog)>>2)]=$incdec_ptr23611;__label__=2;continue $for_body$4;}}while(0);var $158=$n_return;var $cmp230=((($158))|0)>0;if($cmp230){__label__=67;;}else{__label__=68;;}
if(__label__==67){$end_flag=0;var $159=$n_return;var $dec232=((($159)-1)&4294967295);$n_return=$dec232;var $arrayidx233=(($return_addr+$dec232*4)&4294967295);var $160=HEAP32[(($arrayidx233)>>2)];HEAP32[(($prog)>>2)]=$160;;}
var $_pr10=$end_flag;var $161=HEAP32[(($prog)>>2)];var $incdec_ptr236=(($161+2)&4294967295);HEAP32[(($prog)>>2)]=$incdec_ptr236;var $cmp8=((($_pr10))|0)!=1;if($cmp8){__label__=2;continue $for_body$4;}else{__label__=69;break $for_end237$$if_end$2;}}}}while(0);STACKTOP=__stackBase__;return;return;}
function __ZL12InvalidInstnP11PHONEME_TABi($ph,$instn){;var __label__;var $ph_addr;var $instn_addr;$ph_addr=$ph;$instn_addr=$instn;var $0=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($0+12)&4294967295);var $1=HEAP32[(($_stderr)>>2)];var $2=$instn_addr;var $3=$ph_addr;var $mnemonic=(($3)&4294967295);var $4=HEAP32[(($mnemonic)>>2)];var $call=__Z12WordToStringj($4);var $call1=_fprintf($1,((__str17428)&4294967295),allocate([$2,0,0,0,((__ZZ12WordToStringjE3buf)&4294967295),0,0,0],["i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));;return;return;}
function __ZL15StressConditionP10TranslatorP12PHONEME_LISTii($tr,$plist,$condition,$control){;var __label__;var $retval;var $tr_addr;var $plist_addr;var $condition_addr;var $control_addr;var $stress_level;var $pl;$tr_addr=$tr;$plist_addr=$plist;$condition_addr=$condition;$control_addr=$control;var $0=$plist_addr;var $arrayidx=(($0)&4294967295);var $phcode=(($arrayidx)&4294967295);var $1=HEAPU8[($phcode)];var $idxprom=((($1))&255);var $arrayidx1=((_phoneme_tab+$idxprom*4)&4294967295);var $2=HEAP32[(($arrayidx1)>>2)];var $type=(($2+11)&4294967295);var $3=HEAPU8[($type)];var $conv=((($3))&255);var $cmp=((($conv))|0)==2;var $4=$plist_addr;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_else$2:do{if(__label__==1){$pl=$4;__label__=5;break $if_then$$if_else$2;}
else if(__label__==2){var $arrayidx2=(($4+24)&4294967295);var $phcode3=(($arrayidx2)&4294967295);var $5=HEAPU8[($phcode3)];var $idxprom4=((($5))&255);var $arrayidx5=((_phoneme_tab+$idxprom4*4)&4294967295);var $6=HEAP32[(($arrayidx5)>>2)];var $type6=(($6+11)&4294967295);var $7=HEAPU8[($type6)];var $conv7=((($7))&255);var $cmp8=((($conv7))|0)==2;if($cmp8){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $8=$plist_addr;var $arrayidx10=(($8+24)&4294967295);$pl=$arrayidx10;__label__=5;break $if_then$$if_else$2;}
else if(__label__==4){$retval=0;__label__=21;break $if_then$$if_else$2;}}}while(0);$if_end12$$return$8:do{if(__label__==5){var $9=$pl;var $stresslevel=(($9+1)&4294967295);var $10=HEAPU8[($stresslevel)];var $conv13=((($10))&255);var $and=($conv13)&15;$stress_level=$and;var $11=$tr_addr;var $cmp14=((($11))|0)!=0;if($cmp14){__label__=6;;}else{__label__=13;;}
$if_then15$$if_end36$10:do{if(__label__==6){var $12=$control_addr;var $and16=($12)&1;var $tobool=((($and16))|0)!=0;if($tobool){__label__=7;;}else{__label__=10;;}
$land_lhs_true$$if_end25$12:do{if(__label__==7){var $13=$plist_addr;var $synthflags=(($13+4)&4294967295);var $14=HEAPU16[(($synthflags)>>1)];var $conv17=((($14))&65535);var $and18=($conv17)&16;var $tobool19=((($and18))|0)!=0;if(!($tobool19)){__label__=10;break $land_lhs_true$$if_end25$12;}
var $15=$tr_addr;var $langopts=(($15)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx21=(($param+40)&4294967295);var $16=HEAP32[(($arrayidx21)>>2)];var $and22=($16)&1;var $cmp23=((($and22))|0)==0;if(!($cmp23)){__label__=10;break $land_lhs_true$$if_end25$12;}
$retval=0;__label__=21;break $if_end12$$return$8;}}while(0);var $17=$tr_addr;var $langopts26=(($17)&4294967295);var $param27=(($langopts26+24)&4294967295);var $arrayidx28=(($param27+40)&4294967295);var $18=HEAP32[(($arrayidx28)>>2)];var $and29=($18)&2;var $tobool30=((($and29))|0)!=0;if(!($tobool30)){__label__=13;break $if_then15$$if_end36$10;}
var $19=$stress_level;var $20=$pl;var $wordstress=(($20+2)&4294967295);var $21=HEAPU8[($wordstress)];var $conv32=((($21))&255);var $cmp33=((($19))|0)>=((($conv32))|0);if(!($cmp33)){__label__=13;break $if_then15$$if_end36$10;}
$stress_level=4;;}}while(0);var $22=$condition_addr;var $cmp37=((($22))|0)==4;if($cmp37){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $23=$stress_level;var $24=$pl;var $wordstress39=(($24+2)&4294967295);var $25=HEAPU8[($wordstress39)];var $conv40=((($25))&255);var $cmp41=((($23))|0)>=((($conv40))|0);$retval=$cmp41;;}
else if(__label__==15){var $26=$condition_addr;var $cmp43=((($26))|0)==3;var $27=$stress_level;if($cmp43){__label__=16;;}else{__label__=18;;}
$if_then44$$if_else48$23:do{if(__label__==16){var $cmp45=((($27))|0)>3;if(!($cmp45)){__label__=20;break $if_then44$$if_else48$23;}
$retval=1;__label__=21;break $if_end12$$return$8;}
else if(__label__==18){var $28=$condition_addr;var $arrayidx49=((__ZZL15StressConditionP10TranslatorP12PHONEME_LISTiiE15condition_level+$28*4)&4294967295);var $29=HEAP32[(($arrayidx49)>>2)];var $cmp50=((($27))|0)<((($29))|0);if(!($cmp50)){__label__=20;break $if_then44$$if_else48$23;}
$retval=1;__label__=21;break $if_end12$$return$8;}}while(0);$retval=0;;}}}while(0);var $30=$retval;;return $30;return null;}
function __ZL18InterpretConditionP10TranslatoriP12PHONEME_LISTi($tr,$control,$plist,$instn){;var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $control_addr;var $plist_addr;var $instn_addr;var $which;var $data;var $instn2;var $count;var $ph;var $plist_this;$tr_addr=$tr;$control_addr=$control;$plist_addr=$plist;$instn_addr=$instn;var $0=$instn_addr;var $and=($0)&255;$data=$and;var $1=$instn_addr;var $shr=($1)>>8;$instn2=$shr;var $2=$instn2;var $cmp=((($2))|0)<14;var $3=$instn2;if($cmp){__label__=1;;}else{__label__=67;;}
$if_then$$if_else187$2:do{if(__label__==1){var $rem=((($3))|0)%7;$which=$rem;var $4=$which;var $cmp1=((($4))|0)==4;if($cmp1){__lastLabel__=1;__label__=2;;}else{__lastLabel__=1;__label__=5;;}
if(__label__==2){var $5=$plist_addr;var $arrayidx=(($5+24)&4294967295);var $sourceix=(($arrayidx+6)&4294967295);var $6=HEAP16[(($sourceix)>>1)];var $tobool=(tempInt=(($6)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if($tobool){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=0;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==4){var $_pr=$which;__lastLabel__=4;;}}
var $7=__lastLabel__==4?$_pr:($4);var $cmp5=((($7))|0)==5;if($cmp5){__label__=6;;}else{__label__=8;;}
$if_then6$$if_end12$10:do{if(__label__==6){var $8=$plist_addr;var $arrayidx7=(($8)&4294967295);var $sourceix8=(($arrayidx7+6)&4294967295);var $9=HEAP16[(($sourceix8)>>1)];var $tobool9=(tempInt=(($9)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if(!($tobool9)){__label__=8;break $if_then6$$if_end12$10;}
$retval=0;__label__=73;break $if_then$$if_else187$2;}}while(0);var $10=$which;var $cmp13=((($10))|0)==7;if($cmp13){__lastLabel__=8;__label__=9;;}else{__lastLabel__=8;__label__=13;;}
$if_then14$$if_end23$14:do{if(__label__==9){var $11=$plist_addr;var $arrayidx15=(($11+24)&4294967295);var $sourceix16=(($arrayidx15+6)&4294967295);var $12=HEAP16[(($sourceix16)>>1)];var $tobool17=(tempInt=(($12)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if($tobool17){__label__=11;;}else{__label__=10;;}
$if_then21$$lor_lhs_false$16:do{if(__label__==10){var $13=$plist_addr;var $arrayidx18=(($13+48)&4294967295);var $sourceix19=(($arrayidx18+6)&4294967295);var $14=HEAP16[(($sourceix19)>>1)];var $tobool20=(tempInt=(($14)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if($tobool20){__label__=11;break $if_then21$$lor_lhs_false$16;}
var $_pr1=$which;__lastLabel__=12;__label__=13;break $if_then14$$if_end23$14;}}while(0);$retval=0;__label__=73;break $if_then$$if_else187$2;}}while(0);var $15=__lastLabel__==12?$_pr1:($10);var $cmp24=((($15))|0)==6;if($cmp24){__label__=14;;}else{__label__=19;;}
$if_then25$$if_else$21:do{if(__label__==14){$which=2;;while(1){var $16=$which;var $sub=((($16)-1)&4294967295);var $17=$plist_addr;var $arrayidx26=(($17+24*$sub)&4294967295);var $sourceix27=(($arrayidx26+6)&4294967295);var $18=HEAP16[(($sourceix27)>>1)];var $tobool28=(tempInt=(($18)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if($tobool28){__label__=16;break;}
var $19=$which;var $sub31=((($19)-1)&4294967295);var $20=$plist_addr;var $arrayidx32=(($20+24*$sub31)&4294967295);var $phcode=(($arrayidx32)&4294967295);var $21=HEAPU8[($phcode)];var $idxprom=((($21))&255);var $arrayidx33=((_phoneme_tab+$idxprom*4)&4294967295);var $22=HEAP32[(($arrayidx33)>>2)];var $type=(($22+11)&4294967295);var $23=HEAPU8[($type)];var $conv=((($23))&255);var $cmp34=((($conv))|0)==2;var $_pr2=$which;if($cmp34){__lastLabel__=17;__label__=20;break $if_then25$$if_else$21;}else{__lastLabel__=17;;}
var $inc=((($_pr2)+1)&4294967295);$which=$inc;__label__=15;continue;}
$retval=0;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==19){var $24=$which;var $arrayidx37=((__ZZL18InterpretConditionP10TranslatoriP12PHONEME_LISTiE11ph_position+$24*4)&4294967295);var $25=HEAP32[(($arrayidx37)>>2)];$which=$25;__lastLabel__=19;;}}while(0);var $26=__lastLabel__==19?$25:($_pr2);var $27=$plist_addr;$plist_this=$27;var $sub39=((($26)-1)&4294967295);var $28=$plist_addr;var $arrayidx40=(($28+24*$sub39)&4294967295);$plist_addr=$arrayidx40;var $cmp41=((($26))|0)==0;if($cmp41){__label__=21;;}else{__label__=23;;}
$if_then42$$if_end49$30:do{if(__label__==21){var $29=$plist_addr;var $phcode43=(($29)&4294967295);var $30=HEAPU8[($phcode43)];var $conv44=((($30))&255);var $cmp45=((($conv44))|0)==1;if(!($cmp45)){__label__=23;break $if_then42$$if_end49$30;}
var $31=$plist_addr;var $arrayidx47=(($31+-24)&4294967295);$plist_addr=$arrayidx47;;}}while(0);var $32=$control_addr;var $and50=($32)&256;var $tobool51=((($and50))|0)!=0;if($tobool51){__label__=24;;}else{__label__=25;;}
if(__label__==24){var $33=$plist_addr;var $phcode53=(($33)&4294967295);var $34=HEAPU8[($phcode53)];var $idxprom54=((($34))&255);var $arrayidx55=((_phoneme_tab+$idxprom54*4)&4294967295);var $35=HEAP32[(($arrayidx55)>>2)];var $36=$plist_addr;var $ph56=(($36+8)&4294967295);HEAP32[(($ph56)>>2)]=$35;;}
var $37=$plist_addr;var $ph58=(($37+8)&4294967295);var $38=HEAP32[(($ph58)>>2)];$ph=$38;var $39=$instn2;var $cmp59=((($39))|0)<7;if($cmp59){__label__=26;;}else{__label__=32;;}
if(__label__==26){var $40=$data;var $arrayidx61=((_phoneme_tab+$40*4)&4294967295);var $41=HEAP32[(($arrayidx61)>>2)];var $mnemonic=(($41)&4294967295);var $42=HEAP32[(($mnemonic)>>2)];var $43=$ph;var $mnemonic62=(($43)&4294967295);var $44=HEAP32[(($mnemonic62)>>2)];var $cmp63=((($42))|0)==((($44))|0);var $conv64=((($cmp63))&1);var $cmp65=((($conv64))|0)==1;if($cmp65){__label__=27;;}else{__label__=28;;}
if(__label__==27){$retval=1;;}
else if(__label__==28){var $45=$which;var $cmp68=((($45))|0)==0;if($cmp68){__label__=29;;}else{__label__=31;;}
$land_lhs_true$$if_end75$42:do{if(__label__==29){var $46=$ph;var $type69=(($46+11)&4294967295);var $47=HEAPU8[($type69)];var $conv70=((($47))&255);var $cmp71=((($conv70))|0)==2;if(!($cmp71)){__label__=31;break $land_lhs_true$$if_end75$42;}
var $48=$data;var $49=$ph;var $end_type=(($49+13)&4294967295);var $50=HEAPU8[($end_type)];var $conv73=((($50))&255);var $cmp74=((($48))|0)==((($conv73))|0);$retval=$cmp74;__label__=73;break $if_then$$if_else187$2;}}while(0);var $51=$data;var $52=$ph;var $start_type=(($52+12)&4294967295);var $53=HEAPU8[($start_type)];var $conv76=((($53))&255);var $cmp77=((($51))|0)==((($conv76))|0);$retval=$cmp77;;}}
else if(__label__==32){var $54=$instn_addr;var $and79=($54)&31;$data=$and79;var $55=$instn_addr;var $and80=($55)&224;if($and80==0){__label__=33;;}
else if($and80==32){__label__=34;;}
else if($and80==64){__label__=35;;}
else if($and80==128){__label__=36;;}
else{__label__=66;;}
if(__label__==66){$retval=0;;}
else if(__label__==33){var $56=$ph;var $type81=(($56+11)&4294967295);var $57=HEAPU8[($type81)];var $conv82=((($57))&255);var $58=$data;var $cmp83=((($conv82))|0)==((($58))|0);$retval=$cmp83;;}
else if(__label__==34){var $59=$ph;var $phflags=(($59+4)&4294967295);var $60=HEAPU32[(($phflags)>>2)];var $shr85=($60)>>>16;var $and86=($shr85)&15;var $61=$data;var $cmp87=((($and86))|0)==((($61))|0);$retval=$cmp87;;}
else if(__label__==35){var $62=$ph;var $phflags89=(($62+4)&4294967295);var $63=HEAP32[(($phflags89)>>2)];var $64=$data;var $shl=1<<($64);var $and90=($shl)&($63);var $cmp91=((($and90))|0)!=0;$retval=$cmp91;;}
else if(__label__==36){var $65=$data;if($65==0){__label__=37;;}
else if($65==1){__label__=37;;}
else if($65==2){__label__=37;;}
else if($65==3){__label__=37;;}
else if($65==4){__label__=37;;}
else if($65==5){__label__=38;;}
else if($65==6){__label__=41;;}
else if($65==7){__label__=42;;}
else if($65==8){__label__=43;;}
else if($65==9){__label__=46;;}
else if($65==10){__label__=51;;}
else if($65==11){__label__=52;;}
else if($65==12){__label__=56;;}
else{__label__=60;;}
$sw_bb169$$sw_bb93$$sw_bb94$$sw_bb101$$sw_bb105$$sw_bb109$$sw_bb120$$sw_bb134$$for_cond139$$sw_bb156$53:do{if(__label__==37){var $66=$tr_addr;var $67=$plist_addr;var $68=$data;var $call=__ZL15StressConditionP10TranslatorP12PHONEME_LISTii($66,$67,$68,0);$retval=$call;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==38){var $69=$ph;var $type95=(($69+11)&4294967295);var $70=HEAPU8[($type95)];var $conv96=((($70))&255);var $cmp97=((($conv96))|0)==0;if($cmp97){__lastLabel__=38;__label__=40;;}else{__lastLabel__=38;__label__=39;;}
if(__label__==39){var $71=$plist_this;var $synthflags=(($71+4)&4294967295);var $72=HEAPU16[(($synthflags)>>1)];var $conv98=((($72))&65535);var $and99=($conv98)&8192;var $tobool100=((($and99))|0)!=0;__lastLabel__=39;;}
var $73=__lastLabel__==38?1:($tobool100);$retval=$73;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==41){var $74=$plist_addr;var $sourceix102=(($74+6)&4294967295);var $75=HEAPU16[(($sourceix102)>>1)];var $conv103=((($75))&65535);var $cmp104=((($conv103))|0)!=0;$retval=$cmp104;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==42){var $76=$plist_addr;var $sourceix106=(($76+6)&4294967295);var $77=HEAPU16[(($sourceix106)>>1)];var $conv107=((($77))&65535);var $cmp108=((($conv107))|0)==0;$retval=$cmp108;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==43){var $78=$plist_addr;var $arrayidx110=(($78+24)&4294967295);var $sourceix111=(($arrayidx110+6)&4294967295);var $79=HEAP16[(($sourceix111)>>1)];var $tobool112=(tempInt=(($79)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if($tobool112){__lastLabel__=43;__label__=45;;}else{__lastLabel__=43;__label__=44;;}
if(__label__==44){var $80=$plist_addr;var $arrayidx114=(($80+24)&4294967295);var $ph115=(($arrayidx114+8)&4294967295);var $81=HEAP32[(($ph115)>>2)];var $type116=(($81+11)&4294967295);var $82=HEAPU8[($type116)];var $conv117=((($82))&255);var $cmp118=((($conv117))|0)==0;__lastLabel__=44;;}
var $83=__lastLabel__==43?1:($cmp118);$retval=$83;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==46){var $84=$plist_addr;var $sourceix121=(($84+6)&4294967295);var $85=HEAPU16[(($sourceix121)>>1)];var $conv122=((($85))&65535);var $cmp123=((($conv122))|0)!=0;if($cmp123){__label__=47;;}else{__label__=48;;}
if(__label__==47){$retval=0;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==48){while(1){var $86=$plist_addr;var $incdec_ptr=(($86+-24)&4294967295);$plist_addr=$incdec_ptr;var $87=$plist_addr;var $stresslevel=(($87+1)&4294967295);var $88=HEAPU8[($stresslevel)];var $conv126=((($88))&255);var $and127=($conv126)&15;var $cmp128=((($and127))|0)>=4;if($cmp128){__label__=49;break;}
var $89=$plist_addr;var $sourceix131=(($89+6)&4294967295);var $90=HEAPU16[(($sourceix131)>>1)];var $conv132=((($90))&65535);var $cmp133=((($conv132))|0)==0;if($cmp133){__label__=48;continue;}else{__label__=60;break $sw_bb169$$sw_bb93$$sw_bb94$$sw_bb101$$sw_bb105$$sw_bb109$$sw_bb120$$sw_bb134$$for_cond139$$sw_bb156$53;}}
$retval=1;__label__=73;break $if_then$$if_else187$2;}}
else if(__label__==51){var $91=$ph;var $type135=(($91+11)&4294967295);var $92=HEAPU8[($type135)];var $conv136=((($92))&255);var $cmp137=((($conv136))|0)!=2;$retval=$cmp137;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==52){while(1){var $93=$plist_addr;var $incdec_ptr140=(($93+24)&4294967295);$plist_addr=$incdec_ptr140;var $94=$plist_addr;var $phcode141=(($94)&4294967295);var $95=HEAPU8[($phcode141)];var $idxprom142=((($95))&255);var $arrayidx143=((_phoneme_tab+$idxprom142*4)&4294967295);var $96=HEAP32[(($arrayidx143)>>2)];var $97=$plist_addr;var $ph144=(($97+8)&4294967295);HEAP32[(($ph144)>>2)]=$96;var $98=$plist_addr;var $sourceix145=(($98+6)&4294967295);var $99=HEAPU16[(($sourceix145)>>1)];var $conv146=((($99))&65535);var $cmp147=((($conv146))|0)!=0;if($cmp147){__label__=53;break;}
var $100=$plist_addr;var $ph150=(($100+8)&4294967295);var $101=HEAP32[(($ph150)>>2)];var $type151=(($101+11)&4294967295);var $102=HEAPU8[($type151)];var $conv152=((($102))&255);var $cmp153=((($conv152))|0)==2;if($cmp153){__label__=55;break;}else{__label__=52;continue;}}
if(__label__==53){$retval=1;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==55){$retval=0;__label__=73;break $if_then$$if_else187$2;}}
else if(__label__==56){var $103=$ph;var $type157=(($103+11)&4294967295);var $104=HEAPU8[($type157)];var $conv158=((($104))&255);var $cmp159=((($conv158))|0)==2;if($cmp159){__lastLabel__=56;__label__=59;;}else{__lastLabel__=56;__label__=57;;}
$lor_end168$$lor_lhs_false160$80:do{if(__label__==57){var $105=$ph;var $type161=(($105+11)&4294967295);var $106=HEAPU8[($type161)];var $conv162=((($106))&255);var $cmp163=((($conv162))|0)==3;if($cmp163){__lastLabel__=57;__label__=59;break $lor_end168$$lor_lhs_false160$80;}else{__lastLabel__=57;;}
var $107=$ph;var $phflags165=(($107+4)&4294967295);var $108=HEAP32[(($phflags165)>>2)];var $and166=($108)&16;var $tobool167=((($and166))|0)!=0;__lastLabel__=58;;}}while(0);var $109=__lastLabel__==57?1:(__lastLabel__==56?1:($tobool167));$retval=$109;__label__=73;break $if_then$$if_else187$2;}}while(0);$count=0;;while(1){var $110=$plist_addr;var $ph171=(($110+8)&4294967295);var $111=HEAP32[(($ph171)>>2)];var $type172=(($111+11)&4294967295);var $112=HEAPU8[($type172)];var $conv173=((($112))&255);var $cmp174=((($conv173))|0)==2;if($cmp174){__label__=62;;}else{__label__=63;;}
if(__label__==62){var $113=$count;var $inc176=((($113)+1)&4294967295);$count=$inc176;;}
var $114=$plist_addr;var $sourceix178=(($114+6)&4294967295);var $115=HEAPU16[(($sourceix178)>>1)];var $conv179=((($115))&65535);var $cmp180=((($conv179))|0)!=0;if($cmp180){__label__=65;break;}
var $116=$plist_addr;var $incdec_ptr183=(($116+-24)&4294967295);$plist_addr=$incdec_ptr183;__label__=61;continue;}
var $117=$count;var $cmp185=((($117))|0)==1;$retval=$cmp185;;}}}
else if(__label__==67){var $cmp188=((($3))|0)==15;if($cmp188){__label__=68;;}else{__label__=72;;}
$if_then189$$if_end201$93:do{if(__label__==68){var $118=$data;if($118==1){__label__=69;;}
else if($118==2){__label__=70;;}
else if($118==3){__label__=71;;}
else{__label__=72;break $if_then189$$if_end201$93;}
if(__label__==69){var $119=$control_addr;var $and191=($119)&1;var $tobool192=((($and191))|0)!=0;$retval=$tobool192;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==70){var $120=HEAP32[((_voice)>>2)];var $klattv=(($120+112)&4294967295);var $arrayidx194=(($klattv)&4294967295);var $121=HEAP32[(($arrayidx194)>>2)];var $cmp195=((($121))|0)!=0;$retval=$cmp195;__label__=73;break $if_then$$if_else187$2;}
else if(__label__==71){var $122=HEAP8[(((_mbrola_name)&4294967295))];var $conv197=(tempInt=(($122)),(tempInt>=128?tempInt-256:tempInt));var $cmp198=((($conv197))|0)!=0;$retval=$cmp198;__label__=73;break $if_then$$if_else187$2;}}}while(0);$retval=0;;}}while(0);var $123=$retval;;return $123;return null;}
function __ZL13NumInstnWordsPt($prog){;var __label__;var $retval;var $prog_addr;var $instn;var $instn2;var $instn_type;$prog_addr=$prog;var $0=$prog_addr;var $1=HEAPU16[(($0)>>1)];var $conv=((($1))&65535);$instn=$conv;var $2=$instn;var $shr=($2)>>12;$instn_type=$shr;var $3=$instn_type;var $cmp=((($3))|0)<11;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $4=$instn_type;var $arrayidx=((__ZZL13NumInstnWordsPtE7n_words+$4)&4294967295);var $5=HEAP8[($arrayidx)];var $conv1=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));$retval=$conv1;;}
else if(__label__==2){var $6=$prog_addr;var $arrayidx2=(($6+4)&4294967295);var $7=HEAPU16[(($arrayidx2)>>1)];var $conv3=((($7))&65535);$instn2=$conv3;var $8=$instn2;var $shr4=($8)>>12;var $cmp5=((($shr4))|0)==15;if($cmp5){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=4;;}
else if(__label__==4){var $9=$instn2;var $cmp8=((($9))|0)==2;if($cmp8){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=3;;}
else if(__label__==6){$retval=2;;}}}
var $10=$retval;;return $10;return null;}
function __ZL15SwitchVowelTypeP12PHONEME_LISTP12PHONEME_DATAPPti($plist,$phdata,$p_prog,$instn_type){;var __label__;var $plist_addr;var $phdata_addr;var $p_prog_addr;var $instn_type_addr;var $prog;var $voweltype;var $x;$plist_addr=$plist;$phdata_addr=$phdata;$p_prog_addr=$p_prog;$instn_type_addr=$instn_type;var $0=$instn_type_addr;var $cmp=((($0))|0)==2;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$phdata_addr;var $pd_control=(($1)&4294967295);var $2=HEAP32[(($pd_control)>>2)];var $or=($2)|2;HEAP32[(($pd_control)>>2)]=$or;var $3=$plist_addr;var $arrayidx=(($3+24)&4294967295);var $ph=(($arrayidx+8)&4294967295);var $4=HEAP32[(($ph)>>2)];var $start_type=(($4+12)&4294967295);var $5=HEAPU8[($start_type)];var $conv=((($5))&255);$voweltype=$conv;;}
else if(__label__==2){var $6=$plist_addr;var $arrayidx1=(($6+-24)&4294967295);var $ph2=(($arrayidx1+8)&4294967295);var $7=HEAP32[(($ph2)>>2)];var $end_type=(($7+13)&4294967295);var $8=HEAPU8[($end_type)];var $conv3=((($8))&255);$voweltype=$conv3;;}
var $9=$voweltype;var $sub=((($9)-28)&4294967295);$voweltype=$sub;var $10=$voweltype;var $cmp4=((($10))|0)>=0;var $11=$voweltype;var $cmp5=((($11))|0)<6;var $or_cond=($cmp4)&($cmp5);if($or_cond){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $12=$p_prog_addr;var $13=HEAP32[(($12)>>2)];var $14=$voweltype;var $mul=((($14)*2)&4294967295);var $add_ptr=(($13+2*$mul)&4294967295);$prog=$add_ptr;var $15=$prog;var $arrayidx7=(($15+2)&4294967295);var $16=HEAPU16[(($arrayidx7)>>1)];var $conv8=((($16))&65535);var $and=($conv8)&15;var $shl=((($and)*65536)&4294967295);var $17=$prog;var $arrayidx9=(($17+4)&4294967295);var $18=HEAPU16[(($arrayidx9)>>1)];var $conv10=((($18))&65535);var $add=((($shl)+($conv10))&4294967295);var $mul11=((($add)*4)&4294967295);var $19=$instn_type_addr;var $20=$phdata_addr;var $sound_addr=(($20+68)&4294967295);var $arrayidx12=(($sound_addr+$19*4)&4294967295);HEAP32[(($arrayidx12)>>2)]=$mul11;var $21=$prog;var $arrayidx13=(($21+2)&4294967295);var $22=HEAPU16[(($arrayidx13)>>1)];var $conv14=((($22))&65535);var $shr=($conv14)>>4;var $and15=($shr)&255;var $conv16=((($and15))&255);$x=$conv16;var $23=$x;var $conv17=(tempInt=(($23)),(tempInt>=128?tempInt-256:tempInt));var $24=$instn_type_addr;var $25=$phdata_addr;var $sound_param=(($25+88)&4294967295);var $arrayidx18=(($sound_param+$24*4)&4294967295);HEAP32[(($arrayidx18)>>2)]=$conv17;;}
var $26=$p_prog_addr;var $27=HEAP32[(($26)>>2)];var $add_ptr20=(($27+24)&4294967295);HEAP32[(($26)>>2)]=$add_ptr20;;return;return;}
function __Z17InterpretPhoneme2iP12PHONEME_DATA($phcode,$phdata){var __stackBase__=STACKTOP;STACKTOP+=96;_memset(__stackBase__,0,96);var __label__;var $phcode_addr;var $phdata_addr;var $ix;var $plist=__stackBase__;$phcode_addr=$phcode;$phdata_addr=$phdata;var $arraydecay=(($plist)&4294967295);var $0=$arraydecay;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$0;$stop$=$dest$+96;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};$ix=0;;while(1){var $1=$ix;var $arrayidx=(($plist+$1*24)&4294967295);var $phcode1=(($arrayidx)&4294967295);HEAP8[($phcode1)]=9;var $2=HEAP32[((((_phoneme_tab+36)&4294967295))>>2)];var $3=$ix;var $arrayidx2=(($plist+$3*24)&4294967295);var $ph=(($arrayidx2+8)&4294967295);HEAP32[(($ph)>>2)]=$2;var $4=$ix;var $inc=((($4)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<4;if($cmp){__label__=1;continue;}else{__label__=2;break;}}
var $5=$phcode_addr;var $conv=((($5))&255);var $arrayidx3=(($plist+24)&4294967295);var $phcode4=(($arrayidx3)&4294967295);HEAP8[($phcode4)]=$conv;var $6=$phcode_addr;var $arrayidx5=((_phoneme_tab+$6*4)&4294967295);var $7=HEAP32[(($arrayidx5)>>2)];var $arrayidx6=(($plist+24)&4294967295);var $ph7=(($arrayidx6+8)&4294967295);HEAP32[(($ph7)>>2)]=$7;var $arrayidx8=(($plist+48)&4294967295);var $sourceix=(($arrayidx8+6)&4294967295);HEAP16[(($sourceix)>>1)]=1;var $arrayidx9=(($plist+24)&4294967295);var $8=$phdata_addr;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$arrayidx9,$8);STACKTOP=__stackBase__;return;return;}
function __Z12WordToStringj($word){;var __label__;var $word_addr;var $ix;$word_addr=$word;$ix=0;;while(1){var $0=$word_addr;var $1=$ix;var $mul=((($1)*8)&4294967295);var $shr=($0)>>>((($mul))>>>0);var $conv=((($shr))&255);var $2=$ix;var $arrayidx=((__ZZ12WordToStringjE3buf+$2)&4294967295);HEAP8[($arrayidx)]=$conv;var $3=$ix;var $inc=((($3)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<3;if($cmp){__label__=1;continue;}else{__label__=2;break;}}
HEAP8[(((__ZZ12WordToStringjE3buf+4)&4294967295))]=0;;return((__ZZ12WordToStringjE3buf)&4294967295);return null;}
function __Z14SynthesizeInitv(){;var __label__;HEAP32[((__ZL14last_pitch_cmd)>>2)]=0;HEAP32[((__ZL12last_amp_cmd)>>2)]=0;HEAP32[((__ZL10last_frame)>>2)]=0;HEAP32[((__ZL15syllable_centre)>>2)]=-1;;return;return;}
function __Z11PauseLengthii($pause,$control){;var __label__;var $pause_addr;var $control_addr;var $len;$pause_addr=$pause;$control_addr=$control;var $0=$control_addr;var $cmp=((($0))|0)==0;var $1=$pause_addr;if($cmp){__label__=1;;}else{__label__=4;;}
if(__label__==1){var $cmp1=((($1))|0)>=200;var $2=$pause_addr;if($cmp1){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $3=HEAP32[((((_speed+4)&4294967295))>>2)];var $mul=((($3)*($2))&4294967295);var $div=((((($mul))|0)/256)|0);$len=$div;;}
else if(__label__==3){var $4=HEAP32[((((_speed)&4294967295))>>2)];var $mul3=((($4)*($2))&4294967295);var $div4=((((($mul3))|0)/256)|0);$len=$div4;;}}
else if(__label__==4){var $5=HEAP32[((((_speed+12)&4294967295))>>2)];var $mul6=((($5)*($1))&4294967295);var $div7=((((($mul6))|0)/256)|0);$len=$div7;;}
var $6=$len;var $7=HEAP32[((((_speed+8)&4294967295))>>2)];var $cmp9=((($6))|0)<((($7))|0);if($cmp9){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $8=HEAP32[((((_speed+8)&4294967295))>>2)];$len=$8;;}
var $9=$len;;return $9;return null;}
function __Z9DoSample3P12PHONEME_DATAii($phdata,$length_mod,$amp){;var __label__;var $phdata_addr;var $length_mod_addr;var $amp_addr;var $amp2;var $len;$phdata_addr=$phdata;$length_mod_addr=$length_mod;$amp_addr=$amp;__ZL8EndPitchi(1);var $0=$amp_addr;var $cmp=((($0))|0)==-1;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$amp_addr;$amp2=$1;;}
else if(__label__==2){var $2=$phdata_addr;var $sound_param=(($2+88)&4294967295);var $arrayidx=(($sound_param+4)&4294967295);var $3=HEAP32[(($arrayidx)>>2)];$amp2=$3;var $4=$amp2;var $cmp1=((($4))|0)==0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){$amp2=100;;}
var $5=$amp2;var $mul=((($5)*32)&4294967295);var $div=((((($mul))|0)/100)|0);$amp2=$div;;}
HEAP32[((_seq_len_adjust)>>2)]=0;var $6=$phdata_addr;var $sound_addr=(($6+68)&4294967295);var $arrayidx4=(($sound_addr+4)&4294967295);var $7=HEAP32[(($arrayidx4)>>2)];var $cmp5=((($7))|0)==0;if($cmp5){__label__=6;;}else{__label__=7;;}
if(__label__==6){$len=0;;}
else if(__label__==7){var $8=$phdata_addr;var $sound_addr8=(($8+68)&4294967295);var $arrayidx9=(($sound_addr8+4)&4294967295);var $9=HEAP32[(($arrayidx9)>>2)];var $10=$phdata_addr;var $pd_param=(($10+4)&4294967295);var $arrayidx10=(($pd_param+40)&4294967295);var $11=HEAP32[(($arrayidx10)>>2)];var $mul11=((($11)*2)&4294967295);var $12=$phdata_addr;var $pd_control=(($12)&4294967295);var $13=HEAP32[(($pd_control)>>2)];var $14=$length_mod_addr;var $15=$amp2;var $call=__ZL9DoSample2iiiiii($9,2,$mul11,$13,$14,$15);$len=$call;;}
HEAP32[((__ZL10last_frame)>>2)]=0;var $16=$len;;return $16;return null;}
function __ZL8EndPitchi($voice_break){;var __label__;var $voice_break_addr;$voice_break_addr=$voice_break;var $0=HEAP32[((__ZL12pitch_length)>>2)];var $cmp=((($0))|0)>0;var $1=HEAP32[((__ZL14last_pitch_cmd)>>2)];var $cmp1=((($1))|0)>=0;var $or_cond=($cmp)&($cmp1);if($or_cond){__label__=1;;}else{__label__=4;;}
if(__label__==1){var $2=HEAP32[((__ZL14last_pitch_cmd)>>2)];var $arrayidx=((_wcmdq+$2*16)&4294967295);var $arrayidx2=(($arrayidx+4)&4294967295);var $3=HEAP32[(($arrayidx2)>>2)];var $cmp3=((($3))|0)==0;if($cmp3){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $4=HEAP32[((__ZL12pitch_length)>>2)];var $5=HEAP32[((__ZL14last_pitch_cmd)>>2)];var $arrayidx5=((_wcmdq+$5*16)&4294967295);var $arrayidx6=(($arrayidx5+4)&4294967295);HEAP32[(($arrayidx6)>>2)]=$4;;}
HEAP32[((__ZL12pitch_length)>>2)]=0;;}
var $6=$voice_break_addr;var $tobool=((($6))|0)!=0;if($tobool){__label__=5;;}else{__label__=6;;}
if(__label__==5){HEAP32[((__ZL10last_wcmdq)>>2)]=-1;HEAP32[((__ZL10last_frame)>>2)]=0;var $7=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL12syllable_end)>>2)]=$7;__ZL11SmoothSpectv();HEAP32[((__ZL15syllable_centre)>>2)]=-1;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=_vowel_transition;$stop$=$dest$+16;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};;};return;return;}
function __ZL9DoSample2iiiiii($index,$which,$std_length,$control,$length_mod,$amp){;var __label__;var __lastLabel__=null;var $retval;var $index_addr;var $which_addr;var $std_length_addr;var $control_addr;var $length_mod_addr;var $amp_addr;var $length;var $wav_length;var $wav_scale;var $min_length;var $x;var $len4;var $q;var $p;$index_addr=$index;$which_addr=$which;$std_length_addr=$std_length;$control_addr=$control;$length_mod_addr=$length_mod;$amp_addr=$amp;var $0=$index_addr;var $and=($0)&8388607;$index_addr=$and;var $1=$index_addr;var $2=HEAP32[((_wavefile_data)>>2)];var $arrayidx=(($2+$1)&4294967295);$p=$arrayidx;var $3=$p;var $arrayidx1=(($3+2)&4294967295);var $4=HEAPU8[($arrayidx1)];var $conv=((($4))&255);$wav_scale=$conv;var $5=$p;var $arrayidx2=(($5+1)&4294967295);var $6=HEAPU8[($arrayidx2)];var $conv3=((($6))&255);var $mul=((($conv3)*256)&4294967295);$wav_length=$mul;var $7=$p;var $arrayidx4=(($7)&4294967295);var $8=HEAPU8[($arrayidx4)];var $conv5=((($8))&255);var $9=$wav_length;var $add=((($9)+($conv5))&4294967295);$wav_length=$add;var $10=$wav_length;var $cmp=((($10))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $11=HEAP32[((((_speed+24)&4294967295))>>2)];$min_length=$11;var $12=$wav_scale;var $cmp6=((($12))|0)==0;if($cmp6){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $13=$min_length;var $mul8=((($13)*2)&4294967295);$min_length=$mul8;;}
var $14=$std_length_addr;var $cmp10=((($14))|0)>0;if($cmp10){__label__=5;;}else{__label__=9;;}
$if_then11$$if_else22$8:do{if(__label__==5){var $15=$std_length_addr;var $16=HEAP32[((_samplerate)>>2)];var $mul12=((($16)*($15))&4294967295);var $div=((((($mul12))|0)/1000)|0);$std_length_addr=$div;var $17=$wav_scale;var $cmp13=((($17))|0)==0;if($cmp13){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $18=$std_length_addr;var $mul15=((($18)*2)&4294967295);$std_length_addr=$mul15;;}
var $19=$min_length;var $20=$std_length_addr;var $mul17=((($20)*($19))&4294967295);var $21=$wav_length;var $div18=((((($mul17))|0)/((($21))|0))|0);$x=$div18;var $22=$x;var $23=$min_length;var $cmp19=((($22))|0)>((($23))|0);if(!($cmp19)){__label__=10;break $if_then11$$if_else22$8;}
var $24=$x;$min_length=$24;;}
else if(__label__==9){var $25=$wav_length;$std_length_addr=$25;;}}while(0);var $26=$length_mod_addr;var $cmp24=((($26))|0)>0;if($cmp24){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $27=$std_length_addr;var $28=$length_mod_addr;var $mul26=((($28)*($27))&4294967295);var $div27=((((($mul26))|0)/256)|0);$std_length_addr=$div27;;}
var $29=$std_length_addr;var $30=HEAP32[((((_speed+12)&4294967295))>>2)];var $mul29=((($30)*($29))&4294967295);var $div30=((((($mul29))|0)/256)|0);$length=$div30;var $31=$control_addr;var $and31=($31)&4;var $tobool=((($and31))|0)!=0;if($tobool){__label__=13;;}else{__label__=15;;}
$if_then32$$if_end37$19:do{if(__label__==13){var $32=$length;var $33=$std_length_addr;var $cmp33=((($32))|0)>((($33))|0);if(!($cmp33)){__label__=15;break $if_then32$$if_end37$19;}
var $34=$std_length_addr;$length=$34;;}}while(0);var $35=$length;var $36=$min_length;var $cmp38=((($35))|0)<((($36))|0);if($cmp38){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $37=$min_length;$length=$37;;}
var $38=$wav_scale;var $cmp41=((($38))|0)==0;if($cmp41){__label__=18;;}else{__label__=19;;}
if(__label__==18){var $39=$length;var $div43=((((($39))|0)/2)|0);$length=$div43;var $40=$wav_length;var $div44=((((($40))|0)/2)|0);$wav_length=$div44;;}
var $41=$amp_addr;var $cmp46=((($41))|0)<0;if($cmp46){__label__=20;;}else{__label__=21;;}
if(__label__==20){var $42=$length;$retval=$42;;}
else if(__label__==21){var $43=$wav_length;var $div49=((((($43))|0)/4)|0);$len4=$div49;var $44=$index_addr;var $add50=((($44)+4)&4294967295);$index_addr=$add50;var $45=$which_addr;var $and51=($45)&256;var $tobool52=((($and51))|0)!=0;if($tobool52){__label__=22;;}else{__label__=23;;}
if(__label__==22){var $46=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL10last_wcmdq)>>2)]=$46;var $47=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx54=((_wcmdq+$47*16)&4294967295);var $arraydecay=(($arrayidx54)&4294967295);$q=$arraydecay;var $48=$q;var $arrayidx55=(($48)&4294967295);HEAP32[(($arrayidx55)>>2)]=7;var $49=$length;var $50=$wav_length;var $shl=($50)<<16;var $or=($shl)|($49);var $51=$q;var $arrayidx56=(($51+4)&4294967295);HEAP32[(($arrayidx56)>>2)]=$or;var $52=$index_addr;var $53=HEAP32[((_wavefile_data)>>2)];var $arrayidx57=(($53+$52)&4294967295);var $54=($arrayidx57);var $55=$q;var $arrayidx58=(($55+8)&4294967295);HEAP32[(($arrayidx58)>>2)]=$54;var $56=$wav_scale;var $57=$amp_addr;var $shl59=((($57)*256)&4294967295);var $add60=((($shl59)+($56))&4294967295);var $58=$q;var $arrayidx61=(($58+12)&4294967295);HEAP32[(($arrayidx61)>>2)]=$add60;__Z8WcmdqIncv();var $59=$length;$retval=$59;;}
else if(__label__==23){var $60=$length;var $61=$wav_length;var $cmp63=((($60))|0)>((($61))|0);if($cmp63){__label__=24;;}else{__label__=25;;}
if(__label__==24){var $62=$len4;var $mul65=((($62)*3)&4294967295);$x=$mul65;var $63=$x;var $64=$length;var $sub=((($64)-($63))&4294967295);$length=$sub;;}
else if(__label__==25){var $65=$length;$x=$65;$length=0;;}
var $66=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL10last_wcmdq)>>2)]=$66;var $67=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx68=((_wcmdq+$67*16)&4294967295);var $arraydecay69=(($arrayidx68)&4294967295);$q=$arraydecay69;var $68=$q;var $arrayidx70=(($68)&4294967295);HEAP32[(($arrayidx70)>>2)]=6;var $69=$x;var $70=$q;var $arrayidx71=(($70+4)&4294967295);HEAP32[(($arrayidx71)>>2)]=$69;var $71=$index_addr;var $72=HEAP32[((_wavefile_data)>>2)];var $arrayidx72=(($72+$71)&4294967295);var $73=($arrayidx72);var $74=$q;var $arrayidx73=(($74+8)&4294967295);HEAP32[(($arrayidx73)>>2)]=$73;var $75=$wav_scale;var $76=$amp_addr;var $shl74=((($76)*256)&4294967295);var $add75=((($shl74)+($75))&4294967295);var $77=$q;var $arrayidx76=(($77+12)&4294967295);HEAP32[(($arrayidx76)>>2)]=$add75;__Z8WcmdqIncv();var $78=$length;var $79=$len4;var $mul771=((($79)*3)&4294967295);var $cmp782=((($78))|0)>((($mul771))|0);if($cmp782){__lastLabel__=26;__label__=27;;}else{__lastLabel__=26;__label__=30;;}
$while_body$$while_end$39:do{if(__label__==27){while(1){var $80=$len4;$x=$80;var $81=$wav_scale;var $cmp79=((($81))|0)==0;if($cmp79){__label__=28;;}else{__label__=29;;}
if(__label__==28){var $82=$x;var $mul81=((($82)*2)&4294967295);$x=$mul81;;}
var $83=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL10last_wcmdq)>>2)]=$83;var $84=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx83=((_wcmdq+$84*16)&4294967295);var $arraydecay84=(($arrayidx83)&4294967295);$q=$arraydecay84;var $85=$q;var $arrayidx85=(($85)&4294967295);HEAP32[(($arrayidx85)>>2)]=6;var $86=$len4;var $mul86=((($86)*2)&4294967295);var $87=$q;var $arrayidx87=(($87+4)&4294967295);HEAP32[(($arrayidx87)>>2)]=$mul86;var $88=$index_addr;var $89=$x;var $add88=((($89)+($88))&4294967295);var $90=HEAP32[((_wavefile_data)>>2)];var $arrayidx89=(($90+$add88)&4294967295);var $91=($arrayidx89);var $92=$q;var $arrayidx90=(($92+8)&4294967295);HEAP32[(($arrayidx90)>>2)]=$91;var $93=$wav_scale;var $94=$amp_addr;var $shl91=((($94)*256)&4294967295);var $add92=((($shl91)+($93))&4294967295);var $95=$q;var $arrayidx93=(($95+12)&4294967295);HEAP32[(($arrayidx93)>>2)]=$add92;__Z8WcmdqIncv();var $96=$len4;var $mul94=((($96)*2)&4294967295);var $97=$length;var $sub95=((($97)-($mul94))&4294967295);$length=$sub95;var $98=$length;var $99=$len4;var $mul77=((($99)*3)&4294967295);var $cmp78=((($98))|0)>((($mul77))|0);if($cmp78){__lastLabel__=29;__label__=27;continue;}else{__lastLabel__=29;__label__=30;break $while_body$$while_end$39;}}}}while(0);var $100=__lastLabel__==29?$98:($78);var $cmp96=((($100))|0)>0;if($cmp96){__label__=31;;}else{__label__=34;;}
if(__label__==31){var $101=$wav_length;var $102=$length;var $sub98=((($101)-($102))&4294967295);$x=$sub98;var $103=$wav_scale;var $cmp99=((($103))|0)==0;if($cmp99){__label__=32;;}else{__label__=33;;}
if(__label__==32){var $104=$x;var $mul101=((($104)*2)&4294967295);$x=$mul101;;}
var $105=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL10last_wcmdq)>>2)]=$105;var $106=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx103=((_wcmdq+$106*16)&4294967295);var $arraydecay104=(($arrayidx103)&4294967295);$q=$arraydecay104;var $107=$q;var $arrayidx105=(($107)&4294967295);HEAP32[(($arrayidx105)>>2)]=6;var $108=$length;var $109=$q;var $arrayidx106=(($109+4)&4294967295);HEAP32[(($arrayidx106)>>2)]=$108;var $110=$index_addr;var $111=$x;var $add107=((($111)+($110))&4294967295);var $112=HEAP32[((_wavefile_data)>>2)];var $arrayidx108=(($112+$add107)&4294967295);var $113=($arrayidx108);var $114=$q;var $arrayidx109=(($114+8)&4294967295);HEAP32[(($arrayidx109)>>2)]=$113;var $115=$wav_scale;var $116=$amp_addr;var $shl110=((($116)*256)&4294967295);var $add111=((($shl110)+($115))&4294967295);var $117=$q;var $arrayidx112=(($117+12)&4294967295);HEAP32[(($arrayidx112)>>2)]=$add111;__Z8WcmdqIncv();;}
var $118=$length;$retval=$118;;}}}
var $119=$retval;;return $119;return null;}
function __Z18FormantTransition2P10frameref_tRijjP11PHONEME_TABi($seq,$n_frames,$data1,$data2,$other_ph,$which){;var __label__;var $retval;var $seq_addr;var $n_frames_addr;var $data1_addr;var $data2_addr;var $other_ph_addr;var $which_addr;var $ix;var $formant;var $next_rms;var $len;var $rms;var $f1;var $f2;var $f2_min;var $f2_max;var $f3_adj;var $f3_amp;var $flags;var $vcolour;var $fr;var $x;$seq_addr=$seq;$n_frames_addr=$n_frames;$data1_addr=$data1;$data2_addr=$data2;$other_ph_addr=$other_ph;$which_addr=$which;$fr=0;var $0=$n_frames_addr;var $1=HEAP32[(($0)>>2)];var $cmp=((($1))|0)<2;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $2=$data1_addr;var $and=($2)&63;var $mul=((($and)*2)&4294967295);$len=$mul;var $3=$data1_addr;var $shr=($3)>>>6;var $and1=($shr)&63;$rms=$and1;var $4=$data1_addr;var $shr2=($4)>>>12;$flags=$shr2;var $5=$data2_addr;var $and3=($5)&63;var $mul4=((($and3)*50)&4294967295);$f2=$mul4;var $6=$data2_addr;var $shr5=($6)>>>6;var $and6=($shr5)&31;var $sub=((($and6)-15)&4294967295);var $mul7=((($sub)*50)&4294967295);$f2_min=$mul7;var $7=$data2_addr;var $shr8=($7)>>>11;var $and9=($shr8)&31;var $sub10=((($and9)-15)&4294967295);var $mul11=((($sub10)*50)&4294967295);$f2_max=$mul11;var $8=$data2_addr;var $shr12=($8)>>>16;var $and13=($shr12)&31;var $sub14=((($and13)-15)&4294967295);var $mul15=((($sub14)*50)&4294967295);$f3_adj=$mul15;var $9=$data2_addr;var $shr16=($9)>>>21;var $and17=($shr16)&31;var $mul18=((($and17)*8)&4294967295);$f3_amp=$mul18;var $10=$data2_addr;var $shr19=($10)>>>26;var $and20=($shr19)&7;$f1=$and20;var $11=$data2_addr;var $shr21=($11)>>>29;$vcolour=$shr21;var $12=$other_ph_addr;var $cmp22=((($12))|0)!=0;if($cmp22){__label__=3;;}else{__label__=5;;}
$land_lhs_true$$if_end25$5:do{if(__label__==3){var $13=$other_ph_addr;var $mnemonic=(($13)&4294967295);var $14=HEAP32[(($mnemonic)>>2)];var $cmp23=((($14))|0)==63;if(!($cmp23)){__label__=5;break $land_lhs_true$$if_end25$5;}
var $15=$flags;var $or=($15)|8;$flags=$or;;}}while(0);var $16=$which_addr;var $cmp26=((($16))|0)==1;if($cmp26){__label__=6;;}else{__label__=20;;}
$if_then27$$if_else85$9:do{if(__label__==6){var $17=$seq_addr;var $arrayidx=(($17)&4294967295);var $frame=(($arrayidx+4)&4294967295);var $18=HEAP32[(($frame)>>2)];var $call=__ZL9CopyFrameP7frame_ti($18,0);$fr=$call;var $19=$fr;var $20=$seq_addr;var $arrayidx28=(($20)&4294967295);var $frame29=(($arrayidx28+4)&4294967295);HEAP32[(($frame29)>>2)]=$19;var $21=$seq_addr;var $arrayidx30=(($21)&4294967295);var $length=(($arrayidx30)&4294967295);HEAP16[(($length)>>1)]=50;var $22=$len;var $cmp31=((($22))|0)>0;if($cmp31){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $23=$len;var $conv=((($23))&65535);var $24=$seq_addr;var $arrayidx33=(($24)&4294967295);var $length34=(($arrayidx33)&4294967295);HEAP16[(($length34)>>1)]=$conv;;}
var $25=$seq_addr;var $arrayidx36=(($25)&4294967295);var $frflags=(($arrayidx36+2)&4294967295);var $26=HEAP16[(($frflags)>>1)];var $conv37=(tempInt=(($26)),(tempInt>=32768?tempInt-65536:tempInt));var $or38=($conv37)|16384;var $conv39=((($or38))&65535);HEAP16[(($frflags)>>1)]=$conv39;var $27=$fr;var $frflags40=(($27)&4294967295);var $28=HEAP16[(($frflags40)>>1)];var $conv41=(tempInt=(($28)),(tempInt>=32768?tempInt-65536:tempInt));var $or42=($conv41)|16384;var $conv43=((($or42))&65535);HEAP16[(($frflags40)>>1)]=$conv43;var $29=$seq_addr;var $arrayidx44=(($29+8)&4294967295);var $frame45=(($arrayidx44+4)&4294967295);var $30=HEAP32[(($frame45)>>2)];var $rms46=(($30+17)&4294967295);var $31=HEAPU8[($rms46)];var $conv47=((($31))&255);$next_rms=$conv47;var $32=HEAP32[((_voice)>>2)];var $klattv=(($32+112)&4294967295);var $arrayidx48=(($klattv)&4294967295);var $33=HEAP32[(($arrayidx48)>>2)];var $tobool=((($33))|0)!=0;if($tobool){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $34=$seq_addr;var $arrayidx50=(($34+8)&4294967295);var $frame51=(($arrayidx50+4)&4294967295);var $35=HEAP32[(($frame51)>>2)];var $klattp=(($35+39)&4294967295);var $arrayidx52=(($klattp)&4294967295);var $36=HEAPU8[($arrayidx52)];var $conv53=((($36))&255);var $sub54=((($conv53)-4)&4294967295);var $conv55=((($sub54))&255);var $37=$fr;var $klattp56=(($37+39)&4294967295);var $arrayidx57=(($klattp56)&4294967295);HEAP8[($arrayidx57)]=$conv55;;}
var $38=$f2;var $cmp59=((($38))|0)!=0;if($cmp59){__label__=11;;}else{__label__=15;;}
$if_then60$$if_else$17:do{if(__label__==11){var $39=$rms;var $and61=($39)&32;var $tobool62=((($and61))|0)!=0;if($tobool62){__label__=12;;}else{__label__=13;;}
if(__label__==12){var $40=$fr;var $41=$next_rms;var $42=$rms;var $and64=($42)&31;var $mul65=((($and64)*($41))&4294967295);var $div=((((($mul65))|0)/30)|0);__ZL13set_frame_rmsP7frame_ti($40,$div);;}
var $43=$fr;var $44=$f2;var $45=$f2_min;var $46=$f2_max;var $47=$f1;var $48=$f3_adj;var $49=$f3_amp;var $50=$flags;__ZL14AdjustFormantsP7frame_tiiiiiii($43,$44,$45,$46,$47,$48,$49,$50);var $51=$rms;var $and67=($51)&32;var $cmp68=((($and67))|0)==0;if(!($cmp68)){__label__=18;break $if_then60$$if_else$17;}
var $52=$fr;var $53=$rms;var $mul70=((($53)*2)&4294967295);__ZL13set_frame_rmsP7frame_ti($52,$mul70);;}
else if(__label__==15){var $54=$flags;var $and72=($54)&8;var $tobool73=((($and72))|0)!=0;var $55=$fr;if($tobool73){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $56=$next_rms;var $mul75=((($56)*24)&4294967295);var $div76=((((($mul75))|0)/32)|0);__ZL13set_frame_rmsP7frame_ti($55,$div76);;}
else if(__label__==17){__ZL13set_frame_rmsP7frame_ti($55,28);;}}}while(0);var $57=$flags;var $and80=($57)&8;var $tobool81=((($and80))|0)!=0;if(!($tobool81)){__label__=33;break $if_then27$$if_else85$9;}
var $58=$fr;var $call83=__ZL14VowelClosenessP7frame_t($58);var $shl=((($call83)*256)&4294967295);var $add=((($shl)+2048)&4294967295);HEAP32[((__ZL10modn_flags)>>2)]=$add;;}
else if(__label__==20){var $59=$rms;var $mul86=((($59)*2)&4294967295);$rms=$mul86;var $60=$f2;var $cmp87=((($60))|0)!=0;if($cmp87){__label__=22;;}else{__label__=21;;}
if(__label__==21){var $61=$flags;var $cmp88=((($61))|0)!=0;if(!($cmp88)){__label__=33;break $if_then27$$if_else85$9;}}
var $62=$flags;var $and90=($62)&8;var $tobool91=((($and90))|0)!=0;if($tobool91){__label__=23;;}else{__label__=24;;}
$if_then92$$if_else103$33:do{if(__label__==23){var $63=$n_frames_addr;var $64=HEAP32[(($63)>>2)];var $sub93=((($64)-1)&4294967295);var $65=$seq_addr;var $arrayidx94=(($65+8*$sub93)&4294967295);var $frame95=(($arrayidx94+4)&4294967295);var $66=HEAP32[(($frame95)>>2)];var $call96=__ZL9CopyFrameP7frame_ti($66,0);$fr=$call96;var $67=$fr;var $68=$n_frames_addr;var $69=HEAP32[(($68)>>2)];var $sub97=((($69)-1)&4294967295);var $70=$seq_addr;var $arrayidx98=(($70+8*$sub97)&4294967295);var $frame99=(($arrayidx98+4)&4294967295);HEAP32[(($frame99)>>2)]=$67;$rms=35;var $71=$fr;var $call100=__ZL14VowelClosenessP7frame_t($71);var $shl101=((($call100)*256)&4294967295);var $add102=((($shl101)+1024)&4294967295);HEAP32[((__ZL10modn_flags)>>2)]=$add102;;}
else if(__label__==24){var $72=$seq_addr;var $73=$n_frames_addr;var $74=HEAP32[(($73)>>2)];var $inc=((($74)+1)&4294967295);HEAP32[(($73)>>2)]=$inc;var $75=$len;var $call104=__ZL18DuplicateLastFrameP10frameref_tii($72,$74,$75);$fr=$call104;var $76=$len;var $cmp105=((($76))|0)>36;if($cmp105){__label__=25;;}else{__label__=26;;}
if(__label__==25){var $77=$len;var $78=HEAP32[((_seq_len_adjust)>>2)];var $sub107=((($77)-36)&4294967295);var $add108=((($sub107)+($78))&4294967295);HEAP32[((_seq_len_adjust)>>2)]=$add108;;}
var $79=$f2;var $cmp110=((($79))|0)!=0;if(!($cmp110)){__label__=28;break $if_then92$$if_else103$33;}
var $80=$fr;var $81=$f2;var $82=$f2_min;var $83=$f2_max;var $84=$f1;var $85=$f3_adj;var $86=$f3_amp;var $87=$flags;__ZL14AdjustFormantsP7frame_tiiiiiii($80,$81,$82,$83,$84,$85,$86,$87);;}}while(0);var $88=$fr;var $89=$rms;__ZL13set_frame_rmsP7frame_ti($88,$89);var $90=$vcolour;var $cmp114=((($90))|0)>0;var $91=$vcolour;var $cmp116=((($91))|0)<=2;var $or_cond=($cmp114)&($cmp116);if(!($or_cond)){__label__=33;break $if_then27$$if_else85$9;}
$ix=0;var $92=$ix;var $93=$n_frames_addr;var $94=HEAP32[(($93)>>2)];var $cmp1181=((($92))|0)<((($94))|0);if(!($cmp1181)){__label__=33;break $if_then27$$if_else85$9;}
$for_body$42:while(1){var $95=$ix;var $96=$seq_addr;var $arrayidx119=(($96+8*$95)&4294967295);var $frame120=(($arrayidx119+4)&4294967295);var $97=HEAP32[(($frame120)>>2)];var $call121=__ZL9CopyFrameP7frame_ti($97,0);$fr=$call121;var $98=$fr;var $99=$ix;var $100=$seq_addr;var $arrayidx122=(($100+8*$99)&4294967295);var $frame123=(($arrayidx122+4)&4294967295);HEAP32[(($frame123)>>2)]=$98;$formant=1;;while(1){var $101=$formant;var $102=$fr;var $ffreq=(($102+2)&4294967295);var $arrayidx127=(($ffreq+$101*2)&4294967295);var $103=HEAP16[(($arrayidx127)>>1)];var $conv128=(tempInt=(($103)),(tempInt>=32768?tempInt-65536:tempInt));var $104=$formant;var $sub129=((($104)-1)&4294967295);var $105=$vcolour;var $sub130=((($105)-1)&4294967295);var $arrayidx131=((__ZZ18FormantTransition2P10frameref_tRijjP11PHONEME_TABiE10vcolouring+$sub130*10)&4294967295);var $arrayidx132=(($arrayidx131+$sub129*2)&4294967295);var $106=HEAP16[(($arrayidx132)>>1)];var $conv133=(tempInt=(($106)),(tempInt>=32768?tempInt-65536:tempInt));var $mul134=((($conv133)*($conv128))&4294967295);$x=$mul134;var $107=$x;var $div135=((((($107))|0)/256)|0);var $conv136=((($div135))&65535);var $108=$formant;var $109=$fr;var $ffreq137=(($109+2)&4294967295);var $arrayidx138=(($ffreq137+$108*2)&4294967295);HEAP16[(($arrayidx138)>>1)]=$conv136;var $110=$formant;var $inc139=((($110)+1)&4294967295);$formant=$inc139;var $cmp125=((($inc139))|0)<=5;if($cmp125){__label__=31;continue;}else{__label__=32;break;}}
var $111=$ix;var $inc141=((($111)+1)&4294967295);$ix=$inc141;var $112=$ix;var $113=$n_frames_addr;var $114=HEAP32[(($113)>>2)];var $cmp118=((($112))|0)<((($114))|0);if($cmp118){__label__=30;continue $for_body$42;}else{__label__=33;break $if_then27$$if_else85$9;}}}}while(0);var $115=$fr;var $cmp146=((($115))|0)!=0;if($cmp146){__label__=34;;}else{__label__=38;;}
$if_then147$$if_end164$48:do{if(__label__==34){var $116=$flags;var $and148=($116)&4;var $tobool149=((($and148))|0)!=0;if($tobool149){__label__=35;;}else{__label__=36;;}
if(__label__==35){var $117=$fr;var $frflags151=(($117)&4294967295);var $118=HEAP16[(($frflags151)>>1)];var $conv152=(tempInt=(($118)),(tempInt>=32768?tempInt-65536:tempInt));var $or153=($conv152)|32;var $conv154=((($or153))&65535);HEAP16[(($frflags151)>>1)]=$conv154;;}
var $119=$flags;var $and156=($119)&2;var $tobool157=((($and156))|0)!=0;if(!($tobool157)){__label__=38;break $if_then147$$if_end164$48;}
var $120=$fr;var $frflags159=(($120)&4294967295);var $121=HEAP16[(($frflags159)>>1)];var $conv160=(tempInt=(($121)),(tempInt>=32768?tempInt-65536:tempInt));var $or161=($conv160)|16;var $conv162=((($or161))&65535);HEAP16[(($frflags159)>>1)]=$conv162;;}}while(0);var $122=$flags;var $and165=($122)&64;var $tobool166=((($and165))|0)!=0;if($tobool166){__label__=39;;}else{__label__=40;;}
if(__label__==39){__ZL7DoPauseii(12,0);;}
var $123=$flags;var $and169=($123)&16;var $tobool170=((($and169))|0)!=0;if($tobool170){__label__=41;;}else{__label__=42;;}
if(__label__==41){var $124=$len;$retval=$124;;}
else if(__label__==42){$retval=0;;}}
var $125=$retval;;return $125;return null;}
function __ZL9CopyFrameP7frame_ti($frame1,$copy){;var __label__;var $retval;var $frame1_addr;var $copy_addr;var $frame2;$frame1_addr=$frame1;$copy_addr=$copy;var $0=$copy_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=3;;}
$land_lhs_true$$if_end$2:do{if(__label__==1){var $1=$frame1_addr;var $frflags=(($1)&4294967295);var $2=HEAP16[(($frflags)>>1)];var $conv=(tempInt=(($2)),(tempInt>=32768?tempInt-65536:tempInt));var $and=($conv)&32768;var $tobool=((($and))|0)!=0;if(!($tobool)){__label__=3;break $land_lhs_true$$if_end$2;}
var $3=$frame1_addr;$retval=$3;__label__=6;break $land_lhs_true$$if_end$2;}}while(0);if(__label__==3){var $call=__ZL10AllocFramev();$frame2=$call;var $cmp1=((($call))|0)!=0;if($cmp1){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $4=$frame2;var $5=$4;var $6=$frame1_addr;var $7=$6;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$7;$dest$=$5;$stop$=$src$+64;if(($dest$%4)==($src$%4)&&64>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $8=$frame2;var $length=(($8+16)&4294967295);HEAP8[($length)]=0;var $9=$frame2;var $frflags3=(($9)&4294967295);var $10=HEAP16[(($frflags3)>>1)];var $conv4=(tempInt=(($10)),(tempInt>=32768?tempInt-65536:tempInt));var $or=($conv4)|32768;var $conv5=((($or))&65535);HEAP16[(($frflags3)>>1)]=$conv5;;}
var $11=$frame2;$retval=$11;;}
var $12=$retval;;return $12;return null;}
function __ZL13set_frame_rmsP7frame_ti($fr,$new_rms){;var __label__;var $fr_addr;var $new_rms_addr;var $x;var $h;var $ix;$fr_addr=$fr;$new_rms_addr=$new_rms;var $0=HEAP32[((_voice)>>2)];var $klattv=(($0+112)&4294967295);var $arrayidx=(($klattv)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];var $tobool=((($1))|0)!=0;if($tobool){__label__=1;;}else{__label__=3;;}
$if_then$$if_end3$2:do{if(__label__==1){var $2=$new_rms_addr;var $cmp=((($2))|0)==-1;if(!($cmp)){__label__=8;break $if_then$$if_end3$2;}
var $3=$fr_addr;var $klattp=(($3+39)&4294967295);var $arrayidx2=(($klattp)&4294967295);HEAP8[($arrayidx2)]=50;;}
else if(__label__==3){var $4=$fr_addr;var $rms=(($4+17)&4294967295);var $5=HEAPU8[($rms)];var $conv=((($5))&255);var $cmp4=((($conv))|0)==0;if($cmp4){__label__=8;break $if_then$$if_end3$2;}
var $6=$new_rms_addr;var $mul=((($6)*64)&4294967295);var $7=$fr_addr;var $rms7=(($7+17)&4294967295);var $8=HEAPU8[($rms7)];var $conv8=((($8))&255);var $div=((((($mul))|0)/((($conv8))|0))|0);$x=$div;var $9=$x;var $cmp9=((($9))|0)>=200;if($cmp9){__label__=5;;}else{__label__=6;;}
if(__label__==5){$x=199;;}
var $10=$x;var $arrayidx12=((__ZZL13set_frame_rmsP7frame_tiE8sqrt_tab+$10*2)&4294967295);var $11=HEAP16[(($arrayidx12)>>1)];var $conv13=(tempInt=(($11)),(tempInt>=32768?tempInt-65536:tempInt));$x=$conv13;$ix=0;;while(1){var $12=$ix;var $13=$fr_addr;var $fheight=(($13+18)&4294967295);var $arrayidx15=(($fheight+$12)&4294967295);var $14=HEAPU8[($arrayidx15)];var $conv16=((($14))&255);var $15=$x;var $mul17=((($conv16)*($15))&4294967295);$h=$mul17;var $16=$h;var $div18=((((($16))|0)/512)|0);var $conv19=((($div18))&255);var $17=$ix;var $18=$fr_addr;var $fheight20=(($18+18)&4294967295);var $arrayidx21=(($fheight20+$17)&4294967295);HEAP8[($arrayidx21)]=$conv19;var $19=$ix;var $inc=((($19)+1)&4294967295);$ix=$inc;var $cmp14=((($inc))|0)<8;if($cmp14){__label__=7;continue;}else{__label__=8;break $if_then$$if_end3$2;}}}}while(0);;return;return;}
function __ZL14AdjustFormantsP7frame_tiiiiiii($fr,$target,$min,$max,$f1_adj,$f3_adj,$hf_reduce,$flags){;var __label__;var __lastLabel__=null;var $fr_addr;var $target_addr;var $min_addr;var $max_addr;var $f1_adj_addr;var $f3_adj_addr;var $hf_reduce_addr;var $flags_addr;var $x;$fr_addr=$fr;$target_addr=$target;$min_addr=$min;$max_addr=$max;$f1_adj_addr=$f1_adj;$f3_adj_addr=$f3_adj;$hf_reduce_addr=$hf_reduce;$flags_addr=$flags;var $0=$target_addr;var $1=HEAP32[((_voice)>>2)];var $formant_factor=(($1+96)&4294967295);var $2=HEAP32[(($formant_factor)>>2)];var $mul=((($2)*($0))&4294967295);var $div=((((($mul))|0)/256)|0);$target_addr=$div;var $3=$target_addr;var $4=$fr_addr;var $ffreq=(($4+2)&4294967295);var $arrayidx=(($ffreq+4)&4294967295);var $5=HEAP16[(($arrayidx)>>1)];var $conv=(tempInt=(($5)),(tempInt>=32768?tempInt-65536:tempInt));var $sub=((($3)-($conv))&4294967295);var $div1=((((($sub))|0)/2)|0);$x=$div1;var $6=$x;var $7=$max_addr;var $cmp=((($6))|0)>((($7))|0);if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $8=$max_addr;$x=$8;;}
var $9=$x;var $10=$min_addr;var $cmp2=((($9))|0)<((($10))|0);if($cmp2){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $11=$min_addr;$x=$11;;}
var $12=$x;var $13=$fr_addr;var $ffreq5=(($13+2)&4294967295);var $arrayidx6=(($ffreq5+4)&4294967295);var $14=HEAP16[(($arrayidx6)>>1)];var $conv7=(tempInt=(($14)),(tempInt>=32768?tempInt-65536:tempInt));var $add=((($conv7)+($12))&4294967295);var $conv8=((($add))&65535);HEAP16[(($arrayidx6)>>1)]=$conv8;var $15=$f3_adj_addr;var $16=$fr_addr;var $ffreq9=(($16+2)&4294967295);var $arrayidx10=(($ffreq9+6)&4294967295);var $17=HEAP16[(($arrayidx10)>>1)];var $conv11=(tempInt=(($17)),(tempInt>=32768?tempInt-65536:tempInt));var $add12=((($conv11)+($15))&4294967295);var $conv13=((($add12))&65535);HEAP16[(($arrayidx10)>>1)]=$conv13;var $18=$flags_addr;var $and=($18)&32;var $tobool=((($and))|0)!=0;if($tobool){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $19=$f3_adj_addr;var $sub15=(((-($19)))&4294967295);$f3_adj_addr=$sub15;;}
var $20=$f3_adj_addr;var $21=$fr_addr;var $ffreq17=(($21+2)&4294967295);var $arrayidx18=(($ffreq17+8)&4294967295);var $22=HEAP16[(($arrayidx18)>>1)];var $conv19=(tempInt=(($22)),(tempInt>=32768?tempInt-65536:tempInt));var $add20=((($conv19)+($20))&4294967295);var $conv21=((($add20))&65535);HEAP16[(($arrayidx18)>>1)]=$conv21;var $23=$f3_adj_addr;var $24=$fr_addr;var $ffreq22=(($24+2)&4294967295);var $arrayidx23=(($ffreq22+10)&4294967295);var $25=HEAP16[(($arrayidx23)>>1)];var $conv24=(tempInt=(($25)),(tempInt>=32768?tempInt-65536:tempInt));var $add25=((($conv24)+($23))&4294967295);var $conv26=((($add25))&65535);HEAP16[(($arrayidx23)>>1)]=$conv26;var $26=$f1_adj_addr;var $cmp27=((($26))|0)==1;if($cmp27){__lastLabel__=6;__label__=7;;}else{__lastLabel__=6;__label__=12;;}
if(__label__==7){var $27=$fr_addr;var $ffreq29=(($27+2)&4294967295);var $arrayidx30=(($ffreq29+2)&4294967295);var $28=HEAP16[(($arrayidx30)>>1)];var $conv31=(tempInt=(($28)),(tempInt>=32768?tempInt-65536:tempInt));var $sub32=((235-($conv31))&4294967295);$x=$sub32;var $29=$x;var $cmp33=((($29))|0)<-100;if($cmp33){__label__=8;;}else{__label__=9;;}
$if_end35_thread$$if_end35$13:do{if(__label__==8){$x=-100;;}
else if(__label__==9){var $cmp36=((($29))|0)>-60;if(!($cmp36)){__label__=11;break $if_end35_thread$$if_end35$13;}
$x=-60;;}}while(0);var $30=$x;var $31=$fr_addr;var $ffreq39=(($31+2)&4294967295);var $arrayidx40=(($ffreq39+2)&4294967295);var $32=HEAP16[(($arrayidx40)>>1)];var $conv41=(tempInt=(($32)),(tempInt>=32768?tempInt-65536:tempInt));var $add42=((($conv41)+($30))&4294967295);var $conv43=((($add42))&65535);HEAP16[(($arrayidx40)>>1)]=$conv43;var $_pr=$f1_adj_addr;__lastLabel__=11;;}
var $33=__lastLabel__==11?$_pr:($26);var $cmp45=((($33))|0)==2;if($cmp45){__label__=13;;}else{__label__=18;;}
if(__label__==13){var $34=$fr_addr;var $ffreq47=(($34+2)&4294967295);var $arrayidx48=(($ffreq47+2)&4294967295);var $35=HEAP16[(($arrayidx48)>>1)];var $conv49=(tempInt=(($35)),(tempInt>=32768?tempInt-65536:tempInt));var $sub50=((235-($conv49))&4294967295);$x=$sub50;var $36=$x;var $cmp51=((($36))|0)<-300;if($cmp51){__label__=14;;}else{__label__=15;;}
$if_end53_thread$$if_end53$21:do{if(__label__==14){$x=-300;;}
else if(__label__==15){var $cmp54=((($36))|0)>-150;if(!($cmp54)){__label__=17;break $if_end53_thread$$if_end53$21;}
$x=-150;;}}while(0);var $37=$x;var $38=$fr_addr;var $ffreq57=(($38+2)&4294967295);var $arrayidx58=(($ffreq57+2)&4294967295);var $39=HEAP16[(($arrayidx58)>>1)];var $conv59=(tempInt=(($39)),(tempInt>=32768?tempInt-65536:tempInt));var $add60=((($conv59)+($37))&4294967295);var $conv61=((($add60))&65535);HEAP16[(($arrayidx58)>>1)]=$conv61;var $40=$x;var $41=$fr_addr;var $ffreq62=(($41+2)&4294967295);var $arrayidx63=(($ffreq62)&4294967295);var $42=HEAP16[(($arrayidx63)>>1)];var $conv64=(tempInt=(($42)),(tempInt>=32768?tempInt-65536:tempInt));var $add65=((($conv64)+($40))&4294967295);var $conv66=((($add65))&65535);HEAP16[(($arrayidx63)>>1)]=$conv66;;}
var $43=$f1_adj_addr;var $cmp68=((($43))|0)==3;if($cmp68){__label__=19;;}else{__label__=24;;}
if(__label__==19){var $44=$fr_addr;var $ffreq70=(($44+2)&4294967295);var $arrayidx71=(($ffreq70+2)&4294967295);var $45=HEAP16[(($arrayidx71)>>1)];var $conv72=(tempInt=(($45)),(tempInt>=32768?tempInt-65536:tempInt));var $sub73=((100-($conv72))&4294967295);$x=$sub73;var $46=$x;var $cmp74=((($46))|0)<-400;if($cmp74){__label__=20;;}else{__label__=21;;}
$if_end76_thread$$if_end76$29:do{if(__label__==20){$x=-400;;}
else if(__label__==21){var $cmp77=((($46))|0)>-300;if(!($cmp77)){__label__=23;break $if_end76_thread$$if_end76$29;}
$x=-400;;}}while(0);var $47=$x;var $48=$fr_addr;var $ffreq80=(($48+2)&4294967295);var $arrayidx81=(($ffreq80+2)&4294967295);var $49=HEAP16[(($arrayidx81)>>1)];var $conv82=(tempInt=(($49)),(tempInt>=32768?tempInt-65536:tempInt));var $add83=((($conv82)+($47))&4294967295);var $conv84=((($add83))&65535);HEAP16[(($arrayidx81)>>1)]=$conv84;var $50=$x;var $51=$fr_addr;var $ffreq85=(($51+2)&4294967295);var $arrayidx86=(($ffreq85)&4294967295);var $52=HEAP16[(($arrayidx86)>>1)];var $conv87=(tempInt=(($52)),(tempInt>=32768?tempInt-65536:tempInt));var $add88=((($conv87)+($50))&4294967295);var $conv89=((($add88))&65535);HEAP16[(($arrayidx86)>>1)]=$conv89;;}
var $53=$fr_addr;var $54=$hf_reduce_addr;__ZL18formants_reduce_hfP7frame_ti($53,$54);;return;return;}
function __ZL14VowelClosenessP7frame_t($fr){;var __label__;var $retval;var $fr_addr;var $f1;$fr_addr=$fr;var $0=$fr_addr;var $ffreq=(($0+2)&4294967295);var $arrayidx=(($ffreq+2)&4294967295);var $1=HEAP16[(($arrayidx)>>1)];var $conv=(tempInt=(($1)),(tempInt>=32768?tempInt-65536:tempInt));$f1=$conv;var $cmp=((($conv))|0)<300;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=3;;}
else if(__label__==2){var $2=$f1;var $cmp1=((($2))|0)<400;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=2;;}
else if(__label__==4){var $3=$f1;var $cmp4=((($3))|0)<500;if($cmp4){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=1;;}
else if(__label__==6){$retval=0;;}}}
var $4=$retval;;return $4;return null;}
function __ZL18DuplicateLastFrameP10frameref_tii($seq,$n_frames,$length){;var __label__;var $seq_addr;var $n_frames_addr;var $length_addr;var $fr;$seq_addr=$seq;$n_frames_addr=$n_frames;$length_addr=$length;var $0=$length_addr;var $conv=((($0))&65535);var $1=$n_frames_addr;var $sub=((($1)-1)&4294967295);var $2=$seq_addr;var $arrayidx=(($2+8*$sub)&4294967295);var $length1=(($arrayidx)&4294967295);HEAP16[(($length1)>>1)]=$conv;var $3=$n_frames_addr;var $sub2=((($3)-1)&4294967295);var $4=$seq_addr;var $arrayidx3=(($4+8*$sub2)&4294967295);var $frame=(($arrayidx3+4)&4294967295);var $5=HEAP32[(($frame)>>2)];var $call=__ZL9CopyFrameP7frame_ti($5,1);$fr=$call;var $6=$fr;var $7=$n_frames_addr;var $8=$seq_addr;var $arrayidx4=(($8+8*$7)&4294967295);var $frame5=(($arrayidx4+4)&4294967295);HEAP32[(($frame5)>>2)]=$6;var $9=$n_frames_addr;var $10=$seq_addr;var $arrayidx6=(($10+8*$9)&4294967295);var $length7=(($arrayidx6)&4294967295);HEAP16[(($length7)>>1)]=0;var $11=$fr;;return $11;return null;}
function __ZL7DoPauseii($length,$control){;var __label__;var $length_addr;var $control_addr;var $len;$length_addr=$length;$control_addr=$control;var $0=$length_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$len=0;;}
else if(__label__==2){var $1=$length_addr;var $2=$control_addr;var $call=__Z11PauseLengthii($1,$2);$len=$call;var $3=$len;var $4=HEAP32[((_samplerate)>>2)];var $mul=((($4)*($3))&4294967295);var $div=((((($mul))|0)/1000)|0);$len=$div;;}
__ZL8EndPitchi(1);var $5=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx=((_wcmdq+$5*16)&4294967295);var $arrayidx1=(($arrayidx)&4294967295);HEAP32[(($arrayidx1)>>2)]=5;var $6=$len;var $7=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx2=((_wcmdq+$7*16)&4294967295);var $arrayidx3=(($arrayidx2+4)&4294967295);HEAP32[(($arrayidx3)>>2)]=$6;__Z8WcmdqIncv();HEAP32[((__ZL10last_frame)>>2)]=0;var $8=HEAP32[((__ZL13fmt_amplitude)>>2)];var $cmp4=((($8))|0)!=0;if($cmp4){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $9=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx6=((_wcmdq+$9*16)&4294967295);var $arrayidx7=(($arrayidx6)&4294967295);HEAP32[(($arrayidx7)>>2)]=14;HEAP32[((__ZL13fmt_amplitude)>>2)]=0;var $10=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx8=((_wcmdq+$10*16)&4294967295);var $arrayidx9=(($arrayidx8+4)&4294967295);HEAP32[(($arrayidx9)>>2)]=0;__Z8WcmdqIncv();;};return;return;}
function __Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($this_ph,$which,$fmt_params,$plist,$modulation){var __stackBase__=STACKTOP;STACKTOP+=104;_memset(__stackBase__,0,104);var __label__;var __lastLabel__=null;var $retval;var $this_ph_addr;var $which_addr;var $fmt_params_addr;var $plist_addr;var $modulation_addr;var $n_frames=__stackBase__;var $frames;var $frameix;var $frame1;var $frame2;var $fr;var $ix;var $q;var $len;var $frame_length;var $length_factor;var $length_mod;var $length_sum;var $length_min;var $total_len;var $wcmd_spect;var $frame_lengths=__stackBase__+4;$this_ph_addr=$this_ph;$which_addr=$which;$fmt_params_addr=$fmt_params;$plist_addr=$plist;$modulation_addr=$modulation;$total_len=0;$wcmd_spect=3;var $0=$fmt_params_addr;var $fmt_addr=(($0+8)&4294967295);var $1=HEAP32[(($fmt_addr)>>2)];var $cmp=((($1))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $2=$plist_addr;var $length=(($2+12)&4294967295);var $3=HEAP16[(($length)>>1)];var $conv=(tempInt=(($3)),(tempInt>=32768?tempInt-65536:tempInt));$length_mod=$conv;var $4=$length_mod;var $cmp1=((($4))|0)==0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){$length_mod=256;;}
var $5=HEAP32[((_samplerate)>>2)];var $div=((((($5))|0)/70)|0);$length_min=$div;var $6=$which_addr;var $cmp4=((($6))|0)==2;if($cmp4){__lastLabel__=4;__label__=5;;}else{__lastLabel__=4;__label__=11;;}
if(__label__==5){var $7=HEAP32[((_translator)>>2)];var $langopts=(($7)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx=(($param+72)&4294967295);var $8=HEAP32[(($arrayidx)>>2)];var $cmp6=((($8))|0)>0;if($cmp6){__label__=6;;}else{__label__=10;;}
$land_lhs_true$$if_end18thread_pre_split$10:do{if(__label__==6){var $9=$this_ph_addr;var $std_length=(($9+14)&4294967295);var $10=HEAPU8[($std_length)];var $conv7=((($10))&255);var $11=HEAP32[((_translator)>>2)];var $langopts8=(($11)&4294967295);var $param9=(($langopts8+24)&4294967295);var $arrayidx10=(($param9+72)&4294967295);var $12=HEAP32[(($arrayidx10)>>2)];var $cmp11=((($conv7))|0)>=((($12))|0);if($cmp11){__label__=9;;}else{__label__=7;;}
$if_then16$$lor_lhs_false$12:do{if(__label__==7){var $13=$plist_addr;var $synthflags=(($13+4)&4294967295);var $14=HEAPU16[(($synthflags)>>1)];var $conv12=((($14))&65535);var $and=($conv12)&8;var $tobool=((($and))|0)!=0;if($tobool){__label__=9;break $if_then16$$lor_lhs_false$12;}
var $15=$this_ph_addr;var $phflags=(($15+4)&4294967295);var $16=HEAP32[(($phflags)>>2)];var $and14=($16)&2097152;var $tobool15=((($and14))|0)!=0;if(!($tobool15)){__label__=10;break $land_lhs_true$$if_end18thread_pre_split$10;}}}while(0);var $17=$length_min;var $mul=((($17)*2)&4294967295);$length_min=$mul;;}}while(0);var $_pr=$which_addr;__lastLabel__=10;;}
var $18=__lastLabel__==10?$_pr:($6);var $cmp19=((($18))|0)==1;if($cmp19){__label__=12;;}else{__label__=17;;}
$if_then20$$if_end41$18:do{if(__label__==12){var $19=$this_ph_addr;var $type=(($19+11)&4294967295);var $20=HEAPU8[($type)];var $conv21=((($20))&255);var $cmp22=((($conv21))|0)==3;if($cmp22){__label__=15;;}else{__label__=13;;}
$if_then33$$lor_lhs_false23$20:do{if(__label__==13){var $21=$plist_addr;var $arrayidx24=(($21+-24)&4294967295);var $type25=(($arrayidx24+15)&4294967295);var $22=HEAPU8[($type25)];var $conv26=((($22))&255);var $cmp27=((($conv26))|0)==3;if($cmp27){__label__=15;break $if_then33$$lor_lhs_false23$20;}
var $23=$plist_addr;var $arrayidx29=(($23+-24)&4294967295);var $type30=(($arrayidx29+15)&4294967295);var $24=HEAPU8[($type30)];var $conv31=((($24))&255);var $cmp32=((($conv31))|0)==8;if(!($cmp32)){__label__=17;break $if_then20$$if_end41$18;}}}while(0);var $25=$length_mod;var $26=HEAP32[((_translator)>>2)];var $langopts34=(($26)&4294967295);var $param35=(($langopts34+24)&4294967295);var $arrayidx36=(($param35+28)&4294967295);var $27=HEAP32[(($arrayidx36)>>2)];$len=$27;var $cmp37=((($25))|0)<((($27))|0);if(!($cmp37)){__label__=17;break $if_then20$$if_end41$18;}
var $28=$len;$length_mod=$28;;}}while(0);HEAP32[((__ZL10modn_flags)>>2)]=0;var $29=$this_ph_addr;var $30=$which_addr;var $31=$fmt_params_addr;var $32=$plist_addr;var $call=__Z11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LIST($29,$30,$31,$n_frames,$32);$frames=$call;var $cmp42=((($call))|0)==0;if($cmp42){__label__=18;;}else{__label__=19;;}
if(__label__==18){$retval=0;;}
else if(__label__==19){var $33=$fmt_params_addr;var $fmt_amp=(($33+16)&4294967295);var $34=HEAP32[(($fmt_amp)>>2)];var $35=HEAP32[((__ZL13fmt_amplitude)>>2)];var $cmp45=((($34))|0)!=((($35))|0);if($cmp45){__label__=20;;}else{__label__=21;;}
if(__label__==20){var $36=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx47=((_wcmdq+$36*16)&4294967295);var $arraydecay=(($arrayidx47)&4294967295);$q=$arraydecay;var $37=$q;var $arrayidx48=(($37)&4294967295);HEAP32[(($arrayidx48)>>2)]=14;var $38=$fmt_params_addr;var $fmt_amp49=(($38+16)&4294967295);var $39=HEAP32[(($fmt_amp49)>>2)];HEAP32[((__ZL13fmt_amplitude)>>2)]=$39;var $40=$q;var $arrayidx50=(($40+4)&4294967295);HEAP32[(($arrayidx50)>>2)]=$39;__Z8WcmdqIncv();;}
var $41=$frames;var $arrayidx52=(($41)&4294967295);var $frame=(($arrayidx52+4)&4294967295);var $42=HEAP32[(($frame)>>2)];$frame1=$42;var $43=HEAP32[((_voice)>>2)];var $klattv=(($43+112)&4294967295);var $arrayidx53=(($klattv)&4294967295);var $44=HEAP32[(($arrayidx53)>>2)];var $tobool54=((($44))|0)!=0;if($tobool54){__label__=22;;}else{__label__=23;;}
if(__label__==22){$wcmd_spect=1;;}
var $45=$fmt_params_addr;var $wav_addr=(($45+28)&4294967295);var $46=HEAP32[(($wav_addr)>>2)];HEAP32[((_wavefile_ix)>>2)]=$46;var $47=$fmt_params_addr;var $wav_amp=(($47+32)&4294967295);var $48=HEAP32[(($wav_amp)>>2)];var $cmp57=((($48))|0)==0;if($cmp57){__label__=24;;}else{__label__=25;;}
if(__label__==24){HEAP32[((_wavefile_amp)>>2)]=32;;}
else if(__label__==25){var $49=$fmt_params_addr;var $wav_amp59=(($49+32)&4294967295);var $50=HEAP32[(($wav_amp59)>>2)];var $mul60=((($50)*32)&4294967295);var $div61=((((($mul60))|0)/100)|0);HEAP32[((_wavefile_amp)>>2)]=$div61;;}
var $51=HEAP32[((_wavefile_ix)>>2)];var $cmp63=((($51))|0)==0;if($cmp63){__label__=27;;}else{__label__=33;;}
$if_then64$$if_end79$39:do{if(__label__==27){var $_b=HEAPU8[(__ZZ8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTiE9wave_flag_b)];var $52=((($_b))&1);var $tobool65=((($52))|0)!=0;if($tobool65){__label__=28;;}else{__label__=31;;}
if(__label__==28){$wcmd_spect=4;var $53=HEAP32[((_voice)>>2)];var $klattv67=(($53+112)&4294967295);var $arrayidx68=(($klattv67)&4294967295);var $54=HEAP32[(($arrayidx68)>>2)];var $tobool69=((($54))|0)!=0;if($tobool69){__label__=29;;}else{__label__=30;;}
if(__label__==29){$wcmd_spect=2;;}
HEAP8[(__ZZ8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTiE9wave_flag_b)]=0;;}
else if(__label__==31){$wcmd_spect=3;var $55=HEAP32[((_voice)>>2)];var $klattv73=(($55+112)&4294967295);var $arrayidx74=(($klattv73)&4294967295);var $56=HEAP32[(($arrayidx74)>>2)];var $tobool75=((($56))|0)!=0;if(!($tobool75)){__label__=33;break $if_then64$$if_end79$39;}
$wcmd_spect=1;;}}}while(0);var $57=HEAP32[((__ZL10last_frame)>>2)];var $cmp80=((($57))|0)!=0;if($cmp80){__label__=34;;}else{__label__=43;;}
$if_then81$$if_end117$49:do{if(__label__==34){var $58=HEAP32[((__ZL10last_frame)>>2)];var $length82=(($58+16)&4294967295);var $59=HEAPU8[($length82)];var $conv83=((($59))&255);var $cmp84=((($conv83))|0)<2;if($cmp84){__label__=36;;}else{__label__=35;;}
if(__label__==35){var $60=HEAP32[((__ZL10last_frame)>>2)];var $frflags=(($60)&4294967295);var $61=HEAP16[(($frflags)>>1)];var $conv86=(tempInt=(($61)),(tempInt>=32768?tempInt-65536:tempInt));var $and87=($conv86)&2;var $tobool88=((($and87))|0)!=0;if(!($tobool88)){__label__=43;break $if_then81$$if_end117$49;}}
var $62=HEAP32[((__ZL10last_frame)>>2)];var $frflags90=(($62)&4294967295);var $63=HEAP16[(($frflags90)>>1)];var $conv91=(tempInt=(($63)),(tempInt>=32768?tempInt-65536:tempInt));var $and92=($conv91)&16;var $tobool93=((($and92))|0)!=0;if($tobool93){__label__=43;break $if_then81$$if_end117$49;}
var $64=$frame1;var $65=($64);var $66=HEAP32[((__ZL10last_wcmdq)>>2)];var $arrayidx95=((_wcmdq+$66*16)&4294967295);var $arrayidx96=(($arrayidx95+12)&4294967295);HEAP32[(($arrayidx96)>>2)]=$65;var $67=HEAP32[((__ZL10last_frame)>>2)];var $frflags97=(($67)&4294967295);var $68=HEAP16[(($frflags97)>>1)];var $conv98=(tempInt=(($68)),(tempInt>=32768?tempInt-65536:tempInt));var $and99=($conv98)&8;var $tobool100=((($and99))|0)!=0;if(!($tobool100)){__label__=43;break $if_then81$$if_end117$49;}
var $69=$frame1;var $call102=__ZL9CopyFrameP7frame_ti($69,1);$fr=$call102;$ix=3;__lastLabel__=38;;while(1){var $70=__lastLabel__==38?3:($inc);var $cmp104=((($70))|0)<7;if($cmp104){__label__=40;;}else{__label__=41;;}
if(__label__==40){var $71=$ix;var $72=HEAP32[((__ZL10last_frame)>>2)];var $ffreq=(($72+2)&4294967295);var $arrayidx106=(($ffreq+$71*2)&4294967295);var $73=HEAP16[(($arrayidx106)>>1)];var $74=$ix;var $75=$fr;var $ffreq107=(($75+2)&4294967295);var $arrayidx108=(($ffreq107+$74*2)&4294967295);HEAP16[(($arrayidx108)>>1)]=$73;;}
var $76=$ix;var $77=HEAP32[((__ZL10last_frame)>>2)];var $fheight=(($77+18)&4294967295);var $arrayidx110=(($fheight+$76)&4294967295);var $78=HEAP8[($arrayidx110)];var $79=$ix;var $80=$fr;var $fheight111=(($80+18)&4294967295);var $arrayidx112=(($fheight111+$79)&4294967295);HEAP8[($arrayidx112)]=$78;var $81=$ix;var $inc=((($81)+1)&4294967295);$ix=$inc;var $cmp103=((($inc))|0)<8;if($cmp103){__lastLabel__=41;__label__=39;continue;}else{__lastLabel__=41;__label__=42;break;}}
var $82=$fr;var $83=($82);var $84=HEAP32[((__ZL10last_wcmdq)>>2)];var $arrayidx113=((_wcmdq+$84*16)&4294967295);var $arrayidx114=(($arrayidx113+12)&4294967295);HEAP32[(($arrayidx114)>>2)]=$83;;}}while(0);var $85=$this_ph_addr;var $type118=(($85+11)&4294967295);var $86=HEAPU8[($type118)];var $conv119=((($86))&255);var $cmp120=((($conv119))|0)==2;if($cmp120){__label__=44;;}else{__label__=46;;}
$land_lhs_true121$$if_end124$63:do{if(__label__==44){var $87=$which_addr;var $cmp122=((($87))|0)==2;if(!($cmp122)){__label__=46;break $land_lhs_true121$$if_end124$63;}
__ZL11SmoothSpectv();var $88=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL15syllable_centre)>>2)]=$88;;}}while(0);$length_sum=0;$frameix=1;var $89=$frameix;var $90=HEAP32[(($n_frames)>>2)];var $cmp1263=((($89))|0)<((($90))|0);if($cmp1263){__label__=47;;}else{__label__=56;;}
$for_body127$$if_end180$67:do{if(__label__==47){$for_body127$68:while(1){var $91=$length_mod;$length_factor=$91;var $92=$frameix;var $sub=((($92)-1)&4294967295);var $93=$frames;var $arrayidx128=(($93+8*$sub)&4294967295);var $frflags129=(($arrayidx128+2)&4294967295);var $94=HEAP16[(($frflags129)>>1)];var $conv130=(tempInt=(($94)),(tempInt>=32768?tempInt-65536:tempInt));var $and131=($conv130)&4;var $tobool132=((($and131))|0)!=0;if($tobool132){__label__=48;;}else{__label__=49;;}
$if_then133$$if_else138$70:do{if(__label__==48){var $95=$length_mod;var $96=HEAP32[((((_speed+16)&4294967295))>>2)];var $sub134=((256-($96))&4294967295);var $mul135=((($sub134)*($95))&4294967295);var $97=HEAP32[((((_speed+16)&4294967295))>>2)];var $mul136=((($97)*256)&4294967295);var $add=((($mul135)+($mul136))&4294967295);var $div137=((((($add))|0)/256)|0);$length_factor=$div137;;}
else if(__label__==49){var $98=$frameix;var $sub139=((($98)-1)&4294967295);var $99=$frames;var $arrayidx140=(($99+8*$sub139)&4294967295);var $frflags141=(($arrayidx140+2)&4294967295);var $100=HEAP16[(($frflags141)>>1)];var $conv142=(tempInt=(($100)),(tempInt>=32768?tempInt-65536:tempInt));var $and143=($conv142)&16384;var $tobool144=((($and143))|0)!=0;if(!($tobool144)){__label__=51;break $if_then133$$if_else138$70;}
var $101=$length_mod;var $102=HEAP32[((((_speed+20)&4294967295))>>2)];var $sub146=((256-($102))&4294967295);var $mul147=((($sub146)*($101))&4294967295);var $103=HEAP32[((((_speed+20)&4294967295))>>2)];var $mul148=((($103)*256)&4294967295);var $add149=((($mul147)+($mul148))&4294967295);var $div150=((((($add149))|0)/256)|0);$length_factor=$div150;;}}while(0);var $104=$frameix;var $sub153=((($104)-1)&4294967295);var $105=$frames;var $arrayidx154=(($105+8*$sub153)&4294967295);var $length155=(($arrayidx154)&4294967295);var $106=HEAP16[(($length155)>>1)];var $conv156=(tempInt=(($106)),(tempInt>=32768?tempInt-65536:tempInt));$frame_length=$conv156;var $107=$frame_length;var $108=HEAP32[((_samplerate)>>2)];var $mul157=((($108)*($107))&4294967295);var $div158=((((($mul157))|0)/1000)|0);$len=$div158;var $109=$len;var $110=$length_factor;var $mul159=((($110)*($109))&4294967295);var $div160=((((($mul159))|0)/256)|0);$len=$div160;var $111=$len;var $112=$length_sum;var $add161=((($112)+($111))&4294967295);$length_sum=$add161;var $113=$len;var $114=$frameix;var $arrayidx162=(($frame_lengths+$114*4)&4294967295);HEAP32[(($arrayidx162)>>2)]=$113;var $115=$frameix;var $inc164=((($115)+1)&4294967295);$frameix=$inc164;var $116=$frameix;var $117=HEAP32[(($n_frames)>>2)];var $cmp126=((($116))|0)<((($117))|0);if($cmp126){__label__=47;continue $for_body127$68;}else{__label__=52;break $for_body127$68;}}
var $_pr4=$length_sum;var $cmp166=((($_pr4))|0)>0;if(!($cmp166)){__label__=56;break $for_body127$$if_end180$67;}
var $118=$length_sum;var $119=$length_min;var $cmp168=((($118))|0)<((($119))|0);if(!($cmp168)){__label__=56;break $for_body127$$if_end180$67;}
$frameix=1;var $120=$frameix;var $121=HEAP32[(($n_frames)>>2)];var $cmp1712=((($120))|0)<((($121))|0);if(!($cmp1712)){__label__=56;break $for_body127$$if_end180$67;}
while(1){var $122=$frameix;var $arrayidx173=(($frame_lengths+$122*4)&4294967295);var $123=HEAP32[(($arrayidx173)>>2)];var $124=$length_min;var $mul174=((($124)*($123))&4294967295);var $125=$length_sum;var $div175=((((($mul174))|0)/((($125))|0))|0);var $126=$frameix;var $arrayidx176=(($frame_lengths+$126*4)&4294967295);HEAP32[(($arrayidx176)>>2)]=$div175;var $127=$frameix;var $inc178=((($127)+1)&4294967295);$frameix=$inc178;var $128=$frameix;var $129=HEAP32[(($n_frames)>>2)];var $cmp171=((($128))|0)<((($129))|0);if($cmp171){__label__=55;continue;}else{__label__=56;break $for_body127$$if_end180$67;}}}}while(0);$frameix=1;var $130=$frameix;var $131=HEAP32[(($n_frames)>>2)];var $cmp1821=((($130))|0)<((($131))|0);if($cmp1821){__label__=57;;}else{__label__=72;;}
$for_body183$$for_end235$81:do{if(__label__==57){$for_body183$82:while(1){var $132=$frameix;var $133=$frames;var $arrayidx184=(($133+8*$132)&4294967295);var $frame185=(($arrayidx184+4)&4294967295);var $134=HEAP32[(($frame185)>>2)];$frame2=$134;var $135=$fmt_params_addr;var $wav_addr186=(($135+28)&4294967295);var $136=HEAP32[(($wav_addr186)>>2)];var $cmp187=((($136))|0)!=0;if($cmp187){__label__=58;;}else{__label__=60;;}
$land_lhs_true188$$if_end198$84:do{if(__label__==58){var $137=$frame1;var $frflags189=(($137)&4294967295);var $138=HEAP16[(($frflags189)>>1)];var $conv190=(tempInt=(($138)),(tempInt>=32768?tempInt-65536:tempInt));var $and191=($conv190)&128;var $cmp192=((($and191))|0)==0;if(!($cmp192)){__label__=60;break $land_lhs_true188$$if_end198$84;}
HEAP32[((_seq_len_adjust)>>2)]=0;var $139=$fmt_params_addr;var $wav_addr194=(($139+28)&4294967295);var $140=HEAP32[(($wav_addr194)>>2)];var $141=$which_addr;var $add195=((($141)+256)&4294967295);var $142=$fmt_params_addr;var $fmt_control=(($142)&4294967295);var $143=HEAP32[(($fmt_control)>>2)];var $144=HEAP32[((_wavefile_amp)>>2)];var $call196=__ZL9DoSample2iiiiii($140,$add195,0,$143,0,$144);HEAP8[(__ZZ8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTiE9wave_flag_b)]=1;HEAP32[((_wavefile_ix)>>2)]=0;var $145=$fmt_params_addr;var $wav_addr197=(($145+28)&4294967295);HEAP32[(($wav_addr197)>>2)]=0;;}}while(0);var $146=$modulation_addr;var $cmp199=((($146))|0)>=0;if($cmp199){__label__=61;;}else{__label__=66;;}
$if_then200$$if_end214$88:do{if(__label__==61){var $147=$frame1;var $frflags201=(($147)&4294967295);var $148=HEAP16[(($frflags201)>>1)];var $conv202=(tempInt=(($148)),(tempInt>=32768?tempInt-65536:tempInt));var $and203=($conv202)&64;var $tobool204=((($and203))|0)!=0;if($tobool204){__label__=62;;}else{__label__=63;;}
if(__label__==62){$modulation_addr=6;;}
var $149=$frameix;var $150=HEAP32[(($n_frames)>>2)];var $sub207=((($150)-1)&4294967295);var $cmp208=((($149))|0)==((($sub207))|0);if(!($cmp208)){__label__=66;break $if_then200$$if_end214$88;}
var $151=HEAP32[((__ZL10modn_flags)>>2)];var $and210=($151)&3840;var $tobool211=((($and210))|0)!=0;if(!($tobool211)){__label__=66;break $if_then200$$if_end214$88;}
var $152=HEAP32[((__ZL10modn_flags)>>2)];var $153=$modulation_addr;var $or=($153)|($152);$modulation_addr=$or;;}}while(0);var $154=$frameix;var $arrayidx215=(($frame_lengths+$154*4)&4294967295);var $155=HEAP32[(($arrayidx215)>>2)];$len=$155;var $156=HEAP32[((__ZL12pitch_length)>>2)];var $add216=((($156)+($155))&4294967295);HEAP32[((__ZL12pitch_length)>>2)]=$add216;var $157=HEAP32[((__ZL10amp_length)>>2)];var $add217=((($157)+($155))&4294967295);HEAP32[((__ZL10amp_length)>>2)]=$add217;var $cmp218=((($155))|0)==0;if($cmp218){__label__=67;;}else{__label__=68;;}
if(__label__==67){HEAP32[((__ZL10last_frame)>>2)]=0;var $158=$frame2;$frame1=$158;;}
else if(__label__==68){var $159=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL10last_wcmdq)>>2)]=$159;var $160=$modulation_addr;var $cmp221=((($160))|0)>=0;if($cmp221){__label__=69;;}else{__label__=70;;}
if(__label__==69){var $161=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx223=((_wcmdq+$161*16)&4294967295);var $arraydecay224=(($arrayidx223)&4294967295);$q=$arraydecay224;var $162=$wcmd_spect;var $163=$q;var $arrayidx225=(($163)&4294967295);HEAP32[(($arrayidx225)>>2)]=$162;var $164=$len;var $165=$modulation_addr;var $shl=((($165)*65536)&4294967295);var $add226=((($shl)+($164))&4294967295);var $166=$q;var $arrayidx227=(($166+4)&4294967295);HEAP32[(($arrayidx227)>>2)]=$add226;var $167=$frame1;var $168=($167);var $169=$q;var $arrayidx228=(($169+8)&4294967295);HEAP32[(($arrayidx228)>>2)]=$168;var $170=$frame2;var $171=($170);var $172=$q;var $arrayidx229=(($172+12)&4294967295);HEAP32[(($arrayidx229)>>2)]=$171;__Z8WcmdqIncv();;}
var $173=$frame2;$frame1=$173;HEAP32[((__ZL10last_frame)>>2)]=$173;var $174=$len;var $175=$total_len;var $add231=((($175)+($174))&4294967295);$total_len=$add231;;}
var $176=$frameix;var $inc234=((($176)+1)&4294967295);$frameix=$inc234;var $177=$frameix;var $178=HEAP32[(($n_frames)>>2)];var $cmp182=((($177))|0)<((($178))|0);if($cmp182){__label__=57;continue $for_body183$82;}else{__label__=72;break $for_body183$$for_end235$81;}}}}while(0);var $179=$which_addr;var $cmp236=((($179))|0)!=1;var $180=HEAP32[((__ZL13fmt_amplitude)>>2)];var $cmp238=((($180))|0)!=0;var $or_cond=($cmp236)&($cmp238);if($or_cond){__label__=73;;}else{__label__=74;;}
if(__label__==73){var $181=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx240=((_wcmdq+$181*16)&4294967295);var $arraydecay241=(($arrayidx240)&4294967295);$q=$arraydecay241;var $182=$q;var $arrayidx242=(($182)&4294967295);HEAP32[(($arrayidx242)>>2)]=14;HEAP32[((__ZL13fmt_amplitude)>>2)]=0;var $183=$q;var $arrayidx243=(($183+4)&4294967295);HEAP32[(($arrayidx243)>>2)]=0;__Z8WcmdqIncv();;}
var $184=$total_len;$retval=$184;;}}
var $185=$retval;STACKTOP=__stackBase__;return $185;return null;}
function __ZL11SmoothSpectv(){;var __label__;var __lastLabel__=null;var $q;var $frame;var $frame2;var $frame1;var $frame_centre;var $ix;var $len;var $pk;var $modified;var $allowed;var $diff;var $f1;var $f2;var $f1142;var $f2143;var $0=HEAP32[((__ZL14syllable_start)>>2)];var $1=HEAP32[((__ZL12syllable_end)>>2)];var $cmp=((($0))|0)==((($1))|0);if($cmp){__label__=58;;}else{__label__=1;;}
$return$$if_end$2:do{if(__label__==1){var $2=HEAP32[((__ZL15syllable_centre)>>2)];var $cmp1=((($2))|0)<0;if($cmp1){__label__=3;;}else{__label__=2;;}
$if_then3$$lor_lhs_false$4:do{if(__label__==2){var $3=HEAP32[((__ZL15syllable_centre)>>2)];var $4=HEAP32[((__ZL14syllable_start)>>2)];var $cmp2=((($3))|0)==((($4))|0);if($cmp2){__label__=3;break $if_then3$$lor_lhs_false$4;}
var $6=HEAP32[((__ZL15syllable_centre)>>2)];var $arrayidx=((_wcmdq+$6*16)&4294967295);var $arraydecay=(($arrayidx)&4294967295);$q=$arraydecay;var $7=$q;var $arrayidx5=(($7+8)&4294967295);var $8=HEAP32[(($arrayidx5)>>2)];var $9=($8);$frame_centre=$9;var $10=HEAP32[((__ZL15syllable_centre)>>2)];var $sub=((($10)-1)&4294967295);$ix=$sub;var $11=$frame_centre;$frame2=$11;$frame=$11;__lastLabel__=4;;$for_cond$7:while(1){var $12=__lastLabel__==30?$dec:($sub);var $cmp6=((($12))|0)<0;if($cmp6){__label__=6;;}else{__label__=7;;}
if(__label__==6){$ix=159;;}
var $13=$ix;var $arrayidx9=((_wcmdq+$13*16)&4294967295);var $arraydecay10=(($arrayidx9)&4294967295);$q=$arraydecay10;var $14=$q;var $arrayidx11=(($14)&4294967295);var $15=HEAP32[(($arrayidx11)>>2)];var $cmp12=((($15))|0)==5;if($cmp12){__label__=31;break $for_cond$7;}
var $16=$q;var $arrayidx14=(($16)&4294967295);var $17=HEAP32[(($arrayidx14)>>2)];var $cmp15=((($17))|0)==6;if($cmp15){__label__=31;break $for_cond$7;}
var $18=$q;var $arrayidx18=(($18)&4294967295);var $19=HEAP32[(($arrayidx18)>>2)];var $cmp19=((($19))|0)<=4;if($cmp19){__label__=10;;}else{__label__=29;;}
$if_then20$$if_end95$14:do{if(__label__==10){var $20=$q;var $arrayidx21=(($20+4)&4294967295);var $21=HEAP32[(($arrayidx21)>>2)];var $and=($21)&65535;$len=$and;var $22=$q;var $arrayidx22=(($22+12)&4294967295);var $23=HEAP32[(($arrayidx22)>>2)];var $24=($23);$frame1=$24;var $25=$frame1;var $26=$frame;var $cmp23=((($25))|0)==((($26))|0);if(!($cmp23)){__label__=31;break $for_cond$7;}
var $27=$frame2;var $28=($27);var $29=$q;var $arrayidx25=(($29+12)&4294967295);HEAP32[(($arrayidx25)>>2)]=$28;var $30=$frame2;$frame1=$30;var $31=$q;var $arrayidx27=(($31+8)&4294967295);var $32=HEAP32[(($arrayidx27)>>2)];var $33=($32);$frame2=$33;$frame=$33;$modified=0;var $34=$frame;var $frflags=(($34)&4294967295);var $35=HEAP16[(($frflags)>>1)];var $conv=(tempInt=(($35)),(tempInt>=32768?tempInt-65536:tempInt));var $and28=($conv)&16;var $tobool=((($and28))|0)!=0;if($tobool){__label__=31;break $for_cond$7;}
var $36=$frame;var $frflags31=(($36)&4294967295);var $37=HEAP16[(($frflags31)>>1)];var $conv32=(tempInt=(($37)),(tempInt>=32768?tempInt-65536:tempInt));var $and33=($conv32)&32;var $tobool34=((($and33))|0)!=0;if($tobool34){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $38=$len;var $mul=((($38)*12)&4294967295);var $div=((((($mul))|0)/10)|0);$len=$div;;}
$pk=0;;$for_body$21:while(1){var $39=$frame;var $frflags39=(($39)&4294967295);var $40=HEAP16[(($frflags39)>>1)];var $conv40=(tempInt=(($40)),(tempInt>=32768?tempInt-65536:tempInt));var $and41=($conv40)&8;var $tobool42=((($and41))|0)!=0;if($tobool42){__label__=16;;}else{__label__=17;;}
$land_lhs_true$$if_end45$23:do{if(__label__==16){var $41=$pk;var $cmp43=((($41))|0)<3;if($cmp43){__label__=28;break $land_lhs_true$$if_end45$23;}else{__label__=17;break $land_lhs_true$$if_end45$23;}}}while(0);$for_inc$$if_end45$25:do{if(__label__==17){var $42=$pk;var $43=$frame1;var $ffreq=(($43+2)&4294967295);var $arrayidx46=(($ffreq+$42*2)&4294967295);var $44=HEAP16[(($arrayidx46)>>1)];var $conv47=(tempInt=(($44)),(tempInt>=32768?tempInt-65536:tempInt));$f1=$conv47;var $45=$pk;var $46=$frame;var $ffreq48=(($46+2)&4294967295);var $arrayidx49=(($ffreq48+$45*2)&4294967295);var $47=HEAP16[(($arrayidx49)>>1)];var $conv50=(tempInt=(($47)),(tempInt>=32768?tempInt-65536:tempInt));$f2=$conv50;var $48=$f2;var $49=$f1;var $sub51=((($48)-($49))&4294967295);$diff=$sub51;var $cmp52=((($sub51))|0)>0;var $50=$f1;if($cmp52){__label__=18;;}else{__label__=19;;}
if(__label__==18){var $mul54=((($50)*2)&4294967295);var $51=$f2;var $add=((($51)+($mul54))&4294967295);$allowed=$add;;}
else if(__label__==19){var $52=$f2;var $mul56=((($52)*2)&4294967295);var $add57=((($mul56)+($50))&4294967295);$allowed=$add57;;}
var $53=$allowed;var $54=$pk;var $arrayidx59=((_formant_rate+$54*4)&4294967295);var $55=HEAP32[(($arrayidx59)>>2)];var $mul60=((($55)*($53))&4294967295);var $div61=((((($mul60))|0)/3000)|0);$allowed=$div61;var $56=$allowed;var $57=$len;var $mul62=((($57)*($56))&4294967295);var $div63=((((($mul62))|0)/256)|0);$allowed=$div63;var $58=$diff;var $59=$allowed;var $cmp64=((($58))|0)>((($59))|0);if($cmp64){__label__=21;;}else{__label__=24;;}
if(__label__==21){var $60=$modified;var $cmp66=((($60))|0)==0;if($cmp66){__label__=22;;}else{__label__=23;;}
if(__label__==22){var $61=$frame;var $call=__ZL9CopyFrameP7frame_ti($61,0);$frame2=$call;$modified=1;;}
var $62=$pk;var $63=$frame1;var $ffreq69=(($63+2)&4294967295);var $arrayidx70=(($ffreq69+$62*2)&4294967295);var $64=HEAP16[(($arrayidx70)>>1)];var $conv71=(tempInt=(($64)),(tempInt>=32768?tempInt-65536:tempInt));var $65=$allowed;var $add72=((($conv71)+($65))&4294967295);var $conv73=((($add72))&65535);var $66=$pk;var $67=$frame2;var $ffreq74=(($67+2)&4294967295);var $arrayidx75=(($ffreq74+$66*2)&4294967295);HEAP16[(($arrayidx75)>>1)]=$conv73;var $68=$frame2;var $69=($68);var $70=$q;var $arrayidx76=(($70+8)&4294967295);HEAP32[(($arrayidx76)>>2)]=$69;;}
else if(__label__==24){var $71=$diff;var $72=$allowed;var $sub78=(((-($72)))&4294967295);var $cmp79=((($71))|0)<((($sub78))|0);if(!($cmp79)){__label__=28;break $for_inc$$if_end45$25;}
var $73=$modified;var $cmp81=((($73))|0)==0;if($cmp81){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $74=$frame;var $call83=__ZL9CopyFrameP7frame_ti($74,0);$frame2=$call83;$modified=1;;}
var $75=$pk;var $76=$frame1;var $ffreq85=(($76+2)&4294967295);var $arrayidx86=(($ffreq85+$75*2)&4294967295);var $77=HEAP16[(($arrayidx86)>>1)];var $conv87=(tempInt=(($77)),(tempInt>=32768?tempInt-65536:tempInt));var $78=$allowed;var $sub88=((($conv87)-($78))&4294967295);var $conv89=((($sub88))&65535);var $79=$pk;var $80=$frame2;var $ffreq90=(($80+2)&4294967295);var $arrayidx91=(($ffreq90+$79*2)&4294967295);HEAP16[(($arrayidx91)>>1)]=$conv89;var $81=$frame2;var $82=($81);var $83=$q;var $arrayidx92=(($83+8)&4294967295);HEAP32[(($arrayidx92)>>2)]=$82;;}}}while(0);var $84=$pk;var $inc=((($84)+1)&4294967295);$pk=$inc;var $cmp38=((($inc))|0)<6;if($cmp38){__label__=15;continue $for_body$21;}else{__label__=29;break $if_then20$$if_end95$14;}}}}while(0);var $85=$ix;var $86=HEAP32[((__ZL14syllable_start)>>2)];var $cmp96=((($85))|0)==((($86))|0);if($cmp96){__label__=31;break $for_cond$7;}
var $87=$ix;var $dec=((($87)-1)&4294967295);$ix=$dec;__lastLabel__=30;__label__=5;continue $for_cond$7;}
var $88=HEAP32[((__ZL15syllable_centre)>>2)];$ix=$88;$frame=0;;$for_cond100$45:while(1){var $89=$ix;var $arrayidx101=((_wcmdq+$89*16)&4294967295);var $arraydecay102=(($arrayidx101)&4294967295);$q=$arraydecay102;var $90=$q;var $arrayidx103=(($90)&4294967295);var $91=HEAP32[(($arrayidx103)>>2)];var $cmp104=((($91))|0)==5;if($cmp104){__label__=57;break $for_cond100$45;}
var $92=$q;var $arrayidx106=(($92)&4294967295);var $93=HEAP32[(($arrayidx106)>>2)];var $cmp107=((($93))|0)==6;if($cmp107){__label__=57;break $for_cond100$45;}
var $94=$q;var $arrayidx110=(($94)&4294967295);var $95=HEAP32[(($arrayidx110)>>2)];var $cmp111=((($95))|0)<=4;if($cmp111){__label__=35;;}else{__label__=54;;}
$if_then112$$if_end199$49:do{if(__label__==35){var $96=$q;var $arrayidx113=(($96+4)&4294967295);var $97=HEAP32[(($arrayidx113)>>2)];var $and114=($97)&65535;$len=$and114;var $98=$q;var $arrayidx115=(($98+8)&4294967295);var $99=HEAP32[(($arrayidx115)>>2)];var $100=($99);$frame1=$100;var $101=$frame;var $cmp116=((($101))|0)!=0;if($cmp116){__label__=36;;}else{__label__=38;;}
if(__label__==36){var $102=$frame1;var $103=$frame;var $cmp118=((($102))|0)==((($103))|0);if(!($cmp118)){__label__=57;break $for_cond100$45;}
var $104=$frame2;var $105=($104);var $106=$q;var $arrayidx120=(($106+8)&4294967295);HEAP32[(($arrayidx120)>>2)]=$105;var $107=$frame2;$frame1=$107;;}
var $108=$q;var $arrayidx124=(($108+12)&4294967295);var $109=HEAP32[(($arrayidx124)>>2)];var $110=($109);$frame2=$110;$frame=$110;$modified=0;var $111=$frame1;var $frflags125=(($111)&4294967295);var $112=HEAP16[(($frflags125)>>1)];var $conv126=(tempInt=(($112)),(tempInt>=32768?tempInt-65536:tempInt));var $and127=($conv126)&16;var $tobool128=((($and127))|0)!=0;if($tobool128){__label__=57;break $for_cond100$45;}
var $113=$frame1;var $frflags131=(($113)&4294967295);var $114=HEAP16[(($frflags131)>>1)];var $conv132=(tempInt=(($114)),(tempInt>=32768?tempInt-65536:tempInt));var $and133=($conv132)&32;var $tobool134=((($and133))|0)!=0;if($tobool134){__label__=40;;}else{__label__=41;;}
if(__label__==40){var $115=$len;var $mul136=((($115)*6)&4294967295);var $div137=((((($mul136))|0)/5)|0);$len=$div137;;}
$pk=0;;$for_body141$59:while(1){var $116=$pk;var $117=$frame1;var $ffreq144=(($117+2)&4294967295);var $arrayidx145=(($ffreq144+$116*2)&4294967295);var $118=HEAP16[(($arrayidx145)>>1)];var $conv146=(tempInt=(($118)),(tempInt>=32768?tempInt-65536:tempInt));$f1142=$conv146;var $119=$pk;var $120=$frame;var $ffreq147=(($120+2)&4294967295);var $arrayidx148=(($ffreq147+$119*2)&4294967295);var $121=HEAP16[(($arrayidx148)>>1)];var $conv149=(tempInt=(($121)),(tempInt>=32768?tempInt-65536:tempInt));$f2143=$conv149;var $122=$f2143;var $123=$f1142;var $sub150=((($122)-($123))&4294967295);$diff=$sub150;var $cmp151=((($sub150))|0)>0;var $124=$f1142;if($cmp151){__label__=43;;}else{__label__=44;;}
if(__label__==43){var $mul153=((($124)*2)&4294967295);var $125=$f2143;var $add154=((($125)+($mul153))&4294967295);$allowed=$add154;;}
else if(__label__==44){var $126=$f2143;var $mul156=((($126)*2)&4294967295);var $add157=((($mul156)+($124))&4294967295);$allowed=$add157;;}
var $127=$allowed;var $128=$pk;var $arrayidx159=((_formant_rate+$128*4)&4294967295);var $129=HEAP32[(($arrayidx159)>>2)];var $mul160=((($129)*($127))&4294967295);var $div161=((((($mul160))|0)/3000)|0);$allowed=$div161;var $130=$allowed;var $131=$len;var $mul162=((($131)*($130))&4294967295);var $div163=((((($mul162))|0)/256)|0);$allowed=$div163;var $132=$diff;var $133=$allowed;var $cmp164=((($132))|0)>((($133))|0);if($cmp164){__label__=46;;}else{__label__=49;;}
$if_then165$$if_else178$65:do{if(__label__==46){var $134=$modified;var $cmp166=((($134))|0)==0;if($cmp166){__label__=47;;}else{__label__=48;;}
if(__label__==47){var $135=$frame;var $call168=__ZL9CopyFrameP7frame_ti($135,0);$frame2=$call168;$modified=1;;}
var $136=$pk;var $137=$frame1;var $ffreq170=(($137+2)&4294967295);var $arrayidx171=(($ffreq170+$136*2)&4294967295);var $138=HEAP16[(($arrayidx171)>>1)];var $conv172=(tempInt=(($138)),(tempInt>=32768?tempInt-65536:tempInt));var $139=$allowed;var $add173=((($conv172)+($139))&4294967295);var $conv174=((($add173))&65535);var $140=$pk;var $141=$frame2;var $ffreq175=(($141+2)&4294967295);var $arrayidx176=(($ffreq175+$140*2)&4294967295);HEAP16[(($arrayidx176)>>1)]=$conv174;var $142=$frame2;var $143=($142);var $144=$q;var $arrayidx177=(($144+12)&4294967295);HEAP32[(($arrayidx177)>>2)]=$143;;}
else if(__label__==49){var $145=$diff;var $146=$allowed;var $sub179=(((-($146)))&4294967295);var $cmp180=((($145))|0)<((($sub179))|0);if(!($cmp180)){__label__=53;break $if_then165$$if_else178$65;}
var $147=$modified;var $cmp182=((($147))|0)==0;if($cmp182){__label__=51;;}else{__label__=52;;}
if(__label__==51){var $148=$frame;var $call184=__ZL9CopyFrameP7frame_ti($148,0);$frame2=$call184;$modified=1;;}
var $149=$pk;var $150=$frame1;var $ffreq186=(($150+2)&4294967295);var $arrayidx187=(($ffreq186+$149*2)&4294967295);var $151=HEAP16[(($arrayidx187)>>1)];var $conv188=(tempInt=(($151)),(tempInt>=32768?tempInt-65536:tempInt));var $152=$allowed;var $sub189=((($conv188)-($152))&4294967295);var $conv190=((($sub189))&65535);var $153=$pk;var $154=$frame2;var $ffreq191=(($154+2)&4294967295);var $arrayidx192=(($ffreq191+$153*2)&4294967295);HEAP16[(($arrayidx192)>>1)]=$conv190;var $155=$frame2;var $156=($155);var $157=$q;var $arrayidx193=(($157+12)&4294967295);HEAP32[(($arrayidx193)>>2)]=$156;;}}while(0);var $158=$pk;var $inc197=((($158)+1)&4294967295);$pk=$inc197;var $cmp140=((($inc197))|0)<6;if($cmp140){__label__=42;continue $for_body141$59;}else{__label__=54;break $if_then112$$if_end199$49;}}}}while(0);var $159=$ix;var $inc200=((($159)+1)&4294967295);$ix=$inc200;var $cmp201=((($inc200))|0)>=160;if($cmp201){__label__=55;;}else{__label__=56;;}
if(__label__==55){$ix=0;;}
var $160=$ix;var $161=HEAP32[((__ZL12syllable_end)>>2)];var $cmp204=((($160))|0)==((($161))|0);if($cmp204){__label__=57;break $for_cond100$45;}else{__label__=32;continue $for_cond100$45;}}
var $162=HEAP32[((__ZL12syllable_end)>>2)];HEAP32[((__ZL14syllable_start)>>2)]=$162;__label__=58;break $return$$if_end$2;}}while(0);var $5=HEAP32[((__ZL12syllable_end)>>2)];HEAP32[((__ZL14syllable_start)>>2)]=$5;;}}while(0);;return;return;}
function __Z8DoMarkeriiii($type,$char_posn,$length,$value){;var __label__;var $type_addr;var $char_posn_addr;var $length_addr;var $value_addr;$type_addr=$type;$char_posn_addr=$char_posn;$length_addr=$length;$value_addr=$value;var $0=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx=((_wcmdq+$0*16)&4294967295);var $arrayidx1=(($arrayidx)&4294967295);HEAP32[(($arrayidx1)>>2)]=10;var $1=$type_addr;var $2=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx2=((_wcmdq+$2*16)&4294967295);var $arrayidx3=(($arrayidx2+4)&4294967295);HEAP32[(($arrayidx3)>>2)]=$1;var $3=$char_posn_addr;var $and=($3)&16777215;var $4=$length_addr;var $shl=($4)<<24;var $or=($shl)|($and);var $5=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx4=((_wcmdq+$5*16)&4294967295);var $arrayidx5=(($arrayidx4+8)&4294967295);HEAP32[(($arrayidx5)>>2)]=$or;var $6=$value_addr;var $7=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx6=((_wcmdq+$7*16)&4294967295);var $arrayidx7=(($arrayidx6+12)&4294967295);HEAP32[(($arrayidx7)>>2)]=$6;__Z8WcmdqIncv();;return;return;}
function __Z12DoSonicSpeedi($value){;var __label__;var $value_addr;$value_addr=$value;var $0=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx=((_wcmdq+$0*16)&4294967295);var $arrayidx1=(($arrayidx)&4294967295);HEAP32[(($arrayidx1)>>2)]=15;var $1=$value_addr;var $2=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx2=((_wcmdq+$2*16)&4294967295);var $arrayidx3=(($arrayidx2+4)&4294967295);HEAP32[(($arrayidx3)>>2)]=$1;__Z8WcmdqIncv();;return;return;}
function __Z13DoVoiceChangeP7voice_t($v){;var __label__;var $v_addr;var $v2;$v_addr=$v;var $call=_malloc(1344);var $0=$call;$v2=$0;var $1=$v2;var $2=$1;var $3=$v_addr;var $4=$3;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$4;$dest$=$2;$stop$=$src$+1344;if(($dest$%4)==($src$%4)&&1344>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $5=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx=((_wcmdq+$5*16)&4294967295);var $arrayidx1=(($arrayidx)&4294967295);HEAP32[(($arrayidx1)>>2)]=11;var $6=$v2;var $7=($6);var $8=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx2=((_wcmdq+$8*16)&4294967295);var $arrayidx3=(($arrayidx2+4)&4294967295);HEAP32[(($arrayidx3)>>2)]=$7;__Z8WcmdqIncv();;return;return;}
function __Z10DoEmbeddedPii($embix,$sourceix){;var __label__;var $embix_addr;var $sourceix_addr;var $word;var $value;var $command;$embix_addr=$embix;$sourceix_addr=$sourceix;;$do_body$2:while(1){var $0=$embix_addr;var $1=HEAP32[(($0)>>2)];var $arrayidx=((_embedded_list+$1*4)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];$word=$2;var $3=$word;var $shr=($3)>>>8;$value=$shr;var $4=$word;var $and=($4)&127;$command=$and;var $cmp=((($and))|0)==0;if($cmp){__label__=11;break $do_body$2;}
var $5=$embix_addr;var $6=HEAP32[(($5)>>2)];var $inc=((($6)+1)&4294967295);HEAP32[(($5)>>2)]=$inc;var $7=$command;var $and1=($7)&31;if($and1==2){__label__=3;;}
else if($and1==7){__label__=4;;}
else if($and1==10){__label__=7;;}
else if($and1==11){__label__=8;;}
else{__label__=9;;}
$sw_default$$sw_bb$$sw_bb3$$sw_bb23$$sw_bb26$5:do{if(__label__==9){__ZL7DoPauseii(10,0);var $28=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx28=((_wcmdq+$28*16)&4294967295);var $arrayidx29=(($arrayidx28)&4294967295);HEAP32[(($arrayidx29)>>2)]=12;var $29=$command;var $30=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx30=((_wcmdq+$30*16)&4294967295);var $arrayidx31=(($arrayidx30+4)&4294967295);HEAP32[(($arrayidx31)>>2)]=$29;var $31=$value;var $32=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx32=((_wcmdq+$32*16)&4294967295);var $arrayidx33=(($arrayidx32+8)&4294967295);HEAP32[(($arrayidx33)>>2)]=$31;__Z8WcmdqIncv();;}
else if(__label__==3){var $8=$command;var $and2=($8)&96;var $add=((($and2)+8)&4294967295);var $9=$value;__Z11SetEmbeddedii($add,$9);__Z8SetSpeedi(2);;}
else if(__label__==4){var $10=$value;var $11=HEAP32[((_n_soundicon_tab)>>2)];var $cmp4=((($10))|0)<((($11))|0);if(!($cmp4)){__label__=10;break $sw_default$$sw_bb$$sw_bb3$$sw_bb23$$sw_bb26$5;}
var $12=$value;var $arrayidx6=((_soundicon_tab+$12*16)&4294967295);var $length=(($arrayidx6+4)&4294967295);var $13=HEAP32[(($length)>>2)];var $cmp7=((($13))|0)!=0;if(!($cmp7)){__label__=10;break $sw_default$$sw_bb$$sw_bb3$$sw_bb23$$sw_bb26$5;}
__ZL7DoPauseii(10,0);var $14=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx9=((_wcmdq+$14*16)&4294967295);var $arrayidx10=(($arrayidx9)&4294967295);HEAP32[(($arrayidx10)>>2)]=6;var $15=$value;var $arrayidx11=((_soundicon_tab+$15*16)&4294967295);var $length12=(($arrayidx11+4)&4294967295);var $16=HEAP32[(($length12)>>2)];var $17=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx13=((_wcmdq+$17*16)&4294967295);var $arrayidx14=(($arrayidx13+4)&4294967295);HEAP32[(($arrayidx14)>>2)]=$16;var $18=$value;var $arrayidx15=((_soundicon_tab+$18*16)&4294967295);var $data=(($arrayidx15+8)&4294967295);var $19=HEAP32[(($data)>>2)];var $20=($19);var $add16=((($20)+44)&4294967295);var $21=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx17=((_wcmdq+$21*16)&4294967295);var $arrayidx18=(($arrayidx17+8)&4294967295);HEAP32[(($arrayidx18)>>2)]=$add16;var $22=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx19=((_wcmdq+$22*16)&4294967295);var $arrayidx20=(($arrayidx19+12)&4294967295);HEAP32[(($arrayidx20)>>2)]=5376;__Z8WcmdqIncv();;}
else if(__label__==7){var $23=$sourceix_addr;var $and24=($23)&2047;var $24=HEAP32[((_clause_start_char)>>2)];var $add25=((($and24)+($24))&4294967295);var $25=$value;__Z8DoMarkeriiii(3,$add25,0,$25);;}
else if(__label__==8){var $26=HEAP32[((_count_characters)>>2)];var $add27=((($26)+1)&4294967295);var $27=$value;__Z8DoMarkeriiii(4,$add27,0,$27);;}}while(0);var $33=$word;var $and34=($33)&128;var $cmp35=((($and34))|0)==0;if($cmp35){__label__=1;continue $do_body$2;}else{__label__=11;break $do_body$2;}};return;return;}
function __Z8GenerateP12PHONEME_LISTPii($phoneme_list,$n_ph,$resume){var __stackBase__=STACKTOP;STACKTOP+=656;_memset(__stackBase__,0,656);var __label__;var $retval;var $phoneme_list_addr;var $n_ph_addr;var $resume_addr;var $prev;var $next;var $next2;var $p;var $released;var $stress;var $modulation;var $pre_voiced;var $free_min;var $pitch_env;var $amp_env;var $ph;var $prev_ph;var $phdata=__stackBase__;var $phdata_prev=__stackBase__+152;var $phdata_next=__stackBase__+304;var $phdata_tone=__stackBase__+456;var $fmtp=__stackBase__+608;$phoneme_list_addr=$phoneme_list;$n_ph_addr=$n_ph;$resume_addr=$resume;$pitch_env=0;var $0=HEAP32[((_option_quiet)>>2)];var $tobool=((($0))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $1=HEAP8[(((_mbrola_name)&4294967295))];var $conv=(tempInt=(($1)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)!=0;if($cmp){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $2=$phoneme_list_addr;var $3=$n_ph_addr;var $4=$resume_addr;var $call=__Z14MbrolaGenerateP12PHONEME_LISTPii($2,$3,$4);$retval=$call;;}
else if(__label__==4){var $5=$resume_addr;var $cmp3=((($5))|0)==0;if($cmp3){__label__=5;;}else{__label__=6;;}
if(__label__==5){HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE2ix)>>2)]=1;HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE11embedded_ix)>>2)]=0;HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE10word_count)>>2)]=0;HEAP32[((__ZL12pitch_length)>>2)]=0;HEAP32[((__ZL10amp_length)>>2)]=0;HEAP32[((__ZL10last_frame)>>2)]=0;HEAP32[((__ZL10last_wcmdq)>>2)]=-1;var $6=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL14syllable_start)>>2)]=$6;var $7=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL12syllable_end)>>2)]=$7;HEAP32[((__ZL15syllable_centre)>>2)]=-1;HEAP32[((__ZL14last_pitch_cmd)>>2)]=-1;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=_vowel_transition;$stop$=$dest$+16;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};__ZL7DoPauseii(0,0);;}
var $pd_control=(($phdata)&4294967295);var $8=$fmtp;var $fmt_control=(($fmtp)&4294967295);var $sound_addr=(($phdata+68)&4294967295);var $arrayidx173=(($sound_addr)&4294967295);var $fmt_addr=(($fmtp+8)&4294967295);var $sound_param=(($phdata+88)&4294967295);var $arrayidx174=(($sound_param)&4294967295);var $fmt_amp=(($fmtp+16)&4294967295);var $sound_addr199=(($phdata+68)&4294967295);var $arrayidx200=(($sound_addr199)&4294967295);var $fmt_addr201=(($fmtp+8)&4294967295);var $sound_param202=(($phdata+88)&4294967295);var $arrayidx203=(($sound_param202)&4294967295);var $fmt_amp204=(($fmtp+16)&4294967295);var $sound_addr205=(($phdata+68)&4294967295);var $arrayidx206=(($sound_addr205+16)&4294967295);var $wav_addr=(($fmtp+28)&4294967295);var $sound_param207=(($phdata+88)&4294967295);var $arrayidx208=(($sound_param207+16)&4294967295);var $wav_amp=(($fmtp+32)&4294967295);var $9=$fmtp;var $pd_param=(($phdata+4)&4294967295);var $arrayidx290=(($pd_param+40)&4294967295);var $std_length=(($fmtp+44)&4294967295);var $sound_addr291=(($phdata+68)&4294967295);var $arrayidx292=(($sound_addr291)&4294967295);var $fmt_addr293=(($fmtp+8)&4294967295);var $sound_param294=(($phdata+88)&4294967295);var $arrayidx295=(($sound_param294)&4294967295);var $fmt_amp296=(($fmtp+16)&4294967295);var $sound_addr297=(($phdata+68)&4294967295);var $arrayidx298=(($sound_addr297+16)&4294967295);var $wav_addr299=(($fmtp+28)&4294967295);var $sound_param300=(($phdata+88)&4294967295);var $arrayidx301=(($sound_param300+16)&4294967295);var $wav_amp302=(($fmtp+32)&4294967295);var $10=$fmtp;var $pd_param334=(($phdata+4)&4294967295);var $arrayidx335=(($pd_param334+40)&4294967295);var $std_length337=(($fmtp+44)&4294967295);var $sound_addr338=(($phdata+68)&4294967295);var $arrayidx339=(($sound_addr338)&4294967295);var $fmt_addr340=(($fmtp+8)&4294967295);var $sound_param341=(($phdata+88)&4294967295);var $arrayidx342=(($sound_param341)&4294967295);var $fmt_amp343=(($fmtp+16)&4294967295);var $11=$fmtp;var $pd_param400=(($phdata+4)&4294967295);var $arrayidx401=(($pd_param400+40)&4294967295);var $std_length403=(($fmtp+44)&4294967295);var $sound_addr404=(($phdata+68)&4294967295);var $arrayidx405=(($sound_addr404)&4294967295);var $fmt_addr406=(($fmtp+8)&4294967295);var $sound_param407=(($phdata+88)&4294967295);var $arrayidx408=(($sound_param407)&4294967295);var $fmt_amp409=(($fmtp+16)&4294967295);var $sound_addr410=(($phdata+68)&4294967295);var $arrayidx411=(($sound_addr410+16)&4294967295);var $wav_addr412=(($fmtp+28)&4294967295);var $sound_param413=(($phdata+88)&4294967295);var $arrayidx414=(($sound_param413+16)&4294967295);var $wav_amp415=(($fmtp+32)&4294967295);var $12=$fmtp;var $pd_param422=(($phdata+4)&4294967295);var $arrayidx423=(($pd_param422+40)&4294967295);var $std_length425=(($fmtp+44)&4294967295);var $sound_addr426=(($phdata+68)&4294967295);var $arrayidx427=(($sound_addr426+8)&4294967295);var $fmt_addr428=(($fmtp+8)&4294967295);var $pd_control431=(($phdata)&4294967295);var $sound_param435=(($phdata+88)&4294967295);var $arrayidx436=(($sound_param435+8)&4294967295);var $fmt_length=(($fmtp+12)&4294967295);var $fmt_addr455=(($fmtp+8)&4294967295);var $use_vowelin=(($fmtp+4)&4294967295);var $fmt_control458=(($fmtp)&4294967295);var $sound_addr459=(($phdata+68)&4294967295);var $arrayidx460=(($sound_addr459)&4294967295);var $fmt_addr461=(($fmtp+8)&4294967295);var $sound_param463=(($phdata+88)&4294967295);var $arrayidx464=(($sound_param463)&4294967295);var $fmt_amp465=(($fmtp+16)&4294967295);var $pitch_env474=(($phdata_tone+124)&4294967295);var $amp_env476=(($phdata_tone+128)&4294967295);var $amp_env479=(($phdata_tone+128)&4294967295);var $sound_addr542=(($phdata+68)&4294967295);var $arrayidx543=(($sound_addr542)&4294967295);var $fmt_addr544=(($fmtp+8)&4294967295);var $sound_param545=(($phdata+88)&4294967295);var $arrayidx546=(($sound_param545)&4294967295);var $fmt_amp547=(($fmtp+16)&4294967295);var $transition0548=(($fmtp+36)&4294967295);var $transition1549=(($fmtp+40)&4294967295);var $sound_addr550=(($phdata+68)&4294967295);var $arrayidx551=(($sound_addr550+12)&4294967295);var $fmt2_addr=(($fmtp+20)&4294967295);var $sound_param554=(($phdata+88)&4294967295);var $arrayidx555=(($sound_param554+12)&4294967295);var $fmt2_lenadj556=(($fmtp+24)&4294967295);var $fmt2_lenadj562=(($fmtp+24)&4294967295);var $use_vowelin563=(($fmtp+4)&4294967295);var $vowel_transition564=(($phdata_next+108)&4294967295);var $arrayidx565=(($vowel_transition564+8)&4294967295);var $transition0566=(($fmtp+36)&4294967295);var $vowel_transition567=(($phdata_next+108)&4294967295);var $arrayidx568=(($vowel_transition567+12)&4294967295);var $transition1569=(($fmtp+40)&4294967295);var $sound_addr570=(($phdata_next+68)&4294967295);var $arrayidx571=(($sound_addr570+12)&4294967295);var $fmt2_addr572=(($fmtp+20)&4294967295);var $sound_param575=(($phdata_next+88)&4294967295);var $arrayidx576=(($sound_param575+12)&4294967295);var $fmt2_lenadj577=(($fmtp+24)&4294967295);var $sound_addr442=(($phdata_prev+68)&4294967295);var $arrayidx443=(($sound_addr442+8)&4294967295);var $fmt_addr444=(($fmtp+8)&4294967295);var $sound_param447=(($phdata_prev+88)&4294967295);var $arrayidx448=(($sound_param447+8)&4294967295);var $fmt2_lenadj=(($fmtp+24)&4294967295);var $vowel_transition=(($phdata_prev+108)&4294967295);var $arrayidx450=(($vowel_transition)&4294967295);var $transition0=(($fmtp+36)&4294967295);var $vowel_transition451=(($phdata_prev+108)&4294967295);var $arrayidx452=(($vowel_transition451+4)&4294967295);var $transition1=(($fmtp+40)&4294967295);;$while_cond$11:while(1){var $13=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE2ix)>>2)];var $14=$n_ph_addr;var $15=HEAP32[(($14)>>2)];var $cmp6=((($13))|0)<((($15))|0);if(!($cmp6)){__label__=134;break $while_cond$11;}
var $16=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE2ix)>>2)];var $17=$phoneme_list_addr;var $arrayidx=(($17+24*$16)&4294967295);$p=$arrayidx;var $18=$p;var $type=(($18+15)&4294967295);var $19=HEAPU8[($type)];var $conv7=((($19))&255);var $cmp8=((($conv7))|0)==0;if($cmp8){__label__=9;;}else{__label__=10;;}
if(__label__==9){$free_min=5;;}
else if(__label__==10){var $20=$p;var $type10=(($20+15)&4294967295);var $21=HEAPU8[($type10)];var $conv11=((($21))&255);var $cmp12=((($conv11))|0)!=2;if($cmp12){__label__=11;;}else{__label__=12;;}
if(__label__==11){$free_min=10;;}
else if(__label__==12){$free_min=22;;}}
var $call17=__Z9WcmdqFreev();var $22=$free_min;var $cmp18=((($call17))|0)<=((($22))|0);if($cmp18){__label__=14;break $while_cond$11;}
var $23=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE2ix)>>2)];var $sub=((($23)-1)&4294967295);var $24=$phoneme_list_addr;var $arrayidx21=(($24+24*$sub)&4294967295);$prev=$arrayidx21;var $25=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE2ix)>>2)];var $add=((($25)+1)&4294967295);var $26=$phoneme_list_addr;var $arrayidx22=(($26+24*$add)&4294967295);$next=$arrayidx22;var $27=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE2ix)>>2)];var $add23=((($27)+2)&4294967295);var $28=$phoneme_list_addr;var $arrayidx24=(($28+24*$add23)&4294967295);$next2=$arrayidx24;var $29=$p;var $synthflags=(($29+4)&4294967295);var $30=HEAPU16[(($synthflags)>>1)];var $conv25=((($30))&65535);var $and=($conv25)&2;var $tobool26=((($and))|0)!=0;if($tobool26){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $31=$p;var $sourceix=(($31+6)&4294967295);var $32=HEAPU16[(($sourceix)>>1)];var $conv28=((($32))&65535);__Z10DoEmbeddedPii(__ZZ8GenerateP12PHONEME_LISTPiiE11embedded_ix,$conv28);;}
var $33=$p;var $newword=(($33+19)&4294967295);var $34=HEAP8[($newword)];var $tobool30=(tempInt=(($34)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool30){__label__=18;;}else{__label__=26;;}
$if_then31$$if_end63$25:do{if(__label__==18){var $35=$p;var $type32=(($35+15)&4294967295);var $36=HEAPU8[($type32)];var $conv33=((($36))&255);var $cmp34=((($conv33))|0)==2;if($cmp34){__label__=19;;}else{__label__=20;;}
$land_lhs_true$$lor_lhs_false$27:do{if(__label__==19){var $37=HEAP32[((_translator)>>2)];var $langopts=(($37)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx35=(($param+32)&4294967295);var $38=HEAP32[(($arrayidx35)>>2)];var $and36=($38)&1;var $tobool37=((($and36))|0)!=0;if($tobool37){__label__=22;break $land_lhs_true$$lor_lhs_false$27;}else{__label__=20;break $land_lhs_true$$lor_lhs_false$27;}}}while(0);$if_end43$$lor_lhs_false$29:do{if(__label__==20){var $39=$p;var $ph38=(($39+8)&4294967295);var $40=HEAP32[(($ph38)>>2)];var $phflags=(($40+4)&4294967295);var $41=HEAP32[(($phflags)>>2)];var $and39=($41)&16777216;var $tobool40=((($and39))|0)!=0;if($tobool40){__label__=22;break $if_end43$$lor_lhs_false$29;}
HEAP32[((__ZL10last_frame)>>2)]=0;;}}while(0);var $42=$p;var $sourceix44=(($42+6)&4294967295);var $43=HEAPU16[(($sourceix44)>>1)];var $conv45=((($43))&65535);var $and46=($conv45)&2047;var $44=HEAP32[((_clause_start_char)>>2)];var $add47=((($and46)+($44))&4294967295);HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE8sourceix)>>2)]=$add47;var $45=$p;var $newword48=(($45+19)&4294967295);var $46=HEAPU8[($newword48)];var $conv49=((($46))&255);var $and50=($conv49)&4;var $tobool51=((($and50))|0)!=0;if($tobool51){__label__=23;;}else{__label__=24;;}
if(__label__==23){var $47=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE8sourceix)>>2)];var $48=HEAP32[((_count_sentences)>>2)];__Z8DoMarkeriiii(2,$47,0,$48);;}
var $49=$p;var $newword54=(($49+19)&4294967295);var $50=HEAPU8[($newword54)];var $conv55=((($50))&255);var $and56=($conv55)&1;var $tobool57=((($and56))|0)!=0;if(!($tobool57)){__label__=26;break $if_then31$$if_end63$25;}
var $51=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE8sourceix)>>2)];var $52=$p;var $sourceix59=(($52+6)&4294967295);var $53=HEAPU16[(($sourceix59)>>1)];var $conv60=((($53))&65535);var $shr=($conv60)>>11;var $54=HEAP32[((_clause_start_word)>>2)];var $55=HEAPU32[((__ZZ8GenerateP12PHONEME_LISTPiiE10word_count)>>2)];var $inc=((($55)+1)&4294967295);HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE10word_count)>>2)]=$inc;var $add61=((($55)+($54))&4294967295);__Z8DoMarkeriiii(1,$51,$shr,$add61);;}}while(0);__ZL12EndAmplitudev();var $56=$p;var $prepause=(($56+16)&4294967295);var $57=HEAPU8[($prepause)];var $conv64=((($57))&255);var $cmp65=((($conv64))|0)>0;if($cmp65){__label__=27;;}else{__label__=28;;}
if(__label__==27){var $58=$p;var $prepause67=(($58+16)&4294967295);var $59=HEAPU8[($prepause67)];var $conv68=((($59))&255);__ZL7DoPauseii($conv68,1);;}
var $60=HEAP32[((_option_phoneme_events)>>2)];var $tobool70=((($60))|0)!=0;if($tobool70){__label__=29;;}else{__label__=31;;}
$land_lhs_true71$$if_end77$41:do{if(__label__==29){var $61=$p;var $type72=(($61+15)&4294967295);var $62=HEAPU8[($type72)];var $conv73=((($62))&255);var $cmp74=((($conv73))|0)!=2;if(!($cmp74)){__label__=31;break $land_lhs_true71$$if_end77$41;}
var $63=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE8sourceix)>>2)];var $64=$p;var $ph76=(($64+8)&4294967295);var $65=HEAP32[(($ph76)>>2)];var $mnemonic=(($65)&4294967295);var $66=HEAP32[(($mnemonic)>>2)];__Z8DoMarkeriiii(7,$63,0,$66);;}}while(0);var $67=$p;var $type78=(($67+15)&4294967295);var $68=HEAPU8[($type78)];var $conv79=((($68))&255);if($conv79==0){__label__=32;;}
else if($conv79==4){__label__=33;;}
else if($conv79==6){__label__=41;;}
else if($conv79==5){__label__=44;;}
else if($conv79==7){__label__=67;;}
else if($conv79==8){__label__=81;;}
else if($conv79==3){__label__=91;;}
else if($conv79==2){__label__=100;;}
else{__label__=133;;}
$sw_epilog$$sw_bb$$sw_bb81$$sw_bb105$$sw_bb118$$sw_bb229$$sw_bb313$$sw_bb367$$sw_bb418$45:do{if(__label__==32){var $69=$p;var $length=(($69+12)&4294967295);var $70=HEAP16[(($length)>>1)];var $conv80=(tempInt=(($70)),(tempInt>=32768?tempInt-65536:tempInt));__ZL7DoPauseii($conv80,0);;}
else if(__label__==33){$released=0;var $71=$next;var $type82=(($71+15)&4294967295);var $72=HEAPU8[($type82)];var $conv83=((($72))&255);var $cmp84=((($conv83))|0)==2;if($cmp84){__label__=34;;}else{__label__=35;;}
$if_then85$$if_else86$48:do{if(__label__==34){$released=1;;}
else if(__label__==35){var $73=$next;var $newword87=(($73+19)&4294967295);var $74=HEAP8[($newword87)];var $tobool88=(tempInt=(($74)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool88){__label__=38;;}else{__label__=36;;}
$if_end96$$if_then89$51:do{if(__label__==36){var $75=$next;var $type90=(($75+15)&4294967295);var $76=HEAPU8[($type90)];var $conv91=((($76))&255);var $cmp92=((($conv91))|0)==3;if(!($cmp92)){__label__=38;break $if_end96$$if_then89$51;}
$released=1;__label__=40;break $if_then85$$if_else86$48;}}while(0);var $_pr=$released;var $cmp97=((($_pr))|0)==0;if(!($cmp97)){__label__=40;break $if_then85$$if_else86$48;}
var $77=$p;var $synthflags99=(($77+4)&4294967295);var $78=HEAPU16[(($synthflags99)>>1)];var $conv100=((($78))&65535);var $or=($conv100)|8192;var $conv101=((($or))&65535);HEAP16[(($synthflags99)>>1)]=$conv101;;}}while(0);var $79=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$79,$phdata);var $80=HEAP32[(($pd_control)>>2)];var $or103=($80)|4;HEAP32[(($pd_control)>>2)]=$or103;var $call104=__Z9DoSample3P12PHONEME_DATAii($phdata,0,0);;}
else if(__label__==41){var $81=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$81,$phdata);var $82=$p;var $synthflags106=(($82+4)&4294967295);var $83=HEAPU16[(($synthflags106)>>1)];var $conv107=((($83))&65535);var $and108=($conv107)&8;var $tobool109=((($and108))|0)!=0;if($tobool109){__label__=42;;}else{__label__=43;;}
if(__label__==42){var $84=$p;var $length111=(($84+12)&4294967295);var $85=HEAP16[(($length111)>>1)];var $conv112=(tempInt=(($85)),(tempInt>=32768?tempInt-65536:tempInt));var $call113=__Z9DoSample3P12PHONEME_DATAii($phdata,$conv112,0);;}
var $86=$p;var $length115=(($86+12)&4294967295);var $87=HEAP16[(($length115)>>1)];var $conv116=(tempInt=(($87)),(tempInt>=32768?tempInt-65536:tempInt));var $call117=__Z9DoSample3P12PHONEME_DATAii($phdata,$conv116,0);;}
else if(__label__==44){var $88=$p;var $ph119=(($88+8)&4294967295);var $89=HEAP32[(($ph119)>>2)];$ph=$89;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$8;$stop$=$dest$+48;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};HEAP32[(($fmt_control)>>2)]=4;$pre_voiced=0;var $90=$next;var $type120=(($90+15)&4294967295);var $91=HEAPU8[($type120)];var $conv121=((($91))&255);var $cmp122=((($conv121))|0)==2;if($cmp122){__label__=45;;}else{__label__=46;;}
$if_then123$$if_else128$62:do{if(__label__==45){var $92=$p;var $amp=(($92+18)&4294967295);var $93=HEAPU8[($amp)];var $conv124=((($93))&255);__ZL11DoAmplitudeiPh($conv124,0);var $94=$p;var $env=(($94+14)&4294967295);var $95=HEAPU8[($env)];var $idxprom=((($95))&255);var $arrayidx125=((_envelope_data+$idxprom*4)&4294967295);var $96=HEAP32[(($arrayidx125)>>2)];var $97=$p;var $pitch1=(($97+20)&4294967295);var $98=HEAPU8[($pitch1)];var $conv126=((($98))&255);var $99=$p;var $pitch2=(($99+21)&4294967295);var $100=HEAPU8[($pitch2)];var $conv127=((($100))&255);__ZL7DoPitchPhii($96,$conv126,$conv127);$pre_voiced=1;;}
else if(__label__==46){var $101=$next;var $type129=(($101+15)&4294967295);var $102=HEAPU8[($type129)];var $conv130=((($102))&255);var $cmp131=((($conv130))|0)==3;if($cmp131){__label__=47;;}else{__label__=49;;}
$land_lhs_true132$$if_else145$65:do{if(__label__==47){var $103=$next;var $newword133=(($103+19)&4294967295);var $104=HEAP8[($newword133)];var $tobool134=(tempInt=(($104)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool134){__label__=49;break $land_lhs_true132$$if_else145$65;}
var $105=$next;var $amp136=(($105+18)&4294967295);var $106=HEAPU8[($amp136)];var $conv137=((($106))&255);__ZL11DoAmplitudeiPh($conv137,0);var $107=$next;var $env138=(($107+14)&4294967295);var $108=HEAPU8[($env138)];var $idxprom139=((($108))&255);var $arrayidx140=((_envelope_data+$idxprom139*4)&4294967295);var $109=HEAP32[(($arrayidx140)>>2)];var $110=$next;var $pitch1141=(($110+20)&4294967295);var $111=HEAPU8[($pitch1141)];var $conv142=((($111))&255);var $112=$next;var $pitch2143=(($112+21)&4294967295);var $113=HEAPU8[($pitch2143)];var $conv144=((($113))&255);__ZL7DoPitchPhii($109,$conv142,$conv144);$pre_voiced=1;__label__=51;break $if_then123$$if_else128$62;}}while(0);var $114=HEAP32[((__ZL14last_pitch_cmd)>>2)];var $cmp146=((($114))|0)<0;if(!($cmp146)){__label__=51;break $if_then123$$if_else128$62;}
var $115=$next;var $amp148=(($115+18)&4294967295);var $116=HEAPU8[($amp148)];var $conv149=((($116))&255);__ZL11DoAmplitudeiPh($conv149,0);var $117=$p;var $env150=(($117+14)&4294967295);var $118=HEAPU8[($env150)];var $idxprom151=((($118))&255);var $arrayidx152=((_envelope_data+$idxprom151*4)&4294967295);var $119=HEAP32[(($arrayidx152)>>2)];var $120=$p;var $pitch1153=(($120+20)&4294967295);var $121=HEAPU8[($pitch1153)];var $conv154=((($121))&255);var $122=$p;var $pitch2155=(($122+21)&4294967295);var $123=HEAPU8[($pitch2155)];var $conv156=((($123))&255);__ZL7DoPitchPhii($119,$conv154,$conv156);;}}while(0);var $124=$prev;var $type160=(($124+15)&4294967295);var $125=HEAPU8[($type160)];var $conv161=((($125))&255);var $cmp162=((($conv161))|0)==2;if($cmp162){__label__=54;;}else{__label__=52;;}
$if_then172$$lor_lhs_false163$71:do{if(__label__==52){var $126=$prev;var $ph164=(($126+8)&4294967295);var $127=HEAP32[(($ph164)>>2)];var $phflags165=(($127+4)&4294967295);var $128=HEAP32[(($phflags165)>>2)];var $and166=($128)&256;var $tobool167=((($and166))|0)!=0;if($tobool167){__label__=54;break $if_then172$$lor_lhs_false163$71;}
var $129=$ph;var $phflags169=(($129+4)&4294967295);var $130=HEAP32[(($phflags169)>>2)];var $and170=($130)&33554432;var $tobool171=((($and170))|0)!=0;if($tobool171){__label__=54;break $if_then172$$lor_lhs_false163$71;}
var $140=$p;var $synthflags184=(($140+4)&4294967295);var $141=HEAPU16[(($synthflags184)>>1)];var $conv185=((($141))&65535);var $and186=($conv185)&8;var $tobool187=((($and186))|0)!=0;if(!($tobool187)){__label__=58;break $if_then172$$lor_lhs_false163$71;}
__ZL7DoPauseii(50,0);__label__=58;break $if_then172$$lor_lhs_false163$71;}}while(0);$if_then172$$if_end190$76:do{if(__label__==54){var $131=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,1,$131,$phdata);var $132=HEAP32[(($arrayidx173)>>2)];HEAP32[(($fmt_addr)>>2)]=$132;var $133=HEAP32[(($arrayidx174)>>2)];HEAP32[(($fmt_amp)>>2)]=$133;var $134=$ph;var $135=$p;var $call175=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($134,0,$fmtp,$135,0);var $136=$p;var $synthflags176=(($136+4)&4294967295);var $137=HEAPU16[(($synthflags176)>>1)];var $conv177=((($137))&65535);var $and178=($conv177)&8;var $tobool179=((($and178))|0)!=0;if(!($tobool179)){__label__=58;break $if_then172$$if_end190$76;}
__ZL7DoPauseii(25,1);var $138=$ph;var $139=$p;var $call181=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($138,0,$fmtp,$139,0);;}}while(0);var $142=$pre_voiced;var $tobool191=((($142))|0)!=0;if($tobool191){__label__=59;;}else{__label__=60;;}
if(__label__==59){__ZL13StartSyllablev();;}
else if(__label__==60){var $143=$p;var $synthflags194=(($143+4)&4294967295);var $144=HEAPU16[(($synthflags194)>>1)];var $conv195=((($144))&65535);var $or196=($conv195)|8192;var $conv197=((($or196))&65535);HEAP16[(($synthflags194)>>1)]=$conv197;;}
var $145=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$145,$phdata);var $146=HEAP32[(($arrayidx200)>>2)];HEAP32[(($fmt_addr201)>>2)]=$146;var $147=HEAP32[(($arrayidx203)>>2)];HEAP32[(($fmt_amp204)>>2)]=$147;var $148=HEAP32[(($arrayidx206)>>2)];HEAP32[(($wav_addr)>>2)]=$148;var $149=HEAP32[(($arrayidx208)>>2)];HEAP32[(($wav_amp)>>2)]=$149;var $150=$ph;var $151=$p;var $call209=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($150,0,$fmtp,$151,0);var $152=$p;var $newword210=(($152+19)&4294967295);var $153=HEAPU8[($newword210)];var $conv211=((($153))&255);var $cmp212=((($conv211))|0)==0;if(!($cmp212)){__label__=133;break $sw_epilog$$sw_bb$$sw_bb81$$sw_bb105$$sw_bb118$$sw_bb229$$sw_bb313$$sw_bb367$$sw_bb418$45;}
var $154=$next2;var $newword214=(($154+19)&4294967295);var $155=HEAPU8[($newword214)];var $conv215=((($155))&255);var $cmp216=((($conv215))|0)==0;if(!($cmp216)){__label__=133;break $sw_epilog$$sw_bb$$sw_bb81$$sw_bb105$$sw_bb118$$sw_bb229$$sw_bb313$$sw_bb367$$sw_bb418$45;}
var $156=$next;var $type218=(($156+15)&4294967295);var $157=HEAPU8[($type218)];var $conv219=((($157))&255);var $cmp220=((($conv219))|0)==7;if($cmp220){__label__=64;;}else{__label__=65;;}
if(__label__==64){__ZL7DoPauseii(20,0);;}
var $158=$next;var $type223=(($158+15)&4294967295);var $159=HEAPU8[($type223)];var $conv224=((($159))&255);var $cmp225=((($conv224))|0)==6;if(!($cmp225)){__label__=133;break $sw_epilog$$sw_bb$$sw_bb81$$sw_bb105$$sw_bb118$$sw_bb229$$sw_bb313$$sw_bb367$$sw_bb418$45;}
__ZL7DoPauseii(12,0);;}
else if(__label__==67){var $160=$next;var $type230=(($160+15)&4294967295);var $161=HEAPU8[($type230)];var $conv231=((($161))&255);var $cmp232=((($conv231))|0)==2;if($cmp232){__label__=68;;}else{__label__=69;;}
$if_then233$$if_else243$91:do{if(__label__==68){var $162=$p;var $amp234=(($162+18)&4294967295);var $163=HEAPU8[($amp234)];var $conv235=((($163))&255);__ZL11DoAmplitudeiPh($conv235,0);var $164=$p;var $env236=(($164+14)&4294967295);var $165=HEAPU8[($env236)];var $idxprom237=((($165))&255);var $arrayidx238=((_envelope_data+$idxprom237*4)&4294967295);var $166=HEAP32[(($arrayidx238)>>2)];var $167=$p;var $pitch1239=(($167+20)&4294967295);var $168=HEAPU8[($pitch1239)];var $conv240=((($168))&255);var $169=$p;var $pitch2241=(($169+21)&4294967295);var $170=HEAPU8[($pitch2241)];var $conv242=((($170))&255);__ZL7DoPitchPhii($166,$conv240,$conv242);;}
else if(__label__==69){var $171=$next;var $type244=(($171+15)&4294967295);var $172=HEAPU8[($type244)];var $conv245=((($172))&255);var $cmp246=((($conv245))|0)==3;if($cmp246){__label__=70;;}else{__label__=71;;}
if(__label__==70){var $173=$next;var $amp248=(($173+18)&4294967295);var $174=HEAPU8[($amp248)];var $conv249=((($174))&255);__ZL11DoAmplitudeiPh($conv249,0);var $175=$next;var $env250=(($175+14)&4294967295);var $176=HEAPU8[($env250)];var $idxprom251=((($176))&255);var $arrayidx252=((_envelope_data+$idxprom251*4)&4294967295);var $177=HEAP32[(($arrayidx252)>>2)];var $178=$next;var $pitch1253=(($178+20)&4294967295);var $179=HEAPU8[($pitch1253)];var $conv254=((($179))&255);var $180=$next;var $pitch2255=(($180+21)&4294967295);var $181=HEAPU8[($pitch2255)];var $conv256=((($181))&255);__ZL7DoPitchPhii($177,$conv254,$conv256);;}
else if(__label__==71){var $182=HEAP32[((__ZL14last_pitch_cmd)>>2)];var $cmp258=((($182))|0)<0;if(!($cmp258)){__label__=73;break $if_then233$$if_else243$91;}
var $183=$p;var $amp260=(($183+18)&4294967295);var $184=HEAPU8[($amp260)];var $conv261=((($184))&255);__ZL11DoAmplitudeiPh($conv261,0);var $185=$p;var $env262=(($185+14)&4294967295);var $186=HEAPU8[($env262)];var $idxprom263=((($186))&255);var $arrayidx264=((_envelope_data+$idxprom263*4)&4294967295);var $187=HEAP32[(($arrayidx264)>>2)];var $188=$p;var $pitch1265=(($188+20)&4294967295);var $189=HEAPU8[($pitch1265)];var $conv266=((($189))&255);var $190=$p;var $pitch2267=(($190+21)&4294967295);var $191=HEAPU8[($pitch2267)];var $conv268=((($191))&255);__ZL7DoPitchPhii($187,$conv266,$conv268);;}}}while(0);var $192=$next;var $type272=(($192+15)&4294967295);var $193=HEAPU8[($type272)];var $conv273=((($193))&255);var $cmp274=((($conv273))|0)==2;if($cmp274){__label__=76;;}else{__label__=74;;}
$if_then283$$lor_lhs_false275$99:do{if(__label__==74){var $194=$next;var $type276=(($194+15)&4294967295);var $195=HEAPU8[($type276)];var $conv277=((($195))&255);var $cmp278=((($conv277))|0)==3;if($cmp278){__label__=75;;}else{__label__=77;;}
if(__label__==75){var $196=$next;var $newword280=(($196+19)&4294967295);var $197=HEAPU8[($newword280)];var $conv281=((($197))&255);var $cmp282=((($conv281))|0)==0;if($cmp282){__label__=76;break $if_then283$$lor_lhs_false275$99;}}
var $198=$p;var $synthflags285=(($198+4)&4294967295);var $199=HEAPU16[(($synthflags285)>>1)];var $conv286=((($199))&65535);var $or287=($conv286)|8192;var $conv288=((($or287))&65535);HEAP16[(($synthflags285)>>1)]=$conv288;__label__=78;break $if_then283$$lor_lhs_false275$99;}}while(0);if(__label__==76){__ZL13StartSyllablev();;}
var $200=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$200,$phdata);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$9;$stop$=$dest$+48;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $201=HEAP32[(($arrayidx290)>>2)];var $mul=((($201)*2)&4294967295);HEAP32[(($std_length)>>2)]=$mul;var $202=HEAP32[(($arrayidx292)>>2)];HEAP32[(($fmt_addr293)>>2)]=$202;var $203=HEAP32[(($arrayidx295)>>2)];HEAP32[(($fmt_amp296)>>2)]=$203;var $204=HEAP32[(($arrayidx298)>>2)];HEAP32[(($wav_addr299)>>2)]=$204;var $205=HEAP32[(($arrayidx301)>>2)];HEAP32[(($wav_amp302)>>2)]=$205;var $206=$p;var $synthflags303=(($206+4)&4294967295);var $207=HEAPU16[(($synthflags303)>>1)];var $conv304=((($207))&65535);var $and305=($conv304)&8;var $tobool306=((($and305))|0)!=0;if($tobool306){__label__=79;;}else{__label__=80;;}
if(__label__==79){var $208=$p;var $ph308=(($208+8)&4294967295);var $209=HEAP32[(($ph308)>>2)];var $210=$p;var $call309=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($209,0,$fmtp,$210,0);;}
var $211=$p;var $ph311=(($211+8)&4294967295);var $212=HEAP32[(($ph311)>>2)];var $213=$p;var $call312=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($212,0,$fmtp,$213,0);;}
else if(__label__==81){var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$10;$stop$=$dest$+48;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $214=$p;var $synthflags314=(($214+4)&4294967295);var $215=HEAPU16[(($synthflags314)>>1)];var $conv315=((($215))&65535);var $and316=($conv315)&1;var $tobool317=((($and316))|0)!=0;if($tobool317){__label__=83;;}else{__label__=82;;}
if(__label__==82){var $216=$p;var $amp319=(($216+18)&4294967295);var $217=HEAPU8[($amp319)];var $conv320=((($217))&255);__ZL11DoAmplitudeiPh($conv320,0);var $218=$p;var $env321=(($218+14)&4294967295);var $219=HEAPU8[($env321)];var $idxprom322=((($219))&255);var $arrayidx323=((_envelope_data+$idxprom322*4)&4294967295);var $220=HEAP32[(($arrayidx323)>>2)];var $221=$p;var $pitch1324=(($221+20)&4294967295);var $222=HEAPU8[($pitch1324)];var $conv325=((($222))&255);var $223=$p;var $pitch2326=(($223+21)&4294967295);var $224=HEAPU8[($pitch2326)];var $conv327=((($224))&255);__ZL7DoPitchPhii($220,$conv325,$conv327);;}
var $225=$prev;var $type329=(($225+15)&4294967295);var $226=HEAPU8[($type329)];var $conv330=((($226))&255);var $cmp331=((($conv330))|0)==8;if($cmp331){__label__=84;;}else{__label__=85;;}
if(__label__==84){HEAP32[((__ZL10last_frame)>>2)]=0;;}
var $227=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$227,$phdata);var $228=HEAP32[(($arrayidx335)>>2)];var $mul336=((($228)*2)&4294967295);HEAP32[(($std_length337)>>2)]=$mul336;var $229=HEAP32[(($arrayidx339)>>2)];HEAP32[(($fmt_addr340)>>2)]=$229;var $230=HEAP32[(($arrayidx342)>>2)];HEAP32[(($fmt_amp343)>>2)]=$230;var $231=$next;var $type344=(($231+15)&4294967295);var $232=HEAPU8[($type344)];var $conv345=((($232))&255);var $cmp346=((($conv345))|0)==2;if($cmp346){__label__=86;;}else{__label__=87;;}
if(__label__==86){__ZL13StartSyllablev();var $233=$p;var $ph348=(($233+8)&4294967295);var $234=HEAP32[(($ph348)>>2)];var $235=$p;var $call349=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($234,0,$fmtp,$235,0);;}
else if(__label__==87){var $236=$prev;var $type351=(($236+15)&4294967295);var $237=HEAPU8[($type351)];var $conv352=((($237))&255);var $cmp353=((($conv352))|0)==2;if($cmp353){__label__=88;;}else{__label__=90;;}
$land_lhs_true354$$if_else362$120:do{if(__label__==88){var $238=$p;var $synthflags355=(($238+4)&4294967295);var $239=HEAPU16[(($synthflags355)>>1)];var $conv356=((($239))&65535);var $and357=($conv356)&1;var $tobool358=((($and357))|0)!=0;if(!($tobool358)){__label__=90;break $land_lhs_true354$$if_else362$120;}
var $240=$p;var $ph360=(($240+8)&4294967295);var $241=HEAP32[(($ph360)>>2)];var $242=$p;var $call361=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($241,0,$fmtp,$242,0);__label__=133;break $sw_epilog$$sw_bb$$sw_bb81$$sw_bb105$$sw_bb118$$sw_bb229$$sw_bb313$$sw_bb367$$sw_bb418$45;}}while(0);HEAP32[((__ZL10last_frame)>>2)]=0;var $243=$p;var $ph363=(($243+8)&4294967295);var $244=HEAP32[(($ph363)>>2)];var $245=$p;var $call364=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($244,0,$fmtp,$245,0);HEAP32[((__ZL10last_frame)>>2)]=0;;}}
else if(__label__==91){var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$11;$stop$=$dest$+48;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};$modulation=0;var $246=$p;var $ph368=(($246+8)&4294967295);var $247=HEAP32[(($ph368)>>2)];var $phflags369=(($247+4)&4294967295);var $248=HEAP32[(($phflags369)>>2)];var $and370=($248)&128;var $tobool371=((($and370))|0)!=0;if($tobool371){__label__=92;;}else{__label__=93;;}
if(__label__==92){$modulation=5;;}
var $249=$prev;var $ph374=(($249+8)&4294967295);var $250=HEAP32[(($ph374)>>2)];$prev_ph=$250;var $251=$p;var $synthflags375=(($251+4)&4294967295);var $252=HEAPU16[(($synthflags375)>>1)];var $conv376=((($252))&65535);var $and377=($conv376)&1;var $tobool378=((($and377))|0)!=0;if($tobool378){__label__=95;;}else{__label__=94;;}
if(__label__==94){var $253=$p;var $amp380=(($253+18)&4294967295);var $254=HEAPU8[($amp380)];var $conv381=((($254))&255);__ZL11DoAmplitudeiPh($conv381,0);var $255=$p;var $env382=(($255+14)&4294967295);var $256=HEAPU8[($env382)];var $idxprom383=((($256))&255);var $arrayidx384=((_envelope_data+$idxprom383*4)&4294967295);var $257=HEAP32[(($arrayidx384)>>2)];var $258=$p;var $pitch1385=(($258+20)&4294967295);var $259=HEAPU8[($pitch1385)];var $conv386=((($259))&255);var $260=$p;var $pitch2387=(($260+21)&4294967295);var $261=HEAPU8[($pitch2387)];var $conv388=((($261))&255);__ZL7DoPitchPhii($257,$conv386,$conv388);;}
var $262=$prev;var $type390=(($262+15)&4294967295);var $263=HEAPU8[($type390)];var $conv391=((($263))&255);var $cmp392=((($conv391))|0)==8;if($cmp392){__label__=96;;}else{__label__=97;;}
if(__label__==96){HEAP32[((__ZL10last_frame)>>2)]=0;;}
var $264=$next;var $type395=(($264+15)&4294967295);var $265=HEAPU8[($type395)];var $conv396=((($265))&255);var $cmp397=((($conv396))|0)==2;if($cmp397){__label__=98;;}else{__label__=99;;}
if(__label__==98){__ZL13StartSyllablev();;}
var $266=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$266,$phdata);var $267=HEAP32[(($arrayidx401)>>2)];var $mul402=((($267)*2)&4294967295);HEAP32[(($std_length403)>>2)]=$mul402;var $268=HEAP32[(($arrayidx405)>>2)];HEAP32[(($fmt_addr406)>>2)]=$268;var $269=HEAP32[(($arrayidx408)>>2)];HEAP32[(($fmt_amp409)>>2)]=$269;var $270=HEAP32[(($arrayidx411)>>2)];HEAP32[(($wav_addr412)>>2)]=$270;var $271=HEAP32[(($arrayidx414)>>2)];HEAP32[(($wav_amp415)>>2)]=$271;var $272=$p;var $ph416=(($272+8)&4294967295);var $273=HEAP32[(($ph416)>>2)];var $274=$p;var $275=$modulation;var $call417=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($273,0,$fmtp,$274,$275);;}
else if(__label__==100){var $276=$p;var $ph419=(($276+8)&4294967295);var $277=HEAP32[(($ph419)>>2)];$ph=$277;var $278=$p;var $stresslevel=(($278+1)&4294967295);var $279=HEAPU8[($stresslevel)];var $conv420=((($279))&255);var $and421=($conv420)&15;$stress=$and421;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$12;$stop$=$dest$+48;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $280=$p;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$280,$phdata);var $281=HEAP32[(($arrayidx423)>>2)];var $mul424=((($281)*2)&4294967295);HEAP32[(($std_length425)>>2)]=$mul424;var $282=HEAP32[(($arrayidx427)>>2)];HEAP32[(($fmt_addr428)>>2)]=$282;var $cmp429=((($282))|0)!=0;if($cmp429){__label__=101;;}else{__label__=103;;}
$land_lhs_true430$$if_else437$138:do{if(__label__==101){var $283=HEAP32[(($pd_control431)>>2)];var $and432=($283)&2;var $cmp433=((($and432))|0)==0;if(!($cmp433)){__label__=103;break $land_lhs_true430$$if_else437$138;}
var $284=HEAP32[(($arrayidx436)>>2)];HEAP32[(($fmt_length)>>2)]=$284;__label__=107;break $land_lhs_true430$$if_else437$138;}}while(0);$if_end454$$if_else437$141:do{if(__label__==103){var $285=$prev;var $type438=(($285+15)&4294967295);var $286=HEAPU8[($type438)];var $conv439=((($286))&255);var $cmp440=((($conv439))|0)!=0;if(!($cmp440)){__label__=107;break $if_end454$$if_else437$141;}
var $287=$prev;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$287,$phdata_prev);var $288=HEAP32[(($arrayidx443)>>2)];HEAP32[(($fmt_addr444)>>2)]=$288;var $cmp445=((($288))|0)!=0;if($cmp445){__label__=105;;}else{__label__=106;;}
if(__label__==105){var $289=HEAP32[(($arrayidx448)>>2)];HEAP32[(($fmt2_lenadj)>>2)]=$289;;}
var $290=HEAP32[(($arrayidx450)>>2)];HEAP32[(($transition0)>>2)]=$290;var $291=HEAP32[(($arrayidx452)>>2)];HEAP32[(($transition1)>>2)]=$291;;}}while(0);var $292=HEAP32[(($fmt_addr455)>>2)];var $cmp456=((($292))|0)==0;if($cmp456){__label__=108;;}else{__label__=109;;}
if(__label__==108){HEAP32[(($use_vowelin)>>2)]=1;HEAP32[(($fmt_control458)>>2)]=1;var $293=HEAP32[(($arrayidx460)>>2)];HEAP32[(($fmt_addr461)>>2)]=$293;;}
var $294=HEAP32[(($arrayidx464)>>2)];HEAP32[(($fmt_amp465)>>2)]=$294;var $295=$p;var $env466=(($295+14)&4294967295);var $296=HEAPU8[($env466)];var $idxprom467=((($296))&255);var $arrayidx468=((_envelope_data+$idxprom467*4)&4294967295);var $297=HEAP32[(($arrayidx468)>>2)];$pitch_env=$297;$amp_env=0;var $298=$p;var $tone_ph=(($298+3)&4294967295);var $299=HEAPU8[($tone_ph)];var $conv469=((($299))&255);var $cmp470=((($conv469))|0)!=0;if($cmp470){__label__=110;;}else{__label__=112;;}
$if_then471$$if_end482$151:do{if(__label__==110){var $300=$p;var $tone_ph472=(($300+3)&4294967295);var $301=HEAPU8[($tone_ph472)];var $conv473=((($301))&255);__Z17InterpretPhoneme2iP12PHONEME_DATA($conv473,$phdata_tone);var $302=HEAP32[(($pitch_env474)>>2)];var $call475=__Z11GetEnvelopei($302);$pitch_env=$call475;var $303=HEAP32[(($amp_env476)>>2)];var $cmp477=((($303))|0)>0;if(!($cmp477)){__label__=112;break $if_then471$$if_end482$151;}
var $304=HEAP32[(($amp_env479)>>2)];var $call480=__Z11GetEnvelopei($304);$amp_env=$call480;;}}while(0);__ZL13StartSyllablev();$modulation=2;var $305=$stress;var $cmp483=((($305))|0)<=1;if($cmp483){__label__=113;;}else{__label__=114;;}
$if_then484$$if_else485$155:do{if(__label__==113){$modulation=1;;}
else if(__label__==114){var $306=$stress;var $cmp486=((($306))|0)>=7;if(!($cmp486)){__label__=116;break $if_then484$$if_else485$155;}
$modulation=3;;}}while(0);var $307=$prev;var $type490=(($307+15)&4294967295);var $308=HEAPU8[($type490)];var $conv491=((($308))&255);var $cmp492=((($conv491))|0)==5;if($cmp492){__label__=118;;}else{__label__=117;;}
$if_then497$$lor_lhs_false493$160:do{if(__label__==117){var $309=$prev;var $type494=(($309+15)&4294967295);var $310=HEAPU8[($type494)];var $conv495=((($310))&255);var $cmp496=((($conv495))|0)==7;if($cmp496){__label__=118;break $if_then497$$lor_lhs_false493$160;}
var $322=$prev;var $type506=(($322+15)&4294967295);var $323=HEAPU8[($type506)];var $conv507=((($323))&255);var $cmp508=((($conv507))|0)==3;if($cmp508){__label__=121;;}else{__label__=120;;}
$if_then513$$lor_lhs_false509$163:do{if(__label__==120){var $324=$prev;var $type510=(($324+15)&4294967295);var $325=HEAPU8[($type510)];var $conv511=((($325))&255);var $cmp512=((($conv511))|0)==8;if($cmp512){__label__=121;break $if_then513$$lor_lhs_false509$163;}
var $337=$p;var $synthflags522=(($337+4)&4294967295);var $338=HEAPU16[(($synthflags522)>>1)];var $conv523=((($338))&65535);var $and524=($conv523)&1;var $tobool525=((($and524))|0)!=0;if($tobool525){__label__=124;;}else{__label__=123;;}
if(__label__==123){var $339=$p;var $amp527=(($339+18)&4294967295);var $340=HEAPU8[($amp527)];var $conv528=((($340))&255);var $341=$amp_env;__ZL11DoAmplitudeiPh($conv528,$341);var $342=$pitch_env;var $343=$p;var $pitch1529=(($343+20)&4294967295);var $344=HEAPU8[($pitch1529)];var $conv530=((($344))&255);var $345=$p;var $pitch2531=(($345+21)&4294967295);var $346=HEAPU8[($pitch2531)];var $conv532=((($346))&255);__ZL7DoPitchPhii($342,$conv530,$conv532);;}
var $347=$ph;var $348=$p;var $349=$modulation;var $call534=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($347,1,$fmtp,$348,$349);__label__=125;break $if_then497$$lor_lhs_false493$160;}}while(0);var $326=$p;var $amp514=(($326+18)&4294967295);var $327=HEAPU8[($amp514)];var $conv515=((($327))&255);var $328=$amp_env;__ZL11DoAmplitudeiPh($conv515,$328);var $329=$ph;var $330=$p;var $331=$modulation;var $call516=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($329,1,$fmtp,$330,$331);var $332=$pitch_env;var $333=$p;var $pitch1517=(($333+20)&4294967295);var $334=HEAPU8[($pitch1517)];var $conv518=((($334))&255);var $335=$p;var $pitch2519=(($335+21)&4294967295);var $336=HEAPU8[($pitch2519)];var $conv520=((($336))&255);__ZL7DoPitchPhii($332,$conv518,$conv520);__label__=125;break $if_then497$$lor_lhs_false493$160;}}while(0);if(__label__==118){var $311=$p;var $amp498=(($311+18)&4294967295);var $312=HEAPU8[($amp498)];var $conv499=((($312))&255);var $313=$amp_env;__ZL11DoAmplitudeiPh($conv499,$313);var $314=$pitch_env;var $315=$p;var $pitch1500=(($315+20)&4294967295);var $316=HEAPU8[($pitch1500)];var $conv501=((($316))&255);var $317=$p;var $pitch2502=(($317+21)&4294967295);var $318=HEAPU8[($pitch2502)];var $conv503=((($318))&255);__ZL7DoPitchPhii($314,$conv501,$conv503);var $319=$ph;var $320=$p;var $321=$modulation;var $call504=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($319,1,$fmtp,$320,$321);;}
var $350=HEAP32[((_option_phoneme_events)>>2)];var $tobool537=((($350))|0)!=0;if($tobool537){__label__=126;;}else{__label__=127;;}
if(__label__==126){var $351=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE8sourceix)>>2)];var $352=$p;var $ph539=(($352+8)&4294967295);var $353=HEAP32[(($ph539)>>2)];var $mnemonic540=(($353)&4294967295);var $354=HEAP32[(($mnemonic540)>>2)];__Z8DoMarkeriiii(7,$351,0,$354);;}
var $355=HEAP32[(($arrayidx543)>>2)];HEAP32[(($fmt_addr544)>>2)]=$355;var $356=HEAP32[(($arrayidx546)>>2)];HEAP32[(($fmt_amp547)>>2)]=$356;HEAP32[(($transition0548)>>2)]=0;HEAP32[(($transition1549)>>2)]=0;var $357=HEAP32[(($arrayidx551)>>2)];HEAP32[(($fmt2_addr)>>2)]=$357;var $cmp552=((($357))|0)!=0;if($cmp552){__label__=128;;}else{__label__=129;;}
$if_then553$$if_else557$176:do{if(__label__==128){var $358=HEAP32[(($arrayidx555)>>2)];HEAP32[(($fmt2_lenadj556)>>2)]=$358;;}
else if(__label__==129){var $359=$next;var $type558=(($359+15)&4294967295);var $360=HEAPU8[($type558)];var $conv559=((($360))&255);var $cmp560=((($conv559))|0)!=0;if(!($cmp560)){__label__=132;break $if_then553$$if_else557$176;}
HEAP32[(($fmt2_lenadj562)>>2)]=0;var $361=$next;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA(0,0,$361,$phdata_next);HEAP32[(($use_vowelin563)>>2)]=1;var $362=HEAP32[(($arrayidx565)>>2)];HEAP32[(($transition0566)>>2)]=$362;var $363=HEAP32[(($arrayidx568)>>2)];HEAP32[(($transition1569)>>2)]=$363;var $364=HEAP32[(($arrayidx571)>>2)];HEAP32[(($fmt2_addr572)>>2)]=$364;var $cmp573=((($364))|0)!=0;if(!($cmp573)){__label__=132;break $if_then553$$if_else557$176;}
var $365=HEAP32[(($arrayidx576)>>2)];HEAP32[(($fmt2_lenadj577)>>2)]=$365;;}}while(0);var $366=$ph;var $367=$p;var $368=$modulation;var $call581=__Z8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTi($366,2,$fmtp,$367,$368);;}}while(0);var $369=HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE2ix)>>2)];var $inc582=((($369)+1)&4294967295);HEAP32[((__ZZ8GenerateP12PHONEME_LISTPiiE2ix)>>2)]=$inc582;__label__=7;continue $while_cond$11;}
if(__label__==134){__ZL8EndPitchi(1);var $370=$n_ph_addr;var $371=HEAP32[(($370)>>2)];var $cmp583=((($371))|0)>0;if($cmp583){__label__=135;;}else{__label__=136;;}
if(__label__==135){var $372=HEAP32[((_count_characters)>>2)];var $373=HEAP32[((_count_sentences)>>2)];__Z8DoMarkeriiii(5,$372,0,$373);var $374=$n_ph_addr;HEAP32[(($374)>>2)]=0;;}
$retval=0;;}
else if(__label__==14){$retval=1;;}}}
var $375=$retval;STACKTOP=__stackBase__;return $375;return null;}
function __ZL12EndAmplitudev(){;var __label__;var $0=HEAP32[((__ZL10amp_length)>>2)];var $cmp=((($0))|0)>0;if($cmp){__label__=1;;}else{__label__=4;;}
if(__label__==1){var $1=HEAP32[((__ZL12last_amp_cmd)>>2)];var $arrayidx=((_wcmdq+$1*16)&4294967295);var $arrayidx1=(($arrayidx+4)&4294967295);var $2=HEAP32[(($arrayidx1)>>2)];var $cmp2=((($2))|0)==0;if($cmp2){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $3=HEAP32[((__ZL10amp_length)>>2)];var $4=HEAP32[((__ZL12last_amp_cmd)>>2)];var $arrayidx4=((_wcmdq+$4*16)&4294967295);var $arrayidx5=(($arrayidx4+4)&4294967295);HEAP32[(($arrayidx5)>>2)]=$3;;}
HEAP32[((__ZL10amp_length)>>2)]=0;;};return;return;}
function __ZL11DoAmplitudeiPh($amp,$amp_env){;var __label__;var $amp_addr;var $amp_env_addr;var $q;$amp_addr=$amp;$amp_env_addr=$amp_env;var $0=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL12last_amp_cmd)>>2)]=$0;HEAP32[((__ZL10amp_length)>>2)]=0;var $1=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx=((_wcmdq+$1*16)&4294967295);var $arraydecay=(($arrayidx)&4294967295);$q=$arraydecay;var $2=$q;var $arrayidx1=(($2)&4294967295);HEAP32[(($arrayidx1)>>2)]=8;var $3=$q;var $arrayidx2=(($3+4)&4294967295);HEAP32[(($arrayidx2)>>2)]=0;var $4=$amp_env_addr;var $5=($4);var $6=$q;var $arrayidx3=(($6+8)&4294967295);HEAP32[(($arrayidx3)>>2)]=$5;var $7=$amp_addr;var $8=$q;var $arrayidx4=(($8+12)&4294967295);HEAP32[(($arrayidx4)>>2)]=$7;__Z8WcmdqIncv();;return;return;}
function __ZL7DoPitchPhii($env,$pitch1,$pitch2){;var __label__;var $env_addr;var $pitch1_addr;var $pitch2_addr;var $q;$env_addr=$env;$pitch1_addr=$pitch1;$pitch2_addr=$pitch2;__ZL8EndPitchi(0);var $0=$pitch1_addr;var $cmp=((($0))|0)==255;if($cmp){__label__=1;;}else{__label__=2;;}
$if_end_thread$$if_end$2:do{if(__label__==1){$pitch1_addr=55;$pitch2_addr=76;var $1=HEAP32[((((_envelope_data)&4294967295))>>2)];$env_addr=$1;var $2=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL14last_pitch_cmd)>>2)]=$2;HEAP32[((__ZL12pitch_length)>>2)]=0;;}
else if(__label__==2){var $_pr=$pitch2_addr;var $3=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL14last_pitch_cmd)>>2)]=$3;HEAP32[((__ZL12pitch_length)>>2)]=0;var $cmp1=((($_pr))|0)<0;if(!($cmp1)){__label__=4;break $if_end_thread$$if_end$2;}
$pitch2_addr=0;;}}while(0);var $4=HEAP32[((_wcmdq_tail)>>2)];var $arrayidx=((_wcmdq+$4*16)&4294967295);var $arraydecay=(($arrayidx)&4294967295);$q=$arraydecay;var $5=$q;var $arrayidx4=(($5)&4294967295);HEAP32[(($arrayidx4)>>2)]=9;var $6=$q;var $arrayidx5=(($6+4)&4294967295);HEAP32[(($arrayidx5)>>2)]=0;var $7=$env_addr;var $8=($7);var $9=$q;var $arrayidx6=(($9+8)&4294967295);HEAP32[(($arrayidx6)>>2)]=$8;var $10=$pitch1_addr;var $shl=((($10)*65536)&4294967295);var $11=$pitch2_addr;var $add=((($shl)+($11))&4294967295);var $12=$q;var $arrayidx7=(($12+12)&4294967295);HEAP32[(($arrayidx7)>>2)]=$add;__Z8WcmdqIncv();;return;return;}
function __ZL13StartSyllablev(){;var __label__;var $0=HEAP32[((__ZL12syllable_end)>>2)];var $1=HEAP32[((__ZL14syllable_start)>>2)];var $cmp=((($0))|0)==((($1))|0);if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=HEAP32[((_wcmdq_tail)>>2)];HEAP32[((__ZL12syllable_end)>>2)]=$2;;};return;return;}
function __Z12SynthOnTimerv(){;var __label__;var $retval;var $_b=HEAPU8[(__ZL8timer_on_b)];var $0=((($_b))&1);var $tobool=((($0))|0)!=0;if($tobool){__label__=2;;}else{__label__=1;;}
if(__label__==2){while(1){var $call1=__Z9WcmdqUsedv();var $call5=__Z8GenerateP12PHONEME_LISTPii(((_phoneme_list)&4294967295),_n_phoneme_list,1);var $cmp6=((($call5))|0)==0;if($cmp6){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $call8=__Z15SpeakNextClauseP7__sFILEPKvi(0,0,1);;}
var $1=HEAP32[((_skipping_text)>>2)];var $tobool10=((($1))|0)!=0;if($tobool10){__label__=2;continue;}else{__label__=5;break;}}
$retval=0;;}
else if(__label__==1){$retval=0;;}
var $2=$retval;;return $2;return null;}
function __Z15SpeakNextClauseP7__sFILEPKvi($f_in,$text_in,$control){var __stackBase__=STACKTOP;STACKTOP+=8;_memset(__stackBase__,0,8);var __label__;var __lastLabel__=null;var $retval;var $f_in_addr;var $text_in_addr;var $control_addr;var $clause_tone=__stackBase__;var $voice_change=__stackBase__+4;$f_in_addr=$f_in;$text_in_addr=$text_in;$control_addr=$control;var $0=$control_addr;var $cmp=((($0))|0)==4;if($cmp){__label__=1;;}else{__label__=4;;}
$if_then$$if_end$2:do{if(__label__==1){var $1=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)];var $cmp1=((($1))|0)==0;var $2=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6p_text)>>2)];var $cmp2=((($2))|0)==0;var $or_cond=($cmp1)&($cmp2);if($or_cond){__label__=2;;}else{__label__=3;;}
if(__label__==2){$retval=0;;}
else if(__label__==3){$retval=1;;}}
else if(__label__==4){var $3=$control_addr;var $cmp4=((($3))|0)==2;if($cmp4){__label__=5;;}else{__label__=8;;}
if(__label__==5){HEAP8[(__ZL8timer_on_b)]=0;HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6p_text)>>2)]=0;var $4=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)];var $cmp6=((($4))|0)!=0;if($cmp6){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $5=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)];var $call=_fclose($5);HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)]=0;;}
HEAP32[((_n_phoneme_list)>>2)]=0;__Z9WcmdqStopv();HEAP32[((((_embedded_value+24)&4294967295))>>2)]=0;$retval=0;;}
else if(__label__==8){var $6=$control_addr;var $cmp10=((($6))|0)==3;if($cmp10){__label__=9;;}else{__label__=13;;}
if(__label__==9){var $_b=HEAPU8[(__ZL6paused_b)];var $7=($_b)?2:0;var $cmp12=((($7))|0)==0;if($cmp12){__label__=10;;}else{__label__=11;;}
if(__label__==10){HEAP8[(__ZL8timer_on_b)]=0;HEAP8[(__ZL6paused_b)]=1;;}
else if(__label__==11){HEAP8[(__ZL8timer_on_b)]=1;HEAP8[(__ZL6paused_b)]=0;var $call16=__Z8GenerateP12PHONEME_LISTPii(((_phoneme_list)&4294967295),_n_phoneme_list,0);;}
$retval=0;;}
else if(__label__==13){var $8=$control_addr;var $cmp19=((($8))|0)==5;if($cmp19){__label__=14;;}else{__label__=15;;}
if(__label__==14){HEAP32[((_n_phoneme_list)>>2)]=0;__Z9WcmdqStopv();$retval=0;;}
else if(__label__==15){var $9=$f_in_addr;var $cmp22=((($9))|0)!=0;if($cmp22){__label__=17;;}else{__label__=16;;}
$if_then24$$lor_lhs_false$24:do{if(__label__==16){var $10=$text_in_addr;var $cmp23=((($10))|0)!=0;if($cmp23){__label__=17;break $if_then24$$lor_lhs_false$24;}else{__label__=18;break $if_then24$$lor_lhs_false$24;}}}while(0);if(__label__==17){var $11=$f_in_addr;HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)]=$11;var $12=$text_in_addr;HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6p_text)>>2)]=$12;HEAP8[(__ZL8timer_on_b)]=1;HEAP8[(__ZL6paused_b)]=0;;}
var $13=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)];var $cmp26=((($13))|0)==0;var $14=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6p_text)>>2)];var $cmp28=((($14))|0)==0;var $or_cond1=($cmp26)&($cmp28);if($or_cond1){__label__=19;;}else{__label__=20;;}
if(__label__==19){HEAP32[((_skipping_text)>>2)]=0;HEAP8[(__ZL8timer_on_b)]=0;$retval=0;;}
else if(__label__==20){var $15=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)];var $cmp31=((($15))|0)!=0;if($cmp31){__label__=21;;}else{__label__=23;;}
$land_lhs_true32$$if_end36$32:do{if(__label__==21){var $16=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)];var $_flags=(($16+12)&4294967295);var $17=HEAP16[(($_flags)>>1)];var $conv=(tempInt=(($17)),(tempInt>=32768?tempInt-65536:tempInt));var $and=($conv)&32;var $cmp33=((($and))|0)!=0;if(!($cmp33)){__label__=23;break $land_lhs_true32$$if_end36$32;}
HEAP8[(__ZL8timer_on_b)]=0;var $18=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)];var $call35=_fclose($18);HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)]=0;$retval=0;__label__=39;break $if_then$$if_end$2;}}while(0);var $19=HEAP32[((_current_phoneme_table)>>2)];var $20=HEAP32[((_voice)>>2)];var $phoneme_tab_ix=(($20+40)&4294967295);var $21=HEAP32[(($phoneme_tab_ix)>>2)];var $cmp37=((($19))|0)!=((($21))|0);if($cmp37){__label__=24;;}else{__label__=25;;}
if(__label__==24){var $22=HEAP32[((_voice)>>2)];var $phoneme_tab_ix39=(($22+40)&4294967295);var $23=HEAP32[(($phoneme_tab_ix39)>>2)];__Z18SelectPhonemeTablei($23);;}
var $24=HEAP32[((_translator)>>2)];var $25=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text)>>2)];var $26=HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6p_text)>>2)];var $call41=__Z15TranslateClauseP10TranslatorP7__sFILEPKvPiPPc($24,$25,$26,$clause_tone,$voice_change);HEAP32[((__ZZ15SpeakNextClauseP7__sFILEPKviE6p_text)>>2)]=$call41;var $27=HEAP32[((_translator)>>2)];var $28=HEAP32[(($clause_tone)>>2)];__Z11CalcPitchesP10Translatori($27,$28);var $29=HEAP32[((_translator)>>2)];__Z11CalcLengthsP10Translator($29);var $30=HEAP32[((_option_phonemes)>>2)];var $cmp42=((($30))|0)>0;var $31=HEAP32[((_phoneme_callback)>>2)];var $cmp44=((($31))|0)!=0;var $or_cond2=($cmp42)|($cmp44);if($or_cond2){__label__=26;;}else{__label__=31;;}
$if_then45$$if_end62$39:do{if(__label__==26){var $32=HEAP32[((_translator)>>2)];var $phon_out=(($32+332)&4294967295);var $arraydecay=(($phon_out)&4294967295);__Z26GetTranslatedPhonemeStringPci($arraydecay,300);var $33=HEAP32[((_option_phonemes)>>2)];var $cmp46=((($33))|0)>0;if($cmp46){__label__=27;;}else{__label__=29;;}
$if_then47$$if_end55$41:do{if(__label__==27){var $34=HEAP32[((_f_trans)>>2)];var $35=HEAP32[((_translator)>>2)];var $phon_out48=(($35+332)&4294967295);var $arraydecay49=(($phon_out48)&4294967295);var $call50=_fprintf($34,((__str459)&4294967295),allocate([$arraydecay49,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $call51=_iswalpha(269);var $tobool=((($call51))|0)!=0;if($tobool){__label__=29;break $if_then47$$if_end55$41;}
var $36=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($36+12)&4294967295);var $37=HEAP32[(($_stderr)>>2)];var $38=_fwrite(((__str1460)&4294967295),88,1,$37);;}}while(0);var $39=HEAP32[((_phoneme_callback)>>2)];var $cmp56=((($39))|0)!=0;if(!($cmp56)){__label__=31;break $if_then45$$if_end62$39;}
var $40=HEAP32[((_phoneme_callback)>>2)];var $41=HEAP32[((_translator)>>2)];var $phon_out58=(($41+332)&4294967295);var $arraydecay59=(($phon_out58)&4294967295);var $call60=FUNCTION_TABLE[$40]($arraydecay59);;}}while(0);var $42=HEAP32[((_skipping_text)>>2)];var $tobool63=((($42))|0)!=0;if($tobool63){__label__=32;;}else{__label__=33;;}
if(__label__==32){HEAP32[((_n_phoneme_list)>>2)]=0;$retval=1;;}
else if(__label__==33){var $call66=__Z8GenerateP12PHONEME_LISTPii(((_phoneme_list)&4294967295),_n_phoneme_list,0);var $43=HEAP32[(($voice_change)>>2)];var $cmp68=((($43))|0)!=0;if($cmp68){__label__=34;;}else{__label__=35;;}
if(__label__==34){var $44=HEAP32[(($voice_change)>>2)];var $call70=__Z16LoadVoiceVariantPKci($44,0);HEAP32[((__ZL9new_voice)>>2)]=$call70;__lastLabel__=34;;}
else if(__label__==35){var $_pr=HEAP32[((__ZL9new_voice)>>2)];__lastLabel__=35;;}
var $45=__lastLabel__==35?$_pr:($call70);var $tobool72=((($45))|0)!=0;if($tobool72){__label__=37;;}else{__label__=38;;}
if(__label__==37){var $46=HEAP32[((_voice)>>2)];__Z13DoVoiceChangeP7voice_t($46);HEAP32[((__ZL9new_voice)>>2)]=0;;}
$retval=1;;}}}}}}}while(0);var $47=$retval;STACKTOP=__stackBase__;return $47;return null;}
function __Z11SynthStatusv(){;var __label__;var $_b=HEAPU8[(__ZL8timer_on_b)];var $0=((($_b))&1);var $_b1=HEAPU8[(__ZL6paused_b)];var $1=($_b1)?2:0;var $or=($1)|($0);;return $or;return null;}
function __ZL18formants_reduce_hfP7frame_ti($fr,$level){;var __label__;var $fr_addr;var $level_addr;var $ix;var $x;$fr_addr=$fr;$level_addr=$level;var $0=HEAP32[((_voice)>>2)];var $klattv=(($0+112)&4294967295);var $arrayidx=(($klattv)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];var $tobool=((($1))|0)!=0;if($tobool){__label__=3;;}else{__label__=1;;}
$for_end$$if_end$2:do{if(__label__==1){$ix=2;;while(1){var $2=$ix;var $3=$fr_addr;var $fheight=(($3+18)&4294967295);var $arrayidx1=(($fheight+$2)&4294967295);var $4=HEAPU8[($arrayidx1)];var $conv=((($4))&255);var $5=$level_addr;var $mul=((($conv)*($5))&4294967295);$x=$mul;var $6=$x;var $div=((((($6))|0)/100)|0);var $conv2=((($div))&255);var $7=$ix;var $8=$fr_addr;var $fheight3=(($8+18)&4294967295);var $arrayidx4=(($fheight3+$7)&4294967295);HEAP8[($arrayidx4)]=$conv2;var $9=$ix;var $inc=((($9)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<8;if($cmp){__label__=2;continue;}else{__label__=3;break $for_end$$if_end$2;}}}}while(0);;return;return;}
function __ZL10AllocFramev(){;var __label__;var $0=HEAP32[((__ZZL10AllocFramevE2ix)>>2)];var $inc=((($0)+1)&4294967295);HEAP32[((__ZZL10AllocFramevE2ix)>>2)]=$inc;var $cmp=((($inc))|0)>=160;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((__ZZL10AllocFramevE2ix)>>2)]=0;;}
var $1=HEAP32[((__ZZL10AllocFramevE2ix)>>2)];var $arrayidx=((__ZZL10AllocFramevE10frame_pool+$1*64)&4294967295);;return $arrayidx;return null;}
function __Z13SetLengthModsP10Translatori($tr,$value){;var __label__;var $tr_addr;var $value_addr;var $value2;$tr_addr=$tr;$value_addr=$value;var $0=$value_addr;var $rem=((($0))|0)%100;var $arrayidx=((__ZL15length_mod_tabs+$rem*4)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];var $2=$tr_addr;var $langopts=(($2)&4294967295);var $length_mods=(($langopts+176)&4294967295);HEAP32[(($length_mods)>>2)]=$1;var $3=$tr_addr;var $langopts1=(($3)&4294967295);var $length_mods0=(($langopts1+180)&4294967295);HEAP32[(($length_mods0)>>2)]=$1;var $4=$value_addr;var $div=((((($4))|0)/100)|0);$value2=$div;var $cmp=((($div))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $5=$value2;var $arrayidx2=((__ZL15length_mod_tabs+$5*4)&4294967295);var $6=HEAP32[(($arrayidx2)>>2)];var $7=$tr_addr;var $langopts3=(($7)&4294967295);var $length_mods04=(($langopts3+180)&4294967295);HEAP32[(($length_mods04)>>2)]=$6;;};return;return;}
function __Z7IsAlphaj($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $call=_iswalpha($0);var $tobool=((($call))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $1=$c_addr;var $cmp=((($1))>>>0)>=2305;var $2=$c_addr;var $cmp1=((($2))>>>0)<=3575;var $or_cond=($cmp)&($cmp1);var $3=$c_addr;if($or_cond){__label__=3;;}else{__label__=10;;}
if(__label__==3){var $and=($3)&127;var $cmp3=((($and))>>>0)<100;if($cmp3){__label__=4;;}else{__label__=5;;}
if(__label__==4){$retval=1;;}
else if(__label__==5){var $4=$c_addr;var $call6=__Z11lookupwcharPKti(((__ZZ7IsAlphajE18extra_indic_alphas)&4294967295),$4);var $cmp7=((($call6))|0)!=0;if($cmp7){__label__=6;;}else{__label__=7;;}
if(__label__==6){$retval=1;;}
else if(__label__==7){var $5=$c_addr;var $cmp10=((($5))>>>0)>=3450;var $6=$c_addr;var $cmp12=((($6))>>>0)<=3455;var $or_cond1=($cmp10)&($cmp12);if($or_cond1){__label__=8;;}else{__label__=9;;}
if(__label__==8){$retval=1;;}
else if(__label__==9){$retval=0;;}}}}
else if(__label__==10){var $cmp16=((($3))>>>0)>=1611;var $7=$c_addr;var $cmp18=((($7))>>>0)<=1630;var $or_cond2=($cmp16)&($cmp18);if($or_cond2){__label__=11;;}else{__label__=12;;}
if(__label__==11){$retval=1;;}
else if(__label__==12){var $8=$c_addr;var $cmp21=((($8))>>>0)>=768;var $9=$c_addr;var $cmp23=((($9))>>>0)<=879;var $or_cond3=($cmp21)&($cmp23);if($or_cond3){__label__=13;;}else{__label__=14;;}
if(__label__==13){$retval=1;;}
else if(__label__==14){var $10=$c_addr;var $cmp26=((($10))>>>0)>=1920;var $11=$c_addr;var $cmp28=((($11))>>>0)<=1969;var $or_cond4=($cmp26)&($cmp28);if($or_cond4){__label__=15;;}else{__label__=16;;}
if(__label__==15){$retval=1;;}
else if(__label__==16){var $12=$c_addr;var $cmp31=((($12))>>>0)>=4352;var $13=$c_addr;var $cmp33=((($13))>>>0)<=4607;var $or_cond5=($cmp31)&($cmp33);if($or_cond5){__label__=17;;}else{__label__=18;;}
if(__label__==17){$retval=1;;}
else if(__label__==18){var $14=$c_addr;var $cmp36=((($14))>>>0)>12352;var $15=$c_addr;var $cmp38=((($15))>>>0)<=42752;var $or_cond6=($cmp36)&($cmp38);if($or_cond6){__label__=19;;}else{__label__=20;;}
if(__label__==19){$retval=1;;}
else if(__label__==20){$retval=0;;}}}}}}}
var $16=$retval;;return $16;return null;}
function __Z11lookupwcharPKti($list,$c){;var __label__;var $retval;var $list_addr;var $c_addr;var $ix;$list_addr=$list;$c_addr=$c;$ix=0;;while(1){var $0=$ix;var $1=$list_addr;var $arrayidx=(($1+2*$0)&4294967295);var $2=HEAPU16[(($arrayidx)>>1)];var $conv=((($2))&65535);var $cmp=((($conv))|0)!=0;if(!($cmp)){__label__=5;break;}
var $3=$ix;var $4=$list_addr;var $arrayidx1=(($4+2*$3)&4294967295);var $5=HEAPU16[(($arrayidx1)>>1)];var $conv2=((($5))&65535);var $6=$c_addr;var $cmp3=((($conv2))|0)==((($6))|0);var $7=$ix;var $add=((($7)+1)&4294967295);if($cmp3){__label__=3;break;}
$ix=$add;__label__=1;continue;}
if(__label__==5){$retval=0;;}
else if(__label__==3){$retval=$add;;}
var $8=$retval;;return $8;return null;}
function __Z7IsDigitj($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $call=_iswdigit($0);var $tobool=((($call))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $1=$c_addr;var $cmp=((($1))>>>0)>=2406;var $2=$c_addr;var $cmp1=((($2))>>>0)<=2415;var $or_cond=($cmp)&($cmp1);if($or_cond){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=1;;}
else if(__label__==4){$retval=0;;}}
var $3=$retval;;return $3;return null;}
function __Z7IsSpacej($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $1=$c_addr;var $cmp1=((($1))>>>0)>=9472;var $2=$c_addr;var $cmp2=((($2))>>>0)<9632;var $or_cond=($cmp1)&($cmp2);if($or_cond){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=1;;}
else if(__label__==4){var $3=$c_addr;var $call=_iswspace($3);$retval=$call;;}}
var $4=$retval;;return $4;return null;}
function __Z16DeleteTranslatorP10Translator($tr){;var __label__;var $tr_addr;$tr_addr=$tr;var $0=$tr_addr;var $data_dictlist=(($0+1052)&4294967295);var $1=HEAP32[(($data_dictlist)>>2)];var $cmp=((($1))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=$tr_addr;var $data_dictlist1=(($2+1052)&4294967295);var $3=HEAP32[(($data_dictlist1)>>2)];__Z4FreePv($3);;}
var $4=$tr_addr;var $5=$4;__Z4FreePv($5);;return;return;}
function __Z9IsBracketi($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))|0)>=8212;var $1=$c_addr;var $cmp1=((($1))|0)<=8223;var $or_cond=($cmp)&($cmp1);if($or_cond){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $2=$c_addr;var $call=__Z11lookupwcharPKti(((__ZL8brackets)&4294967295),$2);$retval=$call;;}
var $3=$retval;;return $3;return null;}
function __Z8utf8_outjPc($c,$buf){;var __label__;var $retval;var $c_addr;var $buf_addr;var $n_bytes;var $j;var $shift;$c_addr=$c;$buf_addr=$buf;var $0=$c_addr;var $cmp=((($0))>>>0)<128;var $1=$c_addr;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $conv=((($1))&255);var $2=$buf_addr;var $arrayidx=(($2)&4294967295);HEAP8[($arrayidx)]=$conv;$retval=1;;}
else if(__label__==2){var $cmp1=((($1))>>>0)>=1114112;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $3=$buf_addr;var $arrayidx3=(($3)&4294967295);HEAP8[($arrayidx3)]=32;$retval=1;;}
else if(__label__==4){var $4=$c_addr;var $cmp5=((($4))>>>0)<2048;if($cmp5){__label__=5;;}else{__label__=6;;}
if(__label__==5){$n_bytes=1;;}
else if(__label__==6){var $5=$c_addr;var $cmp7=((($5))>>>0)<65536;if($cmp7){__label__=7;;}else{__label__=8;;}
if(__label__==7){$n_bytes=2;;}
else if(__label__==8){$n_bytes=3;;}}
var $6=$n_bytes;var $mul=((($6)*6)&4294967295);$shift=$mul;var $7=$n_bytes;var $arrayidx12=((__ZZ8utf8_outjPcE4code+$7)&4294967295);var $8=HEAPU8[($arrayidx12)];var $conv13=((($8))&255);var $9=$c_addr;var $10=$shift;var $shr=($9)>>>((($10))>>>0);var $or=($shr)|($conv13);var $conv14=((($or))&255);var $11=$buf_addr;var $arrayidx15=(($11)&4294967295);HEAP8[($arrayidx15)]=$conv14;$j=0;var $12=$j;var $13=$n_bytes;var $cmp161=((($12))|0)<((($13))|0);if($cmp161){__label__=10;;}else{__label__=11;;}
$for_body$$for_end$15:do{if(__label__==10){while(1){var $14=$shift;var $sub=((($14)-6)&4294967295);$shift=$sub;var $15=$c_addr;var $16=$shift;var $shr17=($15)>>>((($16))>>>0);var $and=($shr17)&63;var $add=((($and)+128)&4294967295);var $conv18=((($add))&255);var $17=$j;var $add19=((($17)+1)&4294967295);var $18=$buf_addr;var $arrayidx20=(($18+$add19)&4294967295);HEAP8[($arrayidx20)]=$conv18;var $19=$j;var $inc=((($19)+1)&4294967295);$j=$inc;var $20=$j;var $21=$n_bytes;var $cmp16=((($20))|0)<((($21))|0);if($cmp16){__label__=10;continue;}else{__label__=11;break $for_body$$for_end$15;}}}}while(0);var $22=$n_bytes;var $add21=((($22)+1)&4294967295);$retval=$add21;;}}
var $23=$retval;;return $23;return null;}
function __Z11utf8_nbytesPKc($buf){;var __label__;var $retval;var $buf_addr;var $c;$buf_addr=$buf;var $0=$buf_addr;var $arrayidx=(($0)&4294967295);var $1=HEAP8[($arrayidx)];$c=$1;var $2=$c;var $conv=((($2))&255);var $cmp=((($conv))|0)<128;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $3=$c;var $conv1=((($3))&255);var $cmp2=((($conv1))|0)<224;if($cmp2){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=2;;}
else if(__label__==4){var $4=$c;var $conv5=((($4))&255);var $cmp6=((($conv5))|0)<240;if($cmp6){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=3;;}
else if(__label__==6){$retval=4;;}}}
var $5=$retval;;return $5;return null;}
function __Z8utf8_in2PiPKci($c,$buf,$backwards){;var __label__;var $c_addr;var $buf_addr;var $backwards_addr;var $c1;var $n_bytes;var $ix;$c_addr=$c;$buf_addr=$buf;$backwards_addr=$backwards;var $0=$buf_addr;var $1=HEAP8[($0)];var $conv2=(tempInt=(($1)),(tempInt>=128?tempInt-256:tempInt));var $and3=($conv2)&192;var $cmp4=((($and3))|0)==128;if($cmp4){__label__=1;;}else{__label__=5;;}
$while_body$$while_end$2:do{if(__label__==1){while(1){var $2=$backwards_addr;var $tobool=((($2))|0)!=0;var $3=$buf_addr;if($tobool){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $incdec_ptr=(($3+-1)&4294967295);$buf_addr=$incdec_ptr;;}
else if(__label__==3){var $incdec_ptr1=(($3+1)&4294967295);$buf_addr=$incdec_ptr1;;}
var $4=$buf_addr;var $5=HEAP8[($4)];var $conv=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $and=($conv)&192;var $cmp=((($and))|0)==128;if($cmp){__label__=1;continue;}else{__label__=5;break $while_body$$while_end$2;}}}}while(0);$n_bytes=0;var $6=$buf_addr;var $incdec_ptr2=(($6+1)&4294967295);$buf_addr=$incdec_ptr2;var $7=HEAP8[($6)];var $conv3=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));$c1=$conv3;var $and4=($conv3)&128;var $tobool5=((($and4))|0)!=0;if($tobool5){__label__=6;;}else{__label__=14;;}
$if_then6$$if_end27$10:do{if(__label__==6){var $8=$c1;var $and7=($8)&224;var $cmp8=((($and7))|0)==192;if($cmp8){__label__=7;;}else{__label__=8;;}
$if_then9$$if_else10$12:do{if(__label__==7){$n_bytes=1;;}
else if(__label__==8){var $9=$c1;var $and11=($9)&240;var $cmp12=((($and11))|0)==224;if($cmp12){__label__=9;;}else{__label__=10;;}
if(__label__==9){$n_bytes=2;;}
else if(__label__==10){var $10=$c1;var $and15=($10)&248;var $cmp16=((($and15))|0)==240;if(!($cmp16)){__label__=12;break $if_then9$$if_else10$12;}
$n_bytes=3;;}}}while(0);var $11=$n_bytes;var $arrayidx=((__ZZ8utf8_in2PiPKciE4mask+$11)&4294967295);var $12=HEAPU8[($arrayidx)];var $conv21=((($12))&255);var $13=$c1;var $and22=($13)&($conv21);$c1=$and22;$ix=0;var $14=$ix;var $15=$n_bytes;var $cmp231=((($14))|0)<((($15))|0);if(!($cmp231)){__label__=14;break $if_then6$$if_end27$10;}
while(1){var $16=$c1;var $shl=((($16)*64)&4294967295);var $17=$buf_addr;var $incdec_ptr24=(($17+1)&4294967295);$buf_addr=$incdec_ptr24;var $18=HEAP8[($17)];var $conv25=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));var $and26=($conv25)&63;var $add=((($and26)+($shl))&4294967295);$c1=$add;var $19=$ix;var $inc=((($19)+1)&4294967295);$ix=$inc;var $20=$ix;var $21=$n_bytes;var $cmp23=((($20))|0)<((($21))|0);if($cmp23){__label__=13;continue;}else{__label__=14;break $if_then6$$if_end27$10;}}}}while(0);var $22=$c1;var $23=$c_addr;HEAP32[(($23)>>2)]=$22;var $24=$n_bytes;var $add28=((($24)+1)&4294967295);;return $add28;return null;}
function __Z7utf8_inPiPKc($c,$buf){;var __label__;var $c_addr;var $buf_addr;$c_addr=$c;$buf_addr=$buf;var $0=$c_addr;var $1=$buf_addr;var $call=__Z8utf8_in2PiPKci($0,$1,0);;return $call;return null;}
function __Z8strchr_wPKci($s,$c){;var __label__;var $retval;var $s_addr;var $c_addr;$s_addr=$s;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))|0)>=128;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $1=$s_addr;var $2=$c_addr;var $call=_strchr($1,$2);$retval=$call;;}
var $3=$retval;;return $3;return null;}
function __Z10IsAllUpperPKc($word){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $retval;var $word_addr;var $c=__stackBase__;$word_addr=$word;;while(1){var $0=$word_addr;var $1=HEAP8[($0)];var $conv=(tempInt=(($1)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)!=0;if(!($cmp)){__label__=5;break;}
var $2=$word_addr;var $3=HEAP8[($2)];var $conv1=(tempInt=(($3)),(tempInt>=128?tempInt-256:tempInt));var $call=__Z8isspace2j($conv1);var $tobool=((($call))|0)!=0;var $lnot=($tobool)^1;if(!($lnot)){__label__=5;break;}
var $4=$word_addr;var $call2=__Z7utf8_inPiPKc($c,$4);var $5=$word_addr;var $add_ptr=(($5+$call2)&4294967295);$word_addr=$add_ptr;var $6=HEAP32[(($c)>>2)];var $call3=_iswupper($6);var $tobool4=((($call3))|0)!=0;if($tobool4){__label__=1;continue;}else{__label__=4;break;}}
if(__label__==5){$retval=1;;}
else if(__label__==4){$retval=0;;}
var $7=$retval;STACKTOP=__stackBase__;return $7;return null;}
function __Z24ChangeEquivalentPhonemesP10TranslatoriPc($tr,$lang2,$phonemes){var __stackBase__=STACKTOP;STACKTOP+=160;_memset(__stackBase__,0,160);var __label__;var $retval;var $tr_addr;var $lang2_addr;var $phonemes_addr;var $ix;var $len;var $phon;var $p;var $pb;var $eqlist;var $p_out;var $p_in;var $remove_stress;var $phonbuf=__stackBase__;$tr_addr=$tr;$lang2_addr=$lang2;$phonemes_addr=$phonemes;$remove_stress=0;var $0=$tr_addr;var $phoneme_tab_ix=(($0+656)&4294967295);var $1=HEAP32[(($phoneme_tab_ix)>>2)];var $arrayidx=((_phoneme_tab_list+$1*48)&4294967295);var $equivalence_tables=(($arrayidx+44)&4294967295);var $2=HEAP32[(($equivalence_tables)>>2)];$ix=$2;var $cmp=((($2))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $3=$ix;var $4=HEAP32[((_phondata_ptr)>>2)];var $arrayidx1=(($4+$3)&4294967295);$pb=$arrayidx1;;$for_cond$5:while(1){var $5=$pb;var $arrayidx2=(($5)&4294967295);var $6=HEAPU8[($arrayidx2)];var $conv=((($6))&255);var $cmp3=((($conv))|0)==0;if($cmp3){__label__=4;break $for_cond$5;}
var $7=$pb;var $arrayidx6=(($7)&4294967295);var $8=HEAPU8[($arrayidx6)];var $conv7=((($8))&255);var $9=$lang2_addr;var $cmp8=((($conv7))|0)==((($9))|0);var $10=$pb;if($cmp8){__label__=7;break $for_cond$5;}
var $arrayidx11=(($10+2)&4294967295);var $11=HEAPU8[($arrayidx11)];var $conv12=((($11))&255);var $shl=((($conv12)*256)&4294967295);var $12=$pb;var $arrayidx13=(($12+3)&4294967295);var $13=HEAPU8[($arrayidx13)];var $conv14=((($13))&255);var $add=((($conv14)+($shl))&4294967295);$len=$add;var $14=$len;var $mul=((($14)*4)&4294967295);var $15=$pb;var $add_ptr=(($15+$mul)&4294967295);$pb=$add_ptr;__label__=3;continue $for_cond$5;}
if(__label__==4){$retval=0;;}
else if(__label__==7){var $arrayidx15=(($10+1)&4294967295);var $16=HEAPU8[($arrayidx15)];var $conv16=((($16))&255);$remove_stress=$conv16;var $17=HEAP32[((_option_phonemes)>>2)];var $cmp17=((($17))|0)==2;if($cmp17){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $18=$phonemes_addr;var $arraydecay=(($phonbuf)&4294967295);__Z14DecodePhonemesPKcPc($18,$arraydecay);var $19=HEAP32[((_f_trans)>>2)];var $20=$lang2_addr;var $arrayidx19=((_phoneme_tab_list+$20*48)&4294967295);var $name=(($arrayidx19)&4294967295);var $arraydecay20=(($name)&4294967295);var $arraydecay21=(($phonbuf)&4294967295);var $21=$tr_addr;var $phoneme_tab_ix22=(($21+656)&4294967295);var $22=HEAP32[(($phoneme_tab_ix22)>>2)];var $arrayidx23=((_phoneme_tab_list+$22*48)&4294967295);var $name24=(($arrayidx23)&4294967295);var $arraydecay25=(($name24)&4294967295);var $call=_fprintf($19,((__str543)&4294967295),allocate([$arraydecay20,0,0,0,$arraydecay21,0,0,0,$arraydecay25,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
var $23=$phonemes_addr;$p_in=$23;var $24=$pb;var $arrayidx27=(($24+8)&4294967295);$eqlist=$arrayidx27;var $arraydecay28=(($phonbuf)&4294967295);$p_out=$arraydecay28;var $25=$p_in;var $incdec_ptr1=(($25+1)&4294967295);$p_in=$incdec_ptr1;var $26=HEAP8[($25)];$phon=$26;var $conv292=(tempInt=(($26)),(tempInt>=128?tempInt-256:tempInt));var $cmp303=((($conv292))|0)!=0;if($cmp303){__label__=10;;}else{__label__=20;;}
$while_body$$while_end56$15:do{if(__label__==10){$while_body$16:while(1){var $27=$remove_stress;var $tobool=((($27))|0)!=0;if($tobool){__label__=11;;}else{__label__=13;;}
$land_lhs_true$$if_end34$18:do{if(__label__==11){var $28=$phon;var $conv31=(tempInt=(($28)),(tempInt>=128?tempInt-256:tempInt));var $and=($conv31)&255;var $cmp32=((($and))|0)<8;if($cmp32){__label__=12;break $land_lhs_true$$if_end34$18;}else{__label__=13;break $land_lhs_true$$if_end34$18;}}}while(0);$while_cond_backedge$$if_end34$20:do{if(__label__==13){var $31=$eqlist;$p=$31;;while(1){var $32=$p;var $33=HEAP8[($32)];var $conv36=(tempInt=(($33)),(tempInt>=128?tempInt-256:tempInt));var $cmp37=((($conv36))|0)!=0;if(!($cmp37)){__label__=18;break;}
var $34=$p;var $arrayidx39=(($34+1)&4294967295);var $call40=_strlen($arrayidx39);$len=$call40;var $35=$p;var $36=HEAP8[($35)];var $conv41=(tempInt=(($36)),(tempInt>=128?tempInt-256:tempInt));var $37=$phon;var $conv42=(tempInt=(($37)),(tempInt>=128?tempInt-256:tempInt));var $cmp43=((($conv41))|0)==((($conv42))|0);if($cmp43){__label__=16;break;}
var $42=$len;var $add49=((($42)+2)&4294967295);var $43=$p;var $add_ptr50=(($43+$add49)&4294967295);$p=$add_ptr50;__label__=14;continue;}
if(__label__==16){var $38=$p_out;var $39=$p;var $arrayidx45=(($39+1)&4294967295);var $call46=_strcpy($38,$arrayidx45);var $40=$len;var $41=$p_out;var $add_ptr47=(($41+$40)&4294967295);$p_out=$add_ptr47;;}
var $44=$p;var $45=HEAP8[($44)];var $conv51=(tempInt=(($45)),(tempInt>=128?tempInt-256:tempInt));var $cmp52=((($conv51))|0)==0;if(!($cmp52)){__label__=12;break $while_cond_backedge$$if_end34$20;}
var $46=$phon;var $47=$p_out;var $incdec_ptr54=(($47+1)&4294967295);$p_out=$incdec_ptr54;HEAP8[($47)]=$46;;}}while(0);var $29=$p_in;var $incdec_ptr=(($29+1)&4294967295);$p_in=$incdec_ptr;var $30=HEAP8[($29)];$phon=$30;var $conv29=(tempInt=(($30)),(tempInt>=128?tempInt-256:tempInt));var $cmp30=((($conv29))|0)!=0;if($cmp30){__label__=10;continue $while_body$16;}else{__label__=20;break $while_body$$while_end56$15;}}}}while(0);var $48=$p_out;HEAP8[($48)]=0;var $49=$remove_stress;var $tobool57=((($49))|0)!=0;if($tobool57){__label__=21;;}else{__label__=22;;}
if(__label__==21){var $50=$tr_addr;var $arraydecay59=(($phonbuf)&4294967295);__Z13SetWordStressP10TranslatorPcPjii($50,$arraydecay59,0,-1,0);;}
var $51=$phonemes_addr;var $arraydecay61=(($phonbuf)&4294967295);var $call62=_strcpy($51,$arraydecay61);var $52=HEAP32[((_option_phonemes)>>2)];var $cmp63=((($52))|0)==2;if($cmp63){__label__=23;;}else{__label__=24;;}
if(__label__==23){var $53=$tr_addr;var $phoneme_tab_ix65=(($53+656)&4294967295);var $54=HEAP32[(($phoneme_tab_ix65)>>2)];__Z18SelectPhonemeTablei($54);var $55=$phonemes_addr;var $arraydecay66=(($phonbuf)&4294967295);__Z14DecodePhonemesPKcPc($55,$arraydecay66);var $56=HEAP32[((_f_trans)>>2)];var $arraydecay67=(($phonbuf)&4294967295);var $call68=_fprintf($56,((__str1544)&4294967295),allocate([$arraydecay67,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
$retval=1;;}}
var $57=$retval;STACKTOP=__stackBase__;return $57;return null;}
function __Z13TranslateWordP10TranslatorPciP8WORD_TAB($tr,$word_start,$next_pause,$wtab){var __stackBase__=STACKTOP;STACKTOP+=1656;_memset(__stackBase__,0,1656);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $word_start_addr;var $next_pause_addr;var $wtab_addr;var $word1=__stackBase__;var $word_length;var $ix;var $p;var $pfix;var $n_chars;var $dictionary_flags=__stackBase__+4;var $dictionary_flags2=__stackBase__+12;var $end_type;var $prefix_type;var $prefix_stress;var $wordx=__stackBase__+20;var $phonemes=__stackBase__+24;var $ph_limit;var $prefix_phonemes=__stackBase__+184;var $unpron_phonemes=__stackBase__+344;var $end_phonemes=__stackBase__+504;var $word_copy=__stackBase__+664;var $word_copy2=__stackBase__+824;var $word_copy_length;var $prefix_chars=__stackBase__+984;var $found;var $end_flags;var $c_temp;var $first_char=__stackBase__+1052;var $last_char=__stackBase__+1056;var $add_plural_suffix;var $prefix_flags;var $confirm_prefix;var $spell_word;var $stress_bits;var $emphasize_allcaps;var $wflags;var $wmark;var $was_unpronouncable;var $wtab_null=__stackBase__+1060;var $posn;var $non_initial;var $length;var $wc=__stackBase__+1156;var $loopcount;var $end2;var $phonemes2=__stackBase__+1160;var $end_phonemes2=__stackBase__+1320;var $wordpf=__stackBase__+1480;var $prefix_phonemes2=__stackBase__+1484;var $phonemes2482=__stackBase__+1496;var $p659;$tr_addr=$tr;$word_start_addr=$word_start;$next_pause_addr=$next_pause;$wtab_addr=$wtab;$end_type=0;$prefix_type=0;$found=0;HEAP32[(($last_char)>>2)]=0;$add_plural_suffix=0;$prefix_flags=0;$emphasize_allcaps=0;$was_unpronouncable=0;var $0=$wtab_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $arraydecay=(($wtab_null)&4294967295);var $1=$arraydecay;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$1;$stop$=$dest$+96;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $arraydecay1=(($wtab_null)&4294967295);$wtab_addr=$arraydecay1;;}
var $2=$wtab_addr;var $flags=(($2)&4294967295);var $3=HEAP32[(($flags)>>2)];$wflags=$3;var $4=$wtab_addr;var $wmark2=(($4+9)&4294967295);var $5=HEAPU8[($wmark2)];var $conv=((($5))&255);$wmark=$conv;var $arrayidx=(($dictionary_flags)&4294967295);HEAP32[(($arrayidx)>>2)]=0;var $arrayidx3=(($dictionary_flags+4)&4294967295);HEAP32[(($arrayidx3)>>2)]=0;var $arrayidx4=(($dictionary_flags2)&4294967295);HEAP32[(($arrayidx4)>>2)]=0;var $arrayidx5=(($dictionary_flags2+4)&4294967295);HEAP32[(($arrayidx5)>>2)]=0;HEAP32[((_dictionary_skipwords)>>2)]=0;var $arrayidx6=(($phonemes)&4294967295);HEAP8[($arrayidx6)]=0;var $arrayidx7=(($unpron_phonemes)&4294967295);HEAP8[($arrayidx7)]=0;var $arrayidx8=(($prefix_phonemes)&4294967295);HEAP8[($arrayidx8)]=0;var $arrayidx9=(($end_phonemes)&4294967295);HEAP8[($arrayidx9)]=0;var $arrayidx10=(($phonemes+160)&4294967295);$ph_limit=$arrayidx10;var $6=$tr_addr;var $data_dictlist=(($6+1052)&4294967295);var $7=HEAP32[(($data_dictlist)>>2)];var $cmp11=((($7))|0)==0;if($cmp11){__label__=3;;}else{__label__=4;;}
$if_then12$$if_end13$5:do{if(__label__==3){HEAP8[(((_word_phonemes)&4294967295))]=0;$retval=0;;}
else if(__label__==4){var $8=$word_start_addr;HEAP32[(($word1)>>2)]=$8;var $9=HEAP32[(($word1)>>2)];var $10=HEAP8[($9)];var $conv14=(tempInt=(($10)),(tempInt>=128?tempInt-256:tempInt));var $cmp15=((($conv14))|0)==32;if($cmp15){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $11=HEAP32[(($word1)>>2)];var $incdec_ptr=(($11+1)&4294967295);HEAP32[(($word1)>>2)]=$incdec_ptr;;}
var $12=HEAP32[(($word1)>>2)];HEAP32[(($wordx)>>2)]=$12;var $13=HEAP32[(($wordx)>>2)];var $call=__Z7utf8_inPiPKc($first_char,$13);$word_length=0;;$while_cond$11:while(1){var $14=HEAP32[(($wordx)>>2)];var $15=HEAP8[($14)];var $conv18=(tempInt=(($15)),(tempInt>=128?tempInt-256:tempInt));var $cmp19=((($conv18))|0)!=0;var $16=HEAP32[(($wordx)>>2)];if($cmp19){__lastLabel__=7;;}else{__lastLabel__=7;__label__=10;break $while_cond$11;}
var $17=HEAP8[($16)];var $conv20=(tempInt=(($17)),(tempInt>=128?tempInt-256:tempInt));var $cmp21=((($conv20))|0)!=32;var $18=HEAP32[(($wordx)>>2)];if($cmp21){__lastLabel__=8;;}else{__lastLabel__=8;__label__=10;break $while_cond$11;}
var $call22=__Z7utf8_inPiPKc($last_char,$18);var $19=HEAP32[(($wordx)>>2)];var $add_ptr=(($19+$call22)&4294967295);HEAP32[(($wordx)>>2)]=$add_ptr;var $20=$word_length;var $inc=((($20)+1)&4294967295);$word_length=$inc;__label__=7;continue $while_cond$11;}
var $21=__lastLabel__==8?$18:($16);var $22=$word_start_addr;var $sub_ptr_lhs_cast=($21);var $sub_ptr_rhs_cast=($22);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$word_copy_length=$sub_ptr_sub;var $cmp23=((($sub_ptr_sub))|0)>=160;if($cmp23){__label__=11;;}else{__label__=12;;}
if(__label__==11){$word_copy_length=159;;}
var $arraydecay26=(($word_copy2)&4294967295);var $23=$word_start_addr;var $24=$word_copy_length;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$23;$dest$=$arraydecay26;$stop$=$src$+$24;if(($dest$%4)==($src$%4)&&$24>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};$spell_word=0;var $25=HEAP32[((_option_sayas)>>2)];var $cmp27=((($25))|0)==36;if($cmp27){__label__=13;;}else{__label__=16;;}
if(__label__==13){var $26=$word_length;var $cmp29=((($26))|0)==1;if($cmp29){__label__=14;;}else{__label__=15;;}
if(__label__==14){$spell_word=4;;}
else if(__label__==15){var $27=HEAP32[(($word1)>>2)];var $incdec_ptr31=(($27+-1)&4294967295);HEAP32[(($word1)>>2)]=$incdec_ptr31;var $28=HEAP32[(($word1)>>2)];HEAP8[($28)]=95;var $29=$tr_addr;var $arraydecay32=(($phonemes)&4294967295);var $arraydecay33=(($dictionary_flags)&4294967295);var $30=$wtab_addr;var $call34=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($29,$word1,$arraydecay32,$arraydecay33,0,$30);$found=$call34;;}}
var $31=HEAP32[((_option_sayas)>>2)];var $and=($31)&16;var $tobool=((($and))|0)!=0;if($tobool){__label__=17;;}else{__label__=18;;}
$if_then37$$if_else39$25:do{if(__label__==17){var $32=HEAP32[((_option_sayas)>>2)];var $and38=($32)&15;$spell_word=$and38;__lastLabel__=17;__label__=70;break $if_then37$$if_else39$25;}
else if(__label__==18){var $33=$found;var $tobool40=((($33))|0)!=0;if($tobool40){__label__=20;;}else{__label__=19;;}
if(__label__==19){var $34=$tr_addr;var $arraydecay42=(($phonemes)&4294967295);var $arraydecay43=(($dictionary_flags)&4294967295);var $35=$wtab_addr;var $call44=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($34,$word1,$arraydecay42,$arraydecay43,2,$35);$found=$call44;;}
var $arrayidx46=(($dictionary_flags)&4294967295);var $36=HEAP32[(($arrayidx46)>>2)];var $and47=($36)&1;var $tobool48=((($and47))|0)!=0;if($tobool48){__label__=21;;}else{__label__=23;;}
$land_lhs_true$$if_end54$31:do{if(__label__==21){var $37=HEAP32[(($wordx)>>2)];var $arrayidx49=(($37+1)&4294967295);var $38=HEAP8[($arrayidx49)];var $conv50=(tempInt=(($38)),(tempInt>=128?tempInt-256:tempInt));var $cmp51=((($conv50))|0)==46;if(!($cmp51)){__label__=23;break $land_lhs_true$$if_end54$31;}
var $39=HEAP32[(($wordx)>>2)];var $arrayidx53=(($39+1)&4294967295);HEAP8[($arrayidx53)]=32;;}}while(0);var $arrayidx55=(($dictionary_flags)&4294967295);var $40=HEAP32[(($arrayidx55)>>2)];var $and56=($40)&536870912;var $tobool57=((($and56))|0)!=0;if($tobool57){__label__=24;;}else{__label__=27;;}
$if_then58$$if_else80$35:do{if(__label__==24){var $41=HEAP32[(($word1)>>2)];var $arrayidx59=(($41)&4294967295);var $42=HEAP8[($arrayidx59)];var $conv60=(tempInt=(($42)),(tempInt>=128?tempInt-256:tempInt));HEAP32[(($first_char)>>2)]=$conv60;var $arrayidx61=(($dictionary_flags)&4294967295);var $43=HEAP32[(($arrayidx61)>>2)];var $and62=($43)&127;$stress_bits=$and62;var $44=$tr_addr;var $arraydecay63=(($phonemes)&4294967295);var $arraydecay64=(($dictionary_flags2)&4294967295);var $45=$wtab_addr;var $call65=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($44,$word1,$arraydecay63,$arraydecay64,0,$45);$found=$call65;var $arrayidx66=(($dictionary_flags2)&4294967295);var $46=HEAP32[(($arrayidx66)>>2)];var $cmp67=((($46))|0)!=0;if(!($cmp67)){__label__=33;break $if_then58$$if_else80$35;}
var $arrayidx69=(($dictionary_flags2)&4294967295);var $47=HEAP32[(($arrayidx69)>>2)];var $arrayidx70=(($dictionary_flags)&4294967295);HEAP32[(($arrayidx70)>>2)]=$47;var $arrayidx71=(($dictionary_flags2+4)&4294967295);var $48=HEAP32[(($arrayidx71)>>2)];var $arrayidx72=(($dictionary_flags+4)&4294967295);HEAP32[(($arrayidx72)>>2)]=$48;var $49=$stress_bits;var $cmp73=((($49))|0)!=0;if(!($cmp73)){__label__=33;break $if_then58$$if_else80$35;}
var $arrayidx75=(($dictionary_flags)&4294967295);var $50=HEAP32[(($arrayidx75)>>2)];var $and76=($50)&-128;var $51=$stress_bits;var $or=($and76)|($51);var $arrayidx77=(($dictionary_flags)&4294967295);HEAP32[(($arrayidx77)>>2)]=$or;;}
else if(__label__==27){var $52=$found;var $cmp81=((($52))|0)==0;if(!($cmp81)){__label__=33;break $if_then58$$if_else80$35;}
var $arrayidx83=(($dictionary_flags)&4294967295);var $53=HEAP32[(($arrayidx83)>>2)];var $and84=($53)&128;var $tobool85=((($and84))|0)!=0;if(!($tobool85)){__label__=33;break $if_then58$$if_else80$35;}
var $54=HEAP32[(($word1)>>2)];HEAP32[(($wordx)>>2)]=$54;$ix=0;var $55=$ix;var $56=HEAP32[((_dictionary_skipwords)>>2)];var $cmp8815=((($55))|0)<((($56))|0);if(!($cmp8815)){__label__=33;break $if_then58$$if_else80$35;}
while(1){var $57=HEAP32[(($wordx)>>2)];var $58=HEAP8[($57)];var $conv90=(tempInt=(($58)),(tempInt>=128?tempInt-256:tempInt));var $cmp91=((($conv90))|0)==32;if($cmp91){__label__=31;;}else{__label__=32;;}
if(__label__==31){var $59=HEAP32[(($wordx)>>2)];HEAP8[($59)]=45;var $60=$ix;var $inc93=((($60)+1)&4294967295);$ix=$inc93;;}
var $61=HEAP32[(($wordx)>>2)];var $incdec_ptr95=(($61+1)&4294967295);HEAP32[(($wordx)>>2)]=$incdec_ptr95;var $62=$ix;var $63=HEAP32[((_dictionary_skipwords)>>2)];var $cmp88=((($62))|0)<((($63))|0);if($cmp88){__label__=30;continue;}else{__label__=33;break $if_then58$$if_else80$35;}}}}while(0);var $64=$word_length;var $cmp99=((($64))|0)==1;var $65=HEAP32[((_dictionary_skipwords)>>2)];var $cmp101=((($65))|0)==0;var $or_cond=($cmp99)&($cmp101);if($or_cond){__label__=34;;}else{__label__=37;;}
$if_then102$$if_end113$48:do{if(__label__==34){var $66=HEAP32[(($word1)>>2)];var $67=$wtab_addr;var $call103=__ZL17CheckDottedAbbrevPcP8WORD_TAB($66,$67);var $tobool104=((($call103))|0)!=0;if(!($tobool104)){__label__=37;break $if_then102$$if_end113$48;}
var $arrayidx106=(($dictionary_flags)&4294967295);HEAP32[(($arrayidx106)>>2)]=0;var $arrayidx107=(($dictionary_flags+4)&4294967295);HEAP32[(($arrayidx107)>>2)]=0;$spell_word=1;var $68=HEAP32[((_dictionary_skipwords)>>2)];var $tobool108=((($68))|0)!=0;if(!($tobool108)){__label__=37;break $if_then102$$if_end113$48;}
var $arrayidx110=(($dictionary_flags)&4294967295);HEAP32[(($arrayidx110)>>2)]=128;;}}while(0);var $arrayidx114=(($phonemes)&4294967295);var $69=HEAP8[($arrayidx114)];var $conv115=(tempInt=(($69)),(tempInt>=128?tempInt-256:tempInt));var $cmp116=((($conv115))|0)==21;if($cmp116){__label__=38;;}else{__label__=39;;}
if(__label__==38){var $arraydecay118=(($phonemes)&4294967295);var $call119=_strcpy(((_word_phonemes)&4294967295),$arraydecay118);$retval=0;__label__=236;break $if_then12$$if_end13$5;}
else if(__label__==39){var $70=$wmark;var $cmp121=((($70))|0)>0;var $71=$wmark;var $cmp123=((($71))|0)<8;var $or_cond1=($cmp121)&($cmp123);if($or_cond1){__label__=40;;}else{__label__=41;;}
if(__label__==40){var $arrayidx125=(($dictionary_flags)&4294967295);var $72=HEAP32[(($arrayidx125)>>2)];var $and126=($72)&-16;var $73=$wmark;var $or127=($and126)|($73);var $arrayidx128=(($dictionary_flags)&4294967295);HEAP32[(($arrayidx128)>>2)]=$or127;;}
var $74=$found;var $tobool130=((($74))|0)!=0;if($tobool130){__label__=49;;}else{__label__=42;;}
$if_end150$$land_lhs_true131$59:do{if(__label__==42){var $arrayidx132=(($dictionary_flags)&4294967295);var $75=HEAP32[(($arrayidx132)>>2)];var $and133=($75)&131072;var $tobool134=((($and133))|0)!=0;if($tobool134){__label__=43;;}else{__label__=44;;}
if(__label__==43){$spell_word=1;;}
var $_pr=$found;var $tobool137=((($_pr))|0)!=0;if($tobool137){__label__=49;break $if_end150$$land_lhs_true131$59;}
var $76=HEAP32[(($first_char)>>2)];var $call139=_iswdigit($76);var $tobool140=((($call139))|0)!=0;if(!($tobool140)){__label__=49;break $if_end150$$land_lhs_true131$59;}
var $77=$tr_addr;var $call142=__Z6LookupP10TranslatorPKcPc($77,((__str2545)&4294967295),((_word_phonemes)&4294967295));var $78=HEAP8[(((_word_phonemes)&4294967295))];var $conv143=(tempInt=(($78)),(tempInt>=128?tempInt-256:tempInt));var $cmp144=((($conv143))|0)==21;if($cmp144){__label__=47;;}else{__label__=48;;}
if(__label__==47){$retval=0;__label__=236;break $if_then12$$if_end13$5;}
else if(__label__==48){var $79=$tr_addr;var $80=HEAP32[(($word1)>>2)];var $arraydecay147=(($phonemes)&4294967295);var $arraydecay148=(($dictionary_flags)&4294967295);var $81=$wtab_addr;var $call149=__Z15TranslateNumberP10TranslatorPcS1_PjP8WORD_TABi($79,$80,$arraydecay147,$arraydecay148,$81,0);$found=$call149;;}}}while(0);var $82=$found;var $tobool151=((($82))|0)!=0;var $lnot=($tobool151)^1;var $conv152=((($lnot))&1);var $83=$wflags;var $and153=($83)&3;var $cmp154=((($and153))|0)!=2;var $conv155=((($cmp154))&1);var $and156=($conv155)&($conv152);var $tobool157=((($and156))|0)!=0;if($tobool157){__label__=50;;}else{__label__=57;;}
$if_then158$$if_end186$70:do{if(__label__==50){var $84=$tr_addr;var $langopts=(($84)&4294967295);var $numbers=(($langopts+184)&4294967295);var $85=HEAP32[(($numbers)>>2)];var $and159=($85)&16777216;var $tobool160=((($and159))|0)!=0;if($tobool160){__label__=53;;}else{__label__=51;;}
if(__label__==51){var $86=$tr_addr;var $langopts161=(($86)&4294967295);var $numbers162=(($langopts161+184)&4294967295);var $87=HEAP32[(($numbers162)>>2)];var $and163=($87)&33554432;var $tobool164=((($and163))|0)!=0;if(!($tobool164)){__label__=57;break $if_then158$$if_end186$70;}
var $88=$wflags;var $and166=($88)&1;var $tobool167=((($and166))|0)!=0;if(!($tobool167)){__label__=57;break $if_then158$$if_end186$70;}}
var $89=$wflags;var $and169=($89)&16;var $tobool170=((($and169))|0)!=0;if($tobool170){__label__=55;;}else{__label__=54;;}
if(__label__==54){var $90=$wtab_addr;var $arrayidx172=(($90+12)&4294967295);var $flags173=(($arrayidx172)&4294967295);var $91=HEAP32[(($flags173)>>2)];var $and174=($91)&256;var $tobool175=((($and174))|0)!=0;if($tobool175){__label__=57;break $if_then158$$if_end186$70;}}
var $92=$tr_addr;var $93=HEAP32[(($word1)>>2)];var $arraydecay177=(($phonemes)&4294967295);var $94=$wtab_addr;var $call178=__Z14TranslateRomanP10TranslatorPcS1_P8WORD_TAB($92,$93,$arraydecay177,$94);$found=$call178;var $cmp179=((($call178))|0)!=0;if(!($cmp179)){__label__=57;break $if_then158$$if_end186$70;}
var $arrayidx181=(($dictionary_flags)&4294967295);var $95=HEAP32[(($arrayidx181)>>2)];var $or182=($95)|131072;HEAP32[(($arrayidx181)>>2)]=$or182;;}}while(0);var $96=$wflags;var $and187=($96)&1;var $tobool188=((($and187))|0)!=0;if($tobool188){__label__=58;;}else{__label__=69;;}
$land_lhs_true189$$if_end219thread_pre_split$81:do{if(__label__==58){var $97=$word_length;var $cmp190=((($97))|0)>1;if(!($cmp190)){__label__=69;break $land_lhs_true189$$if_end219thread_pre_split$81;}
var $98=HEAP32[(($first_char)>>2)];var $call192=_iswalpha($98);var $tobool193=((($call192))|0)!=0;if(!($tobool193)){__label__=69;break $land_lhs_true189$$if_end219thread_pre_split$81;}
var $99=HEAP32[((_option_tone_flags)>>2)];var $and195=($99)&256;var $tobool196=((($and195))|0)!=0;if($tobool196){__label__=61;;}else{__label__=63;;}
$land_lhs_true197$$if_else202$85:do{if(__label__==61){var $arrayidx198=(($dictionary_flags)&4294967295);var $100=HEAP32[(($arrayidx198)>>2)];var $and199=($100)&131072;var $tobool200=((($and199))|0)!=0;if($tobool200){__label__=63;break $land_lhs_true197$$if_else202$85;}
$emphasize_allcaps=2048;__label__=69;break $land_lhs_true189$$if_end219thread_pre_split$81;}}while(0);var $101=$found;var $tobool203=((($101))|0)!=0;if($tobool203){__label__=69;break $land_lhs_true189$$if_end219thread_pre_split$81;}
var $arrayidx205=(($dictionary_flags)&4294967295);var $102=HEAP32[(($arrayidx205)>>2)];var $and206=($102)&128;var $tobool207=((($and206))|0)!=0;if($tobool207){__label__=69;break $land_lhs_true189$$if_end219thread_pre_split$81;}
var $103=$word_length;var $cmp209=((($103))|0)<4;if(!($cmp209)){__label__=69;break $land_lhs_true189$$if_end219thread_pre_split$81;}
var $104=$tr_addr;var $clause_lower_count=(($104+8308)&4294967295);var $105=HEAP32[(($clause_lower_count)>>2)];var $cmp211=((($105))|0)>3;if(!($cmp211)){__label__=69;break $land_lhs_true189$$if_end219thread_pre_split$81;}
var $106=$tr_addr;var $clause_upper_count=(($106+8304)&4294967295);var $107=HEAP32[(($clause_upper_count)>>2)];var $108=$tr_addr;var $clause_lower_count213=(($108+8308)&4294967295);var $109=HEAP32[(($clause_lower_count213)>>2)];var $cmp214=((($107))|0)<=((($109))|0);if(!($cmp214)){__label__=69;break $land_lhs_true189$$if_end219thread_pre_split$81;}
$spell_word=1;__label__=71;break $if_then37$$if_else39$25;}}while(0);var $_pr5=$spell_word;__lastLabel__=69;__label__=70;break $if_then37$$if_else39$25;}}}while(0);$if_end219$$if_then221$95:do{if(__label__==70){var $110=__lastLabel__==69?$_pr5:($and38);var $cmp220=((($110))|0)>0;if($cmp220){__label__=71;break $if_end219$$if_then221$95;}
var $115=$found;var $cmp232=((($115))|0)==0;if(!($cmp232)){__label__=166;break $if_end219$$if_then221$95;}
$posn=0;$non_initial=0;$length=999;var $116=HEAP32[(($word1)>>2)];HEAP32[(($wordx)>>2)]=$116;var $arraydecay252=(($unpron_phonemes)&4294967295);var $arrayidx256=(($unpron_phonemes)&4294967295);;$while_cond234$99:while(1){var $117=$length;var $cmp235=((($117))|0)<3;var $118=$length;var $cmp237=((($118))|0)>0;var $or_cond2=($cmp235)&($cmp237);if($or_cond2){__label__=80;;}else{__label__=78;;}
if(__label__==78){var $119=$word_length;var $cmp238=((($119))|0)>1;if(!($cmp238)){__label__=89;break $while_cond234$99;}
var $120=$tr_addr;var $121=HEAP32[(($wordx)>>2)];var $122=$posn;var $call240=__Z14UnpronouncableP10TranslatorPci($120,$121,$122);var $tobool241=((($call240))|0)!=0;if(!($tobool241)){__label__=89;break $while_cond234$99;}}
$was_unpronouncable=67108864;$emphasize_allcaps=0;var $123=HEAP32[(($wordx)>>2)];var $arrayidx244=(($123)&4294967295);var $124=HEAP8[($arrayidx244)];var $conv245=(tempInt=(($124)),(tempInt>=128?tempInt-256:tempInt));var $cmp246=((($conv245))|0)==39;if($cmp246){__label__=89;break $while_cond234$99;}
var $125=$posn;var $cmp249=((($125))|0)>0;if($cmp249){__label__=82;;}else{__label__=83;;}
if(__label__==82){$non_initial=1;;}
var $126=$tr_addr;var $127=HEAP32[(($wordx)>>2)];var $128=$non_initial;var $call253=__Z15TranslateLetterP10TranslatorPcS1_i($126,$127,$arraydecay252,$128);var $129=HEAP32[(($wordx)>>2)];var $add_ptr254=(($129+$call253)&4294967295);HEAP32[(($wordx)>>2)]=$add_ptr254;var $130=$posn;var $inc255=((($130)+1)&4294967295);$posn=$inc255;var $131=HEAP8[($arrayidx256)];var $conv257=(tempInt=(($131)),(tempInt>=128?tempInt-256:tempInt));var $cmp258=((($conv257))|0)==21;if($cmp258){__label__=84;break $while_cond234$99;}
$length=0;var $132=$length;var $133=HEAP32[(($wordx)>>2)];var $arrayidx26921=(($133+$132)&4294967295);var $134=HEAP8[($arrayidx26921)];var $conv27022=(tempInt=(($134)),(tempInt>=128?tempInt-256:tempInt));var $cmp27123=((($conv27022))|0)!=32;if(!($cmp27123)){__label__=77;continue $while_cond234$99;}
while(1){var $135=$length;var $inc273=((($135)+1)&4294967295);$length=$inc273;var $136=$length;var $137=HEAP32[(($wordx)>>2)];var $arrayidx269=(($137+$136)&4294967295);var $138=HEAP8[($arrayidx269)];var $conv270=(tempInt=(($138)),(tempInt>=128?tempInt-256:tempInt));var $cmp271=((($conv270))|0)!=32;if($cmp271){__label__=88;continue;}else{__label__=77;continue $while_cond234$99;}}}
if(__label__==89){var $139=$tr_addr;var $arraydecay276=(($unpron_phonemes)&4294967295);var $140=$posn;__Z17SetSpellingStressP10TranslatorPcii($139,$arraydecay276,0,$140);var $141=HEAP32[(($wordx)>>2)];var $142=HEAP8[($141)];var $conv277=(tempInt=(($142)),(tempInt>=128?tempInt-256:tempInt));var $cmp278=((($conv277))|0)!=32;if(!($cmp278)){__label__=166;break $if_end219$$if_then221$95;}
var $arrayidx280=(($unpron_phonemes)&4294967295);var $143=HEAP8[($arrayidx280)];var $conv281=(tempInt=(($143)),(tempInt>=128?tempInt-256:tempInt));var $cmp282=((($conv281))|0)!=0;if($cmp282){__label__=91;;}else{__label__=93;;}
$land_lhs_true283$$if_end289$115:do{if(__label__==91){var $144=HEAP32[(($wordx)>>2)];var $arrayidx284=(($144)&4294967295);var $145=HEAP8[($arrayidx284)];var $conv285=(tempInt=(($145)),(tempInt>=128?tempInt-256:tempInt));var $cmp286=((($conv285))|0)!=39;if(!($cmp286)){__label__=93;break $land_lhs_true283$$if_end289$115;}
var $146=HEAP32[(($wordx)>>2)];var $arrayidx288=(($146+-1)&4294967295);HEAP8[($arrayidx288)]=32;;}}while(0);var $147=$tr_addr;var $148=HEAP32[(($wordx)>>2)];var $arraydecay290=(($phonemes)&4294967295);var $arraydecay291=(($end_phonemes)&4294967295);var $149=$wflags;var $arraydecay292=(($dictionary_flags)&4294967295);var $call293=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($147,$148,$arraydecay290,160,$arraydecay291,$149,$arraydecay292);$end_type=$call293;var $arrayidx294=(($phonemes)&4294967295);var $150=HEAP8[($arrayidx294)];var $conv295=(tempInt=(($150)),(tempInt>=128?tempInt-256:tempInt));var $cmp296=((($conv295))|0)==21;var $arraydecay298=(($phonemes)&4294967295);if($cmp296){__label__=94;;}else{__label__=95;;}
if(__label__==94){var $call299=_strcpy(((_word_phonemes)&4294967295),$arraydecay298);$retval=0;__label__=236;break $if_then12$$if_end13$5;}
else if(__label__==95){var $151=HEAP8[($arraydecay298)];var $conv302=(tempInt=(($151)),(tempInt>=128?tempInt-256:tempInt));var $cmp303=((($conv302))|0)==0;if($cmp303){__label__=96;;}else{__label__=101;;}
$land_lhs_true304$$if_end321$122:do{if(__label__==96){var $arrayidx305=(($end_phonemes)&4294967295);var $152=HEAP8[($arrayidx305)];var $conv306=(tempInt=(($152)),(tempInt>=128?tempInt-256:tempInt));var $cmp307=((($conv306))|0)==0;if(!($cmp307)){__label__=101;break $land_lhs_true304$$if_end321$122;}
var $153=HEAP32[(($wordx)>>2)];var $call309=__Z7utf8_inPiPKc($wc,$153);var $154=$word_length;var $cmp310=((($154))|0)==1;if(!($cmp310)){__label__=101;break $land_lhs_true304$$if_end321$122;}
var $155=HEAP32[(($wc)>>2)];var $call312=__Z7IsAlphaj($155);var $tobool313=((($call312))|0)!=0;if(!($tobool313)){__label__=101;break $land_lhs_true304$$if_end321$122;}
var $156=$tr_addr;var $157=HEAP32[(($wordx)>>2)];var $arraydecay315=(($phonemes)&4294967295);var $158=$spell_word;var $call316=__ZL22SpeakIndividualLettersP10TranslatorPcS1_i($156,$157,$arraydecay315,$158);HEAP32[(($wordx)>>2)]=$call316;var $cmp317=((($call316))|0)==0;if(!($cmp317)){__label__=101;break $land_lhs_true304$$if_end321$122;}
$retval=0;__label__=236;break $if_then12$$if_end13$5;}}while(0);var $159=HEAP32[(($wordx)>>2)];var $arrayidx322=(($159+-1)&4294967295);var $160=HEAP8[($arrayidx322)];$c_temp=$160;$found=0;$confirm_prefix=1;$loopcount=0;var $arrayidx333=(($phonemes2)&4294967295);var $arraydecay334=(($phonemes2)&4294967295);var $arraydecay335=(($end_phonemes2)&4294967295);var $arraydecay338=(($dictionary_flags)&4294967295);var $arraydecay342=(($word_copy)&4294967295);var $arraydecay344=(($phonemes)&4294967295);var $arraydecay345=(($end_phonemes)&4294967295);var $arraydecay347=(($dictionary_flags)&4294967295);var $arraydecay349=(($word_copy)&4294967295);var $arraydecay350=(($word_copy)&4294967295);var $arraydecay355=(($phonemes)&4294967295);var $arraydecay356=(($phonemes2)&4294967295);var $arraydecay358=(($end_phonemes)&4294967295);var $arraydecay359=(($end_phonemes2)&4294967295);var $arraydecay363=(($end_phonemes)&4294967295);var $arraydecay364=(($end_phonemes2)&4294967295);var $arraydecay365=(($end_phonemes2)&4294967295);var $arraydecay418=(($prefix_phonemes2)&4294967295);var $arraydecay419=(($end_phonemes)&4294967295);var $arrayidx420=(($prefix_chars+1)&4294967295);var $arraydecay421=(($prefix_phonemes)&4294967295);var $arraydecay422=(($phonemes)&4294967295);var $arraydecay424=(($phonemes)&4294967295);var $arraydecay425=(($dictionary_flags)&4294967295);var $arraydecay429=(($prefix_phonemes)&4294967295);var $arraydecay430=(($phonemes)&4294967295);var $arrayidx433=(($dictionary_flags)&4294967295);var $arrayidx437=(($prefix_phonemes)&4294967295);var $arraydecay438=(($prefix_phonemes)&4294967295);var $arrayidx446=(($end_phonemes)&4294967295);var $arraydecay447=(($phonemes)&4294967295);var $arraydecay448=(($dictionary_flags2)&4294967295);var $arrayidx450=(($dictionary_flags)&4294967295);var $arrayidx453=(($dictionary_flags2)&4294967295);var $arrayidx454=(($dictionary_flags)&4294967295);var $arrayidx455=(($dictionary_flags2+4)&4294967295);var $arrayidx456=(($dictionary_flags+4)&4294967295);var $arraydecay461=(($phonemes)&4294967295);var $arraydecay462=(($end_phonemes)&4294967295);var $arraydecay463=(($dictionary_flags)&4294967295);var $arrayidx465=(($phonemes)&4294967295);var $arraydecay442=(($prefix_phonemes)&4294967295);var $arraydecay443=(($end_phonemes)&4294967295);var $arrayidx392=(($prefix_chars)&4294967295);__lastLabel__=101;;$for_cond$129:while(1){var $161=__lastLabel__==136?$inc475:(0);var $cmp323=((($161))|0)<50;var $162=$end_type;if(!($cmp323)){__label__=137;break $for_cond$129;}
var $and325=($162)&1024;var $tobool326=((($and325))|0)!=0;if(!($tobool326)){__label__=137;break $for_cond$129;}
var $163=$confirm_prefix;var $tobool328=((($163))|0)!=0;if($tobool328){__label__=105;;}else{__label__=111;;}
$land_lhs_true329$$if_end370$133:do{if(__label__==105){var $164=$end_type;var $and330=($164)&131072;var $tobool331=((($and330))|0)!=0;if($tobool331){__label__=111;break $land_lhs_true329$$if_end370$133;}
HEAP8[($arrayidx333)]=0;var $165=$tr_addr;var $166=HEAP32[(($wordx)>>2)];var $167=$wflags;var $or337=($167)|805306368;var $call339=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($165,$166,$arraydecay334,160,$arraydecay335,$or337,$arraydecay338);$end2=$call339;var $168=$end2;var $tobool340=((($168))|0)!=0;if(!($tobool340)){__label__=111;break $land_lhs_true329$$if_end370$133;}
var $169=$tr_addr;var $170=HEAP32[(($wordx)>>2)];var $171=$end2;var $call343=__Z12RemoveEndingP10TranslatorPciS1_($169,$170,$171,$arraydecay342);var $172=$tr_addr;var $173=HEAP32[(($wordx)>>2)];var $174=$wflags;var $or346=($174)|268435456;var $call348=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($172,$173,$arraydecay344,160,$arraydecay345,$or346,$arraydecay347);$end_type=$call348;var $175=HEAP32[(($wordx)>>2)];var $call351=_strlen($arraydecay350);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay349;$dest$=$175;$stop$=$src$+$call351;if(($dest$%4)==($src$%4)&&$call351>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $176=$end_type;var $and352=($176)&1024;var $cmp353=((($and352))|0)==0;if($cmp353){__label__=108;;}else{__label__=110;;}
$if_then354$$if_end368$137:do{if(__label__==108){var $177=$end2;$end_type=$177;var $call357=_strcpy($arraydecay355,$arraydecay356);var $call360=_strcpy($arraydecay358,$arraydecay359);var $178=HEAP32[((_option_phonemes)>>2)];var $cmp361=((($178))|0)==2;if(!($cmp361)){__label__=110;break $if_then354$$if_end368$137;}
__Z14DecodePhonemesPKcPc($arraydecay363,$arraydecay364);var $179=HEAP32[((_f_trans)>>2)];var $call366=_fprintf($179,((__str4547)&4294967295),allocate([$arraydecay365,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}}while(0);$confirm_prefix=0;__label__=136;break $land_lhs_true329$$if_end370$133;}}while(0);$if_end370$$for_inc474$141:do{if(__label__==111){var $180=$end_type;$prefix_type=$180;var $181=$prefix_type;var $and371=($181)&2048;var $tobool372=((($and371))|0)!=0;if($tobool372){__label__=112;;}else{__label__=113;;}
if(__label__==112){var $182=$tr_addr;var $expect_verb=(($182+8272)&4294967295);HEAP32[(($expect_verb)>>2)]=1;;}
var $183=$c_temp;var $184=HEAP32[(($wordx)>>2)];var $arrayidx375=(($184+-1)&4294967295);HEAP8[($arrayidx375)]=$183;var $185=$prefix_type;var $and376=($185)&131072;var $cmp377=((($and376))|0)==0;if($cmp377){__label__=114;;}else{__label__=118;;}
$if_then378$$if_else391$146:do{if(__label__==114){var $186=$prefix_type;var $and379=($186)&15;$ix=$and379;var $cmp38119=((($and379))|0)>0;if(!($cmp38119)){__label__=124;break $if_then378$$if_else391$146;}
$for_body382$148:while(1){var $187=HEAP32[(($wordx)>>2)];var $incdec_ptr383=(($187+1)&4294967295);HEAP32[(($wordx)>>2)]=$incdec_ptr383;var $188=HEAP32[(($wordx)>>2)];var $189=HEAP8[($188)];var $conv38516=(tempInt=(($189)),(tempInt>=128?tempInt-256:tempInt));var $and38617=($conv38516)&192;var $cmp38718=((($and38617))|0)==128;if($cmp38718){__label__=116;;}else{__label__=117;;}
$while_body388$$for_inc$150:do{if(__label__==116){while(1){var $190=HEAP32[(($wordx)>>2)];var $incdec_ptr389=(($190+1)&4294967295);HEAP32[(($wordx)>>2)]=$incdec_ptr389;var $191=HEAP32[(($wordx)>>2)];var $192=HEAP8[($191)];var $conv385=(tempInt=(($192)),(tempInt>=128?tempInt-256:tempInt));var $and386=($conv385)&192;var $cmp387=((($and386))|0)==128;if($cmp387){__label__=116;continue;}else{__label__=117;break $while_body388$$for_inc$150;}}}}while(0);var $193=$ix;var $dec=((($193)-1)&4294967295);$ix=$dec;var $cmp381=((($dec))|0)>0;if($cmp381){__label__=115;continue $for_body382$148;}else{__label__=124;break $if_then378$$if_else391$146;}}}
else if(__label__==118){$pfix=1;HEAP8[($arrayidx392)]=0;var $194=$prefix_type;var $and393=($194)&63;$n_chars=$and393;$ix=0;var $195=$ix;var $196=$n_chars;var $cmp39520=((($195))|0)<((($196))|0);if($cmp39520){__label__=119;;}else{__label__=123;;}
$for_body396$$for_end410$155:do{if(__label__==119){$for_body396$156:while(1){var $197=HEAP32[(($wordx)>>2)];var $incdec_ptr397=(($197+1)&4294967295);HEAP32[(($wordx)>>2)]=$incdec_ptr397;var $198=HEAP8[($197)];var $199=$pfix;var $inc398=((($199)+1)&4294967295);$pfix=$inc398;var $arrayidx399=(($prefix_chars+$199)&4294967295);HEAP8[($arrayidx399)]=$198;var $200=$prefix_type;var $and400=($200)&131072;var $tobool401=((($and400))|0)!=0;if($tobool401){__label__=120;;}else{__label__=122;;}
$land_lhs_true402$$for_inc408$158:do{if(__label__==120){var $201=$ix;var $202=$n_chars;var $sub=((($202)-1)&4294967295);var $cmp403=((($201))|0)==((($sub))|0);if(!($cmp403)){__label__=122;break $land_lhs_true402$$for_inc408$158;}
var $203=$pfix;var $sub405=((($203)-1)&4294967295);var $arrayidx406=(($prefix_chars+$sub405)&4294967295);HEAP8[($arrayidx406)]=0;;}}while(0);var $204=$ix;var $inc409=((($204)+1)&4294967295);$ix=$inc409;var $205=$ix;var $206=$n_chars;var $cmp395=((($205))|0)<((($206))|0);if($cmp395){__label__=119;continue $for_body396$156;}else{__label__=123;break $for_body396$$for_end410$155;}}}}while(0);var $207=$pfix;var $arrayidx411=(($prefix_chars+$207)&4294967295);HEAP8[($arrayidx411)]=0;;}}while(0);var $208=HEAP32[(($wordx)>>2)];var $arrayidx413=(($208+-1)&4294967295);var $209=HEAP8[($arrayidx413)];$c_temp=$209;var $210=HEAP32[(($wordx)>>2)];var $arrayidx414=(($210+-1)&4294967295);HEAP8[($arrayidx414)]=32;$confirm_prefix=1;var $211=$prefix_type;var $and415=($211)&131072;var $tobool416=((($and415))|0)!=0;if($tobool416){__label__=125;;}else{__label__=129;;}
$if_then417$$if_else441$164:do{if(__label__==125){__Z8strncpy0PcPKci($arraydecay418,$arraydecay419,12);HEAP32[(($wordpf)>>2)]=$arrayidx420;var $call423=_strcpy($arraydecay421,$arraydecay422);var $212=$tr_addr;var $213=$wtab_addr;var $call426=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($212,$wordpf,$arraydecay424,$arraydecay425,0,$213);$found=$call426;var $214=$found;var $tobool427=((($214))|0)!=0;if($tobool427){__label__=126;;}else{__label__=127;;}
if(__label__==126){var $call431=_strcpy($arraydecay429,$arraydecay430);;}
var $215=HEAP32[(($arrayidx433)>>2)];var $and434=($215)&131072;var $tobool435=((($and434))|0)!=0;if(!($tobool435)){__label__=130;break $if_then417$$if_else441$164;}
HEAP8[($arrayidx437)]=0;var $216=$tr_addr;var $217=HEAP32[(($wordpf)>>2)];var $call439=__ZL22SpeakIndividualLettersP10TranslatorPcS1_i($216,$217,$arraydecay438,1);;}
else if(__label__==129){var $call444=_strcat($arraydecay442,$arraydecay443);;}}while(0);HEAP8[($arrayidx446)]=0;$end_type=0;var $218=$tr_addr;var $219=$wtab_addr;var $call449=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($218,$wordx,$arraydecay447,$arraydecay448,1024,$219);$found=$call449;var $220=HEAP32[(($arrayidx450)>>2)];var $cmp451=((($220))|0)==0;if($cmp451){__label__=131;;}else{__label__=132;;}
if(__label__==131){var $221=HEAP32[(($arrayidx453)>>2)];HEAP32[(($arrayidx454)>>2)]=$221;var $222=HEAP32[(($arrayidx455)>>2)];HEAP32[(($arrayidx456)>>2)]=$222;;}
else if(__label__==132){$prefix_flags=1;;}
var $223=$found;var $cmp459=((($223))|0)==0;if(!($cmp459)){__label__=136;break $if_end370$$for_inc474$141;}
var $224=$tr_addr;var $225=HEAP32[(($wordx)>>2)];var $call464=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($224,$225,$arraydecay461,160,$arraydecay462,0,$arraydecay463);$end_type=$call464;var $226=HEAP8[($arrayidx465)];var $conv466=(tempInt=(($226)),(tempInt>=128?tempInt-256:tempInt));var $cmp467=((($conv466))|0)==21;if($cmp467){__label__=135;break $for_cond$129;}}}while(0);var $229=$loopcount;var $inc475=((($229)+1)&4294967295);$loopcount=$inc475;__lastLabel__=136;__label__=102;continue $for_cond$129;}
if(__label__==137){var $cmp477=((($162))|0)!=0;if($cmp477){__label__=138;;}else{__label__=165;;}
$land_lhs_true478$$if_end603$180:do{if(__label__==138){var $230=$end_type;var $and479=($230)&1024;var $tobool480=((($and479))|0)!=0;if($tobool480){__label__=165;break $land_lhs_true478$$if_end603$180;}
var $arraydecay483=(($phonemes2482)&4294967295);var $arraydecay484=(($phonemes)&4294967295);var $call485=_strcpy($arraydecay483,$arraydecay484);var $231=$tr_addr;var $232=HEAP32[(($wordx)>>2)];var $233=$end_type;var $arraydecay486=(($word_copy)&4294967295);var $call487=__Z12RemoveEndingP10TranslatorPciS1_($231,$232,$233,$arraydecay486);$end_flags=$call487;var $arrayidx488=(($phonemes)&4294967295);HEAP8[($arrayidx488)]=0;var $arrayidx489=(($prefix_phonemes)&4294967295);var $234=HEAP8[($arrayidx489)];var $conv490=(tempInt=(($234)),(tempInt>=128?tempInt-256:tempInt));var $cmp491=((($conv490))|0)!=0;if($cmp491){__label__=140;;}else{__label__=148;;}
$if_then492$$if_end526$183:do{if(__label__==140){var $235=$c_temp;var $236=HEAP32[(($wordx)>>2)];var $arrayidx493=(($236+-1)&4294967295);HEAP8[($arrayidx493)]=$235;var $237=$tr_addr;var $arraydecay494=(($phonemes)&4294967295);var $arraydecay495=(($dictionary_flags2)&4294967295);var $238=$end_flags;var $239=$wtab_addr;var $call496=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($237,$word1,$arraydecay494,$arraydecay495,$238,$239);$found=$call496;var $240=HEAP32[(($wordx)>>2)];var $arrayidx497=(($240+-1)&4294967295);HEAP8[($arrayidx497)]=32;var $arrayidx498=(($phonemes)&4294967295);var $241=HEAP8[($arrayidx498)];var $conv499=(tempInt=(($241)),(tempInt>=128?tempInt-256:tempInt));var $cmp500=((($conv499))|0)==21;if($cmp500){__label__=141;;}else{__label__=142;;}
if(__label__==141){var $242=HEAP32[(($wordx)>>2)];var $arraydecay502=(($word_copy)&4294967295);var $arraydecay503=(($word_copy)&4294967295);var $call504=_strlen($arraydecay503);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay502;$dest$=$242;$stop$=$src$+$call504;if(($dest$%4)==($src$%4)&&$call504>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $arraydecay505=(($phonemes)&4294967295);var $call506=_strcpy(((_word_phonemes)&4294967295),$arraydecay505);$retval=0;__label__=236;break $if_then12$$if_end13$5;}
else if(__label__==142){var $arrayidx508=(($dictionary_flags)&4294967295);var $243=HEAP32[(($arrayidx508)>>2)];var $cmp509=((($243))|0)==0;if($cmp509){__label__=143;;}else{__label__=144;;}
if(__label__==143){var $arrayidx511=(($dictionary_flags2)&4294967295);var $244=HEAP32[(($arrayidx511)>>2)];var $arrayidx512=(($dictionary_flags)&4294967295);HEAP32[(($arrayidx512)>>2)]=$244;var $arrayidx513=(($dictionary_flags2+4)&4294967295);var $245=HEAP32[(($arrayidx513)>>2)];var $arrayidx514=(($dictionary_flags+4)&4294967295);HEAP32[(($arrayidx514)>>2)]=$245;;}
var $246=$found;var $tobool516=((($246))|0)!=0;if($tobool516){__label__=145;;}else{__label__=146;;}
if(__label__==145){var $arrayidx518=(($prefix_phonemes)&4294967295);HEAP8[($arrayidx518)]=0;var $_pr8=$found;var $cmp520=((($_pr8))|0)==0;if(!($cmp520)){__label__=162;break $if_then492$$if_end526$183;}}
var $arrayidx522=(($dictionary_flags2)&4294967295);var $247=HEAP32[(($arrayidx522)>>2)];var $cmp523=((($247))|0)!=0;if(!($cmp523)){__label__=148;break $if_then492$$if_end526$183;}
$prefix_flags=1;__label__=148;break $if_then492$$if_end526$183;}}}while(0);$if_end526$$if_end592$195:do{if(__label__==148){var $_pr10=$found;var $cmp527=((($_pr10))|0)==0;if(!($cmp527)){__label__=162;break $if_end526$$if_end592$195;}
var $248=$tr_addr;var $arraydecay529=(($phonemes)&4294967295);var $arraydecay530=(($dictionary_flags2)&4294967295);var $249=$end_flags;var $250=$wtab_addr;var $call531=__Z14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TAB($248,$wordx,$arraydecay529,$arraydecay530,$249,$250);$found=$call531;var $arrayidx532=(($phonemes)&4294967295);var $251=HEAP8[($arrayidx532)];var $conv533=(tempInt=(($251)),(tempInt>=128?tempInt-256:tempInt));var $cmp534=((($conv533))|0)==21;if($cmp534){__label__=150;;}else{__label__=151;;}
if(__label__==150){var $252=HEAP32[(($wordx)>>2)];var $arraydecay536=(($word_copy)&4294967295);var $arraydecay537=(($word_copy)&4294967295);var $call538=_strlen($arraydecay537);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay536;$dest$=$252;$stop$=$src$+$call538;if(($dest$%4)==($src$%4)&&$call538>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $arraydecay539=(($phonemes)&4294967295);var $call540=_strcpy(((_word_phonemes)&4294967295),$arraydecay539);$retval=0;__label__=236;break $if_then12$$if_end13$5;}
else if(__label__==151){var $arrayidx547=(($dictionary_flags)&4294967295);var $253=HEAP32[(($arrayidx547)>>2)];var $cmp548=((($253))|0)==0;if($cmp548){__label__=152;;}else{__label__=153;;}
if(__label__==152){var $arrayidx550=(($dictionary_flags2)&4294967295);var $254=HEAP32[(($arrayidx550)>>2)];var $arrayidx551=(($dictionary_flags)&4294967295);HEAP32[(($arrayidx551)>>2)]=$254;var $arrayidx552=(($dictionary_flags2+4)&4294967295);var $255=HEAP32[(($arrayidx552)>>2)];var $arrayidx553=(($dictionary_flags+4)&4294967295);HEAP32[(($arrayidx553)>>2)]=$255;;}
var $_pr12_pr=$found;var $cmp556=((($_pr12_pr))|0)==0;if(!($cmp556)){__label__=162;break $if_end526$$if_end592$195;}
var $256=$end_type;var $and558=($256)&16384;var $tobool559=((($and558))|0)!=0;if($tobool559){__label__=155;;}else{__label__=156;;}
if(__label__==155){var $arraydecay561=(($phonemes)&4294967295);var $arraydecay562=(($phonemes2482)&4294967295);var $call563=_strcpy($arraydecay561,$arraydecay562);var $257=$tr_addr;var $arraydecay564=(($phonemes)&4294967295);var $arrayidx565=(($dictionary_flags)&4294967295);var $258=HEAP32[(($arrayidx565)>>2)];__Z21ApplySpecialAttributeP10TranslatorPci($257,$arraydecay564,$258);;}
else if(__label__==156){var $259=$end_flags;var $and567=($259)&4;var $tobool568=((($and567))|0)!=0;if($tobool568){__label__=157;;}else{__label__=158;;}
if(__label__==157){var $260=$wflags;var $or570=($260)|8192;$wflags=$or570;;}
var $261=$end_type;var $and572=($261)&262144;var $tobool573=((($and572))|0)!=0;if($tobool573){__label__=159;;}else{__label__=160;;}
if(__label__==159){var $262=$wflags;var $or575=($262)|134217728;$wflags=$or575;;}
var $263=$tr_addr;var $264=HEAP32[(($wordx)>>2)];var $arraydecay577=(($phonemes)&4294967295);var $265=$wflags;var $arraydecay578=(($dictionary_flags)&4294967295);var $call579=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($263,$264,$arraydecay577,160,0,$265,$arraydecay578);var $arrayidx580=(($phonemes)&4294967295);var $266=HEAP8[($arrayidx580)];var $conv581=(tempInt=(($266)),(tempInt>=128?tempInt-256:tempInt));var $cmp582=((($conv581))|0)==21;if(!($cmp582)){__label__=162;break $if_end526$$if_end592$195;}
var $arraydecay584=(($phonemes)&4294967295);var $call585=_strcpy(((_word_phonemes)&4294967295),$arraydecay584);var $267=HEAP32[(($wordx)>>2)];var $arraydecay586=(($word_copy)&4294967295);var $arraydecay587=(($word_copy)&4294967295);var $call588=_strlen($arraydecay587);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay586;$dest$=$267;$stop$=$src$+$call588;if(($dest$%4)==($src$%4)&&$call588>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $268=$c_temp;var $269=HEAP32[(($wordx)>>2)];var $arrayidx589=(($269+-1)&4294967295);HEAP8[($arrayidx589)]=$268;$retval=0;__label__=236;break $if_then12$$if_end13$5;}}}}while(0);var $270=$end_type;var $and593=($270)&65536;var $cmp594=((($and593))|0)==0;if($cmp594){__label__=163;;}else{__label__=164;;}
if(__label__==163){var $271=$tr_addr;var $arraydecay596=(($phonemes)&4294967295);var $arraydecay597=(($end_phonemes)&4294967295);__Z14AppendPhonemesP10TranslatorPciPKc($271,$arraydecay596,160,$arraydecay597);var $arrayidx598=(($end_phonemes)&4294967295);HEAP8[($arrayidx598)]=0;;}
var $272=HEAP32[(($wordx)>>2)];var $arraydecay600=(($word_copy)&4294967295);var $arraydecay601=(($word_copy)&4294967295);var $call602=_strlen($arraydecay601);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay600;$dest$=$272;$stop$=$src$+$call602;if(($dest$%4)==($src$%4)&&$call602>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}}while(0);var $273=$c_temp;var $274=HEAP32[(($wordx)>>2)];var $arrayidx604=(($274+-1)&4294967295);HEAP8[($arrayidx604)]=$273;__label__=166;break $if_end219$$if_then221$95;}
else if(__label__==135){var $227=$c_temp;var $228=HEAP32[(($wordx)>>2)];var $arrayidx469=(($228+-1)&4294967295);HEAP8[($arrayidx469)]=$227;var $arraydecay470=(($phonemes)&4294967295);var $call471=_strcpy(((_word_phonemes)&4294967295),$arraydecay470);$retval=0;__label__=236;break $if_then12$$if_end13$5;}}}
else if(__label__==84){var $arraydecay260=(($unpron_phonemes)&4294967295);var $call261=_strcpy(((_word_phonemes)&4294967295),$arraydecay260);var $arrayidx262=(($unpron_phonemes+1)&4294967295);var $call263=_strcmp($arrayidx262,((__str52704)&4294967295));var $cmp264=((($call263))|0)==0;if($cmp264){__label__=85;;}else{__label__=86;;}
if(__label__==85){$retval=65536;__label__=236;break $if_then12$$if_end13$5;}
else if(__label__==86){$retval=0;__label__=236;break $if_then12$$if_end13$5;}}}}while(0);$if_then221$$if_end607$225:do{if(__label__==71){var $arrayidx222=(($phonemes)&4294967295);HEAP8[($arrayidx222)]=0;$end_type=0;var $111=$tr_addr;var $112=HEAP32[(($word1)>>2)];var $arraydecay223=(($phonemes)&4294967295);var $113=$spell_word;var $call224=__ZL22SpeakIndividualLettersP10TranslatorPcS1_i($111,$112,$arraydecay223,$113);var $cmp225=((($call224))|0)==0;if(!($cmp225)){__label__=166;break $if_then221$$if_end607$225;}
var $114=$word_length;var $cmp227=((($114))|0)>1;if($cmp227){__label__=73;;}else{__label__=74;;}
if(__label__==73){$retval=65536;__label__=236;break $if_then12$$if_end13$5;}
else if(__label__==74){$retval=0;__label__=236;break $if_then12$$if_end13$5;}}}while(0);var $275=$add_plural_suffix;var $tobool608=((($275))|0)!=0;if($tobool608){__label__=168;;}else{__label__=167;;}
$if_then612$$lor_lhs_false609$232:do{if(__label__==167){var $276=$wflags;var $and610=($276)&4;var $tobool611=((($and610))|0)!=0;if($tobool611){__label__=168;break $if_then612$$lor_lhs_false609$232;}else{__label__=174;break $if_then612$$lor_lhs_false609$232;}}}while(0);$if_then612$$if_end630$234:do{if(__label__==168){var $277=HEAP32[(($last_char)>>2)];var $cmp613=((($277))|0)==102;if($cmp613){__label__=169;;}else{__label__=170;;}
if(__label__==169){var $278=$tr_addr;var $arraydecay615=(($phonemes)&4294967295);var $call616=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($278,((__ZZ13TranslateWordP10TranslatorPciP8WORD_TABE7word_ss+1)&4294967295),$arraydecay615,160,0,0,0);;}
else if(__label__==170){var $279=HEAP32[(($last_char)>>2)];var $cmp618=((($279))|0)==0;if($cmp618){__label__=172;;}else{__label__=171;;}
$if_then622$$lor_lhs_false619$239:do{if(__label__==171){var $280=HEAP32[(($last_char)>>2)];var $call620=__Z8strchr_wPKci(((__str5548)&4294967295),$280);var $cmp621=((($call620))|0)==0;if($cmp621){__label__=172;break $if_then622$$lor_lhs_false619$239;}
var $282=$tr_addr;var $arraydecay626=(($phonemes)&4294967295);var $call627=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($282,((__ZZ13TranslateWordP10TranslatorPciP8WORD_TABE7word_iz+1)&4294967295),$arraydecay626,160,0,0,0);__label__=174;break $if_then612$$if_end630$234;}}while(0);var $281=$tr_addr;var $arraydecay623=(($phonemes)&4294967295);var $call624=__Z14TranslateRulesP10TranslatorPcS1_iS1_iPj($281,((__ZZ13TranslateWordP10TranslatorPciP8WORD_TABE7word_zz+1)&4294967295),$arraydecay623,160,0,0,0);;}}}while(0);var $283=$emphasize_allcaps;var $284=$wflags;var $or631=($284)|($283);$wflags=$or631;$prefix_stress=0;var $arraydecay632=(($prefix_phonemes)&4294967295);$p=$arraydecay632;var $285=$p;var $286=HEAP8[($285)];var $conv63426=(tempInt=(($286)),(tempInt>=128?tempInt-256:tempInt));var $cmp63527=((($conv63426))|0)!=0;if($cmp63527){__label__=175;;}else{__label__=179;;}
$for_body636$$for_end647$244:do{if(__label__==175){$for_body636$245:while(1){var $287=$p;var $288=HEAP8[($287)];var $conv637=(tempInt=(($288)),(tempInt>=128?tempInt-256:tempInt));var $cmp638=((($conv637))|0)==6;if($cmp638){__label__=177;;}else{__label__=176;;}
$if_then642$$lor_lhs_false639$247:do{if(__label__==176){var $289=$p;var $290=HEAP8[($289)];var $conv640=(tempInt=(($290)),(tempInt>=128?tempInt-256:tempInt));var $cmp641=((($conv640))|0)==7;if($cmp641){__label__=177;break $if_then642$$lor_lhs_false639$247;}else{__label__=178;break $if_then642$$lor_lhs_false639$247;}}}while(0);if(__label__==177){var $291=$p;var $292=HEAP8[($291)];var $conv643=(tempInt=(($292)),(tempInt>=128?tempInt-256:tempInt));$prefix_stress=$conv643;;}
var $293=$p;var $incdec_ptr646=(($293+1)&4294967295);$p=$incdec_ptr646;var $294=$p;var $295=HEAP8[($294)];var $conv634=(tempInt=(($295)),(tempInt>=128?tempInt-256:tempInt));var $cmp635=((($conv634))|0)!=0;if($cmp635){__label__=175;continue $for_body636$245;}else{__label__=179;break $for_body636$$for_end647$244;}}}}while(0);var $296=$prefix_flags;var $tobool648=((($296))|0)!=0;if($tobool648){__label__=181;;}else{__label__=180;;}
$if_then651$$lor_lhs_false649$253:do{if(__label__==180){var $297=$prefix_stress;var $cmp650=((($297))|0)!=0;if($cmp650){__label__=181;break $if_then651$$lor_lhs_false649$253;}
var $313=$tr_addr;var $arraydecay695=(($phonemes)&4294967295);var $arraydecay696=(($dictionary_flags)&4294967295);__Z13SetWordStressP10TranslatorPcPjii($313,$arraydecay695,$arraydecay696,-1,0);var $arraydecay701=(($unpron_phonemes)&4294967295);var $arraydecay702=(($prefix_phonemes)&4294967295);var $arraydecay703=(($phonemes)&4294967295);var $call704=_snprintf(((_word_phonemes)&4294967295),160,((__str6549)&4294967295),allocate([$arraydecay701,0,0,0,$arraydecay702,0,0,0,$arraydecay703,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));HEAP8[(((_word_phonemes+159)&4294967295))]=0;__label__=192;break $if_then651$$lor_lhs_false649$253;}}while(0);$if_then651$$if_end705$256:do{if(__label__==181){var $298=$tr_addr;var $langopts652=(($298)&4294967295);var $param=(($langopts652+24)&4294967295);var $arrayidx653=(($param+12)&4294967295);var $299=HEAP32[(($arrayidx653)>>2)];var $tobool654=((($299))|0)!=0;if($tobool654){__label__=183;;}else{__label__=182;;}
$if_then658$$lor_lhs_false655$258:do{if(__label__==182){var $300=$prefix_type;var $and656=($300)&65536;var $tobool657=((($and656))|0)!=0;if($tobool657){__label__=183;break $if_then658$$lor_lhs_false655$258;}
var $arraydecay684=(($unpron_phonemes)&4294967295);var $arraydecay685=(($prefix_phonemes)&4294967295);var $arraydecay686=(($phonemes)&4294967295);var $call687=_snprintf(((_word_phonemes)&4294967295),160,((__str6549)&4294967295),allocate([$arraydecay684,0,0,0,$arraydecay685,0,0,0,$arraydecay686,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));HEAP8[(((_word_phonemes+159)&4294967295))]=0;var $312=$tr_addr;var $arraydecay688=(($dictionary_flags)&4294967295);__Z13SetWordStressP10TranslatorPcPjii($312,((_word_phonemes)&4294967295),$arraydecay688,-1,0);__label__=192;break $if_then651$$if_end705$256;}}while(0);var $301=$tr_addr;var $arraydecay660=(($phonemes)&4294967295);var $arraydecay661=(($dictionary_flags)&4294967295);__Z13SetWordStressP10TranslatorPcPjii($301,$arraydecay660,$arraydecay661,3,0);$ix=0;var $arraydecay662=(($prefix_phonemes)&4294967295);$p659=$arraydecay662;var $302=$p659;var $303=HEAP8[($302)];var $conv66424=(tempInt=(($303)),(tempInt>=128?tempInt-256:tempInt));var $cmp66525=((($conv66424))|0)!=0;if($cmp66525){__label__=184;;}else{__label__=189;;}
$for_body666$$for_end677$262:do{if(__label__==184){while(1){var $304=$p659;var $305=HEAP8[($304)];var $conv667=(tempInt=(($305)),(tempInt>=128?tempInt-256:tempInt));var $cmp668=((($conv667))|0)==6;if($cmp668){__label__=185;;}else{__label__=188;;}
if(__label__==185){var $306=$ix;var $cmp670=((($306))|0)==0;if($cmp670){__label__=186;;}else{__label__=187;;}
if(__label__==186){$ix=1;;}
else if(__label__==187){var $307=$p659;HEAP8[($307)]=5;;}}
var $308=$p659;var $incdec_ptr676=(($308+1)&4294967295);$p659=$incdec_ptr676;var $309=$p659;var $310=HEAP8[($309)];var $conv664=(tempInt=(($310)),(tempInt>=128?tempInt-256:tempInt));var $cmp665=((($conv664))|0)!=0;if($cmp665){__label__=184;continue;}else{__label__=189;break $for_body666$$for_end677$262;}}}}while(0);var $arraydecay678=(($unpron_phonemes)&4294967295);var $arraydecay679=(($prefix_phonemes)&4294967295);var $arraydecay680=(($phonemes)&4294967295);var $call681=_snprintf(((_word_phonemes)&4294967295),160,((__str6549)&4294967295),allocate([$arraydecay678,0,0,0,$arraydecay679,0,0,0,$arraydecay680,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));HEAP8[(((_word_phonemes+159)&4294967295))]=0;var $311=$tr_addr;var $arraydecay682=(($dictionary_flags)&4294967295);__Z13SetWordStressP10TranslatorPcPjii($311,((_word_phonemes)&4294967295),$arraydecay682,-1,0);;}}while(0);var $arrayidx706=(($end_phonemes)&4294967295);var $314=HEAP8[($arrayidx706)];var $conv707=(tempInt=(($314)),(tempInt>=128?tempInt-256:tempInt));var $cmp708=((($conv707))|0)!=0;if($cmp708){__label__=193;;}else{__label__=194;;}
if(__label__==193){var $call710=_strlen(((_word_phonemes)&4294967295));$ix=$call710;var $315=$ix;var $sub711=((159-($315))&4294967295);var $arrayidx712=(($end_phonemes+$sub711)&4294967295);HEAP8[($arrayidx712)]=0;var $316=$ix;var $arrayidx713=((_word_phonemes+$316)&4294967295);var $arraydecay714=(($end_phonemes)&4294967295);var $call715=_strcpy($arrayidx713,$arraydecay714);;}
var $317=$wflags;var $and717=($317)&16;var $tobool718=((($and717))|0)!=0;if($tobool718){__label__=195;;}else{__label__=196;;}
if(__label__==195){var $arrayidx720=(($dictionary_flags)&4294967295);var $318=HEAP32[(($arrayidx720)>>2)];var $and721=($318)&-268435457;HEAP32[(($arrayidx720)>>2)]=$and721;;}
var $319=$wflags;var $and723=($319)&128;var $tobool724=((($and723))|0)!=0;if($tobool724){__label__=197;;}else{__label__=199;;}
$land_lhs_true725$$if_else730$279:do{if(__label__==197){var $320=$tr_addr;var $langopts726=(($320)&4294967295);var $stress_flags=(($langopts726+12)&4294967295);var $321=HEAP32[(($stress_flags)>>2)];var $and727=($321)&1048576;var $tobool728=((($and727))|0)!=0;if(!($tobool728)){__label__=199;break $land_lhs_true725$$if_else730$279;}
var $322=$tr_addr;__Z16ChangeWordStressP10TranslatorPci($322,((_word_phonemes)&4294967295),3);__label__=208;break $land_lhs_true725$$if_else730$279;}}while(0);$if_end761$$if_else730$282:do{if(__label__==199){var $323=$wflags;var $and731=($323)&3072;var $tobool732=((($and731))|0)!=0;if($tobool732){__label__=200;;}else{__label__=202;;}
if(__label__==200){var $324=$tr_addr;__Z16ChangeWordStressP10TranslatorPci($324,((_word_phonemes)&4294967295),6);var $325=$wflags;var $and734=($325)&2048;var $tobool735=((($and734))|0)!=0;if(!($tobool735)){__label__=208;break $if_end761$$if_else730$282;}
var $arrayidx737=(($dictionary_flags)&4294967295);var $326=HEAP32[(($arrayidx737)>>2)];var $or738=($326)|268435456;HEAP32[(($arrayidx737)>>2)]=$or738;;}
else if(__label__==202){var $327=HEAP32[((_dictionary_skipwords)>>2)];var $328=$wtab_addr;var $arrayidx741=(($328+12*$327)&4294967295);var $flags742=(($arrayidx741)&4294967295);var $329=HEAP32[(($flags742)>>2)];var $and743=($329)&16;var $tobool744=((($and743))|0)!=0;if(!($tobool744)){__label__=208;break $if_end761$$if_else730$282;}
var $arrayidx746=(($dictionary_flags)&4294967295);var $330=HEAP32[(($arrayidx746)>>2)];var $and747=($330)&6144;var $tobool748=((($and747))|0)!=0;if($tobool748){__label__=204;;}else{__label__=205;;}
if(__label__==204){var $331=$tr_addr;__Z16ChangeWordStressP10TranslatorPci($331,((_word_phonemes)&4294967295),4);;}
else if(__label__==205){var $arrayidx751=(($dictionary_flags)&4294967295);var $332=HEAP32[(($arrayidx751)>>2)];var $and752=($332)&8192;var $tobool753=((($and752))|0)!=0;if(!($tobool753)){__label__=208;break $if_end761$$if_else730$282;}
var $_b=HEAPU8[(__ZL18any_stressed_words_b)];var $333=((($_b))&1);var $tobool755=((($333))|0)!=0;if(!($tobool755)){__label__=208;break $if_end761$$if_else730$282;}
var $334=$tr_addr;__Z16ChangeWordStressP10TranslatorPci($334,((_word_phonemes)&4294967295),3);;}}}}while(0);var $335=$end_type;var $and762=($335)&8192;var $tobool763=((($and762))|0)!=0;if($tobool763){__label__=209;;}else{__label__=210;;}
if(__label__==209){var $336=$tr_addr;var $expect_verb765=(($336+8272)&4294967295);HEAP32[(($expect_verb765)>>2)]=2;var $337=$tr_addr;var $expect_verb_s=(($337+8280)&4294967295);HEAP32[(($expect_verb_s)>>2)]=2;;}
var $arrayidx767=(($dictionary_flags+4)&4294967295);var $338=HEAP32[(($arrayidx767)>>2)];var $and768=($338)&8;var $tobool769=((($and768))|0)!=0;if($tobool769){__label__=211;;}else{__label__=212;;}
$if_then770$$if_else772$298:do{if(__label__==211){var $339=$tr_addr;var $expect_past=(($339+8276)&4294967295);HEAP32[(($expect_past)>>2)]=3;var $340=$tr_addr;var $expect_verb771=(($340+8272)&4294967295);HEAP32[(($expect_verb771)>>2)]=0;var $341=$tr_addr;var $expect_noun=(($341+8284)&4294967295);HEAP32[(($expect_noun)>>2)]=0;;}
else if(__label__==212){var $arrayidx773=(($dictionary_flags+4)&4294967295);var $342=HEAP32[(($arrayidx773)>>2)];var $and774=($342)&1;var $tobool775=((($and774))|0)!=0;if($tobool775){__label__=213;;}else{__label__=214;;}
if(__label__==213){var $343=$tr_addr;var $expect_verb777=(($343+8272)&4294967295);HEAP32[(($expect_verb777)>>2)]=2;var $344=$tr_addr;var $expect_verb_s778=(($344+8280)&4294967295);HEAP32[(($expect_verb_s778)>>2)]=0;var $345=$tr_addr;var $expect_noun779=(($345+8284)&4294967295);HEAP32[(($expect_noun779)>>2)]=0;;}
else if(__label__==214){var $arrayidx781=(($dictionary_flags+4)&4294967295);var $346=HEAP32[(($arrayidx781)>>2)];var $and782=($346)&2;var $tobool783=((($and782))|0)!=0;if($tobool783){__label__=215;;}else{__label__=216;;}
if(__label__==215){var $347=$tr_addr;var $expect_verb785=(($347+8272)&4294967295);HEAP32[(($expect_verb785)>>2)]=0;var $348=$tr_addr;var $expect_verb_s786=(($348+8280)&4294967295);HEAP32[(($expect_verb_s786)>>2)]=2;var $349=$tr_addr;var $expect_past787=(($349+8276)&4294967295);HEAP32[(($expect_past787)>>2)]=0;var $350=$tr_addr;var $expect_noun788=(($350+8284)&4294967295);HEAP32[(($expect_noun788)>>2)]=0;;}
else if(__label__==216){var $arrayidx790=(($dictionary_flags+4)&4294967295);var $351=HEAP32[(($arrayidx790)>>2)];var $and791=($351)&4;var $tobool792=((($and791))|0)!=0;if(!($tobool792)){__label__=218;break $if_then770$$if_else772$298;}
var $352=$tr_addr;var $expect_noun794=(($352+8284)&4294967295);HEAP32[(($expect_noun794)>>2)]=2;var $353=$tr_addr;var $expect_verb795=(($353+8272)&4294967295);HEAP32[(($expect_verb795)>>2)]=0;var $354=$tr_addr;var $expect_verb_s796=(($354+8280)&4294967295);HEAP32[(($expect_verb_s796)>>2)]=0;var $355=$tr_addr;var $expect_past797=(($355+8276)&4294967295);HEAP32[(($expect_past797)>>2)]=0;;}}}}while(0);var $356=HEAP32[(($wordx)>>2)];var $arrayidx802=(($356)&4294967295);var $357=HEAP8[($arrayidx802)];var $conv803=(tempInt=(($357)),(tempInt>=128?tempInt-256:tempInt));var $cmp804=((($conv803))|0)!=0;if($cmp804){__label__=219;;}else{__label__=228;;}
$land_lhs_true805$$if_end834$309:do{if(__label__==219){var $arrayidx806=(($dictionary_flags+4)&4294967295);var $358=HEAP32[(($arrayidx806)>>2)];var $and807=($358)&256;var $tobool808=((($and807))|0)!=0;if($tobool808){__label__=228;break $land_lhs_true805$$if_end834$309;}
var $359=$tr_addr;var $expect_verb810=(($359+8272)&4294967295);var $360=HEAP32[(($expect_verb810)>>2)];var $cmp811=((($360))|0)>0;if($cmp811){__label__=221;;}else{__label__=222;;}
if(__label__==221){var $361=$tr_addr;var $expect_verb813=(($361+8272)&4294967295);var $362=HEAP32[(($expect_verb813)>>2)];var $dec814=((($362)-1)&4294967295);HEAP32[(($expect_verb813)>>2)]=$dec814;;}
var $363=$tr_addr;var $expect_verb_s816=(($363+8280)&4294967295);var $364=HEAP32[(($expect_verb_s816)>>2)];var $cmp817=((($364))|0)>0;if($cmp817){__label__=223;;}else{__label__=224;;}
if(__label__==223){var $365=$tr_addr;var $expect_verb_s819=(($365+8280)&4294967295);var $366=HEAP32[(($expect_verb_s819)>>2)];var $dec820=((($366)-1)&4294967295);HEAP32[(($expect_verb_s819)>>2)]=$dec820;;}
var $367=$tr_addr;var $expect_noun822=(($367+8284)&4294967295);var $368=HEAP32[(($expect_noun822)>>2)];var $cmp823=((($368))|0)>0;if($cmp823){__label__=225;;}else{__label__=226;;}
if(__label__==225){var $369=$tr_addr;var $expect_noun825=(($369+8284)&4294967295);var $370=HEAP32[(($expect_noun825)>>2)];var $dec826=((($370)-1)&4294967295);HEAP32[(($expect_noun825)>>2)]=$dec826;;}
var $371=$tr_addr;var $expect_past828=(($371+8276)&4294967295);var $372=HEAP32[(($expect_past828)>>2)];var $cmp829=((($372))|0)>0;if(!($cmp829)){__label__=228;break $land_lhs_true805$$if_end834$309;}
var $373=$tr_addr;var $expect_past831=(($373+8276)&4294967295);var $374=HEAP32[(($expect_past831)>>2)];var $dec832=((($374)-1)&4294967295);HEAP32[(($expect_past831)>>2)]=$dec832;;}}while(0);var $375=$word_length;var $cmp835=((($375))|0)==1;if($cmp835){__label__=229;;}else{__label__=232;;}
$land_lhs_true836$$if_end846$323:do{if(__label__==229){var $376=$tr_addr;var $translator_name=(($376+280)&4294967295);var $377=HEAP32[(($translator_name)>>2)];var $cmp837=((($377))|0)==25966;if(!($cmp837)){__label__=232;break $land_lhs_true836$$if_end846$323;}
var $378=HEAP32[(($first_char)>>2)];var $call839=_iswalpha($378);var $tobool840=((($call839))|0)!=0;var $379=HEAP32[(($first_char)>>2)];var $cmp842=((($379))|0)!=105;var $or_cond3=($tobool840)&($cmp842);if(!($or_cond3)){__label__=232;break $land_lhs_true836$$if_end846$323;}
var $arrayidx844=(($dictionary_flags)&4294967295);var $380=HEAP32[(($arrayidx844)>>2)];var $or845=($380)|16777216;HEAP32[(($arrayidx844)>>2)]=$or845;;}}while(0);var $381=$tr_addr;var $langopts847=(($381)&4294967295);var $param848=(($langopts847+24)&4294967295);var $arrayidx849=(($param848+60)&4294967295);var $382=HEAP32[(($arrayidx849)>>2)];var $and850=($382)&2;var $tobool851=((($and850))|0)!=0;if($tobool851){__label__=233;;}else{__label__=235;;}
$land_lhs_true852$$if_end858$328:do{if(__label__==233){var $arrayidx853=(($dictionary_flags)&4294967295);var $383=HEAP32[(($arrayidx853)>>2)];var $and854=($383)&3145728;var $cmp855=((($and854))|0)!=0;if(!($cmp855)){__label__=235;break $land_lhs_true852$$if_end858$328;}
var $384=$tr_addr;var $arrayidx857=(($dictionary_flags)&4294967295);var $385=HEAP32[(($arrayidx857)>>2)];__Z22ApplySpecialAttribute2P10TranslatorPci($384,((_word_phonemes)&4294967295),$385);;}}while(0);var $386=$was_unpronouncable;var $arrayidx859=(($dictionary_flags)&4294967295);var $387=HEAP32[(($arrayidx859)>>2)];var $or860=($387)|($386);HEAP32[(($arrayidx859)>>2)]=$or860;var $388=$word_start_addr;var $arraydecay861=(($word_copy2)&4294967295);var $389=$word_copy_length;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay861;$dest$=$388;$stop$=$src$+$389;if(($dest$%4)==($src$%4)&&$389>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $arrayidx862=(($dictionary_flags)&4294967295);var $390=HEAP32[(($arrayidx862)>>2)];$retval=$390;;}}while(0);var $391=$retval;STACKTOP=__stackBase__;return $391;return null;}
function __ZL17CheckDottedAbbrevPcP8WORD_TAB($word1,$wtab){var __stackBase__=STACKTOP;STACKTOP+=84;_memset(__stackBase__,0,84);var __label__;var $word1_addr;var $wtab_addr;var $wc=__stackBase__;var $count;var $nbytes;var $ok;var $ix;var $word;var $wbuf;var $word_buf=__stackBase__+4;$word1_addr=$word1;$wtab_addr=$wtab;$count=0;var $0=$word1_addr;$word=$0;var $arraydecay=(($word_buf)&4294967295);$wbuf=$arraydecay;$ix=0;;$for_cond$2:while(1){$ok=0;var $1=$word;var $call=__Z7utf8_inPiPKc($wc,$1);$nbytes=$call;var $2=$nbytes;var $3=$word;var $arrayidx=(($3+$2)&4294967295);var $4=HEAP8[($arrayidx)];var $conv=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)==32;if($cmp){__label__=2;;}else{__label__=11;;}
$land_lhs_true$$if_end27$4:do{if(__label__==2){var $5=HEAP32[(($wc)>>2)];var $call1=__Z7IsAlphaj($5);var $tobool=((($call1))|0)!=0;if(!($tobool)){__label__=11;break $land_lhs_true$$if_end27$4;}
var $6=$nbytes;var $add=((($6)+1)&4294967295);var $7=$word;var $arrayidx2=(($7+$add)&4294967295);var $8=HEAP8[($arrayidx2)];var $conv3=(tempInt=(($8)),(tempInt>=128?tempInt-256:tempInt));var $cmp4=((($conv3))|0)==46;if($cmp4){__label__=4;;}else{__label__=8;;}
if(__label__==4){var $9=$nbytes;var $add6=((($9)+2)&4294967295);var $10=$word;var $arrayidx7=(($10+$add6)&4294967295);var $11=HEAP8[($arrayidx7)];var $conv8=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $cmp9=((($conv8))|0)==32;if($cmp9){__label__=5;;}else{__label__=6;;}
if(__label__==5){$ok=1;__label__=12;break $land_lhs_true$$if_end27$4;}
else if(__label__==6){var $12=$nbytes;var $add11=((($12)+2)&4294967295);var $13=$word;var $arrayidx12=(($13+$add11)&4294967295);var $14=HEAP8[($arrayidx12)];var $conv13=(tempInt=(($14)),(tempInt>=128?tempInt-256:tempInt));var $cmp14=((($conv13))|0)==39;if(!($cmp14)){__label__=11;break $land_lhs_true$$if_end27$4;}
var $15=$nbytes;var $add16=((($15)+2)&4294967295);$nbytes=$add16;$ok=2;__label__=12;break $land_lhs_true$$if_end27$4;}}
else if(__label__==8){var $16=$count;var $cmp19=((($16))|0)>0;if(!($cmp19)){__label__=11;break $land_lhs_true$$if_end27$4;}
var $17=$nbytes;var $18=$word;var $arrayidx21=(($18+$17)&4294967295);var $19=HEAP8[($arrayidx21)];var $conv22=(tempInt=(($19)),(tempInt>=128?tempInt-256:tempInt));var $cmp23=((($conv22))|0)==32;if(!($cmp23)){__label__=11;break $land_lhs_true$$if_end27$4;}
$ok=2;__label__=12;break $land_lhs_true$$if_end27$4;}}}while(0);if(__label__==11){var $_pr=$ok;var $cmp28=((($_pr))|0)==0;if($cmp28){__label__=17;break $for_cond$2;}}
$ix=0;var $20=$ix;var $21=$nbytes;var $cmp324=((($20))|0)<((($21))|0);if($cmp324){__label__=13;;}else{__label__=14;;}
$for_body$$for_end$19:do{if(__label__==13){while(1){var $22=$ix;var $23=$word;var $arrayidx33=(($23+$22)&4294967295);var $24=HEAP8[($arrayidx33)];var $25=$wbuf;var $incdec_ptr=(($25+1)&4294967295);$wbuf=$incdec_ptr;HEAP8[($25)]=$24;var $26=$ix;var $inc=((($26)+1)&4294967295);$ix=$inc;var $27=$ix;var $28=$nbytes;var $cmp32=((($27))|0)<((($28))|0);if($cmp32){__label__=13;continue;}else{__label__=14;break $for_body$$for_end$19;}}}}while(0);var $29=$count;var $inc34=((($29)+1)&4294967295);$count=$inc34;var $30=$ok;var $cmp35=((($30))|0)==2;var $31=$nbytes;if($cmp35){__label__=15;break $for_cond$2;}
var $add38=((($31)+3)&4294967295);var $33=$word;var $add_ptr39=(($33+$add38)&4294967295);$word=$add_ptr39;__label__=1;continue $for_cond$2;}
if(__label__==15){var $32=$word;var $add_ptr=(($32+$31)&4294967295);$word=$add_ptr;;}
var $34=$count;var $cmp41=((($34))|0)>1;if($cmp41){__label__=18;;}else{__label__=21;;}
if(__label__==18){var $35=$wbuf;var $arraydecay43=(($word_buf)&4294967295);var $sub_ptr_lhs_cast=($35);var $sub_ptr_rhs_cast=($arraydecay43);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$ix=$sub_ptr_sub;var $36=$word1_addr;var $arraydecay44=(($word_buf)&4294967295);var $37=$ix;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay44;$dest$=$36;$stop$=$src$+$37;if(($dest$%4)==($src$%4)&&$37>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $38=$ix;var $39=$word1_addr;var $arrayidx452=(($39+$38)&4294967295);var $40=$word;var $cmp463=((($arrayidx452))>>>0)<((($40))>>>0);if($cmp463){__label__=19;;}else{__label__=20;;}
$while_body$$while_end$29:do{if(__label__==19){while(1){var $41=$ix;var $inc47=((($41)+1)&4294967295);$ix=$inc47;var $42=$word1_addr;var $arrayidx48=(($42+$41)&4294967295);HEAP8[($arrayidx48)]=32;var $43=$ix;var $44=$word1_addr;var $arrayidx45=(($44+$43)&4294967295);var $45=$word;var $cmp46=((($arrayidx45))>>>0)<((($45))>>>0);if($cmp46){__label__=19;continue;}else{__label__=20;break $while_body$$while_end$29;}}}}while(0);var $46=$count;var $sub=((($46)-1)&4294967295);var $mul=((($sub)*2)&4294967295);HEAP32[((_dictionary_skipwords)>>2)]=$mul;;}
var $47=$count;STACKTOP=__stackBase__;return $47;return null;}
function __ZL22SpeakIndividualLettersP10TranslatorPcS1_i($tr,$word,$phonemes,$spell_word){;var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $word_addr;var $phonemes_addr;var $spell_word_addr;var $posn;var $capitals;var $non_initial;$tr_addr=$tr;$word_addr=$word;$phonemes_addr=$phonemes;$spell_word_addr=$spell_word;$posn=0;$capitals=0;$non_initial=0;var $0=$spell_word_addr;var $cmp=((($0))|0)>2;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$capitals=2;;}
$while_cond$4:while(1){var $1=$word_addr;var $2=HEAP8[($1)];var $conv=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));var $cmp1=((($conv))|0)!=32;if(!($cmp1)){__label__=3;break $while_cond$4;}
var $4=$word_addr;var $5=HEAP8[($4)];var $conv2=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $cmp3=((($conv2))|0)!=0;var $6=$tr_addr;if($cmp3){__lastLabel__=4;;}else{__lastLabel__=4;__label__=7;break $while_cond$4;}
var $7=$word_addr;var $8=$phonemes_addr;var $9=$capitals;var $10=$non_initial;var $or=($10)|($9);var $call=__Z15TranslateLetterP10TranslatorPcS1_i($6,$7,$8,$or);var $11=$word_addr;var $add_ptr=(($11+$call)&4294967295);$word_addr=$add_ptr;var $12=$posn;var $inc=((($12)+1)&4294967295);$posn=$inc;$non_initial=1;var $13=$phonemes_addr;var $arrayidx=(($13)&4294967295);var $14=HEAP8[($arrayidx)];var $conv4=(tempInt=(($14)),(tempInt>=128?tempInt-256:tempInt));var $cmp5=((($conv4))|0)==21;if($cmp5){__label__=6;break $while_cond$4;}else{__label__=2;continue $while_cond$4;}}
$land_end_thread$$while_end$$if_then6$8:do{if(__label__==3){var $3=$tr_addr;__lastLabel__=3;__label__=7;break $land_end_thread$$while_end$$if_then6$8;}
else if(__label__==6){var $15=$phonemes_addr;var $call7=_strcpy(((_word_phonemes)&4294967295),$15);$retval=0;__label__=8;break $land_end_thread$$while_end$$if_then6$8;}}while(0);if(__label__==7){var $16=__lastLabel__==3?$3:($6);var $17=$phonemes_addr;var $18=$spell_word_addr;var $19=$posn;__Z17SetSpellingStressP10TranslatorPcii($16,$17,$18,$19);var $20=$word_addr;$retval=$20;;}
var $21=$retval;;return $21;return null;}
function __Z14SetTranslator2PKc($new_language){;var __label__;var $new_language_addr;var $new_phoneme_tab;$new_language_addr=$new_language;var $0=$new_language_addr;var $call=__Z22SelectPhonemeTableNamePKc($0);$new_phoneme_tab=$call;var $cmp=((($call))|0)>=0;if($cmp){__label__=1;;}else{__label__=7;;}
$if_then$$if_end14$2:do{if(__label__==1){var $1=HEAP32[((_translator2)>>2)];var $cmp1=((($1))|0)!=0;if($cmp1){__label__=2;;}else{__label__=5;;}
if(__label__==2){var $2=$new_language_addr;var $call2=_strcmp($2,((__ZL20translator2_language)&4294967295));var $cmp3=((($call2))|0)!=0;var $3=HEAP32[((_translator2)>>2)];if($cmp3){__label__=3;;}else{__label__=4;;}
if(__label__==3){__Z16DeleteTranslatorP10Translator($3);HEAP32[((_translator2)>>2)]=0;;}
else if(__label__==4){var $cmp5=((($3))|0)==0;if(!($cmp5)){__label__=7;break $if_then$$if_end14$2;}}}
var $4=$new_language_addr;var $call7=__Z16SelectTranslatorPKc($4);HEAP32[((_translator2)>>2)]=$call7;var $5=$new_language_addr;var $call8=_strcpy(((__ZL20translator2_language)&4294967295),$5);var $6=HEAP32[((_translator2)>>2)];var $7=$new_language_addr;var $call9=__Z14LoadDictionaryP10TranslatorPKci($6,$7,0);var $cmp10=((($call9))|0)!=0;if(!($cmp10)){__label__=7;break $if_then$$if_end14$2;}
var $8=HEAP32[((_voice)>>2)];var $phoneme_tab_ix=(($8+40)&4294967295);var $9=HEAP32[(($phoneme_tab_ix)>>2)];__Z18SelectPhonemeTablei($9);$new_phoneme_tab=-1;HEAP8[(((__ZL20translator2_language)&4294967295))]=0;;}}while(0);var $10=$new_phoneme_tab;;return $10;return null;}
function __Z15TranslateClauseP10TranslatorP7__sFILEPKvPiPPc($tr,$f_text,$vp_input,$tone_out,$voice_change){var __stackBase__=STACKTOP;STACKTOP+=6500;_memset(__stackBase__,0,6500);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $f_text_addr;var $vp_input_addr;var $tone_out_addr;var $voice_change_addr;var $ix;var $c;var $cc=__stackBase__;var $source_index=__stackBase__+4;var $prev_source_index;var $source_index_word;var $prev_in=__stackBase__+8;var $prev_out=__stackBase__+12;var $prev_out2;var $prev_in2;var $prev_in_save;var $next_in=__stackBase__+16;var $next_in_nbytes;var $char_inserted=__stackBase__+20;var $clause_pause;var $pre_pause_add;var $word_mark;var $all_upper_case;var $finished;var $single_quoted;var $phoneme_mode;var $dict_flags;var $word_flags;var $next_word_flags;var $embedded_count;var $letter_count;var $space_inserted;var $syllable_marked;var $decimal_sep_count;var $word;var $p;var $j;var $k;var $n_digits;var $individual_digits;var $charix_top=__stackBase__+24;var $charix=__stackBase__+28;var $words=__stackBase__+1436;var $word_count;var $sbuf=__stackBase__+5036;var $terminator;var $tone;var $tone2=__stackBase__+5736;var $srcix;var $next2_in=__stackBase__+5740;var $nx;var $c_temp=__stackBase__+5744;var $pn;var $pw;var $nw;var $number_buf=__stackBase__+5748;var $num_wtab=__stackBase__+5900;var $p2;$tr_addr=$tr;$f_text_addr=$f_text;$vp_input_addr=$vp_input;$tone_out_addr=$tone_out;$voice_change_addr=$voice_change;HEAP32[(($source_index)>>2)]=0;$prev_source_index=0;$source_index_word=0;HEAP32[(($prev_out)>>2)]=32;$prev_in2=0;$prev_in_save=0;HEAP32[(($char_inserted)>>2)]=0;$pre_pause_add=0;$word_mark=0;$all_upper_case=1;$phoneme_mode=0;$dict_flags=0;$embedded_count=0;$letter_count=0;$space_inserted=0;$syllable_marked=0;$decimal_sep_count=0;HEAP32[(($charix_top)>>2)]=0;$word_count=0;var $0=$tr_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){$retval=0;;}
else if(__label__==2){var $1=$vp_input_addr;HEAP32[((_p_textinput)>>2)]=$1;var $2=$vp_input_addr;var $3=$2;HEAP32[((_p_wchar_input)>>2)]=$3;HEAP32[((__ZL11embedded_ix)>>2)]=0;HEAP32[((__ZL13embedded_read)>>2)]=0;HEAP32[((_pre_pause)>>2)]=0;HEAP8[(__ZL18any_stressed_words_b)]=0;var $4=HEAP32[((_count_characters)>>2)];HEAP32[((_clause_start_char)>>2)]=$4;var $cmp1=((($4))|0)<0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){HEAP32[((_clause_start_char)>>2)]=0;;}
var $5=HEAP32[((_count_words)>>2)];var $add=((($5)+1)&4294967295);HEAP32[((_clause_start_word)>>2)]=$add;$ix=0;;$for_body$8:while(1){var $6=$ix;var $arrayidx=(($charix+$6*2)&4294967295);HEAP16[(($arrayidx)>>1)]=0;var $7=$ix;var $inc=((($7)+1)&4294967295);$ix=$inc;var $cmp4=((($inc))|0)<700;if($cmp4){__label__=5;continue $for_body$8;}else{__label__=6;break $for_body$8;}}
var $8=$tr_addr;var $9=$f_text_addr;var $arraydecay=(($charix)&4294967295);var $call=__Z10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_($8,$9,((__ZL6source)&4294967295),$arraydecay,$charix_top,700,$tone2,((__ZZ15TranslateClauseP10TranslatorP7__sFILEPKvPiPPcE17voice_change_name)&4294967295));$terminator=$call;var $10=HEAP32[((_f_logespeak)>>2)];var $cmp5=((($10))|0)!=0;if($cmp5){__label__=7;;}else{__label__=11;;}
$land_lhs_true$$if_end17$11:do{if(__label__==7){var $11=HEAP32[((_logging_type)>>2)];var $and=($11)&4;var $tobool=((($and))|0)!=0;if(!($tobool)){__label__=11;break $land_lhs_true$$if_end17$11;}
var $12=HEAP32[((_f_logespeak)>>2)];var $13=$terminator;var $call7=_fprintf($12,((__str7550)&4294967295),allocate([$13,0,0,0],["i32",0,0,0],ALLOC_STACK));$p=((__ZL6source)&4294967295);var $14=$p;var $15=HEAP8[($14)];var $conv59=(tempInt=(($15)),(tempInt>=128?tempInt-256:tempInt));var $cmp960=((($conv59))|0)!=0;if($cmp960){__label__=9;;}else{__label__=10;;}
$for_body10$$for_end14$14:do{if(__label__==9){while(1){var $16=$p;var $17=HEAP8[($16)];var $conv11=(tempInt=(($17)),(tempInt>=128?tempInt-256:tempInt));var $18=HEAP32[((_f_logespeak)>>2)];var $call12=_fputc($conv11,$18);var $19=$p;var $incdec_ptr=(($19+1)&4294967295);$p=$incdec_ptr;var $20=$p;var $21=HEAP8[($20)];var $conv=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));var $cmp9=((($conv))|0)!=0;if($cmp9){__label__=9;continue;}else{__label__=10;break $for_body10$$for_end14$14;}}}}while(0);var $22=HEAP32[((_f_logespeak)>>2)];var $23=_fwrite(((__str8551)&4294967295),10,1,$22);var $24=HEAP32[((_f_logespeak)>>2)];var $call16=_fflush($24);;}}while(0);$p=((__ZL6source)&4294967295);var $25=HEAP32[(($charix_top)>>2)];var $add18=((($25)+1)&4294967295);var $arrayidx19=(($charix+$add18*2)&4294967295);HEAP16[(($arrayidx19)>>1)]=0;var $26=HEAP32[(($charix_top)>>2)];var $add20=((($26)+2)&4294967295);var $arrayidx21=(($charix+$add20*2)&4294967295);HEAP16[(($arrayidx21)>>1)]=32767;var $27=HEAP32[(($charix_top)>>2)];var $add22=((($27)+3)&4294967295);var $arrayidx23=(($charix+$add22*2)&4294967295);HEAP16[(($arrayidx23)>>1)]=0;var $28=$terminator;var $and24=($28)&4095;var $mul=((($and24)*10)&4294967295);$clause_pause=$mul;var $29=$terminator;var $shr=($29)>>12;var $and25=($shr)&7;$tone=$and25;var $30=HEAP32[(($tone2)>>2)];var $cmp26=((($30))|0)!=0;if($cmp26){__label__=12;;}else{__label__=13;;}
if(__label__==12){var $31=HEAP32[(($tone2)>>2)];$tone=$31;;}
$p=((__ZL6source)&4294967295);;$for_cond29$22:while(1){var $32=$p;var $33=HEAP8[($32)];var $conv30=(tempInt=(($33)),(tempInt>=128?tempInt-256:tempInt));var $cmp31=((($conv30))|0)!=0;if(!($cmp31)){__label__=17;break $for_cond29$22;}
var $34=$p;var $35=HEAP8[($34)];var $conv33=(tempInt=(($35)),(tempInt>=128?tempInt-256:tempInt));var $call34=__Z8isspace2j($conv33);var $tobool35=((($call34))|0)!=0;if(!($tobool35)){__label__=17;break $for_cond29$22;}
var $36=$p;var $incdec_ptr39=(($36+1)&4294967295);$p=$incdec_ptr39;__label__=14;continue $for_cond29$22;}
var $37=$p;var $38=HEAP8[($37)];var $conv41=(tempInt=(($38)),(tempInt>=128?tempInt-256:tempInt));var $cmp42=((($conv41))|0)==0;if($cmp42){__label__=18;;}else{__label__=21;;}
if(__label__==18){var $39=HEAP32[((__ZL16max_clause_pause)>>2)];var $40=$clause_pause;var $sub=((($40)-($39))&4294967295);$clause_pause=$sub;var $41=$clause_pause;var $cmp44=((($41))|0)<0;if($cmp44){__label__=19;;}else{__label__=20;;}
if(__label__==19){$clause_pause=0;;}
var $42=$terminator;var $and47=($42)&-524289;$terminator=$and47;var $43=$clause_pause;var $44=HEAP32[((__ZL16max_clause_pause)>>2)];var $add48=((($44)+($43))&4294967295);HEAP32[((__ZL16max_clause_pause)>>2)]=$add48;;}
else if(__label__==21){var $45=$clause_pause;HEAP32[((__ZL16max_clause_pause)>>2)]=$45;;}
var $46=$terminator;var $47=$tr_addr;var $clause_terminator=(($47+8324)&4294967295);HEAP32[(($clause_terminator)>>2)]=$46;var $48=HEAP32[((_new_sentence)>>2)];var $tobool50=((($48))|0)!=0;if($tobool50){__label__=23;;}else{__label__=26;;}
$if_then51$$if_end59$34:do{if(__label__==23){var $49=HEAP32[((_count_sentences)>>2)];var $inc52=((($49)+1)&4294967295);HEAP32[((_count_sentences)>>2)]=$inc52;var $50=HEAP32[((_skip_sentences)>>2)];var $cmp53=((($50))|0)>0;if(!($cmp53)){__label__=26;break $if_then51$$if_end59$34;}
var $51=HEAP32[((_skip_sentences)>>2)];var $dec=((($51)-1)&4294967295);HEAP32[((_skip_sentences)>>2)]=$dec;var $52=HEAP32[((_skip_sentences)>>2)];var $cmp55=((($52))|0)==0;if(!($cmp55)){__label__=26;break $if_then51$$if_end59$34;}
HEAP32[((_skipping_text)>>2)]=0;;}}while(0);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=((_ph_list2)&4294967295);$stop$=$dest$+8;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};HEAP8[(((_ph_list2)&4294967295))]=10;HEAP32[((_n_ph_list2)>>2)]=1;var $53=$tr_addr;var $prev_last_stress=(($53+8288)&4294967295);HEAP32[(($prev_last_stress)>>2)]=0;var $54=$tr_addr;var $prepause_timeout=(($54+8312)&4294967295);HEAP32[(($prepause_timeout)>>2)]=0;var $55=$tr_addr;var $expect_verb=(($55+8272)&4294967295);HEAP32[(($expect_verb)>>2)]=0;var $56=$tr_addr;var $expect_noun=(($56+8284)&4294967295);HEAP32[(($expect_noun)>>2)]=0;var $57=$tr_addr;var $expect_past=(($57+8276)&4294967295);HEAP32[(($expect_past)>>2)]=0;var $58=$tr_addr;var $expect_verb_s=(($58+8280)&4294967295);HEAP32[(($expect_verb_s)>>2)]=0;var $59=$tr_addr;var $phonemes_repeat_count=(($59+652)&4294967295);HEAP32[(($phonemes_repeat_count)>>2)]=0;var $60=$tr_addr;var $end_stressed_vowel=(($60+8316)&4294967295);HEAP32[(($end_stressed_vowel)>>2)]=0;var $61=$tr_addr;var $prev_dict_flags=(($61+8320)&4294967295);HEAP32[(($prev_dict_flags)>>2)]=0;$word_count=0;$single_quoted=0;$word_flags=0;$next_word_flags=0;var $arrayidx60=(($sbuf)&4294967295);HEAP8[($arrayidx60)]=0;var $arrayidx61=(($sbuf+1)&4294967295);HEAP8[($arrayidx61)]=32;var $arrayidx62=(($sbuf+2)&4294967295);HEAP8[($arrayidx62)]=32;$ix=3;HEAP32[(($prev_in)>>2)]=32;var $62=$ix;var $conv63=((($62))&65535);var $arrayidx64=(($words)&4294967295);var $start=(($arrayidx64+4)&4294967295);HEAP16[(($start)>>1)]=$conv63;var $arrayidx65=(($words)&4294967295);var $flags=(($arrayidx65)&4294967295);HEAP32[(($flags)>>2)]=0;$finished=0;$j=0;var $63=$j;var $arrayidx6755=(($charix+$63*2)&4294967295);var $64=HEAP16[(($arrayidx6755)>>1)];var $conv6856=(tempInt=(($64)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp6957=((($conv6856))|0)<=0;var $65=$j;if($cmp6957){__lastLabel__=26;__label__=27;;}else{__lastLabel__=26;__label__=28;;}
$for_inc71$$for_end73$39:do{if(__label__==27){while(1){var $66=__lastLabel__==27?$69:($65);var $inc72=((($66)+1)&4294967295);$j=$inc72;var $67=$j;var $arrayidx67=(($charix+$67*2)&4294967295);var $68=HEAP16[(($arrayidx67)>>1)];var $conv68=(tempInt=(($68)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp69=((($conv68))|0)<=0;var $69=$j;if($cmp69){__lastLabel__=27;__label__=27;continue;}else{__lastLabel__=27;__label__=28;break $for_inc71$$for_end73$39;}}}}while(0);var $_lcssa54=__lastLabel__==26?$65:($69);var $arrayidx74=(($charix+$_lcssa54*2)&4294967295);var $70=HEAP16[(($arrayidx74)>>1)];var $arrayidx75=(($words)&4294967295);var $sourceix=(($arrayidx75+6)&4294967295);HEAP16[(($sourceix)>>1)]=$70;$k=0;var $71=$j;var $arrayidx7651=(($charix+$71*2)&4294967295);var $72=HEAP16[(($arrayidx7651)>>1)];var $conv7752=(tempInt=(($72)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp7853=((($conv7752))|0)!=0;if($cmp7853){__label__=29;;}else{__label__=32;;}
$while_body$$while_end$43:do{if(__label__==29){while(1){var $73=$j;var $inc79=((($73)+1)&4294967295);$j=$inc79;var $arrayidx80=(($charix+$73*2)&4294967295);var $74=HEAP16[(($arrayidx80)>>1)];var $conv81=(tempInt=(($74)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp82=((($conv81))|0)!=-1;if($cmp82){__label__=30;;}else{__label__=31;;}
if(__label__==30){var $75=$k;var $inc84=((($75)+1)&4294967295);$k=$inc84;;}
var $76=$j;var $arrayidx76=(($charix+$76*2)&4294967295);var $77=HEAP16[(($arrayidx76)>>1)];var $conv77=(tempInt=(($77)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp78=((($conv77))|0)!=0;if($cmp78){__label__=29;continue;}else{__label__=32;break $while_body$$while_end$43;}}}}while(0);var $78=$k;var $conv86=((($78))&255);var $arrayidx87=(($words)&4294967295);var $length=(($arrayidx87+10)&4294967295);HEAP8[($length)]=$conv86;;$while_cond88$50:while(1){var $79=$finished;var $tobool89=((($79))|0)!=0;if($tobool89){__label__=230;break $while_cond88$50;}
var $80=$ix;var $cmp91=((($80))|0)<700;var $81=HEAP32[((_n_ph_list2)>>2)];var $cmp92=((($81))|0)<996;var $or_cond12=($cmp91)&($cmp92);if(!($or_cond12)){__label__=230;break $while_cond88$50;}
var $82=HEAP32[(($prev_out)>>2)];$prev_out2=$82;var $83=$ix;var $sub94=((($83)-1)&4294967295);var $arrayidx95=(($sbuf+$sub94)&4294967295);var $call96=__Z8utf8_in2PiPKci($prev_out,$arrayidx95,1);var $84=$tr_addr;var $langopts=(($84)&4294967295);var $tone_numbers=(($langopts+250)&4294967295);var $85=HEAP8[($tone_numbers)];var $tobool97=(tempInt=(($85)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool97){__label__=36;;}else{__label__=39;;}
$land_lhs_true98$$if_end105$54:do{if(__label__==36){var $86=HEAP32[(($prev_out)>>2)];var $call99=__ZL9IsDigit09j($86);var $tobool100=((($call99))|0)!=0;if(!($tobool100)){__label__=39;break $land_lhs_true98$$if_end105$54;}
var $87=$prev_out2;var $call102=__Z7IsAlphaj($87);var $tobool103=((($call102))|0)!=0;if(!($tobool103)){__label__=39;break $land_lhs_true98$$if_end105$54;}
HEAP32[(($prev_out)>>2)]=97;;}}while(0);var $88=$prev_in_save;var $cmp106=((($88))|0)!=0;if($cmp106){__label__=40;;}else{__label__=41;;}
$if_then107$$if_else108$59:do{if(__label__==40){var $89=$prev_in_save;HEAP32[(($prev_in)>>2)]=$89;$prev_in_save=0;;}
else if(__label__==41){var $90=HEAPU32[(($source_index)>>2)];var $cmp109=((($90))>>>0)>0;if(!($cmp109)){__label__=43;break $if_then107$$if_else108$59;}
var $91=HEAP32[(($prev_in)>>2)];$prev_in2=$91;var $92=HEAP32[(($source_index)>>2)];var $sub111=((($92)-1)&4294967295);var $arrayidx112=((__ZL6source+$sub111)&4294967295);var $call113=__Z8utf8_in2PiPKci($prev_in,$arrayidx112,1);;}}while(0);var $93=HEAP32[(($source_index)>>2)];$prev_source_index=$93;var $94=HEAP32[(($char_inserted)>>2)];var $tobool116=((($94))|0)!=0;if($tobool116){__label__=44;;}else{__label__=45;;}
if(__label__==44){var $95=HEAP32[(($char_inserted)>>2)];$c=$95;HEAP32[(($char_inserted)>>2)]=0;;}
else if(__label__==45){var $96=HEAP32[(($source_index)>>2)];var $arrayidx119=((__ZL6source+$96)&4294967295);var $call120=__Z7utf8_inPiPKc($cc,$arrayidx119);var $97=HEAP32[(($source_index)>>2)];var $add121=((($97)+($call120))&4294967295);HEAP32[(($source_index)>>2)]=$add121;var $98=HEAP32[(($cc)>>2)];$c=$98;;}
var $99=HEAP32[(($source_index)>>2)];var $arrayidx123=((__ZL6source+$99)&4294967295);var $call124=__Z7utf8_inPiPKc($next_in,$arrayidx123);$next_in_nbytes=$call124;var $100=$c;if($100==0){__label__=47;;}
else if($100==1){__label__=49;;}
else{__label__=48;;}
$lor_lhs_false$$if_end127_thread$$if_then131$68:do{if(__label__==47){$finished=1;$c=32;__label__=48;break $lor_lhs_false$$if_end127_thread$$if_then131$68;}}while(0);$lor_lhs_false$$if_then131$70:do{if(__label__==48){var $101=$c;var $102=HEAP8[(_ctrl_embedded)];var $conv129=(tempInt=(($102)),(tempInt>=128?tempInt-256:tempInt));var $cmp130=((($101))|0)==((($conv129))|0);if($cmp130){__label__=49;break $lor_lhs_false$$if_then131$70;}else{__label__=52;break $lor_lhs_false$$if_then131$70;}}}while(0);if(__label__==49){var $103=HEAP32[(($source_index)>>2)];var $sub132=((($103)-1)&4294967295);$srcix=$sub132;var $104=HEAP32[(($prev_in)>>2)];var $cmp133=((($104))|0)!=32;if($cmp133){__label__=50;;}else{__label__=51;;}
if(__label__==50){$c=32;var $105=$c;$prev_in_save=$105;var $106=HEAP32[(($source_index)>>2)];var $dec135=((($106)-1)&4294967295);HEAP32[(($source_index)>>2)]=$dec135;;}
else if(__label__==51){var $call137=__ZL15EmbeddedCommandRj($source_index);var $107=$embedded_count;var $add138=((($107)+($call137))&4294967295);$embedded_count=$add138;var $108=HEAP32[(($prev_in)>>2)];$prev_in_save=$108;var $109=$srcix;var $arrayidx139=((__ZL6source+$109)&4294967295);var $110=HEAP32[(($source_index)>>2)];var $111=$srcix;var $sub140=((($110)-($111))&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arrayidx139;$stop$=$dest$+$sub140;$value4$=32;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=32;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=32;};var $112=$srcix;HEAP32[(($source_index)>>2)]=$112;__label__=33;continue $while_cond88$50;}}
var $113=HEAP32[((__ZL13option_sayas2)>>2)];var $cmp143=((($113))|0)==36;if($cmp143){__label__=53;;}else{__label__=58;;}
$land_lhs_true144$$if_end153$78:do{if(__label__==53){var $114=$c;var $cmp145=((($114))|0)!=32;if(!($cmp145)){__label__=58;break $land_lhs_true144$$if_end153$78;}
var $115=HEAP32[(($prev_in)>>2)];var $cmp147=((($115))|0)==32;if($cmp147){__label__=55;;}else{__label__=57;;}
$land_lhs_true148$$if_end151$81:do{if(__label__==55){var $116=HEAP32[(($next_in)>>2)];var $cmp149=((($116))|0)==32;if(!($cmp149)){__label__=57;break $land_lhs_true148$$if_end151$81;}
HEAP32[((__ZL13option_sayas2)>>2)]=20;;}}while(0);var $117=$c;var $call152=__Z9towlower2j($117);$c=$call152;;}}while(0);var $118=$phoneme_mode;var $tobool154=((($118))|0)!=0;if($tobool154){__label__=59;;}else{__label__=62;;}
$if_then155$$if_else162$86:do{if(__label__==59){$all_upper_case=8;var $119=$c;var $cmp156=((($119))|0)==93;if(!($cmp156)){__label__=195;break $if_then155$$if_else162$86;}
var $120=HEAP32[(($next_in)>>2)];var $cmp158=((($120))|0)==93;if(!($cmp158)){__label__=195;break $if_then155$$if_else162$86;}
$phoneme_mode=0;var $121=HEAP32[(($source_index)>>2)];var $inc160=((($121)+1)&4294967295);HEAP32[(($source_index)>>2)]=$inc160;$c=32;;}
else if(__label__==62){var $122=HEAP32[((__ZL13option_sayas2)>>2)];var $and163=($122)&240;var $cmp164=((($and163))|0)==64;if($cmp164){__label__=63;;}else{__label__=68;;}
if(__label__==63){var $123=$c;var $call166=_iswdigit($123);var $tobool167=((($call166))|0)!=0;if($tobool167){__label__=64;;}else{__label__=66;;}
if(__label__==64){var $124=HEAP32[((__ZL18count_sayas_digits)>>2)];var $inc169=((($124)+1)&4294967295);HEAP32[((__ZL18count_sayas_digits)>>2)]=$inc169;var $125=HEAP32[((__ZL18count_sayas_digits)>>2)];var $126=HEAP32[((__ZL13option_sayas2)>>2)];var $and170=($126)&15;var $cmp171=((($125))|0)>((($and170))|0);if(!($cmp171)){__label__=195;break $if_then155$$if_else162$86;}
$c=32;$space_inserted=1;HEAP32[((__ZL18count_sayas_digits)>>2)]=0;;}
else if(__label__==66){HEAP32[((__ZL18count_sayas_digits)>>2)]=0;var $127=HEAP32[(($prev_out)>>2)];var $call175=_iswdigit($127);var $tobool176=((($call175))|0)!=0;if(!($tobool176)){__label__=195;break $if_then155$$if_else162$86;}
$c=32;$space_inserted=1;;}}
else if(__label__==68){var $128=HEAP32[((__ZL13option_sayas2)>>2)];var $and181=($128)&16;var $cmp182=((($and181))|0)==0;if(!($cmp182)){__label__=195;break $if_then155$$if_else162$86;}
var $129=$c;var $cmp184=((($129))|0)==146;var $130=$c;var $cmp186=((($130))|0)==180;var $or_cond=($cmp184)|($cmp186);var $131=$c;var $cmp188=((($131))|0)==8217;var $or_cond2=($or_cond)|($cmp188);var $132=$c;var $cmp190=((($132))|0)==8242;var $or_cond3=($or_cond2)|($cmp190);if($or_cond3){__label__=70;;}else{__label__=71;;}
if(__label__==70){$c=39;;}
var $133=$c;var $cmp193=((($133))|0)==8216;var $134=$c;var $cmp195=((($134))|0)==63;var $or_cond4=($cmp193)|($cmp195);if($or_cond4){__lastLabel__=71;__label__=72;;}else{__lastLabel__=71;__label__=76;;}
$land_lhs_true196$$if_end203$103:do{if(__label__==72){var $135=HEAP32[(($prev_out)>>2)];var $call197=__Z7IsAlphaj($135);var $tobool198=((($call197))|0)!=0;if($tobool198){__label__=73;;}else{__label__=75;;}
$land_lhs_true199$$if_end203thread_pre_split$105:do{if(__label__==73){var $136=HEAP32[(($next_in)>>2)];var $call200=__Z7IsAlphaj($136);var $tobool201=((($call200))|0)!=0;if(!($tobool201)){__label__=75;break $land_lhs_true199$$if_end203thread_pre_split$105;}
$c=39;__label__=80;break $land_lhs_true196$$if_end203$103;}}while(0);var $_pr=$c;__lastLabel__=75;__label__=76;break $land_lhs_true196$$if_end203$103;}}while(0);$if_end210$$if_end203$109:do{if(__label__==76){var $137=__lastLabel__==75?$_pr:($134);var $cmp204=((($137))|0)==1328;if($cmp204){__label__=77;;}else{__label__=78;;}
if(__label__==77){$c=32;var $138=$word_flags;var $or=($138)|1024;$word_flags=$or;;}
else if(__label__==78){var $_pr15_pr=$c;var $cmp207=((($_pr15_pr))|0)==1367;if(!($cmp207)){__label__=80;break $if_end210$$if_end203$109;}
$c=32;var $139=$word_flags;var $or209=($139)|131072;$word_flags=$or209;;}}}while(0);var $140=$tr_addr;var $141=HEAP32[(($source_index)>>2)];var $arrayidx211=((__ZL6source+$141)&4294967295);var $142=HEAP32[(($prev_in)>>2)];var $143=$c;var $144=HEAP32[(($next_in)>>2)];var $call212=__ZL13TranslateCharP10TranslatorPcijjPi($140,$arrayidx211,$142,$143,$144,$char_inserted);$c=$call212;var $cmp213=((($call212))|0)==8;if($cmp213){__label__=33;continue $while_cond88$50;}
var $145=HEAP32[(($char_inserted)>>2)];var $tobool216=((($145))|0)!=0;if($tobool216){__label__=82;;}else{__label__=83;;}
if(__label__==82){var $146=HEAP32[(($char_inserted)>>2)];HEAP32[(($next_in)>>2)]=$146;;}
var $147=$c;var $call219=__Z7IsAlphaj($147);var $tobool220=((($call219))|0)!=0;if($tobool220){__label__=91;;}else{__label__=84;;}
$if_end244$$land_lhs_true221$120:do{if(__label__==84){var $148=$c;var $call222=__Z7IsSpacej($148);var $tobool223=((($call222))|0)!=0;if($tobool223){__label__=91;break $if_end244$$land_lhs_true221$120;}
var $149=$tr_addr;var $punct_within_word=(($149+704)&4294967295);var $150=HEAP32[(($punct_within_word)>>2)];var $151=$c;var $call225=_wcschr($150,$151);var $cmp226=((($call225))|0)==0;if(!($cmp226)){__label__=91;break $if_end244$$land_lhs_true221$120;}
var $152=HEAP32[(($prev_out)>>2)];var $call228=__Z7IsAlphaj($152);var $tobool229=((($call228))|0)!=0;if(!($tobool229)){__label__=91;break $if_end244$$land_lhs_true221$120;}
var $153=$tr_addr;var $langopts231=(($153)&4294967295);var $tone_numbers232=(($langopts231+250)&4294967295);var $154=HEAP8[($tone_numbers232)];var $tobool233=(tempInt=(($154)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool233){__label__=88;;}else{__label__=90;;}
$land_lhs_true234$$if_else241$125:do{if(__label__==88){var $155=$c;var $call235=__ZL9IsDigit09j($155);var $tobool236=((($call235))|0)!=0;if(!($tobool236)){__label__=90;break $land_lhs_true234$$if_else241$125;}
var $156=HEAP32[(($next_in)>>2)];var $call238=__ZL9IsDigit09j($156);var $tobool239=((($call238))|0)!=0;if(!($tobool239)){__label__=91;break $if_end244$$land_lhs_true221$120;}}}while(0);$c=32;$space_inserted=1;;}}while(0);var $157=HEAP32[(($prev_out)>>2)];var $call245=_iswdigit($157);var $tobool246=((($call245))|0)!=0;if($tobool246){__label__=92;;}else{__label__=94;;}
$if_then247$$if_else258$130:do{if(__label__==92){var $158=$c;var $call248=_iswdigit($158);var $tobool249=((($call248))|0)==0;var $159=$c;var $cmp251=((($159))|0)!=46;var $or_cond5=($tobool249)&($cmp251);var $160=$c;var $cmp253=((($160))|0)!=44;var $or_cond6=($or_cond5)&($cmp253);var $161=$c;var $cmp255=((($161))|0)!=32;var $or_cond7=($or_cond6)&($cmp255);if($or_cond7){__lastLabel__=92;;}else{__lastLabel__=92;__label__=97;break $if_then247$$if_else258$130;}
$c=32;$space_inserted=1;__label__=101;break $if_then247$$if_else258$130;}
else if(__label__==94){var $162=HEAP32[(($prev_in)>>2)];var $cmp259=((($162))|0)!=44;if($cmp259){__label__=95;;}else{__label__=96;;}
if(__label__==95){$decimal_sep_count=0;;}
var $_pr17=$c;__lastLabel__=96;__label__=97;break $if_then247$$if_else258$130;}}while(0);$if_end273$$if_end262$137:do{if(__label__==97){var $163=__lastLabel__==96?$_pr17:($161);var $cmp263=((($163))|0)==91;if(!($cmp263)){__label__=101;break $if_end273$$if_end262$137;}
var $164=HEAP32[(($next_in)>>2)];var $cmp265=((($164))|0)==2;if($cmp265){__label__=100;;}else{__label__=99;;}
if(__label__==99){var $165=HEAP32[(($next_in)>>2)];var $cmp267=((($165))|0)==91;var $166=HEAP32[((_option_phoneme_input)>>2)];var $tobool269=((($166))|0)!=0;var $or_cond8=($cmp267)&($tobool269);if(!($or_cond8)){__label__=101;break $if_end273$$if_end262$137;}}
$phoneme_mode=8;var $167=HEAP32[(($source_index)>>2)];var $inc271=((($167)+1)&4294967295);HEAP32[(($source_index)>>2)]=$inc271;__label__=33;continue $while_cond88$50;}}while(0);var $168=$c;var $call274=__Z7IsAlphaj($168);var $tobool275=((($call274))|0)!=0;if($tobool275){__label__=102;;}else{__label__=138;;}
if(__label__==102){var $169=HEAP32[(($prev_out)>>2)];var $call277=__Z7IsAlphaj($169);var $tobool278=((($call277))|0)!=0;if($tobool278){__label__=103;;}else{__label__=106;;}
$lor_lhs_false279$$if_then286$146:do{if(__label__==103){var $170=$tr_addr;var $langopts280=(($170)&4294967295);var $ideographs=(($langopts280+251)&4294967295);var $171=HEAP8[($ideographs)];var $tobool281=(tempInt=(($171)),(tempInt>=128?tempInt-256:tempInt))!=0;if(!($tobool281)){__label__=118;break $lor_lhs_false279$$if_then286$146;}
var $172=$c;var $cmp283=((($172))|0)>12352;if($cmp283){__label__=106;break $lor_lhs_false279$$if_then286$146;}
var $173=HEAP32[(($prev_out)>>2)];var $cmp285=((($173))|0)>12352;if($cmp285){__label__=106;break $lor_lhs_false279$$if_then286$146;}else{__label__=118;break $lor_lhs_false279$$if_then286$146;}}}while(0);$if_then286$$if_end327$150:do{if(__label__==106){var $174=$tr_addr;var $punct_within_word287=(($174+704)&4294967295);var $175=HEAP32[(($punct_within_word287)>>2)];var $176=HEAP32[(($prev_out)>>2)];var $call288=_wcschr($175,$176);var $cmp289=((($call288))|0)==0;if($cmp289){__label__=107;;}else{__label__=108;;}
if(__label__==107){$letter_count=0;;}
var $177=HEAP32[(($prev_out)>>2)];var $cmp292=((($177))|0)!=32;if($cmp292){__label__=109;;}else{__label__=112;;}
$land_lhs_true293$$if_else303$155:do{if(__label__==109){var $178=$tr_addr;var $punct_within_word294=(($178+704)&4294967295);var $179=HEAP32[(($punct_within_word294)>>2)];var $180=HEAP32[(($prev_out)>>2)];var $call295=_wcschr($179,$180);var $cmp296=((($call295))|0)==0;if(!($cmp296)){__label__=112;break $land_lhs_true293$$if_else303$155;}
$c=32;$space_inserted=1;var $181=HEAP32[(($prev_out)>>2)];var $call298=__Z9IsBracketi($181);var $tobool299=((($call298))|0)!=0;if($tobool299){__label__=118;break $if_then286$$if_end327$150;}
var $182=$next_word_flags;var $or301=($182)|256;$next_word_flags=$or301;__label__=118;break $if_then286$$if_end327$150;}}while(0);var $183=$c;var $call304=_iswupper($183);var $tobool305=((($call304))|0)!=0;if($tobool305){__label__=113;;}else{__label__=114;;}
if(__label__==113){var $184=$word_flags;var $or307=($184)|2;$word_flags=$or307;;}
var $185=HEAP32[(($prev_out)>>2)];var $cmp309=((($185))|0)==32;if(!($cmp309)){__label__=118;break $if_then286$$if_end327$150;}
var $186=$ix;var $sub311=((($186)-2)&4294967295);var $arrayidx312=(($sbuf+$sub311)&4294967295);var $187=HEAP8[($arrayidx312)];var $conv313=(tempInt=(($187)),(tempInt>=128?tempInt-256:tempInt));var $call314=_iswdigit($conv313);var $tobool315=((($call314))|0)!=0;if(!($tobool315)){__label__=118;break $if_then286$$if_end327$150;}
var $188=HEAP32[(($prev_in)>>2)];var $call317=_iswdigit($188);var $tobool318=((($call317))|0)!=0;if($tobool318){__label__=118;break $if_then286$$if_end327$150;}
var $189=$ix;var $inc320=((($189)+1)&4294967295);$ix=$inc320;var $arrayidx321=(($sbuf+$189)&4294967295);HEAP8[($arrayidx321)]=32;var $190=$word_count;var $arrayidx322=(($words+$190*12)&4294967295);var $start323=(($arrayidx322+4)&4294967295);var $191=HEAP16[(($start323)>>1)];var $inc324=((($191)+1)&65535);HEAP16[(($start323)>>1)]=$inc324;;}}while(0);var $192=$letter_count;var $inc328=((($192)+1)&4294967295);$letter_count=$inc328;var $193=$c;var $call329=_iswupper($193);var $tobool330=((($call329))|0)!=0;if($tobool330){__label__=119;;}else{__label__=130;;}
if(__label__==119){var $194=$c;var $call332=__Z9towlower2j($194);$c=$call332;var $195=$tr_addr;var $langopts333=(($195)&4294967295);var $param=(($langopts333+24)&4294967295);var $arrayidx334=(($param+52)&4294967295);var $196=HEAP32[(($arrayidx334)>>2)];$j=$196;var $cmp335=((($196))|0)>0;if($cmp335){__label__=120;;}else{__label__=123;;}
if(__label__==120){var $197=$j;var $cmp337=((($197))|0)==2;if(!($cmp337)){__label__=195;break $if_then155$$if_else162$86;}
var $198=$syllable_marked;var $cmp339=((($198))|0)==0;if(!($cmp339)){__label__=195;break $if_then155$$if_else162$86;}
var $199=$c;HEAP32[(($char_inserted)>>2)]=$199;$c=712;$syllable_marked=1;;}
else if(__label__==123){var $200=HEAP32[(($prev_in)>>2)];var $call343=_iswlower($200);var $tobool344=((($call343))|0)!=0;if($tobool344){__label__=124;;}else{__label__=125;;}
if(__label__==124){$c=32;$space_inserted=1;var $201=$c;$prev_in_save=$201;;}
else if(__label__==125){var $202=$c;var $cmp347=((($202))|0)!=32;if(!($cmp347)){__label__=195;break $if_then155$$if_else162$86;}
var $203=HEAP32[(($prev_in)>>2)];var $call349=_iswupper($203);var $tobool350=((($call349))|0)!=0;if(!($tobool350)){__label__=195;break $if_then155$$if_else162$86;}
var $204=HEAP32[(($next_in)>>2)];var $call352=_iswlower($204);var $tobool353=((($call352))|0)!=0;if(!($tobool353)){__label__=195;break $if_then155$$if_else162$86;}
var $205=HEAP32[(($source_index)>>2)];var $206=$next_in_nbytes;var $add355=((($206)+($205))&4294967295);var $arrayidx356=((__ZL6source+$add355)&4294967295);var $call357=__Z7utf8_inPiPKc($next2_in,$arrayidx356);var $207=HEAP32[(($next2_in)>>2)];var $call358=__Z7IsAlphaj($207);var $tobool359=((($call358))|0)!=0;if(!($tobool359)){__label__=195;break $if_then155$$if_else162$86;}
$c=32;$space_inserted=1;var $208=$c;$prev_in_save=$208;var $209=$next_word_flags;var $or361=($209)|256;$next_word_flags=$or361;;}}}
else if(__label__==130){var $210=$all_upper_case;var $tobool367=((($210))|0)!=0;if($tobool367){__label__=131;;}else{__label__=137;;}
$land_lhs_true368$$if_else386$182:do{if(__label__==131){var $211=$letter_count;var $cmp369=((($211))|0)>2;if(!($cmp369)){__label__=137;break $land_lhs_true368$$if_else386$182;}
var $212=$c;var $cmp371=((($212))|0)==115;if($cmp371){__label__=133;;}else{__label__=136;;}
$land_lhs_true372$$if_else384$185:do{if(__label__==133){var $213=HEAP32[(($next_in)>>2)];var $cmp373=((($213))|0)==32;if(!($cmp373)){__label__=136;break $land_lhs_true372$$if_else384$185;}
$c=32;var $214=$all_upper_case;var $or375=($214)|4;$all_upper_case=$or375;var $215=$ix;var $sub376=((($215)-1)&4294967295);var $arrayidx377=(($sbuf+$sub376)&4294967295);var $216=HEAP8[($arrayidx377)];var $conv378=(tempInt=(($216)),(tempInt>=128?tempInt-256:tempInt));var $cmp379=((($conv378))|0)==39;if(!($cmp379)){__label__=195;break $if_then155$$if_else162$86;}
var $217=$ix;var $sub381=((($217)-1)&4294967295);var $arrayidx382=(($sbuf+$sub381)&4294967295);HEAP8[($arrayidx382)]=32;__label__=195;break $if_then155$$if_else162$86;}}while(0);$all_upper_case=0;__label__=195;break $if_then155$$if_else162$86;}}while(0);$all_upper_case=0;;}}
else if(__label__==138){var $218=$c;var $cmp390=((($218))|0)==45;if($cmp390){__label__=139;;}else{__label__=154;;}
if(__label__==139){var $219=HEAP32[(($prev_in)>>2)];var $call392=__Z7IsSpacej($219);var $tobool393=((($call392))|0)!=0;if($tobool393){__label__=146;;}else{__label__=140;;}
$if_else410$$land_lhs_true394$194:do{if(__label__==140){var $220=HEAP32[(($next_in)>>2)];var $call395=__Z7IsAlphaj($220);var $tobool396=((($call395))|0)!=0;if(!($tobool396)){__label__=146;break $if_else410$$land_lhs_true394$194;}
var $221=HEAP32[(($prev_out)>>2)];var $cmp398=((($221))|0)!=32;if($cmp398){__label__=142;;}else{__label__=143;;}
if(__label__==142){$c=32;$space_inserted=1;__label__=195;break $if_then155$$if_else162$86;}
else if(__label__==143){var $222=$word_flags;var $or401=($222)|128;$word_flags=$or401;var $223=$word_count;var $cmp402=((($223))|0)>0;if($cmp402){__label__=144;;}else{__label__=145;;}
if(__label__==144){var $224=$word_count;var $sub404=((($224)-1)&4294967295);var $arrayidx405=(($words+$sub404*12)&4294967295);var $flags406=(($arrayidx405)&4294967295);var $225=HEAP32[(($flags406)>>2)];var $or407=($225)|16384;HEAP32[(($flags406)>>2)]=$or407;;}
$c=32;__label__=195;break $if_then155$$if_else162$86;}}}while(0);var $226=HEAP32[(($prev_in)>>2)];var $cmp411=((($226))|0)==32;var $227=HEAP32[(($next_in)>>2)];var $cmp413=((($227))|0)==32;var $or_cond26=($cmp411)&($cmp413);if($or_cond26){__label__=147;;}else{__label__=148;;}
if(__label__==147){$c=32;$pre_pause_add=4;;}
else if(__label__==148){var $cmp416=((($227))|0)==45;if($cmp416){__label__=149;;}else{__label__=150;;}
if(__label__==149){var $228=HEAP32[(($source_index)>>2)];var $inc418=((($228)+1)&4294967295);HEAP32[(($source_index)>>2)]=$inc418;$c=32;$pre_pause_add=4;;}
else if(__label__==150){var $229=HEAP32[(($prev_out)>>2)];var $cmp420=((($229))|0)==32;if(!($cmp420)){__label__=195;break $if_then155$$if_else162$86;}
var $230=$ix;var $sub422=((($230)-2)&4294967295);var $arrayidx423=(($sbuf+$sub422)&4294967295);var $231=HEAP8[($arrayidx423)];var $conv424=(tempInt=(($231)),(tempInt>=128?tempInt-256:tempInt));var $call425=__Z7IsAlphaj($conv424);var $tobool426=((($call425))|0)!=0;if(!($tobool426)){__label__=195;break $if_then155$$if_else162$86;}
var $232=HEAP32[(($prev_in)>>2)];var $call428=__Z7IsAlphaj($232);var $tobool429=((($call428))|0)!=0;if($tobool429){__label__=195;break $if_then155$$if_else162$86;}
var $233=$ix;var $inc431=((($233)+1)&4294967295);$ix=$inc431;var $arrayidx432=(($sbuf+$233)&4294967295);HEAP8[($arrayidx432)]=32;var $234=$word_count;var $arrayidx433=(($words+$234*12)&4294967295);var $start434=(($arrayidx433+4)&4294967295);var $235=HEAP16[(($start434)>>1)];var $inc435=((($235)+1)&65535);HEAP16[(($start434)>>1)]=$inc435;;}}}
else if(__label__==154){var $236=$c;var $cmp441=((($236))|0)==46;if($cmp441){__label__=155;;}else{__label__=162;;}
if(__label__==155){var $237=HEAP32[(($prev_out)>>2)];var $cmp443=((($237))|0)==46;if($cmp443){__label__=156;;}else{__label__=157;;}
if(__label__==156){$c=32;$space_inserted=1;;}
else if(__label__==157){var $238=$word_count;var $cmp446=((($238))|0)>0;if(!($cmp446)){__label__=195;break $if_then155$$if_else162$86;}
var $239=$word_count;var $sub448=((($239)-1)&4294967295);var $arrayidx449=(($words+$sub448*12)&4294967295);var $flags450=(($arrayidx449)&4294967295);var $240=HEAP32[(($flags450)>>2)];var $and451=($240)&256;var $tobool452=((($and451))|0)!=0;if($tobool452){__label__=195;break $if_then155$$if_else162$86;}
var $241=HEAP32[(($prev_in)>>2)];var $call454=__Z7IsAlphaj($241);var $tobool455=((($call454))|0)!=0;if(!($tobool455)){__label__=195;break $if_then155$$if_else162$86;}
var $242=$word_count;var $sub457=((($242)-1)&4294967295);var $arrayidx458=(($words+$sub457*12)&4294967295);var $flags459=(($arrayidx458)&4294967295);var $243=HEAP32[(($flags459)>>2)];var $or460=($243)|65536;HEAP32[(($flags459)>>2)]=$or460;var $244=HEAP32[(($next_in)>>2)];var $call461=__Z7IsSpacej($244);var $tobool462=((($call461))|0)!=0;var $245=HEAP32[(($next_in)>>2)];var $cmp464=((($245))|0)==45;var $or_cond9=($tobool462)|($cmp464);if(!($or_cond9)){__label__=195;break $if_then155$$if_else162$86;}
$c=32;;}}
else if(__label__==162){var $246=$c;var $cmp470=((($246))|0)==39;if($cmp470){__label__=163;;}else{__label__=178;;}
if(__label__==163){var $247=HEAP32[(($prev_in)>>2)];var $cmp472=((($247))|0)==46;if($cmp472){__label__=165;;}else{__label__=164;;}
$land_lhs_true476$$lor_lhs_false473$226:do{if(__label__==164){var $248=HEAP32[(($prev_in)>>2)];var $call474=_iswalnum($248);var $tobool475=((($call474))|0)!=0;if($tobool475){__label__=165;break $land_lhs_true476$$lor_lhs_false473$226;}else{__label__=167;break $land_lhs_true476$$lor_lhs_false473$226;}}}while(0);$land_lhs_true476$$if_else480$228:do{if(__label__==165){var $249=HEAP32[(($next_in)>>2)];var $call477=__Z7IsAlphaj($249);var $tobool478=((($call477))|0)!=0;if(!($tobool478)){__label__=167;break $land_lhs_true476$$if_else480$228;}
$single_quoted=0;__label__=195;break $if_then155$$if_else162$86;}}while(0);var $250=$tr_addr;var $char_plus_apostrophe=(($250+700)&4294967295);var $251=HEAP32[(($char_plus_apostrophe)>>2)];var $252=HEAP32[(($prev_in)>>2)];var $call481=_wcschr($251,$252);var $cmp482=((($call481))|0)!=0;if($cmp482){__label__=168;;}else{__label__=171;;}
$land_lhs_true483$$if_else490$232:do{if(__label__==168){var $253=$prev_out2;var $cmp484=((($253))|0)==32;if(!($cmp484)){__label__=171;break $land_lhs_true483$$if_else490$232;}
$single_quoted=0;var $254=HEAP32[(($next_in)>>2)];var $cmp486=((($254))|0)==32;if(!($cmp486)){__label__=195;break $if_then155$$if_else162$86;}
var $255=HEAP32[(($source_index)>>2)];var $inc488=((($255)+1)&4294967295);HEAP32[(($source_index)>>2)]=$inc488;__label__=195;break $if_then155$$if_else162$86;}}while(0);var $256=HEAP32[(($prev_out)>>2)];var $cmp491=((($256))|0)==115;if($cmp491){__label__=172;;}else{__label__=174;;}
$land_lhs_true492$$if_else495$237:do{if(__label__==172){var $257=$single_quoted;var $cmp493=((($257))|0)==0;if(!($cmp493)){__label__=174;break $land_lhs_true492$$if_else495$237;}
$c=32;__label__=195;break $if_then155$$if_else162$86;}}while(0);var $258=HEAP32[(($prev_out)>>2)];var $call496=__Z7IsSpacej($258);var $tobool497=((($call496))|0)!=0;if($tobool497){__label__=175;;}else{__label__=176;;}
if(__label__==175){$single_quoted=1;;}
else if(__label__==176){$single_quoted=0;;}
$pre_pause_add=4;$c=32;;}
else if(__label__==178){var $259=$c;var $call505=__Z11lookupwcharPKti(((__ZL6breaks)&4294967295),$259);var $cmp506=((($call505))|0)!=0;if($cmp506){__label__=179;;}else{__label__=180;;}
if(__label__==179){$c=32;;}
else if(__label__==180){var $260=$c;var $call509=_iswdigit($260);var $tobool510=((($call509))|0)!=0;if(!($tobool510)){__label__=195;break $if_then155$$if_else162$86;}
var $261=$tr_addr;var $langopts512=(($261)&4294967295);var $tone_numbers513=(($langopts512+250)&4294967295);var $262=HEAP8[($tone_numbers513)];var $tobool514=(tempInt=(($262)),(tempInt>=128?tempInt-256:tempInt))!=0;if($tobool514){__label__=182;;}else{__label__=184;;}
$land_lhs_true515$$if_else522$250:do{if(__label__==182){var $263=HEAP32[(($prev_out)>>2)];var $call516=__Z7IsAlphaj($263);var $tobool517=((($call516))|0)!=0;if(!($tobool517)){__label__=184;break $land_lhs_true515$$if_else522$250;}
var $264=HEAP32[(($next_in)>>2)];var $call519=__Z7IsDigitj($264);var $tobool520=((($call519))|0)!=0;if(!($tobool520)){__label__=195;break $if_then155$$if_else162$86;}}}while(0);var $265=HEAP32[(($prev_out)>>2)];var $cmp523=((($265))|0)!=32;if($cmp523){__label__=185;;}else{__label__=192;;}
if(__label__==185){var $266=HEAP32[(($prev_out)>>2)];var $call525=_iswdigit($266);var $tobool526=((($call525))|0)!=0;var $_pr20=HEAP32[(($prev_out)>>2)];if($tobool526){__label__=191;;}else{__label__=186;;}
if(__label__==191){var $cmp540=((($_pr20))|0)==32;if(!($cmp540)){__label__=195;break $if_then155$$if_else162$86;}}
else if(__label__==186){var $267=$tr_addr;var $langopts528=(($267)&4294967295);var $decimal_sep=(($langopts528+208)&4294967295);var $268=HEAP32[(($decimal_sep)>>2)];var $cmp529=((($_pr20))|0)!=((($268))|0);if($cmp529){__label__=189;;}else{__label__=187;;}
$if_then536$$lor_lhs_false530$259:do{if(__label__==187){var $269=$decimal_sep_count;var $cmp531=((($269))|0)>0;if($cmp531){__label__=188;;}else{__label__=190;;}
if(__label__==188){var $270=$tr_addr;var $langopts533=(($270)&4294967295);var $decimal_sep534=(($langopts533+208)&4294967295);var $271=HEAP32[(($decimal_sep534)>>2)];var $cmp535=((($271))|0)==44;if($cmp535){__label__=189;break $if_then536$$lor_lhs_false530$259;}}
$decimal_sep_count=1;__label__=195;break $if_then155$$if_else162$86;}}while(0);$c=32;$space_inserted=1;__label__=195;break $if_then155$$if_else162$86;}}
var $272=$ix;var $sub542=((($272)-2)&4294967295);var $arrayidx543=(($sbuf+$sub542)&4294967295);var $273=HEAP8[($arrayidx543)];var $conv544=(tempInt=(($273)),(tempInt>=128?tempInt-256:tempInt));var $call545=__Z7IsAlphaj($conv544);var $tobool546=((($call545))|0)!=0;if(!($tobool546)){__label__=195;break $if_then155$$if_else162$86;}
var $274=HEAP32[(($prev_in)>>2)];var $call548=__Z7IsAlphaj($274);var $tobool549=((($call548))|0)!=0;if($tobool549){__label__=195;break $if_then155$$if_else162$86;}
var $275=$ix;var $inc551=((($275)+1)&4294967295);$ix=$inc551;var $arrayidx552=(($sbuf+$275)&4294967295);HEAP8[($arrayidx552)]=32;var $276=$word_count;var $arrayidx553=(($words+$276*12)&4294967295);var $start554=(($arrayidx553+4)&4294967295);var $277=HEAP16[(($start554)>>1)];var $inc555=((($277)+1)&65535);HEAP16[(($start554)>>1)]=$inc555;;}}}}}}}}while(0);var $278=$c;var $call568=__Z7IsSpacej($278);var $tobool569=((($call568))|0)!=0;if($tobool569){__label__=196;;}else{__label__=225;;}
$if_then570$$if_else688$269:do{if(__label__==196){var $279=HEAP32[(($prev_out)>>2)];var $cmp571=((($279))|0)==32;if($cmp571){__label__=197;;}else{__label__=198;;}
if(__label__==197){var $280=$word_flags;var $or573=($280)|262144;$word_flags=$or573;__label__=33;continue $while_cond88$50;}
else if(__label__==198){var $281=HEAP32[(($cc)>>2)];var $cmp575=((($281))|0)==9;var $282=HEAP32[(($cc)>>2)];var $cmp577=((($282))|0)==10;var $or_cond10=($cmp575)|($cmp577);if($or_cond10){__label__=199;;}else{__label__=200;;}
if(__label__==199){var $283=$next_word_flags;var $or579=($283)|262144;$next_word_flags=$or579;;}
var $284=$space_inserted;var $tobool581=((($284))|0)!=0;if($tobool581){__label__=201;;}else{__label__=208;;}
if(__label__==201){$j=0;var $285=HEAP32[(($source_index)>>2)];var $sub583=((($285)-1)&4294967295);$k=$sub583;;while(1){var $286=$k;var $287=$source_index_word;var $cmp585=((($286))|0)>=((($287))|0);if(!($cmp585)){__label__=207;break;}
var $288=$k;var $arrayidx587=(($charix+$288*2)&4294967295);var $289=HEAP16[(($arrayidx587)>>1)];var $conv588=(tempInt=(($289)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp589=((($conv588))|0)!=0;if(!($cmp589)){__label__=207;break;}
var $290=$k;var $arrayidx592=(($charix+$290*2)&4294967295);var $291=HEAP16[(($arrayidx592)>>1)];var $conv593=(tempInt=(($291)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp594=((($conv593))|0)>0;if($cmp594){__label__=205;;}else{__label__=206;;}
if(__label__==205){var $292=$j;var $inc596=((($292)+1)&4294967295);$j=$inc596;;}
var $293=$k;var $dec598=((($293)-1)&4294967295);$k=$dec598;__label__=202;continue;}
var $294=$j;var $conv600=((($294))&255);var $295=$word_count;var $arrayidx601=(($words+$295*12)&4294967295);var $length602=(($arrayidx601+10)&4294967295);HEAP8[($length602)]=$conv600;;}
var $296=HEAP32[(($source_index)>>2)];$source_index_word=$296;var $297=$ix;var $inc604=((($297)+1)&4294967295);$ix=$inc604;var $arrayidx605=(($sbuf+$297)&4294967295);HEAP8[($arrayidx605)]=32;var $298=$word_count;var $cmp606=((($298))|0)<299;if($cmp606){__label__=209;;}else{__label__=223;;}
$land_lhs_true607$$if_end684$288:do{if(__label__==209){var $299=$ix;var $300=$word_count;var $arrayidx608=(($words+$300*12)&4294967295);var $start609=(($arrayidx608+4)&4294967295);var $301=HEAPU16[(($start609)>>1)];var $conv610=((($301))&65535);var $cmp611=((($299))|0)>((($conv610))|0);if(!($cmp611)){__label__=223;break $land_lhs_true607$$if_end684$288;}
var $302=$embedded_count;var $cmp613=((($302))|0)>0;if($cmp613){__label__=211;;}else{__label__=212;;}
if(__label__==211){var $303=HEAP32[((__ZL11embedded_ix)>>2)];var $sub615=((($303)-1)&4294967295);var $arrayidx616=((_embedded_list+$sub615*4)&4294967295);var $304=HEAP32[(($arrayidx616)>>2)];var $or617=($304)|128;HEAP32[(($arrayidx616)>>2)]=$or617;var $305=$word_count;var $arrayidx618=(($words+$305*12)&4294967295);var $flags619=(($arrayidx618)&4294967295);var $306=HEAP32[(($flags619)>>2)];var $or620=($306)|64;HEAP32[(($flags619)>>2)]=$or620;$embedded_count=0;;}
var $307=HEAP32[((_pre_pause)>>2)];var $conv622=((($307))&255);var $308=$word_count;var $arrayidx623=(($words+$308*12)&4294967295);var $pre_pause=(($arrayidx623+8)&4294967295);HEAP8[($pre_pause)]=$conv622;var $309=$all_upper_case;var $310=$word_flags;var $_b=HEAPU8[(__ZL13word_emphasis_b)];var $311=($_b)?2048:0;var $312=$word_count;var $arrayidx626=(($words+$312*12)&4294967295);var $flags627=(($arrayidx626)&4294967295);var $313=HEAP32[(($flags627)>>2)];var $or624=($310)|($309);var $or625=($or624)|($311);var $or628=($or625)|($313);HEAP32[(($flags627)>>2)]=$or628;var $314=$word_mark;var $conv629=((($314))&255);var $315=$word_count;var $arrayidx630=(($words+$315*12)&4294967295);var $wmark=(($arrayidx630+9)&4294967295);HEAP8[($wmark)]=$conv629;var $316=HEAP32[((_pre_pause)>>2)];var $cmp631=((($316))|0)>0;if($cmp631){__label__=213;;}else{__label__=216;;}
if(__label__==213){var $317=$ix;$j=$317;var $318=$j;var $319=$word_count;var $arrayidx63438=(($words+$319*12)&4294967295);var $start63539=(($arrayidx63438+4)&4294967295);var $320=HEAPU16[(($start63539)>>1)];var $conv63640=((($320))&65535);var $cmp63741=((($318))|0)>((($conv63640))|0);var $321=$j;if($cmp63741){__lastLabel__=213;__label__=214;;}else{__lastLabel__=213;__label__=215;;}
$for_body638$$for_end644$296:do{if(__label__==214){while(1){var $322=__lastLabel__==214?$329:($321);var $sub639=((($322)-1)&4294967295);var $arrayidx640=(($sbuf+$sub639)&4294967295);var $323=HEAP8[($arrayidx640)];var $324=$j;var $arrayidx641=(($sbuf+$324)&4294967295);HEAP8[($arrayidx641)]=$323;var $325=$j;var $dec643=((($325)-1)&4294967295);$j=$dec643;var $326=$j;var $327=$word_count;var $arrayidx634=(($words+$327*12)&4294967295);var $start635=(($arrayidx634+4)&4294967295);var $328=HEAPU16[(($start635)>>1)];var $conv636=((($328))&65535);var $cmp637=((($326))|0)>((($conv636))|0);var $329=$j;if($cmp637){__lastLabel__=214;__label__=214;continue;}else{__lastLabel__=214;__label__=215;break $for_body638$$for_end644$296;}}}}while(0);var $_lcssa37=__lastLabel__==213?$321:($329);var $arrayidx645=(($sbuf+$_lcssa37)&4294967295);HEAP8[($arrayidx645)]=32;var $330=$word_count;var $arrayidx646=(($words+$330*12)&4294967295);var $start647=(($arrayidx646+4)&4294967295);var $331=HEAP16[(($start647)>>1)];var $inc648=((($331)+1)&65535);HEAP16[(($start647)>>1)]=$inc648;var $332=$ix;var $inc649=((($332)+1)&4294967295);$ix=$inc649;;}
var $333=$word_count;var $inc651=((($333)+1)&4294967295);$word_count=$inc651;var $334=$ix;var $conv652=((($334))&65535);var $335=$word_count;var $arrayidx653=(($words+$335*12)&4294967295);var $start654=(($arrayidx653+4)&4294967295);HEAP16[(($start654)>>1)]=$conv652;var $336=$word_count;var $arrayidx655=(($words+$336*12)&4294967295);var $flags656=(($arrayidx655)&4294967295);HEAP32[(($flags656)>>2)]=0;var $337=HEAP32[(($source_index)>>2)];$j=$337;var $338=$j;var $arrayidx65844=(($charix+$338*2)&4294967295);var $339=HEAP16[(($arrayidx65844)>>1)];var $conv65945=(tempInt=(($339)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp66046=((($conv65945))|0)<=0;var $340=$j;if($cmp66046){__lastLabel__=216;__label__=217;;}else{__lastLabel__=216;__label__=218;;}
$for_inc662$$for_end664$301:do{if(__label__==217){while(1){var $341=__lastLabel__==217?$344:($340);var $inc663=((($341)+1)&4294967295);$j=$inc663;var $342=$j;var $arrayidx658=(($charix+$342*2)&4294967295);var $343=HEAP16[(($arrayidx658)>>1)];var $conv659=(tempInt=(($343)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp660=((($conv659))|0)<=0;var $344=$j;if($cmp660){__lastLabel__=217;__label__=217;continue;}else{__lastLabel__=217;__label__=218;break $for_inc662$$for_end664$301;}}}}while(0);var $_lcssa43=__lastLabel__==216?$340:($344);var $arrayidx665=(($charix+$_lcssa43*2)&4294967295);var $345=HEAP16[(($arrayidx665)>>1)];var $346=$word_count;var $arrayidx666=(($words+$346*12)&4294967295);var $sourceix667=(($arrayidx666+6)&4294967295);HEAP16[(($sourceix667)>>1)]=$345;$k=0;var $347=$j;var $arrayidx66948=(($charix+$347*2)&4294967295);var $348=HEAP16[(($arrayidx66948)>>1)];var $conv67049=(tempInt=(($348)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp67150=((($conv67049))|0)!=0;if($cmp67150){__label__=219;;}else{__label__=222;;}
$while_body672$$while_end680$305:do{if(__label__==219){while(1){var $349=$j;var $inc673=((($349)+1)&4294967295);$j=$inc673;var $arrayidx674=(($charix+$349*2)&4294967295);var $350=HEAP16[(($arrayidx674)>>1)];var $conv675=(tempInt=(($350)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp676=((($conv675))|0)!=-1;if($cmp676){__label__=220;;}else{__label__=221;;}
if(__label__==220){var $351=$k;var $inc678=((($351)+1)&4294967295);$k=$inc678;;}
var $352=$j;var $arrayidx669=(($charix+$352*2)&4294967295);var $353=HEAP16[(($arrayidx669)>>1)];var $conv670=(tempInt=(($353)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp671=((($conv670))|0)!=0;if($cmp671){__label__=219;continue;}else{__label__=222;break $while_body672$$while_end680$305;}}}}while(0);var $354=$k;var $conv681=((($354))&255);var $355=$word_count;var $arrayidx682=(($words+$355*12)&4294967295);var $length683=(($arrayidx682+10)&4294967295);HEAP8[($length683)]=$conv681;var $356=$next_word_flags;$word_flags=$356;$next_word_flags=0;HEAP32[((_pre_pause)>>2)]=0;$word_mark=0;$all_upper_case=1;$syllable_marked=0;;}}while(0);var $357=$space_inserted;var $tobool685=((($357))|0)!=0;if(!($tobool685)){__label__=227;break $if_then570$$if_else688$269;}
var $358=$prev_source_index;HEAP32[(($source_index)>>2)]=$358;HEAP32[(($char_inserted)>>2)]=0;$space_inserted=0;;}}
else if(__label__==225){var $359=$ix;var $cmp689=((($359))|0)<696;if(!($cmp689)){__label__=227;break $if_then570$$if_else688$269;}
var $360=$c;var $361=$ix;var $arrayidx691=(($sbuf+$361)&4294967295);var $call692=__Z8utf8_outjPc($360,$arrayidx691);var $362=$ix;var $add693=((($362)+($call692))&4294967295);$ix=$add693;;}}while(0);var $363=$pre_pause_add;var $364=HEAP32[((_pre_pause)>>2)];var $cmp696=((($363))|0)>((($364))|0);if($cmp696){__label__=228;;}else{__label__=229;;}
if(__label__==228){var $365=$pre_pause_add;HEAP32[((_pre_pause)>>2)]=$365;;}
$pre_pause_add=0;__label__=33;continue $while_cond88$50;}
var $366=$word_count;var $cmp700=((($366))|0)==0;if($cmp700){__label__=231;;}else{__label__=233;;}
$land_lhs_true701$$if_end710$321:do{if(__label__==231){var $367=$embedded_count;var $cmp702=((($367))|0)>0;if(!($cmp702)){__label__=233;break $land_lhs_true701$$if_end710$321;}
var $368=HEAP32[((__ZL11embedded_ix)>>2)];var $sub704=((($368)-1)&4294967295);var $arrayidx705=((_embedded_list+$sub704*4)&4294967295);var $369=HEAP32[(($arrayidx705)>>2)];var $or706=($369)|128;HEAP32[(($arrayidx705)>>2)]=$or706;var $370=$word_count;var $arrayidx707=(($words+$370*12)&4294967295);var $flags708=(($arrayidx707)&4294967295);var $371=HEAP32[(($flags708)>>2)];var $or709=($371)|64;HEAP32[(($flags708)>>2)]=$or709;$word_count=1;;}}while(0);var $372=$ix;var $sub711=((($372)-1)&4294967295);var $arrayidx712=(($sbuf+$sub711)&4294967295);var $373=$tr_addr;var $clause_end=(($373+8292)&4294967295);HEAP32[(($clause_end)>>2)]=$arrayidx712;var $374=$ix;var $arrayidx713=(($sbuf+$374)&4294967295);HEAP8[($arrayidx713)]=0;var $arrayidx714=(($words)&4294967295);var $pre_pause715=(($arrayidx714+8)&4294967295);HEAP8[($pre_pause715)]=0;var $375=$word_count;var $arrayidx716=(($words+$375*12)&4294967295);var $pre_pause717=(($arrayidx716+8)&4294967295);HEAP8[($pre_pause717)]=8;var $376=$word_count;var $cmp718=((($376))|0)>0;if($cmp718){__label__=234;;}else{__label__=241;;}
$if_then719$$if_end751$325:do{if(__label__==234){var $377=$word_count;var $sub720=((($377)-1)&4294967295);$ix=$sub720;__lastLabel__=234;;while(1){var $378=__lastLabel__==237?$dec732:($sub720);var $cmp722=((($378))|0)>0;var $379=$ix;if($cmp722){__lastLabel__=235;;}else{__lastLabel__=235;__label__=238;break;}
var $arrayidx724=(($words+$379*12)&4294967295);var $start725=(($arrayidx724+4)&4294967295);var $380=HEAPU16[(($start725)>>1)];var $idxprom=((($380))&65535);var $arrayidx726=(($sbuf+$idxprom)&4294967295);var $381=HEAP8[($arrayidx726)];var $conv727=(tempInt=(($381)),(tempInt>=128?tempInt-256:tempInt));var $call728=__Z9IsBracketi($conv727);var $tobool729=((($call728))|0)!=0;var $382=$ix;if($tobool729){__lastLabel__=236;;}else{__lastLabel__=236;__label__=238;break;}
var $dec732=((($382)-1)&4294967295);$ix=$dec732;__lastLabel__=237;__label__=235;continue;}
var $383=__lastLabel__==236?$382:($379);var $arrayidx734=(($words+$383*12)&4294967295);var $flags735=(($arrayidx734)&4294967295);var $384=HEAP32[(($flags735)>>2)];var $or736=($384)|16;HEAP32[(($flags735)>>2)]=$or736;var $385=$terminator;var $and737=($385)&4194304;var $tobool738=((($and737))|0)!=0;if(!($tobool738)){__label__=241;break $if_then719$$if_end751$325;}
var $386=$word_count;var $sub740=((($386)-1)&4294967295);var $arrayidx741=(($words+$sub740*12)&4294967295);var $flags742=(($arrayidx741)&4294967295);var $387=HEAP32[(($flags742)>>2)];var $and743=($387)&256;var $tobool744=((($and743))|0)!=0;if($tobool744){__label__=241;break $if_then719$$if_end751$325;}
var $388=$word_count;var $sub746=((($388)-1)&4294967295);var $arrayidx747=(($words+$sub746*12)&4294967295);var $flags748=(($arrayidx747)&4294967295);var $389=HEAP32[(($flags748)>>2)];var $or749=($389)|65536;HEAP32[(($flags748)>>2)]=$or749;;}}while(0);var $arrayidx752=(($words)&4294967295);var $flags753=(($arrayidx752)&4294967295);var $390=HEAP32[(($flags753)>>2)];var $or754=($390)|512;HEAP32[(($flags753)>>2)]=$or754;$ix=0;var $391=$ix;var $392=$word_count;var $cmp75636=((($391))|0)<((($392))|0);if($cmp75636){__label__=242;;}else{__label__=296;;}
$for_body757_lr_ph$$for_end994$335:do{if(__label__==242){var $arraydecay781=(($number_buf)&4294967295);var $arrayidx783=(($number_buf+130)&4294967295);var $arraydecay816=(($number_buf)&4294967295);var $sub_ptr_rhs_cast818=($arraydecay816);var $arraydecay820=(($number_buf)&4294967295);var $arrayidx836=(($number_buf)&4294967295);var $arrayidx837=(($number_buf+1)&4294967295);var $arrayidx850=(($number_buf+130)&4294967295);var $arrayidx920=(($number_buf+1)&4294967295);var $arraydecay967=(($number_buf)&4294967295);var $arrayidx969=(($number_buf+2)&4294967295);var $arrayidx970=(($number_buf+2)&4294967295);;$for_body757$337:while(1){var $393=HEAP32[((_count_words)>>2)];var $inc758=((($393)+1)&4294967295);HEAP32[((_count_words)>>2)]=$inc758;var $394=HEAP32[((_skip_words)>>2)];var $cmp759=((($394))|0)>0;if($cmp759){__label__=244;;}else{__label__=246;;}
$if_then760$$if_end765$339:do{if(__label__==244){var $395=HEAP32[((_skip_words)>>2)];var $dec761=((($395)-1)&4294967295);HEAP32[((_skip_words)>>2)]=$dec761;var $396=HEAP32[((_skip_words)>>2)];var $cmp762=((($396))|0)==0;if(!($cmp762)){__label__=246;break $if_then760$$if_end765$339;}
HEAP32[((_skipping_text)>>2)]=0;__label__=247;break $if_then760$$if_end765$339;}}while(0);$if_end768$$if_end765$342:do{if(__label__==246){var $_pr22=HEAP32[((_skipping_text)>>2)];var $tobool766=((($_pr22))|0)!=0;if($tobool766){__label__=295;break $if_end768$$if_end765$342;}else{__label__=247;break $if_end768$$if_end765$342;}}}while(0);$if_end768$$for_inc992$344:do{if(__label__==247){var $397=$ix;var $arrayidx769=(($words+$397*12)&4294967295);var $start770=(($arrayidx769+4)&4294967295);var $398=HEAPU16[(($start770)>>1)];var $idxprom771=((($398))&65535);var $arrayidx772=(($sbuf+$idxprom771)&4294967295);$pw=$arrayidx772;$word=$arrayidx772;var $399=$word;var $arrayidx773=(($399)&4294967295);var $400=HEAP8[($arrayidx773)];var $conv774=(tempInt=(($400)),(tempInt>=128?tempInt-256:tempInt));var $call775=_iswdigit($conv774);var $tobool776=((($call775))|0)!=0;if($tobool776){__label__=248;;}else{__label__=261;;}
$land_lhs_true777$$if_end824$346:do{if(__label__==248){var $401=$tr_addr;var $langopts778=(($401)&4294967295);var $break_numbers=(($langopts778+192)&4294967295);var $402=HEAP32[(($break_numbers)>>2)];var $cmp779=((($402))|0)!=1227133512;if(!($cmp779)){__label__=261;break $land_lhs_true777$$if_end824$346;}
$pn=$arraydecay781;;while(1){var $403=$pn;var $cmp784=((($403))>>>0)<((($arrayidx783))>>>0);if(!($cmp784)){__label__=260;break;}
var $404=$pw;var $405=HEAP8[($404)];var $conv786=(tempInt=(($405)),(tempInt>=128?tempInt-256:tempInt));var $call787=_iswdigit($conv786);var $tobool788=((($call787))|0)!=0;var $406=$pw;if($tobool788){__label__=252;;}else{__label__=253;;}
if(__label__==252){var $incdec_ptr790=(($406+1)&4294967295);$pw=$incdec_ptr790;var $407=HEAP8[($406)];var $408=$pn;var $incdec_ptr791=(($408+1)&4294967295);$pn=$incdec_ptr791;HEAP8[($408)]=$407;__label__=250;continue;}
else if(__label__==253){var $409=HEAP8[($406)];var $conv793=(tempInt=(($409)),(tempInt>=128?tempInt-256:tempInt));var $410=$tr_addr;var $langopts794=(($410)&4294967295);var $thousands_sep=(($langopts794+204)&4294967295);var $411=HEAP32[(($thousands_sep)>>2)];var $cmp795=((($conv793))|0)==((($411))|0);if(!($cmp795)){__label__=259;break;}
var $412=$pw;var $arrayidx797=(($412+1)&4294967295);var $413=HEAP8[($arrayidx797)];var $conv798=(tempInt=(($413)),(tempInt>=128?tempInt-256:tempInt));var $cmp799=((($conv798))|0)==32;if(!($cmp799)){__label__=259;break;}
var $414=$pw;var $arrayidx801=(($414+2)&4294967295);var $415=HEAP8[($arrayidx801)];var $conv802=(tempInt=(($415)),(tempInt>=128?tempInt-256:tempInt));var $call803=_iswdigit($conv802);var $tobool804=((($call803))|0)!=0;if(!($tobool804)){__label__=259;break;}
var $416=$pw;var $arrayidx806=(($416+3)&4294967295);var $417=HEAP8[($arrayidx806)];var $conv807=(tempInt=(($417)),(tempInt>=128?tempInt-256:tempInt));var $cmp808=((($conv807))|0)!=32;if(!($cmp808)){__label__=259;break;}
var $418=$pw;var $arrayidx810=(($418+4)&4294967295);var $419=HEAP8[($arrayidx810)];var $conv811=(tempInt=(($419)),(tempInt>=128?tempInt-256:tempInt));var $cmp812=((($conv811))|0)!=32;if(!($cmp812)){__label__=259;break;}
var $420=$pw;var $add_ptr=(($420+2)&4294967295);$pw=$add_ptr;var $421=$ix;var $inc814=((($421)+1)&4294967295);$ix=$inc814;__label__=250;continue;}}
if(__label__==259){var $422=$pw;var $423=$word;var $sub_ptr_lhs_cast=($422);var $sub_ptr_rhs_cast=($423);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$nx=$sub_ptr_sub;var $424=$word;var $425=$nx;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$424;$stop$=$dest$+$425;$value4$=32;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=32;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=32;};var $426=$pn;var $sub_ptr_lhs_cast817=($426);var $sub_ptr_sub819=((($sub_ptr_lhs_cast817)-($sub_ptr_rhs_cast818))&4294967295);$nx=$sub_ptr_sub819;var $427=$word;var $428=$nx;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay820;$dest$=$427;$stop$=$src$+$428;if(($dest$%4)==($src$%4)&&$428>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}
var $429=$word;$pw=$429;;}}while(0);$n_digits=0;var $430=$n_digits;var $431=$word;var $arrayidx82630=(($431+$430)&4294967295);var $432=HEAP8[($arrayidx82630)];var $conv82731=(tempInt=(($432)),(tempInt>=128?tempInt-256:tempInt));var $call82832=_iswdigit($conv82731);var $tobool82933=((($call82832))|0)!=0;var $433=$n_digits;if($tobool82933){__lastLabel__=261;__label__=262;;}else{__lastLabel__=261;__label__=263;;}
$for_inc831$$for_end833$364:do{if(__label__==262){while(1){var $434=__lastLabel__==262?$438:($433);var $inc832=((($434)+1)&4294967295);$n_digits=$inc832;var $435=$n_digits;var $436=$word;var $arrayidx826=(($436+$435)&4294967295);var $437=HEAP8[($arrayidx826)];var $conv827=(tempInt=(($437)),(tempInt>=128?tempInt-256:tempInt));var $call828=_iswdigit($conv827);var $tobool829=((($call828))|0)!=0;var $438=$n_digits;if($tobool829){__lastLabel__=262;__label__=262;continue;}else{__lastLabel__=262;__label__=263;break $for_inc831$$for_end833$364;}}}}while(0);var $_lcssa29=__lastLabel__==261?$433:($438);var $cmp834=((($_lcssa29))|0)>4;if($cmp834){__label__=264;;}else{__label__=284;;}
$if_then835$$if_else939$368:do{if(__label__==264){HEAP8[($arrayidx836)]=32;$pn=$arrayidx837;var $439=$n_digits;$nx=$439;$nw=0;$individual_digits=0;var $440=$n_digits;var $441=$tr_addr;var $langopts838=(($441)&4294967295);var $max_digits=(($langopts838+212)&4294967295);var $442=HEAP32[(($max_digits)>>2)];var $cmp839=((($440))|0)>((($442))|0);if($cmp839){__label__=266;;}else{__label__=265;;}
$if_then844$$lor_lhs_false840$370:do{if(__label__==265){var $443=$word;var $arrayidx841=(($443)&4294967295);var $444=HEAP8[($arrayidx841)];var $conv842=(tempInt=(($444)),(tempInt>=128?tempInt-256:tempInt));var $cmp843=((($conv842))|0)==48;if($cmp843){__label__=266;break $if_then844$$lor_lhs_false840$370;}else{__label__=267;break $if_then844$$lor_lhs_false840$370;}}}while(0);if(__label__==266){var $445=$ix;var $arrayidx845=(($words+$445*12)&4294967295);var $flags846=(($arrayidx845)&4294967295);var $446=HEAP32[(($flags846)>>2)];var $or847=($446)|524288;HEAP32[(($flags846)>>2)]=$or847;;}
$while_cond849$374:while(1){var $447=$pn;var $cmp851=((($447))>>>0)<((($arrayidx850))>>>0);if(!($cmp851)){__label__=278;break $while_cond849$374;}
var $448=$pw;var $incdec_ptr853=(($448+1)&4294967295);$pw=$incdec_ptr853;var $449=HEAP8[($448)];var $conv854=(tempInt=(($449)),(tempInt>=128?tempInt-256:tempInt));$c=$conv854;var $isdigittmp=((($conv854)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call855=((($isdigit))&1);var $tobool856=((($call855))|0)!=0;if($tobool856){__label__=270;;}else{__label__=269;;}
if(__label__==269){var $450=$c;var $451=$tr_addr;var $langopts858=(($451)&4294967295);var $decimal_sep859=(($langopts858+208)&4294967295);var $452=HEAP32[(($decimal_sep859)>>2)];var $cmp860=((($450))|0)!=((($452))|0);if($cmp860){__label__=278;break $while_cond849$374;}}
var $453=$c;var $conv863=((($453))&255);var $454=$pn;var $incdec_ptr864=(($454+1)&4294967295);$pn=$incdec_ptr864;HEAP8[($454)]=$conv863;var $455=$nx;var $dec865=((($455)-1)&4294967295);$nx=$dec865;var $cmp866=((($dec865))|0)>0;if(!($cmp866)){__label__=267;continue $while_cond849$374;}
var $456=$tr_addr;var $langopts868=(($456)&4294967295);var $break_numbers869=(($langopts868+192)&4294967295);var $457=HEAP32[(($break_numbers869)>>2)];var $458=$nx;var $shl=1<<($458);var $and870=($shl)&($457);var $tobool871=((($and870))|0)!=0;if(!($tobool871)){__label__=267;continue $while_cond849$374;}
var $459=$nw;var $inc873=((($459)+1)&4294967295);$nw=$inc873;var $arrayidx874=(($num_wtab+$459*12)&4294967295);var $460=$arrayidx874;var $461=$ix;var $arrayidx875=(($words+$461*12)&4294967295);var $462=$arrayidx875;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$462;$dest$=$460;$stop$=$src$+12;if(($dest$%4)==($src$%4)&&12>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $463=$tr_addr;var $langopts876=(($463)&4294967295);var $thousands_sep877=(($langopts876+204)&4294967295);var $464=HEAP32[(($thousands_sep877)>>2)];var $cmp878=((($464))|0)!=32;if($cmp878){__label__=273;;}else{__label__=274;;}
if(__label__==273){var $465=$tr_addr;var $langopts880=(($465)&4294967295);var $thousands_sep881=(($langopts880+204)&4294967295);var $466=HEAP32[(($thousands_sep881)>>2)];var $conv882=((($466))&255);var $467=$pn;var $incdec_ptr883=(($467+1)&4294967295);$pn=$incdec_ptr883;HEAP8[($467)]=$conv882;;}
var $468=$pn;var $incdec_ptr885=(($468+1)&4294967295);$pn=$incdec_ptr885;HEAP8[($468)]=32;var $469=$tr_addr;var $langopts886=(($469)&4294967295);var $break_numbers887=(($langopts886+192)&4294967295);var $470=HEAP32[(($break_numbers887)>>2)];var $471=$nx;var $sub888=((($471)-1)&4294967295);var $shl889=1<<($sub888);var $and890=($shl889)&($470);var $tobool891=((($and890))|0)!=0;if($tobool891){__label__=275;;}else{__label__=276;;}
if(__label__==275){var $472=$pn;var $incdec_ptr893=(($472+1)&4294967295);$pn=$incdec_ptr893;HEAP8[($472)]=48;var $473=$pn;var $incdec_ptr894=(($473+1)&4294967295);$pn=$incdec_ptr894;HEAP8[($473)]=48;;}
var $474=$tr_addr;var $langopts896=(($474)&4294967295);var $break_numbers897=(($langopts896+192)&4294967295);var $475=HEAP32[(($break_numbers897)>>2)];var $476=$nx;var $sub898=((($476)-2)&4294967295);var $shl899=1<<($sub898);var $and900=($shl899)&($475);var $tobool901=((($and900))|0)!=0;if(!($tobool901)){__label__=267;continue $while_cond849$374;}
var $477=$pn;var $incdec_ptr903=(($477+1)&4294967295);$pn=$incdec_ptr903;HEAP8[($477)]=48;__label__=267;continue $while_cond849$374;}
var $478=$pw;var $incdec_ptr907=(($478+-1)&4294967295);$pw=$incdec_ptr907;var $479=$nw;var $arrayidx908=(($num_wtab+$479*12)&4294967295);var $480=$arrayidx908;var $481=$ix;var $arrayidx909=(($words+$481*12)&4294967295);var $482=$arrayidx909;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$482;$dest$=$480;$stop$=$src$+24;if(($dest$%4)==($src$%4)&&24>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};$j=1;var $483=$j;var $484=$nw;var $cmp91134=((($483))|0)<=((($484))|0);if($cmp91134){__label__=279;;}else{__label__=280;;}
$for_body912$$for_end918$390:do{if(__label__==279){while(1){var $485=$j;var $arrayidx913=(($num_wtab+$485*12)&4294967295);var $flags914=(($arrayidx913)&4294967295);var $486=HEAP32[(($flags914)>>2)];var $and915=($486)&-262209;HEAP32[(($flags914)>>2)]=$and915;var $487=$j;var $inc917=((($487)+1)&4294967295);$j=$inc917;var $488=$j;var $489=$nw;var $cmp911=((($488))|0)<=((($489))|0);if($cmp911){__label__=279;continue;}else{__label__=280;break $for_body912$$for_end918$390;}}}}while(0);var $490=$pn;var $491=$pw;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$491;$dest$=$490;$stop$=$src$+16;if(($dest$%4)==($src$%4)&&16>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $492=$pn;var $arrayidx919=(($492+16)&4294967295);HEAP8[($arrayidx919)]=0;$nw=0;$pw=$arrayidx920;var $493=$pw;var $494=$pn;var $cmp92235=((($493))>>>0)<((($494))>>>0);if(!($cmp92235)){__label__=293;break $if_then835$$if_else939$368;}
$for_body923$394:while(1){var $495=$tr_addr;var $496=$pw;var $497=$nw;var $inc924=((($497)+1)&4294967295);$nw=$inc924;var $arrayidx925=(($num_wtab+$497*12)&4294967295);var $498=$ix;var $arrayidx926=(($words+$498*12)&4294967295);var $pre_pause927=(($arrayidx926+8)&4294967295);var $499=HEAPU8[($pre_pause927)];var $conv928=((($499))&255);var $call929=__ZL14TranslateWord2P10TranslatorPcP8WORD_TABii($495,$496,$arrayidx925,$conv928,0);$dict_flags=$call929;;while(1){var $500=$pw;var $incdec_ptr931=(($500+1)&4294967295);$pw=$incdec_ptr931;var $501=HEAP8[($500)];var $conv932=(tempInt=(($501)),(tempInt>=128?tempInt-256:tempInt));var $cmp933=((($conv932))|0)!=32;if($cmp933){__label__=282;continue;}else{__label__=283;break;}}
var $502=$ix;var $arrayidx936=(($words+$502*12)&4294967295);var $pre_pause937=(($arrayidx936+8)&4294967295);HEAP8[($pre_pause937)]=0;var $503=$pw;var $504=$pn;var $cmp922=((($503))>>>0)<((($504))>>>0);if($cmp922){__label__=281;continue $for_body923$394;}else{__label__=293;break $if_then835$$if_else939$368;}}}
else if(__label__==284){HEAP32[((_pre_pause)>>2)]=0;var $505=$tr_addr;var $506=$word;var $507=$ix;var $arrayidx940=(($words+$507*12)&4294967295);var $508=$ix;var $arrayidx941=(($words+$508*12)&4294967295);var $pre_pause942=(($arrayidx941+8)&4294967295);var $509=HEAPU8[($pre_pause942)];var $conv943=((($509))&255);var $510=$ix;var $add944=((($510)+1)&4294967295);var $arrayidx945=(($words+$add944*12)&4294967295);var $pre_pause946=(($arrayidx945+8)&4294967295);var $511=HEAPU8[($pre_pause946)];var $conv947=((($511))&255);var $call948=__ZL14TranslateWord2P10TranslatorPcP8WORD_TABii($505,$506,$arrayidx940,$conv943,$conv947);$dict_flags=$call948;var $512=HEAP32[((_pre_pause)>>2)];var $513=$ix;var $add949=((($513)+1)&4294967295);var $arrayidx950=(($words+$add949*12)&4294967295);var $pre_pause951=(($arrayidx950+8)&4294967295);var $514=HEAPU8[($pre_pause951)];var $conv952=((($514))&255);var $cmp953=((($512))|0)>((($conv952))|0);if($cmp953){__label__=285;;}else{__label__=286;;}
if(__label__==285){var $515=HEAP32[((_pre_pause)>>2)];var $conv955=((($515))&255);var $516=$ix;var $add956=((($516)+1)&4294967295);var $arrayidx957=(($words+$add956*12)&4294967295);var $pre_pause958=(($arrayidx957+8)&4294967295);HEAP8[($pre_pause958)]=$conv955;HEAP32[((_pre_pause)>>2)]=0;;}
var $517=$dict_flags;var $and960=($517)&65536;var $tobool961=((($and960))|0)!=0;if($tobool961){__label__=287;;}else{__label__=289;;}
$if_then962$$if_end975$403:do{if(__label__==287){var $518=$word;$pw=$518;var $519=$pw;var $520=HEAP8[($519)];var $conv96427=(tempInt=(($520)),(tempInt>=128?tempInt-256:tempInt));var $cmp96528=((($conv96427))|0)!=32;if(!($cmp96528)){__label__=289;break $if_then962$$if_end975$403;}
while(1){var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arraydecay967;$stop$=$dest$+9;$value4$=32;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=32;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=32;};var $521=$pw;var $call968=__Z7utf8_inPiPKc($c_temp,$521);$nx=$call968;var $522=$pw;var $523=$nx;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$522;$dest$=$arrayidx969;$stop$=$src$+$523;if(($dest$%4)==($src$%4)&&$523>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $524=$tr_addr;var $525=$ix;var $arrayidx971=(($words+$525*12)&4294967295);var $call972=__ZL14TranslateWord2P10TranslatorPcP8WORD_TABii($524,$arrayidx970,$arrayidx971,0,0);var $526=$nx;var $527=$pw;var $add_ptr973=(($527+$526)&4294967295);$pw=$add_ptr973;var $528=$pw;var $529=HEAP8[($528)];var $conv964=(tempInt=(($529)),(tempInt>=128?tempInt-256:tempInt));var $cmp965=((($conv964))|0)!=32;if($cmp965){__label__=288;continue;}else{__label__=289;break $if_then962$$if_end975$403;}}}}while(0);var $530=$dict_flags;var $and976=($530)&50331648;var $tobool977=((($and976))|0)!=0;if(!($tobool977)){__label__=293;break $if_then835$$if_else939$368;}
var $531=$ix;var $532=$word_count;var $sub979=((($532)-1)&4294967295);var $cmp980=((($531))|0)==((($sub979))|0);if(!($cmp980)){__label__=293;break $if_then835$$if_else939$368;}
var $533=$terminator;var $and982=($533)&4194304;var $tobool983=((($and982))|0)!=0;if(!($tobool983)){__label__=293;break $if_then835$$if_else939$368;}
$clause_pause=10;$tone=4;;}}while(0);var $534=$dict_flags;var $and987=($534)&128;var $tobool988=((($and987))|0)!=0;if(!($tobool988)){__label__=295;break $if_end768$$for_inc992$344;}
var $535=HEAP32[((_dictionary_skipwords)>>2)];var $536=$ix;var $add990=((($536)+($535))&4294967295);$ix=$add990;;}}while(0);var $537=$ix;var $inc993=((($537)+1)&4294967295);$ix=$inc993;var $538=$ix;var $539=$word_count;var $cmp756=((($538))|0)<((($539))|0);if($cmp756){__label__=243;continue $for_body757$337;}else{__label__=296;break $for_body757_lr_ph$$for_end994$335;}}}}while(0);$ix=0;var $540=HEAP32[((_n_ph_list2)>>2)];__lastLabel__=296;;$for_body997$415:while(1){var $541=__lastLabel__==296?$540:($549);var $542=$ix;var $add998=((($542)+($541))&4294967295);var $arrayidx999=((_ph_list2+$add998*8)&4294967295);$p2=$arrayidx999;var $543=$p2;var $phcode=(($543)&4294967295);HEAP8[($phcode)]=9;var $544=$p2;var $stresslevel=(($544+1)&4294967295);HEAP8[($stresslevel)]=0;var $545=HEAP32[(($source_index)>>2)];var $conv1000=((($545))&65535);var $546=$p2;var $sourceix1001=(($546+6)&4294967295);HEAP16[(($sourceix1001)>>1)]=$conv1000;var $547=$p2;var $synthflags=(($547+4)&4294967295);HEAP16[(($synthflags)>>1)]=0;var $548=$ix;var $inc1003=((($548)+1)&4294967295);$ix=$inc1003;var $cmp996=((($inc1003))|0)<2;var $549=HEAP32[((_n_ph_list2)>>2)];if($cmp996){__lastLabel__=297;__label__=297;continue $for_body997$415;}else{__lastLabel__=297;__label__=298;break $for_body997$415;}}
var $add1005=((($549)+2)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$add1005;var $550=HEAP32[((_count_words)>>2)];var $cmp1006=((($550))|0)==0;if($cmp1006){__label__=299;;}else{__label__=300;;}
if(__label__==299){$clause_pause=0;;}
var $call1009=__Z3Eofv();var $tobool1010=((($call1009))|0)!=0;if($tobool1010){__label__=301;;}else{__label__=303;;}
$land_lhs_true1011$$if_end1016$421:do{if(__label__==301){var $551=$word_count;var $cmp1012=((($551))|0)==0;var $552=HEAP32[((_option_endpause)>>2)];var $cmp1014=((($552))|0)==0;var $or_cond11=($cmp1012)|($cmp1014);if(!($or_cond11)){__label__=303;break $land_lhs_true1011$$if_end1016$421;}
$clause_pause=10;;}}while(0);var $553=$tr_addr;var $554=$clause_pause;var $555=HEAP32[((_new_sentence)>>2)];__Z15MakePhonemeListP10Translatorii($553,$554,$555);var $556=$embedded_count;var $tobool1017=((($556))|0)!=0;if($tobool1017){__label__=304;;}else{__label__=305;;}
if(__label__==304){var $557=HEAP32[((_n_phoneme_list)>>2)];var $sub1019=((($557)-2)&4294967295);var $arrayidx1020=((_phoneme_list+$sub1019*24)&4294967295);var $synthflags1021=(($arrayidx1020+4)&4294967295);HEAP16[(($synthflags1021)>>1)]=2;var $558=HEAP32[((__ZL11embedded_ix)>>2)];var $sub1022=((($558)-1)&4294967295);var $arrayidx1023=((_embedded_list+$sub1022*4)&4294967295);var $559=HEAP32[(($arrayidx1023)>>2)];var $or1024=($559)|128;HEAP32[(($arrayidx1023)>>2)]=$or1024;;}
var $560=$tone;var $561=$tone_out_addr;HEAP32[(($561)>>2)]=$560;HEAP32[((_new_sentence)>>2)]=0;var $562=$terminator;var $and1026=($562)&524288;var $tobool1027=((($and1026))|0)!=0;if($tobool1027){__label__=306;;}else{__label__=307;;}
if(__label__==306){HEAP32[((_new_sentence)>>2)]=1;;}
var $563=$voice_change_addr;var $cmp1030=((($563))|0)!=0;if($cmp1030){__label__=308;;}else{__label__=311;;}
if(__label__==308){var $564=$terminator;var $and1032=($564)&131072;var $tobool1033=((($and1032))|0)!=0;var $565=$voice_change_addr;if($tobool1033){__label__=309;;}else{__label__=310;;}
if(__label__==309){HEAP32[(($565)>>2)]=((__ZZ15TranslateClauseP10TranslatorP7__sFILEPKvPiPPcE17voice_change_name)&4294967295);;}
else if(__label__==310){HEAP32[(($565)>>2)]=0;;}}
var $call1038=__Z3Eofv();var $tobool1039=((($call1038))|0)!=0;if($tobool1039){__label__=313;;}else{__label__=312;;}
$if_then1042$$lor_lhs_false1040$437:do{if(__label__==312){var $566=$vp_input_addr;var $cmp1041=((($566))|0)==0;if($cmp1041){__label__=313;break $if_then1042$$lor_lhs_false1040$437;}
var $567=HEAP32[((_option_multibyte)>>2)];var $cmp1044=((($567))|0)==3;if($cmp1044){__label__=315;;}else{__label__=316;;}
if(__label__==315){var $568=HEAP32[((_p_wchar_input)>>2)];var $569=$568;$retval=$569;__label__=317;break $if_then$$if_end$2;}
else if(__label__==316){var $570=HEAP32[((_p_textinput)>>2)];$retval=$570;__label__=317;break $if_then$$if_end$2;}}}while(0);$retval=0;;}}while(0);var $571=$retval;STACKTOP=__stackBase__;return $571;return null;}
function __ZL9IsDigit09j($c){;var __label__;var $retval;var $c_addr;$c_addr=$c;var $0=$c_addr;var $cmp=((($0))>>>0)>=48;var $1=$c_addr;var $cmp1=((($1))>>>0)<=57;var $or_cond=($cmp)&($cmp1);if($or_cond){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){$retval=0;;}
var $2=$retval;;return $2;return null;}
function __ZL15EmbeddedCommandRj($source_index){;var __label__;var __lastLabel__=null;var $retval;var $source_index_addr;var $commands;var $value;var $sign;var $c;var $p;var $cmd;$source_index_addr=$source_index;$commands=((__str12555)&4294967295);$value=-1;$sign=0;var $0=$source_index_addr;var $1=HEAP32[(($0)>>2)];var $arrayidx=((__ZL6source+$1)&4294967295);var $2=HEAP8[($arrayidx)];$c=$2;var $3=$c;var $conv=((($3))&255);var $cmp=((($conv))|0)==43;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_else$2:do{if(__label__==1){$sign=64;var $4=$source_index_addr;var $5=HEAP32[(($4)>>2)];var $inc=((($5)+1)&4294967295);HEAP32[(($4)>>2)]=$inc;;}
else if(__label__==2){var $6=$c;var $conv1=((($6))&255);var $cmp2=((($conv1))|0)==45;if(!($cmp2)){__label__=4;break $if_then$$if_else$2;}
$sign=96;var $7=$source_index_addr;var $8=HEAP32[(($7)>>2)];var $inc4=((($8)+1)&4294967295);HEAP32[(($7)>>2)]=$inc4;;}}while(0);var $9=$source_index_addr;var $10=HEAP32[(($9)>>2)];var $arrayidx6=((__ZL6source+$10)&4294967295);var $11=HEAP8[($arrayidx6)];var $conv7=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp=((($conv7)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call=((($isdigit))&1);var $tobool=((($call))|0)!=0;if($tobool){__label__=5;;}else{__label__=7;;}
$if_then8$$if_end16$7:do{if(__label__==5){var $12=$source_index_addr;var $13=HEAP32[(($12)>>2)];var $arrayidx9=((__ZL6source+$13)&4294967295);var $call10=_atoi($arrayidx9);$value=$call10;var $14=$source_index_addr;var $15=HEAP32[(($14)>>2)];var $arrayidx113=((__ZL6source+$15)&4294967295);var $16=HEAP8[($arrayidx113)];var $conv124=(tempInt=(($16)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp15=((($conv124)-48)&4294967295);var $isdigit26=((($isdigittmp15))>>>0)<10;if(!($isdigit26)){__label__=7;break $if_then8$$if_end16$7;}
while(1){var $17=$source_index_addr;var $18=HEAP32[(($17)>>2)];var $inc15=((($18)+1)&4294967295);HEAP32[(($17)>>2)]=$inc15;var $19=$source_index_addr;var $20=HEAP32[(($19)>>2)];var $arrayidx11=((__ZL6source+$20)&4294967295);var $21=HEAP8[($arrayidx11)];var $conv12=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp1=((($conv12)-48)&4294967295);var $isdigit2=((($isdigittmp1))>>>0)<10;var $call13=((($isdigit2))&1);var $tobool14=((($call13))|0)!=0;if($tobool14){__label__=6;continue;}else{__label__=7;break $if_then8$$if_end16$7;}}}}while(0);var $22=$source_index_addr;var $23=HEAP32[(($22)>>2)];var $inc17=((($23)+1)&4294967295);HEAP32[(($22)>>2)]=$inc17;var $arrayidx18=((__ZL6source+$23)&4294967295);var $24=HEAP8[($arrayidx18)];$c=$24;var $25=HEAP32[((__ZL11embedded_ix)>>2)];var $cmp19=((($25))|0)>=248;if($cmp19){__label__=8;;}else{__label__=9;;}
if(__label__==8){$retval=0;;}
else if(__label__==9){var $26=$commands;var $27=$c;var $conv22=((($27))&255);var $call23=__Z8strchr_wPKci($26,$conv22);$p=$call23;var $cmp24=((($call23))|0)==0;if($cmp24){__label__=10;;}else{__label__=11;;}
if(__label__==10){$retval=0;;}
else if(__label__==11){var $28=$p;var $29=$commands;var $sub_ptr_lhs_cast=($28);var $sub_ptr_rhs_cast=($29);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);var $add=((($sub_ptr_sub)+1)&4294967295);$cmd=$add;var $30=$value;var $cmp27=((($30))|0)==-1;if($cmp27){__lastLabel__=11;__label__=12;;}else{__lastLabel__=11;__label__=13;;}
if(__label__==12){var $31=$cmd;var $arrayidx29=((_embedded_default+$31*4)&4294967295);var $32=HEAP32[(($arrayidx29)>>2)];$value=$32;$sign=0;__lastLabel__=12;;}
var $33=__lastLabel__==12?$31:($add);var $cmp31=((($33))|0)==9;if($cmp31){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $34=$value;HEAP32[((__ZL13option_sayas2)>>2)]=$34;HEAP32[((__ZL18count_sayas_digits)>>2)]=0;;}
var $35=$cmd;var $cmp34=((($35))|0)==13;if($cmp34){__label__=16;;}else{__label__=19;;}
if(__label__==16){var $36=$value;var $cmp36=((($36))|0)>=3;if($cmp36){__label__=17;;}else{__label__=18;;}
if(__label__==17){HEAP8[(__ZL13word_emphasis_b)]=1;;}
else if(__label__==18){HEAP8[(__ZL13word_emphasis_b)]=0;;}}
var $37=$cmd;var $38=$sign;var $39=$value;var $shl=((($39)*256)&4294967295);var $add41=((($38)+($37))&4294967295);var $add42=((($add41)+($shl))&4294967295);var $40=HEAP32[((__ZL11embedded_ix)>>2)];var $inc43=((($40)+1)&4294967295);HEAP32[((__ZL11embedded_ix)>>2)]=$inc43;var $arrayidx44=((_embedded_list+$40*4)&4294967295);HEAP32[(($arrayidx44)>>2)]=$add42;$retval=1;;}}
var $41=$retval;;return $41;return null;}
function __ZL13TranslateCharP10TranslatorPcijjPi($tr,$ptr,$prev_in,$c,$next_in,$insert){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $retval;var $tr_addr;var $ptr_addr;var $prev_in_addr;var $c_addr;var $next_in_addr;var $insert_addr;var $code;var $initial;var $medial;var $final;var $next2=__stackBase__;$tr_addr=$tr;$ptr_addr=$ptr;$prev_in_addr=$prev_in;$c_addr=$c;$next_in_addr=$next_in;$insert_addr=$insert;var $0=$tr_addr;var $translator_name=(($0+280)&4294967295);var $1=HEAP32[(($translator_name)>>2)];if($1==24934){__label__=1;;}
else if($1==28268){__label__=1;;}
else if($1==27503){__label__=9;;}
else{__label__=18;;}
$sw_epilog$$sw_bb$$sw_bb17$2:do{if(__label__==1){var $2=$prev_in_addr;var $call=_iswalpha($2);var $tobool=((($call))|0)!=0;if($tobool){__label__=18;break $sw_epilog$$sw_bb$$sw_bb17$2;}
var $3=$ptr_addr;var $arrayidx=(($3+1)&4294967295);var $call1=__Z7utf8_inPiPKc($next2,$arrayidx);var $4=$c_addr;var $cmp=((($4))|0)==39;if(!($cmp)){__label__=18;break $sw_epilog$$sw_bb$$sw_bb17$2;}
var $5=HEAP32[(($next2)>>2)];var $call2=__Z7IsSpacej($5);var $tobool3=((($call2))|0)!=0;if(!($tobool3)){__label__=18;break $sw_epilog$$sw_bb$$sw_bb17$2;}
var $6=$next_in_addr;var $cmp5=((($6))|0)==110;if($cmp5){__label__=5;;}else{__label__=7;;}
$land_lhs_true6$$if_end$7:do{if(__label__==5){var $7=$tr_addr;var $translator_name7=(($7+280)&4294967295);var $8=HEAP32[(($translator_name7)>>2)];var $cmp8=((($8))|0)==24934;if(!($cmp8)){__label__=7;break $land_lhs_true6$$if_end$7;}
var $9=$ptr_addr;var $arrayidx10=(($9)&4294967295);HEAP8[($arrayidx10)]=32;$retval=601;__label__=19;break $sw_epilog$$sw_bb$$sw_bb17$2;}}while(0);var $10=$next_in_addr;var $cmp11=((($10))|0)==110;var $11=$next_in_addr;var $cmp12=((($11))|0)==116;var $or_cond=($cmp11)|($cmp12);if(!($or_cond)){__label__=18;break $sw_epilog$$sw_bb$$sw_bb17$2;}
$retval=601;__label__=19;break $sw_epilog$$sw_bb$$sw_bb17$2;}
else if(__label__==9){var $12=$c_addr;var $sub=((($12)-44032)&4294967295);$code=$sub;var $cmp18=((($sub))|0)>=0;var $13=$c_addr;var $cmp20=((($13))>>>0)<=55215;var $or_cond1=($cmp18)&($cmp20);if($or_cond1){__label__=10;;}else{__label__=15;;}
if(__label__==10){var $14=$code;var $div=((((($14))|0)/28)|0);var $div22=((((($div))|0)/21)|0);$initial=$div22;var $15=$code;var $div23=((((($15))|0)/28)|0);var $rem=((($div23))|0)%21;$medial=$rem;var $16=$code;var $rem24=((($16))|0)%28;$final=$rem24;var $17=$initial;var $cmp25=((($17))|0)==11;if($cmp25){__label__=11;;}else{__label__=13;;}
$if_then26$$if_else$15:do{if(__label__==11){var $18=$medial;var $add=((($18)+4449)&4294967295);$c_addr=$add;var $19=$final;var $cmp27=((($19))|0)>0;if(!($cmp27)){__label__=14;break $if_then26$$if_else$15;}
var $20=$final;var $add29=((($20)+4519)&4294967295);var $21=$insert_addr;HEAP32[(($21)>>2)]=$add29;;}
else if(__label__==13){var $22=$initial;var $add31=((($22)+4352)&4294967295);$c_addr=$add31;var $23=$medial;var $mul=((($23)*28)&4294967295);var $24=$final;var $add33=((($24)+50500)&4294967295);var $add34=((($add33)+($mul))&4294967295);var $25=$insert_addr;HEAP32[(($25)>>2)]=$add34;;}}while(0);var $26=$c_addr;$retval=$26;__label__=19;break $sw_epilog$$sw_bb$$sw_bb17$2;}
else if(__label__==15){var $27=$c_addr;var $sub37=((($27)-12592)&4294967295);$code=$sub37;var $cmp38=((($sub37))|0)>=0;if(!($cmp38)){__label__=18;break $sw_epilog$$sw_bb$$sw_bb17$2;}
var $28=$code;var $cmp40=((($28))|0)<52;if(!($cmp40)){__label__=18;break $sw_epilog$$sw_bb$$sw_bb17$2;}
var $29=$code;var $arrayidx42=((__ZZL13TranslateCharP10TranslatorPcijjPiE20hangul_compatibility+$29)&4294967295);var $30=HEAPU8[($arrayidx42)];var $conv=((($30))&255);var $add43=((($conv)+4352)&4294967295);$retval=$add43;__label__=19;break $sw_epilog$$sw_bb$$sw_bb17$2;}}}while(0);if(__label__==18){var $31=$tr_addr;var $32=$c_addr;var $33=$next_in_addr;var $34=$insert_addr;var $call46=__ZL14SubstituteCharP10TranslatorjjPi($31,$32,$33,$34);$retval=$call46;;}
var $35=$retval;STACKTOP=__stackBase__;return $35;return null;}
function __ZL14TranslateWord2P10TranslatorPcP8WORD_TABii($tr,$word,$wtab,$pre_pause,$next_pause){var __stackBase__=STACKTOP;STACKTOP+=392;_memset(__stackBase__,0,392);var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $word_addr;var $wtab_addr;var $pre_pause_addr;var $next_pause_addr;var $flags;var $stress;var $next_stress;var $next_tone;var $p;var $srcix;var $embedded_cmd;var $value;var $found_dict_flag;var $ph_code;var $plist2;var $ph;var $max_stress;var $max_stress_ix;var $prev_vowel;var $pitch_raised;var $switch_phonemes;var $first_phoneme;var $source_ix;var $len;var $ix;var $sylimit;var $new_language;var $bad_phoneme=__stackBase__;var $word_flags;var $word_copy_len;var $word_copy=__stackBase__+4;var $old_dictionary_name=__stackBase__+168;var $c1;var $lang_name=__stackBase__+208;var $c2;var $p2;var $ok;var $flags2=__stackBase__+220;var $c_word2=__stackBase__+228;var $ph_buf=__stackBase__+232;$tr_addr=$tr;$word_addr=$word;$wtab_addr=$wtab;$pre_pause_addr=$pre_pause;$next_pause_addr=$next_pause;$flags=0;$next_tone=0;$max_stress_ix=0;$prev_vowel=-1;$pitch_raised=0;$switch_phonemes=-1;$first_phoneme=1;var $0=HEAP32[((_f_logespeak)>>2)];var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=7;;}
$land_lhs_true$$if_end10$2:do{if(__label__==1){var $1=HEAP32[((_logging_type)>>2)];var $and=($1)&8;var $tobool=((($and))|0)!=0;if(!($tobool)){__label__=7;break $land_lhs_true$$if_end10$2;}
var $2=HEAP32[((_f_logespeak)>>2)];var $3=$wtab_addr;var $flags1=(($3)&4294967295);var $4=HEAP32[(($flags1)>>2)];var $5=$wtab_addr;var $length=(($5+10)&4294967295);var $6=HEAPU8[($length)];var $conv=((($6))&255);var $call=_fprintf($2,((__str9552)&4294967295),allocate([$4,0,0,0,$conv,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STACK));$ix=0;__lastLabel__=2;;while(1){var $7=__lastLabel__==5?$inc:(0);var $cmp2=((($7))|0)<40;if(!($cmp2)){__label__=6;break;}
var $8=$ix;var $9=$word_addr;var $arrayidx=(($9+$8)&4294967295);var $10=HEAP8[($arrayidx)];var $conv3=(tempInt=(($10)),(tempInt>=128?tempInt-256:tempInt));var $cmp4=((($conv3))|0)==0;if($cmp4){__label__=6;break;}
var $11=$ix;var $12=$word_addr;var $arrayidx6=(($12+$11)&4294967295);var $13=HEAP8[($arrayidx6)];var $conv7=(tempInt=(($13)),(tempInt>=128?tempInt-256:tempInt));var $14=HEAP32[((_f_logespeak)>>2)];var $call8=_fputc($conv7,$14);var $15=$ix;var $inc=((($15)+1)&4294967295);$ix=$inc;__lastLabel__=5;__label__=3;continue;}
var $16=HEAP32[((_f_logespeak)>>2)];var $17=_fwrite(((__str10553)&4294967295),2,1,$16);;}}while(0);var $18=$wtab_addr;var $length11=(($18+10)&4294967295);var $19=HEAPU8[($length11)];var $conv12=((($19))&255);$len=$conv12;var $cmp13=((($conv12))|0)>31;if($cmp13){__label__=8;;}else{__label__=9;;}
if(__label__==8){$len=31;;}
var $20=$wtab_addr;var $sourceix=(($20+6)&4294967295);var $21=HEAPU16[(($sourceix)>>1)];var $conv16=((($21))&65535);var $and17=($conv16)&2047;var $22=$len;var $shl=($22)<<11;var $or=($and17)|($shl);$source_ix=$or;var $23=$wtab_addr;var $arrayidx18=(($23)&4294967295);var $flags19=(($arrayidx18)&4294967295);var $24=HEAP32[(($flags19)>>2)];$word_flags=$24;var $25=$word_flags;var $and20=($25)&64;var $tobool21=((($and20))|0)!=0;if($tobool21){__label__=10;;}else{__label__=18;;}
$if_then22$$if_end33$14:do{if(__label__==10){HEAP8[(__ZL13embedded_flag_b)]=1;;while(1){var $26=HEAP32[((__ZL13embedded_read)>>2)];var $inc23=((($26)+1)&4294967295);HEAP32[((__ZL13embedded_read)>>2)]=$inc23;var $arrayidx24=((_embedded_list+$26*4)&4294967295);var $27=HEAP32[(($arrayidx24)>>2)];$embedded_cmd=$27;var $28=$embedded_cmd;var $shr=($28)>>8;$value=$shr;var $29=$embedded_cmd;var $and25=($29)&31;if($and25==9){__label__=12;;}
else if($and25==13){__label__=13;;}
else if($and25==12){__label__=14;;}
else{__label__=17;;}
if(__label__==12){var $30=$value;HEAP32[((_option_sayas)>>2)]=$30;;}
else if(__label__==13){var $31=$value;HEAP32[((__ZL15option_emphasis)>>2)]=$31;;}
else if(__label__==14){var $32=$value;var $cmp28=((($32))|0)==0;if($cmp28){__label__=15;;}else{__label__=16;;}
if(__label__==15){$pre_pause_addr=0;;}
else if(__label__==16){var $33=$value;var $34=$pre_pause_addr;var $add=((($34)+($33))&4294967295);$pre_pause_addr=$add;;}}
var $35=$embedded_cmd;var $and31=($35)&128;var $cmp32=((($and31))|0)==0;if($cmp32){__label__=11;continue;}else{__label__=18;break $if_then22$$if_end33$14;}}}}while(0);var $36=$word_addr;var $arrayidx34=(($36)&4294967295);var $37=HEAP8[($arrayidx34)];var $conv35=(tempInt=(($37)),(tempInt>=128?tempInt-256:tempInt));var $cmp36=((($conv35))|0)==0;if($cmp36){__label__=19;;}else{__label__=20;;}
$if_then37$$if_end38$27:do{if(__label__==19){HEAP8[(((_word_phonemes)&4294967295))]=0;$retval=0;;}
else if(__label__==20){var $38=$tr_addr;var $prepause_timeout=(($38+8312)&4294967295);var $39=HEAP32[(($prepause_timeout)>>2)];var $cmp39=((($39))|0)>0;if($cmp39){__label__=21;;}else{__label__=22;;}
if(__label__==21){var $40=$tr_addr;var $prepause_timeout41=(($40+8312)&4294967295);var $41=HEAP32[(($prepause_timeout41)>>2)];var $dec=((($41)-1)&4294967295);HEAP32[(($prepause_timeout41)>>2)]=$dec;;}
var $42=HEAP32[((_option_sayas)>>2)];var $and43=($42)&240;var $cmp44=((($and43))|0)==16;if($cmp44){__label__=23;;}else{__label__=25;;}
$if_then45$$if_end51$33:do{if(__label__==23){var $43=$word_flags;var $and46=($43)&512;var $tobool47=((($and46))|0)!=0;if($tobool47){__label__=25;break $if_then45$$if_end51$33;}
var $44=$pre_pause_addr;var $add49=((($44)+4)&4294967295);$pre_pause_addr=$add49;;}}while(0);var $45=$word_flags;var $and52=($45)&2;var $tobool53=((($and52))|0)!=0;if($tobool53){__label__=26;;}else{__label__=32;;}
$if_then54$$if_end72$37:do{if(__label__==26){var $46=HEAP32[((_option_capitals)>>2)];var $cmp55=((($46))|0)>2;var $47=HEAP32[((__ZL11embedded_ix)>>2)];var $cmp57=((($47))|0)<244;var $or_cond=($cmp55)&($cmp57);if(!($or_cond)){__label__=32;break $if_then54$$if_end72$37;}
var $_b3=HEAPU8[(__ZL13embedded_flag_b)];var $48=($_b3)?2:0;var $tobool59=((($48))|0)!=0;if($tobool59){__label__=28;;}else{__label__=29;;}
if(__label__==28){var $49=HEAP32[((__ZL11embedded_ix)>>2)];var $sub=((($49)-1)&4294967295);var $arrayidx61=((_embedded_list+$sub*4)&4294967295);var $50=HEAP32[(($arrayidx61)>>2)];var $and62=($50)&-129;HEAP32[(($arrayidx61)>>2)]=$and62;;}
var $51=HEAP32[((_option_capitals)>>2)];$pitch_raised=$51;var $cmp64=((($51))|0)==3;if($cmp64){__label__=30;;}else{__label__=31;;}
if(__label__==30){$pitch_raised=20;;}
var $52=$pitch_raised;var $shl67=((($52)*256)&4294967295);var $add68=((($shl67)+193)&4294967295);var $53=HEAP32[((__ZL11embedded_ix)>>2)];var $inc69=((($53)+1)&4294967295);HEAP32[((__ZL11embedded_ix)>>2)]=$inc69;var $arrayidx70=((_embedded_list+$53*4)&4294967295);HEAP32[(($arrayidx70)>>2)]=$add68;HEAP8[(__ZL13embedded_flag_b)]=1;;}}while(0);$p=((_word_phonemes)&4294967295);var $54=$word_flags;var $and73=($54)&8;var $tobool74=((($and73))|0)!=0;if($tobool74){__label__=33;;}else{__label__=40;;}
$if_then75$$if_else100$47:do{if(__label__==33){var $55=$word_addr;var $call76=_memcmp($55,((__str11554)&4294967295),3);var $cmp77=((($call76))|0)==0;var $56=$word_addr;if($cmp77){__label__=34;;}else{__label__=38;;}
$if_then78$$if_else96$49:do{if(__label__==34){var $add_ptr=(($56+3)&4294967295);$word_addr=$add_ptr;$ix=0;var $57=$word_addr;var $incdec_ptr32=(($57+1)&4294967295);$word_addr=$incdec_ptr32;var $58=HEAP8[($57)];var $conv8033=(tempInt=(($58)),(tempInt>=128?tempInt-256:tempInt));$c1=$conv8033;var $59=$c1;var $cmp8134=((($59))|0)==32;var $60=$c1;var $cmp8235=((($60))|0)==0;var $or_cond436=($cmp8134)|($cmp8235);if($or_cond436){__label__=36;;}else{__label__=35;;}
$for_end89$$if_end84$51:do{if(__label__==35){while(1){var $61=$c1;var $call85=_tolower($61);var $conv86=((($call85))&255);var $62=$ix;var $inc87=((($62)+1)&4294967295);$ix=$inc87;var $arrayidx88=(($lang_name+$62)&4294967295);HEAP8[($arrayidx88)]=$conv86;var $63=$word_addr;var $incdec_ptr=(($63+1)&4294967295);$word_addr=$incdec_ptr;var $64=HEAP8[($63)];var $conv80=(tempInt=(($64)),(tempInt>=128?tempInt-256:tempInt));$c1=$conv80;var $65=$c1;var $cmp81=((($65))|0)==32;var $66=$c1;var $cmp82=((($66))|0)==0;var $or_cond4=($cmp81)|($cmp82);if($or_cond4){__label__=36;break $for_end89$$if_end84$51;}else{__label__=35;continue;}}}}while(0);var $67=$ix;var $arrayidx90=(($lang_name+$67)&4294967295);HEAP8[($arrayidx90)]=0;var $arraydecay=(($lang_name)&4294967295);var $call91=__Z18LookupPhonemeTablePKc($arraydecay);$ix=$call91;var $cmp92=((($call91))|0)>0;if(!($cmp92)){__label__=39;break $if_then78$$if_else96$49;}
var $68=$ix;__Z18SelectPhonemeTablei($68);HEAP8[(((_word_phonemes)&4294967295))]=21;var $69=$ix;var $conv94=((($69))&255);HEAP8[(((_word_phonemes+1)&4294967295))]=$conv94;HEAP8[(((_word_phonemes+2)&4294967295))]=0;;}
else if(__label__==38){var $arraydecay97=(($bad_phoneme)&4294967295);var $call98=__Z14EncodePhonemesPcS_Ph($56,((_word_phonemes)&4294967295),$arraydecay97);;}}while(0);$flags=-2147483648;;}
else if(__label__==40){$ix=0;;$while_cond$59:while(1){var $70=$ix;var $71=$word_addr;var $arrayidx101=(($71+$70)&4294967295);var $72=HEAP8[($arrayidx101)];var $73=$ix;var $arrayidx102=(($word_copy+$73)&4294967295);HEAP8[($arrayidx102)]=$72;var $conv103=(tempInt=(($72)),(tempInt>=128?tempInt-256:tempInt));$c2=$conv103;var $cmp104=((($conv103))|0)!=32;if(!($cmp104)){__label__=43;break $while_cond$59;}
var $74=$c2;var $cmp106=((($74))|0)!=0;if(!($cmp106)){__label__=43;break $while_cond$59;}
var $76=$ix;var $cmp107=((($76))|0)<160;var $77=$ix;if($cmp107){__lastLabel__=44;;}else{__lastLabel__=44;__label__=46;break $while_cond$59;}
var $inc108=((($77)+1)&4294967295);$ix=$inc108;__label__=41;continue $while_cond$59;}
if(__label__==43){var $75=$ix;__lastLabel__=43;;}
var $78=__lastLabel__==43?$75:($77);$word_copy_len=$78;var $79=HEAP32[((_translator)>>2)];var $80=$word_addr;var $81=$next_pause_addr;var $82=$wtab_addr;var $call109=__Z13TranslateWordP10TranslatorPciP8WORD_TAB($79,$80,$81,$82);$flags=$call109;var $83=$flags;var $and110=($83)&65536;var $tobool111=((($and110))|0)!=0;if($tobool111){__label__=47;;}else{__label__=48;;}
if(__label__==47){var $84=$word_addr;var $arraydecay113=(($word_copy)&4294967295);var $85=$word_copy_len;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay113;$dest$=$84;$stop$=$src$+$85;if(($dest$%4)==($src$%4)&&$85>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $86=$flags;$retval=$86;__label__=171;break $if_then37$$if_end38$27;}
else if(__label__==48){var $87=$flags;var $and115=($87)&8388608;var $tobool116=((($and115))|0)!=0;if($tobool116){__label__=49;;}else{__label__=72;;}
$land_lhs_true117$$if_end192$70:do{if(__label__==49){var $88=$wtab_addr;var $arrayidx118=(($88+12)&4294967295);var $flags119=(($arrayidx118)&4294967295);var $89=HEAP32[(($flags119)>>2)];var $and120=($89)&8;var $tobool121=((($and120))|0)!=0;if($tobool121){__label__=72;break $land_lhs_true117$$if_end192$70;}
$ok=1;var $arrayidx123=(($flags2)&4294967295);HEAP32[(($arrayidx123)>>2)]=0;var $90=$tr_addr;var $langopts=(($90)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx124=(($param+44)&4294967295);var $91=HEAP32[(($arrayidx124)>>2)];$sylimit=$91;var $92=$word_addr;$p2=$92;var $93=$p2;var $94=HEAP8[($93)];var $conv12620=(tempInt=(($94)),(tempInt>=128?tempInt-256:tempInt));var $cmp12721=((($conv12620))|0)!=32;var $95=$p2;var $incdec_ptr12922=(($95+1)&4294967295);if($cmp12721){__lastLabel__=50;__label__=51;;}else{__lastLabel__=50;__label__=52;;}
$while_body128$$while_end130$73:do{if(__label__==51){while(1){var $incdec_ptr12923=__lastLabel__==51?$incdec_ptr129:($incdec_ptr12922);$p2=$incdec_ptr12923;var $96=$p2;var $97=HEAP8[($96)];var $conv126=(tempInt=(($97)),(tempInt>=128?tempInt-256:tempInt));var $cmp127=((($conv126))|0)!=32;var $98=$p2;var $incdec_ptr129=(($98+1)&4294967295);if($cmp127){__lastLabel__=51;__label__=51;continue;}else{__lastLabel__=51;__label__=52;break $while_body128$$while_end130$73;}}}}while(0);var $incdec_ptr129_lcssa=__lastLabel__==50?$incdec_ptr12922:($incdec_ptr129);var $call132=__Z7utf8_inPiPKc($c_word2,$incdec_ptr129_lcssa);var $99=HEAP32[(($c_word2)>>2)];var $call133=_iswalpha($99);var $tobool134=((($call133))|0)!=0;if($tobool134){__label__=54;;}else{__label__=53;;}
if(__label__==54){var $_pr=$ok;var $cmp137=((($_pr))|0)!=0;if(!($cmp137)){__label__=72;break $land_lhs_true117$$if_end192$70;}
var $arraydecay139=(($ph_buf)&4294967295);var $call140=_strcpy($arraydecay139,((_word_phonemes)&4294967295));var $100=HEAP32[((_translator)>>2)];var $101=$p2;var $add_ptr141=(($101+1)&4294967295);var $102=$wtab_addr;var $add_ptr142=(($102+12)&4294967295);var $call143=__Z13TranslateWordP10TranslatorPciP8WORD_TAB($100,$add_ptr141,0,$add_ptr142);var $arrayidx144=(($flags2)&4294967295);HEAP32[(($arrayidx144)>>2)]=$call143;var $arrayidx145=(($flags2)&4294967295);var $103=HEAP32[(($arrayidx145)>>2)];var $and146=($103)&67108864;var $tobool147=((($and146))|0)!=0;if($tobool147){__label__=56;;}else{__label__=57;;}
if(__label__==56){$ok=0;;}
var $104=$sylimit;var $and150=($104)&256;var $tobool151=((($and150))|0)!=0;if($tobool151){__label__=58;;}else{__label__=60;;}
$if_then152$$if_end158$83:do{if(__label__==58){var $arrayidx153=(($flags2)&4294967295);var $105=HEAP32[(($arrayidx153)>>2)];var $and154=($105)&1048576;var $cmp155=((($and154))|0)==0;if(!($cmp155)){__label__=60;break $if_then152$$if_end158$83;}
$ok=0;;}}while(0);var $106=$sylimit;var $and159=($106)&512;var $tobool160=((($and159))|0)!=0;if($tobool160){__label__=61;;}else{__label__=63;;}
$land_lhs_true161$$if_end167$87:do{if(__label__==61){var $107=$wtab_addr;var $add_ptr162=(($107+12)&4294967295);var $flags163=(($add_ptr162)&4294967295);var $108=HEAP32[(($flags163)>>2)];var $and164=($108)&16;var $tobool165=((($and164))|0)!=0;if(!($tobool165)){__label__=63;break $land_lhs_true161$$if_end167$87;}
$ok=0;__label__=64;break $land_lhs_true161$$if_end167$87;}}while(0);$if_end173$$if_end167$90:do{if(__label__==63){var $_pr8=$ok;var $cmp168=((($_pr8))|0)==0;if($cmp168){__label__=64;break $if_end173$$if_end167$90;}else{__label__=65;break $if_end173$$if_end167$90;}}}while(0);if(__label__==64){var $arraydecay170=(($ph_buf)&4294967295);var $call171=_strcpy(((_word_phonemes)&4294967295),$arraydecay170);var $_pr10_pr=$ok;var $tobool174=((($_pr10_pr))|0)!=0;if(!($tobool174)){__label__=72;break $land_lhs_true117$$if_end192$70;}}
var $109=$p2;HEAP8[($109)]=45;var $110=HEAP32[((_translator)>>2)];var $111=$word_addr;var $112=$next_pause_addr;var $113=$wtab_addr;var $call176=__Z13TranslateWordP10TranslatorPciP8WORD_TAB($110,$111,$112,$113);$flags=$call176;var $114=$sylimit;var $cmp177=((($114))|0)>0;if($cmp177){__lastLabel__=65;__label__=66;;}else{__lastLabel__=65;__label__=69;;}
if(__label__==66){var $115=$p;var $call179=__ZL14CountSyllablesPh($115);var $116=$sylimit;var $and180=($116)&31;var $cmp181=((($call179))|0)>((($and180))|0);if($cmp181){__label__=67;;}else{__label__=68;;}
if(__label__==67){var $117=$p2;HEAP8[($117)]=32;var $118=HEAP32[((_translator)>>2)];var $119=$word_addr;var $120=$next_pause_addr;var $121=$wtab_addr;var $call183=__Z13TranslateWordP10TranslatorPciP8WORD_TAB($118,$119,$120,$121);$flags=$call183;__label__=72;break $land_lhs_true117$$if_end192$70;}
else if(__label__==68){var $_pr14=$flags;__lastLabel__=68;;}}
var $122=__lastLabel__==68?$_pr14:($call176);var $cmp185=((($122))|0)==0;if($cmp185){__label__=70;;}else{__label__=71;;}
if(__label__==70){var $arrayidx187=(($flags2)&4294967295);var $123=HEAP32[(($arrayidx187)>>2)];$flags=$123;;}
var $124=$flags;var $or189=($124)|128;$flags=$or189;HEAP32[((_dictionary_skipwords)>>2)]=1;;}
else if(__label__==53){$ok=0;;}}}while(0);var $125=$p;var $arrayidx193=(($125)&4294967295);var $126=HEAPU8[($arrayidx193)];var $conv194=((($126))&255);var $cmp195=((($conv194))|0)==21;if($cmp195){__label__=73;;}else{__label__=84;;}
$if_then196$$if_end232$106:do{if(__label__==73){var $127=$word_addr;var $arraydecay197=(($word_copy)&4294967295);var $128=$word_copy_len;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay197;$dest$=$127;$stop$=$src$+$128;if(($dest$%4)==($src$%4)&&$128>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $129=$p;var $arrayidx198=(($129+1)&4294967295);$new_language=$arrayidx198;var $130=$new_language;var $arrayidx199=(($130)&4294967295);var $131=HEAP8[($arrayidx199)];var $conv200=(tempInt=(($131)),(tempInt>=128?tempInt-256:tempInt));var $cmp201=((($conv200))|0)==0;if($cmp201){__label__=74;;}else{__label__=75;;}
if(__label__==74){$new_language=((__str52704)&4294967295);;}
var $arraydecay204=(($old_dictionary_name)&4294967295);var $call205=_strcpy($arraydecay204,((_dictionary_name)&4294967295));var $132=$new_language;var $call206=__Z14SetTranslator2PKc($132);$switch_phonemes=$call206;var $cmp207=((($call206))|0)>=0;if($cmp207){__label__=76;;}else{__label__=79;;}
$if_then208$$if_then217$111:do{if(__label__==76){var $133=HEAP32[((_translator2)>>2)];var $134=$word_addr;var $135=$next_pause_addr;var $136=$wtab_addr;var $call209=__Z13TranslateWordP10TranslatorPciP8WORD_TAB($133,$134,$135,$136);$flags=$call209;var $137=$p;var $arrayidx210=(($137)&4294967295);var $138=HEAPU8[($arrayidx210)];var $conv211=((($138))&255);var $cmp212=((($conv211))|0)==21;if($cmp212){__label__=77;;}else{__label__=78;;}
if(__label__==77){$switch_phonemes=-1;__label__=79;break $if_then208$$if_then217$111;}
else if(__label__==78){var $_pr15=$switch_phonemes;var $cmp216=((($_pr15))|0)<0;if($cmp216){__label__=79;break $if_then208$$if_then217$111;}else{__label__=80;break $if_then208$$if_then217$111;}}}}while(0);if(__label__==79){var $139=$p;var $arrayidx218=(($139)&4294967295);HEAP8[($arrayidx218)]=13;var $140=$p;var $arrayidx219=(($140+1)&4294967295);HEAP8[($arrayidx219)]=13;var $141=$p;var $arrayidx220=(($141+2)&4294967295);HEAP8[($arrayidx220)]=0;;}
var $142=$tr_addr;var $143=$switch_phonemes;var $144=$p;var $call222=__Z24ChangeEquivalentPhonemesP10TranslatoriPc($142,$143,$144);var $tobool223=((($call222))|0)!=0;if($tobool223){__label__=81;;}else{__label__=82;;}
if(__label__==81){$switch_phonemes=-1;;}
else if(__label__==82){var $_pr17=$switch_phonemes;var $cmp226=((($_pr17))|0)==-1;if(!($cmp226)){__label__=84;break $if_then196$$if_end232$106;}}
var $arraydecay228=(($old_dictionary_name)&4294967295);var $call229=_strcpy(((_dictionary_name)&4294967295),$arraydecay228);var $145=HEAP32[((_voice)>>2)];var $phoneme_tab_ix=(($145+40)&4294967295);var $146=HEAP32[(($phoneme_tab_ix)>>2)];__Z18SelectPhonemeTablei($146);var $147=HEAP32[((_voice)>>2)];var $phoneme_tab_ix230=(($147+40)&4294967295);var $148=HEAP32[(($phoneme_tab_ix230)>>2)];$switch_phonemes=$148;;}}while(0);var $149=$word_flags;var $and233=($149)&128;var $tobool234=((($and233))|0)!=0;if($tobool234){__label__=95;;}else{__label__=85;;}
$if_end261$$if_then235$124:do{if(__label__==85){var $150=$flags;var $and236=($150)&268435456;var $tobool237=((($and236))|0)!=0;if($tobool237){__label__=86;;}else{__label__=88;;}
$if_then238$$if_end242$126:do{if(__label__==86){var $151=$pre_pause_addr;var $cmp239=((($151))|0)<1;if(!($cmp239)){__label__=88;break $if_then238$$if_end242$126;}
$pre_pause_addr=1;;}}while(0);var $152=$flags;var $and243=($152)&256;var $tobool244=((($and243))|0)!=0;if(!($tobool244)){__label__=95;break $if_end261$$if_then235$124;}
var $153=$word_flags;var $tobool246=((($153))|0)!=0;if($tobool246){__label__=95;break $if_end261$$if_then235$124;}
var $154=$wtab_addr;var $arrayidx248=(($154+-12)&4294967295);var $flags249=(($arrayidx248)&4294967295);var $155=HEAP32[(($flags249)>>2)];var $and250=($155)&512;var $tobool251=((($and250))|0)!=0;if($tobool251){__label__=95;break $if_end261$$if_then235$124;}
var $156=$tr_addr;var $prepause_timeout253=(($156+8312)&4294967295);var $157=HEAP32[(($prepause_timeout253)>>2)];var $cmp254=((($157))|0)==0;if(!($cmp254)){__label__=95;break $if_end261$$if_then235$124;}
var $158=$pre_pause_addr;var $cmp256=((($158))|0)<4;if($cmp256){__label__=93;;}else{__label__=94;;}
if(__label__==93){$pre_pause_addr=4;;}
var $159=$tr_addr;var $prepause_timeout259=(($159+8312)&4294967295);HEAP32[(($prepause_timeout259)>>2)]=3;;}}while(0);var $160=HEAP32[((__ZL15option_emphasis)>>2)];var $cmp262=((($160))|0)>=3;if(!($cmp262)){__label__=98;break $if_then75$$if_else100$47;}
var $161=$pre_pause_addr;var $cmp264=((($161))|0)<1;if(!($cmp264)){__label__=98;break $if_then75$$if_else100$47;}
$pre_pause_addr=1;;}}}while(0);var $162=HEAP32[((_n_ph_list2)>>2)];var $arrayidx268=((_ph_list2+$162*8)&4294967295);$plist2=$arrayidx268;$stress=0;$next_stress=1;$srcix=0;$max_stress=-1;$found_dict_flag=0;var $163=$flags;var $and269=($163)&-2147483648;var $tobool270=((($and269))|0)!=0;if($tobool270){__label__=99;;}else{__label__=101;;}
$land_lhs_true271$$while_cond276_preheader$141:do{if(__label__==99){var $164=$flags;var $and272=($164)&536870912;var $tobool273=((($and272))|0)!=0;if($tobool273){__label__=101;break $land_lhs_true271$$while_cond276_preheader$141;}
$found_dict_flag=16;;}}while(0);var $165=$pre_pause_addr;var $cmp27729=((($165))|0)>0;var $166=HEAP32[((_n_ph_list2)>>2)];var $cmp27930=((($166))|0)<996;var $or_cond531=($cmp27729)&($cmp27930);if($or_cond531){__lastLabel__=101;__label__=102;;}else{__lastLabel__=101;__label__=106;;}
$while_body281$$while_end292$145:do{if(__label__==102){while(1){var $167=__lastLabel__==101?$165:($173);var $cmp282=((($167))|0)>1;var $168=HEAP32[((_n_ph_list2)>>2)];var $inc284=((($168)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc284;var $arrayidx285=((_ph_list2+$168*8)&4294967295);if($cmp282){__label__=103;;}else{__label__=104;;}
if(__label__==103){__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx285,9);var $169=$pre_pause_addr;var $sub286=((($169)-2)&4294967295);$pre_pause_addr=$sub286;;}
else if(__label__==104){__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx285,11);var $170=$pre_pause_addr;var $dec290=((($170)-1)&4294967295);$pre_pause_addr=$dec290;;}
var $171=$tr_addr;var $end_stressed_vowel=(($171+8316)&4294967295);HEAP32[(($end_stressed_vowel)>>2)]=0;var $172=$tr_addr;var $prev_dict_flags=(($172+8320)&4294967295);HEAP32[(($prev_dict_flags)>>2)]=0;var $173=$pre_pause_addr;var $cmp277=((($173))|0)>0;var $174=HEAP32[((_n_ph_list2)>>2)];var $cmp279=((($174))|0)<996;var $or_cond5=($cmp277)&($cmp279);if($or_cond5){__lastLabel__=105;__label__=102;continue;}else{__lastLabel__=105;__label__=106;break $while_body281$$while_end292$145;}}}}while(0);var $175=HEAP32[((_option_capitals)>>2)];var $cmp293=((($175))|0)==1;if($cmp293){__label__=107;;}else{__label__=111;;}
$land_lhs_true294$$if_end315$153:do{if(__label__==107){var $176=$word_flags;var $and295=($176)&2;var $tobool296=((($and295))|0)!=0;if(!($tobool296)){__label__=111;break $land_lhs_true294$$if_end315$153;}
var $177=HEAP32[((_n_ph_list2)>>2)];var $inc298=((($177)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc298;var $arrayidx299=((_ph_list2+$177*8)&4294967295);__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx299,10);var $178=HEAP32[((_n_ph_list2)>>2)];var $inc300=((($178)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc300;var $arrayidx301=((_ph_list2+$178*8)&4294967295);__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx301,18);var $179=$word_flags;var $and302=($179)&1;var $tobool303=((($and302))|0)!=0;if(!($tobool303)){__label__=111;break $land_lhs_true294$$if_end315$153;}
var $180=$word_addr;var $arrayidx305=(($180+1)&4294967295);var $181=HEAP8[($arrayidx305)];var $conv306=(tempInt=(($181)),(tempInt>=128?tempInt-256:tempInt));var $call307=__Z7IsAlphaj($conv306);var $tobool308=((($call307))|0)!=0;if(!($tobool308)){__label__=111;break $land_lhs_true294$$if_end315$153;}
var $182=HEAP32[((_n_ph_list2)>>2)];var $inc310=((($182)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc310;var $arrayidx311=((_ph_list2+$182*8)&4294967295);__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx311,10);var $183=HEAP32[((_n_ph_list2)>>2)];var $inc312=((($183)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc312;var $arrayidx313=((_ph_list2+$183*8)&4294967295);__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx313,18);;}}while(0);var $184=$switch_phonemes;var $cmp316=((($184))|0)>=0;if($cmp316){__label__=112;;}else{__label__=113;;}
if(__label__==112){var $185=HEAP32[((_n_ph_list2)>>2)];var $arrayidx318=((_ph_list2+$185*8)&4294967295);__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx318,21);var $186=$switch_phonemes;var $conv319=((($186))&255);var $187=HEAP32[((_n_ph_list2)>>2)];var $inc320=((($187)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc320;var $arrayidx321=((_ph_list2+$187*8)&4294967295);var $tone_ph=(($arrayidx321+3)&4294967295);HEAP8[($tone_ph)]=$conv319;;}
var $188=$word_flags;var $and323=($188)&128;var $tobool324=((($and323))|0)!=0;if($tobool324){__label__=114;;}else{__label__=116;;}
$land_lhs_true325$$if_end331$162:do{if(__label__==114){var $189=$p;var $190=HEAPU8[($189)];var $idxprom=((($190))&255);var $arrayidx326=((_phoneme_tab+$idxprom*4)&4294967295);var $191=HEAP32[(($arrayidx326)>>2)];var $type=(($191+11)&4294967295);var $192=HEAPU8[($type)];var $conv327=((($192))&255);var $cmp328=((($conv327))|0)==0;if(!($cmp328)){__label__=116;break $land_lhs_true325$$if_end331$162;}
var $193=$p;var $incdec_ptr330=(($193+1)&4294967295);$p=$incdec_ptr330;;}}while(0);var $194=$p;var $arrayidx332=(($194)&4294967295);var $195=HEAPU8[($arrayidx332)];var $conv333=((($195))&255);var $cmp334=((($conv333))|0)==0;if($cmp334){__label__=117;;}else{__label__=119;;}
$land_lhs_true335$$while_cond341_preheader$166:do{if(__label__==117){var $_b2=HEAPU8[(__ZL13embedded_flag_b)];var $196=($_b2)?2:0;var $tobool336=((($196))|0)!=0;if(!($tobool336)){__label__=119;break $land_lhs_true335$$while_cond341_preheader$166;}
var $197=$p;var $arrayidx338=(($197)&4294967295);HEAP8[($arrayidx338)]=23;var $198=$p;var $arrayidx339=(($198+1)&4294967295);HEAP8[($arrayidx339)]=0;;}}while(0);var $199=$p;var $incdec_ptr34224=(($199+1)&4294967295);$p=$incdec_ptr34224;var $200=HEAPU8[($199)];$ph_code=$200;var $conv34325=((($200))&255);var $cmp34426=((($conv34325))|0)!=0;var $201=HEAP32[((_n_ph_list2)>>2)];var $cmp34627=((($201))|0)<996;var $or_cond628=($cmp34426)&($cmp34627);if($or_cond628){__label__=120;;}else{__label__=157;;}
$while_body348$$while_end511$170:do{if(__label__==120){$while_body348$171:while(1){var $202=$ph_code;var $conv349=((($202))&255);var $cmp350=((($conv349))|0)==255;if($cmp350){__label__=121;;}else{__label__=122;;}
$while_cond341_backedge$$if_end352$173:do{if(__label__==122){var $206=$ph_code;var $idxprom353=((($206))&255);var $arrayidx354=((_phoneme_tab+$idxprom353*4)&4294967295);var $207=HEAP32[(($arrayidx354)>>2)];$ph=$207;var $208=$ph_code;var $conv355=((($208))&255);var $cmp356=((($conv355))|0)==21;if($cmp356){__label__=123;;}else{__label__=124;;}
if(__label__==123){var $209=$ph_code;var $210=HEAP32[((_n_ph_list2)>>2)];var $arrayidx358=((_ph_list2+$210*8)&4294967295);var $phcode=(($arrayidx358)&4294967295);HEAP8[($phcode)]=$209;var $211=HEAP32[((_n_ph_list2)>>2)];var $arrayidx359=((_ph_list2+$211*8)&4294967295);var $sourceix360=(($arrayidx359+6)&4294967295);HEAP16[(($sourceix360)>>1)]=0;var $_b1=HEAPU8[(__ZL13embedded_flag_b)];var $212=($_b1)?2:0;var $conv361=((($212))&65535);var $213=HEAP32[((_n_ph_list2)>>2)];var $arrayidx362=((_ph_list2+$213*8)&4294967295);var $synthflags=(($arrayidx362+4)&4294967295);HEAP16[(($synthflags)>>1)]=$conv361;var $214=$p;var $incdec_ptr363=(($214+1)&4294967295);$p=$incdec_ptr363;var $215=HEAP8[($214)];var $216=HEAP32[((_n_ph_list2)>>2)];var $inc364=((($216)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc364;var $arrayidx365=((_ph_list2+$216*8)&4294967295);var $tone_ph366=(($arrayidx365+3)&4294967295);HEAP8[($tone_ph366)]=$215;;}
else if(__label__==124){var $217=$ph;var $type368=(($217+11)&4294967295);var $218=HEAPU8[($type368)];var $conv369=((($218))&255);var $cmp370=((($conv369))|0)==1;if($cmp370){__label__=125;;}else{__label__=130;;}
if(__label__==125){var $219=$ph;var $program=(($219+8)&4294967295);var $220=HEAPU16[(($program)>>1)];var $conv372=((($220))&65535);var $cmp373=((($conv372))|0)==0;if($cmp373){__label__=126;;}else{__label__=127;;}
if(__label__==126){var $221=$ph;var $std_length=(($221+14)&4294967295);var $222=HEAPU8[($std_length)];var $conv375=((($222))&255);$next_stress=$conv375;;}
else if(__label__==127){var $223=$prev_vowel;var $cmp377=((($223))|0)>=0;var $224=$ph_code;if($cmp377){__label__=128;;}else{__label__=129;;}
if(__label__==128){var $225=$prev_vowel;var $arrayidx379=((_ph_list2+$225*8)&4294967295);var $tone_ph380=(($arrayidx379+3)&4294967295);HEAP8[($tone_ph380)]=$224;;}
else if(__label__==129){var $conv382=((($224))&255);$next_tone=$conv382;;}}}
else if(__label__==130){var $226=$ph_code;var $conv386=((($226))&255);var $cmp387=((($conv386))|0)==20;if($cmp387){__label__=131;;}else{__label__=132;;}
if(__label__==131){var $227=HEAP32[((_n_ph_list2)>>2)];var $sub389=((($227)-1)&4294967295);$prev_vowel=$sub389;var $228=$prev_vowel;var $arrayidx390=((_ph_list2+$228*8)&4294967295);var $synthflags391=(($arrayidx390+4)&4294967295);var $229=HEAPU16[(($synthflags391)>>1)];var $conv392=((($229))&65535);var $or393=($conv392)|4;var $conv394=((($or393))&65535);HEAP16[(($synthflags391)>>1)]=$conv394;var $230=$next_stress;var $conv395=((($230))&255);var $231=$prev_vowel;var $arrayidx396=((_ph_list2+$231*8)&4294967295);var $stresslevel=(($arrayidx396+1)&4294967295);HEAP8[($stresslevel)]=$conv395;;}
else if(__label__==132){var $232=$ph_code;var $conv398=((($232))&255);var $cmp399=((($conv398))|0)==12;if($cmp399){__label__=133;;}else{__label__=134;;}
if(__label__==133){var $233=HEAP32[((_n_ph_list2)>>2)];var $sub401=((($233)-1)&4294967295);var $arrayidx402=((_ph_list2+$sub401*8)&4294967295);var $synthflags403=(($arrayidx402+4)&4294967295);var $234=HEAPU16[(($synthflags403)>>1)];var $conv404=((($234))&65535);var $or405=($conv404)|8;var $conv406=((($or405))&65535);HEAP16[(($synthflags403)>>1)]=$conv406;;}
else if(__label__==134){var $235=$ph_code;var $conv408=((($235))&255);var $cmp409=((($conv408))|0)==15;if($cmp409){__label__=135;;}else{__label__=136;;}
if(__label__==135){var $236=$source_ix;var $add411=((($236)+1)&4294967295);$srcix=$add411;;}
else if(__label__==136){var $237=$ph_code;var $conv413=((($237))&255);var $cmp414=((($conv413))|0)==22;if($cmp414){__label__=137;;}else{__label__=139;;}
if(__label__==137){var $238=$tr_addr;var $langopts416=(($238)&4294967295);var $param417=(($langopts416+24)&4294967295);var $arrayidx418=(($param417+56)&4294967295);var $239=HEAP32[(($arrayidx418)>>2)];var $tobool419=((($239))|0)!=0;if(!($tobool419)){__label__=121;break $while_cond341_backedge$$if_end352$173;}
var $240=$flags;var $or421=($240)|524288;$flags=$or421;;}
else if(__label__==139){var $241=$ph_code;var $242=HEAP32[((_n_ph_list2)>>2)];var $arrayidx424=((_ph_list2+$242*8)&4294967295);var $phcode425=(($arrayidx424)&4294967295);HEAP8[($phcode425)]=$241;var $243=HEAP32[((_n_ph_list2)>>2)];var $arrayidx426=((_ph_list2+$243*8)&4294967295);var $tone_ph427=(($arrayidx426+3)&4294967295);HEAP8[($tone_ph427)]=0;var $_b=HEAPU8[(__ZL13embedded_flag_b)];var $244=($_b)?2:0;var $245=$found_dict_flag;var $or428=($244)|($245);var $conv429=((($or428))&65535);var $246=HEAP32[((_n_ph_list2)>>2)];var $arrayidx430=((_ph_list2+$246*8)&4294967295);var $synthflags431=(($arrayidx430+4)&4294967295);HEAP16[(($synthflags431)>>1)]=$conv429;HEAP8[(__ZL13embedded_flag_b)]=0;var $247=$srcix;var $conv432=((($247))&65535);var $248=HEAP32[((_n_ph_list2)>>2)];var $arrayidx433=((_ph_list2+$248*8)&4294967295);var $sourceix434=(($arrayidx433+6)&4294967295);HEAP16[(($sourceix434)>>1)]=$conv432;$srcix=0;var $249=$ph;var $type435=(($249+11)&4294967295);var $250=HEAPU8[($type435)];var $conv436=((($250))&255);var $cmp437=((($conv436))|0)==2;if($cmp437){__label__=140;;}else{__label__=149;;}
$if_then438$$if_else466$200:do{if(__label__==140){var $251=$next_stress;$stress=$251;$next_stress=1;var $252=$stress;var $cmp439=((($252))|0)>=4;if($cmp439){__label__=141;;}else{__label__=142;;}
if(__label__==141){HEAP8[(__ZL18any_stressed_words_b)]=1;;}
var $253=$prev_vowel;var $cmp442=((($253))|0)>=0;if($cmp442){__label__=143;;}else{__label__=145;;}
$land_lhs_true443$$if_end451$205:do{if(__label__==143){var $254=HEAP32[((_n_ph_list2)>>2)];var $sub444=((($254)-1)&4294967295);var $255=$prev_vowel;var $cmp445=((($sub444))|0)!=((($255))|0);if(!($cmp445)){__label__=145;break $land_lhs_true443$$if_end451$205;}
var $256=$stress;var $conv447=((($256))&255);var $257=HEAP32[((_n_ph_list2)>>2)];var $sub448=((($257)-1)&4294967295);var $arrayidx449=((_ph_list2+$sub448*8)&4294967295);var $stresslevel450=(($arrayidx449+1)&4294967295);HEAP8[($stresslevel450)]=$conv447;;}}while(0);var $258=HEAP32[((_n_ph_list2)>>2)];var $arrayidx452=((_ph_list2+$258*8)&4294967295);var $synthflags453=(($arrayidx452+4)&4294967295);var $259=HEAPU16[(($synthflags453)>>1)];var $conv454=((($259))&65535);var $or455=($conv454)|4;var $conv456=((($or455))&65535);HEAP16[(($synthflags453)>>1)]=$conv456;var $260=HEAP32[((_n_ph_list2)>>2)];$prev_vowel=$260;var $261=$stress;var $262=$max_stress;var $cmp457=((($261))|0)>((($262))|0);if($cmp457){__label__=146;;}else{__label__=147;;}
if(__label__==146){var $263=$stress;$max_stress=$263;var $264=HEAP32[((_n_ph_list2)>>2)];$max_stress_ix=$264;;}
var $265=$next_tone;var $cmp460=((($265))|0)!=0;if(!($cmp460)){__label__=156;break $if_then438$$if_else466$200;}
var $266=$next_tone;var $conv462=((($266))&255);var $267=HEAP32[((_n_ph_list2)>>2)];var $arrayidx463=((_ph_list2+$267*8)&4294967295);var $tone_ph464=(($arrayidx463+3)&4294967295);HEAP8[($tone_ph464)]=$conv462;$next_tone=0;;}
else if(__label__==149){var $268=$first_phoneme;var $tobool467=((($268))|0)!=0;if(!($tobool467)){__label__=156;break $if_then438$$if_else466$200;}
var $269=$tr_addr;var $langopts469=(($269)&4294967295);var $param470=(($langopts469+24)&4294967295);var $arrayidx471=(($param470+56)&4294967295);var $270=HEAP32[(($arrayidx471)>>2)];var $tobool472=((($270))|0)!=0;if(!($tobool472)){__label__=156;break $if_then438$$if_else466$200;}
var $271=$tr_addr;var $prev_dict_flags474=(($271+8320)&4294967295);var $272=HEAP32[(($prev_dict_flags474)>>2)];var $and475=($272)&524288;var $tobool476=((($and475))|0)!=0;if($tobool476){__label__=152;;}else{__label__=153;;}
$land_lhs_true477$$lor_lhs_false483$216:do{if(__label__==152){var $273=$tr_addr;var $langopts478=(($273)&4294967295);var $param479=(($langopts478+24)&4294967295);var $arrayidx480=(($param479+56)&4294967295);var $274=HEAP32[(($arrayidx480)>>2)];var $and481=($274)&1;var $tobool482=((($and481))|0)!=0;if($tobool482){__label__=155;break $land_lhs_true477$$lor_lhs_false483$216;}else{__label__=153;break $land_lhs_true477$$lor_lhs_false483$216;}}}while(0);if(__label__==153){var $275=$tr_addr;var $end_stressed_vowel484=(($275+8316)&4294967295);var $276=HEAP32[(($end_stressed_vowel484)>>2)];var $tobool485=((($276))|0)!=0;if(!($tobool485)){__label__=156;break $if_then438$$if_else466$200;}
var $277=$tr_addr;var $langopts487=(($277)&4294967295);var $param488=(($langopts487+24)&4294967295);var $arrayidx489=(($param488+56)&4294967295);var $278=HEAP32[(($arrayidx489)>>2)];var $and490=($278)&2;var $tobool491=((($and490))|0)!=0;if(!($tobool491)){__label__=156;break $if_then438$$if_else466$200;}}
var $279=HEAP32[((_n_ph_list2)>>2)];var $arrayidx493=((_ph_list2+$279*8)&4294967295);var $synthflags494=(($arrayidx493+4)&4294967295);var $280=HEAPU16[(($synthflags494)>>1)];var $conv495=((($280))&65535);var $or496=($conv495)|8;var $conv497=((($or496))&65535);HEAP16[(($synthflags494)>>1)]=$conv497;;}}while(0);var $281=$stress;var $conv501=((($281))&255);var $282=HEAP32[((_n_ph_list2)>>2)];var $arrayidx502=((_ph_list2+$282*8)&4294967295);var $stresslevel503=(($arrayidx502+1)&4294967295);HEAP8[($stresslevel503)]=$conv501;var $283=HEAP32[((_n_ph_list2)>>2)];var $inc504=((($283)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc504;$first_phoneme=0;;}}}}}}}}while(0);var $203=$p;var $incdec_ptr342=(($203+1)&4294967295);$p=$incdec_ptr342;var $204=HEAPU8[($203)];$ph_code=$204;var $conv343=((($204))&255);var $cmp344=((($conv343))|0)!=0;var $205=HEAP32[((_n_ph_list2)>>2)];var $cmp346=((($205))|0)<996;var $or_cond6=($cmp344)&($cmp346);if($or_cond6){__label__=120;continue $while_body348$171;}else{__label__=157;break $while_body348$$while_end511$170;}}}}while(0);var $284=$word_flags;var $and512=($284)&131072;var $tobool513=((($and512))|0)!=0;if($tobool513){__label__=158;;}else{__label__=159;;}
if(__label__==158){var $285=HEAP32[((_n_ph_list2)>>2)];var $inc515=((($285)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc515;var $arrayidx516=((_ph_list2+$285*8)&4294967295);__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx516,27);;}
var $286=$word_flags;var $and518=($286)&128;var $cmp519=((($and518))|0)==0;if($cmp519){__label__=160;;}else{__label__=161;;}
if(__label__==160){var $287=$source_ix;var $conv521=((($287))&65535);var $288=$plist2;var $sourceix522=(($288+6)&4294967295);HEAP16[(($sourceix522)>>1)]=$conv521;;}
var $289=$tr_addr;var $end_stressed_vowel524=(($289+8316)&4294967295);HEAP32[(($end_stressed_vowel524)>>2)]=0;var $290=$stress;var $cmp525=((($290))|0)>=4;if($cmp525){__label__=162;;}else{__label__=164;;}
$land_lhs_true526$$if_end537$231:do{if(__label__==162){var $291=HEAP32[((_n_ph_list2)>>2)];var $sub527=((($291)-1)&4294967295);var $arrayidx528=((_ph_list2+$sub527*8)&4294967295);var $phcode529=(($arrayidx528)&4294967295);var $292=HEAPU8[($phcode529)];var $idxprom530=((($292))&255);var $arrayidx531=((_phoneme_tab+$idxprom530*4)&4294967295);var $293=HEAP32[(($arrayidx531)>>2)];var $type532=(($293+11)&4294967295);var $294=HEAPU8[($type532)];var $conv533=((($294))&255);var $cmp534=((($conv533))|0)==2;if(!($cmp534)){__label__=164;break $land_lhs_true526$$if_end537$231;}
var $295=$tr_addr;var $end_stressed_vowel536=(($295+8316)&4294967295);HEAP32[(($end_stressed_vowel536)>>2)]=1;;}}while(0);var $296=$switch_phonemes;var $cmp538=((($296))|0)>=0;if($cmp538){__label__=165;;}else{__label__=166;;}
if(__label__==165){var $arraydecay540=(($old_dictionary_name)&4294967295);var $call541=_strcpy(((_dictionary_name)&4294967295),$arraydecay540);var $297=HEAP32[((_voice)>>2)];var $phoneme_tab_ix542=(($297+40)&4294967295);var $298=HEAP32[(($phoneme_tab_ix542)>>2)];__Z18SelectPhonemeTablei($298);var $299=HEAP32[((_n_ph_list2)>>2)];var $arrayidx543=((_ph_list2+$299*8)&4294967295);__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx543,21);var $300=HEAP32[((_voice)>>2)];var $phoneme_tab_ix544=(($300+40)&4294967295);var $301=HEAP32[(($phoneme_tab_ix544)>>2)];var $conv545=((($301))&255);var $302=HEAP32[((_n_ph_list2)>>2)];var $inc546=((($302)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc546;var $arrayidx547=((_ph_list2+$302*8)&4294967295);var $tone_ph548=(($arrayidx547+3)&4294967295);HEAP8[($tone_ph548)]=$conv545;;}
var $303=$pitch_raised;var $cmp550=((($303))|0)>0;if($cmp550){__label__=167;;}else{__label__=168;;}
if(__label__==167){var $304=$pitch_raised;var $shl552=((($304)*256)&4294967295);var $add553=((($shl552)+225)&4294967295);var $305=HEAP32[((__ZL11embedded_ix)>>2)];var $inc554=((($305)+1)&4294967295);HEAP32[((__ZL11embedded_ix)>>2)]=$inc554;var $arrayidx555=((_embedded_list+$305*4)&4294967295);HEAP32[(($arrayidx555)>>2)]=$add553;var $306=HEAP32[((_n_ph_list2)>>2)];var $arrayidx556=((_ph_list2+$306*8)&4294967295);__ZL9SetPlist2P13PHONEME_LIST2h($arrayidx556,10);var $307=HEAP32[((_n_ph_list2)>>2)];var $inc557=((($307)+1)&4294967295);HEAP32[((_n_ph_list2)>>2)]=$inc557;var $arrayidx558=((_ph_list2+$307*8)&4294967295);var $synthflags559=(($arrayidx558+4)&4294967295);HEAP16[(($synthflags559)>>1)]=2;;}
var $308=$flags;var $and561=($308)&4096;var $tobool562=((($and561))|0)!=0;if($tobool562){__label__=169;;}else{__label__=170;;}
if(__label__==169){var $309=$max_stress_ix;var $arrayidx564=((_ph_list2+$309*8)&4294967295);var $synthflags565=(($arrayidx564+4)&4294967295);var $310=HEAPU16[(($synthflags565)>>1)];var $conv566=((($310))&65535);var $or567=($conv566)|64;var $conv568=((($or567))&65535);HEAP16[(($synthflags565)>>1)]=$conv568;;}
var $311=$flags;var $312=$tr_addr;var $prev_dict_flags570=(($312+8320)&4294967295);HEAP32[(($prev_dict_flags570)>>2)]=$311;var $313=$flags;$retval=$313;;}}while(0);var $314=$retval;STACKTOP=__stackBase__;return $314;return null;}
function __Z8InitTexti($control){;var __label__;var $control_addr;$control_addr=$control;HEAP32[((_count_sentences)>>2)]=0;HEAP32[((_count_words)>>2)]=0;HEAP32[((_end_character_position)>>2)]=0;HEAP32[((_skip_sentences)>>2)]=0;HEAP8[(((_skip_marker)&4294967295))]=0;HEAP32[((_skip_words)>>2)]=0;HEAP32[((_skip_characters)>>2)]=0;HEAP32[((_skipping_text)>>2)]=0;HEAP32[((_new_sentence)>>2)]=1;HEAP32[((_option_sayas)>>2)]=0;HEAP32[((__ZL13option_sayas2)>>2)]=0;HEAP32[((__ZL15option_emphasis)>>2)]=0;HEAP8[(__ZL13word_emphasis_b)]=0;HEAP8[(__ZL13embedded_flag_b)]=0;__Z9InitText2v();var $0=$control_addr;var $and=($0)&8192;var $cmp=((($and))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){__Z12InitNamedatav();;};return;return;}
function __ZL14CountSyllablesPh($phonemes){;var __label__;var $phonemes_addr;var $count;var $phon;$phonemes_addr=$phonemes;$count=0;var $0=$phonemes_addr;var $incdec_ptr1=(($0+1)&4294967295);$phonemes_addr=$incdec_ptr1;var $1=HEAPU8[($0)];var $conv2=((($1))&255);$phon=$conv2;var $cmp3=((($conv2))|0)!=0;if($cmp3){__label__=1;;}else{__label__=4;;}
$while_body$$while_end$2:do{if(__label__==1){while(1){var $2=$phon;var $arrayidx=((_phoneme_tab+$2*4)&4294967295);var $3=HEAP32[(($arrayidx)>>2)];var $type=(($3+11)&4294967295);var $4=HEAPU8[($type)];var $conv1=((($4))&255);var $cmp2=((($conv1))|0)==2;if($cmp2){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $5=$count;var $inc=((($5)+1)&4294967295);$count=$inc;;}
var $6=$phonemes_addr;var $incdec_ptr=(($6+1)&4294967295);$phonemes_addr=$incdec_ptr;var $7=HEAPU8[($6)];var $conv=((($7))&255);$phon=$conv;var $cmp=((($conv))|0)!=0;if($cmp){__label__=1;continue;}else{__label__=4;break $while_body$$while_end$2;}}}}while(0);var $8=$count;;return $8;return null;}
function __ZL9SetPlist2P13PHONEME_LIST2h($p,$phcode){;var __label__;var $p_addr;var $phcode_addr;$p_addr=$p;$phcode_addr=$phcode;var $0=$phcode_addr;var $1=$p_addr;var $phcode1=(($1)&4294967295);HEAP8[($phcode1)]=$0;var $2=$p_addr;var $stresslevel=(($2+1)&4294967295);HEAP8[($stresslevel)]=0;var $3=$p_addr;var $tone_ph=(($3+3)&4294967295);HEAP8[($tone_ph)]=0;var $_b=HEAPU8[(__ZL13embedded_flag_b)];var $4=($_b)?2:0;var $conv=((($4))&65535);var $5=$p_addr;var $synthflags=(($5+4)&4294967295);HEAP16[(($synthflags)>>1)]=$conv;var $6=$p_addr;var $sourceix=(($6+6)&4294967295);HEAP16[(($sourceix)>>1)]=0;HEAP8[(__ZL13embedded_flag_b)]=0;;return;return;}
function __ZL14SubstituteCharP10TranslatorjjPi($tr,$c,$next_in,$insert){;var __label__;var __lastLabel__=null;var $retval;var $tr_addr;var $c_addr;var $next_in_addr;var $insert_addr;var $ix;var $word;var $new_c;var $c2;var $c_lower;var $upper_case;var $replace_chars;$tr_addr=$tr;$c_addr=$c;$next_in_addr=$next_in;$insert_addr=$insert;$upper_case=0;var $_b=HEAPU8[(__ZZL14SubstituteCharP10TranslatorjjPiE11ignore_next_b)];var $0=((($_b))&1);var $tobool=((($0))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP8[(__ZZL14SubstituteCharP10TranslatorjjPiE11ignore_next_b)]=0;$retval=8;;}
else if(__label__==2){var $1=$c_addr;var $cmp=((($1))|0)==0;if($cmp){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=0;;}
else if(__label__==4){var $2=$tr_addr;var $langopts=(($2)&4294967295);var $replace_chars3=(($langopts+264)&4294967295);var $3=HEAP32[(($replace_chars3)>>2)];$replace_chars=$3;var $cmp4=((($3))|0)==0;var $4=$c_addr;if($cmp4){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=$4;;}
else if(__label__==6){$c_lower=$4;var $call=_iswupper($4);var $tobool7=((($call))|0)!=0;if($tobool7){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $5=$c_addr;var $call9=_towlower($5);$c_lower=$call9;$upper_case=1;;}
$new_c=0;$ix=0;;$for_cond$14:while(1){var $6=$ix;var $7=$replace_chars;var $arrayidx=(($7+4*$6)&4294967295);var $8=HEAP32[(($arrayidx)>>2)];$word=$8;var $cmp11=((($8))|0)!=0;if(!($cmp11)){__label__=16;break $for_cond$14;}
var $9=$c_lower;var $10=$word;var $and=($10)&65535;var $cmp12=((($9))|0)==((($and))|0);if($cmp12){__label__=11;;}else{__label__=15;;}
if(__label__==11){var $11=$word;var $shr=($11)>>>16;var $cmp14=((($shr))|0)==0;if($cmp14){__label__=12;break $for_cond$14;}
var $15=$word;var $shr18=($15)>>>16;var $16=$next_in_addr;var $call19=_towlower($16);var $cmp20=((($shr18))|0)==((($call19))|0);if($cmp20){__label__=14;break $for_cond$14;}}
var $20=$ix;var $add26=((($20)+2)&4294967295);$ix=$add26;__label__=9;continue $for_cond$14;}
if(__label__==16){var $_pr=$new_c;__lastLabel__=16;;}
else if(__label__==12){var $12=$ix;var $add=((($12)+1)&4294967295);var $13=$replace_chars;var $arrayidx16=(($13+4*$add)&4294967295);var $14=HEAPU32[(($arrayidx16)>>2)];$new_c=$14;__lastLabel__=12;;}
else if(__label__==14){var $17=$ix;var $add22=((($17)+1)&4294967295);var $18=$replace_chars;var $arrayidx23=(($18+4*$add22)&4294967295);var $19=HEAPU32[(($arrayidx23)>>2)];$new_c=$19;HEAP8[(__ZZL14SubstituteCharP10TranslatorjjPiE11ignore_next_b)]=1;__lastLabel__=14;;}
var $21=__lastLabel__==16?$_pr:(__lastLabel__==14?$19:($14));var $cmp27=((($21))|0)==0;if($cmp27){__label__=18;;}else{__label__=19;;}
if(__label__==18){var $22=$c_addr;$retval=$22;;}
else if(__label__==19){var $23=$new_c;var $and30=($23)&-2097152;var $tobool31=((($and30))|0)!=0;if($tobool31){__label__=20;;}else{__label__=24;;}
if(__label__==20){var $24=$new_c;var $shr33=($24)>>>16;$c2=$shr33;var $25=$upper_case;var $tobool34=((($25))|0)!=0;if($tobool34){__label__=21;;}else{__label__=23;;}
$land_lhs_true$$if_end39$31:do{if(__label__==21){var $26=$next_in_addr;var $call35=_iswupper($26);var $tobool36=((($call35))|0)!=0;if(!($tobool36)){__label__=23;break $land_lhs_true$$if_end39$31;}
var $27=$c2;var $call38=_towupper($27);$c2=$call38;;}}while(0);var $28=$c2;var $29=$insert_addr;HEAP32[(($29)>>2)]=$28;var $30=$new_c;var $and40=($30)&65535;$new_c=$and40;;}
var $31=$upper_case;var $tobool42=((($31))|0)!=0;if($tobool42){__label__=25;;}else{__label__=26;;}
if(__label__==25){var $32=$new_c;var $call44=_towupper($32);$new_c=$call44;;}
var $33=$new_c;$retval=$33;;}}}}
var $34=$retval;;return $34;return null;}
function _init_MBR($voice_path){var __stackBase__=STACKTOP;STACKTOP+=48;_memset(__stackBase__,0,48);var __label__;var $retval;var $voice_path_addr;var $error;var $result;var $wavhdr=__stackBase__;$voice_path_addr=$voice_path;var $0=$voice_path_addr;var $call=__ZL12start_mbrolaPKc($0);$error=$call;var $1=$error;var $tobool=((($1))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){$retval=-1;;}
else if(__label__==2){var $call1=__ZL14send_to_mbrolaPKc(((__str580)&4294967295));$result=$call1;var $2=$result;var $cmp=((($2))|0)!=2;if($cmp){__label__=3;;}else{__label__=4;;}
if(__label__==3){__ZL11stop_mbrolav();$retval=-1;;}
else if(__label__==4){var $arraydecay=(($wavhdr)&4294967295);var $call4=__ZL19receive_from_mbrolaPvj($arraydecay,45);$result=$call4;var $3=$result;var $cmp5=((($3))|0)!=44;if($cmp5){__label__=5;;}else{__label__=8;;}
if(__label__==5){var $4=$result;var $cmp7=((($4))|0)>=0;if($cmp7){__label__=6;;}else{__label__=7;;}
if(__label__==6){__ZL3errPKcz(((__str1581)&4294967295),allocate(1,"i32",ALLOC_STACK));;}
__ZL11stop_mbrolav();$retval=-1;;}
else if(__label__==8){var $arraydecay11=(($wavhdr)&4294967295);var $call12=_memcmp($arraydecay11,((__str2582)&4294967295),4);var $cmp13=((($call12))|0)!=0;if($cmp13){__label__=10;;}else{__label__=9;;}
$if_then17$$lor_lhs_false$14:do{if(__label__==9){var $arraydecay14=(($wavhdr)&4294967295);var $add_ptr=(($arraydecay14+8)&4294967295);var $call15=_memcmp($add_ptr,((__str3583)&4294967295),8);var $cmp16=((($call15))|0)!=0;if($cmp16){__label__=10;break $if_then17$$lor_lhs_false$14;}
var $arrayidx=(($wavhdr+24)&4294967295);var $5=HEAPU8[($arrayidx)];var $conv=((($5))&255);var $arrayidx19=(($wavhdr+25)&4294967295);var $6=HEAPU8[($arrayidx19)];var $conv20=((($6))&255);var $shl=((($conv20)*256)&4294967295);var $arrayidx21=(($wavhdr+26)&4294967295);var $7=HEAPU8[($arrayidx21)];var $conv22=((($7))&255);var $shl23=((($conv22)*65536)&4294967295);var $arrayidx25=(($wavhdr+27)&4294967295);var $8=HEAPU8[($arrayidx25)];var $conv26=((($8))&255);var $shl27=((($conv26)*16777216)&4294967295);var $add=((($shl)+($conv))&4294967295);var $add24=((($add)+($shl23))&4294967295);var $add28=((($add24)+($shl27))&4294967295);HEAP32[((__ZL14mbr_samplerate)>>2)]=$add28;var $9=HEAP32[((__ZL14mbr_voice_path)>>2)];var $10=$voice_path_addr;var $cmp29=((($9))|0)!=((($10))|0);if($cmp29){__label__=12;;}else{__label__=13;;}
if(__label__==12){var $11=HEAP32[((__ZL14mbr_voice_path)>>2)];;var $12=$voice_path_addr;var $call31=_strdup($12);HEAP32[((__ZL14mbr_voice_path)>>2)]=$call31;;}
$retval=0;__label__=14;break $if_then$$if_end$2;}}while(0);__ZL3errPKcz(((__str4584)&4294967295),allocate(1,"i32",ALLOC_STACK));__ZL11stop_mbrolav();$retval=-1;;}}}}while(0);var $13=$retval;STACKTOP=__stackBase__;return $13;return null;}
function __ZL12start_mbrolaPKc($voice_path){var __stackBase__=STACKTOP;STACKTOP+=44;_memset(__stackBase__,0,44);var __label__;var $retval;var $voice_path_addr;var $error;var $p_stdin=__stackBase__;var $p_stdout=__stackBase__+8;var $p_stderr=__stackBase__+16;var $charbuf=__stackBase__+24;var $i;$voice_path_addr=$voice_path;var $0=HEAP32[((__ZL9mbr_state)>>2)];var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){__ZL3errPKcz(((__str22602)&4294967295),allocate(1,"i32",ALLOC_STACK));$retval=-1;;}
else if(__label__==2){var $arraydecay=(($p_stdin)&4294967295);var $arraydecay1=(($p_stdout)&4294967295);var $arraydecay2=(($p_stderr)&4294967295);var $call=__ZL12create_pipesPiS_S_($arraydecay,$arraydecay1,$arraydecay2);$error=$call;var $1=$error;var $tobool=((($1))|0)!=0;if($tobool){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=-1;;}
else if(__label__==4){var $call5=_fork();HEAP32[((__ZL7mbr_pid)>>2)]=$call5;var $2=HEAP32[((__ZL7mbr_pid)>>2)];var $cmp6=((($2))|0)==-1;if($cmp6){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $call8=___errno();var $3=HEAP32[(($call8)>>2)];$error=$3;var $arraydecay9=(($p_stdin)&4294967295);var $arraydecay10=(($p_stdout)&4294967295);var $arraydecay11=(($p_stderr)&4294967295);__ZL11close_pipesPiS_S_($arraydecay9,$arraydecay10,$arraydecay11);var $4=$error;var $call12=_strerror($4);__ZL3errPKcz(((__str23603)&4294967295),allocate([$call12,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=-1;;}
else if(__label__==6){var $5=HEAP32[((__ZL7mbr_pid)>>2)];var $cmp14=((($5))|0)==0;if($cmp14){__label__=7;;}else{__label__=14;;}
if(__label__==7){var $arrayidx=(($p_stdin)&4294967295);var $6=HEAP32[(($arrayidx)>>2)];var $call16=_dup2($6,0);var $cmp17=((($call16))|0)==-1;if($cmp17){__label__=10;;}else{__label__=8;;}
$if_then25$$lor_lhs_false$13:do{if(__label__==8){var $arrayidx18=(($p_stdout+4)&4294967295);var $7=HEAP32[(($arrayidx18)>>2)];var $call19=_dup2($7,1);var $cmp20=((($call19))|0)==-1;if($cmp20){__label__=10;break $if_then25$$lor_lhs_false$13;}
var $arrayidx22=(($p_stderr+4)&4294967295);var $8=HEAP32[(($arrayidx22)>>2)];var $call23=_dup2($8,2);var $cmp24=((($call23))|0)==-1;if($cmp24){__label__=10;break $if_then25$$lor_lhs_false$13;}else{__label__=11;break $if_then25$$lor_lhs_false$13;}}}while(0);if(__label__==10){var $call26=___errno();var $9=HEAP32[(($call26)>>2)];var $call27=_strerror($9);var $call28=_snprintf(((__ZL12mbr_errorbuf)&4294967295),160,((__str24604)&4294967295),allocate([$call27,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $arrayidx29=(($p_stderr+4)&4294967295);var $10=HEAP32[(($arrayidx29)>>2)];var $call30=_strlen(((__ZL12mbr_errorbuf)&4294967295));var $call31=_write($10,((__ZL12mbr_errorbuf)&4294967295),$call30);__exit(1);;}
var $arrayidx33=(($p_stderr+4)&4294967295);var $11=HEAP32[(($arrayidx33)>>2)];$i=$11;var $cmp341=((($11))|0)>2;if($cmp341){__label__=12;;}else{__label__=13;;}
$for_body$$for_end$19:do{if(__label__==12){while(1){var $12=$i;var $call35=_close($12);var $13=$i;var $dec=((($13)-1)&4294967295);$i=$dec;var $cmp34=((($dec))|0)>2;if($cmp34){__label__=12;continue;}else{__label__=13;break $for_body$$for_end$19;}}}}while(0);var $call36=_signal(1,1);var $call37=_signal(2,1);var $call38=_signal(3,1);var $call39=_signal(15,1);var $arraydecay40=(($charbuf)&4294967295);var $14=HEAPF32[((__ZL10mbr_volume)>>2)];var $conv=($14);var $call41=_snprintf($arraydecay40,20,((__str25605)&4294967295),allocate([$conv,0,0,0,0,0,0,0],["double",0,0,0,0,0,0,0],ALLOC_STACK));var $arraydecay42=(($charbuf)&4294967295);var $15=$voice_path_addr;var $call43=_execlp(((__str33683)&4294967295),((__str33683)&4294967295),allocate([((__str27607)&4294967295),0,0,0,((__str28608)&4294967295),0,0,0,$arraydecay42,0,0,0,$15,0,0,0,((__str56708)&4294967295),0,0,0,((__str30610)&4294967295),0,0,0,0,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $call44=___errno();var $16=HEAP32[(($call44)>>2)];var $call45=_strerror($16);var $call46=_snprintf(((__ZL12mbr_errorbuf)&4294967295),160,((__str31611)&4294967295),allocate([$call45,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $call47=_strlen(((__ZL12mbr_errorbuf)&4294967295));var $call48=_write(2,((__ZL12mbr_errorbuf)&4294967295),$call47);__exit(1);;}
var $arraydecay50=(($charbuf)&4294967295);var $17=HEAP32[((__ZL7mbr_pid)>>2)];var $call51=_snprintf($arraydecay50,20,((__str32612)&4294967295),allocate([$17,0,0,0],["i32",0,0,0],ALLOC_STACK));var $arraydecay52=(($charbuf)&4294967295);var $call53=_open($arraydecay52,0,allocate(1,"i32",ALLOC_STACK));HEAP32[((__ZL13mbr_proc_stat)>>2)]=$call53;var $cmp54=((($call53))|0)==-1;if($cmp54){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $call56=___errno();var $18=HEAP32[(($call56)>>2)];$error=$18;var $arraydecay57=(($p_stdin)&4294967295);var $arraydecay58=(($p_stdout)&4294967295);var $arraydecay59=(($p_stderr)&4294967295);__ZL11close_pipesPiS_S_($arraydecay57,$arraydecay58,$arraydecay59);var $19=HEAP32[((__ZL7mbr_pid)>>2)];var $call60=_waitpid($19,0,0);HEAP32[((__ZL7mbr_pid)>>2)]=0;var $20=$error;var $call61=_strerror($20);__ZL3errPKcz(((__str33613)&4294967295),allocate([$call61,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=-1;;}
else if(__label__==16){var $call63=_signal(13,1);var $arrayidx64=(($p_stdin+4)&4294967295);var $21=HEAP32[(($arrayidx64)>>2)];var $call65=_fcntl($21,4,allocate([16384,0,0,0],["i32",0,0,0],ALLOC_STACK));var $cmp66=((($call65))|0)==-1;if($cmp66){__label__=19;;}else{__label__=17;;}
$if_then75$$lor_lhs_false67$27:do{if(__label__==17){var $arrayidx68=(($p_stdout)&4294967295);var $22=HEAP32[(($arrayidx68)>>2)];var $call69=_fcntl($22,4,allocate([16384,0,0,0],["i32",0,0,0],ALLOC_STACK));var $cmp70=((($call69))|0)==-1;if($cmp70){__label__=19;break $if_then75$$lor_lhs_false67$27;}
var $arrayidx72=(($p_stderr)&4294967295);var $23=HEAP32[(($arrayidx72)>>2)];var $call73=_fcntl($23,4,allocate([16384,0,0,0],["i32",0,0,0],ALLOC_STACK));var $cmp74=((($call73))|0)==-1;if($cmp74){__label__=19;break $if_then75$$lor_lhs_false67$27;}
var $arrayidx83=(($p_stdin+4)&4294967295);var $27=HEAP32[(($arrayidx83)>>2)];HEAP32[((__ZL10mbr_cmd_fd)>>2)]=$27;var $arrayidx84=(($p_stdout)&4294967295);var $28=HEAP32[(($arrayidx84)>>2)];HEAP32[((__ZL12mbr_audio_fd)>>2)]=$28;var $arrayidx85=(($p_stderr)&4294967295);var $29=HEAP32[(($arrayidx85)>>2)];HEAP32[((__ZL12mbr_error_fd)>>2)]=$29;var $arrayidx86=(($p_stdin)&4294967295);var $30=HEAP32[(($arrayidx86)>>2)];var $call87=_close($30);var $arrayidx88=(($p_stdout+4)&4294967295);var $31=HEAP32[(($arrayidx88)>>2)];var $call89=_close($31);var $arrayidx90=(($p_stderr+4)&4294967295);var $32=HEAP32[(($arrayidx90)>>2)];var $call91=_close($32);HEAP32[((__ZL9mbr_state)>>2)]=1;$retval=0;__label__=21;break $if_then$$if_end$2;}}while(0);var $call76=___errno();var $24=HEAP32[(($call76)>>2)];$error=$24;var $arraydecay77=(($p_stdin)&4294967295);var $arraydecay78=(($p_stdout)&4294967295);var $arraydecay79=(($p_stderr)&4294967295);__ZL11close_pipesPiS_S_($arraydecay77,$arraydecay78,$arraydecay79);var $25=HEAP32[((__ZL7mbr_pid)>>2)];var $call80=_waitpid($25,0,0);HEAP32[((__ZL7mbr_pid)>>2)]=0;var $26=$error;var $call81=_strerror($26);__ZL3errPKcz(((__str34614)&4294967295),allocate([$call81,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=-1;;}}}}}while(0);var $33=$retval;STACKTOP=__stackBase__;return $33;return null;}
function __ZL14send_to_mbrolaPKc($cmd){;var __label__;var __lastLabel__=null;var $retval;var $cmd_addr;var $result;var $len;var $error;var $data;$cmd_addr=$cmd;var $0=HEAP32[((__ZL7mbr_pid)>>2)];var $tobool=((($0))|0)!=0;if($tobool){__label__=2;;}else{__label__=1;;}
$if_end$$if_then$2:do{if(__label__==2){var $1=$cmd_addr;var $call=_strlen($1);$len=$call;var $2=HEAP32[((__ZL10mbr_cmd_fd)>>2)];var $3=$cmd_addr;var $4=$len;var $call1=_write($2,$3,$4);$result=$call1;var $5=$result;var $cmp=((($5))|0)==-1;if($cmp){__label__=3;;}else{__label__=10;;}
if(__label__==3){var $call3=___errno();var $6=HEAP32[(($call3)>>2)];$error=$6;var $7=$error;var $cmp4=((($7))|0)==32;if($cmp4){__lastLabel__=3;__label__=4;;}else{__lastLabel__=3;__label__=7;;}
if(__label__==4){var $call5=__ZL17mbrola_has_errorsv();var $tobool6=((($call5))|0)!=0;if($tobool6){__label__=5;;}else{__label__=6;;}
if(__label__==5){$retval=-1;__label__=17;break $if_end$$if_then$2;}
else if(__label__==6){var $_pr=$error;__lastLabel__=6;;}}
var $8=__lastLabel__==6?$_pr:($7);var $cmp8=((($8))|0)==11;if($cmp8){__label__=8;;}else{__label__=9;;}
if(__label__==8){$result=0;;}
else if(__label__==9){var $9=$error;var $call11=_strerror($9);__ZL3errPKcz(((__str20600)&4294967295),allocate([$call11,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=-1;__label__=17;break $if_end$$if_then$2;}}
var $10=$result;var $11=$len;var $cmp15=((($10))|0)!=((($11))|0);if($cmp15){__label__=11;;}else{__label__=16;;}
$if_then16$$if_end28$16:do{if(__label__==11){var $12=$len;var $13=$result;var $_neg=(((-($13)))&4294967295);var $add=((($12)+16)&4294967295);var $sub=((($add)+($_neg))&4294967295);var $call17=_malloc($sub);var $14=$call17;$data=$14;var $15=$data;var $tobool18=((($15))|0)!=0;if(!($tobool18)){__label__=16;break $if_then16$$if_end28$16;}
var $16=$data;var $next=(($16)&4294967295);HEAP32[(($next)>>2)]=0;var $17=$data;var $done=(($17+4)&4294967295);HEAP32[(($done)>>2)]=0;var $18=$len;var $19=$result;var $sub20=((($18)-($19))&4294967295);var $20=$data;var $size=(($20+8)&4294967295);HEAP32[(($size)>>2)]=$sub20;var $21=$data;var $buffer=(($21+12)&4294967295);var $arraydecay=(($buffer)&4294967295);var $22=$cmd_addr;var $23=$result;var $add_ptr=(($22+$23)&4294967295);var $24=$len;var $25=$result;var $sub21=((($24)-($25))&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$add_ptr;$dest$=$arraydecay;$stop$=$src$+$sub21;if(($dest$%4)==($src$%4)&&$sub21>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $26=$len;$result=$26;var $27=HEAP32[((__ZL21mbr_pending_data_head)>>2)];var $tobool22=((($27))|0)!=0;var $28=$data;if($tobool22){__label__=14;;}else{__label__=13;;}
if(__label__==14){var $29=HEAP32[((__ZL21mbr_pending_data_tail)>>2)];var $next25=(($29)&4294967295);HEAP32[(($next25)>>2)]=$28;;}
else if(__label__==13){HEAP32[((__ZL21mbr_pending_data_head)>>2)]=$28;;}
var $30=$data;HEAP32[((__ZL21mbr_pending_data_tail)>>2)]=$30;;}}while(0);var $31=$result;$retval=$31;;}
else if(__label__==1){$retval=-1;;}}while(0);var $32=$retval;;return $32;return null;}
function __ZL11stop_mbrolav(){;var __label__;var $0=HEAP32[((__ZL9mbr_state)>>2)];var $cmp=((($0))|0)==0;if($cmp){__label__=4;;}else{__label__=1;;}
if(__label__==1){var $1=HEAP32[((__ZL13mbr_proc_stat)>>2)];var $call=_close($1);var $2=HEAP32[((__ZL10mbr_cmd_fd)>>2)];var $call1=_close($2);var $3=HEAP32[((__ZL12mbr_audio_fd)>>2)];var $call2=_close($3);var $4=HEAP32[((__ZL12mbr_error_fd)>>2)];var $call3=_close($4);var $5=HEAP32[((__ZL7mbr_pid)>>2)];var $tobool=((($5))|0)!=0;if($tobool){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $6=HEAP32[((__ZL7mbr_pid)>>2)];var $call5=_kill($6,15);var $7=HEAP32[((__ZL7mbr_pid)>>2)];var $call6=_waitpid($7,0,0);HEAP32[((__ZL7mbr_pid)>>2)]=0;;}
HEAP32[((__ZL9mbr_state)>>2)]=0;;};return;return;}
function __ZL19receive_from_mbrolaPvj($buffer,$bufsize){var __stackBase__=STACKTOP;STACKTOP+=24;_memset(__stackBase__,0,24);var __label__;var $retval;var $buffer_addr;var $bufsize_addr;var $result;var $wait;var $cursize;var $pollfd=__stackBase__;var $nfds;var $idle;var $head;var $data;var $left;var $error;var $curpos;var $space;var $obtained;$buffer_addr=$buffer;$bufsize_addr=$bufsize;$wait=1;$cursize=0;var $0=HEAP32[((__ZL7mbr_pid)>>2)];var $tobool=((($0))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
$do_body_preheader$$if_then$2:do{if(__label__==1){var $arrayidx=(($pollfd)&4294967295);var $fd=(($arrayidx)&4294967295);var $arrayidx1=(($pollfd)&4294967295);var $events=(($arrayidx1+4)&4294967295);var $arrayidx2=(($pollfd+8)&4294967295);var $fd3=(($arrayidx2)&4294967295);var $arrayidx4=(($pollfd+8)&4294967295);var $events5=(($arrayidx4+4)&4294967295);var $arrayidx9=(($pollfd+16)&4294967295);var $fd10=(($arrayidx9)&4294967295);var $arrayidx11=(($pollfd+16)&4294967295);var $events12=(($arrayidx11+4)&4294967295);var $arraydecay=(($pollfd)&4294967295);var $arrayidx29=(($pollfd+8)&4294967295);var $revents=(($arrayidx29+6)&4294967295);var $arrayidx37=(($pollfd+16)&4294967295);var $revents38=(($arrayidx37+6)&4294967295);var $arrayidx66=(($pollfd)&4294967295);var $revents67=(($arrayidx66+6)&4294967295);;$do_body$4:while(1){$nfds=0;var $1=HEAP32[((__ZL12mbr_audio_fd)>>2)];HEAP32[(($fd)>>2)]=$1;HEAP16[(($events)>>1)]=1;var $2=$nfds;var $inc=((($2)+1)&4294967295);$nfds=$inc;var $3=HEAP32[((__ZL12mbr_error_fd)>>2)];HEAP32[(($fd3)>>2)]=$3;HEAP16[(($events5)>>1)]=1;var $4=$nfds;var $inc6=((($4)+1)&4294967295);$nfds=$inc6;var $5=HEAP32[((__ZL21mbr_pending_data_head)>>2)];var $tobool7=((($5))|0)!=0;if($tobool7){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $6=HEAP32[((__ZL10mbr_cmd_fd)>>2)];HEAP32[(($fd10)>>2)]=$6;HEAP16[(($events12)>>1)]=2;var $7=$nfds;var $inc13=((($7)+1)&4294967295);$nfds=$inc13;;}
var $call=__ZL14mbrola_is_idlev();$idle=$call;var $8=$nfds;var $9=$idle;var $tobool15=((($9))|0)!=0;var $10=$wait;var $cond=($tobool15)?0:($10);var $call16=_poll($arraydecay,$8,$cond);$result=$call16;var $cmp=((($call16))|0)==-1;if($cmp){__label__=6;break $do_body$4;}
var $12=$result;var $cmp21=((($12))|0)==0;if($cmp21){__label__=8;;}else{__label__=13;;}
$if_then22$$if_end28$10:do{if(__label__==8){var $13=$idle;var $tobool23=((($13))|0)!=0;if($tobool23){__label__=9;break $do_body$4;}
var $14=$wait;var $cmp25=((($14))|0)>=3750;if($cmp25){__label__=11;break $do_body$4;}
var $15=$wait;var $mul=((($15)*4)&4294967295);$wait=$mul;;}
else if(__label__==13){$wait=1;var $16=HEAP16[(($revents)>>1)];var $tobool30=(tempInt=(($16)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if($tobool30){__label__=14;;}else{__label__=16;;}
if(__label__==14){var $call31=__ZL17mbrola_has_errorsv();var $tobool32=((($call31))|0)!=0;if($tobool32){__label__=15;break $do_body$4;}}
var $17=HEAP32[((__ZL21mbr_pending_data_head)>>2)];var $tobool35=((($17))|0)!=0;if($tobool35){__label__=17;;}else{__label__=27;;}
$land_lhs_true36$$if_end65$18:do{if(__label__==17){var $18=HEAP16[(($revents38)>>1)];var $tobool39=(tempInt=(($18)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if(!($tobool39)){__label__=27;break $land_lhs_true36$$if_end65$18;}
var $19=HEAP32[((__ZL21mbr_pending_data_head)>>2)];$head=$19;var $20=$head;var $buffer41=(($20+12)&4294967295);var $arraydecay42=(($buffer41)&4294967295);var $21=$head;var $done=(($21+4)&4294967295);var $22=HEAP32[(($done)>>2)];var $add_ptr=(($arraydecay42+$22)&4294967295);$data=$add_ptr;var $23=$head;var $size=(($23+8)&4294967295);var $24=HEAP32[(($size)>>2)];var $25=$head;var $done43=(($25+4)&4294967295);var $26=HEAP32[(($done43)>>2)];var $sub=((($24)-($26))&4294967295);$left=$sub;var $27=HEAP32[((__ZL10mbr_cmd_fd)>>2)];var $28=$data;var $29=$left;var $call44=_write($27,$28,$29);$result=$call44;var $30=$result;var $cmp45=((($30))|0)==-1;if($cmp45){__label__=19;break $do_body$4;}
var $34=$result;var $35=$left;var $cmp56=((($34))|0)!=((($35))|0);if($cmp56){__label__=24;;}else{__label__=25;;}
if(__label__==24){var $36=$result;var $37=$head;var $done58=(($37+4)&4294967295);var $38=HEAP32[(($done58)>>2)];var $add=((($38)+($36))&4294967295);HEAP32[(($done58)>>2)]=$add;;}
else if(__label__==25){var $39=$head;var $next=(($39)&4294967295);var $40=HEAP32[(($next)>>2)];HEAP32[((__ZL21mbr_pending_data_head)>>2)]=$40;var $41=$head;var $42=$41;;var $43=HEAP32[((__ZL21mbr_pending_data_head)>>2)];var $tobool60=((($43))|0)!=0;if($tobool60){__label__=31;break $if_then22$$if_end28$10;}
HEAP32[((__ZL21mbr_pending_data_tail)>>2)]=0;;}}}while(0);var $44=HEAP16[(($revents67)>>1)];var $tobool68=(tempInt=(($44)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if(!($tobool68)){__label__=31;break $if_then22$$if_end28$10;}
var $45=$buffer_addr;var $46=$cursize;var $add_ptr70=(($45+$46)&4294967295);$curpos=$add_ptr70;var $47=$bufsize_addr;var $48=$cursize;var $sub71=((($47)-($48))&4294967295);$space=$sub71;var $49=HEAP32[((__ZL12mbr_audio_fd)>>2)];var $50=$curpos;var $51=$space;var $call72=_read($49,$50,$51);$obtained=$call72;var $52=$obtained;var $cmp73=((($52))|0)==-1;if($cmp73){__label__=29;break $do_body$4;}
var $54=$obtained;var $55=$cursize;var $add78=((($55)+($54))&4294967295);$cursize=$add78;HEAP32[((__ZL9mbr_state)>>2)]=3;;}}while(0);var $56=$cursize;var $57=$bufsize_addr;var $cmp80=((($56))>>>0)<((($57))>>>0);if($cmp80){__label__=3;continue $do_body$4;}else{__label__=32;break $do_body$4;}}
if(__label__==6){var $call18=___errno();var $11=HEAP32[(($call18)>>2)];var $call19=_strerror($11);__ZL3errPKcz(((__str18598)&4294967295),allocate([$call19,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=-1;__label__=33;break $do_body_preheader$$if_then$2;}
else if(__label__==9){HEAP32[((__ZL9mbr_state)>>2)]=1;;}
else if(__label__==11){HEAP32[((__ZL9mbr_state)>>2)]=4;__ZL3errPKcz(((__str19599)&4294967295),allocate(1,"i32",ALLOC_STACK));;}
else if(__label__==15){$retval=-1;__label__=33;break $do_body_preheader$$if_then$2;}
else if(__label__==19){var $call47=___errno();var $31=HEAP32[(($call47)>>2)];$error=$31;var $32=$error;var $cmp48=((($32))|0)==32;if($cmp48){__label__=20;;}else{__label__=22;;}
$land_lhs_true49$$if_end53$36:do{if(__label__==20){var $call50=__ZL17mbrola_has_errorsv();var $tobool51=((($call50))|0)!=0;if(!($tobool51)){__label__=22;break $land_lhs_true49$$if_end53$36;}
$retval=-1;__label__=33;break $do_body_preheader$$if_then$2;}}while(0);var $33=$error;var $call54=_strerror($33);__ZL3errPKcz(((__str20600)&4294967295),allocate([$call54,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=-1;__label__=33;break $do_body_preheader$$if_then$2;}
else if(__label__==29){var $call75=___errno();var $53=HEAP32[(($call75)>>2)];var $call76=_strerror($53);__ZL3errPKcz(((__str21601)&4294967295),allocate([$call76,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=-1;__label__=33;break $do_body_preheader$$if_then$2;}
var $58=$cursize;$retval=$58;;}
else if(__label__==2){$retval=-1;;}}while(0);var $59=$retval;STACKTOP=__stackBase__;return $59;return null;}
function __ZL3errPKcz($errmsg){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $errmsg_addr;var $params=__stackBase__;$errmsg_addr=$errmsg;var $params1=$params;HEAP32[(($params1)>>2)]=arguments[__ZL3errPKcz.length];;var $0=$errmsg_addr;var $1=HEAP32[(($params)>>2)];var $call=_vsnprintf(((__ZL12mbr_errorbuf)&4294967295),160,$0,$1);var $params2=$params;;__ZL3logPKcz(((__str16596)&4294967295),allocate([((__ZL12mbr_errorbuf)&4294967295),0,0,0],["i8*",0,0,0],ALLOC_STACK));STACKTOP=__stackBase__;return;return;}
function _close_MBR(){;var __label__;__ZL11stop_mbrolav();__ZL17free_pending_datav();var $0=HEAP32[((__ZL14mbr_voice_path)>>2)];;HEAP32[((__ZL14mbr_voice_path)>>2)]=0;HEAPF32[((__ZL10mbr_volume)>>2)]=1;;return;return;}
function __ZL17free_pending_datav(){;var __label__;var $p;var $head;var $0=HEAP32[((__ZL21mbr_pending_data_head)>>2)];$head=$0;var $tobool1=((($0))|0)!=0;if($tobool1){__label__=1;;}else{__label__=2;;}
$while_body$$while_end$2:do{if(__label__==1){while(1){var $1=$head;$p=$1;var $2=$head;var $next=(($2)&4294967295);var $3=HEAP32[(($next)>>2)];$head=$3;var $4=$p;var $5=$4;;var $_pr=$head;var $tobool=((($_pr))|0)!=0;if($tobool){__label__=1;continue;}else{__label__=2;break $while_body$$while_end$2;}}}}while(0);HEAP32[((__ZL21mbr_pending_data_head)>>2)]=0;HEAP32[((__ZL21mbr_pending_data_tail)>>2)]=0;;return;return;}
function _reset_MBR(){var __stackBase__=STACKTOP;STACKTOP+=4096;_memset(__stackBase__,0,4096);var __label__;var $retval;var $result;var $success;var $dummybuf=__stackBase__;$success=1;var $0=HEAP32[((__ZL9mbr_state)>>2)];var $cmp=((($0))|0)==1;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $1=HEAP32[((__ZL7mbr_pid)>>2)];var $tobool=((($1))|0)!=0;if($tobool){__label__=4;;}else{__label__=3;;}
if(__label__==4){var $2=HEAP32[((__ZL7mbr_pid)>>2)];var $call=_kill($2,30);var $cmp3=((($call))|0)==-1;if($cmp3){__label__=5;;}else{__label__=6;;}
if(__label__==5){$success=0;;}
__ZL17free_pending_datav();var $3=HEAP32[((__ZL10mbr_cmd_fd)>>2)];var $call6=_write($3,((__str5585)&4294967295),3);$result=$call6;var $cmp7=((($call6))|0)!=3;if($cmp7){__label__=7;;}else{__label__=8;;}
if(__label__==7){$success=0;;}
var $arraydecay=(($dummybuf)&4294967295);;$do_body$13:while(1){var $4=HEAP32[((__ZL12mbr_audio_fd)>>2)];var $call10=_read($4,$arraydecay,4096);$result=$call10;var $cmp11=((($call10))|0)>0;if($cmp11){__label__=9;continue $do_body$13;}else{__label__=10;break $do_body$13;}}
var $5=$result;var $cmp12=((($5))|0)!=-1;if($cmp12){__label__=12;;}else{__label__=11;;}
$if_then15$$lor_lhs_false$16:do{if(__label__==11){var $call13=___errno();var $6=HEAP32[(($call13)>>2)];var $cmp14=((($6))|0)!=11;if($cmp14){__label__=12;break $if_then15$$lor_lhs_false$16;}else{__label__=13;break $if_then15$$lor_lhs_false$16;}}}while(0);if(__label__==12){$success=0;;}
var $call17=__ZL17mbrola_has_errorsv();var $tobool18=((($call17))|0)!=0;if($tobool18){__label__=16;;}else{__label__=14;;}
$if_end21$$land_lhs_true$21:do{if(__label__==14){var $7=$success;var $tobool19=((($7))|0)!=0;if(!($tobool19)){__label__=16;break $if_end21$$land_lhs_true$21;}
HEAP32[((__ZL9mbr_state)>>2)]=1;;}}while(0);var $8=$success;$retval=$8;;}
else if(__label__==3){$retval=0;;}}
var $9=$retval;STACKTOP=__stackBase__;return $9;return null;}
function __ZL17mbrola_has_errorsv(){var __stackBase__=STACKTOP;STACKTOP+=256;_memset(__stackBase__,0,256);var __label__;var $retval;var $result;var $buffer=__stackBase__;var $buf_ptr;var $lf;var $arraydecay=(($buffer)&4294967295);$buf_ptr=$arraydecay;var $arraydecay1=(($buffer)&4294967295);var $sub_ptr_rhs_cast=($arraydecay1);var $sub_ptr_rhs_cast_neg=(((-($sub_ptr_rhs_cast)))&4294967295);var $sub_ptr_rhs_cast_neg_neg=(((-($sub_ptr_rhs_cast_neg)))&4294967295);var $sub=((($sub_ptr_rhs_cast_neg_neg)+255)&4294967295);var $arraydecay27=(($buffer)&4294967295);var $arraydecay28=(($buffer)&4294967295);;$for_cond$2:while(1){var $0=HEAP32[((__ZL12mbr_error_fd)>>2)];var $1=$buf_ptr;var $2=$buf_ptr;var $sub_ptr_lhs_cast=($2);var $sub_ptr_lhs_cast_neg=(((-($sub_ptr_lhs_cast)))&4294967295);var $sub2=((($sub)+($sub_ptr_lhs_cast_neg))&4294967295);var $call=_read($0,$1,$sub2);$result=$call;var $cmp=((($call))|0)==-1;if($cmp){__label__=2;break $for_cond$2;}
var $5=$result;var $cmp9=((($5))|0)==0;if($cmp9){__label__=6;break $for_cond$2;}
var $6=$result;var $7=$buf_ptr;var $arrayidx=(($7+$6)&4294967295);HEAP8[($arrayidx)]=0;;$for_cond13$6:while(1){var $8=$buf_ptr;var $call14=_strchr($8,10);$lf=$call14;var $tobool=((($call14))|0)!=0;var $9=$buf_ptr;if(!($tobool)){__label__=14;break $for_cond13$6;}
var $call15=_strncmp($9,((__str8588)&4294967295),18);var $cmp16=((($call15))|0)==0;if($cmp16){__label__=13;;}else{__label__=10;;}
$for_inc$$lor_lhs_false$9:do{if(__label__==10){var $10=$buf_ptr;var $call17=_strncmp($10,((__str9589)&4294967295),18);var $cmp18=((($call17))|0)==0;if($cmp18){__label__=13;break $for_inc$$lor_lhs_false$9;}
var $11=$lf;HEAP8[($11)]=0;var $12=$buf_ptr;__ZL3logPKcz(((__str10590)&4294967295),allocate([$12,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $13=$lf;var $14=$result;var $sub21=((($14)-1)&4294967295);var $15=$buf_ptr;var $arrayidx22=(($15+$sub21)&4294967295);var $cmp23=((($13))|0)==((($arrayidx22))|0);if($cmp23){__label__=12;break $for_cond$2;}}}while(0);var $17=$lf;var $add_ptr=(($17+1)&4294967295);$buf_ptr=$add_ptr;__label__=8;continue $for_cond13$6;}
var $18=$result;_llvm_memmove_p0i8_p0i8_i32($arraydecay27,$9,$18,1,0);var $19=$result;var $add_ptr29=(($arraydecay28+$19)&4294967295);$buf_ptr=$add_ptr29;__label__=1;continue $for_cond$2;}
if(__label__==2){var $call3=___errno();var $3=HEAP32[(($call3)>>2)];var $cmp4=((($3))|0)==11;if($cmp4){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=0;;}
else if(__label__==4){var $call6=___errno();var $4=HEAP32[(($call6)>>2)];var $call7=_strerror($4);__ZL3errPKcz(((__str7587)&4294967295),allocate([$call7,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=-1;;}}
else if(__label__==6){__ZL11mbrola_diedv();$retval=-1;;}
else if(__label__==12){var $16=$buf_ptr;var $call25=_snprintf(((__ZL12mbr_errorbuf)&4294967295),160,((__str57709)&4294967295),allocate([$16,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=0;;}
var $20=$retval;STACKTOP=__stackBase__;return $20;return null;}
function _read_MBR($buffer,$nb_samples){;var __label__;var $buffer_addr;var $nb_samples_addr;var $result;$buffer_addr=$buffer;$nb_samples_addr=$nb_samples;var $0=$buffer_addr;var $1=$nb_samples_addr;var $mul=((($1)*2)&4294967295);var $call=__ZL19receive_from_mbrolaPvj($0,$mul);$result=$call;var $2=$result;var $cmp=((($2))|0)>0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $3=$result;var $div=((((($3))|0)/2)|0);$result=$div;;}
var $4=$result;;return $4;return null;}
function _write_MBR($data){;var __label__;var $data_addr;$data_addr=$data;HEAP32[((__ZL9mbr_state)>>2)]=2;var $0=$data_addr;var $call=__ZL14send_to_mbrolaPKc($0);;return $call;return null;}
function _flush_MBR(){;var __label__;var $call=__ZL14send_to_mbrolaPKc(((__str5585)&4294967295));var $cmp=((($call))|0)==3;var $conv=((($cmp))&1);;return $conv;return null;}
function _getFreq_MBR(){;var __label__;var $0=HEAP32[((__ZL14mbr_samplerate)>>2)];;return $0;return null;}
function _setVolumeRatio_MBR($value){;var __label__;var $value_addr;$value_addr=$value;var $0=$value_addr;var $1=HEAPF32[((__ZL10mbr_volume)>>2)];var $cmp=($0)==($1);if($cmp){__label__=3;;}else{__label__=1;;}
$return$$if_end$2:do{if(__label__==1){var $2=$value_addr;HEAPF32[((__ZL10mbr_volume)>>2)]=$2;var $3=HEAP32[((__ZL9mbr_state)>>2)];var $cmp1=((($3))|0)!=1;if($cmp1){__label__=3;break $return$$if_end$2;}
__ZL11stop_mbrolav();var $4=HEAP32[((__ZL14mbr_voice_path)>>2)];var $call=_init_MBR($4);;}}while(0);;return;return;}
function _lastErrorStr_MBR($buffer,$bufsize){;var __label__;var __lastLabel__=null;var $buffer_addr;var $bufsize_addr;var $result;$buffer_addr=$buffer;$bufsize_addr=$bufsize;var $0=HEAP32[((__ZL7mbr_pid)>>2)];var $tobool=((($0))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $call=__ZL17mbrola_has_errorsv();;}
var $1=$buffer_addr;var $2=$bufsize_addr;var $call1=_snprintf($1,$2,((__str57709)&4294967295),allocate([((__ZL12mbr_errorbuf)&4294967295),0,0,0],["i8*",0,0,0],ALLOC_STACK));$result=$call1;var $3=$result;var $4=$bufsize_addr;var $cmp=((($3))|0)>=((($4))|0);if($cmp){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $5=$bufsize_addr;var $sub=((($5)-1)&4294967295);__lastLabel__=3;;}
else if(__label__==4){var $6=$result;__lastLabel__=4;;}
var $cond=__lastLabel__==3?$sub:($6);;return $cond;return null;}
function _resetError_MBR(){;var __label__;HEAP8[(((__ZL12mbr_errorbuf)&4294967295))]=0;;return;return;}
function __ZL11mbrola_diedv(){var __stackBase__=STACKTOP;STACKTOP+=84;_memset(__stackBase__,0,84);var __label__;var $pid;var $status=__stackBase__;var $len;var $msg;var $msgbuf=__stackBase__+4;var $sig;var $exst;var $0=HEAP32[((__ZL7mbr_pid)>>2)];var $call=_waitpid($0,$status,1);$pid=$call;var $1=$pid;var $tobool=((($1))|0)!=0;if($tobool){__label__=2;;}else{__label__=1;;}
$if_else$$if_then$2:do{if(__label__==2){var $2=$pid;var $3=HEAP32[((__ZL7mbr_pid)>>2)];var $cmp=((($2))|0)!=((($3))|0);if($cmp){__label__=3;;}else{__label__=4;;}
if(__label__==3){$msg=((__str12592)&4294967295);;}
else if(__label__==4){HEAP32[((__ZL7mbr_pid)>>2)]=0;var $4=HEAP32[(($status)>>2)];var $and=($4)&127;var $cmp3=((($and))|0)>0;if($cmp3){__label__=5;;}else{__label__=7;;}
$land_lhs_true$$if_else10$7:do{if(__label__==5){var $5=HEAP32[(($status)>>2)];var $and4=($5)&127;var $cmp5=((($and4))|0)<127;if(!($cmp5)){__label__=7;break $land_lhs_true$$if_else10$7;}
var $6=HEAP32[(($status)>>2)];var $and7=($6)&127;$sig=$and7;var $arraydecay=(($msgbuf)&4294967295);var $7=$sig;var $call8=_snprintf($arraydecay,80,((__str13593)&4294967295),allocate([$7,0,0,0],["i32",0,0,0],ALLOC_STACK));var $arraydecay9=(($msgbuf)&4294967295);$msg=$arraydecay9;__label__=10;break $if_else$$if_then$2;}}while(0);var $8=HEAP32[(($status)>>2)];var $and11=($8)&255;var $cmp12=((($and11))|0)==0;if($cmp12){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $9=HEAP32[(($status)>>2)];var $shr=($9)>>8;var $and14=($shr)&255;$exst=$and14;var $arraydecay15=(($msgbuf)&4294967295);var $10=$exst;var $call16=_snprintf($arraydecay15,80,((__str14594)&4294967295),allocate([$10,0,0,0],["i32",0,0,0],ALLOC_STACK));var $arraydecay17=(($msgbuf)&4294967295);$msg=$arraydecay17;;}
else if(__label__==9){$msg=((__str15595)&4294967295);;}}}
else if(__label__==1){$msg=((__str11591)&4294967295);;}}while(0);var $11=$msg;__ZL3logPKcz(((__str16596)&4294967295),allocate([$11,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $call22=_strlen(((__ZL12mbr_errorbuf)&4294967295));$len=$call22;var $tobool23=((($call22))|0)!=0;if($tobool23){__label__=12;;}else{__label__=11;;}
if(__label__==12){var $13=$len;var $add_ptr=((((__ZL12mbr_errorbuf)&4294967295)+$13)&4294967295);var $14=$len;var $sub=((160-($14))&4294967295);var $15=$msg;var $call27=_snprintf($add_ptr,$sub,((__str17597)&4294967295),allocate([$15,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==11){var $12=$msg;var $call25=_snprintf(((__ZL12mbr_errorbuf)&4294967295),160,((__str57709)&4294967295),allocate([$12,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
STACKTOP=__stackBase__;return;return;}
function __ZL3logPKcz($msg){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $msg_addr;var $params=__stackBase__;$msg_addr=$msg;var $params1=$params;HEAP32[(($params1)>>2)]=arguments[__ZL3logPKcz.length];;var $0=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($0+12)&4294967295);var $1=HEAP32[(($_stderr)>>2)];var $2=$msg_addr;var $3=HEAP32[(($params)>>2)];var $call=_vfprintf($1,$2,$3);var $4=HEAP32[((__impure_ptr)>>2)];var $_stderr2=(($4+12)&4294967295);var $5=HEAP32[(($_stderr2)>>2)];var $call3=_fputc(10,$5);var $params4=$params;;STACKTOP=__stackBase__;return;return;}
function __ZL14mbrola_is_idlev(){var __stackBase__=STACKTOP;STACKTOP+=20;_memset(__stackBase__,0,20);var __label__;var __lastLabel__=null;var $retval;var $p;var $buffer=__stackBase__;var $0=HEAP32[((__ZL13mbr_proc_stat)>>2)];var $call=_lseek($0,0,0);var $cmp=((($call))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){$retval=0;;}
else if(__label__==2){var $1=HEAP32[((__ZL13mbr_proc_stat)>>2)];var $arraydecay=(($buffer)&4294967295);var $call1=_read($1,$arraydecay,20);var $cmp2=((($call1))|0)!=20;if($cmp2){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=0;;}
else if(__label__==4){var $arraydecay5=(($buffer)&4294967295);var $call6=_memchr($arraydecay5,41,20);$p=$call6;var $2=$p;var $tobool=((($2))|0)!=0;if($tobool){__label__=5;;}else{__label__=6;;}
$lor_lhs_false$$if_then9$8:do{if(__label__==5){var $3=$p;var $arraydecay7=(($buffer)&4294967295);var $sub_ptr_lhs_cast=($3);var $sub_ptr_rhs_cast=($arraydecay7);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);var $cmp8=((($sub_ptr_sub))>>>0)>=18;if($cmp8){__label__=6;break $lor_lhs_false$$if_then9$8;}
var $4=$p;var $arrayidx=(($4+1)&4294967295);var $5=HEAP8[($arrayidx)];var $conv=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $cmp11=((($conv))|0)==32;if($cmp11){__lastLabel__=7;__label__=8;;}else{__lastLabel__=7;__label__=9;;}
if(__label__==8){var $6=$p;var $arrayidx12=(($6+2)&4294967295);var $7=HEAP8[($arrayidx12)];var $conv13=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $cmp14=((($conv13))|0)==83;__lastLabel__=8;;}
var $8=__lastLabel__==7?0:($cmp14);var $conv15=((($8))&1);$retval=$conv15;__label__=10;break $if_then$$if_end$2;}}while(0);$retval=0;;}}}while(0);var $9=$retval;STACKTOP=__stackBase__;return $9;return null;}
function __ZL12create_pipesPiS_S_($p1,$p2,$p3){;var __label__;var $retval;var $p1_addr;var $p2_addr;var $p3_addr;var $error;$p1_addr=$p1;$p2_addr=$p2;$p3_addr=$p3;var $0=$p1_addr;var $call=_pipe($0);var $cmp=((($call))|0)!=-1;if($cmp){__label__=1;;}else{__label__=7;;}
$if_then$$if_else18$2:do{if(__label__==1){var $1=$p2_addr;var $call1=_pipe($1);var $cmp2=((($call1))|0)!=-1;if($cmp2){__label__=2;;}else{__label__=5;;}
if(__label__==2){var $2=$p3_addr;var $call4=_pipe($2);var $cmp5=((($call4))|0)!=-1;if($cmp5){__label__=3;;}else{__label__=4;;}
if(__label__==3){$retval=0;__label__=9;break $if_then$$if_else18$2;}
else if(__label__==4){var $call7=___errno();var $3=HEAP32[(($call7)>>2)];$error=$3;var $4=$p2_addr;var $arrayidx=(($4)&4294967295);var $5=HEAP32[(($arrayidx)>>2)];var $call8=_close($5);var $6=$p2_addr;var $arrayidx9=(($6+4)&4294967295);var $7=HEAP32[(($arrayidx9)>>2)];var $call10=_close($7);;}}
else if(__label__==5){var $call12=___errno();var $8=HEAP32[(($call12)>>2)];$error=$8;;}
var $9=$p1_addr;var $arrayidx14=(($9)&4294967295);var $10=HEAP32[(($arrayidx14)>>2)];var $call15=_close($10);var $11=$p1_addr;var $arrayidx16=(($11+4)&4294967295);var $12=HEAP32[(($arrayidx16)>>2)];var $call17=_close($12);__label__=8;break $if_then$$if_else18$2;}
else if(__label__==7){var $call19=___errno();var $13=HEAP32[(($call19)>>2)];$error=$13;__label__=8;break $if_then$$if_else18$2;}}while(0);if(__label__==8){var $14=$error;var $call21=_strerror($14);__ZL3errPKcz(((__str35615)&4294967295),allocate([$call21,0,0,0],["i8*",0,0,0],ALLOC_STACK));$retval=-1;;}
var $15=$retval;;return $15;return null;}
function __ZL11close_pipesPiS_S_($p1,$p2,$p3){;var __label__;var $p1_addr;var $p2_addr;var $p3_addr;$p1_addr=$p1;$p2_addr=$p2;$p3_addr=$p3;var $0=$p1_addr;var $arrayidx=(($0)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];var $call=_close($1);var $2=$p1_addr;var $arrayidx1=(($2+4)&4294967295);var $3=HEAP32[(($arrayidx1)>>2)];var $call2=_close($3);var $4=$p2_addr;var $arrayidx3=(($4)&4294967295);var $5=HEAP32[(($arrayidx3)>>2)];var $call4=_close($5);var $6=$p2_addr;var $arrayidx5=(($6+4)&4294967295);var $7=HEAP32[(($arrayidx5)>>2)];var $call6=_close($7);var $8=$p3_addr;var $arrayidx7=(($8)&4294967295);var $9=HEAP32[(($arrayidx7)>>2)];var $call8=_close($9);var $10=$p3_addr;var $arrayidx9=(($10+4)&4294967295);var $11=HEAP32[(($arrayidx9)>>2)];var $call10=_close($11);;return;return;}
function __Z15SetIndicLettersP10Translator($tr){;var __label__;var $tr_addr;$tr_addr=$tr;var $0=$tr_addr;var $letter_bits=(($0+708)&4294967295);var $arraydecay=(($letter_bits)&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arraydecay;$stop$=$dest$+256;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $1=$tr_addr;__ZL18SetLetterBitsRangeP10Translatoriii($1,0,4,20);var $2=$tr_addr;__ZL18SetLetterBitsRangeP10Translatoriii($2,0,62,77);var $3=$tr_addr;__ZL18SetLetterBitsRangeP10Translatoriii($3,0,85,87);var $4=$tr_addr;__ZL18SetLetterBitsRangeP10Translatoriii($4,1,62,77);var $5=$tr_addr;__ZL18SetLetterBitsRangeP10Translatoriii($5,1,85,87);var $6=$tr_addr;__ZL18SetLetterBitsRangeP10Translatoriii($6,2,21,57);var $7=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($7,2,((__ZZ15SetIndicLettersP10TranslatorE15dev_consonants2)&4294967295));var $8=$tr_addr;__ZL18SetLetterBitsRangeP10Translatoriii($8,6,4,20);var $9=$tr_addr;__ZL18SetLetterBitsRangeP10Translatoriii($9,6,62,76);var $10=$tr_addr;__ZL18SetLetterBitsRangeP10Translatoriii($10,6,85,87);var $11=$tr_addr;var $langopts=(($11)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx=(($param+20)&4294967295);HEAP32[(($arrayidx)>>2)]=1;var $12=$tr_addr;var $letter_bits_offset=(($12+964)&4294967295);var $13=HEAP32[(($letter_bits_offset)>>2)];var $add=((($13)+77)&4294967295);var $14=$tr_addr;var $langopts1=(($14)&4294967295);var $suffix_add_e=(($langopts1+276)&4294967295);HEAP32[(($suffix_add_e)>>2)]=$add;;return;return;}
function __ZL18SetLetterBitsRangeP10Translatoriii($tr,$group,$first,$last){;var __label__;var $tr_addr;var $group_addr;var $first_addr;var $last_addr;var $bits;var $ix;$tr_addr=$tr;$group_addr=$group;$first_addr=$first;$last_addr=$last;var $0=$group_addr;var $shl=1<<($0);$bits=$shl;var $1=$first_addr;$ix=$1;var $2=$ix;var $3=$last_addr;var $cmp1=((($2))|0)<=((($3))|0);if($cmp1){__label__=1;;}else{__label__=2;;}
$for_body$$for_end$2:do{if(__label__==1){while(1){var $4=$bits;var $5=$ix;var $6=$tr_addr;var $letter_bits=(($6+708)&4294967295);var $arrayidx=(($letter_bits+$5)&4294967295);var $7=HEAPU8[($arrayidx)];var $conv=((($7))&255);var $or=($conv)|($4);var $conv1=((($or))&255);HEAP8[($arrayidx)]=$conv1;var $8=$ix;var $inc=((($8)+1)&4294967295);$ix=$inc;var $9=$ix;var $10=$last_addr;var $cmp=((($9))|0)<=((($10))|0);if($cmp){__label__=1;continue;}else{__label__=2;break $for_body$$for_end$2;}}}}while(0);;return;return;}
function __ZL13SetLetterBitsP10TranslatoriPKc($tr,$group,$string){;var __label__;var $tr_addr;var $group_addr;var $string_addr;var $bits;var $c;$tr_addr=$tr;$group_addr=$group;$string_addr=$string;var $0=$group_addr;var $shl=1<<($0);$bits=$shl;var $1=$string_addr;var $incdec_ptr1=(($1+1)&4294967295);$string_addr=$incdec_ptr1;var $2=HEAPU8[($1)];$c=$2;var $conv3=((($2))&255);var $cmp4=((($conv3))|0)!=0;if($cmp4){__label__=1;;}else{__label__=2;;}
$while_body$$while_end$2:do{if(__label__==1){while(1){var $3=$bits;var $4=$c;var $idxprom=((($4))&255);var $5=$tr_addr;var $letter_bits=(($5+708)&4294967295);var $arrayidx=(($letter_bits+$idxprom)&4294967295);var $6=HEAPU8[($arrayidx)];var $conv1=((($6))&255);var $or=($conv1)|($3);var $conv2=((($or))&255);HEAP8[($arrayidx)]=$conv2;var $7=$string_addr;var $incdec_ptr=(($7+1)&4294967295);$string_addr=$incdec_ptr;var $8=HEAPU8[($7)];$c=$8;var $conv=((($8))&255);var $cmp=((($conv))|0)!=0;if($cmp){__label__=1;continue;}else{__label__=2;break $while_body$$while_end$2;}}}}while(0);;return;return;}
function __Z15SetupTranslatorP10TranslatorPKsPKh($tr,$lengths,$amps){;var __label__;var __lastLabel__=null;var $tr_addr;var $lengths_addr;var $amps_addr;$tr_addr=$tr;$lengths_addr=$lengths;$amps_addr=$amps;var $0=$lengths_addr;var $cmp=((($0))|0)!=0;if($cmp){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=2;;}
if(__label__==1){var $1=$tr_addr;var $stress_lengths=(($1+676)&4294967295);var $arraydecay=(($stress_lengths)&4294967295);var $2=$arraydecay;var $3=$lengths_addr;var $4=$3;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$4;$dest$=$2;$stop$=$src$+16;if(($dest$%4)==($src$%4)&&16>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $_pr=$amps_addr;__lastLabel__=1;;}
var $5=__lastLabel__==1?$_pr:($amps);var $cmp1=((($5))|0)!=0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $6=$tr_addr;var $stress_amps=(($6+660)&4294967295);var $arraydecay3=(($stress_amps)&4294967295);var $7=$amps_addr;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$7;$dest$=$arraydecay3;$stop$=$src$+8;if(($dest$%4)==($src$%4)&&8>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;};return;return;}
function __Z16SelectTranslatorPKc($name){;var __label__;var __lastLabel__=null;var $name_addr;var $name2;var $tr;$name_addr=$name;$name2=0;var $0=$name_addr;var $1=HEAP8[($0)];var $conv2=(tempInt=(($1)),(tempInt>=128?tempInt-256:tempInt));var $cmp3=((($conv2))|0)!=0;if($cmp3){__label__=1;;}else{__label__=2;;}
$while_body$$while_end$2:do{if(__label__==1){while(1){var $2=$name2;var $shl=((($2)*256)&4294967295);var $3=$name_addr;var $incdec_ptr=(($3+1)&4294967295);$name_addr=$incdec_ptr;var $4=HEAP8[($3)];var $conv1=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $add=((($conv1)+($shl))&4294967295);$name2=$add;var $5=$name_addr;var $6=HEAP8[($5)];var $conv=(tempInt=(($6)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)!=0;if($cmp){__label__=1;continue;}else{__label__=2;break $while_body$$while_end$2;}}}}while(0);var $call=__ZL13NewTranslatorv();$tr=$call;var $7=$name2;if($7==24934){__label__=3;;}
else if($7==24941){__label__=4;;}
else if($7==24946){__label__=5;;}
else if($7==25191){__label__=6;;}
else if($7==25198){__label__=7;;}
else if($7==25465){__label__=8;;}
else if($7==25697){__label__=9;;}
else if($7==25701){__label__=10;;}
else if($7==25718){__label__=11;;}
else if($7==25966){__label__=12;;}
else if($7==25964){__label__=13;;}
else if($7==6779491){__label__=13;;}
else if($7==25967){__label__=15;;}
else if($7==25971){__label__=16;;}
else if($7==25441){__label__=16;;}
else if($7==7364976){__label__=16;;}
else if($7==25973){__label__=21;;}
else if($7==26209){__label__=22;;}
else if($7==25972){__label__=23;;}
else if($7==26217){__label__=24;;}
else if($7==26226){__label__=25;;}
else if($7==26729){__label__=26;;}
else if($7==28261){__label__=26;;}
else if($7==28769){__label__=26;;}
else if($7==26738){__label__=29;;}
else if($7==25203){__label__=29;;}
else if($7==29554){__label__=29;;}
else if($7==26740){__label__=33;;}
else if($7==26741){__label__=34;;}
else if($7==26745){__label__=35;;}
else if($7==26980){__label__=36;;}
else if($7==26995){__label__=37;;}
else if($7==26996){__label__=38;;}
else if($7==6972015){__label__=39;;}
else if($7==27489){__label__=40;;}
else if($7==27503){__label__=41;;}
else if($7==27509){__label__=42;;}
else if($7==27745){__label__=43;;}
else if($7==27766){__label__=44;;}
else if($7==28011){__label__=45;;}
else if($7==28268){__label__=46;;}
else if($7==28271){__label__=47;;}
else if($7==28525){__label__=48;;}
else if($7==28780){__label__=49;;}
else if($7==28788){__label__=50;;}
else if($7==29295){__label__=51;;}
else if($7==29301){__label__=52;;}
else if($7==29303){__label__=53;;}
else if($7==29547){__label__=54;;}
else if($7==25459){__label__=54;;}
else if($7==29545){__label__=57;;}
else if($7==29548){__label__=58;;}
else if($7==29553){__label__=59;;}
else if($7==29558){__label__=60;;}
else if($7==29559){__label__=61;;}
else if($7==29806){__label__=61;;}
else if($7==29793){__label__=62;;}
else if($7==28012){__label__=62;;}
else if($7==27502){__label__=62;;}
else if($7==28018){__label__=62;;}
else if($7==29797){__label__=62;;}
else if($7==29810){__label__=73;;}
else if($7==30066){__label__=74;;}
else if($7==30313){__label__=75;;}
else if($7==30575){__label__=76;;}
else if($7==31336){__label__=77;;}
else if($7==8022137){__label__=77;;}
else{__label__=79;;}
$sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6:do{if(__label__==79){var $495=$tr;var $langopts756=(($495)&4294967295);var $param757=(($langopts756+24)&4294967295);var $arrayidx758=(($param757+20)&4294967295);HEAP32[(($arrayidx758)>>2)]=1;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==3){var $8=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($8,((__ZZ16SelectTranslatorPKcE17stress_lengths_af)&4294967295),0);var $9=$tr;var $langopts=(($9)&4294967295);var $stress_rule=(($langopts+8)&4294967295);HEAP32[(($stress_rule)>>2)]=0;var $10=$tr;var $langopts2=(($10)&4294967295);var $vowel_pause=(($langopts2+4)&4294967295);HEAP32[(($vowel_pause)>>2)]=48;var $11=$tr;var $langopts3=(($11)&4294967295);var $param=(($langopts3+24)&4294967295);var $arrayidx=(($param+4)&4294967295);HEAP32[(($arrayidx)>>2)]=1;var $12=$tr;var $langopts4=(($12)&4294967295);var $param5=(($langopts4+24)&4294967295);var $arrayidx6=(($param5+12)&4294967295);HEAP32[(($arrayidx6)>>2)]=1;var $13=$tr;__ZL14SetLetterVowelP10Translatori($13,121);var $14=$tr;var $langopts7=(($14)&4294967295);var $numbers=(($langopts7+184)&4294967295);HEAP32[(($numbers)>>2)]=16779472;var $15=$tr;var $langopts8=(($15)&4294967295);var $accents=(($langopts8+220)&4294967295);HEAP32[(($accents)>>2)]=1;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==4){var $16=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($16,((__ZZ16SelectTranslatorPKcE17stress_lengths_fr)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_fr)&4294967295));var $17=$tr;var $langopts10=(($17)&4294967295);var $stress_rule11=(($langopts10+8)&4294967295);HEAP32[(($stress_rule11)>>2)]=0;var $18=$tr;var $langopts12=(($18)&4294967295);var $stress_flags=(($langopts12+12)&4294967295);HEAP32[(($stress_flags)>>2)]=36;var $19=$tr;var $langopts13=(($19)&4294967295);var $length_mods=(($langopts13+176)&4294967295);var $20=HEAP32[(($length_mods)>>2)];var $21=$tr;var $langopts14=(($21)&4294967295);var $length_mods0=(($langopts14+180)&4294967295);HEAP32[(($length_mods0)>>2)]=$20;var $22=$tr;var $langopts15=(($22)&4294967295);var $param16=(($langopts15+24)&4294967295);var $arrayidx17=(($param16+20)&4294967295);HEAP32[(($arrayidx17)>>2)]=1;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==5){var $23=$tr;var $letter_bits_offset=(($23+964)&4294967295);HEAP32[(($letter_bits_offset)>>2)]=1536;var $24=$tr;var $langopts19=(($24)&4294967295);var $numbers20=(($langopts19+184)&4294967295);HEAP32[(($numbers20)>>2)]=2884720;var $25=$tr;var $langopts21=(($25)&4294967295);var $param22=(($langopts21+24)&4294967295);var $arrayidx23=(($param22+20)&4294967295);HEAP32[(($arrayidx23)>>2)]=1;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==6){var $26=$tr;__ZL18SetCyrillicLettersP10Translator($26);var $27=$tr;__ZL14SetLetterVowelP10Translatori($27,42);var $28=$tr;var $langopts25=(($28)&4294967295);var $param26=(($langopts25+24)&4294967295);var $arrayidx27=(($param26+20)&4294967295);HEAP32[(($arrayidx27)>>2)]=1074;var $29=$tr;var $langopts28=(($29)&4294967295);var $param29=(($langopts28+24)&4294967295);var $arrayidx30=(($param29+16)&4294967295);HEAP32[(($arrayidx30)>>2)]=23;var $30=$tr;var $langopts31=(($30)&4294967295);var $param32=(($langopts31+24)&4294967295);var $arrayidx33=(($param32+40)&4294967295);HEAP32[(($arrayidx33)>>2)]=2;var $31=$tr;var $langopts34=(($31)&4294967295);var $stress_rule35=(($langopts34+8)&4294967295);HEAP32[(($stress_rule35)>>2)]=2;var $32=$tr;var $langopts36=(($32)&4294967295);var $numbers37=(($langopts36+184)&4294967295);HEAP32[(($numbers37)>>2)]=184554728;var $33=$tr;var $langopts38=(($33)&4294967295);var $thousands_sep=(($langopts38+204)&4294967295);HEAP32[(($thousands_sep)>>2)]=32;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==7){var $34=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($34,((__ZZ16SelectTranslatorPKcE17stress_lengths_bn)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_bn)&4294967295));var $35=$tr;var $langopts40=(($35)&4294967295);var $length_mods41=(($langopts40+176)&4294967295);var $36=HEAP32[(($length_mods41)>>2)];var $37=$tr;var $langopts42=(($37)&4294967295);var $length_mods043=(($langopts42+180)&4294967295);HEAP32[(($length_mods043)>>2)]=$36;var $38=$tr;var $langopts44=(($38)&4294967295);var $stress_rule45=(($langopts44+8)&4294967295);HEAP32[(($stress_rule45)>>2)]=0;var $39=$tr;var $langopts46=(($39)&4294967295);var $stress_flags47=(($langopts46+12)&4294967295);HEAP32[(($stress_flags47)>>2)]=65540;var $40=$tr;var $letter_bits_offset48=(($40+964)&4294967295);HEAP32[(($letter_bits_offset48)>>2)]=2432;var $41=$tr;__Z15SetIndicLettersP10Translator($41);var $42=$tr;__ZL18SetLetterBitsRangeP10Translatoriii($42,4,62,76);var $43=$tr;var $langopts49=(($43)&4294967295);var $numbers50=(($langopts49+184)&4294967295);HEAP32[(($numbers50)>>2)]=1;var $44=$tr;var $langopts51=(($44)&4294967295);var $break_numbers=(($langopts51+192)&4294967295);HEAP32[(($break_numbers)>>2)]=613567144;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==8){var $45=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($45,((__ZZ16SelectTranslatorPKcE17stress_lengths_cy)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_cy)&4294967295));var $46=HEAP32[((((_charsets+56)&4294967295))>>2)];var $47=$tr;var $charset_a0=(($47+696)&4294967295);HEAP32[(($charset_a0)>>2)]=$46;var $48=$tr;var $langopts53=(($48)&4294967295);var $stress_rule54=(($langopts53+8)&4294967295);HEAP32[(($stress_rule54)>>2)]=2;var $49=$tr;var $langopts55=(($49)&4294967295);var $stress_flags56=(($langopts55+12)&4294967295);HEAP32[(($stress_flags56)>>2)]=22;var $50=$tr;var $langopts57=(($50)&4294967295);var $unstressed_wd1=(($langopts57+16)&4294967295);HEAP32[(($unstressed_wd1)>>2)]=0;var $51=$tr;var $langopts58=(($51)&4294967295);var $unstressed_wd2=(($langopts58+20)&4294967295);HEAP32[(($unstressed_wd2)>>2)]=2;var $52=$tr;var $langopts59=(($52)&4294967295);var $param60=(($langopts59+24)&4294967295);var $arrayidx61=(($param60+28)&4294967295);HEAP32[(($arrayidx61)>>2)]=120;var $53=$tr;var $langopts62=(($53)&4294967295);var $numbers63=(($langopts62+184)&4294967295);HEAP32[(($numbers63)>>2)]=1024;var $54=$tr;__ZL14SetLetterVowelP10Translatori($54,119);var $55=$tr;__ZL14SetLetterVowelP10Translatori($55,121);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==9){var $56=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($56,((__ZZ16SelectTranslatorPKcE17stress_lengths_da)&4294967295),0);var $57=$tr;var $langopts65=(($57)&4294967295);var $stress_rule66=(($langopts65+8)&4294967295);HEAP32[(($stress_rule66)>>2)]=0;var $58=$tr;var $langopts67=(($58)&4294967295);var $param68=(($langopts67+24)&4294967295);var $arrayidx69=(($param68+12)&4294967295);HEAP32[(($arrayidx69)>>2)]=1;var $59=$tr;__ZL14SetLetterVowelP10Translatori($59,121);var $60=$tr;var $langopts70=(($60)&4294967295);var $numbers71=(($langopts70+184)&4294967295);HEAP32[(($numbers71)>>2)]=184618072;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==10){var $61=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($61,((__ZZ16SelectTranslatorPKcE17stress_lengths_de)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_de)&4294967295));var $62=$tr;var $langopts73=(($62)&4294967295);var $stress_rule74=(($langopts73+8)&4294967295);HEAP32[(($stress_rule74)>>2)]=0;var $63=$tr;var $langopts75=(($63)&4294967295);var $word_gap=(($langopts75)&4294967295);HEAP32[(($word_gap)>>2)]=8;var $64=$tr;var $langopts76=(($64)&4294967295);var $vowel_pause77=(($langopts76+4)&4294967295);HEAP32[(($vowel_pause77)>>2)]=48;var $65=$tr;var $langopts78=(($65)&4294967295);var $param79=(($langopts78+24)&4294967295);var $arrayidx80=(($param79+12)&4294967295);HEAP32[(($arrayidx80)>>2)]=1;var $66=$tr;var $langopts81=(($66)&4294967295);var $param82=(($langopts81+24)&4294967295);var $arrayidx83=(($param82+16)&4294967295);HEAP32[(($arrayidx83)>>2)]=16;var $67=$tr;var $langopts84=(($67)&4294967295);var $param85=(($langopts84+24)&4294967295);var $arrayidx86=(($param85+72)&4294967295);HEAP32[(($arrayidx86)>>2)]=87;var $68=$tr;var $langopts87=(($68)&4294967295);var $numbers88=(($langopts87+184)&4294967295);HEAP32[(($numbers88)>>2)]=16846872;var $69=$tr;__ZL14SetLetterVowelP10Translatori($69,121);var $70=$tr;var $langopts89=(($70)&4294967295);var $param90=(($langopts89+24)&4294967295);var $arrayidx91=(($param90+20)&4294967295);HEAP32[(($arrayidx91)>>2)]=2;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==11){var $71=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($71,((__ZZ16SelectTranslatorPKcE17stress_lengths_ta)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_ta)&4294967295));var $72=$tr;var $langopts93=(($72)&4294967295);var $param94=(($langopts93+24)&4294967295);var $arrayidx95=(($param94+20)&4294967295);HEAP32[(($arrayidx95)>>2)]=1;var $73=$tr;var $langopts96=(($73)&4294967295);var $length_mods97=(($langopts96+176)&4294967295);var $74=HEAP32[(($length_mods97)>>2)];var $75=$tr;var $langopts98=(($75)&4294967295);var $length_mods099=(($langopts98+180)&4294967295);HEAP32[(($length_mods099)>>2)]=$74;var $76=$tr;var $letter_bits_offset100=(($76+964)&4294967295);HEAP32[(($letter_bits_offset100)>>2)]=1920;var $77=$tr;var $langopts101=(($77)&4294967295);var $stress_rule102=(($langopts101+8)&4294967295);HEAP32[(($stress_rule102)>>2)]=0;var $78=$tr;var $langopts103=(($78)&4294967295);var $stress_flags104=(($langopts103+12)&4294967295);HEAP32[(($stress_flags104)>>2)]=65540;var $79=$tr;__ZL18SetLetterBitsRangeP10Translatoriii($79,1,38,48);var $80=$tr;var $langopts105=(($80)&4294967295);var $break_numbers106=(($langopts105+192)&4294967295);HEAP32[(($break_numbers106)>>2)]=5288;var $81=$tr;var $langopts107=(($81)&4294967295);var $numbers108=(($langopts107+184)&4294967295);HEAP32[(($numbers108)>>2)]=1;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==12){var $82=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($82,((__ZZ16SelectTranslatorPKcE17stress_lengths_en)&4294967295),0);var $83=$tr;var $langopts110=(($83)&4294967295);var $stress_rule111=(($langopts110+8)&4294967295);HEAP32[(($stress_rule111)>>2)]=0;var $84=$tr;var $langopts112=(($84)&4294967295);var $stress_flags113=(($langopts112+12)&4294967295);HEAP32[(($stress_flags113)>>2)]=8;var $85=$tr;var $langopts114=(($85)&4294967295);var $numbers115=(($langopts114+184)&4294967295);HEAP32[(($numbers115)>>2)]=16779328;var $86=$tr;var $langopts116=(($86)&4294967295);var $param117=(($langopts116+24)&4294967295);var $arrayidx118=(($param117+44)&4294967295);HEAP32[(($arrayidx118)>>2)]=2;var $87=$tr;var $langopts119=(($87)&4294967295);var $suffix_add_e=(($langopts119+276)&4294967295);HEAP32[(($suffix_add_e)>>2)]=101;var $88=$tr;var $langopts120=(($88)&4294967295);var $param121=(($langopts120+24)&4294967295);var $arrayidx122=(($param121+20)&4294967295);HEAP32[(($arrayidx122)>>2)]=2;var $89=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($89,6,((__str630)&4294967295));__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==13){var $90=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($90,((__ZZ16SelectTranslatorPKcE17stress_lengths_el)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_el)&4294967295));var $91=HEAP32[((((_charsets+28)&4294967295))>>2)];var $92=$tr;var $charset_a0124=(($92+696)&4294967295);HEAP32[(($charset_a0124)>>2)]=$91;var $93=$tr;var $char_plus_apostrophe=(($93+700)&4294967295);HEAP32[(($char_plus_apostrophe)>>2)]=((__ZZ16SelectTranslatorPKcE18el_char_apostrophe)&4294967295);var $94=$tr;var $letter_bits_offset125=(($94+964)&4294967295);HEAP32[(($letter_bits_offset125)>>2)]=896;var $95=$tr;var $letter_bits=(($95+708)&4294967295);var $arraydecay=(($letter_bits)&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arraydecay;$stop$=$dest$+256;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $96=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($96,0,((__ZZ16SelectTranslatorPKcE9el_vowels)&4294967295));var $97=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($97,7,((__ZZ16SelectTranslatorPKcE9el_vowels)&4294967295));var $98=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($98,1,((__ZZ16SelectTranslatorPKcE12el_voiceless)&4294967295));var $99=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($99,2,((__ZZ16SelectTranslatorPKcE13el_consonants)&4294967295));var $100=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($100,6,((__ZZ16SelectTranslatorPKcE10el_fvowels)&4294967295));var $101=$tr;var $langopts126=(($101)&4294967295);var $length_mods127=(($langopts126+176)&4294967295);var $102=HEAP32[(($length_mods127)>>2)];var $103=$tr;var $langopts128=(($103)&4294967295);var $length_mods0129=(($langopts128+180)&4294967295);HEAP32[(($length_mods0129)>>2)]=$102;var $104=$tr;var $langopts130=(($104)&4294967295);var $stress_rule131=(($langopts130+8)&4294967295);HEAP32[(($stress_rule131)>>2)]=2;var $105=$tr;var $langopts132=(($105)&4294967295);var $stress_flags133=(($langopts132+12)&4294967295);HEAP32[(($stress_flags133)>>2)]=6;var $106=$tr;var $langopts134=(($106)&4294967295);var $unstressed_wd1135=(($langopts134+16)&4294967295);HEAP32[(($unstressed_wd1135)>>2)]=0;var $107=$tr;var $langopts136=(($107)&4294967295);var $unstressed_wd2137=(($langopts136+20)&4294967295);HEAP32[(($unstressed_wd2137)>>2)]=2;var $108=$tr;var $langopts138=(($108)&4294967295);var $param139=(($langopts138+24)&4294967295);var $arrayidx140=(($param139+28)&4294967295);HEAP32[(($arrayidx140)>>2)]=130;var $109=$tr;var $langopts141=(($109)&4294967295);var $numbers142=(($langopts141+184)&4294967295);HEAP32[(($numbers142)>>2)]=264;var $110=$tr;var $langopts143=(($110)&4294967295);var $numbers2=(($langopts143+188)&4294967295);HEAP32[(($numbers2)>>2)]=4098;var $111=$name2;var $cmp144=((($111))|0)==6779491;if(!($cmp144)){__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
var $112=$tr;var $langopts145=(($112)&4294967295);var $param146=(($langopts145+24)&4294967295);var $arrayidx147=(($param146+20)&4294967295);HEAP32[(($arrayidx147)>>2)]=1;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==15){var $113=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($113,((__ZZ16SelectTranslatorPKcE17stress_lengths_eo)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_eo)&4294967295));var $114=HEAP32[((((_charsets+12)&4294967295))>>2)];var $115=$tr;var $charset_a0149=(($115+696)&4294967295);HEAP32[(($charset_a0149)>>2)]=$114;var $116=$tr;var $char_plus_apostrophe150=(($116+700)&4294967295);HEAP32[(($char_plus_apostrophe150)>>2)]=((__ZZ16SelectTranslatorPKcE18eo_char_apostrophe)&4294967295);var $117=$tr;var $langopts151=(($117)&4294967295);var $vowel_pause152=(($langopts151+4)&4294967295);HEAP32[(($vowel_pause152)>>2)]=2;var $118=$tr;var $langopts153=(($118)&4294967295);var $stress_rule154=(($langopts153+8)&4294967295);HEAP32[(($stress_rule154)>>2)]=2;var $119=$tr;var $langopts155=(($119)&4294967295);var $stress_flags156=(($langopts155+12)&4294967295);HEAP32[(($stress_flags156)>>2)]=22;var $120=$tr;var $langopts157=(($120)&4294967295);var $unstressed_wd2158=(($langopts157+20)&4294967295);HEAP32[(($unstressed_wd2158)>>2)]=2;var $121=$tr;var $langopts159=(($121)&4294967295);var $numbers160=(($langopts159+184)&4294967295);HEAP32[(($numbers160)>>2)]=16782344;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==16){var $122=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($122,((__ZZ16SelectTranslatorPKcE17stress_lengths_es)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_es)&4294967295));var $123=$tr;var $langopts162=(($123)&4294967295);var $length_mods163=(($langopts162+176)&4294967295);var $124=HEAP32[(($length_mods163)>>2)];var $125=$tr;var $langopts164=(($125)&4294967295);var $length_mods0165=(($langopts164+180)&4294967295);HEAP32[(($length_mods0165)>>2)]=$124;var $126=$tr;var $langopts166=(($126)&4294967295);var $stress_rule167=(($langopts166+8)&4294967295);HEAP32[(($stress_rule167)>>2)]=2;var $127=$tr;var $langopts168=(($127)&4294967295);var $stress_flags169=(($langopts168+12)&4294967295);HEAP32[(($stress_flags169)>>2)]=534;var $128=$tr;var $langopts170=(($128)&4294967295);var $unstressed_wd1171=(($langopts170+16)&4294967295);HEAP32[(($unstressed_wd1171)>>2)]=0;var $129=$tr;var $langopts172=(($129)&4294967295);var $unstressed_wd2173=(($langopts172+20)&4294967295);HEAP32[(($unstressed_wd2173)>>2)]=2;var $130=$tr;var $langopts174=(($130)&4294967295);var $param175=(($langopts174+24)&4294967295);var $arrayidx176=(($param175+28)&4294967295);HEAP32[(($arrayidx176)>>2)]=120;var $131=$tr;var $langopts177=(($131)&4294967295);var $numbers178=(($langopts177+184)&4294967295);HEAP32[(($numbers178)>>2)]=85984552;var $132=$tr;var $langopts179=(($132)&4294967295);var $numbers2180=(($langopts179+188)&4294967295);HEAP32[(($numbers2180)>>2)]=4096;var $133=$name2;var $cmp181=((($133))|0)==25441;if($cmp181){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $134=$tr;var $punct_within_word=(($134+704)&4294967295);HEAP32[(($punct_within_word)>>2)]=((__ZZ16SelectTranslatorPKcE20ca_punct_within_word)&4294967295);var $135=$tr;var $langopts183=(($135)&4294967295);var $stress_flags184=(($langopts183+12)&4294967295);HEAP32[(($stress_flags184)>>2)]=566;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==18){var $136=$name2;var $cmp185=((($136))|0)==7364976;var $137=$tr;var $langopts187=(($137)&4294967295);if($cmp185){__label__=19;;}else{__label__=20;;}
if(__label__==19){var $stress_flags188=(($langopts187+12)&4294967295);HEAP32[(($stress_flags188)>>2)]=310;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==20){var $param191=(($langopts187+24)&4294967295);var $arrayidx192=(($param191+20)&4294967295);HEAP32[(($arrayidx192)>>2)]=2;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}}}
else if(__label__==21){var $138=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($138,((__ZZ16SelectTranslatorPKcE17stress_lengths_eu)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_eu)&4294967295));var $139=$tr;var $langopts196=(($139)&4294967295);var $stress_rule197=(($langopts196+8)&4294967295);HEAP32[(($stress_rule197)>>2)]=1;var $140=$tr;var $langopts198=(($140)&4294967295);var $numbers199=(($langopts198+184)&4294967295);HEAP32[(($numbers199)>>2)]=1049960;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==22){var $141=$tr;var $letter_bits_offset201=(($141+964)&4294967295);HEAP32[(($letter_bits_offset201)>>2)]=1536;var $142=$tr;var $langopts202=(($142)&4294967295);var $numbers203=(($langopts202+184)&4294967295);HEAP32[(($numbers203)>>2)]=96;var $143=$tr;var $langopts204=(($143)&4294967295);var $param205=(($langopts204+24)&4294967295);var $arrayidx206=(($param205+20)&4294967295);HEAP32[(($arrayidx206)>>2)]=1;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==23){var $144=HEAP32[((((_charsets+16)&4294967295))>>2)];var $145=$tr;var $charset_a0208=(($145+696)&4294967295);HEAP32[(($charset_a0208)>>2)]=$144;__label__=24;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==25){var $155=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($155,((__ZZ16SelectTranslatorPKcE17stress_lengths_fr)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_fr)&4294967295));var $156=$tr;var $langopts223=(($156)&4294967295);var $stress_rule224=(($langopts223+8)&4294967295);HEAP32[(($stress_rule224)>>2)]=3;var $157=$tr;var $langopts225=(($157)&4294967295);var $stress_flags226=(($langopts225+12)&4294967295);HEAP32[(($stress_flags226)>>2)]=36;var $158=$tr;var $langopts227=(($158)&4294967295);var $param228=(($langopts227+24)&4294967295);var $arrayidx229=(($param228+8)&4294967295);HEAP32[(($arrayidx229)>>2)]=1;var $159=$tr;var $langopts230=(($159)&4294967295);var $length_mods231=(($langopts230+176)&4294967295);var $160=HEAP32[(($length_mods231)>>2)];var $161=$tr;var $langopts232=(($161)&4294967295);var $length_mods0233=(($langopts232+180)&4294967295);HEAP32[(($length_mods0233)>>2)]=$160;var $162=$tr;var $langopts234=(($162)&4294967295);var $accents235=(($langopts234+220)&4294967295);HEAP32[(($accents235)>>2)]=2;var $163=$tr;var $langopts236=(($163)&4294967295);var $numbers237=(($langopts236+184)&4294967295);HEAP32[(($numbers237)>>2)]=118658312;var $164=$tr;__ZL14SetLetterVowelP10Translatori($164,121);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==26){var $165=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($165,((__ZZ16SelectTranslatorPKcE17stress_lengths_hi)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_hi)&4294967295));var $166=HEAP32[((((_charsets+76)&4294967295))>>2)];var $167=$tr;var $charset_a0239=(($167+696)&4294967295);HEAP32[(($charset_a0239)>>2)]=$166;var $168=$tr;var $langopts240=(($168)&4294967295);var $length_mods241=(($langopts240+176)&4294967295);var $169=HEAP32[(($length_mods241)>>2)];var $170=$tr;var $langopts242=(($170)&4294967295);var $length_mods0243=(($langopts242+180)&4294967295);HEAP32[(($length_mods0243)>>2)]=$169;var $171=$tr;var $langopts244=(($171)&4294967295);var $stress_rule245=(($langopts244+8)&4294967295);HEAP32[(($stress_rule245)>>2)]=6;var $172=$tr;var $langopts246=(($172)&4294967295);var $stress_flags247=(($langopts246+12)&4294967295);HEAP32[(($stress_flags247)>>2)]=65540;var $173=$tr;var $langopts248=(($173)&4294967295);var $numbers249=(($langopts248+184)&4294967295);HEAP32[(($numbers249)>>2)]=16;var $174=$tr;var $langopts250=(($174)&4294967295);var $break_numbers251=(($langopts250+192)&4294967295);HEAP32[(($break_numbers251)>>2)]=84648;var $175=$tr;var $letter_bits_offset252=(($175+964)&4294967295);HEAP32[(($letter_bits_offset252)>>2)]=2304;var $176=$name2;var $cmp253=((($176))|0)==28769;if($cmp253){__label__=27;;}else{__label__=28;;}
if(__label__==27){var $177=$tr;var $letter_bits_offset255=(($177+964)&4294967295);HEAP32[(($letter_bits_offset255)>>2)]=2560;;}
var $178=$tr;__Z15SetIndicLettersP10Translator($178);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==29){var $cmp258=((($7))|0)==29554;var $179=$tr;if($cmp258){__label__=30;;}else{__label__=31;;}
if(__label__==30){__Z15SetupTranslatorP10TranslatorPKsPKh($179,((__ZZ16SelectTranslatorPKcE17stress_lengths_sr)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_hr)&4294967295));;}
else if(__label__==31){__Z15SetupTranslatorP10TranslatorPKsPKh($179,((__ZZ16SelectTranslatorPKcE17stress_lengths_hr)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_hr)&4294967295));;}
var $180=HEAP32[((((_charsets+8)&4294967295))>>2)];var $181=$tr;var $charset_a0262=(($181+696)&4294967295);HEAP32[(($charset_a0262)>>2)]=$180;var $182=$tr;var $langopts263=(($182)&4294967295);var $stress_rule264=(($langopts263+8)&4294967295);HEAP32[(($stress_rule264)>>2)]=0;var $183=$tr;var $langopts265=(($183)&4294967295);var $stress_flags266=(($langopts265+12)&4294967295);HEAP32[(($stress_flags266)>>2)]=16;var $184=$tr;var $langopts267=(($184)&4294967295);var $param268=(($langopts267+24)&4294967295);var $arrayidx269=(($param268+16)&4294967295);HEAP32[(($arrayidx269)>>2)]=3;var $185=$tr;var $langopts270=(($185)&4294967295);var $max_initial_consonants=(($langopts270+248)&4294967295);HEAP8[($max_initial_consonants)]=5;var $186=$tr;var $langopts271=(($186)&4294967295);var $spelling_stress272=(($langopts271+249)&4294967295);HEAP8[($spelling_stress272)]=1;var $187=$tr;var $langopts273=(($187)&4294967295);var $accents274=(($langopts273+220)&4294967295);HEAP32[(($accents274)>>2)]=1;var $188=$tr;var $langopts275=(($188)&4294967295);var $numbers276=(($langopts275+184)&4294967295);HEAP32[(($numbers276)>>2)]=33572172;var $189=$tr;var $langopts277=(($189)&4294967295);var $numbers2278=(($langopts277+188)&4294967295);HEAP32[(($numbers2278)>>2)]=74;var $190=$tr;var $langopts279=(($190)&4294967295);var $replace_chars=(($langopts279+264)&4294967295);HEAP32[(($replace_chars)>>2)]=((__ZL22replace_cyrillic_latin)&4294967295);var $191=$tr;__ZL14SetLetterVowelP10Translatori($191,121);var $192=$tr;__ZL14SetLetterVowelP10Translatori($192,114);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==33){var $193=$tr;var $langopts281=(($193)&4294967295);var $stress_rule282=(($langopts281+8)&4294967295);HEAP32[(($stress_rule282)>>2)]=3;var $194=$tr;var $langopts283=(($194)&4294967295);var $stress_flags284=(($langopts283+12)&4294967295);HEAP32[(($stress_flags284)>>2)]=36;var $195=$tr;var $langopts285=(($195)&4294967295);var $numbers286=(($langopts285+184)&4294967295);HEAP32[(($numbers286)>>2)]=17990912;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==34){var $196=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($196,((__ZZ16SelectTranslatorPKcE17stress_lengths_hu)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_hu)&4294967295));var $197=HEAP32[((((_charsets+8)&4294967295))>>2)];var $198=$tr;var $charset_a0288=(($198+696)&4294967295);HEAP32[(($charset_a0288)>>2)]=$197;var $199=$tr;var $langopts289=(($199)&4294967295);var $vowel_pause290=(($langopts289+4)&4294967295);HEAP32[(($vowel_pause290)>>2)]=32;var $200=$tr;var $langopts291=(($200)&4294967295);var $stress_rule292=(($langopts291+8)&4294967295);HEAP32[(($stress_rule292)>>2)]=0;var $201=$tr;var $langopts293=(($201)&4294967295);var $stress_flags294=(($langopts293+12)&4294967295);HEAP32[(($stress_flags294)>>2)]=1081398;var $202=$tr;var $langopts295=(($202)&4294967295);var $unstressed_wd1296=(($langopts295+16)&4294967295);HEAP32[(($unstressed_wd1296)>>2)]=2;var $203=$tr;var $langopts297=(($203)&4294967295);var $param298=(($langopts297+24)&4294967295);var $arrayidx299=(($param298+56)&4294967295);HEAP32[(($arrayidx299)>>2)]=1;var $204=$tr;var $langopts300=(($204)&4294967295);var $param301=(($langopts300+24)&4294967295);var $arrayidx302=(($param301+68)&4294967295);HEAP32[(($arrayidx302)>>2)]=2;var $205=$tr;var $langopts303=(($205)&4294967295);var $numbers304=(($langopts303+184)&4294967295);HEAP32[(($numbers304)>>2)]=186758144;var $206=$tr;var $langopts305=(($206)&4294967295);var $thousands_sep306=(($langopts305+204)&4294967295);HEAP32[(($thousands_sep306)>>2)]=32;var $207=$tr;var $langopts307=(($207)&4294967295);var $decimal_sep=(($langopts307+208)&4294967295);HEAP32[(($decimal_sep)>>2)]=44;var $208=$tr;var $langopts308=(($208)&4294967295);var $max_roman=(($langopts308+196)&4294967295);HEAP32[(($max_roman)>>2)]=899;var $209=$tr;var $langopts309=(($209)&4294967295);var $min_roman=(($langopts309+200)&4294967295);HEAP32[(($min_roman)>>2)]=1;var $210=$tr;__ZL14SetLetterVowelP10Translatori($210,121);var $211=$tr;var $langopts310=(($211)&4294967295);var $spelling_stress311=(($langopts310+249)&4294967295);HEAP8[($spelling_stress311)]=1;var $212=$tr;__Z13SetLengthModsP10Translatori($212,3);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==35){var $213=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($213,((__ZZ16SelectTranslatorPKcE17stress_lengths_hy)&4294967295),0);var $214=$tr;var $langopts313=(($214)&4294967295);var $stress_rule314=(($langopts313+8)&4294967295);HEAP32[(($stress_rule314)>>2)]=3;var $215=$tr;var $letter_bits_offset315=(($215+964)&4294967295);HEAP32[(($letter_bits_offset315)>>2)]=1328;var $216=$tr;var $letter_bits316=(($216+708)&4294967295);var $arraydecay317=(($letter_bits316)&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arraydecay317;$stop$=$dest$+256;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $217=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($217,0,((__ZZ16SelectTranslatorPKcE9hy_vowels)&4294967295));var $218=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($218,7,((__ZZ16SelectTranslatorPKcE9hy_vowels)&4294967295));var $219=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($219,2,((__ZZ16SelectTranslatorPKcE13hy_consonants)&4294967295));var $220=$tr;var $langopts318=(($220)&4294967295);var $max_initial_consonants319=(($langopts318+248)&4294967295);HEAP8[($max_initial_consonants319)]=6;var $221=$tr;var $langopts320=(($221)&4294967295);var $numbers321=(($langopts320+184)&4294967295);HEAP32[(($numbers321)>>2)]=1032;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==36){var $222=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($222,((__ZZ16SelectTranslatorPKcE17stress_lengths_id)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_id)&4294967295));var $223=$tr;var $langopts323=(($223)&4294967295);var $stress_rule324=(($langopts323+8)&4294967295);HEAP32[(($stress_rule324)>>2)]=2;var $224=$tr;var $langopts325=(($224)&4294967295);var $numbers326=(($langopts325+184)&4294967295);HEAP32[(($numbers326)>>2)]=16781320;var $225=$tr;var $langopts327=(($225)&4294967295);var $stress_flags328=(($langopts327+12)&4294967295);HEAP32[(($stress_flags328)>>2)]=22;var $226=$tr;var $langopts329=(($226)&4294967295);var $accents330=(($langopts329+220)&4294967295);HEAP32[(($accents330)>>2)]=2;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==37){var $227=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($227,((__ZZ16SelectTranslatorPKcE17stress_lengths_is)&4294967295),0);var $228=$tr;var $langopts332=(($228)&4294967295);var $stress_rule333=(($langopts332+8)&4294967295);HEAP32[(($stress_rule333)>>2)]=0;var $229=$tr;var $langopts334=(($229)&4294967295);var $stress_flags335=(($langopts334+12)&4294967295);HEAP32[(($stress_flags335)>>2)]=16;var $230=$tr;var $langopts336=(($230)&4294967295);var $param337=(($langopts336+24)&4294967295);var $arrayidx338=(($param337+8)&4294967295);HEAP32[(($arrayidx338)>>2)]=17;var $231=$tr;var $langopts339=(($231)&4294967295);var $param340=(($langopts339+24)&4294967295);var $arrayidx341=(($param340+40)&4294967295);HEAP32[(($arrayidx341)>>2)]=2;var $232=$tr;__ZL15ResetLetterBitsP10Translatori($232,24);var $233=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($233,4,((__str1631)&4294967295));var $234=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($234,3,((__str2632)&4294967295));var $235=$tr;var $letter_groups=(($235+968)&4294967295);var $arrayidx342=(($letter_groups+4)&4294967295);HEAP32[(($arrayidx342)>>2)]=((__ZZ16SelectTranslatorPKcE16is_lettergroup_B)&4294967295);var $236=$tr;__ZL14SetLetterVowelP10Translatori($236,121);var $237=$tr;var $langopts343=(($237)&4294967295);var $numbers344=(($langopts343+184)&4294967295);HEAP32[(($numbers344)>>2)]=2280;var $238=$tr;var $langopts345=(($238)&4294967295);var $numbers2346=(($langopts345+188)&4294967295);HEAP32[(($numbers2346)>>2)]=2;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==38){var $239=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($239,((__ZZ16SelectTranslatorPKcE17stress_lengths_it)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_it)&4294967295));var $240=$tr;var $langopts348=(($240)&4294967295);var $length_mods349=(($langopts348+176)&4294967295);var $241=HEAP32[(($length_mods349)>>2)];var $242=$tr;var $langopts350=(($242)&4294967295);var $length_mods0351=(($langopts350+180)&4294967295);HEAP32[(($length_mods0351)>>2)]=$241;var $243=$tr;var $langopts352=(($243)&4294967295);var $stress_rule353=(($langopts352+8)&4294967295);HEAP32[(($stress_rule353)>>2)]=2;var $244=$tr;var $langopts354=(($244)&4294967295);var $stress_flags355=(($langopts354+12)&4294967295);HEAP32[(($stress_flags355)>>2)]=131088;var $245=$tr;var $langopts356=(($245)&4294967295);var $vowel_pause357=(($langopts356+4)&4294967295);HEAP32[(($vowel_pause357)>>2)]=1;var $246=$tr;var $langopts358=(($246)&4294967295);var $unstressed_wd1359=(($langopts358+16)&4294967295);HEAP32[(($unstressed_wd1359)>>2)]=2;var $247=$tr;var $langopts360=(($247)&4294967295);var $unstressed_wd2361=(($langopts360+20)&4294967295);HEAP32[(($unstressed_wd2361)>>2)]=2;var $248=$tr;var $langopts362=(($248)&4294967295);var $param363=(($langopts362+24)&4294967295);var $arrayidx364=(($param363+8)&4294967295);HEAP32[(($arrayidx364)>>2)]=2;var $249=$tr;var $langopts365=(($249)&4294967295);var $param366=(($langopts365+24)&4294967295);var $arrayidx367=(($param366+56)&4294967295);HEAP32[(($arrayidx367)>>2)]=2;var $250=$tr;var $langopts368=(($250)&4294967295);var $param369=(($langopts368+24)&4294967295);var $arrayidx370=(($param369+28)&4294967295);HEAP32[(($arrayidx370)>>2)]=130;var $251=$tr;var $langopts371=(($251)&4294967295);var $param372=(($langopts371+24)&4294967295);var $arrayidx373=(($param372+40)&4294967295);HEAP32[(($arrayidx373)>>2)]=1;var $252=$tr;var $langopts374=(($252)&4294967295);var $param375=(($langopts374+24)&4294967295);var $arrayidx376=(($param375+60)&4294967295);HEAP32[(($arrayidx376)>>2)]=2;var $253=$tr;var $langopts377=(($253)&4294967295);var $numbers378=(($langopts377+184)&4294967295);HEAP32[(($numbers378)>>2)]=16786952;var $254=$tr;var $langopts379=(($254)&4294967295);var $accents380=(($langopts379+220)&4294967295);HEAP32[(($accents380)>>2)]=2;var $255=$tr;__ZL14SetLetterVowelP10Translatori($255,121);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==39){var $256=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($256,((__ZZ16SelectTranslatorPKcE18stress_lengths_jbo)&4294967295),0);var $257=$tr;var $langopts382=(($257)&4294967295);var $stress_rule383=(($langopts382+8)&4294967295);HEAP32[(($stress_rule383)>>2)]=2;var $258=$tr;var $langopts384=(($258)&4294967295);var $vowel_pause385=(($langopts384+4)&4294967295);HEAP32[(($vowel_pause385)>>2)]=524;var $259=$tr;var $punct_within_word386=(($259+704)&4294967295);HEAP32[(($punct_within_word386)>>2)]=((__ZZ16SelectTranslatorPKcE21jbo_punct_within_word)&4294967295);var $260=$tr;var $langopts387=(($260)&4294967295);var $param388=(($langopts387+24)&4294967295);var $arrayidx389=(($param388+52)&4294967295);HEAP32[(($arrayidx389)>>2)]=2;var $261=$tr;__ZL14SetLetterVowelP10Translatori($261,121);var $262=$tr;var $langopts390=(($262)&4294967295);var $max_lengthmod=(($langopts390+272)&4294967295);HEAP32[(($max_lengthmod)>>2)]=368;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==40){var $263=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($263,((__ZZ16SelectTranslatorPKcE17stress_lengths_ta)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_ta)&4294967295));var $264=$tr;var $letter_bits392=(($264+708)&4294967295);var $arraydecay393=(($letter_bits392)&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arraydecay393;$stop$=$dest$+256;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $265=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($265,0,((__ZZ16SelectTranslatorPKcE9ka_vowels)&4294967295));var $266=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($266,2,((__ZZ16SelectTranslatorPKcE13ka_consonants)&4294967295));var $267=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($267,7,((__ZZ16SelectTranslatorPKcE9ka_vowels)&4294967295));var $268=$tr;var $langopts394=(($268)&4294967295);var $stress_rule395=(($langopts394+8)&4294967295);HEAP32[(($stress_rule395)>>2)]=0;var $269=$tr;var $langopts396=(($269)&4294967295);var $stress_flags397=(($langopts396+12)&4294967295);HEAP32[(($stress_flags397)>>2)]=16;var $270=$tr;var $letter_bits_offset398=(($270+964)&4294967295);HEAP32[(($letter_bits_offset398)>>2)]=4224;var $271=$tr;var $langopts399=(($271)&4294967295);var $max_initial_consonants400=(($langopts399+248)&4294967295);HEAP8[($max_initial_consonants400)]=7;var $272=$tr;var $langopts401=(($272)&4294967295);var $numbers402=(($langopts401+184)&4294967295);HEAP32[(($numbers402)>>2)]=3187744;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==41){var $273=$tr;var $letter_bits_offset404=(($273+964)&4294967295);HEAP32[(($letter_bits_offset404)>>2)]=4352;var $274=$tr;var $letter_bits405=(($274+708)&4294967295);var $arraydecay406=(($letter_bits405)&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arraydecay406;$stop$=$dest$+256;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $275=$tr;__ZL18SetLetterBitsRangeP10Translatoriii($275,0,97,117);var $276=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($276,6,((__ZZ16SelectTranslatorPKcE10ko_ivowels)&4294967295));var $277=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($277,5,((__ZZ16SelectTranslatorPKcE9ko_voiced)&4294967295));var $278=$tr;var $langopts407=(($278)&4294967295);var $stress_rule408=(($langopts407+8)&4294967295);HEAP32[(($stress_rule408)>>2)]=8;var $279=$tr;var $langopts409=(($279)&4294967295);var $param410=(($langopts409+24)&4294967295);var $arrayidx411=(($param410+20)&4294967295);HEAP32[(($arrayidx411)>>2)]=1;var $280=$tr;var $langopts412=(($280)&4294967295);var $numbers413=(($langopts412+184)&4294967295);HEAP32[(($numbers413)>>2)]=1024;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==42){var $281=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($281,((__ZZ16SelectTranslatorPKcE17stress_lengths_ku)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_ku)&4294967295));var $282=HEAP32[((((_charsets+36)&4294967295))>>2)];var $283=$tr;var $charset_a0415=(($283+696)&4294967295);HEAP32[(($charset_a0415)>>2)]=$282;var $284=$tr;var $langopts416=(($284)&4294967295);var $stress_rule417=(($langopts416+8)&4294967295);HEAP32[(($stress_rule417)>>2)]=7;var $285=$tr;var $langopts418=(($285)&4294967295);var $numbers419=(($langopts418+184)&4294967295);HEAP32[(($numbers419)>>2)]=263264;var $286=$tr;var $langopts420=(($286)&4294967295);var $max_initial_consonants421=(($langopts420+248)&4294967295);HEAP8[($max_initial_consonants421)]=2;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==43){var $287=HEAP32[((((_charsets+16)&4294967295))>>2)];var $288=$tr;var $charset_a0423=(($288+696)&4294967295);HEAP32[(($charset_a0423)>>2)]=$287;var $289=$tr;var $langopts424=(($289)&4294967295);var $stress_rule425=(($langopts424+8)&4294967295);HEAP32[(($stress_rule425)>>2)]=2;var $290=$tr;var $langopts426=(($290)&4294967295);var $stress_flags427=(($langopts426+12)&4294967295);HEAP32[(($stress_flags427)>>2)]=32;var $291=$tr;var $langopts428=(($291)&4294967295);var $unstressed_wd1429=(($langopts428+16)&4294967295);HEAP32[(($unstressed_wd1429)>>2)]=0;var $292=$tr;var $langopts430=(($292)&4294967295);var $unstressed_wd2431=(($langopts430+20)&4294967295);HEAP32[(($unstressed_wd2431)>>2)]=2;var $293=$tr;var $langopts432=(($293)&4294967295);var $param433=(($langopts432+24)&4294967295);var $arrayidx434=(($param433+4)&4294967295);HEAP32[(($arrayidx434)>>2)]=1;var $294=$tr;var $langopts435=(($294)&4294967295);var $numbers436=(($langopts435+184)&4294967295);HEAP32[(($numbers436)>>2)]=16777216;var $295=$tr;var $langopts437=(($295)&4294967295);var $max_roman438=(($langopts437+196)&4294967295);HEAP32[(($max_roman438)>>2)]=5000;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==44){var $296=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($296,((__ZZ16SelectTranslatorPKcE17stress_lengths_lv)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_lv)&4294967295));var $297=$tr;var $langopts440=(($297)&4294967295);var $stress_rule441=(($langopts440+8)&4294967295);HEAP32[(($stress_rule441)>>2)]=0;var $298=$tr;var $langopts442=(($298)&4294967295);var $spelling_stress443=(($langopts442+249)&4294967295);HEAP8[($spelling_stress443)]=1;var $299=HEAP32[((((_charsets+16)&4294967295))>>2)];var $300=$tr;var $charset_a0444=(($300+696)&4294967295);HEAP32[(($charset_a0444)>>2)]=$299;var $301=$tr;var $langopts445=(($301)&4294967295);var $numbers446=(($langopts445+184)&4294967295);HEAP32[(($numbers446)>>2)]=99336;var $302=$tr;var $langopts447=(($302)&4294967295);var $stress_flags448=(($langopts447+12)&4294967295);HEAP32[(($stress_flags448)>>2)]=262166;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==45){var $303=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($303,((__ZZ16SelectTranslatorPKcE17stress_lengths_mk)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_mk)&4294967295));var $304=HEAP32[((((_charsets+20)&4294967295))>>2)];var $305=$tr;var $charset_a0450=(($305+696)&4294967295);HEAP32[(($charset_a0450)>>2)]=$304;var $306=$tr;var $letter_groups451=(($306+968)&4294967295);var $arrayidx452=(($letter_groups451+28)&4294967295);HEAP32[(($arrayidx452)>>2)]=((__ZZ16SelectTranslatorPKcE15vowels_cyrillic)&4294967295);var $307=$tr;var $letter_groups453=(($307+968)&4294967295);var $arrayidx454=(($letter_groups453)&4294967295);HEAP32[(($arrayidx454)>>2)]=((__ZZ16SelectTranslatorPKcE15vowels_cyrillic)&4294967295);var $308=$tr;var $langopts455=(($308)&4294967295);var $stress_rule456=(($langopts455+8)&4294967295);HEAP32[(($stress_rule456)>>2)]=4;var $309=$tr;var $langopts457=(($309)&4294967295);var $numbers458=(($langopts457+184)&4294967295);HEAP32[(($numbers458)>>2)]=2114600;var $310=$tr;var $langopts459=(($310)&4294967295);var $numbers2460=(($langopts459+188)&4294967295);HEAP32[(($numbers2460)>>2)]=138;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==46){var $311=$tr;var $langopts462=(($311)&4294967295);var $stress_rule463=(($langopts462+8)&4294967295);HEAP32[(($stress_rule463)>>2)]=0;var $312=$tr;var $langopts464=(($312)&4294967295);var $vowel_pause465=(($langopts464+4)&4294967295);HEAP32[(($vowel_pause465)>>2)]=48;var $313=$tr;var $langopts466=(($313)&4294967295);var $param467=(($langopts466+24)&4294967295);var $arrayidx468=(($param467+4)&4294967295);HEAP32[(($arrayidx468)>>2)]=1;var $314=$tr;var $langopts469=(($314)&4294967295);var $param470=(($langopts469+24)&4294967295);var $arrayidx471=(($param470+12)&4294967295);HEAP32[(($arrayidx471)>>2)]=1;var $315=$tr;var $langopts472=(($315)&4294967295);var $param473=(($langopts472+24)&4294967295);var $arrayidx474=(($param473+16)&4294967295);HEAP32[(($arrayidx474)>>2)]=16;var $316=$tr;__ZL14SetLetterVowelP10Translatori($316,121);var $317=$tr;var $langopts475=(($317)&4294967295);var $numbers476=(($langopts475+184)&4294967295);HEAP32[(($numbers476)>>2)]=2169880;var $318=$tr;var $langopts477=(($318)&4294967295);var $ordinal_indicator=(($langopts477+216)&4294967295);HEAP32[(($ordinal_indicator)>>2)]=((__str3633)&4294967295);var $319=$tr;var $langopts478=(($319)&4294967295);var $stress_flags479=(($langopts478+12)&4294967295);HEAP32[(($stress_flags479)>>2)]=128;var $320=$tr;var $stress_lengths=(($320+676)&4294967295);var $arraydecay480=(($stress_lengths)&4294967295);var $321=$arraydecay480;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=__ZZ16SelectTranslatorPKcE17stress_lengths_nl;$dest$=$321;$stop$=$src$+16;if(($dest$%4)==($src$%4)&&16>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==47){var $322=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($322,((__ZZ16SelectTranslatorPKcE17stress_lengths_no)&4294967295),0);var $323=$tr;var $langopts482=(($323)&4294967295);var $stress_rule483=(($langopts482+8)&4294967295);HEAP32[(($stress_rule483)>>2)]=0;var $324=$tr;__ZL14SetLetterVowelP10Translatori($324,121);var $325=$tr;var $langopts484=(($325)&4294967295);var $numbers485=(($langopts484+184)&4294967295);HEAP32[(($numbers485)>>2)]=71752;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==48){var $326=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($326,((__ZZ16SelectTranslatorPKcE17stress_lengths_om)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_om)&4294967295));var $327=$tr;var $langopts487=(($327)&4294967295);var $stress_rule488=(($langopts487+8)&4294967295);HEAP32[(($stress_rule488)>>2)]=2;var $328=$tr;var $langopts489=(($328)&4294967295);var $stress_flags490=(($langopts489+12)&4294967295);HEAP32[(($stress_flags490)>>2)]=524310;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==49){var $329=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($329,((__ZZ16SelectTranslatorPKcE17stress_lengths_pl)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_pl)&4294967295));var $330=HEAP32[((((_charsets+8)&4294967295))>>2)];var $331=$tr;var $charset_a0492=(($331+696)&4294967295);HEAP32[(($charset_a0492)>>2)]=$330;var $332=$tr;var $langopts493=(($332)&4294967295);var $stress_rule494=(($langopts493+8)&4294967295);HEAP32[(($stress_rule494)>>2)]=2;var $333=$tr;var $langopts495=(($333)&4294967295);var $stress_flags496=(($langopts495+12)&4294967295);HEAP32[(($stress_flags496)>>2)]=6;var $334=$tr;var $langopts497=(($334)&4294967295);var $param498=(($langopts497+24)&4294967295);var $arrayidx499=(($param498+16)&4294967295);HEAP32[(($arrayidx499)>>2)]=8;var $335=$tr;var $langopts500=(($335)&4294967295);var $max_initial_consonants501=(($langopts500+248)&4294967295);HEAP8[($max_initial_consonants501)]=7;var $336=$tr;var $langopts502=(($336)&4294967295);var $numbers503=(($langopts502+184)&4294967295);HEAP32[(($numbers503)>>2)]=20488;var $337=$tr;var $langopts504=(($337)&4294967295);var $numbers2505=(($langopts504+188)&4294967295);HEAP32[(($numbers2505)>>2)]=64;var $338=$tr;var $langopts506=(($338)&4294967295);var $param507=(($langopts506+24)&4294967295);var $arrayidx508=(($param507+44)&4294967295);HEAP32[(($arrayidx508)>>2)]=260;var $339=$tr;__ZL14SetLetterVowelP10Translatori($339,121);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==50){var $340=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($340,((__ZZ16SelectTranslatorPKcE17stress_lengths_pt)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_pt)&4294967295));var $341=$tr;var $langopts510=(($341)&4294967295);var $length_mods511=(($langopts510+176)&4294967295);var $342=HEAP32[(($length_mods511)>>2)];var $343=$tr;var $langopts512=(($343)&4294967295);var $length_mods0513=(($langopts512+180)&4294967295);HEAP32[(($length_mods0513)>>2)]=$342;var $344=$tr;var $langopts514=(($344)&4294967295);var $stress_rule515=(($langopts514+8)&4294967295);HEAP32[(($stress_rule515)>>2)]=3;var $345=$tr;var $langopts516=(($345)&4294967295);var $stress_flags517=(($langopts516+12)&4294967295);HEAP32[(($stress_flags517)>>2)]=139286;var $346=$tr;var $langopts518=(($346)&4294967295);var $numbers519=(($langopts518+184)&4294967295);HEAP32[(($numbers519)>>2)]=16793704;var $347=$tr;__ZL14SetLetterVowelP10Translatori($347,121);var $348=$tr;__ZL15ResetLetterBitsP10Translatori($348,2);var $349=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($349,1,((__str4634)&4294967295));var $350=$tr;var $langopts520=(($350)&4294967295);var $param521=(($langopts520+24)&4294967295);var $arrayidx522=(($param521+60)&4294967295);HEAP32[(($arrayidx522)>>2)]=2;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==51){var $351=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($351,((__ZZ16SelectTranslatorPKcE17stress_lengths_ro)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_ro)&4294967295));var $352=$tr;var $langopts524=(($352)&4294967295);var $stress_rule525=(($langopts524+8)&4294967295);HEAP32[(($stress_rule525)>>2)]=2;var $353=$tr;var $langopts526=(($353)&4294967295);var $stress_flags527=(($langopts526+12)&4294967295);HEAP32[(($stress_flags527)>>2)]=262;var $354=HEAP32[((((_charsets+8)&4294967295))>>2)];var $355=$tr;var $charset_a0528=(($355+696)&4294967295);HEAP32[(($charset_a0528)>>2)]=$354;var $356=$tr;var $langopts529=(($356)&4294967295);var $numbers530=(($langopts529+184)&4294967295);HEAP32[(($numbers530)>>2)]=16805928;var $357=$tr;var $langopts531=(($357)&4294967295);var $numbers2532=(($langopts531+188)&4294967295);HEAP32[(($numbers2532)>>2)]=30;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==52){var $358=$tr;__ZL18Translator_RussianP10Translator($358);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==53){var $359=$tr;var $langopts535=(($359)&4294967295);var $stress_rule536=(($langopts535+8)&4294967295);HEAP32[(($stress_rule536)>>2)]=2;var $360=$tr;var $langopts537=(($360)&4294967295);var $stress_flags538=(($langopts537+12)&4294967295);HEAP32[(($stress_flags538)>>2)]=22;var $361=$tr;var $langopts539=(($361)&4294967295);var $length_mods540=(($langopts539+176)&4294967295);var $362=HEAP32[(($length_mods540)>>2)];var $363=$tr;var $langopts541=(($363)&4294967295);var $length_mods0542=(($langopts541+180)&4294967295);HEAP32[(($length_mods0542)>>2)]=$362;var $364=$tr;var $langopts543=(($364)&4294967295);var $numbers544=(($langopts543+184)&4294967295);HEAP32[(($numbers544)>>2)]=278624;var $365=$tr;var $langopts545=(($365)&4294967295);var $numbers2546=(($langopts545+188)&4294967295);HEAP32[(($numbers2546)>>2)]=512;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==54){var $366=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($366,((__ZZ16SelectTranslatorPKcE17stress_lengths_sk)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_sk)&4294967295));var $367=HEAP32[((((_charsets+8)&4294967295))>>2)];var $368=$tr;var $charset_a0548=(($368+696)&4294967295);HEAP32[(($charset_a0548)>>2)]=$367;var $369=$tr;var $langopts549=(($369)&4294967295);var $stress_rule550=(($langopts549+8)&4294967295);HEAP32[(($stress_rule550)>>2)]=0;var $370=$tr;var $langopts551=(($370)&4294967295);var $stress_flags552=(($langopts551+12)&4294967295);HEAP32[(($stress_flags552)>>2)]=22;var $371=$tr;var $langopts553=(($371)&4294967295);var $param554=(($langopts553+24)&4294967295);var $arrayidx555=(($param554+16)&4294967295);HEAP32[(($arrayidx555)>>2)]=3;var $372=$tr;var $langopts556=(($372)&4294967295);var $max_initial_consonants557=(($langopts556+248)&4294967295);HEAP8[($max_initial_consonants557)]=5;var $373=$tr;var $langopts558=(($373)&4294967295);var $spelling_stress559=(($langopts558+249)&4294967295);HEAP8[($spelling_stress559)]=1;var $374=$tr;var $langopts560=(($374)&4294967295);var $param561=(($langopts560+24)&4294967295);var $arrayidx562=(($param561+44)&4294967295);HEAP32[(($arrayidx562)>>2)]=4;var $375=$tr;var $langopts563=(($375)&4294967295);var $numbers564=(($langopts563+184)&4294967295);HEAP32[(($numbers564)>>2)]=16794624;var $376=$tr;var $langopts565=(($376)&4294967295);var $numbers2566=(($langopts565+188)&4294967295);HEAP32[(($numbers2566)>>2)]=256;var $377=$tr;var $langopts567=(($377)&4294967295);var $thousands_sep568=(($langopts567+204)&4294967295);HEAP32[(($thousands_sep568)>>2)]=0;var $378=$tr;var $langopts569=(($378)&4294967295);var $decimal_sep570=(($langopts569+208)&4294967295);HEAP32[(($decimal_sep570)>>2)]=44;var $379=$name2;var $cmp571=((($379))|0)==25459;if($cmp571){__label__=55;;}else{__label__=56;;}
if(__label__==55){var $380=$tr;var $langopts573=(($380)&4294967295);var $numbers2574=(($langopts573+188)&4294967295);HEAP32[(($numbers2574)>>2)]=264;;}
var $381=$tr;__ZL14SetLetterVowelP10Translatori($381,121);var $382=$tr;__ZL14SetLetterVowelP10Translatori($382,114);var $383=$tr;__ZL15ResetLetterBitsP10Translatori($383,32);var $384=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($384,5,((__str5635)&4294967295));__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==57){var $385=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($385,((__ZZ16SelectTranslatorPKcE17stress_lengths_ta)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_ta)&4294967295));var $386=$tr;var $langopts577=(($386)&4294967295);var $length_mods578=(($langopts577+176)&4294967295);var $387=HEAP32[(($length_mods578)>>2)];var $388=$tr;var $langopts579=(($388)&4294967295);var $length_mods0580=(($langopts579+180)&4294967295);HEAP32[(($length_mods0580)>>2)]=$387;var $389=$tr;var $langopts581=(($389)&4294967295);var $stress_rule582=(($langopts581+8)&4294967295);HEAP32[(($stress_rule582)>>2)]=0;var $390=$tr;var $langopts583=(($390)&4294967295);var $stress_flags584=(($langopts583+12)&4294967295);HEAP32[(($stress_flags584)>>2)]=65556;var $391=$tr;var $langopts585=(($391)&4294967295);var $spelling_stress586=(($langopts585+249)&4294967295);HEAP8[($spelling_stress586)]=1;var $392=$tr;var $letter_bits_offset587=(($392+964)&4294967295);HEAP32[(($letter_bits_offset587)>>2)]=3456;var $393=$tr;var $letter_bits588=(($393+708)&4294967295);var $arraydecay589=(($letter_bits588)&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arraydecay589;$stop$=$dest$+256;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $394=$tr;__ZL18SetLetterBitsRangeP10Translatoriii($394,0,5,22);var $395=$tr;__ZL18SetLetterBitsRangeP10Translatoriii($395,0,74,115);var $396=$tr;__ZL18SetLetterBitsRangeP10Translatoriii($396,1,74,115);var $397=$tr;__ZL18SetLetterBitsRangeP10Translatoriii($397,2,26,70);var $398=$tr;var $langopts590=(($398)&4294967295);var $param591=(($langopts590+24)&4294967295);var $arrayidx592=(($param591+20)&4294967295);HEAP32[(($arrayidx592)>>2)]=1;var $399=$tr;var $letter_bits_offset593=(($399+964)&4294967295);var $400=HEAP32[(($letter_bits_offset593)>>2)];var $add594=((($400)+74)&4294967295);var $401=$tr;var $langopts595=(($401)&4294967295);var $suffix_add_e596=(($langopts595+276)&4294967295);HEAP32[(($suffix_add_e596)>>2)]=$add594;var $402=$tr;var $langopts597=(($402)&4294967295);var $numbers598=(($langopts597+184)&4294967295);HEAP32[(($numbers598)>>2)]=2097152;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==58){var $403=HEAP32[((((_charsets+8)&4294967295))>>2)];var $404=$tr;var $charset_a0600=(($404+696)&4294967295);HEAP32[(($charset_a0600)>>2)]=$403;var $405=$tr;var $langopts601=(($405)&4294967295);var $stress_rule602=(($langopts601+8)&4294967295);HEAP32[(($stress_rule602)>>2)]=2;var $406=$tr;var $langopts603=(($406)&4294967295);var $stress_flags604=(($langopts603+12)&4294967295);HEAP32[(($stress_flags604)>>2)]=32;var $407=$tr;var $langopts605=(($407)&4294967295);var $param606=(($langopts605+24)&4294967295);var $arrayidx607=(($param606+16)&4294967295);HEAP32[(($arrayidx607)>>2)]=19;var $408=$tr;var $langopts608=(($408)&4294967295);var $numbers609=(($langopts608+184)&4294967295);HEAP32[(($numbers609)>>2)]=16864280;var $409=$tr;var $langopts610=(($409)&4294967295);var $numbers2611=(($langopts610+188)&4294967295);HEAP32[(($numbers2611)>>2)]=256;var $410=$tr;var $langopts612=(($410)&4294967295);var $thousands_sep613=(($langopts612+204)&4294967295);HEAP32[(($thousands_sep613)>>2)]=32;var $411=$tr;__ZL14SetLetterVowelP10Translatori($411,114);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==59){var $412=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($412,((__ZZ16SelectTranslatorPKcE17stress_lengths_sq)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_sq)&4294967295));var $413=$tr;var $langopts615=(($413)&4294967295);var $stress_rule616=(($langopts615+8)&4294967295);HEAP32[(($stress_rule616)>>2)]=2;var $414=$tr;var $langopts617=(($414)&4294967295);var $stress_flags618=(($langopts617+12)&4294967295);HEAP32[(($stress_flags618)>>2)]=278;var $415=$tr;__ZL14SetLetterVowelP10Translatori($415,121);var $416=$tr;var $langopts619=(($416)&4294967295);var $numbers620=(($langopts619+184)&4294967295);HEAP32[(($numbers620)>>2)]=32872;var $417=$tr;var $langopts621=(($417)&4294967295);var $accents622=(($langopts621+220)&4294967295);HEAP32[(($accents622)>>2)]=2;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==60){var $418=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($418,((__ZZ16SelectTranslatorPKcE17stress_lengths_sv)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_sv)&4294967295));var $419=$tr;var $langopts624=(($419)&4294967295);var $stress_rule625=(($langopts624+8)&4294967295);HEAP32[(($stress_rule625)>>2)]=0;var $420=$tr;__ZL14SetLetterVowelP10Translatori($420,121);var $421=$tr;var $langopts626=(($421)&4294967295);var $numbers627=(($langopts626+184)&4294967295);HEAP32[(($numbers627)>>2)]=6408;var $422=$tr;var $langopts628=(($422)&4294967295);var $accents629=(($langopts628+220)&4294967295);HEAP32[(($accents629)>>2)]=1;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==61){var $423=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($423,((__ZZ16SelectTranslatorPKcE17stress_lengths_sw)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_sw)&4294967295));var $424=$tr;var $langopts631=(($424)&4294967295);var $length_mods632=(($langopts631+176)&4294967295);var $425=HEAP32[(($length_mods632)>>2)];var $426=$tr;var $langopts633=(($426)&4294967295);var $length_mods0634=(($langopts633+180)&4294967295);HEAP32[(($length_mods0634)>>2)]=$425;var $427=$tr;var $langopts635=(($427)&4294967295);var $vowel_pause636=(($langopts635+4)&4294967295);HEAP32[(($vowel_pause636)>>2)]=1;var $428=$tr;var $langopts637=(($428)&4294967295);var $stress_rule638=(($langopts637+8)&4294967295);HEAP32[(($stress_rule638)>>2)]=2;var $429=$tr;var $langopts639=(($429)&4294967295);var $stress_flags640=(($langopts639+12)&4294967295);HEAP32[(($stress_flags640)>>2)]=22;var $430=$tr;var $langopts641=(($430)&4294967295);var $numbers642=(($langopts641+184)&4294967295);HEAP32[(($numbers642)>>2)]=1248;var $431=$tr;var $langopts643=(($431)&4294967295);var $break_numbers644=(($langopts643+192)&4294967295);HEAP32[(($break_numbers644)>>2)]=1227133544;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==62){var $432=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($432,((__ZZ16SelectTranslatorPKcE17stress_lengths_ta)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_ta)&4294967295));var $433=$tr;var $langopts646=(($433)&4294967295);var $length_mods647=(($langopts646+176)&4294967295);var $434=HEAP32[(($length_mods647)>>2)];var $435=$tr;var $langopts648=(($435)&4294967295);var $length_mods0649=(($langopts648+180)&4294967295);HEAP32[(($length_mods0649)>>2)]=$434;var $436=$tr;var $langopts650=(($436)&4294967295);var $stress_rule651=(($langopts650+8)&4294967295);HEAP32[(($stress_rule651)>>2)]=0;var $437=$tr;var $langopts652=(($437)&4294967295);var $stress_flags653=(($langopts652+12)&4294967295);HEAP32[(($stress_flags653)>>2)]=65540;var $438=$tr;var $langopts654=(($438)&4294967295);var $spelling_stress655=(($langopts654+249)&4294967295);HEAP8[($spelling_stress655)]=1;var $439=$tr;var $langopts656=(($439)&4294967295);var $break_numbers657=(($langopts656+192)&4294967295);HEAP32[(($break_numbers657)>>2)]=5288;var $440=$name2;var $cmp658=((($440))|0)==29793;if($cmp658){__lastLabel__=62;__label__=63;;}else{__lastLabel__=62;__label__=64;;}
if(__label__==63){var $441=$tr;var $letter_bits_offset660=(($441+964)&4294967295);HEAP32[(($letter_bits_offset660)>>2)]=2944;var $442=$tr;var $langopts661=(($442)&4294967295);var $numbers662=(($langopts661+184)&4294967295);HEAP32[(($numbers662)>>2)]=2097152;var $_pr=$name2;__lastLabel__=63;;}
var $443=__lastLabel__==63?$_pr:($440);var $cmp664=((($443))|0)==28018;if($cmp664){__label__=65;;}else{__label__=66;;}
$if_then665$$if_else667$75:do{if(__label__==65){var $444=$tr;var $letter_bits_offset666=(($444+964)&4294967295);HEAP32[(($letter_bits_offset666)>>2)]=2304;;}
else if(__label__==66){var $445=$name2;var $cmp668=((($445))|0)==28012;if($cmp668){__label__=67;;}else{__label__=68;;}
if(__label__==67){var $446=$tr;var $letter_bits_offset670=(($446+964)&4294967295);HEAP32[(($letter_bits_offset670)>>2)]=3328;var $447=$tr;var $langopts671=(($447)&4294967295);var $numbers672=(($langopts671+184)&4294967295);HEAP32[(($numbers672)>>2)]=2097152;;}
else if(__label__==68){var $448=$name2;var $cmp674=((($448))|0)==27502;if($cmp674){__label__=69;;}else{__label__=70;;}
if(__label__==69){var $449=$tr;var $letter_bits_offset676=(($449+964)&4294967295);HEAP32[(($letter_bits_offset676)>>2)]=3200;var $450=$tr;var $langopts677=(($450)&4294967295);var $numbers678=(($langopts677+184)&4294967295);HEAP32[(($numbers678)>>2)]=1;;}
else if(__label__==70){var $451=$name2;var $cmp680=((($451))|0)==29797;if(!($cmp680)){__label__=72;break $if_then665$$if_else667$75;}
var $452=$tr;var $letter_bits_offset682=(($452+964)&4294967295);HEAP32[(($letter_bits_offset682)>>2)]=3072;var $453=$tr;var $langopts683=(($453)&4294967295);var $numbers684=(($langopts683+184)&4294967295);HEAP32[(($numbers684)>>2)]=1;;}}}}while(0);var $454=$tr;var $langopts689=(($454)&4294967295);var $param690=(($langopts689+24)&4294967295);var $arrayidx691=(($param690+32)&4294967295);HEAP32[(($arrayidx691)>>2)]=1;var $455=$tr;__Z15SetIndicLettersP10Translator($455);var $456=$tr;__ZL18SetLetterBitsRangeP10Translatoriii($456,1,78,78);__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==73){var $457=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($457,((__ZZ16SelectTranslatorPKcE17stress_lengths_tr)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_tr)&4294967295));var $458=HEAP32[((((_charsets+36)&4294967295))>>2)];var $459=$tr;var $charset_a0693=(($459+696)&4294967295);HEAP32[(($charset_a0693)>>2)]=$458;var $460=$tr;var $langopts694=(($460)&4294967295);var $stress_rule695=(($langopts694+8)&4294967295);HEAP32[(($stress_rule695)>>2)]=7;var $461=$tr;var $langopts696=(($461)&4294967295);var $stress_flags697=(($langopts696+12)&4294967295);HEAP32[(($stress_flags697)>>2)]=32;var $462=$tr;var $langopts698=(($462)&4294967295);var $numbers699=(($langopts698+184)&4294967295);HEAP32[(($numbers699)>>2)]=2114824;var $463=$tr;var $langopts700=(($463)&4294967295);var $max_initial_consonants701=(($langopts700+248)&4294967295);HEAP8[($max_initial_consonants701)]=2;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==74){var $464=$tr;var $letter_bits_offset703=(($464+964)&4294967295);HEAP32[(($letter_bits_offset703)>>2)]=1536;var $465=$tr;var $langopts704=(($465)&4294967295);var $param705=(($langopts704+24)&4294967295);var $arrayidx706=(($param705+20)&4294967295);HEAP32[(($arrayidx706)>>2)]=1;var $466=$tr;var $langopts707=(($466)&4294967295);var $numbers708=(($langopts707+184)&4294967295);HEAP32[(($numbers708)>>2)]=16;var $467=$tr;var $langopts709=(($467)&4294967295);var $break_numbers710=(($langopts709+192)&4294967295);HEAP32[(($break_numbers710)>>2)]=21160;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==75){var $468=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($468,((__ZZ16SelectTranslatorPKcE17stress_lengths_vi)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_vi)&4294967295));var $469=$tr;var $langopts712=(($469)&4294967295);var $length_mods713=(($langopts712+176)&4294967295);var $470=HEAP32[(($length_mods713)>>2)];var $471=$tr;var $langopts714=(($471)&4294967295);var $length_mods0715=(($langopts714+180)&4294967295);HEAP32[(($length_mods0715)>>2)]=$470;var $472=$tr;var $langopts716=(($472)&4294967295);var $stress_rule717=(($langopts716+8)&4294967295);HEAP32[(($stress_rule717)>>2)]=0;var $473=$tr;var $langopts718=(($473)&4294967295);var $word_gap719=(($langopts718)&4294967295);HEAP32[(($word_gap719)>>2)]=33;var $474=$tr;var $letter_groups720=(($474+968)&4294967295);var $arrayidx721=(($letter_groups720+28)&4294967295);HEAP32[(($arrayidx721)>>2)]=((__ZZ16SelectTranslatorPKcE9vowels_vi)&4294967295);var $475=$tr;var $letter_groups722=(($475+968)&4294967295);var $arrayidx723=(($letter_groups722)&4294967295);HEAP32[(($arrayidx723)>>2)]=((__ZZ16SelectTranslatorPKcE9vowels_vi)&4294967295);var $476=$tr;var $langopts724=(($476)&4294967295);var $tone_language=(($langopts724+224)&4294967295);HEAP32[(($tone_language)>>2)]=1;var $477=$tr;var $langopts725=(($477)&4294967295);var $unstressed_wd1726=(($langopts725+16)&4294967295);HEAP32[(($unstressed_wd1726)>>2)]=2;var $478=$tr;var $langopts727=(($478)&4294967295);var $numbers728=(($langopts727+184)&4294967295);HEAP32[(($numbers728)>>2)]=12615688;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==76){var $479=$tr;var $langopts730=(($479)&4294967295);var $stress_rule731=(($langopts730+8)&4294967295);HEAP32[(($stress_rule731)>>2)]=0;var $480=$tr;var $langopts732=(($480)&4294967295);var $numbers733=(($langopts732+184)&4294967295);HEAP32[(($numbers733)>>2)]=2098528;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
else if(__label__==77){var $481=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($481,((__ZZ16SelectTranslatorPKcE17stress_lengths_zh)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_zh)&4294967295));var $482=$tr;var $langopts735=(($482)&4294967295);var $stress_rule736=(($langopts735+8)&4294967295);HEAP32[(($stress_rule736)>>2)]=3;var $483=$tr;var $langopts737=(($483)&4294967295);var $stress_flags738=(($langopts737+12)&4294967295);HEAP32[(($stress_flags738)>>2)]=2;var $484=$tr;var $langopts739=(($484)&4294967295);var $vowel_pause740=(($langopts739+4)&4294967295);HEAP32[(($vowel_pause740)>>2)]=0;var $485=$tr;var $langopts741=(($485)&4294967295);var $tone_language742=(($langopts741+224)&4294967295);HEAP32[(($tone_language742)>>2)]=1;var $486=$tr;var $langopts743=(($486)&4294967295);var $length_mods744=(($langopts743+176)&4294967295);var $487=HEAP32[(($length_mods744)>>2)];var $488=$tr;var $langopts745=(($488)&4294967295);var $length_mods0746=(($langopts745+180)&4294967295);HEAP32[(($length_mods0746)>>2)]=$487;var $489=$tr;var $langopts747=(($489)&4294967295);var $tone_numbers=(($langopts747+250)&4294967295);HEAP8[($tone_numbers)]=1;var $490=$tr;var $langopts748=(($490)&4294967295);var $ideographs=(($langopts748+251)&4294967295);HEAP8[($ideographs)]=1;var $491=$tr;var $langopts749=(($491)&4294967295);var $word_gap750=(($langopts749)&4294967295);HEAP32[(($word_gap750)>>2)]=33;var $492=$name2;var $cmp751=((($492))|0)==31336;if(!($cmp751)){__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}
var $493=$tr;var $langopts753=(($493)&4294967295);var $textmode=(($langopts753+252)&4294967295);HEAP8[($textmode)]=1;var $494=$tr;var $langopts754=(($494)&4294967295);var $listx=(($langopts754+260)&4294967295);HEAP32[(($listx)>>2)]=1;__label__=80;break $sw_default$$sw_bb$$sw_bb9$$sw_bb18$$sw_bb24$$sw_bb39$$sw_bb52$$sw_bb64$$sw_bb72$$sw_bb92$$sw_bb109$$sw_bb123$$sw_bb148$$sw_bb161$$sw_bb195$$sw_bb200$$sw_bb207$$sw_bb209$$sw_bb222$$sw_bb238$$sw_bb257$$sw_bb280$$sw_bb287$$sw_bb312$$sw_bb322$$sw_bb331$$sw_bb347$$sw_bb381$$sw_bb391$$sw_bb403$$sw_bb414$$sw_bb422$$sw_bb439$$sw_bb449$$sw_bb461$$sw_bb481$$sw_bb486$$sw_bb491$$sw_bb509$$sw_bb523$$sw_bb533$$sw_bb534$$sw_bb547$$sw_bb576$$sw_bb599$$sw_bb614$$sw_bb623$$sw_bb630$$sw_bb645$$sw_bb692$$sw_bb702$$sw_bb711$$sw_bb729$$sw_bb734$6;}}while(0);if(__label__==24){var $146=$tr;__Z15SetupTranslatorP10TranslatorPKsPKh($146,((__ZZ16SelectTranslatorPKcE17stress_lengths_fi)&4294967295),((__ZZ16SelectTranslatorPKcE14stress_amps_fi)&4294967295));var $147=$tr;var $langopts210=(($147)&4294967295);var $stress_rule211=(($langopts210+8)&4294967295);HEAP32[(($stress_rule211)>>2)]=0;var $148=$tr;var $langopts212=(($148)&4294967295);var $stress_flags213=(($langopts212+12)&4294967295);HEAP32[(($stress_flags213)>>2)]=86;var $149=$tr;var $langopts214=(($149)&4294967295);var $param215=(($langopts214+24)&4294967295);var $arrayidx216=(($param215+56)&4294967295);HEAP32[(($arrayidx216)>>2)]=1;var $150=$tr;var $langopts217=(($150)&4294967295);var $long_stop=(($langopts217+240)&4294967295);HEAP32[(($long_stop)>>2)]=130;var $151=$tr;var $langopts218=(($151)&4294967295);var $numbers219=(($langopts218+184)&4294967295);HEAP32[(($numbers219)>>2)]=4104;var $152=$tr;__ZL14SetLetterVowelP10Translatori($152,121);var $153=$tr;var $langopts220=(($153)&4294967295);var $spelling_stress=(($langopts220+249)&4294967295);HEAP8[($spelling_stress)]=1;var $154=$tr;var $langopts221=(($154)&4294967295);var $intonation_group=(($langopts221+228)&4294967295);HEAP32[(($intonation_group)>>2)]=3;;}
var $496=$name2;var $497=$tr;var $translator_name=(($497+280)&4294967295);HEAP32[(($translator_name)>>2)]=$496;var $498=$tr;var $langopts759=(($498)&4294967295);var $numbers760=(($langopts759+184)&4294967295);var $499=HEAP32[(($numbers760)>>2)];var $and=($499)&8;var $tobool=((($and))|0)!=0;if($tobool){__label__=81;;}else{__label__=82;;}
if(__label__==81){var $500=$tr;var $langopts762=(($500)&4294967295);var $thousands_sep763=(($langopts762+204)&4294967295);HEAP32[(($thousands_sep763)>>2)]=46;var $501=$tr;var $langopts764=(($501)&4294967295);var $decimal_sep765=(($langopts764+208)&4294967295);HEAP32[(($decimal_sep765)>>2)]=44;;}
var $502=$tr;var $langopts767=(($502)&4294967295);var $numbers768=(($langopts767+184)&4294967295);var $503=HEAP32[(($numbers768)>>2)];var $and769=($503)&4;var $tobool770=((($and769))|0)!=0;if($tobool770){__label__=83;;}else{__label__=84;;}
if(__label__==83){var $504=$tr;var $langopts772=(($504)&4294967295);var $thousands_sep773=(($langopts772+204)&4294967295);HEAP32[(($thousands_sep773)>>2)]=0;;}
var $505=$tr;;return $505;return null;}
function __ZL13NewTranslatorv(){;var __label__;var $retval;var $tr;var $ix;var $call=__Z5Alloci(8328);var $0=$call;$tr=$0;var $1=$tr;var $cmp=((($1))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $2=HEAP32[((((_charsets+4)&4294967295))>>2)];var $3=$tr;var $charset_a0=(($3+696)&4294967295);HEAP32[(($charset_a0)>>2)]=$2;HEAP8[(((_dictionary_name)&4294967295))]=0;var $4=$tr;var $dict_condition=(($4+692)&4294967295);HEAP32[(($dict_condition)>>2)]=0;var $5=$tr;var $data_dictrules=(($5+1048)&4294967295);HEAP32[(($data_dictrules)>>2)]=0;var $6=$tr;var $data_dictlist=(($6+1052)&4294967295);HEAP32[(($data_dictlist)>>2)]=0;var $7=$tr;var $transpose_min=(($7+288)&4294967295);HEAP32[(($transpose_min)>>2)]=97;var $8=$tr;var $transpose_max=(($8+284)&4294967295);HEAP32[(($transpose_max)>>2)]=122;var $9=$tr;var $frequent_pairs=(($9+8268)&4294967295);HEAP32[(($frequent_pairs)>>2)]=0;var $10=$tr;var $letter_bits_offset=(($10+964)&4294967295);HEAP32[(($letter_bits_offset)>>2)]=0;var $11=$tr;var $letter_bits=(($11+708)&4294967295);var $arraydecay=(($letter_bits)&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arraydecay;$stop$=$dest$+256;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $12=$tr;var $letter_groups=(($12+968)&4294967295);var $arraydecay1=(($letter_groups)&4294967295);var $13=$arraydecay1;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$13;$stop$=$dest$+32;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $14=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($14,0,((__str6636)&4294967295));var $15=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($15,1,((__str7637)&4294967295));var $16=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($16,2,((__str8638)&4294967295));var $17=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($17,3,((__str9639)&4294967295));var $18=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($18,4,((__str10640)&4294967295));var $19=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($19,5,((__str11641)&4294967295));var $20=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($20,6,((__str12642)&4294967295));var $21=$tr;__ZL13SetLetterBitsP10TranslatoriPKc($21,7,((__str630)&4294967295));var $22=$tr;var $char_plus_apostrophe=(($22+700)&4294967295);HEAP32[(($char_plus_apostrophe)>>2)]=((__ZZL13NewTranslatorvE13empty_wstring)&4294967295);var $23=$tr;var $punct_within_word=(($23+704)&4294967295);HEAP32[(($punct_within_word)>>2)]=((__ZZL13NewTranslatorvE13punct_in_word)&4294967295);$ix=0;;while(1){var $24=$ix;var $arrayidx=((__ZZL13NewTranslatorvE12stress_amps2+$24)&4294967295);var $25=HEAP8[($arrayidx)];var $26=$ix;var $27=$tr;var $stress_amps=(($27+660)&4294967295);var $arrayidx3=(($stress_amps+$26)&4294967295);HEAP8[($arrayidx3)]=$25;var $28=$ix;var $arrayidx4=((__ZZL13NewTranslatorvE12stress_amps2+$28)&4294967295);var $29=HEAPU8[($arrayidx4)];var $conv=((($29))&255);var $sub=((($conv)-1)&4294967295);var $conv5=((($sub))&255);var $30=$ix;var $31=$tr;var $stress_amps_r=(($31+668)&4294967295);var $arrayidx6=(($stress_amps_r+$30)&4294967295);HEAP8[($arrayidx6)]=$conv5;var $32=$ix;var $arrayidx7=((__ZZL13NewTranslatorvE15stress_lengths2+$32*2)&4294967295);var $33=HEAP16[(($arrayidx7)>>1)];var $34=$ix;var $35=$tr;var $stress_lengths=(($35+676)&4294967295);var $arrayidx8=(($stress_lengths+$34*2)&4294967295);HEAP16[(($arrayidx8)>>1)]=$33;var $36=$ix;var $inc=((($36)+1)&4294967295);$ix=$inc;var $cmp2=((($inc))|0)<8;if($cmp2){__label__=3;continue;}else{__label__=4;break;}}
var $37=$tr;var $langopts=(($37)&4294967295);var $38=$langopts;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$38;$stop$=$dest$+280;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $39=$tr;var $langopts9=(($39)&4294967295);var $max_lengthmod=(($langopts9+272)&4294967295);HEAP32[(($max_lengthmod)>>2)]=500;var $40=$tr;var $langopts10=(($40)&4294967295);var $stress_rule=(($langopts10+8)&4294967295);HEAP32[(($stress_rule)>>2)]=2;var $41=$tr;var $langopts11=(($41)&4294967295);var $unstressed_wd1=(($langopts11+16)&4294967295);HEAP32[(($unstressed_wd1)>>2)]=1;var $42=$tr;var $langopts12=(($42)&4294967295);var $unstressed_wd2=(($langopts12+20)&4294967295);HEAP32[(($unstressed_wd2)>>2)]=3;var $43=$tr;var $langopts13=(($43)&4294967295);var $param=(($langopts13+24)&4294967295);var $arrayidx14=(($param+28)&4294967295);HEAP32[(($arrayidx14)>>2)]=95;var $44=$tr;var $langopts15=(($44)&4294967295);var $param16=(($langopts15+24)&4294967295);var $arrayidx17=(($param16+72)&4294967295);HEAP32[(($arrayidx17)>>2)]=95;var $45=$tr;var $langopts18=(($45)&4294967295);var $param19=(($langopts18+24)&4294967295);var $arrayidx20=(($param19+36)&4294967295);HEAP32[(($arrayidx20)>>2)]=19;var $46=$tr;var $langopts21=(($46)&4294967295);var $param22=(($langopts21+24)&4294967295);var $arrayidx23=(($param22+20)&4294967295);HEAP32[(($arrayidx23)>>2)]=115;var $47=$tr;var $langopts24=(($47)&4294967295);var $param25=(($langopts24+24)&4294967295);var $arrayidx26=(($param25+64)&4294967295);HEAP32[(($arrayidx26)>>2)]=4;var $48=$tr;var $langopts27=(($48)&4294967295);var $param2=(($langopts27+100)&4294967295);var $arrayidx28=(($param2+64)&4294967295);HEAP32[(($arrayidx28)>>2)]=2;var $49=$tr;var $langopts29=(($49)&4294967295);var $max_initial_consonants=(($langopts29+248)&4294967295);HEAP8[($max_initial_consonants)]=3;var $50=$tr;var $langopts30=(($50)&4294967295);var $replace_chars=(($langopts30+264)&4294967295);HEAP32[(($replace_chars)>>2)]=0;var $51=$tr;var $langopts31=(($51)&4294967295);var $ascii_language=(($langopts31+268)&4294967295);HEAP32[(($ascii_language)>>2)]=((__str13643)&4294967295);var $52=$tr;__Z13SetLengthModsP10Translatori($52,201);var $53=$tr;var $langopts32=(($53)&4294967295);var $long_stop=(($langopts32+240)&4294967295);HEAP32[(($long_stop)>>2)]=100;var $54=$tr;var $langopts33=(($54)&4294967295);var $max_roman=(($langopts33+196)&4294967295);HEAP32[(($max_roman)>>2)]=49;var $55=$tr;var $langopts34=(($55)&4294967295);var $min_roman=(($langopts34+200)&4294967295);HEAP32[(($min_roman)>>2)]=2;var $56=$tr;var $langopts35=(($56)&4294967295);var $thousands_sep=(($langopts35+204)&4294967295);HEAP32[(($thousands_sep)>>2)]=44;var $57=$tr;var $langopts36=(($57)&4294967295);var $decimal_sep=(($langopts36+208)&4294967295);HEAP32[(($decimal_sep)>>2)]=46;var $58=$tr;var $langopts37=(($58)&4294967295);var $break_numbers=(($langopts37+192)&4294967295);HEAP32[(($break_numbers)>>2)]=1227133512;var $59=$tr;var $langopts38=(($59)&4294967295);var $max_digits=(($langopts38+212)&4294967295);HEAP32[(($max_digits)>>2)]=14;var $60=$tr;var $punct_to_tone=(($60+1000)&4294967295);var $arraydecay39=(($punct_to_tone)&4294967295);var $61=$arraydecay39;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((_punctuation_to_tone)&4294967295);$dest$=$61;$stop$=$src$+48;if(($dest$%4)==($src$%4)&&48>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $62=$tr;var $langopts40=(($62)&4294967295);var $tunes=(($langopts40+232)&4294967295);var $arraydecay41=(($tunes)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__ZZL13NewTranslatorvE13default_tunes)&4294967295);$dest$=$arraydecay41;$stop$=$src$+6;if(($dest$%4)==($src$%4)&&6>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $63=$tr;$retval=$63;;}
var $64=$retval;;return $64;return null;}
function __ZL14SetLetterVowelP10Translatori($tr,$c){;var __label__;var $tr_addr;var $c_addr;$tr_addr=$tr;$c_addr=$c;var $0=$c_addr;var $1=$tr_addr;var $letter_bits=(($1+708)&4294967295);var $arrayidx=(($letter_bits+$0)&4294967295);var $2=HEAPU8[($arrayidx)];var $conv=((($2))&255);var $and=($conv)&64;var $or=($and)|129;var $conv1=((($or))&255);var $3=$c_addr;var $4=$tr_addr;var $letter_bits2=(($4+708)&4294967295);var $arrayidx3=(($letter_bits2+$3)&4294967295);HEAP8[($arrayidx3)]=$conv1;;return;return;}
function __ZL18SetCyrillicLettersP10Translator($tr){;var __label__;var $tr_addr;$tr_addr=$tr;var $0=HEAP32[((((_charsets+72)&4294967295))>>2)];var $1=$tr_addr;var $charset_a0=(($1+696)&4294967295);HEAP32[(($charset_a0)>>2)]=$0;var $2=$tr_addr;var $transpose_min=(($2+288)&4294967295);HEAP32[(($transpose_min)>>2)]=1072;var $3=$tr_addr;var $transpose_max=(($3+284)&4294967295);HEAP32[(($transpose_max)>>2)]=1105;var $4=$tr_addr;var $frequent_pairs=(($4+8268)&4294967295);HEAP32[(($frequent_pairs)>>2)]=((__ZL8pairs_ru)&4294967295);var $5=$tr_addr;var $letter_bits_offset=(($5+964)&4294967295);HEAP32[(($letter_bits_offset)>>2)]=1056;var $6=$tr_addr;var $letter_bits=(($6+708)&4294967295);var $arraydecay=(($letter_bits)&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$arraydecay;$stop$=$dest$+256;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $7=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($7,0,((__ZZL18SetCyrillicLettersP10TranslatorE9ru_vowels)&4294967295));var $8=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($8,1,((__ZZL18SetCyrillicLettersP10TranslatorE7ru_soft)&4294967295));var $9=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($9,2,((__ZZL18SetCyrillicLettersP10TranslatorE13ru_consonants)&4294967295));var $10=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($10,3,((__ZZL18SetCyrillicLettersP10TranslatorE7ru_hard)&4294967295));var $11=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($11,4,((__ZZL18SetCyrillicLettersP10TranslatorE10ru_nothard)&4294967295));var $12=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($12,5,((__ZZL18SetCyrillicLettersP10TranslatorE9ru_voiced)&4294967295));var $13=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($13,6,((__ZZL18SetCyrillicLettersP10TranslatorE10ru_ivowels)&4294967295));var $14=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($14,7,((__ZZL18SetCyrillicLettersP10TranslatorE9ru_vowels)&4294967295));;return;return;}
function __ZL15ResetLetterBitsP10Translatori($tr,$groups){;var __label__;var $tr_addr;var $groups_addr;var $ix;var $mask;$tr_addr=$tr;$groups_addr=$groups;var $0=$groups_addr;var $neg=($0)^-1;$mask=$neg;$ix=0;;while(1){var $1=$mask;var $2=$ix;var $3=$tr_addr;var $letter_bits=(($3+708)&4294967295);var $arrayidx=(($letter_bits+$2)&4294967295);var $4=HEAPU8[($arrayidx)];var $conv=((($4))&255);var $and=($conv)&($1);var $conv1=((($and))&255);HEAP8[($arrayidx)]=$conv1;var $5=$ix;var $inc=((($5)+1)&4294967295);$ix=$inc;var $cmp=((($inc))>>>0)<256;if($cmp){__label__=1;continue;}else{__label__=2;break;}};return;return;}
function __ZL18Translator_RussianP10Translator($tr){;var __label__;var $tr_addr;$tr_addr=$tr;var $0=$tr_addr;__Z15SetupTranslatorP10TranslatorPKsPKh($0,((__ZZL18Translator_RussianP10TranslatorE17stress_lengths_ru)&4294967295),((__ZZL18Translator_RussianP10TranslatorE14stress_amps_ru)&4294967295));var $1=$tr_addr;__ZL18SetCyrillicLettersP10Translator($1);var $2=$tr_addr;__ZL13SetLetterBitsP10TranslatoriPKc($2,6,((__ZZL18Translator_RussianP10TranslatorE11ru_ivowels2)&4294967295));var $3=$tr_addr;var $langopts=(($3)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx=(($param+20)&4294967295);HEAP32[(($arrayidx)>>2)]=1074;var $4=$tr_addr;var $langopts1=(($4)&4294967295);var $param2=(($langopts1+24)&4294967295);var $arrayidx3=(($param2+16)&4294967295);HEAP32[(($arrayidx3)>>2)]=1;var $5=$tr_addr;var $langopts4=(($5)&4294967295);var $param5=(($langopts4+24)&4294967295);var $arrayidx6=(($param5+40)&4294967295);HEAP32[(($arrayidx6)>>2)]=2;var $6=$tr_addr;var $langopts7=(($6)&4294967295);var $stress_rule=(($langopts7+8)&4294967295);HEAP32[(($stress_rule)>>2)]=5;var $7=$tr_addr;var $langopts8=(($7)&4294967295);var $stress_flags=(($langopts8+12)&4294967295);HEAP32[(($stress_flags)>>2)]=32;var $8=$tr_addr;var $langopts9=(($8)&4294967295);var $numbers=(($langopts9+184)&4294967295);HEAP32[(($numbers)>>2)]=1032;var $9=$tr_addr;var $langopts10=(($9)&4294967295);var $numbers2=(($langopts10+188)&4294967295);HEAP32[(($numbers2)>>2)]=194;var $10=$tr_addr;var $langopts11=(($10)&4294967295);var $phoneme_change=(($langopts11+244)&4294967295);HEAP32[(($phoneme_change)>>2)]=1;var $11=$tr_addr;var $langopts12=(($11)&4294967295);var $testing=(($langopts12+256)&4294967295);HEAP32[(($testing)>>2)]=2;;return;return;}
function __Z14ReadTonePointsPcPi($string,$tone_pts){;var __label__;var $string_addr;var $tone_pts_addr;var $ix;$string_addr=$string;$tone_pts_addr=$tone_pts;$ix=0;;while(1){var $0=$ix;var $1=$tone_pts_addr;var $arrayidx=(($1+4*$0)&4294967295);HEAP32[(($arrayidx)>>2)]=-1;var $2=$ix;var $inc=((($2)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<12;if($cmp){__label__=1;continue;}else{__label__=2;break;}}
var $3=$string_addr;var $4=$tone_pts_addr;var $arrayidx1=(($4)&4294967295);var $5=$tone_pts_addr;var $arrayidx2=(($5+4)&4294967295);var $6=$tone_pts_addr;var $arrayidx3=(($6+8)&4294967295);var $7=$tone_pts_addr;var $arrayidx4=(($7+12)&4294967295);var $8=$tone_pts_addr;var $arrayidx5=(($8+16)&4294967295);var $9=$tone_pts_addr;var $arrayidx6=(($9+20)&4294967295);var $10=$tone_pts_addr;var $arrayidx7=(($10+24)&4294967295);var $11=$tone_pts_addr;var $arrayidx8=(($11+28)&4294967295);var $12=$tone_pts_addr;var $arrayidx9=(($12+32)&4294967295);var $13=$tone_pts_addr;var $arrayidx10=(($13+36)&4294967295);var $call=_sscanf($3,((__str44696)&4294967295),allocate([$arrayidx1,0,0,0,$arrayidx2,0,0,0,$arrayidx3,0,0,0,$arrayidx4,0,0,0,$arrayidx5,0,0,0,$arrayidx6,0,0,0,$arrayidx7,0,0,0,$arrayidx8,0,0,0,$arrayidx9,0,0,0,$arrayidx10,0,0,0],["i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));;return;return;}
function __Z10VoiceReseti($tone_only){;var __label__;var $tone_only_addr;var $pk;$tone_only_addr=$tone_only;var $0=HEAP32[((_voice)>>2)];var $pitch_base=(($0+44)&4294967295);HEAP32[(($pitch_base)>>2)]=290816;var $1=HEAP32[((_voice)>>2)];var $pitch_range=(($1+48)&4294967295);HEAP32[(($pitch_range)>>2)]=4104;var $2=HEAP32[((_voice)>>2)];var $formant_factor=(($2+96)&4294967295);HEAP32[(($formant_factor)>>2)]=256;var $3=HEAP32[((_voice)>>2)];var $speed_percent=(($3+64)&4294967295);HEAP32[(($speed_percent)>>2)]=100;var $4=HEAP32[((_voice)>>2)];var $echo_delay=(($4+76)&4294967295);HEAP32[(($echo_delay)>>2)]=0;var $5=HEAP32[((_voice)>>2)];var $echo_amp=(($5+80)&4294967295);HEAP32[(($echo_amp)>>2)]=0;var $6=HEAP32[((_voice)>>2)];var $flutter=(($6+68)&4294967295);HEAP32[(($flutter)>>2)]=64;var $7=HEAP32[((_voice)>>2)];var $n_harmonic_peaks=(($7+84)&4294967295);HEAP32[(($n_harmonic_peaks)>>2)]=5;var $8=HEAP32[((_voice)>>2)];var $peak_shape=(($8+88)&4294967295);HEAP32[(($peak_shape)>>2)]=0;var $9=HEAP32[((_voice)>>2)];var $voicing=(($9+92)&4294967295);HEAP32[(($voicing)>>2)]=64;var $10=HEAP32[((_voice)>>2)];var $consonant_amp=(($10+100)&4294967295);HEAP32[(($consonant_amp)>>2)]=100;var $11=HEAP32[((_voice)>>2)];var $consonant_ampv=(($11+104)&4294967295);HEAP32[(($consonant_ampv)>>2)]=100;var $12=HEAP32[((_voice)>>2)];var $samplerate=(($12+108)&4294967295);HEAP32[(($samplerate)>>2)]=22050;var $13=HEAP32[((_voice)>>2)];var $klattv=(($13+112)&4294967295);var $arraydecay=(($klattv)&4294967295);var $14=$arraydecay;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$14;$stop$=$dest$+32;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};HEAP32[((((_speed+32)&4294967295))>>2)]=450;HEAP32[((((_speed+32+4)&4294967295))>>2)]=800;HEAP32[((((_speed+32+8)&4294967295))>>2)]=175;var $15=HEAP32[((_voice)>>2)];var $roughness=(($15+72)&4294967295);HEAP32[(($roughness)>>2)]=2;__Z10InitBreathv();$pk=0;;while(1){var $16=$pk;var $17=HEAP32[((_voice)>>2)];var $freq=(($17+144)&4294967295);var $arrayidx=(($freq+$16*2)&4294967295);HEAP16[(($arrayidx)>>1)]=256;var $18=$pk;var $arrayidx1=((__ZZ10VoiceResetiE15default_heights+$18)&4294967295);var $19=HEAPU8[($arrayidx1)];var $conv=((($19))&255);var $mul=((($conv)*2)&4294967295);var $conv2=((($mul))&65535);var $20=$pk;var $21=HEAP32[((_voice)>>2)];var $height=(($21+162)&4294967295);var $arrayidx3=(($height+$20*2)&4294967295);HEAP16[(($arrayidx3)>>1)]=$conv2;var $22=$pk;var $arrayidx4=((__ZZ10VoiceResetiE14default_widths+$22)&4294967295);var $23=HEAPU8[($arrayidx4)];var $conv5=((($23))&255);var $mul6=((($conv5)*2)&4294967295);var $conv7=((($mul6))&65535);var $24=$pk;var $25=HEAP32[((_voice)>>2)];var $width=(($25+180)&4294967295);var $arrayidx8=(($width+$24*2)&4294967295);HEAP16[(($arrayidx8)>>1)]=$conv7;var $26=$pk;var $27=HEAP32[((_voice)>>2)];var $breath=(($27+272)&4294967295);var $arrayidx9=(($breath+$26*4)&4294967295);HEAP32[(($arrayidx9)>>2)]=0;var $28=$pk;var $arrayidx10=((__ZZ10VoiceResetiE13breath_widths+$28*4)&4294967295);var $29=HEAP32[(($arrayidx10)>>2)];var $30=$pk;var $31=HEAP32[((_voice)>>2)];var $breathw=(($31+308)&4294967295);var $arrayidx11=(($breathw+$30*4)&4294967295);HEAP32[(($arrayidx11)>>2)]=$29;var $32=$pk;var $33=HEAP32[((_voice)>>2)];var $freqadd=(($33+198)&4294967295);var $arrayidx12=(($freqadd+$32*2)&4294967295);HEAP16[(($arrayidx12)>>1)]=0;var $34=$pk;var $arrayidx13=((__ZL18formant_rate_22050+$34*4)&4294967295);var $35=HEAP32[(($arrayidx13)>>2)];var $mul14=((($35)*22050)&4294967295);var $36=HEAP32[((_samplerate)>>2)];var $div=((((($mul14))|0)/((($36))|0))|0);var $37=$pk;var $arrayidx15=((_formant_rate+$37*4)&4294967295);HEAP32[(($arrayidx15)>>2)]=$div;var $38=$pk;var $inc=((($38)+1)&4294967295);$pk=$inc;var $cmp=((($inc))|0)<9;if($cmp){__label__=1;continue;}else{__label__=2;break;}}
var $39=HEAP32[((_voice)>>2)];var $height16=(($39+162)&4294967295);var $arrayidx17=(($height16+4)&4294967295);HEAP16[(($arrayidx17)>>1)]=240;var $40=HEAP32[((_voice)>>2)];__ZL13SetToneAdjustP7voice_tPi($40,((_tone_points)&4294967295));var $41=HEAP32[((_voice)>>2)];var $speedf1=(($41+52)&4294967295);HEAP32[(($speedf1)>>2)]=256;var $42=HEAP32[((_voice)>>2)];var $speedf2=(($42+56)&4294967295);HEAP32[(($speedf2)>>2)]=238;var $43=HEAP32[((_voice)>>2)];var $speedf3=(($43+60)&4294967295);HEAP32[(($speedf3)>>2)]=232;var $44=$tone_only_addr;var $cmp18=((($44))|0)==0;if($cmp18){__label__=3;;}else{__label__=4;;}
if(__label__==3){HEAP32[((_n_replace_phonemes)>>2)]=0;HEAP32[((_option_quiet)>>2)]=0;var $call=__Z15LoadMbrolaTablePKcS0_i(0,0,0);;};return;return;}
function __ZL13SetToneAdjustP7voice_tPi($voice,$tone_pts){;var __label__;var $voice_addr;var $tone_pts_addr;var $ix;var $pt;var $y;var $freq1;var $freq2;var $height1;var $height2;var $rate;$voice_addr=$voice;$tone_pts_addr=$tone_pts;$freq1=0;var $0=$tone_pts_addr;var $arrayidx=(($0+4)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];$height1=$1;$pt=0;;$for_body$2:while(1){var $2=$pt;var $3=$tone_pts_addr;var $arrayidx1=(($3+4*$2)&4294967295);var $4=HEAP32[(($arrayidx1)>>2)];var $cmp2=((($4))|0)==-1;if($cmp2){__label__=2;;}else{__label__=4;;}
$if_then$$if_end8$4:do{if(__label__==2){var $5=$pt;var $6=$tone_pts_addr;var $arrayidx3=(($6+4*$5)&4294967295);HEAP32[(($arrayidx3)>>2)]=8000;var $7=$pt;var $cmp4=((($7))|0)>0;if(!($cmp4)){__label__=4;break $if_then$$if_end8$4;}
var $8=$pt;var $sub=((($8)-1)&4294967295);var $9=$tone_pts_addr;var $arrayidx6=(($9+4*$sub)&4294967295);var $10=HEAP32[(($arrayidx6)>>2)];var $11=$pt;var $add=((($11)+1)&4294967295);var $12=$tone_pts_addr;var $arrayidx7=(($12+4*$add)&4294967295);HEAP32[(($arrayidx7)>>2)]=$10;;}}while(0);var $13=$pt;var $14=$tone_pts_addr;var $arrayidx9=(($14+4*$13)&4294967295);var $15=HEAP32[(($arrayidx9)>>2)];var $div=((((($15))|0)/8)|0);$freq2=$div;var $16=$pt;var $add10=((($16)+1)&4294967295);var $17=$tone_pts_addr;var $arrayidx11=(($17+4*$add10)&4294967295);var $18=HEAP32[(($arrayidx11)>>2)];$height2=$18;var $19=$freq2;var $20=$freq1;var $sub12=((($19)-($20))&4294967295);var $cmp13=((($sub12))|0)>0;if($cmp13){__label__=5;;}else{__label__=9;;}
$if_then14$$if_end31$8:do{if(__label__==5){var $21=$height2;var $22=$height1;var $sub15=((($21)-($22))&4294967295);var $conv=((($sub15))|0);var $23=$freq2;var $24=$freq1;var $sub16=((($23)-($24))&4294967295);var $conv17=((($sub16))|0);var $div18=($conv)/($conv17);$rate=$div18;var $25=$freq1;$ix=$25;var $26=$ix;var $27=$freq2;var $cmp201=((($26))|0)<((($27))|0);if(!($cmp201)){__label__=9;break $if_then14$$if_end31$8;}
while(1){var $28=$height1;var $29=$rate;var $30=$ix;var $31=$freq1;var $sub22=((($30)-($31))&4294967295);var $conv23=((($sub22))|0);var $mul=($29)*($conv23);var $conv24=((($mul))|0);var $add25=((($conv24)+($28))&4294967295);$y=$add25;var $cmp26=((($add25))|0)>255;if($cmp26){__label__=7;;}else{__label__=8;;}
if(__label__==7){$y=255;;}
var $32=$y;var $conv29=((($32))&255);var $33=$ix;var $34=$voice_addr;var $tone_adjust=(($34+344)&4294967295);var $arrayidx30=(($tone_adjust+$33)&4294967295);HEAP8[($arrayidx30)]=$conv29;var $35=$ix;var $inc=((($35)+1)&4294967295);$ix=$inc;var $36=$ix;var $37=$freq2;var $cmp20=((($36))|0)<((($37))|0);if($cmp20){__label__=6;continue;}else{__label__=9;break $if_then14$$if_end31$8;}}}}while(0);var $38=$freq2;$freq1=$38;var $39=$height2;$height1=$39;var $40=$pt;var $add33=((($40)+2)&4294967295);$pt=$add33;var $cmp=((($add33))|0)<12;if($cmp){__label__=1;continue $for_body$2;}else{__label__=10;break $for_body$2;}};return;return;}
function __Z9LoadVoicePKci($vname,$control){var __stackBase__=STACKTOP;STACKTOP+=1260;_memset(__stackBase__,0,1260);var __label__;var __lastLabel__=null;var $retval;var $vname_addr;var $control_addr;var $f_voice;var $p;var $key;var $ix;var $n;var $value=__stackBase__;var $value2=__stackBase__+4;var $error;var $langix;var $tone_only;var $language_set;var $phonemes_set;var $stress_amps_set;var $stress_lengths_set;var $stress_add_set;var $conditional_rules;var $langopts;var $new_translator;var $voicename=__stackBase__+8;var $language_name=__stackBase__+48;var $translator_name=__stackBase__+88;var $new_dictionary=__stackBase__+128;var $phonemes_name=__stackBase__+168;var $option_name=__stackBase__+208;var $language_type;var $buf=__stackBase__+248;var $path_voices=__stackBase__+448;var $langname=__stackBase__+612;var $stress_amps=__stackBase__+616;var $stress_lengths=__stackBase__+648;var $stress_add=__stackBase__+680;var $names=__stackBase__+712;var $pitch1=__stackBase__+1032;var $pitch2=__stackBase__+1036;var $len;var $priority=__stackBase__+1040;var $age=__stackBase__+1044;var $vgender=__stackBase__+1048;var $factor;var $tone_data=__stackBase__+1128;var $srate=__stackBase__+1176;var $name=__stackBase__+1180;var $phtrans=__stackBase__+1220;$vname_addr=$vname;$control_addr=$control;$f_voice=0;$error=0;$langix=0;var $0=$control_addr;var $and=($0)&2;$tone_only=$and;$language_set=0;$phonemes_set=0;$stress_amps_set=0;$stress_lengths_set=0;$stress_add_set=0;$conditional_rules=0;$langopts=0;$new_translator=0;var $arraydecay=(($voicename)&4294967295);var $1=$vname_addr;var $call=_strcpy($arraydecay,$1);var $arrayidx=(($voicename)&4294967295);var $2=HEAP8[($arrayidx)];var $conv=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));var $cmp=((($conv))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $arraydecay1=(($voicename)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str45697)&4294967295);$dest$=$arraydecay1;$stop$=$src$+8;if(($dest$%4)==($src$%4)&&8>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}
var $3=$control_addr;var $and3=($3)&16;var $tobool=((($and3))|0)!=0;if($tobool){__label__=3;;}else{__label__=5;;}
$if_then4$$if_else$5:do{if(__label__==3){var $arraydecay5=(($buf)&4294967295);var $4=$vname_addr;var $call6=_strcpy($arraydecay5,$4);var $arraydecay7=(($buf)&4294967295);var $call8=__Z13GetFileLengthPKc($arraydecay7);var $cmp9=((($call8))|0)<=0;if(!($cmp9)){__label__=9;break $if_then4$$if_else$5;}
$retval=0;__label__=137;break $if_then4$$if_else$5;}
else if(__label__==5){var $arraydecay12=(($path_voices)&4294967295);var $call13=_sprintf($arraydecay12,((__str46698)&4294967295),allocate([((_path_home)&4294967295),0,0,0,47,0,0,0,47,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STACK));var $arraydecay14=(($buf)&4294967295);var $arraydecay15=(($path_voices)&4294967295);var $arraydecay16=(($voicename)&4294967295);var $call17=_sprintf($arraydecay14,((__str47699)&4294967295),allocate([$arraydecay15,0,0,0,$arraydecay16,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay18=(($buf)&4294967295);var $call19=__Z13GetFileLengthPKc($arraydecay18);var $cmp20=((($call19))|0)<=0;if(!($cmp20)){__label__=9;break $if_then4$$if_else$5;}
var $arrayidx22=(($voicename)&4294967295);var $5=HEAP8[($arrayidx22)];var $arrayidx23=(($langname)&4294967295);HEAP8[($arrayidx23)]=$5;var $arrayidx24=(($voicename+1)&4294967295);var $6=HEAP8[($arrayidx24)];var $arrayidx25=(($langname+1)&4294967295);HEAP8[($arrayidx25)]=$6;var $arrayidx26=(($langname+2)&4294967295);HEAP8[($arrayidx26)]=0;var $arraydecay27=(($buf)&4294967295);var $arraydecay28=(($path_voices)&4294967295);var $arraydecay29=(($langname)&4294967295);var $arraydecay30=(($voicename)&4294967295);var $call31=_sprintf($arraydecay27,((__str48700)&4294967295),allocate([$arraydecay28,0,0,0,$arraydecay29,0,0,0,47,0,0,0,$arraydecay30,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay32=(($buf)&4294967295);var $call33=__Z13GetFileLengthPKc($arraydecay32);var $cmp34=((($call33))|0)<=0;if(!($cmp34)){__label__=9;break $if_then4$$if_else$5;}
var $arraydecay36=(($buf)&4294967295);var $arraydecay37=(($path_voices)&4294967295);var $arraydecay38=(($voicename)&4294967295);var $call39=_sprintf($arraydecay36,((__str49701)&4294967295),allocate([$arraydecay37,0,0,0,47,0,0,0,$arraydecay38,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay40=(($buf)&4294967295);var $call41=__Z13GetFileLengthPKc($arraydecay40);var $cmp42=((($call41))|0)<=0;if(!($cmp42)){__label__=9;break $if_then4$$if_else$5;}
var $arraydecay44=(($buf)&4294967295);var $arraydecay45=(($path_voices)&4294967295);var $arraydecay46=(($voicename)&4294967295);var $call47=_sprintf($arraydecay44,((__str50702)&4294967295),allocate([$arraydecay45,0,0,0,47,0,0,0,$arraydecay46,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));__label__=9;break $if_then4$$if_else$5;}}while(0);$return$$if_end51$12:do{if(__label__==9){var $arraydecay52=(($buf)&4294967295);var $call53=_fopen($arraydecay52,((__str51703)&4294967295));$f_voice=$call53;$language_type=((__str52704)&4294967295);var $cmp54=((($call53))|0)==0;if($cmp54){__label__=10;;}else{__label__=14;;}
$if_then55$$if_end66$14:do{if(__label__==10){var $7=$control_addr;var $and56=($7)&3;var $tobool57=((($and56))|0)!=0;if($tobool57){__label__=11;;}else{__label__=12;;}
if(__label__==11){$retval=0;__label__=137;break $return$$if_end51$12;}
else if(__label__==12){var $arraydecay60=(($voicename)&4294967295);var $call61=__Z22SelectPhonemeTableNamePKc($arraydecay60);var $cmp62=((($call61))|0)>=0;if(!($cmp62)){__label__=14;break $if_then55$$if_end66$14;}
var $arraydecay64=(($voicename)&4294967295);$language_type=$arraydecay64;;}}}while(0);var $8=$tone_only;var $tobool67=((($8))|0)==0;var $9=HEAP32[((_translator)>>2)];var $cmp68=((($9))|0)!=0;var $or_cond=($tobool67)&($cmp68);if($or_cond){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $10=HEAP32[((_translator)>>2)];__Z16DeleteTranslatorP10Translator($10);HEAP32[((_translator)>>2)]=0;;}
var $arraydecay71=(($translator_name)&4294967295);var $11=$language_type;var $call72=_strcpy($arraydecay71,$11);var $arraydecay73=(($new_dictionary)&4294967295);var $12=$language_type;var $call74=_strcpy($arraydecay73,$12);var $arraydecay75=(($phonemes_name)&4294967295);var $13=$language_type;var $call76=_strcpy($arraydecay75,$13);var $14=$tone_only;var $tobool77=((($14))|0)!=0;if($tobool77){__label__=18;;}else{__label__=17;;}
if(__label__==18){var $call80=_strchr(((__ZZ9LoadVoicePKciE16voice_identifier)&4294967295),43);$p=$call80;var $cmp81=((($call80))|0)!=0;if($cmp81){__label__=19;;}else{__label__=20;;}
if(__label__==19){var $16=$p;HEAP8[($16)]=0;;}
var $arraydecay84=(($buf)&4294967295);var $17=$vname_addr;var $arrayidx85=(($17+3)&4294967295);var $call86=_sprintf($arraydecay84,((__str53705)&4294967295),allocate([$arrayidx85,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $arraydecay87=(($buf)&4294967295);var $call88=_strcat(((__ZZ9LoadVoicePKciE16voice_identifier)&4294967295),$arraydecay87);var $18=HEAP32[((_translator)>>2)];var $langopts89=(($18)&4294967295);$langopts=$langopts89;;}
else if(__label__==17){HEAP32[((_voice)>>2)]=__ZL9voicedata;var $15=$vname_addr;__Z8strncpy0PcPKci(((__ZZ9LoadVoicePKciE16voice_identifier)&4294967295),$15,40);HEAP8[(((__ZZ9LoadVoicePKciE10voice_name)&4294967295))]=0;HEAP8[(((__ZZ9LoadVoicePKciE15voice_languages)&4294967295))]=0;HEAP32[((((_voice_selected+8)&4294967295))>>2)]=((__ZZ9LoadVoicePKciE16voice_identifier)&4294967295);HEAP32[((((_voice_selected)&4294967295))>>2)]=((__ZZ9LoadVoicePKciE10voice_name)&4294967295);HEAP32[((((_voice_selected+4)&4294967295))>>2)]=((__ZZ9LoadVoicePKciE15voice_languages)&4294967295);;}
var $19=$tone_only;__Z10VoiceReseti($19);var $20=$tone_only;var $tobool91=((($20))|0)!=0;if($tobool91){__label__=23;;}else{__label__=22;;}
if(__label__==22){var $arraydecay93=(($phonemes_name)&4294967295);var $call94=__Z22SelectPhonemeTableNamePKc($arraydecay93);;}
var $arraydecay97=(($buf)&4294967295);var $arraydecay100=(($buf)&4294967295);var $arrayidx109=(($buf)&4294967295);var $arraydecay114=(($buf)&4294967295);var $arraydecay416=(($buf)&4294967295);var $arrayidx119=(($language_name)&4294967295);var $arraydecay120=(($language_name)&4294967295);var $arraydecay122=(($language_name)&4294967295);var $arraydecay127=(($language_name)&4294967295);var $arraydecay136=(($language_name)&4294967295);var $arraydecay142=(($language_name)&4294967295);var $arraydecay144=(($translator_name)&4294967295);var $arraydecay146=(($new_dictionary)&4294967295);var $arraydecay148=(($phonemes_name)&4294967295);var $arraydecay150=(($phonemes_name)&4294967295);var $arraydecay155=(($translator_name)&4294967295);var $arraydecay170=(($vgender)&4294967295);var $arraydecay172=(($vgender)&4294967295);var $arraydecay180=(($translator_name)&4294967295);var $arraydecay185=(($translator_name)&4294967295);var $arraydecay189=(($new_dictionary)&4294967295);var $arraydecay192=(($phonemes_name)&4294967295);var $arraydecay206=(($stress_lengths)&4294967295);var $arraydecay209=(($stress_amps)&4294967295);var $arraydecay212=(($stress_add)&4294967295);var $arrayidx222=(($names)&4294967295);var $arraydecay223=(($arrayidx222)&4294967295);var $arrayidx224=(($names+40)&4294967295);var $arraydecay225=(($arrayidx224)&4294967295);var $arrayidx226=(($names+80)&4294967295);var $arraydecay227=(($arrayidx226)&4294967295);var $arrayidx228=(($names+120)&4294967295);var $arraydecay229=(($arrayidx228)&4294967295);var $arrayidx230=(($names+160)&4294967295);var $arraydecay231=(($arrayidx230)&4294967295);var $arrayidx232=(($names+200)&4294967295);var $arraydecay233=(($arrayidx232)&4294967295);var $arraydecay290=(($phonemes_name)&4294967295);var $arraydecay308=(($option_name)&4294967295);var $arraydecay312=(($option_name)&4294967295);var $arraydecay320=(($buf)&4294967295);var $arraydecay347=(($tone_data)&4294967295);var $arraydecay348=(($tone_data)&4294967295);var $arrayidx385=(($phtrans)&4294967295);var $arraydecay386=(($name)&4294967295);var $arraydecay387=(($phtrans)&4294967295);var $arraydecay389=(($name)&4294967295);var $arraydecay390=(($phtrans)&4294967295);;$while_cond$34:while(1){var $21=$f_voice;var $cmp96=((($21))|0)!=0;if(!($cmp96)){__label__=114;break $while_cond$34;}
var $22=$f_voice;var $call98=__ZL11fgets_stripPciP7__sFILE($arraydecay97,200,$22);var $cmp99=((($call98))|0)!=0;if(!($cmp99)){__label__=112;break $while_cond$34;}
$p=$arraydecay100;;$for_cond$38:while(1){var $23=$p;var $24=HEAP8[($23)];var $conv101=(tempInt=(($24)),(tempInt>=128?tempInt-256:tempInt));var $cmp102=((($conv101))|0)!=0;if(!($cmp102)){__label__=30;break $for_cond$38;}
var $25=$p;var $26=HEAP8[($25)];var $conv104=(tempInt=(($26)),(tempInt>=128?tempInt-256:tempInt));var $call105=_isspace($conv104);var $tobool106=((($call105))|0)!=0;var $lnot=($tobool106)^1;if(!($lnot)){__label__=30;break $for_cond$38;}
var $27=$p;var $incdec_ptr=(($27+1)&4294967295);$p=$incdec_ptr;__label__=27;continue $for_cond$38;}
var $28=$p;var $incdec_ptr108=(($28+1)&4294967295);$p=$incdec_ptr108;HEAP8[($28)]=0;var $29=HEAP8[($arrayidx109)];var $conv110=(tempInt=(($29)),(tempInt>=128?tempInt-256:tempInt));var $cmp111=((($conv110))|0)==0;if($cmp111){__label__=24;continue $while_cond$34;}
var $call115=__Z10LookupMnemP8MNEM_TABPKc(((__ZL11keyword_tab)&4294967295),$arraydecay114);$key=$call115;var $30=$key;if($30==2){__label__=33;;}
else if($30==1){__label__=41;;}
else if($30==3){__label__=45;;}
else if($30==4){__label__=46;;}
else if($30==6){__label__=50;;}
else if($30==5){__label__=51;;}
else if($30==7){__label__=52;;}
else if($30==8){__label__=53;;}
else if($30==20){__label__=54;;}
else if($30==21){__label__=55;;}
else if($30==22){__label__=56;;}
else if($30==18){__label__=57;;}
else if($30==19){__label__=59;;}
else if($30==23){__label__=32;;}
else if($30==32){__label__=73;;}
else if($30==17){__label__=76;;}
else if($30==24){__label__=77;;}
else if($30==25){__label__=78;;}
else if($30==26){__label__=80;;}
else if($30==27){__label__=81;;}
else if($30==9){__label__=85;;}
else if($30==10){__label__=86;;}
else if($30==11){__label__=88;;}
else if($30==12){__label__=90;;}
else if($30==13){__label__=94;;}
else if($30==14){__label__=95;;}
else if($30==15){__label__=97;;}
else if($30==16){__label__=101;;}
else if($30==33){__label__=102;;}
else if($30==31){__label__=103;;}
else if($30==28){__label__=104;;}
else if($30==29){__label__=107;;}
else if($30==30){__label__=108;;}
else{__label__=109;;}
if(__label__==109){var $195=$key;var $and407=($195)&65280;var $cmp408=((($and407))|0)==256;if($cmp408){__label__=110;;}else{__label__=111;;}
if(__label__==110){var $196=$p;var $197=$key;var $and410=($197)&255;var $198=$langopts;var $param411=(($198+24)&4294967295);var $arrayidx412=(($param411+$and410*4)&4294967295);var $call413=_sscanf($196,((__str63715)&4294967295),allocate([$arrayidx412,0,0,0],["i32*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}
else if(__label__==111){var $199=HEAP32[((__impure_ptr)>>2)];var $_stderr415=(($199+12)&4294967295);var $200=HEAP32[(($_stderr415)>>2)];var $call417=_fprintf($200,((__str68720)&4294967295),allocate([$arraydecay416,0,0,0],["i8*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}}
else if(__label__==33){var $33=$tone_only;var $tobool116=((($33))|0)!=0;if($tobool116){__label__=24;continue $while_cond$34;}
HEAP32[(($priority)>>2)]=5;HEAP8[($arrayidx119)]=0;var $34=$p;var $call121=_sscanf($34,((__str54706)&4294967295),allocate([$arraydecay120,0,0,0,$priority,0,0,0],["i8*",0,0,0,"i32*",0,0,0],ALLOC_STACK));var $call123=_strcmp($arraydecay122,((__str55707)&4294967295));var $cmp124=((($call123))|0)==0;if($cmp124){__label__=24;continue $while_cond$34;}
var $call128=_strlen($arraydecay127);var $add=((($call128)+2)&4294967295);$len=$add;var $35=$len;var $36=$langix;var $_neg=(((-($36)))&4294967295);var $sub129=((($_neg)+99)&4294967295);var $cmp130=((($35))>>>0)<((($sub129))>>>0);if($cmp130){__label__=36;;}else{__label__=37;;}
if(__label__==36){var $37=HEAP32[(($priority)>>2)];var $conv132=((($37))&255);var $38=$langix;var $arrayidx133=((__ZZ9LoadVoicePKciE15voice_languages+$38)&4294967295);HEAP8[($arrayidx133)]=$conv132;var $39=$langix;var $add134=((($39)+1)&4294967295);var $arrayidx135=((__ZZ9LoadVoicePKciE15voice_languages+$add134)&4294967295);var $call137=_strcpy($arrayidx135,$arraydecay136);var $40=$len;var $41=$langix;var $add138=((($41)+($40))&4294967295);$langix=$add138;;}
var $42=$language_set;var $cmp140=((($42))|0)==0;if(!($cmp140)){__label__=24;continue $while_cond$34;}
var $call143=_strtok($arraydecay142,((__str56708)&4294967295));$language_type=$call143;$language_set=1;var $43=$language_type;var $call145=_strcpy($arraydecay144,$43);var $44=$language_type;var $call147=_strcpy($arraydecay146,$44);var $45=$language_type;var $call149=_strcpy($arraydecay148,$45);var $call151=__Z22SelectPhonemeTableNamePKc($arraydecay150);var $46=$new_translator;var $cmp152=((($46))|0)!=0;if($cmp152){__label__=39;;}else{__label__=40;;}
if(__label__==39){var $47=$new_translator;__Z16DeleteTranslatorP10Translator($47);;}
var $call156=__Z16SelectTranslatorPKc($arraydecay155);$new_translator=$call156;var $48=$new_translator;var $langopts157=(($48)&4294967295);$langopts=$langopts157;__label__=24;continue $while_cond$34;}
else if(__label__==41){var $49=$tone_only;var $cmp160=((($49))|0)==0;if(!($cmp160)){__label__=24;continue $while_cond$34;}
var $50=$p;var $51=HEAP8[($50)];var $conv1636=(tempInt=(($51)),(tempInt>=128?tempInt-256:tempInt));var $call1647=_isspace($conv1636);var $tobool1658=((($call1647))|0)!=0;var $52=$p;if($tobool1658){__lastLabel__=42;__label__=43;;}else{__lastLabel__=42;__label__=44;;}
$while_body166$$while_end$61:do{if(__label__==43){while(1){var $53=__lastLabel__==43?$56:($52);var $incdec_ptr167=(($53+1)&4294967295);$p=$incdec_ptr167;var $54=$p;var $55=HEAP8[($54)];var $conv163=(tempInt=(($55)),(tempInt>=128?tempInt-256:tempInt));var $call164=_isspace($conv163);var $tobool165=((($call164))|0)!=0;var $56=$p;if($tobool165){__lastLabel__=43;__label__=43;continue;}else{__lastLabel__=43;__label__=44;break $while_body166$$while_end$61;}}}}while(0);var $_lcssa=__lastLabel__==42?$52:($56);__Z8strncpy0PcPKci(((__ZZ9LoadVoicePKciE10voice_name)&4294967295),$_lcssa,40);__label__=24;continue $while_cond$34;}
else if(__label__==45){HEAP32[(($age)>>2)]=0;var $57=$p;var $call171=_sscanf($57,((__str54706)&4294967295),allocate([$arraydecay170,0,0,0,$age,0,0,0],["i8*",0,0,0,"i32*",0,0,0],ALLOC_STACK));var $call173=__Z10LookupMnemP8MNEM_TABPKc(((_genders)&4294967295),$arraydecay172);var $conv174=((($call173))&255);HEAP8[(((_voice_selected+12)&4294967295))]=$conv174;var $58=HEAP32[(($age)>>2)];var $conv175=((($58))&255);HEAP8[(((_voice_selected+13)&4294967295))]=$conv175;__label__=24;continue $while_cond$34;}
else if(__label__==46){var $59=$tone_only;var $tobool177=((($59))|0)!=0;if($tobool177){__label__=24;continue $while_cond$34;}
var $60=$p;var $call181=_sscanf($60,((__str57709)&4294967295),allocate([$arraydecay180,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $61=$new_translator;var $cmp182=((($61))|0)!=0;if($cmp182){__label__=48;;}else{__label__=49;;}
if(__label__==48){var $62=$new_translator;__Z16DeleteTranslatorP10Translator($62);;}
var $call186=__Z16SelectTranslatorPKc($arraydecay185);$new_translator=$call186;var $63=$new_translator;var $langopts187=(($63)&4294967295);$langopts=$langopts187;__label__=24;continue $while_cond$34;}
else if(__label__==50){var $64=$p;var $call190=_sscanf($64,((__str57709)&4294967295),allocate([$arraydecay189,0,0,0],["i8*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}
else if(__label__==51){var $65=$p;var $call193=_sscanf($65,((__str57709)&4294967295),allocate([$arraydecay192,0,0,0],["i8*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}
else if(__label__==52){var $66=$p;__ZL12VoiceFormantPc($66);__label__=24;continue $while_cond$34;}
else if(__label__==53){var $67=$p;var $call196=_sscanf($67,((__str58710)&4294967295),allocate([$pitch1,0,0,0,$pitch2,0,0,0],["i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));$n=$call196;var $68=HEAP32[(($pitch1)>>2)];var $sub197=((($68)-9)&4294967295);var $shl=($sub197)<<12;var $69=HEAP32[((_voice)>>2)];var $pitch_base=(($69+44)&4294967295);HEAP32[(($pitch_base)>>2)]=$shl;var $70=HEAP32[(($pitch2)>>2)];var $71=HEAP32[(($pitch1)>>2)];var $sub198=((($70)-($71))&4294967295);var $mul=((($sub198)*108)&4294967295);var $72=HEAP32[((_voice)>>2)];var $pitch_range=(($72+48)&4294967295);HEAP32[(($pitch_range)>>2)]=$mul;var $73=HEAP32[(($pitch1)>>2)];var $sub199=((($73)-82)&4294967295);var $conv200=((($sub199))|0);var $div=($conv200)/82;$factor=$div;var $74=$factor;var $div201=($74)/4;var $add202=1+($div201);var $mul203=($add202)*256;var $conv204=((($mul203))|0);var $75=HEAP32[((_voice)>>2)];var $formant_factor=(($75+96)&4294967295);HEAP32[(($formant_factor)>>2)]=$conv204;__label__=24;continue $while_cond$34;}
else if(__label__==54){var $76=$p;var $call207=__ZL12Read8NumbersPcPi($76,$arraydecay206);$stress_lengths_set=$call207;__label__=24;continue $while_cond$34;}
else if(__label__==55){var $77=$p;var $call210=__ZL12Read8NumbersPcPi($77,$arraydecay209);$stress_amps_set=$call210;__label__=24;continue $while_cond$34;}
else if(__label__==56){var $78=$p;var $call213=__ZL12Read8NumbersPcPi($78,$arraydecay212);$stress_add_set=$call213;__label__=24;continue $while_cond$34;}
else if(__label__==57){var $79=$p;var $call215=_sscanf($79,((__str58710)&4294967295),allocate([_option_tone_flags,0,0,0,_option_tone2,0,0,0],["i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));var $80=HEAP32[((_option_tone_flags)>>2)];var $and216=($80)&255;var $cmp217=((($and216))|0)!=0;if(!($cmp217)){__label__=24;continue $while_cond$34;}
var $81=HEAP32[((_option_tone_flags)>>2)];var $and219=($81)&255;var $82=$langopts;var $intonation_group=(($82+228)&4294967295);HEAP32[(($intonation_group)>>2)]=$and219;__label__=24;continue $while_cond$34;}
else if(__label__==59){var $83=$p;var $call234=_sscanf($83,((__str59711)&4294967295),allocate([$arraydecay223,0,0,0,$arraydecay225,0,0,0,$arraydecay227,0,0,0,$arraydecay229,0,0,0,$arraydecay231,0,0,0,$arraydecay233,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));$n=$call234;var $84=$langopts;var $intonation_group235=(($84+228)&4294967295);HEAP32[(($intonation_group235)>>2)]=0;$ix=0;var $85=$ix;var $86=$n;var $cmp2379=((($85))|0)<((($86))|0);if(!($cmp2379)){__label__=24;continue $while_cond$34;}
while(1){var $87=$ix;var $arrayidx239=(($names+$87*40)&4294967295);var $arraydecay240=(($arrayidx239)&4294967295);var $call241=_strcmp($arraydecay240,((__str60712)&4294967295));var $cmp242=((($call241))|0)==0;if($cmp242){__label__=64;;}else{__label__=61;;}
if(__label__==61){var $88=$ix;var $arrayidx245=(($names+$88*40)&4294967295);var $arraydecay246=(($arrayidx245)&4294967295);var $call247=__ZL10LookupTunePKc($arraydecay246);HEAP32[(($value)>>2)]=$call247;var $cmp248=((($call247))|0)<0;if($cmp248){__label__=62;;}else{__label__=63;;}
if(__label__==62){var $89=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($89+12)&4294967295);var $90=HEAP32[(($_stderr)>>2)];var $91=$ix;var $arrayidx250=(($names+$91*40)&4294967295);var $arraydecay251=(($arrayidx250)&4294967295);var $call252=_fprintf($90,((__str61713)&4294967295),allocate([$arraydecay251,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==63){var $92=HEAP32[(($value)>>2)];var $conv254=((($92))&255);var $93=$ix;var $94=$langopts;var $tunes=(($94+232)&4294967295);var $arrayidx255=(($tunes+$93)&4294967295);HEAP8[($arrayidx255)]=$conv254;;}}
var $95=$ix;var $inc=((($95)+1)&4294967295);$ix=$inc;var $96=$ix;var $97=$n;var $cmp237=((($96))|0)<((($97))|0);if($cmp237){__label__=60;continue;}else{__label__=24;continue $while_cond$34;}}}
else if(__label__==32){var $31=$p;var $32=HEAP8[($31)];var $conv26117=(tempInt=(($32)),(tempInt>=128?tempInt-256:tempInt));var $cmp26218=((($conv26117))|0)!=0;if(!($cmp26218)){__label__=24;continue $while_cond$34;}
$while_cond264_preheader$90:while(1){var $100=$p;var $101=HEAP8[($100)];var $conv26510=(tempInt=(($101)),(tempInt>=128?tempInt-256:tempInt));var $call26611=_isspace($conv26510);var $tobool26712=((($call26611))|0)!=0;if($tobool26712){__label__=67;;}else{__label__=68;;}
$while_body268$$while_end270$92:do{if(__label__==67){while(1){var $102=$p;var $incdec_ptr269=(($102+1)&4294967295);$p=$incdec_ptr269;var $103=$p;var $104=HEAP8[($103)];var $conv265=(tempInt=(($104)),(tempInt>=128?tempInt-256:tempInt));var $call266=_isspace($conv265);var $tobool267=((($call266))|0)!=0;if($tobool267){__label__=67;continue;}else{__label__=68;break $while_body268$$while_end270$92;}}}}while(0);$n=-1;var $105=$p;var $call271=_atoi($105);$n=$call271;var $cmp272=((($call271))|0)>0;if($cmp272){__label__=69;;}else{__label__=71;;}
$land_lhs_true273$$while_cond279_preheader$96:do{if(__label__==69){var $106=$n;var $cmp274=((($106))|0)<32;if(!($cmp274)){__label__=71;break $land_lhs_true273$$while_cond279_preheader$96;}
var $107=$p;var $incdec_ptr276=(($107+1)&4294967295);$p=$incdec_ptr276;var $108=$n;var $shl277=1<<($108);var $109=$conditional_rules;var $or=($109)|($shl277);$conditional_rules=$or;;}}while(0);var $110=$p;var $111=HEAP8[($110)];var $conv28013=(tempInt=(($111)),(tempInt>=128?tempInt-256:tempInt));var $call28114=_isalnum($conv28013);var $tobool28215=((($call28114))|0)!=0;if($tobool28215){__label__=72;;}else{__label__=65;;}
$while_body283$$while_cond260_loopexit$100:do{if(__label__==72){while(1){var $112=$p;var $incdec_ptr284=(($112+1)&4294967295);$p=$incdec_ptr284;var $113=$p;var $114=HEAP8[($113)];var $conv280=(tempInt=(($114)),(tempInt>=128?tempInt-256:tempInt));var $call281=_isalnum($conv280);var $tobool282=((($call281))|0)!=0;if($tobool282){__label__=72;continue;}else{__label__=65;break $while_body283$$while_cond260_loopexit$100;}}}}while(0);var $98=$p;var $99=HEAP8[($98)];var $conv261=(tempInt=(($99)),(tempInt>=128?tempInt-256:tempInt));var $cmp262=((($conv261))|0)!=0;if($cmp262){__label__=66;continue $while_cond264_preheader$90;}else{__label__=24;continue $while_cond$34;}}}
else if(__label__==73){var $115=$phonemes_set;var $cmp288=((($115))|0)==0;if($cmp288){__label__=74;;}else{__label__=75;;}
if(__label__==74){var $call291=__Z22SelectPhonemeTableNamePKc($arraydecay290);$phonemes_set=1;;}
var $116=$key;var $117=$p;__ZL18PhonemeReplacementiPc($116,$117);__label__=24;continue $while_cond$34;}
else if(__label__==76){var $118=$p;var $119=$langopts;var $word_gap=(($119)&4294967295);var $120=$langopts;var $vowel_pause=(($120+4)&4294967295);var $call294=_sscanf($118,((__str58710)&4294967295),allocate([$word_gap,0,0,0,$vowel_pause,0,0,0],["i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}
else if(__label__==77){var $121=$p;var $122=$langopts;var $stress_rule=(($122+8)&4294967295);var $123=$langopts;var $stress_flags=(($123+12)&4294967295);var $124=$langopts;var $unstressed_wd1=(($124+16)&4294967295);var $125=$langopts;var $unstressed_wd2=(($125+20)&4294967295);var $call296=_sscanf($121,((__str62714)&4294967295),allocate([$stress_rule,0,0,0,$stress_flags,0,0,0,$unstressed_wd1,0,0,0,$unstressed_wd2,0,0,0],["i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}
else if(__label__==78){var $126=$p;var $call298=_sscanf($126,((__str63715)&4294967295),allocate([$value,0,0,0],["i32*",0,0,0],ALLOC_STACK));var $cmp299=((($call298))|0)==1;var $127=HEAP32[(($value)>>2)];var $cmp301=((($127))|0)<20;var $or_cond1=($cmp299)&($cmp301);if(!($or_cond1)){__label__=24;continue $while_cond$34;}
var $128=HEAP32[(($value)>>2)];var $arrayidx303=((_charsets+$128*4)&4294967295);var $129=HEAP32[(($arrayidx303)>>2)];var $130=$new_translator;var $charset_a0=(($130+696)&4294967295);HEAP32[(($charset_a0)>>2)]=$129;__label__=24;continue $while_cond$34;}
else if(__label__==80){var $131=$p;var $132=$langopts;var $numbers=(($132+184)&4294967295);var $133=$langopts;var $numbers2=(($133+188)&4294967295);var $call306=_sscanf($131,((__str58710)&4294967295),allocate([$numbers,0,0,0,$numbers2,0,0,0],["i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}
else if(__label__==81){HEAP32[(($value2)>>2)]=0;var $134=$p;var $call309=_sscanf($134,((__str64716)&4294967295),allocate([$arraydecay308,0,0,0,$value,0,0,0,$value2,0,0,0],["i8*",0,0,0,"i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));var $cmp310=((($call309))|0)>=2;if($cmp310){__label__=82;;}else{__label__=84;;}
$land_lhs_true311$$if_else318$114:do{if(__label__==82){var $call313=__Z10LookupMnemP8MNEM_TABPKc(((__ZL11options_tab)&4294967295),$arraydecay312);$ix=$call313;var $cmp314=((($call313))|0)>=0;if(!($cmp314)){__label__=84;break $land_lhs_true311$$if_else318$114;}
var $135=HEAP32[(($value)>>2)];var $136=$ix;var $137=$langopts;var $param=(($137+24)&4294967295);var $arrayidx316=(($param+$136*4)&4294967295);HEAP32[(($arrayidx316)>>2)]=$135;var $138=HEAP32[(($value2)>>2)];var $139=$ix;var $140=$langopts;var $param2=(($140+100)&4294967295);var $arrayidx317=(($param2+$139*4)&4294967295);HEAP32[(($arrayidx317)>>2)]=$138;__label__=24;continue $while_cond$34;}}while(0);var $141=HEAP32[((__impure_ptr)>>2)];var $_stderr319=(($141+12)&4294967295);var $142=HEAP32[(($_stderr319)>>2)];var $143=$p;var $call321=_fprintf($142,((__str65717)&4294967295),allocate([$arraydecay320,0,0,0,$143,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}
else if(__label__==85){HEAP32[(($value)>>2)]=0;var $144=HEAP32[((_voice)>>2)];var $echo_amp=(($144+80)&4294967295);HEAP32[(($echo_amp)>>2)]=0;var $145=$p;var $146=HEAP32[((_voice)>>2)];var $echo_delay=(($146+76)&4294967295);var $147=HEAP32[((_voice)>>2)];var $echo_amp324=(($147+80)&4294967295);var $call325=_sscanf($145,((__str58710)&4294967295),allocate([$echo_delay,0,0,0,$echo_amp324,0,0,0],["i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}
else if(__label__==86){var $148=$p;var $call327=_sscanf($148,((__str63715)&4294967295),allocate([$value,0,0,0],["i32*",0,0,0],ALLOC_STACK));var $cmp328=((($call327))|0)==1;if(!($cmp328)){__label__=24;continue $while_cond$34;}
var $149=HEAP32[(($value)>>2)];var $mul330=((($149)*32)&4294967295);var $150=HEAP32[((_voice)>>2)];var $flutter=(($150+68)&4294967295);HEAP32[(($flutter)>>2)]=$mul330;__label__=24;continue $while_cond$34;}
else if(__label__==88){var $151=$p;var $call333=_sscanf($151,((__str63715)&4294967295),allocate([$value,0,0,0],["i32*",0,0,0],ALLOC_STACK));var $cmp334=((($call333))|0)==1;if(!($cmp334)){__label__=24;continue $while_cond$34;}
var $152=HEAP32[(($value)>>2)];var $153=HEAP32[((_voice)>>2)];var $roughness=(($153+72)&4294967295);HEAP32[(($roughness)>>2)]=$152;__label__=24;continue $while_cond$34;}
else if(__label__==90){var $154=$p;var $call338=_sscanf($154,((__str63715)&4294967295),allocate([$value,0,0,0],["i32*",0,0,0],ALLOC_STACK));var $cmp339=((($call338))|0)==1;if(!($cmp339)){__label__=24;continue $while_cond$34;}
var $155=HEAP32[(($value)>>2)];var $cmp341=((($155))|0)>4;if($cmp341){__label__=92;;}else{__label__=93;;}
if(__label__==92){var $156=HEAP32[((_voice)>>2)];var $peak_shape=(($156+88)&4294967295);HEAP32[(($peak_shape)>>2)]=1;HEAP32[(($value)>>2)]=4;;}
var $157=HEAP32[(($value)>>2)];var $add344=((($157)+1)&4294967295);var $158=HEAP32[((_voice)>>2)];var $n_harmonic_peaks=(($158+84)&4294967295);HEAP32[(($n_harmonic_peaks)>>2)]=$add344;__label__=24;continue $while_cond$34;}
else if(__label__==94){var $159=$p;__Z14ReadTonePointsPcPi($159,$arraydecay347);var $160=HEAP32[((_voice)>>2)];__ZL13SetToneAdjustP7voice_tPi($160,$arraydecay348);__label__=24;continue $while_cond$34;}
else if(__label__==95){var $161=$p;var $call350=_sscanf($161,((__str63715)&4294967295),allocate([$value,0,0,0],["i32*",0,0,0],ALLOC_STACK));var $cmp351=((($call350))|0)==1;if(!($cmp351)){__label__=24;continue $while_cond$34;}
var $162=HEAP32[(($value)>>2)];var $mul353=((($162)*64)&4294967295);var $div354=((((($mul353))|0)/100)|0);var $163=HEAP32[((_voice)>>2)];var $voicing=(($163+92)&4294967295);HEAP32[(($voicing)>>2)]=$div354;__label__=24;continue $while_cond$34;}
else if(__label__==97){var $164=$p;var $165=HEAP32[((_voice)>>2)];var $breath=(($165+272)&4294967295);var $arrayidx357=(($breath+4)&4294967295);var $call358=__ZL12Read8NumbersPcPi($164,$arrayidx357);var $166=HEAP32[((_voice)>>2)];var $breath359=(($166+272)&4294967295);var $arrayidx360=(($breath359)&4294967295);HEAP32[(($arrayidx360)>>2)]=$call358;$ix=1;;while(1){var $167=$ix;var $rem=((($167))|0)%2;var $tobool364=((($rem))|0)!=0;if($tobool364){__label__=99;;}else{__label__=100;;}
if(__label__==99){var $168=$ix;var $169=HEAP32[((_voice)>>2)];var $breath366=(($169+272)&4294967295);var $arrayidx367=(($breath366+$168*4)&4294967295);var $170=HEAP32[(($arrayidx367)>>2)];var $sub368=(((-($170)))&4294967295);var $171=$ix;var $172=HEAP32[((_voice)>>2)];var $breath369=(($172+272)&4294967295);var $arrayidx370=(($breath369+$171*4)&4294967295);HEAP32[(($arrayidx370)>>2)]=$sub368;;}
var $173=$ix;var $inc373=((($173)+1)&4294967295);$ix=$inc373;var $cmp362=((($inc373))|0)<8;if($cmp362){__label__=98;continue;}else{__label__=24;continue $while_cond$34;}}}
else if(__label__==101){var $174=$p;var $175=HEAP32[((_voice)>>2)];var $breathw=(($175+308)&4294967295);var $arrayidx376=(($breathw+4)&4294967295);var $call377=__ZL12Read8NumbersPcPi($174,$arrayidx376);var $176=HEAP32[((_voice)>>2)];var $breathw378=(($176+308)&4294967295);var $arrayidx379=(($breathw378)&4294967295);HEAP32[(($arrayidx379)>>2)]=$call377;__label__=24;continue $while_cond$34;}
else if(__label__==102){var $177=$p;var $178=HEAP32[((_voice)>>2)];var $consonant_amp=(($178+100)&4294967295);var $179=HEAP32[((_voice)>>2)];var $consonant_ampv=(($179+104)&4294967295);var $call381=_sscanf($177,((__str58710)&4294967295),allocate([$consonant_amp,0,0,0,$consonant_ampv,0,0,0],["i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));HEAP32[(($value)>>2)]=$call381;__label__=24;continue $while_cond$34;}
else if(__label__==103){var $180=$p;var $181=HEAP32[((_voice)>>2)];var $speed_percent=(($181+64)&4294967295);var $call383=_sscanf($180,((__str63715)&4294967295),allocate([$speed_percent,0,0,0],["i32*",0,0,0],ALLOC_STACK));__label__=24;continue $while_cond$34;}
else if(__label__==104){HEAP32[(($srate)>>2)]=16000;HEAP8[($arrayidx385)]=0;var $182=$p;var $call388=_sscanf($182,((__str66718)&4294967295),allocate([$arraydecay386,0,0,0,$arraydecay387,0,0,0,$srate,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i32*",0,0,0],ALLOC_STACK));var $183=HEAP32[(($srate)>>2)];var $call391=__Z15LoadMbrolaTablePKcS0_i($arraydecay389,$arraydecay390,$183);var $cmp392=((($call391))|0)!=0;if($cmp392){__label__=105;;}else{__label__=106;;}
if(__label__==105){var $184=HEAP32[((__impure_ptr)>>2)];var $_stderr394=(($184+12)&4294967295);var $185=HEAP32[(($_stderr394)>>2)];var $186=_fwrite(((__str67719)&4294967295),23,1,$185);;}
var $187=HEAP32[(($srate)>>2)];var $188=HEAP32[((_voice)>>2)];var $samplerate=(($188+108)&4294967295);HEAP32[(($samplerate)>>2)]=$187;__label__=24;continue $while_cond$34;}
else if(__label__==107){var $189=HEAP32[((_voice)>>2)];var $klattv=(($189+112)&4294967295);var $arrayidx398=(($klattv)&4294967295);HEAP32[(($arrayidx398)>>2)]=1;var $190=$p;var $191=HEAP32[((_voice)>>2)];var $klattv399=(($191+112)&4294967295);var $arraydecay400=(($klattv399)&4294967295);var $call401=__ZL12Read8NumbersPcPi($190,$arraydecay400);var $192=HEAP32[((_voice)>>2)];var $klattv402=(($192+112)&4294967295);var $arrayidx403=(($klattv402+20)&4294967295);var $193=HEAP32[(($arrayidx403)>>2)];var $sub404=((($193)-40)&4294967295);HEAP32[(($arrayidx403)>>2)]=$sub404;__label__=24;continue $while_cond$34;}
else if(__label__==108){var $194=$p;var $call406=__ZL12Read8NumbersPcPi($194,((_speed+32)&4294967295));__Z8SetSpeedi(3);__label__=24;continue $while_cond$34;}}
$if_end423$$while_end419$146:do{if(__label__==112){var $_pr=$f_voice;var $cmp420=((($_pr))|0)!=0;if(!($cmp420)){__label__=114;break $if_end423$$while_end419$146;}
var $201=$f_voice;var $call422=_fclose($201);;}}while(0);var $202=$new_translator;var $cmp424=((($202))|0)==0;if($cmp424){__label__=115;;}else{__label__=117;;}
$land_lhs_true425$$if_end430$150:do{if(__label__==115){var $203=$tone_only;var $tobool426=((($203))|0)!=0;if($tobool426){__label__=117;break $land_lhs_true425$$if_end430$150;}
var $arraydecay428=(($translator_name)&4294967295);var $call429=__Z16SelectTranslatorPKc($arraydecay428);$new_translator=$call429;;}}while(0);__Z8SetSpeedi(3);$ix=0;;$for_body433$154:while(1){var $204=$ix;var $205=HEAP32[((_voice)>>2)];var $freq=(($205+144)&4294967295);var $arrayidx434=(($freq+$204*2)&4294967295);var $206=HEAP16[(($arrayidx434)>>1)];var $207=$ix;var $208=HEAP32[((_voice)>>2)];var $freq2=(($208+216)&4294967295);var $arrayidx435=(($freq2+$207*2)&4294967295);HEAP16[(($arrayidx435)>>1)]=$206;var $209=$ix;var $210=HEAP32[((_voice)>>2)];var $height=(($210+162)&4294967295);var $arrayidx436=(($height+$209*2)&4294967295);var $211=HEAP16[(($arrayidx436)>>1)];var $212=$ix;var $213=HEAP32[((_voice)>>2)];var $height2=(($213+234)&4294967295);var $arrayidx437=(($height2+$212*2)&4294967295);HEAP16[(($arrayidx437)>>1)]=$211;var $214=$ix;var $215=HEAP32[((_voice)>>2)];var $width=(($215+180)&4294967295);var $arrayidx438=(($width+$214*2)&4294967295);var $216=HEAP16[(($arrayidx438)>>1)];var $217=$ix;var $218=HEAP32[((_voice)>>2)];var $width2=(($218+252)&4294967295);var $arrayidx439=(($width2+$217*2)&4294967295);HEAP16[(($arrayidx439)>>1)]=$216;var $219=$ix;var $inc441=((($219)+1)&4294967295);$ix=$inc441;var $cmp432=((($inc441))|0)<9;if($cmp432){__label__=118;continue $for_body433$154;}else{__label__=119;break $for_body433$154;}}
var $220=$tone_only;var $tobool443=((($220))|0)!=0;if($tobool443){__label__=120;;}else{__label__=121;;}
if(__label__==120){var $221=HEAP32[((_translator)>>2)];$new_translator=$221;;}
else if(__label__==121){var $arraydecay446=(($phonemes_name)&4294967295);var $call447=__Z22SelectPhonemeTableNamePKc($arraydecay446);$ix=$call447;var $cmp448=((($call447))|0)<0;if($cmp448){__label__=122;;}else{__label__=123;;}
if(__label__==122){var $222=HEAP32[((__impure_ptr)>>2)];var $_stderr450=(($222+12)&4294967295);var $223=HEAP32[(($_stderr450)>>2)];var $arraydecay451=(($phonemes_name)&4294967295);var $call452=_fprintf($223,((__str69721)&4294967295),allocate([$arraydecay451,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
var $224=$ix;var $225=HEAP32[((_voice)>>2)];var $phoneme_tab_ix=(($225+40)&4294967295);HEAP32[(($phoneme_tab_ix)>>2)]=$224;var $226=$ix;var $227=$new_translator;var $phoneme_tab_ix454=(($227+656)&4294967295);HEAP32[(($phoneme_tab_ix454)>>2)]=$226;var $228=$new_translator;var $arraydecay455=(($new_dictionary)&4294967295);var $229=$control_addr;var $and456=($229)&4;var $call457=__Z14LoadDictionaryP10TranslatorPKci($228,$arraydecay455,$and456);$error=$call457;var $230=HEAP8[(((_dictionary_name)&4294967295))];var $conv458=(tempInt=(($230)),(tempInt>=128?tempInt-256:tempInt));var $cmp459=((($conv458))|0)==0;if($cmp459){__label__=124;;}else{__label__=125;;}
if(__label__==124){$retval=0;__label__=137;break $return$$if_end51$12;}
else if(__label__==125){var $231=$conditional_rules;var $232=$new_translator;var $dict_condition=(($232+692)&4294967295);HEAP32[(($dict_condition)>>2)]=$231;var $233=$langix;var $arrayidx462=((__ZZ9LoadVoicePKciE15voice_languages+$233)&4294967295);HEAP8[($arrayidx462)]=0;;}}
var $234=$new_translator;var $langopts464=(($234)&4294967295);$langopts=$langopts464;var $235=$langopts;var $param465=(($235+24)&4294967295);var $arrayidx466=(($param465+24)&4294967295);var $236=HEAP32[(($arrayidx466)>>2)];HEAP32[(($value)>>2)]=$236;var $cmp467=((($236))|0)!=0;if($cmp467){__label__=127;;}else{__label__=128;;}
if(__label__==127){var $237=$new_translator;var $238=HEAP32[(($value)>>2)];__Z13SetLengthModsP10Translatori($237,$238);;}
var $239=HEAP32[((_voice)>>2)];var $width470=(($239+180)&4294967295);var $arrayidx471=(($width470)&4294967295);var $240=HEAP16[(($arrayidx471)>>1)];var $conv472=(tempInt=(($240)),(tempInt>=32768?tempInt-65536:tempInt));var $mul473=((($conv472)*105)&4294967295);var $div474=((((($mul473))|0)/100)|0);var $conv475=((($div474))&65535);var $241=HEAP32[((_voice)>>2)];var $width476=(($241+180)&4294967295);var $arrayidx477=(($width476)&4294967295);HEAP16[(($arrayidx477)>>1)]=$conv475;var $242=$tone_only;var $tobool478=((($242))|0)!=0;if($tobool478){__label__=130;;}else{__label__=129;;}
if(__label__==129){var $243=$new_translator;HEAP32[((_translator)>>2)]=$243;;}
$ix=0;var $244=$ix;var $245=$stress_lengths_set;var $cmp4825=((($244))|0)<((($245))|0);if($cmp4825){__label__=131;;}else{__label__=132;;}
$for_body483$$for_end490$173:do{if(__label__==131){while(1){var $246=$ix;var $arrayidx484=(($stress_lengths+$246*4)&4294967295);var $247=HEAP32[(($arrayidx484)>>2)];var $conv485=((($247))&65535);var $248=$ix;var $249=HEAP32[((_translator)>>2)];var $stress_lengths486=(($249+676)&4294967295);var $arrayidx487=(($stress_lengths486+$248*2)&4294967295);HEAP16[(($arrayidx487)>>1)]=$conv485;var $250=$ix;var $inc489=((($250)+1)&4294967295);$ix=$inc489;var $251=$ix;var $252=$stress_lengths_set;var $cmp482=((($251))|0)<((($252))|0);if($cmp482){__label__=131;continue;}else{__label__=132;break $for_body483$$for_end490$173;}}}}while(0);$ix=0;var $253=$ix;var $254=$stress_add_set;var $cmp4924=((($253))|0)<((($254))|0);if($cmp4924){__label__=133;;}else{__label__=134;;}
$for_body493$$for_end502$177:do{if(__label__==133){while(1){var $255=$ix;var $arrayidx494=(($stress_add+$255*4)&4294967295);var $256=HEAP32[(($arrayidx494)>>2)];var $257=$ix;var $258=HEAP32[((_translator)>>2)];var $stress_lengths495=(($258+676)&4294967295);var $arrayidx496=(($stress_lengths495+$257*2)&4294967295);var $259=HEAP16[(($arrayidx496)>>1)];var $conv497=(tempInt=(($259)),(tempInt>=32768?tempInt-65536:tempInt));var $add498=((($conv497)+($256))&4294967295);var $conv499=((($add498))&65535);HEAP16[(($arrayidx496)>>1)]=$conv499;var $260=$ix;var $inc501=((($260)+1)&4294967295);$ix=$inc501;var $261=$ix;var $262=$stress_add_set;var $cmp492=((($261))|0)<((($262))|0);if($cmp492){__label__=133;continue;}else{__label__=134;break $for_body493$$for_end502$177;}}}}while(0);$ix=0;var $263=$ix;var $264=$stress_amps_set;var $cmp5043=((($263))|0)<((($264))|0);if($cmp5043){__label__=135;;}else{__label__=136;;}
$for_body505$$for_end516$181:do{if(__label__==135){while(1){var $265=$ix;var $arrayidx506=(($stress_amps+$265*4)&4294967295);var $266=HEAP32[(($arrayidx506)>>2)];var $conv507=((($266))&255);var $267=$ix;var $268=HEAP32[((_translator)>>2)];var $stress_amps508=(($268+660)&4294967295);var $arrayidx509=(($stress_amps508+$267)&4294967295);HEAP8[($arrayidx509)]=$conv507;var $269=$ix;var $arrayidx510=(($stress_amps+$269*4)&4294967295);var $270=HEAP32[(($arrayidx510)>>2)];var $sub511=((($270)-1)&4294967295);var $conv512=((($sub511))&255);var $271=$ix;var $272=HEAP32[((_translator)>>2)];var $stress_amps_r=(($272+668)&4294967295);var $arrayidx513=(($stress_amps_r+$271)&4294967295);HEAP8[($arrayidx513)]=$conv512;var $273=$ix;var $inc515=((($273)+1)&4294967295);$ix=$inc515;var $274=$ix;var $275=$stress_amps_set;var $cmp504=((($274))|0)<((($275))|0);if($cmp504){__label__=135;continue;}else{__label__=136;break $for_body505$$for_end516$181;}}}}while(0);var $276=HEAP32[((_voice)>>2)];$retval=$276;;}}while(0);var $277=$retval;STACKTOP=__stackBase__;return $277;return null;}
function __ZL11fgets_stripPciP7__sFILE($buf,$size,$f_in){;var __label__;var $retval;var $buf_addr;var $size_addr;var $f_in_addr;var $len;var $p;$buf_addr=$buf;$size_addr=$size;$f_in_addr=$f_in;var $0=$buf_addr;var $1=$size_addr;var $2=$f_in_addr;var $call=_fgets($0,$1,$2);var $cmp=((($call))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $3=$buf_addr;var $call1=_strlen($3);$len=$call1;;while(1){var $4=$len;var $dec=((($4)-1)&4294967295);$len=$dec;var $cmp2=((($dec))|0)>0;if(!($cmp2)){__label__=6;break;}
var $5=$len;var $6=$buf_addr;var $arrayidx=(($6+$5)&4294967295);var $7=HEAP8[($arrayidx)];var $conv=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $call3=_isspace($conv);var $tobool=((($call3))|0)!=0;if(!($tobool)){__label__=6;break;}
var $8=$len;var $9=$buf_addr;var $arrayidx4=(($9+$8)&4294967295);HEAP8[($arrayidx4)]=0;__label__=3;continue;}
var $10=$buf_addr;var $call5=_strstr($10,((__str82734)&4294967295));$p=$call5;var $cmp6=((($call5))|0)!=0;if($cmp6){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $11=$p;HEAP8[($11)]=0;;}
var $12=$buf_addr;$retval=$12;;}
var $13=$retval;;return $13;return null;}
function __ZL12VoiceFormantPc($p){var __stackBase__=STACKTOP;STACKTOP+=20;_memset(__stackBase__,0,20);var __label__;var $p_addr;var $ix;var $formant=__stackBase__;var $freq=__stackBase__+4;var $height=__stackBase__+8;var $width=__stackBase__+12;var $freqadd=__stackBase__+16;$p_addr=$p;HEAP32[(($freq)>>2)]=100;HEAP32[(($height)>>2)]=100;HEAP32[(($width)>>2)]=100;HEAP32[(($freqadd)>>2)]=0;var $0=$p_addr;var $call=_sscanf($0,((__str81733)&4294967295),allocate([$formant,0,0,0,$freq,0,0,0,$height,0,0,0,$width,0,0,0,$freqadd,0,0,0],["i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));$ix=$call;var $1=$ix;var $cmp=((($1))|0)<2;if($cmp){__label__=9;;}else{__label__=1;;}
$return$$if_end$2:do{if(__label__==1){var $2=HEAP32[(($formant)>>2)];var $cmp1=((($2))|0)<0;var $3=HEAP32[(($formant)>>2)];var $cmp2=((($3))|0)>8;var $or_cond=($cmp1)|($cmp2);if($or_cond){__label__=9;break $return$$if_end$2;}
var $4=HEAP32[(($freq)>>2)];var $cmp5=((($4))|0)>=0;if($cmp5){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $5=HEAP32[(($freq)>>2)];var $conv=((($5))|0);var $mul=($conv)*2.56001;var $conv7=((($mul))|0);var $conv8=((($conv7))&65535);var $6=HEAP32[(($formant)>>2)];var $7=HEAP32[((_voice)>>2)];var $freq9=(($7+144)&4294967295);var $arrayidx=(($freq9+$6*2)&4294967295);HEAP16[(($arrayidx)>>1)]=$conv8;;}
var $8=HEAP32[(($height)>>2)];var $cmp11=((($8))|0)>=0;if($cmp11){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $9=HEAP32[(($height)>>2)];var $conv13=((($9))|0);var $mul14=($conv13)*2.56001;var $conv15=((($mul14))|0);var $conv16=((($conv15))&65535);var $10=HEAP32[(($formant)>>2)];var $11=HEAP32[((_voice)>>2)];var $height17=(($11+162)&4294967295);var $arrayidx18=(($height17+$10*2)&4294967295);HEAP16[(($arrayidx18)>>1)]=$conv16;;}
var $12=HEAP32[(($width)>>2)];var $cmp20=((($12))|0)>=0;if($cmp20){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $13=HEAP32[(($width)>>2)];var $conv22=((($13))|0);var $mul23=($conv22)*2.56001;var $conv24=((($mul23))|0);var $conv25=((($conv24))&65535);var $14=HEAP32[(($formant)>>2)];var $15=HEAP32[((_voice)>>2)];var $width26=(($15+180)&4294967295);var $arrayidx27=(($width26+$14*2)&4294967295);HEAP16[(($arrayidx27)>>1)]=$conv25;;}
var $16=HEAP32[(($freqadd)>>2)];var $conv29=((($16))&65535);var $17=HEAP32[(($formant)>>2)];var $18=HEAP32[((_voice)>>2)];var $freqadd30=(($18+198)&4294967295);var $arrayidx31=(($freqadd30+$17*2)&4294967295);HEAP16[(($arrayidx31)>>1)]=$conv29;;}}while(0);STACKTOP=__stackBase__;return;return;}
function __ZL12Read8NumbersPcPi($data_in,$data){;var __label__;var $data_in_addr;var $data_addr;$data_in_addr=$data_in;$data_addr=$data;var $0=$data_addr;var $1=$0;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$1;$stop$=$dest$+12;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $2=$data_in_addr;var $3=$data_addr;var $arrayidx=(($3)&4294967295);var $4=$data_addr;var $arrayidx1=(($4+4)&4294967295);var $5=$data_addr;var $arrayidx2=(($5+8)&4294967295);var $6=$data_addr;var $arrayidx3=(($6+12)&4294967295);var $7=$data_addr;var $arrayidx4=(($7+16)&4294967295);var $8=$data_addr;var $arrayidx5=(($8+20)&4294967295);var $9=$data_addr;var $arrayidx6=(($9+24)&4294967295);var $10=$data_addr;var $arrayidx7=(($10+28)&4294967295);var $call=_sscanf($2,((__str80732)&4294967295),allocate([$arrayidx,0,0,0,$arrayidx1,0,0,0,$arrayidx2,0,0,0,$arrayidx3,0,0,0,$arrayidx4,0,0,0,$arrayidx5,0,0,0,$arrayidx6,0,0,0,$arrayidx7,0,0,0],["i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0,"i32*",0,0,0],ALLOC_STACK));;return $call;return null;}
function __ZL10LookupTunePKc($name){;var __label__;var $retval;var $name_addr;var $ix;$name_addr=$name;$ix=0;;while(1){var $0=$ix;var $1=HEAP32[((_n_tunes)>>2)];var $cmp=((($0))|0)<((($1))|0);if(!($cmp)){__label__=5;break;}
var $2=$name_addr;var $3=$ix;var $4=HEAP32[((_tunes)>>2)];var $arrayidx=(($4+68*$3)&4294967295);var $name1=(($arrayidx)&4294967295);var $arraydecay=(($name1)&4294967295);var $call=_strcmp($2,$arraydecay);var $cmp2=((($call))|0)==0;var $5=$ix;if($cmp2){__label__=3;break;}
var $inc=((($5)+1)&4294967295);$ix=$inc;__label__=1;continue;}
if(__label__==5){$retval=-1;;}
else if(__label__==3){$retval=$5;;}
var $6=$retval;;return $6;return null;}
function __ZL18PhonemeReplacementiPc($type,$p){var __stackBase__=STACKTOP;STACKTOP+=28;_memset(__stackBase__,0,28);var __label__;var $type_addr;var $p_addr;var $n;var $phon;var $flags=__stackBase__;var $phon_string1=__stackBase__+4;var $phon_string2=__stackBase__+16;$type_addr=$type;$p_addr=$p;HEAP32[(($flags)>>2)]=0;var $arraydecay=(($phon_string2)&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=((__str60712)&4294967295);$dest$=$arraydecay;$stop$=$src$+5;if(($dest$%4)==($src$%4)&&5>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $0=$p_addr;var $arraydecay1=(($phon_string1)&4294967295);var $arraydecay2=(($phon_string2)&4294967295);var $call3=_sscanf($0,((__str79731)&4294967295),allocate([$flags,0,0,0,$arraydecay1,0,0,0,$arraydecay2,0,0,0],["i32*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));$n=$call3;var $1=$n;var $cmp=((($1))|0)<2;var $2=HEAP32[((_n_replace_phonemes)>>2)];var $cmp4=((($2))|0)>=60;var $or_cond=($cmp)|($cmp4);if($or_cond){__label__=3;;}else{__label__=1;;}
$return$$if_end$2:do{if(__label__==1){var $arraydecay5=(($phon_string1)&4294967295);var $call6=__Z19LookupPhonemeStringPKc($arraydecay5);$phon=$call6;var $cmp7=((($call6))|0)==0;if($cmp7){__label__=3;break $return$$if_end$2;}
var $3=$phon;var $conv=((($3))&255);var $4=HEAP32[((_n_replace_phonemes)>>2)];var $arrayidx=((_replace_phonemes+$4*3)&4294967295);var $old_ph=(($arrayidx)&4294967295);HEAP8[($old_ph)]=$conv;var $arraydecay10=(($phon_string2)&4294967295);var $call11=__Z19LookupPhonemeStringPKc($arraydecay10);var $conv12=((($call11))&255);var $5=HEAP32[((_n_replace_phonemes)>>2)];var $arrayidx13=((_replace_phonemes+$5*3)&4294967295);var $new_ph=(($arrayidx13+1)&4294967295);HEAP8[($new_ph)]=$conv12;var $6=HEAP32[(($flags)>>2)];var $conv14=((($6))&255);var $7=HEAP32[((_n_replace_phonemes)>>2)];var $inc=((($7)+1)&4294967295);HEAP32[((_n_replace_phonemes)>>2)]=$inc;var $arrayidx15=((_replace_phonemes+$7*3)&4294967295);var $type16=(($arrayidx15+2)&4294967295);HEAP8[($type16)]=$conv14;;}}while(0);STACKTOP=__stackBase__;return;return;}
function __Z16LoadVoiceVariantPKci($vname,$variant_num){var __stackBase__=STACKTOP;STACKTOP+=60;_memset(__stackBase__,0,60);var __label__;var $retval;var $vname_addr;var $variant_num_addr;var $v;var $variant_name;var $buf=__stackBase__;$vname_addr=$vname;$variant_num_addr=$variant_num;var $arraydecay=(($buf)&4294967295);var $0=$vname_addr;__Z8strncpy0PcPKci($arraydecay,$0,60);var $arraydecay1=(($buf)&4294967295);var $1=$variant_num_addr;__ZL23ExtractVoiceVariantNamePci($arraydecay1,$1);$variant_name=((__ZZL23ExtractVoiceVariantNamePciE12variant_name)&4294967295);var $arraydecay2=(($buf)&4294967295);var $call3=__Z9LoadVoicePKci($arraydecay2,0);$v=$call3;var $cmp=((($call3))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $2=$variant_name;var $arrayidx=(($2)&4294967295);var $3=HEAP8[($arrayidx)];var $conv=(tempInt=(($3)),(tempInt>=128?tempInt-256:tempInt));var $cmp4=((($conv))|0)!=0;if($cmp4){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $4=$variant_name;var $call6=__Z9LoadVoicePKci($4,2);$v=$call6;;}
var $5=$v;$retval=$5;;}
var $6=$retval;STACKTOP=__stackBase__;return $6;return null;}
function __ZL23ExtractVoiceVariantNamePci($vname,$variant_num){var __stackBase__=STACKTOP;STACKTOP+=8;_memset(__stackBase__,0,8);var __label__;var __lastLabel__=null;var $vname_addr;var $variant_num_addr;var $p;var $variant_prefix=__stackBase__;$vname_addr=$vname;$variant_num_addr=$variant_num;HEAP8[(((__ZZL23ExtractVoiceVariantNamePciE12variant_name)&4294967295))]=0;var $arraydecay=(($variant_prefix)&4294967295);var $call=_sprintf($arraydecay,((__str76728)&4294967295),allocate([47,0,0,0],["i32",0,0,0],ALLOC_STACK));var $0=$vname_addr;var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=5;;}
$if_then$$if_end10thread_pre_split$2:do{if(__label__==1){var $1=$vname_addr;var $call1=_strchr($1,43);$p=$call1;var $cmp2=((($call1))|0)!=0;if(!($cmp2)){__label__=5;break $if_then$$if_end10thread_pre_split$2;}
var $2=$p;var $incdec_ptr=(($2+1)&4294967295);$p=$incdec_ptr;HEAP8[($2)]=0;var $3=$p;var $4=HEAP8[($3)];var $conv=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $isdigittmp=((($conv)-48)&4294967295);var $isdigit=((($isdigittmp))>>>0)<10;var $call4=((($isdigit))&1);var $tobool=((($call4))|0)!=0;if($tobool){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $5=$p;var $call6=_atoi($5);$variant_num_addr=$call6;__lastLabel__=3;__label__=6;break $if_then$$if_end10thread_pre_split$2;}
else if(__label__==4){var $arraydecay7=(($variant_prefix)&4294967295);var $call8=_strcpy(((__ZZL23ExtractVoiceVariantNamePciE12variant_name)&4294967295),$arraydecay7);var $6=$p;__Z8strncpy0PcPKci(((__ZZL23ExtractVoiceVariantNamePciE12variant_name+3)&4294967295),$6,17);__label__=5;break $if_then$$if_end10thread_pre_split$2;}}}while(0);if(__label__==5){var $_pr=$variant_num_addr;__lastLabel__=5;;}
var $7=__lastLabel__==5?$_pr:($call6);var $cmp11=((($7))|0)>0;if($cmp11){__label__=7;;}else{__label__=10;;}
if(__label__==7){var $8=$variant_num_addr;var $cmp13=((($8))|0)<10;var $arraydecay15=(($variant_prefix)&4294967295);var $9=$variant_num_addr;if($cmp13){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $call16=_sprintf(((__ZZL23ExtractVoiceVariantNamePciE12variant_name)&4294967295),((__str77729)&4294967295),allocate([$arraydecay15,0,0,0,$9,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));;}
else if(__label__==9){var $sub=((($9)-10)&4294967295);var $call19=_sprintf(((__ZZL23ExtractVoiceVariantNamePciE12variant_name)&4294967295),((__str78730)&4294967295),allocate([$arraydecay15,0,0,0,$sub,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));;}}
STACKTOP=__stackBase__;return;return;}
function __Z17SelectVoiceByNamePP12espeak_VOICEPKc($voices,$name){var __stackBase__=STACKTOP;STACKTOP+=44;_memset(__stackBase__,0,44);var __label__;var __lastLabel__=null;var $retval;var $voices_addr;var $name_addr;var $ix;var $match_fname;var $match_fname2;var $match_name;var $id;var $last_part_len;var $last_part=__stackBase__;$voices_addr=$voices;$name_addr=$name;$match_fname=-1;$match_fname2=-1;$match_name=-1;var $0=$voices_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=4;;}
if(__label__==1){var $1=HEAP32[((__ZL13n_voices_list)>>2)];var $cmp1=((($1))|0)==0;if($cmp1){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $call=_espeak_ListVoices(0);;}
$voices_addr=((__ZL11voices_list)&4294967295);;}
var $arraydecay=(($last_part)&4294967295);var $2=$name_addr;var $call4=_sprintf($arraydecay,((__str70722)&4294967295),allocate([47,0,0,0,$2,0,0,0],["i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $arraydecay5=(($last_part)&4294967295);var $call6=_strlen($arraydecay5);$last_part_len=$call6;$ix=0;var $arraydecay18=(($last_part)&4294967295);;$for_cond$8:while(1){var $3=$ix;var $4=$voices_addr;var $arrayidx=(($4+4*$3)&4294967295);var $5=HEAP32[(($arrayidx)>>2)];var $cmp7=((($5))|0)!=0;if(!($cmp7)){__label__=13;break $for_cond$8;}
var $6=$name_addr;var $7=$ix;var $8=$voices_addr;var $arrayidx8=(($8+4*$7)&4294967295);var $9=HEAP32[(($arrayidx8)>>2)];var $name9=(($9)&4294967295);var $10=HEAP32[(($name9)>>2)];var $call10=_strcmp($6,$10);var $cmp11=((($call10))|0)==0;if($cmp11){__label__=7;break $for_cond$8;}
var $12=$name_addr;var $13=$ix;var $14=$voices_addr;var $arrayidx13=(($14+4*$13)&4294967295);var $15=HEAP32[(($arrayidx13)>>2)];var $identifier=(($15+8)&4294967295);var $16=HEAP32[(($identifier)>>2)];$id=$16;var $call14=_strcmp($12,$16);var $cmp15=((($call14))|0)==0;if($cmp15){__label__=9;;}else{__label__=10;;}
$if_then16$$if_else17$12:do{if(__label__==9){var $17=$ix;$match_fname=$17;;}
else if(__label__==10){var $18=$id;var $call19=_strlen($18);var $19=$last_part_len;var $sub=((($call19)-($19))&4294967295);var $20=$id;var $arrayidx20=(($20+$sub)&4294967295);var $call21=_strcmp($arraydecay18,$arrayidx20);var $cmp22=((($call21))|0)==0;if(!($cmp22)){__label__=12;break $if_then16$$if_else17$12;}
var $21=$ix;$match_fname2=$21;;}}while(0);var $22=$ix;var $inc=((($22)+1)&4294967295);$ix=$inc;__label__=5;continue $for_cond$8;}
if(__label__==13){var $_pr=$match_name;__lastLabel__=13;;}
else if(__label__==7){var $11=$ix;$match_name=$11;__lastLabel__=7;;}
var $23=__lastLabel__==13?$_pr:($11);var $cmp27=((($23))|0)<0;if($cmp27){__label__=15;;}else{__label__=17;;}
$if_then28$$if_end32thread_pre_split$21:do{if(__label__==15){var $24=$match_fname;$match_name=$24;var $25=$match_name;var $cmp29=((($25))|0)<0;if(!($cmp29)){__label__=20;break $if_then28$$if_end32thread_pre_split$21;}
var $26=$match_fname2;$match_name=$26;__lastLabel__=16;__label__=18;break $if_then28$$if_end32thread_pre_split$21;}
else if(__label__==17){var $_pr1=$match_name;__lastLabel__=17;__label__=18;break $if_then28$$if_end32thread_pre_split$21;}}while(0);$if_end32$$if_end35$25:do{if(__label__==18){var $27=__lastLabel__==17?$_pr1:($26);var $cmp33=((($27))|0)<0;if(!($cmp33)){__label__=20;break $if_end32$$if_end35$25;}
$retval=0;__label__=21;break $if_end32$$if_end35$25;}}while(0);if(__label__==20){var $28=$match_name;var $29=$voices_addr;var $arrayidx36=(($29+4*$28)&4294967295);var $30=HEAP32[(($arrayidx36)>>2)];$retval=$30;;}
var $31=$retval;STACKTOP=__stackBase__;return $31;return null;}
function _espeak_ListVoices($voice_spec){var __stackBase__=STACKTOP;STACKTOP+=164;_memset(__stackBase__,0,164);var __label__;var $voice_spec_addr;var $ix;var $j;var $v;var $path_voices=__stackBase__;$voice_spec_addr=$voice_spec;$ix=0;var $0=$ix;var $1=HEAP32[((__ZL13n_voices_list)>>2)];var $cmp3=((($0))|0)<((($1))|0);if($cmp3){__label__=1;;}else{__label__=4;;}
$for_body$$for_end$2:do{if(__label__==1){while(1){var $2=$ix;var $arrayidx=((__ZL11voices_list+$2*4)&4294967295);var $3=HEAP32[(($arrayidx)>>2)];var $cmp1=((($3))|0)!=0;if($cmp1){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $4=$ix;var $arrayidx2=((__ZL11voices_list+$4*4)&4294967295);var $5=HEAP32[(($arrayidx2)>>2)];var $6=$5;;;}
var $7=$ix;var $inc=((($7)+1)&4294967295);$ix=$inc;var $8=$ix;var $9=HEAP32[((__ZL13n_voices_list)>>2)];var $cmp=((($8))|0)<((($9))|0);if($cmp){__label__=1;continue;}else{__label__=4;break $for_body$$for_end$2;}}}}while(0);HEAP32[((__ZL13n_voices_list)>>2)]=0;var $arraydecay=(($path_voices)&4294967295);var $call=_sprintf($arraydecay,((__str72724)&4294967295),allocate([((_path_home)&4294967295),0,0,0,47,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));var $arraydecay3=(($path_voices)&4294967295);var $call4=_strlen($arraydecay3);var $add=((($call4)+1)&4294967295);HEAP32[((__ZL15len_path_voices)>>2)]=$add;var $arraydecay5=(($path_voices)&4294967295);__ZL9GetVoicesPKc($arraydecay5);var $10=HEAP32[((__ZL13n_voices_list)>>2)];var $arrayidx6=((__ZL11voices_list+$10*4)&4294967295);HEAP32[(($arrayidx6)>>2)]=0;var $11=HEAP32[((__ZL13n_voices_list)>>2)];_qsort(__ZL11voices_list,$11,4,6);var $12=$voice_spec_addr;var $tobool=((($12))|0)!=0;if($tobool){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $13=$voice_spec_addr;var $call8=__ZL14SetVoiceScoresP12espeak_VOICEPS0_i($13,((__ZZ17espeak_ListVoicesE6voices)&4294967295),1);;}
else if(__label__==6){$j=0;$ix=0;var $14=$ix;var $arrayidx101=((__ZL11voices_list+$14*4)&4294967295);var $15=HEAP32[(($arrayidx101)>>2)];$v=$15;var $cmp112=((($15))|0)!=0;if($cmp112){__label__=7;;}else{__label__=12;;}
$for_body12$$for_end28$12:do{if(__label__==7){$for_body12$13:while(1){var $16=$v;var $languages=(($16+4)&4294967295);var $17=HEAP32[(($languages)>>2)];var $arrayidx13=(($17)&4294967295);var $18=HEAP8[($arrayidx13)];var $conv=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));var $cmp14=((($conv))|0)!=0;if($cmp14){__label__=8;;}else{__label__=11;;}
$land_lhs_true$$for_inc26$15:do{if(__label__==8){var $19=$v;var $languages15=(($19+4)&4294967295);var $20=HEAP32[(($languages15)>>2)];var $arrayidx16=(($20+1)&4294967295);var $call17=_strcmp($arrayidx16,((__str55707)&4294967295));var $cmp18=((($call17))|0)!=0;if(!($cmp18)){__label__=11;break $land_lhs_true$$for_inc26$15;}
var $21=$v;var $identifier=(($21+8)&4294967295);var $22=HEAP32[(($identifier)>>2)];var $call20=_memcmp($22,((__str73725)&4294967295),3);var $cmp21=((($call20))|0)!=0;if(!($cmp21)){__label__=11;break $land_lhs_true$$for_inc26$15;}
var $23=$v;var $24=$j;var $inc23=((($24)+1)&4294967295);$j=$inc23;var $arrayidx24=((__ZZ17espeak_ListVoicesE6voices+$24*4)&4294967295);HEAP32[(($arrayidx24)>>2)]=$23;;}}while(0);var $25=$ix;var $inc27=((($25)+1)&4294967295);$ix=$inc27;var $26=$ix;var $arrayidx10=((__ZL11voices_list+$26*4)&4294967295);var $27=HEAP32[(($arrayidx10)>>2)];$v=$27;var $cmp11=((($27))|0)!=0;if($cmp11){__label__=7;continue $for_body12$13;}else{__label__=12;break $for_body12$$for_end28$12;}}}}while(0);var $28=$j;var $arrayidx29=((__ZZ17espeak_ListVoicesE6voices+$28*4)&4294967295);HEAP32[(($arrayidx29)>>2)]=0;;}
STACKTOP=__stackBase__;return((__ZZ17espeak_ListVoicesE6voices)&4294967295);return null;}
function __Z11SelectVoiceP12espeak_VOICEPi($voice_select,$found){var __stackBase__=STACKTOP;STACKTOP+=1272;_memset(__stackBase__,0,1272);var __label__;var $retval;var $voice_select_addr;var $found_addr;var $nv;var $ix;var $ix2;var $j;var $n_variants;var $variant_number;var $gender;var $skip;var $aged;var $variant_name;var $p;var $p_start;var $vp;var $vp2;var $voice_select2=__stackBase__;var $voices=__stackBase__+24;var $voices2=__stackBase__+624;$voice_select_addr=$voice_select;$found_addr=$found;$aged=1;$vp=0;var $0=$found_addr;HEAP32[(($0)>>2)]=1;var $1=$voice_select2;var $2=$voice_select_addr;var $3=$2;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$3;$dest$=$1;$stop$=$src$+24;if(($dest$%4)==($src$%4)&&24>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $4=HEAP32[((__ZL13n_voices_list)>>2)];var $cmp=((($4))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $call=_espeak_ListVoices(0);;}
var $languages=(($voice_select2+4)&4294967295);var $5=HEAP32[(($languages)>>2)];var $cmp1=((($5))|0)==0;if($cmp1){__label__=4;;}else{__label__=3;;}
$if_then4$$lor_lhs_false$5:do{if(__label__==3){var $languages2=(($voice_select2+4)&4294967295);var $6=HEAP32[(($languages2)>>2)];var $arrayidx=(($6)&4294967295);var $7=HEAP8[($arrayidx)];var $conv=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $cmp3=((($conv))|0)==0;if($cmp3){__label__=4;break $if_then4$$lor_lhs_false$5;}else{__label__=14;break $if_then4$$lor_lhs_false$5;}}}while(0);$if_then4$$if_end41$7:do{if(__label__==4){var $name=(($voice_select2)&4294967295);var $8=HEAP32[(($name)>>2)];var $cmp5=((($8))|0)==0;if($cmp5){__label__=5;;}else{__label__=7;;}
$if_then6$$if_end12$9:do{if(__label__==5){var $identifier=(($voice_select2+8)&4294967295);var $9=HEAP32[(($identifier)>>2)];var $name7=(($voice_select2)&4294967295);HEAP32[(($name7)>>2)]=$9;var $cmp8=((($9))|0)==0;if(!($cmp8)){__label__=7;break $if_then6$$if_end12$9;}
var $name10=(($voice_select2)&4294967295);HEAP32[(($name10)>>2)]=((__str45697)&4294967295);;}}while(0);var $name13=(($voice_select2)&4294967295);var $10=HEAP32[(($name13)>>2)];__Z8strncpy0PcPKci(((__ZZ11SelectVoiceP12espeak_VOICEPiE3buf)&4294967295),$10,60);__ZL23ExtractVoiceVariantNamePci(((__ZZ11SelectVoiceP12espeak_VOICEPiE3buf)&4294967295),0);$variant_name=((__ZZL23ExtractVoiceVariantNamePciE12variant_name)&4294967295);var $call15=__Z17SelectVoiceByNamePP12espeak_VOICEPKc(((__ZL11voices_list)&4294967295),((__ZZ11SelectVoiceP12espeak_VOICEPiE3buf)&4294967295));$vp=$call15;var $cmp16=((($call15))|0)!=0;if(!($cmp16)){__label__=14;break $if_then4$$if_end41$7;}
var $11=$vp;var $languages18=(($11+4)&4294967295);var $12=HEAP32[(($languages18)>>2)];var $arrayidx19=(($12+1)&4294967295);var $languages20=(($voice_select2+4)&4294967295);HEAP32[(($languages20)>>2)]=$arrayidx19;var $gender21=(($voice_select2+12)&4294967295);var $13=HEAPU8[($gender21)];var $conv22=((($13))&255);var $cmp23=((($conv22))|0)==0;if(!($cmp23)){__label__=14;break $if_then4$$if_end41$7;}
var $age=(($voice_select2+13)&4294967295);var $14=HEAPU8[($age)];var $conv24=((($14))&255);var $cmp25=((($conv24))|0)==0;if(!($cmp25)){__label__=14;break $if_then4$$if_end41$7;}
var $variant=(($voice_select2+14)&4294967295);var $15=HEAPU8[($variant)];var $conv27=((($15))&255);var $cmp28=((($conv27))|0)==0;if(!($cmp28)){__label__=14;break $if_then4$$if_end41$7;}
var $16=$variant_name;var $arrayidx30=(($16)&4294967295);var $17=HEAP8[($arrayidx30)];var $conv31=(tempInt=(($17)),(tempInt>=128?tempInt-256:tempInt));var $cmp32=((($conv31))|0)!=0;var $18=$vp;var $identifier34=(($18+8)&4294967295);var $19=HEAP32[(($identifier34)>>2)];if($cmp32){__label__=12;;}else{__label__=13;;}
if(__label__==12){var $20=$variant_name;var $arrayidx35=(($20+3)&4294967295);var $call36=_sprintf(((__ZZ11SelectVoiceP12espeak_VOICEPiE8voice_id)&4294967295),((__str71723)&4294967295),allocate([$19,0,0,0,$arrayidx35,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));$retval=((__ZZ11SelectVoiceP12espeak_VOICEPiE8voice_id)&4294967295);__label__=53;break $if_then4$$if_end41$7;}
else if(__label__==13){$retval=$19;__label__=53;break $if_then4$$if_end41$7;}}}while(0);if(__label__==14){var $arraydecay=(($voices)&4294967295);var $call42=__ZL14SetVoiceScoresP12espeak_VOICEPS0_i($voice_select2,$arraydecay,0);$nv=$call42;var $cmp43=((($call42))|0)==0;if($cmp43){__label__=15;;}else{__label__=17;;}
$if_then44$$if_end50$22:do{if(__label__==15){var $21=$found_addr;HEAP32[(($21)>>2)]=0;var $call45=__Z17SelectVoiceByNamePP12espeak_VOICEPKc(((__ZL11voices_list)&4294967295),((__str45697)&4294967295));var $arrayidx46=(($voices)&4294967295);HEAP32[(($arrayidx46)>>2)]=$call45;var $cmp47=((($call45))|0)!=0;if(!($cmp47)){__label__=17;break $if_then44$$if_end50$22;}
$nv=1;;}}while(0);$gender=0;var $gender51=(($voice_select2+12)&4294967295);var $22=HEAPU8[($gender51)];var $conv52=((($22))&255);var $cmp53=((($conv52))|0)==2;if($cmp53){__label__=20;;}else{__label__=18;;}
$if_then62$$lor_lhs_false54$26:do{if(__label__==18){var $age55=(($voice_select2+13)&4294967295);var $23=HEAPU8[($age55)];var $conv56=((($23))&255);var $cmp57=((($conv56))|0)>0;if($cmp57){__label__=19;;}else{__label__=21;;}
if(__label__==19){var $age59=(($voice_select2+13)&4294967295);var $24=HEAPU8[($age59)];var $conv60=((($24))&255);var $cmp61=((($conv60))|0)<13;if($cmp61){__label__=20;break $if_then62$$lor_lhs_false54$26;}}
var $gender63=(($voice_select2+12)&4294967295);var $25=HEAPU8[($gender63)];var $conv64=((($25))&255);var $cmp65=((($conv64))|0)==1;if(!($cmp65)){__label__=23;break $if_then62$$lor_lhs_false54$26;}
$gender=1;__label__=23;break $if_then62$$lor_lhs_false54$26;}}while(0);if(__label__==20){$gender=2;;}
var $age69=(($voice_select2+13)&4294967295);var $26=HEAPU8[($age69)];var $conv70=((($26))&255);var $cmp71=((($conv70))|0)<60;if($cmp71){__label__=24;;}else{__label__=25;;}
$if_end73_thread$$if_end73$35:do{if(__label__==24){$aged=0;var $27=$gender;var $arrayidx742=((_variant_lists+$27*4)&4294967295);var $28=HEAP32[(($arrayidx742)>>2)];$p_start=$28;$p=$28;__label__=26;break $if_end73_thread$$if_end73$35;}
else if(__label__==25){var $_pr=$aged;var $29=$gender;var $arrayidx74=((_variant_lists+$29*4)&4294967295);var $30=HEAP32[(($arrayidx74)>>2)];$p_start=$30;$p=$30;var $cmp75=((($_pr))|0)==0;if($cmp75){__label__=26;break $if_end73_thread$$if_end73$35;}else{__label__=27;break $if_end73_thread$$if_end73$35;}}}while(0);if(__label__==26){var $31=$p;var $incdec_ptr=(($31+1)&4294967295);$p=$incdec_ptr;;}
$n_variants=0;$ix=0;$ix2=0;var $32=$ix;var $33=$nv;var $cmp786=((($32))|0)<((($33))|0);if($cmp786){__label__=28;;}else{__label__=44;;}
$for_body$$while_cond$41:do{if(__label__==28){$for_body$42:while(1){var $34=$ix;var $arrayidx79=(($voices+$34*4)&4294967295);var $35=HEAP32[(($arrayidx79)>>2)];$vp=$35;$skip=0;var $36=$gender;var $cmp80=((($36))|0)!=0;if($cmp80){__label__=29;;}else{__label__=31;;}
$land_lhs_true81$$if_end86$44:do{if(__label__==29){var $37=$vp;var $gender82=(($37+12)&4294967295);var $38=HEAPU8[($gender82)];var $conv83=((($38))&255);var $39=$gender;var $cmp84=((($conv83))|0)!=((($39))|0);if(!($cmp84)){__label__=31;break $land_lhs_true81$$if_end86$44;}
$skip=1;;}}while(0);var $40=$ix2;var $cmp87=((($40))|0)==0;if($cmp87){__label__=32;;}else{__label__=35;;}
$land_lhs_true88$$if_end94$48:do{if(__label__==32){var $41=$aged;var $tobool=((($41))|0)!=0;if(!($tobool)){__label__=35;break $land_lhs_true88$$if_end94$48;}
var $42=$vp;var $age90=(($42+13)&4294967295);var $43=HEAPU8[($age90)];var $conv91=((($43))&255);var $cmp92=((($conv91))|0)<60;if(!($cmp92)){__label__=35;break $land_lhs_true88$$if_end94$48;}
$skip=1;__label__=37;break $land_lhs_true88$$if_end94$48;}}while(0);$if_end98$$if_end94$52:do{if(__label__==35){var $_pr4=$skip;var $cmp95=((($_pr4))|0)==0;if(!($cmp95)){__label__=37;break $if_end98$$if_end94$52;}
var $44=$vp;var $45=$ix2;var $inc=((($45)+1)&4294967295);$ix2=$inc;var $arrayidx97=(($voices2+$45*4)&4294967295);HEAP32[(($arrayidx97)>>2)]=$44;;}}while(0);$j=0;;while(1){var $46=$j;var $47=$vp;var $xx1=(($47+15)&4294967295);var $48=HEAPU8[($xx1)];var $conv100=((($48))&255);var $cmp101=((($46))|0)<((($conv100))|0);if(!($cmp101)){__label__=43;break;}
var $49=$n_variants;var $cmp102=((($49))|0)<12;if(!($cmp102)){__label__=43;break;}
var $50=$p;var $51=HEAP8[($50)];var $conv104=(tempInt=(($51)),(tempInt>=128?tempInt-256:tempInt));$variant_number=$conv104;var $cmp105=((($conv104))|0)==0;if($cmp105){__label__=41;;}else{__label__=42;;}
if(__label__==41){var $52=$p_start;$p=$52;__label__=38;continue;}
else if(__label__==42){var $53=$n_variants;var $inc108=((($53)+1)&4294967295);$n_variants=$inc108;var $arrayidx109=((__ZZ11SelectVoiceP12espeak_VOICEPiE14voice_variants+$53*24)&4294967295);$vp2=$arrayidx109;var $54=$vp2;var $55=$54;var $56=$vp;var $57=$56;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$57;$dest$=$55;$stop$=$src$+24;if(($dest$%4)==($src$%4)&&24>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $58=$variant_number;var $conv110=((($58))&255);var $59=$vp2;var $variant111=(($59+14)&4294967295);HEAP8[($variant111)]=$conv110;var $60=$vp2;var $61=$ix2;var $inc112=((($61)+1)&4294967295);$ix2=$inc112;var $arrayidx113=(($voices2+$61*4)&4294967295);HEAP32[(($arrayidx113)>>2)]=$60;var $62=$p;var $incdec_ptr114=(($62+1)&4294967295);$p=$incdec_ptr114;var $63=$j;var $inc115=((($63)+1)&4294967295);$j=$inc115;__label__=38;continue;}}
var $64=$ix;var $inc116=((($64)+1)&4294967295);$ix=$inc116;var $65=$ix;var $66=$nv;var $cmp78=((($65))|0)<((($66))|0);if($cmp78){__label__=28;continue $for_body$42;}else{__label__=44;break $for_body$$while_cond$41;}}}}while(0);while(1){var $67=$vp;var $cmp118=((($67))|0)!=0;if(!($cmp118)){__label__=48;break;}
var $68=$p;var $incdec_ptr120=(($68+1)&4294967295);$p=$incdec_ptr120;var $69=HEAP8[($68)];var $conv121=(tempInt=(($69)),(tempInt>=128?tempInt-256:tempInt));$variant_number=$conv121;var $cmp122=((($conv121))|0)!=0;if(!($cmp122)){__label__=48;break;}
var $70=$n_variants;var $cmp124=((($70))|0)<12;if(!($cmp124)){__label__=48;break;}
var $71=$n_variants;var $inc126=((($71)+1)&4294967295);$n_variants=$inc126;var $arrayidx127=((__ZZ11SelectVoiceP12espeak_VOICEPiE14voice_variants+$71*24)&4294967295);$vp2=$arrayidx127;var $72=$vp2;var $73=$72;var $74=$vp;var $75=$74;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$75;$dest$=$73;$stop$=$src$+24;if(($dest$%4)==($src$%4)&&24>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $76=$variant_number;var $conv128=((($76))&255);var $77=$vp2;var $variant129=(($77+14)&4294967295);HEAP8[($variant129)]=$conv128;var $78=$vp2;var $79=$ix2;var $inc130=((($79)+1)&4294967295);$ix2=$inc130;var $arrayidx131=(($voices2+$79*4)&4294967295);HEAP32[(($arrayidx131)>>2)]=$78;__label__=44;continue;}
var $80=$ix2;var $cmp132=((($80))|0)==0;if($cmp132){__label__=49;;}else{__label__=50;;}
if(__label__==49){$retval=0;;}
else if(__label__==50){var $variant135=(($voice_select2+14)&4294967295);var $81=HEAPU8[($variant135)];var $conv136=((($81))&255);var $82=$ix2;var $rem=((($conv136))|0)%((($82))|0);var $arrayidx137=(($voices2+$rem*4)&4294967295);var $83=HEAP32[(($arrayidx137)>>2)];$vp=$83;var $84=$vp;var $variant138=(($84+14)&4294967295);var $85=HEAPU8[($variant138)];var $conv139=((($85))&255);var $cmp140=((($conv139))|0)!=0;var $86=$vp;if($cmp140){__label__=51;;}else{__label__=52;;}
if(__label__==51){var $variant142=(($86+14)&4294967295);var $87=HEAPU8[($variant142)];var $conv143=((($87))&255);__ZL23ExtractVoiceVariantNamePci(0,$conv143);$variant_name=((__ZZL23ExtractVoiceVariantNamePciE12variant_name)&4294967295);var $88=$vp;var $identifier145=(($88+8)&4294967295);var $89=HEAP32[(($identifier145)>>2)];var $90=$variant_name;var $arrayidx146=(($90+3)&4294967295);var $call147=_sprintf(((__ZZ11SelectVoiceP12espeak_VOICEPiE8voice_id)&4294967295),((__str71723)&4294967295),allocate([$89,0,0,0,$arrayidx146,0,0,0],["i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));$retval=((__ZZ11SelectVoiceP12espeak_VOICEPiE8voice_id)&4294967295);;}
else if(__label__==52){var $identifier149=(($86+8)&4294967295);var $91=HEAP32[(($identifier149)>>2)];$retval=$91;;}}}
var $92=$retval;STACKTOP=__stackBase__;return $92;return null;}
function __ZL14SetVoiceScoresP12espeak_VOICEPS0_i($voice_select,$voices,$control){var __stackBase__=STACKTOP;STACKTOP+=80;_memset(__stackBase__,0,80);var __label__;var $retval;var $voice_select_addr;var $voices_addr;var $control_addr;var $ix;var $score;var $nv;var $n_parts;var $lang_len;var $vp;var $language=__stackBase__;$voice_select_addr=$voice_select;$voices_addr=$voices;$control_addr=$control;$n_parts=0;$lang_len=0;var $0=$voice_select_addr;var $languages=(($0+4)&4294967295);var $1=HEAP32[(($languages)>>2)];var $cmp=((($1))|0)!=0;if($cmp){__label__=1;;}else{__label__=6;;}
$land_lhs_true$$if_end16$2:do{if(__label__==1){var $2=$voice_select_addr;var $languages1=(($2+4)&4294967295);var $3=HEAP32[(($languages1)>>2)];var $arrayidx=(($3)&4294967295);var $4=HEAP8[($arrayidx)];var $conv=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $cmp2=((($conv))|0)!=0;if(!($cmp2)){__label__=6;break $land_lhs_true$$if_end16$2;}
$n_parts=1;var $5=$voice_select_addr;var $languages3=(($5+4)&4294967295);var $6=HEAP32[(($languages3)>>2)];var $call=_strlen($6);$lang_len=$call;$ix=0;var $7=$ix;var $8=$lang_len;var $cmp42=((($7))|0)<=((($8))|0);var $9=$ix;var $cmp53=((($9))>>>0)<80;var $or_cond4=($cmp42)&($cmp53);if(!($or_cond4)){__label__=6;break $land_lhs_true$$if_end16$2;}
while(1){var $10=$ix;var $11=$voice_select_addr;var $languages6=(($11+4)&4294967295);var $12=HEAP32[(($languages6)>>2)];var $arrayidx7=(($12+$10)&4294967295);var $13=HEAP8[($arrayidx7)];var $conv8=(tempInt=(($13)),(tempInt>=128?tempInt-256:tempInt));var $call9=_tolower($conv8);var $conv10=((($call9))&255);var $14=$ix;var $arrayidx11=(($language+$14)&4294967295);HEAP8[($arrayidx11)]=$conv10;var $conv12=(tempInt=(($conv10)),(tempInt>=128?tempInt-256:tempInt));var $cmp13=((($conv12))|0)==45;if($cmp13){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $15=$n_parts;var $inc=((($15)+1)&4294967295);$n_parts=$inc;;}
var $16=$ix;var $inc15=((($16)+1)&4294967295);$ix=$inc15;var $17=$ix;var $18=$lang_len;var $cmp4=((($17))|0)<=((($18))|0);var $19=$ix;var $cmp5=((($19))>>>0)<80;var $or_cond=($cmp4)&($cmp5);if($or_cond){__label__=3;continue;}else{__label__=6;break $land_lhs_true$$if_end16$2;}}}}while(0);$nv=0;$ix=0;var $20=$ix;var $21=HEAP32[((__ZL13n_voices_list)>>2)];var $cmp181=((($20))|0)<((($21))|0);if($cmp181){__label__=7;;}else{__label__=13;;}
$for_body19_lr_ph$$for_end37$11:do{if(__label__==7){var $arraydecay=(($language)&4294967295);;$for_body19$13:while(1){var $22=$ix;var $arrayidx20=((__ZL11voices_list+$22*4)&4294967295);var $23=HEAP32[(($arrayidx20)>>2)];$vp=$23;var $24=$control_addr;var $and=($24)&1;var $cmp21=((($and))|0)==0;if($cmp21){__label__=9;;}else{__label__=10;;}
$land_lhs_true22$$if_end26$15:do{if(__label__==9){var $25=$vp;var $identifier=(($25+8)&4294967295);var $26=HEAP32[(($identifier)>>2)];var $call23=_memcmp($26,((__str73725)&4294967295),3);var $cmp24=((($call23))|0)==0;if($cmp24){__label__=12;break $land_lhs_true22$$if_end26$15;}else{__label__=10;break $land_lhs_true22$$if_end26$15;}}}while(0);$for_inc35$$if_end26$17:do{if(__label__==10){var $27=$voice_select_addr;var $28=$n_parts;var $29=$lang_len;var $30=$ix;var $arrayidx27=((__ZL11voices_list+$30*4)&4294967295);var $31=HEAP32[(($arrayidx27)>>2)];var $call28=__ZL10ScoreVoiceP12espeak_VOICEPKciiS0_($27,$arraydecay,$28,$29,$31);$score=$call28;var $cmp29=((($call28))|0)>0;if(!($cmp29)){__label__=12;break $for_inc35$$if_end26$17;}
var $32=$vp;var $33=$nv;var $inc31=((($33)+1)&4294967295);$nv=$inc31;var $34=$voices_addr;var $arrayidx32=(($34+4*$33)&4294967295);HEAP32[(($arrayidx32)>>2)]=$32;var $35=$score;var $36=$vp;var $score33=(($36+16)&4294967295);HEAP32[(($score33)>>2)]=$35;;}}while(0);var $37=$ix;var $inc36=((($37)+1)&4294967295);$ix=$inc36;var $38=$ix;var $39=HEAP32[((__ZL13n_voices_list)>>2)];var $cmp18=((($38))|0)<((($39))|0);if($cmp18){__label__=8;continue $for_body19$13;}else{__label__=13;break $for_body19_lr_ph$$for_end37$11;}}}}while(0);var $40=$nv;var $41=$voices_addr;var $arrayidx38=(($41+4*$40)&4294967295);HEAP32[(($arrayidx38)>>2)]=0;var $42=$nv;var $cmp39=((($42))|0)==0;if($cmp39){__label__=14;;}else{__label__=15;;}
if(__label__==14){$retval=0;;}
else if(__label__==15){var $43=$voices_addr;var $44=$43;var $45=$nv;_qsort($44,$45,4,8);var $46=$nv;$retval=$46;;}
var $47=$retval;STACKTOP=__stackBase__;return $47;return null;}
function __Z14SetVoiceByNamePKc($name){var __stackBase__=STACKTOP;STACKTOP+=24;_memset(__stackBase__,0,24);var __label__;var $retval;var $name_addr;var $v;var $voice_selector=__stackBase__;var $variant_name;$name_addr=$name;var $0=$name_addr;__Z8strncpy0PcPKci(((__ZZ14SetVoiceByNamePKcE3buf)&4294967295),$0,60);__ZL23ExtractVoiceVariantNamePci(((__ZZ14SetVoiceByNamePKcE3buf)&4294967295),0);$variant_name=((__ZZL23ExtractVoiceVariantNamePciE12variant_name)&4294967295);var $1=$voice_selector;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$1;$stop$=$dest$+24;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $2=$name_addr;var $name1=(($voice_selector)&4294967295);HEAP32[(($name1)>>2)]=$2;var $call2=__Z9LoadVoicePKci(((__ZZ14SetVoiceByNamePKcE3buf)&4294967295),1);var $cmp=((($call2))|0)!=0;if($cmp){__label__=1;;}else{__label__=4;;}
$if_then$$if_end6$2:do{if(__label__==1){var $3=$variant_name;var $arrayidx=(($3)&4294967295);var $4=HEAP8[($arrayidx)];var $conv=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));var $cmp3=((($conv))|0)!=0;if($cmp3){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $5=$variant_name;var $call5=__Z9LoadVoicePKci($5,2);;}
var $6=HEAP32[((_voice)>>2)];__Z13DoVoiceChangeP7voice_t($6);__Z13SetVoiceStackP12espeak_VOICE($voice_selector);$retval=0;;}
else if(__label__==4){var $7=HEAP32[((__ZL13n_voices_list)>>2)];var $cmp7=((($7))|0)==0;if($cmp7){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $call9=_espeak_ListVoices(0);;}
var $call11=__Z17SelectVoiceByNamePP12espeak_VOICEPKc(((__ZL11voices_list)&4294967295),((__ZZ14SetVoiceByNamePKcE3buf)&4294967295));$v=$call11;var $cmp12=((($call11))|0)!=0;if($cmp12){__label__=7;;}else{__label__=11;;}
$if_then13$$if_end24$11:do{if(__label__==7){var $8=$v;var $identifier=(($8+8)&4294967295);var $9=HEAP32[(($identifier)>>2)];var $call14=__Z9LoadVoicePKci($9,0);var $cmp15=((($call14))|0)!=0;if(!($cmp15)){__label__=11;break $if_then13$$if_end24$11;}
var $10=$variant_name;var $arrayidx17=(($10)&4294967295);var $11=HEAP8[($arrayidx17)];var $conv18=(tempInt=(($11)),(tempInt>=128?tempInt-256:tempInt));var $cmp19=((($conv18))|0)!=0;if($cmp19){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $12=$variant_name;var $call21=__Z9LoadVoicePKci($12,2);;}
var $13=HEAP32[((_voice)>>2)];__Z13DoVoiceChangeP7voice_t($13);__Z13SetVoiceStackP12espeak_VOICE($voice_selector);$retval=0;__label__=12;break $if_then$$if_end6$2;}}while(0);$retval=-1;;}}while(0);var $14=$retval;STACKTOP=__stackBase__;return $14;return null;}
function __Z20SetVoiceByPropertiesP12espeak_VOICE($voice_selector){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $retval;var $voice_selector_addr;var $voice_id;var $voice_found=__stackBase__;$voice_selector_addr=$voice_selector;var $0=$voice_selector_addr;var $call=__Z11SelectVoiceP12espeak_VOICEPi($0,$voice_found);$voice_id=$call;var $1=HEAP32[(($voice_found)>>2)];var $cmp=((($1))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=2;;}
else if(__label__==2){var $2=$voice_id;var $call1=__Z16LoadVoiceVariantPKci($2,0);var $3=HEAP32[((_voice)>>2)];__Z13DoVoiceChangeP7voice_t($3);var $4=$voice_selector_addr;__Z13SetVoiceStackP12espeak_VOICE($4);$retval=0;;}
var $5=$retval;STACKTOP=__stackBase__;return $5;return null;}
function __ZL9GetVoicesPKc($path){var __stackBase__=STACKTOP;STACKTOP+=252;_memset(__stackBase__,0,252);var __label__;var __lastLabel__=null;var $path_addr;var $f_voice;var $voice_data;var $ftype;var $fname=__stackBase__;var $dir;var $ent;$path_addr=$path;var $0=$path_addr;var $call=_opendir($0);$dir=$call;var $cmp=((($call))|0)==0;if($cmp){__label__=13;;}else{__label__=1;;}
if(__label__==1){var $1=$dir;var $call11=_readdir($1);$ent=$call11;var $cmp22=((($call11))|0)==0;var $2=HEAP32[((__ZL13n_voices_list)>>2)];var $cmp33=((($2))|0)>=148;var $or_cond4=($cmp22)|($cmp33);if($or_cond4){__label__=12;;}else{__label__=2;;}
$while_end$$if_end5_lr_ph$4:do{if(__label__==2){var $arraydecay=(($fname)&4294967295);var $arraydecay8=(($fname)&4294967295);var $arraydecay14=(($fname)&4294967295);var $arraydecay17=(($fname)&4294967295);var $arraydecay22=(($fname)&4294967295);;$if_end5$6:while(1){var $3=$path_addr;var $4=$ent;var $d_name=(($4+4)&4294967295);var $arraydecay6=(($d_name)&4294967295);var $call7=_sprintf($arraydecay,((__str74726)&4294967295),allocate([$3,0,0,0,47,0,0,0,$arraydecay6,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STACK));var $call9=__Z13GetFileLengthPKc($arraydecay8);$ftype=$call9;var $cmp10=((($call9))|0)==-2;if($cmp10){__lastLabel__=3;__label__=4;;}else{__lastLabel__=3;__label__=7;;}
$land_lhs_true$$if_else$8:do{if(__label__==4){var $5=$ent;var $d_name11=(($5+4)&4294967295);var $arrayidx=(($d_name11)&4294967295);var $6=HEAP8[($arrayidx)];var $conv=(tempInt=(($6)),(tempInt>=128?tempInt-256:tempInt));var $cmp12=((($conv))|0)!=46;if($cmp12){__label__=5;;}else{__label__=6;;}
if(__label__==5){__ZL9GetVoicesPKc($arraydecay14);__label__=9;break $land_lhs_true$$if_else$8;}
else if(__label__==6){var $_pr=$ftype;__lastLabel__=6;__label__=7;break $land_lhs_true$$if_else$8;}}}while(0);$while_cond_backedge$$if_else$13:do{if(__label__==7){var $7=__lastLabel__==6?$_pr:($call9);var $cmp15=((($7))|0)>0;if(!($cmp15)){__label__=9;break $while_cond_backedge$$if_else$13;}
var $call18=_fopen($arraydecay17,((__str51703)&4294967295));$f_voice=$call18;var $cmp19=((($call18))|0)==0;if($cmp19){__label__=9;break $while_cond_backedge$$if_else$13;}
var $10=$f_voice;var $11=HEAP32[((__ZL15len_path_voices)>>2)];var $add_ptr=(($arraydecay22+$11)&4294967295);var $12=$ent;var $d_name23=(($12+4)&4294967295);var $arraydecay24=(($d_name23)&4294967295);var $call25=__ZL13ReadVoiceFileP7__sFILEPKcS2_($10,$add_ptr,$arraydecay24);$voice_data=$call25;var $13=$f_voice;var $call26=_fclose($13);var $14=$voice_data;var $cmp27=((($14))|0)!=0;if(!($cmp27)){__label__=9;break $while_cond_backedge$$if_else$13;}
var $15=$voice_data;var $16=HEAP32[((__ZL13n_voices_list)>>2)];var $inc=((($16)+1)&4294967295);HEAP32[((__ZL13n_voices_list)>>2)]=$inc;var $arrayidx29=((__ZL11voices_list+$16*4)&4294967295);HEAP32[(($arrayidx29)>>2)]=$15;;}}while(0);var $8=$dir;var $call1=_readdir($8);$ent=$call1;var $cmp2=((($call1))|0)==0;var $9=HEAP32[((__ZL13n_voices_list)>>2)];var $cmp3=((($9))|0)>=148;var $or_cond=($cmp2)|($cmp3);if($or_cond){__label__=12;break $while_end$$if_end5_lr_ph$4;}else{__label__=3;continue $if_end5$6;}}}}while(0);var $17=$dir;var $call33=_closedir($17);;}
STACKTOP=__stackBase__;return;return;}
function __ZL15VoiceNameSorterPKvS0_($p1,$p2){;var __label__;var $retval;var $p1_addr;var $p2_addr;var $ix;var $v1;var $v2;$p1_addr=$p1;$p2_addr=$p2;var $0=$p1_addr;var $1=$0;var $2=HEAP32[(($1)>>2)];$v1=$2;var $3=$p2_addr;var $4=$3;var $5=HEAP32[(($4)>>2)];$v2=$5;var $6=$v1;var $languages=(($6+4)&4294967295);var $7=HEAP32[(($languages)>>2)];var $arrayidx=(($7+1)&4294967295);var $8=$v2;var $languages1=(($8+4)&4294967295);var $9=HEAP32[(($languages1)>>2)];var $arrayidx2=(($9+1)&4294967295);var $call=_strcmp($arrayidx,$arrayidx2);$ix=$call;var $cmp=((($call))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $10=$ix;$retval=$10;;}
else if(__label__==2){var $11=$v1;var $languages3=(($11+4)&4294967295);var $12=HEAP32[(($languages3)>>2)];var $arrayidx4=(($12)&4294967295);var $13=HEAP8[($arrayidx4)];var $conv=(tempInt=(($13)),(tempInt>=128?tempInt-256:tempInt));var $14=$v2;var $languages5=(($14+4)&4294967295);var $15=HEAP32[(($languages5)>>2)];var $arrayidx6=(($15)&4294967295);var $16=HEAP8[($arrayidx6)];var $conv7=(tempInt=(($16)),(tempInt>=128?tempInt-256:tempInt));var $sub=((($conv)-($conv7))&4294967295);$ix=$sub;var $cmp8=((($sub))|0)!=0;if($cmp8){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $17=$ix;$retval=$17;;}
else if(__label__==4){var $18=$v1;var $name=(($18)&4294967295);var $19=HEAP32[(($name)>>2)];var $20=$v2;var $name11=(($20)&4294967295);var $21=HEAP32[(($name11)>>2)];var $call12=_strcmp($19,$21);$retval=$call12;;}}
var $22=$retval;;return $22;return null;}
function _espeak_GetCurrentVoice(){;var __label__;;return _voice_selected;return null;}
function __ZL13ReadVoiceFileP7__sFILEPKcS2_($f_in,$fname,$leafname){var __stackBase__=STACKTOP;STACKTOP+=672;_memset(__stackBase__,0,672);var __label__;var $retval;var $f_in_addr;var $fname_addr;var $leafname_addr;var $linebuf=__stackBase__;var $vname=__stackBase__+120;var $vgender=__stackBase__+200;var $vlanguage=__stackBase__+280;var $languages=__stackBase__+360;var $len;var $langix;var $n_languages;var $p;var $voice_data;var $priority=__stackBase__+660;var $age=__stackBase__+664;var $n_variants=__stackBase__+668;var $gender;$f_in_addr=$f_in;$fname_addr=$fname;$leafname_addr=$leafname;$langix=0;$n_languages=0;HEAP32[(($n_variants)>>2)]=3;var $arrayidx=(($vname)&4294967295);HEAP8[($arrayidx)]=0;var $arrayidx1=(($vgender)&4294967295);HEAP8[($arrayidx1)]=0;HEAP32[(($age)>>2)]=0;var $arraydecay=(($linebuf)&4294967295);var $0=$f_in_addr;var $call4=__ZL11fgets_stripPciP7__sFILE($arraydecay,120,$0);var $cmp5=((($call4))|0)!=0;if($cmp5){__label__=1;;}else{__label__=14;;}
$while_body_lr_ph$$while_end49$2:do{if(__label__==1){var $arraydecay2=(($linebuf)&4294967295);var $arrayidx5=(($linebuf+4)&4294967295);var $arraydecay9=(($vname)&4294967295);var $arraydecay10=(($linebuf)&4294967295);var $arrayidx14=(($vlanguage)&4294967295);var $arrayidx15=(($linebuf+8)&4294967295);var $arraydecay16=(($vlanguage)&4294967295);var $arraydecay18=(($vlanguage)&4294967295);var $arraydecay27=(($vlanguage)&4294967295);var $arraydecay31=(($linebuf)&4294967295);var $arrayidx35=(($linebuf+6)&4294967295);var $arraydecay36=(($vgender)&4294967295);var $arraydecay39=(($linebuf)&4294967295);var $arrayidx43=(($linebuf+8)&4294967295);;$while_body$4:while(1){var $call3=_memcmp($arraydecay2,((__str5655)&4294967295),4);var $cmp4=((($call3))|0)==0;if($cmp4){__label__=3;;}else{__label__=6;;}
$if_then$$if_else$6:do{if(__label__==3){$p=$arrayidx5;var $1=$p;var $2=HEAP8[($1)];var $conv1=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));var $call72=_isspace($conv1);var $tobool3=((($call72))|0)!=0;if($tobool3){__label__=4;;}else{__label__=5;;}
$while_body8$$while_end$8:do{if(__label__==4){while(1){var $3=$p;var $incdec_ptr=(($3+1)&4294967295);$p=$incdec_ptr;var $4=$p;var $5=HEAP8[($4)];var $conv=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $call7=_isspace($conv);var $tobool=((($call7))|0)!=0;if($tobool){__label__=4;continue;}else{__label__=5;break $while_body8$$while_end$8;}}}}while(0);var $6=$p;__Z8strncpy0PcPKci($arraydecay9,$6,80);;}
else if(__label__==6){var $call11=_memcmp($arraydecay10,((__str6656)&4294967295),8);var $cmp12=((($call11))|0)==0;if($cmp12){__label__=7;;}else{__label__=10;;}
if(__label__==7){HEAP32[(($priority)>>2)]=5;HEAP8[($arrayidx14)]=0;var $call17=_sscanf($arrayidx15,((__str54706)&4294967295),allocate([$arraydecay16,0,0,0,$priority,0,0,0],["i8*",0,0,0,"i32*",0,0,0],ALLOC_STACK));var $call19=_strlen($arraydecay18);var $add=((($call19)+2)&4294967295);$len=$add;var $7=$len;var $8=$langix;var $_neg=(((-($8)))&4294967295);var $sub20=((($_neg)+299)&4294967295);var $cmp21=((($7))>>>0)<((($sub20))>>>0);if(!($cmp21)){__label__=9;break $if_then$$if_else$6;}
var $9=HEAP32[(($priority)>>2)];var $conv23=((($9))&255);var $10=$langix;var $arrayidx24=(($languages+$10)&4294967295);HEAP8[($arrayidx24)]=$conv23;var $11=$langix;var $add25=((($11)+1)&4294967295);var $arrayidx26=(($languages+$add25)&4294967295);var $call28=_strcpy($arrayidx26,$arraydecay27);var $12=$len;var $13=$langix;var $add29=((($13)+($12))&4294967295);$langix=$add29;var $14=$n_languages;var $inc=((($14)+1)&4294967295);$n_languages=$inc;;}
else if(__label__==10){var $call32=_memcmp($arraydecay31,((__str7657)&4294967295),6);var $cmp33=((($call32))|0)==0;if($cmp33){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $call37=_sscanf($arrayidx35,((__str54706)&4294967295),allocate([$arraydecay36,0,0,0,$age,0,0,0],["i8*",0,0,0,"i32*",0,0,0],ALLOC_STACK));;}
else if(__label__==12){var $call40=_memcmp($arraydecay39,((__str75727)&4294967295),8);var $cmp41=((($call40))|0)==0;if(!($cmp41)){__label__=9;break $if_then$$if_else$6;}
var $call44=_sscanf($arrayidx43,((__str63715)&4294967295),allocate([$n_variants,0,0,0],["i32*",0,0,0],ALLOC_STACK));;}}}}while(0);var $15=$f_in_addr;var $call=__ZL11fgets_stripPciP7__sFILE($arraydecay,120,$15);var $cmp=((($call))|0)!=0;if($cmp){__label__=2;continue $while_body$4;}else{__label__=14;break $while_body_lr_ph$$while_end49$2;}}}}while(0);var $16=$langix;var $inc50=((($16)+1)&4294967295);$langix=$inc50;var $arrayidx51=(($languages+$16)&4294967295);HEAP8[($arrayidx51)]=0;var $arraydecay52=(($vgender)&4294967295);var $call53=__Z10LookupMnemP8MNEM_TABPKc(((_genders)&4294967295),$arraydecay52);$gender=$call53;var $17=$n_languages;var $cmp54=((($17))|0)==0;if($cmp54){__label__=15;;}else{__label__=16;;}
if(__label__==15){$retval=0;;}
else if(__label__==16){var $18=$langix;var $19=$fname_addr;var $call58=_strlen($19);var $arraydecay60=(($vname)&4294967295);var $call61=_strlen($arraydecay60);var $add59=((($18)+27)&4294967295);var $add62=((($add59)+($call58))&4294967295);var $add63=((($add62)+($call61))&4294967295);var $call64=_calloc($add63,1);$p=$call64;var $20=$p;var $21=$20;$voice_data=$21;var $22=$p;var $arrayidx65=(($22+24)&4294967295);$p=$arrayidx65;var $23=$p;var $arraydecay66=(($languages)&4294967295);var $24=$langix;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$arraydecay66;$dest$=$23;$stop$=$src$+$24;if(($dest$%4)==($src$%4)&&$24>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $25=$p;var $26=$voice_data;var $languages67=(($26+4)&4294967295);HEAP32[(($languages67)>>2)]=$25;var $27=$langix;var $28=$p;var $arrayidx68=(($28+$27)&4294967295);var $29=$fname_addr;var $call69=_strcpy($arrayidx68,$29);var $30=$langix;var $31=$p;var $arrayidx70=(($31+$30)&4294967295);var $32=$voice_data;var $identifier=(($32+8)&4294967295);HEAP32[(($identifier)>>2)]=$arrayidx70;var $33=$langix;var $34=$p;var $arrayidx71=(($34+$33)&4294967295);var $35=$voice_data;var $name=(($35)&4294967295);HEAP32[(($name)>>2)]=$arrayidx71;var $arrayidx72=(($vname)&4294967295);var $36=HEAP8[($arrayidx72)];var $conv73=(tempInt=(($36)),(tempInt>=128?tempInt-256:tempInt));var $cmp74=((($conv73))|0)!=0;if($cmp74){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $37=$fname_addr;var $call76=_strlen($37);var $38=$langix;var $add77=((($call76)+1)&4294967295);var $add78=((($add77)+($38))&4294967295);$langix=$add78;var $39=$langix;var $40=$p;var $arrayidx79=(($40+$39)&4294967295);var $arraydecay80=(($vname)&4294967295);var $call81=_strcpy($arrayidx79,$arraydecay80);var $41=$langix;var $42=$p;var $arrayidx82=(($42+$41)&4294967295);var $43=$voice_data;var $name83=(($43)&4294967295);HEAP32[(($name83)>>2)]=$arrayidx82;;}
var $44=HEAP32[(($age)>>2)];var $conv85=((($44))&255);var $45=$voice_data;var $age86=(($45+13)&4294967295);HEAP8[($age86)]=$conv85;var $46=$gender;var $conv87=((($46))&255);var $47=$voice_data;var $gender88=(($47+12)&4294967295);HEAP8[($gender88)]=$conv87;var $48=$voice_data;var $variant=(($48+14)&4294967295);HEAP8[($variant)]=0;var $49=HEAP32[(($n_variants)>>2)];var $conv89=((($49))&255);var $50=$voice_data;var $xx1=(($50+15)&4294967295);HEAP8[($xx1)]=$conv89;var $51=$voice_data;$retval=$51;;}
var $52=$retval;STACKTOP=__stackBase__;return $52;return null;}
function __ZL10ScoreVoiceP12espeak_VOICEPKciiS0_($voice_spec,$spec_language,$spec_n_parts,$spec_lang_len,$voice){;var __label__;var __lastLabel__=null;var $retval;var $voice_spec_addr;var $spec_language_addr;var $spec_n_parts_addr;var $spec_lang_len_addr;var $voice_addr;var $ix;var $p;var $c1;var $c2;var $language_priority;var $n_parts;var $matching;var $matching_parts;var $score;var $x;var $ratio;var $required_age;var $diff;$voice_spec_addr=$voice_spec;$spec_language_addr=$spec_language;$spec_n_parts_addr=$spec_n_parts;$spec_lang_len_addr=$spec_lang_len;$voice_addr=$voice;$score=0;var $0=$voice_addr;var $languages=(($0+4)&4294967295);var $1=HEAP32[(($languages)>>2)];$p=$1;var $2=$spec_language_addr;var $call=_strcmp($2,((__str33683)&4294967295));var $cmp=((($call))|0)==0;if($cmp){__label__=1;;}else{__label__=4;;}
$if_then$$if_end4$2:do{if(__label__==1){var $3=$voice_addr;var $identifier=(($3+8)&4294967295);var $4=HEAP32[(($identifier)>>2)];var $call1=_memcmp($4,((__str73725)&4294967295),3);var $cmp2=((($call1))|0)==0;if($cmp2){__label__=2;;}else{__label__=3;;}
if(__label__==2){$retval=100;;}
else if(__label__==3){$retval=0;;}}
else if(__label__==4){var $5=$spec_n_parts_addr;var $cmp5=((($5))|0)==0;if($cmp5){__label__=5;;}else{__label__=6;;}
$if_end60_thread$$if_else$8:do{if(__label__==5){$score=100;;}
else if(__label__==6){var $6=$p;var $7=HEAP8[($6)];var $conv=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));var $cmp7=((($conv))|0)==0;if($cmp7){__label__=7;;}else{__label__=9;;}
$land_lhs_true$$while_cond_preheader$11:do{if(__label__==7){var $8=$spec_language_addr;var $call8=_strcmp($8,((__str75727)&4294967295));var $cmp9=((($call8))|0)==0;if(!($cmp9)){__label__=9;break $land_lhs_true$$while_cond_preheader$11;}
$score=100;;}}while(0);var $9=$p;var $10=HEAP8[($9)];var $conv123=(tempInt=(($10)),(tempInt>=128?tempInt-256:tempInt));var $cmp134=((($conv123))|0)!=0;if($cmp134){__label__=10;;}else{__label__=31;;}
$while_body$$if_end60$15:do{if(__label__==10){$while_body$16:while(1){var $11=$p;var $incdec_ptr=(($11+1)&4294967295);$p=$incdec_ptr;var $12=HEAP8[($11)];var $conv14=(tempInt=(($12)),(tempInt>=128?tempInt-256:tempInt));$language_priority=$conv14;$matching=1;$matching_parts=0;$n_parts=1;$ix=0;;$for_cond$18:while(1){var $13=$ix;var $14=$spec_lang_len_addr;var $cmp15=((($13))|0)>=((($14))|0);if($cmp15){__label__=13;;}else{__label__=12;;}
$if_then18$$lor_lhs_false$20:do{if(__label__==12){var $15=$ix;var $16=$spec_language_addr;var $arrayidx=(($16+$15)&4294967295);var $17=HEAP8[($arrayidx)];var $conv16=(tempInt=(($17)),(tempInt>=128?tempInt-256:tempInt));$c1=$conv16;var $cmp17=((($conv16))|0)==45;if($cmp17){__label__=13;break $if_then18$$lor_lhs_false$20;}else{__label__=14;break $if_then18$$lor_lhs_false$20;}}}while(0);if(__label__==13){$c1=0;;}
var $18=$ix;var $19=$p;var $arrayidx20=(($19+$18)&4294967295);var $20=HEAP8[($arrayidx20)];var $conv21=(tempInt=(($20)),(tempInt>=128?tempInt-256:tempInt));$c2=$conv21;var $cmp22=((($conv21))|0)==45;if($cmp22){__label__=15;;}else{__label__=16;;}
if(__label__==15){$c2=0;;}
var $21=$c1;var $22=$c2;var $cmp25=((($21))|0)!=((($22))|0);if($cmp25){__label__=17;;}else{__label__=18;;}
if(__label__==17){$matching=0;;}
var $23=$ix;var $24=$p;var $arrayidx28=(($24+$23)&4294967295);var $25=HEAP8[($arrayidx28)];var $conv29=(tempInt=(($25)),(tempInt>=128?tempInt-256:tempInt));var $cmp30=((($conv29))|0)==45;if($cmp30){__label__=19;;}else{__label__=21;;}
$if_then31$$if_end35$31:do{if(__label__==19){var $26=$n_parts;var $inc=((($26)+1)&4294967295);$n_parts=$inc;var $27=$matching;var $tobool=((($27))|0)!=0;if(!($tobool)){__label__=21;break $if_then31$$if_end35$31;}
var $28=$matching_parts;var $inc33=((($28)+1)&4294967295);$matching_parts=$inc33;;}}while(0);var $29=$ix;var $30=$p;var $arrayidx36=(($30+$29)&4294967295);var $31=HEAP8[($arrayidx36)];var $conv37=(tempInt=(($31)),(tempInt>=128?tempInt-256:tempInt));var $cmp38=((($conv37))|0)==0;var $32=$ix;var $add=((($32)+1)&4294967295);if($cmp38){__label__=23;break $for_cond$18;}
$ix=$add;__label__=11;continue $for_cond$18;}
var $33=$p;var $add_ptr=(($33+$add)&4294967295);$p=$add_ptr;var $34=$matching;var $35=$matching_parts;var $add42=((($35)+($34))&4294967295);$matching_parts=$add42;var $36=$matching_parts;var $cmp43=((($36))|0)==0;if($cmp43){__label__=24;;}else{__label__=25;;}
$while_cond_backedge$$if_end45$37:do{if(__label__==25){$x=5;var $39=$spec_n_parts_addr;var $40=$matching_parts;var $sub=((($39)-($40))&4294967295);$diff=$sub;var $cmp46=((($sub))|0)>0;if($cmp46){__label__=26;;}else{__label__=27;;}
if(__label__==26){var $41=$diff;var $42=$x;var $sub48=((($42)-($41))&4294967295);$x=$sub48;;}
var $43=$n_parts;var $44=$matching_parts;var $sub50=((($43)-($44))&4294967295);$diff=$sub50;var $cmp51=((($sub50))|0)>0;if($cmp51){__label__=28;;}else{__label__=29;;}
if(__label__==28){var $45=$diff;var $46=$x;var $sub53=((($46)-($45))&4294967295);$x=$sub53;;}
var $47=$x;var $mul=((($47)*100)&4294967295);var $48=$language_priority;var $mul55=((($48)*2)&4294967295);var $sub56=((($mul)-($mul55))&4294967295);$x=$sub56;var $49=$x;var $50=$score;var $cmp57=((($49))|0)>((($50))|0);if(!($cmp57)){__label__=24;break $while_cond_backedge$$if_end45$37;}
var $51=$x;$score=$51;;}}while(0);var $37=$p;var $38=HEAP8[($37)];var $conv12=(tempInt=(($38)),(tempInt>=128?tempInt-256:tempInt));var $cmp13=((($conv12))|0)!=0;if($cmp13){__label__=10;continue $while_body$16;}else{__label__=31;break $while_body$$if_end60$15;}}}}while(0);var $_pr=$score;var $cmp61=((($_pr))|0)==0;if(!($cmp61)){__label__=33;break $if_end60_thread$$if_else$8;}
$retval=0;__label__=63;break $if_then$$if_end4$2;}}while(0);var $52=$voice_spec_addr;var $name=(($52)&4294967295);var $53=HEAP32[(($name)>>2)];var $cmp64=((($53))|0)!=0;if($cmp64){__label__=34;;}else{__label__=38;;}
$if_then65$$if_end81$50:do{if(__label__==34){var $54=$voice_spec_addr;var $name66=(($54)&4294967295);var $55=HEAP32[(($name66)>>2)];var $56=$voice_addr;var $name67=(($56)&4294967295);var $57=HEAP32[(($name67)>>2)];var $call68=_strcmp($55,$57);var $cmp69=((($call68))|0)==0;if($cmp69){__label__=35;;}else{__label__=36;;}
if(__label__==35){var $58=$score;var $add71=((($58)+500)&4294967295);$score=$add71;;}
else if(__label__==36){var $59=$voice_spec_addr;var $name73=(($59)&4294967295);var $60=HEAP32[(($name73)>>2)];var $61=$voice_addr;var $identifier74=(($61+8)&4294967295);var $62=HEAP32[(($identifier74)>>2)];var $call75=_strcmp($60,$62);var $cmp76=((($call75))|0)==0;if(!($cmp76)){__label__=38;break $if_then65$$if_end81$50;}
var $63=$score;var $add78=((($63)+400)&4294967295);$score=$add78;;}}}while(0);var $64=$voice_spec_addr;var $gender=(($64+12)&4294967295);var $65=HEAPU8[($gender)];var $conv82=((($65))&255);var $cmp83=((($conv82))|0)==1;if($cmp83){__label__=40;;}else{__label__=39;;}
$land_lhs_true88$$lor_lhs_false84$57:do{if(__label__==39){var $66=$voice_spec_addr;var $gender85=(($66+12)&4294967295);var $67=HEAPU8[($gender85)];var $conv86=((($67))&255);var $cmp87=((($conv86))|0)==2;if($cmp87){__label__=40;break $land_lhs_true88$$lor_lhs_false84$57;}else{__label__=45;break $land_lhs_true88$$lor_lhs_false84$57;}}}while(0);$land_lhs_true88$$if_end107$59:do{if(__label__==40){var $68=$voice_addr;var $gender89=(($68+12)&4294967295);var $69=HEAPU8[($gender89)];var $conv90=((($69))&255);var $cmp91=((($conv90))|0)==1;if($cmp91){__label__=42;;}else{__label__=41;;}
if(__label__==41){var $70=$voice_addr;var $gender93=(($70+12)&4294967295);var $71=HEAPU8[($gender93)];var $conv94=((($71))&255);var $cmp95=((($conv94))|0)==2;if(!($cmp95)){__label__=45;break $land_lhs_true88$$if_end107$59;}}
var $72=$voice_spec_addr;var $gender97=(($72+12)&4294967295);var $73=HEAPU8[($gender97)];var $conv98=((($73))&255);var $74=$voice_addr;var $gender99=(($74+12)&4294967295);var $75=HEAPU8[($gender99)];var $conv100=((($75))&255);var $cmp101=((($conv98))|0)==((($conv100))|0);var $76=$score;if($cmp101){__label__=43;;}else{__label__=44;;}
if(__label__==43){var $add103=((($76)+50)&4294967295);$score=$add103;;}
else if(__label__==44){var $sub105=((($76)-50)&4294967295);$score=$sub105;;}}}while(0);var $77=$voice_spec_addr;var $age=(($77+13)&4294967295);var $78=HEAPU8[($age)];var $conv108=((($78))&255);var $cmp109=((($conv108))|0)<=12;if($cmp109){__label__=46;;}else{__label__=49;;}
$land_lhs_true110$$if_end120$68:do{if(__label__==46){var $79=$voice_addr;var $gender111=(($79+12)&4294967295);var $80=HEAPU8[($gender111)];var $conv112=((($80))&255);var $cmp113=((($conv112))|0)==2;if(!($cmp113)){__label__=49;break $land_lhs_true110$$if_end120$68;}
var $81=$voice_addr;var $age115=(($81+13)&4294967295);var $82=HEAPU8[($age115)];var $conv116=((($82))&255);var $cmp117=((($conv116))|0)>12;if(!($cmp117)){__label__=49;break $land_lhs_true110$$if_end120$68;}
var $83=$score;var $add119=((($83)+5)&4294967295);$score=$add119;;}}while(0);var $84=$voice_addr;var $age121=(($84+13)&4294967295);var $85=HEAPU8[($age121)];var $conv122=((($85))&255);var $cmp123=((($conv122))|0)!=0;if($cmp123){__label__=50;;}else{__label__=59;;}
$if_then124$$if_end153thread_pre_split$73:do{if(__label__==50){var $86=$voice_spec_addr;var $age125=(($86+13)&4294967295);var $87=HEAPU8[($age125)];var $conv126=((($87))&255);var $cmp127=((($conv126))|0)==0;if($cmp127){__label__=51;;}else{__label__=52;;}
if(__label__==51){$required_age=30;;}
else if(__label__==52){var $88=$voice_spec_addr;var $age130=(($88+13)&4294967295);var $89=HEAPU8[($age130)];var $conv131=((($89))&255);$required_age=$conv131;;}
var $90=$required_age;var $mul133=((($90)*100)&4294967295);var $91=$voice_addr;var $age134=(($91+13)&4294967295);var $92=HEAPU8[($age134)];var $conv135=((($92))&255);var $div=((((($mul133))|0)/((($conv135))|0))|0);$ratio=$div;var $cmp136=((($div))|0)<100;if($cmp136){__label__=54;;}else{__label__=55;;}
if(__label__==54){var $93=$ratio;var $div138=((10000/((($93))|0))|0);$ratio=$div138;;}
var $94=$ratio;var $sub140=((($94)-100)&4294967295);var $div141=((((($sub140))|0)/10)|0);$ratio=$div141;var $95=$ratio;var $sub142=((5-($95))&4294967295);$x=$sub142;var $cmp143=((($sub142))|0)>0;if($cmp143){__label__=56;;}else{__label__=57;;}
if(__label__==56){$x=0;;}
var $96=$score;var $97=$x;var $add146=((($97)+($96))&4294967295);$score=$add146;var $98=$voice_spec_addr;var $age147=(($98+13)&4294967295);var $99=HEAPU8[($age147)];var $conv148=((($99))&255);var $cmp149=((($conv148))|0)>0;if(!($cmp149)){__label__=59;break $if_then124$$if_end153thread_pre_split$73;}
var $100=$score;var $add151=((($100)+10)&4294967295);$score=$add151;__lastLabel__=58;__label__=60;break $if_then124$$if_end153thread_pre_split$73;}}while(0);if(__label__==59){var $_pr2=$score;__lastLabel__=59;;}
var $101=__lastLabel__==59?$_pr2:($add151);var $cmp154=((($101))|0)<1;if($cmp154){__label__=61;;}else{__label__=62;;}
if(__label__==61){$score=1;;}
var $102=$score;$retval=$102;;}}while(0);var $103=$retval;;return $103;return null;}
function __ZL16VoiceScoreSorterPKvS0_($p1,$p2){;var __label__;var $retval;var $p1_addr;var $p2_addr;var $ix;var $v1;var $v2;$p1_addr=$p1;$p2_addr=$p2;var $0=$p1_addr;var $1=$0;var $2=HEAP32[(($1)>>2)];$v1=$2;var $3=$p2_addr;var $4=$3;var $5=HEAP32[(($4)>>2)];$v2=$5;var $6=$v2;var $score=(($6+16)&4294967295);var $7=HEAP32[(($score)>>2)];var $8=$v1;var $score1=(($8+16)&4294967295);var $9=HEAP32[(($score1)>>2)];var $sub=((($7)-($9))&4294967295);$ix=$sub;var $cmp=((($sub))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $10=$ix;$retval=$10;;}
else if(__label__==2){var $11=$v1;var $name=(($11)&4294967295);var $12=HEAP32[(($name)>>2)];var $13=$v2;var $name2=(($13)&4294967295);var $14=HEAP32[(($name2)>>2)];var $call=_strcmp($12,$14);$retval=$call;;}
var $15=$retval;;return $15;return null;}
function __Z9WcmdqStopv(){;var __label__;HEAP32[((_wcmdq_head)>>2)]=0;HEAP32[((_wcmdq_tail)>>2)]=0;var $0=HEAP32[((__ZL18sonicSpeedupStream)>>2)];var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=HEAP32[((__ZL18sonicSpeedupStream)>>2)];_sonicDestroyStream($1);HEAP32[((__ZL18sonicSpeedupStream)>>2)]=0;;}
var $2=HEAP8[(((_mbrola_name)&4294967295))];var $conv=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));var $cmp1=((($conv))|0)!=0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){__Z11MbrolaResetv();;};return;return;}
function __Z9WcmdqFreev(){;var __label__;var $i;var $0=HEAP32[((_wcmdq_head)>>2)];var $1=HEAP32[((_wcmdq_tail)>>2)];var $sub=((($0)-($1))&4294967295);$i=$sub;var $2=$i;var $cmp=((($2))|0)<=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $3=$i;var $add=((($3)+160)&4294967295);$i=$add;;}
var $4=$i;;return $4;return null;}
function __Z9WcmdqUsedv(){;var __label__;var $call=__Z9WcmdqFreev();var $sub=((160-($call))&4294967295);;return $sub;return null;}
function __Z8WcmdqIncv(){;var __label__;var $0=HEAP32[((_wcmdq_tail)>>2)];var $inc=((($0)+1)&4294967295);HEAP32[((_wcmdq_tail)>>2)]=$inc;var $cmp=((($inc))|0)>=160;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((_wcmdq_tail)>>2)]=0;;};return;return;}
function __Z16WavegenOpenSoundv(){;var __label__;;return 0;return null;}
function __Z17WavegenCloseSoundv(){;var __label__;;return 0;return null;}
function __Z16WavegenInitSoundv(){;var __label__;;return 0;return null;}
function __Z11WavegenInitii($rate,$wavemult_fact){;var __label__;var $rate_addr;var $wavemult_fact_addr;var $ix;var $x;$rate_addr=$rate;$wavemult_fact_addr=$wavemult_fact;var $0=$wavemult_fact_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$wavemult_fact_addr=60;;}
HEAP32[((_wvoice)>>2)]=0;var $1=$rate_addr;HEAP32[((_samplerate_native)>>2)]=$1;HEAP32[((_samplerate)>>2)]=$1;var $2=HEAP32[((_samplerate)>>2)];var $div=((134217728/((($2))|0))|0);HEAP32[((__ZL16PHASE_INC_FACTOR)>>2)]=$div;var $3=HEAP32[((_samplerate)>>2)];var $mul=((($3)*64)&4294967295);var $4=$rate_addr;var $div1=((((($mul))|0)/((($4))|0))|0);HEAP32[((__ZL11Flutter_inc)>>2)]=$div1;HEAP32[((__ZL11samplecount)>>2)]=0;HEAP32[((__ZL8nsamples)>>2)]=0;HEAP32[((__ZL9wavephase)>>2)]=2147483647;HEAP32[((((_wdata+52)&4294967295))>>2)]=32;HEAP32[((((_wdata+60)&4294967295))>>2)]=100;$ix=0;;$for_body$5:while(1){var $5=$ix;var $arrayidx=((_embedded_default+$5*4)&4294967295);var $6=HEAP32[(($arrayidx)>>2)];var $7=$ix;var $arrayidx3=((_embedded_value+$7*4)&4294967295);HEAP32[(($arrayidx3)>>2)]=$6;var $8=$ix;var $inc=((($8)+1)&4294967295);$ix=$inc;var $cmp2=((($inc))|0)<15;if($cmp2){__label__=3;continue $for_body$5;}else{__label__=4;break $for_body$5;}}
var $9=HEAP32[((_samplerate)>>2)];var $10=$wavemult_fact_addr;var $mul4=((($10)*($9))&4294967295);var $div5=((((($mul4))|0)/12800)|0);HEAP32[((__ZL12wavemult_max)>>2)]=$div5;var $11=HEAP32[((__ZL12wavemult_max)>>2)];var $cmp6=((($11))|0)>128;if($cmp6){__label__=5;;}else{__label__=6;;}
if(__label__==5){HEAP32[((__ZL12wavemult_max)>>2)]=128;;}
var $12=HEAP32[((__ZL12wavemult_max)>>2)];var $div9=((((($12))|0)/2)|0);HEAP32[((__ZL15wavemult_offset)>>2)]=$div9;var $13=HEAP32[((_samplerate)>>2)];var $cmp10=((($13))|0)!=22050;if($cmp10){__label__=7;;}else{__label__=9;;}
$if_then11$$if_end25$11:do{if(__label__==7){$ix=0;var $14=$ix;var $15=HEAP32[((__ZL12wavemult_max)>>2)];var $cmp131=((($14))|0)<((($15))|0);if(!($cmp131)){__label__=9;break $if_then11$$if_end25$11;}
while(1){var $16=$ix;var $conv=((($16))|0);var $mul15=6.283185307*($conv);var $17=HEAP32[((__ZL12wavemult_max)>>2)];var $conv16=((($17))|0);var $div17=($mul15)/($conv16);var $call=_cos($div17);var $sub=1-($call);var $mul18=127*($sub);$x=$mul18;var $18=$x;var $conv19=((($18))|0);var $conv20=((($conv19))&255);var $19=$ix;var $arrayidx21=((__ZL8wavemult+$19)&4294967295);HEAP8[($arrayidx21)]=$conv20;var $20=$ix;var $inc23=((($20)+1)&4294967295);$ix=$inc23;var $21=$ix;var $22=HEAP32[((__ZL12wavemult_max)>>2)];var $cmp13=((($21))|0)<((($22))|0);if($cmp13){__label__=8;continue;}else{__label__=9;break $if_then11$$if_end25$11;}}}}while(0);__ZL17WavegenInitPkDatai(1);__ZL17WavegenInitPkDatai(0);HEAP32[((__ZL8pk_shape)>>2)]=((__ZL9pk_shape2)&4294967295);__Z9KlattInitv();;return;return;}
function __ZL17WavegenInitPkDatai($which){;var __label__;;return;return;}
function __Z12GetAmplitudev(){;var __label__;var $amp;var $0=HEAP32[((((_embedded_value+12)&4294967295))>>2)];var $mul=((($0)*55)&4294967295);var $div=((((($mul))|0)/100)|0);$amp=$div;var $1=$amp;var $2=HEAP32[((((_embedded_value+52)&4294967295))>>2)];var $arrayidx=((__ZZ12GetAmplitudevE12amp_emphasis+$2)&4294967295);var $3=HEAPU8[($arrayidx)];var $conv=((($3))&255);var $mul1=((($conv)*($1))&4294967295);var $div2=((((($mul1))|0)/16)|0);HEAP32[((__ZL17general_amplitude)>>2)]=$div2;var $4=HEAP32[((__ZL17general_amplitude)>>2)];;return $4;return null;}
function __Z16PeaksToHarmspectP15wavegen_peaks_tiPii($peaks,$pitch,$htab,$control){;var __label__;var $retval;var $peaks_addr;var $pitch_addr;var $htab_addr;var $control_addr;var $f;var $p;var $fp;var $fhi;var $h;var $pk;var $hmax;var $hmax_samplerate;var $x;var $ix;var $h1;var $y;var $h2;$peaks_addr=$peaks;$pitch_addr=$pitch;$htab_addr=$htab;$control_addr=$control;var $0=HEAP32[((_wvoice)>>2)];var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $1=HEAP32[((_wvoice)>>2)];var $n_harmonic_peaks=(($1+84)&4294967295);var $2=HEAP32[(($n_harmonic_peaks)>>2)];var $3=$peaks_addr;var $arrayidx=(($3+80*$2)&4294967295);var $freq=(($arrayidx)&4294967295);var $4=HEAP32[(($freq)>>2)];var $5=HEAP32[((_wvoice)>>2)];var $n_harmonic_peaks1=(($5+84)&4294967295);var $6=HEAP32[(($n_harmonic_peaks1)>>2)];var $7=$peaks_addr;var $arrayidx2=(($7+80*$6)&4294967295);var $right=(($arrayidx2+12)&4294967295);var $8=HEAP32[(($right)>>2)];var $add=((($8)+($4))&4294967295);var $9=$pitch_addr;var $div=((((($add))|0)/((($9))|0))|0);$hmax=$div;var $10=$hmax;var $cmp3=((($10))|0)>=400;if($cmp3){__label__=3;;}else{__label__=4;;}
if(__label__==3){$hmax=399;;}
var $11=HEAP32[((_samplerate)>>2)];var $mul=((($11)*19)&4294967295);var $div6=((((($mul))|0)/40)|0);var $shl=($div6)<<16;var $12=$pitch_addr;var $div7=((((($shl))|0)/((($12))|0))|0);$hmax_samplerate=$div7;var $13=$hmax;var $14=$hmax_samplerate;var $cmp8=((($13))|0)>((($14))|0);if($cmp8){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $15=$hmax_samplerate;$hmax=$15;;}
$h=0;var $16=$h;var $17=$hmax;var $cmp118=((($16))|0)<=((($17))|0);if($cmp118){__label__=7;;}else{__label__=8;;}
$for_body$$for_end$11:do{if(__label__==7){while(1){var $18=$h;var $19=$htab_addr;var $arrayidx12=(($19+4*$18)&4294967295);HEAP32[(($arrayidx12)>>2)]=0;var $20=$h;var $inc=((($20)+1)&4294967295);$h=$inc;var $21=$h;var $22=$hmax;var $cmp11=((($21))|0)<=((($22))|0);if($cmp11){__label__=7;continue;}else{__label__=8;break $for_body$$for_end$11;}}}}while(0);$h=0;$pk=0;var $23=$pk;var $24=HEAP32[((_wvoice)>>2)];var $n_harmonic_peaks146=(($24+84)&4294967295);var $25=HEAP32[(($n_harmonic_peaks146)>>2)];var $cmp157=((($23))|0)<=((($25))|0);if($cmp157){__label__=9;;}else{__label__=18;;}
$for_body16$$for_end67$15:do{if(__label__==9){$for_body16$16:while(1){var $26=$pk;var $27=$peaks_addr;var $arrayidx17=(($27+80*$26)&4294967295);$p=$arrayidx17;var $28=$p;var $height=(($28+4)&4294967295);var $29=HEAP32[(($height)>>2)];var $cmp18=((($29))|0)==0;if($cmp18){__label__=17;;}else{__label__=10;;}
$for_inc65$$lor_lhs_false$18:do{if(__label__==10){var $30=$p;var $freq19=(($30)&4294967295);var $31=HEAP32[(($freq19)>>2)];$fp=$31;var $cmp20=((($31))|0)==0;if($cmp20){__label__=17;break $for_inc65$$lor_lhs_false$18;}
var $32=$p;var $freq23=(($32)&4294967295);var $33=HEAP32[(($freq23)>>2)];var $34=$p;var $right24=(($34+12)&4294967295);var $35=HEAP32[(($right24)>>2)];var $add25=((($35)+($33))&4294967295);$fhi=$add25;var $36=$p;var $freq26=(($36)&4294967295);var $37=HEAP32[(($freq26)>>2)];var $38=$p;var $left=(($38+8)&4294967295);var $39=HEAP32[(($left)>>2)];var $sub=((($37)-($39))&4294967295);var $40=$pitch_addr;var $div27=((((($sub))|0)/((($40))|0))|0);var $add28=((($div27)+1)&4294967295);$h=$add28;var $41=$h;var $cmp29=((($41))|0)<=0;if($cmp29){__label__=12;;}else{__label__=13;;}
if(__label__==12){$h=1;;}
var $42=$pitch_addr;var $43=$h;var $mul32=((($43)*($42))&4294967295);$f=$mul32;var $44=$f;var $45=$fp;var $cmp344=((($44))|0)<((($45))|0);if($cmp344){__label__=14;;}else{__label__=15;;}
$for_body35$$for_cond48_loopexit$24:do{if(__label__==14){while(1){var $46=$fp;var $47=$f;var $sub36=((($46)-($47))&4294967295);var $48=$p;var $left37=(($48+8)&4294967295);var $49=HEAP32[(($left37)>>2)];var $shr=($49)>>8;var $div38=((((($sub36))|0)/((($shr))|0))|0);var $50=HEAP32[((__ZL8pk_shape)>>2)];var $arrayidx39=(($50+$div38)&4294967295);var $51=HEAPU8[($arrayidx39)];var $conv=((($51))&255);var $52=$p;var $height40=(($52+4)&4294967295);var $53=HEAP32[(($height40)>>2)];var $mul41=((($53)*($conv))&4294967295);var $54=$h;var $inc42=((($54)+1)&4294967295);$h=$inc42;var $55=$htab_addr;var $arrayidx43=(($55+4*$54)&4294967295);var $56=HEAP32[(($arrayidx43)>>2)];var $add44=((($56)+($mul41))&4294967295);HEAP32[(($arrayidx43)>>2)]=$add44;var $57=$pitch_addr;var $58=$f;var $add46=((($58)+($57))&4294967295);$f=$add46;var $59=$f;var $60=$fp;var $cmp34=((($59))|0)<((($60))|0);if($cmp34){__label__=14;continue;}else{__label__=15;break $for_body35$$for_cond48_loopexit$24;}}}}while(0);var $61=$f;var $62=$fhi;var $cmp495=((($61))|0)<((($62))|0);if(!($cmp495)){__label__=17;break $for_inc65$$lor_lhs_false$18;}
while(1){var $63=$f;var $64=$fp;var $sub51=((($63)-($64))&4294967295);var $65=$p;var $right52=(($65+12)&4294967295);var $66=HEAP32[(($right52)>>2)];var $shr53=($66)>>8;var $div54=((((($sub51))|0)/((($shr53))|0))|0);var $67=HEAP32[((__ZL8pk_shape)>>2)];var $arrayidx55=(($67+$div54)&4294967295);var $68=HEAPU8[($arrayidx55)];var $conv56=((($68))&255);var $69=$p;var $height57=(($69+4)&4294967295);var $70=HEAP32[(($height57)>>2)];var $mul58=((($70)*($conv56))&4294967295);var $71=$h;var $inc59=((($71)+1)&4294967295);$h=$inc59;var $72=$htab_addr;var $arrayidx60=(($72+4*$71)&4294967295);var $73=HEAP32[(($arrayidx60)>>2)];var $add61=((($73)+($mul58))&4294967295);HEAP32[(($arrayidx60)>>2)]=$add61;var $74=$pitch_addr;var $75=$f;var $add63=((($75)+($74))&4294967295);$f=$add63;var $76=$f;var $77=$fhi;var $cmp49=((($76))|0)<((($77))|0);if($cmp49){__label__=16;continue;}else{__label__=17;break $for_inc65$$lor_lhs_false$18;}}}}while(0);var $78=$pk;var $inc66=((($78)+1)&4294967295);$pk=$inc66;var $79=$pk;var $80=HEAP32[((_wvoice)>>2)];var $n_harmonic_peaks14=(($80+84)&4294967295);var $81=HEAP32[(($n_harmonic_peaks14)>>2)];var $cmp15=((($79))|0)<=((($81))|0);if($cmp15){__label__=9;continue $for_body16$16;}else{__label__=18;break $for_body16$$for_end67$15;}}}}while(0);var $82=$peaks_addr;var $arrayidx68=(($82+80)&4294967295);var $height69=(($arrayidx68+4)&4294967295);var $83=HEAP32[(($height69)>>2)];var $mul70=((($83)*10)&4294967295);$y=$mul70;var $84=$pitch_addr;var $div71=((65536000/((($84))|0))|0);$h2=$div71;var $cmp72=((($div71))|0)>0;if($cmp72){__label__=19;;}else{__label__=21;;}
$if_then73$$for_cond81thread_pre_split$32:do{if(__label__==19){var $85=$y;var $86=$h2;var $div74=((((($85))|0)/((($86))|0))|0);$x=$div74;$h=1;var $cmp753=((($85))|0)>0;if(!($cmp753)){__label__=21;break $if_then73$$for_cond81thread_pre_split$32;}
while(1){var $87=$y;var $88=$h;var $inc76=((($88)+1)&4294967295);$h=$inc76;var $89=$htab_addr;var $arrayidx77=(($89+4*$88)&4294967295);var $90=HEAP32[(($arrayidx77)>>2)];var $add78=((($90)+($87))&4294967295);HEAP32[(($arrayidx77)>>2)]=$add78;var $91=$x;var $92=$y;var $sub79=((($92)-($91))&4294967295);$y=$sub79;var $cmp75=((($sub79))|0)>0;if($cmp75){__label__=20;continue;}else{__label__=21;break $if_then73$$for_cond81thread_pre_split$32;}}}}while(0);var $_pr=$pk;var $cmp822=((($_pr))|0)<9;if($cmp822){__label__=22;;}else{__label__=27;;}
$for_body83$$for_end105$37:do{if(__label__==22){while(1){var $93=$pk;var $94=$peaks_addr;var $arrayidx84=(($94+80*$93)&4294967295);var $height85=(($arrayidx84+4)&4294967295);var $95=HEAP32[(($height85)>>2)];var $shr86=($95)>>14;$x=$shr86;var $96=$x;var $97=$x;var $mul87=((($96)*5)&4294967295);var $mul88=((($mul87)*($97))&4294967295);var $div89=((((($mul88))|0)/2)|0);var $98=$pk;var $arrayidx90=((__ZL11peak_height+$98*4)&4294967295);HEAP32[(($arrayidx90)>>2)]=$div89;var $99=$control_addr;var $cmp91=((($99))|0)==0;if($cmp91){__label__=23;;}else{__label__=24;;}
if(__label__==23){var $100=$pk;var $101=$peaks_addr;var $arrayidx93=(($101+80*$100)&4294967295);var $freq94=(($arrayidx93)&4294967295);var $102=HEAP32[(($freq94)>>2)];var $103=$pitch_addr;var $div95=((((($102))|0)/((($103))|0))|0);var $104=$pk;var $arrayidx96=((__ZL13peak_harmonic+$104*4)&4294967295);HEAP32[(($arrayidx96)>>2)]=$div95;;}
var $105=$pk;var $arrayidx98=((__ZL13peak_harmonic+$105*4)&4294967295);var $106=HEAP32[(($arrayidx98)>>2)];var $107=$hmax_samplerate;var $cmp99=((($106))|0)>=((($107))|0);if($cmp99){__label__=25;;}else{__label__=26;;}
if(__label__==25){var $108=$pk;var $arrayidx101=((__ZL11peak_height+$108*4)&4294967295);HEAP32[(($arrayidx101)>>2)]=0;;}
var $109=$pk;var $inc104=((($109)+1)&4294967295);$pk=$inc104;var $cmp82=((($inc104))|0)<9;if($cmp82){__label__=22;continue;}else{__label__=27;break $for_body83$$for_end105$37;}}}}while(0);$f=0;$h=0;var $110=$h;var $111=$hmax;var $cmp1071=((($110))|0)<=((($111))|0);if($cmp1071){__label__=28;;}else{__label__=31;;}
$for_body108$$for_end127$47:do{if(__label__==28){while(1){var $112=$h;var $113=$htab_addr;var $arrayidx109=(($113+4*$112)&4294967295);var $114=HEAP32[(($arrayidx109)>>2)];var $shr110=($114)>>15;$x=$shr110;var $115=$x;var $116=$x;var $mul111=((($116)*($115))&4294967295);var $shr112=($mul111)>>8;var $117=$h;var $118=$htab_addr;var $arrayidx113=(($118+4*$117)&4294967295);HEAP32[(($arrayidx113)>>2)]=$shr112;var $119=$f;var $shr114=($119)>>19;$ix=$shr114;var $cmp115=((($shr114))|0)<1000;if($cmp115){__label__=29;;}else{__label__=30;;}
if(__label__==29){var $120=$h;var $121=$htab_addr;var $arrayidx117=(($121+4*$120)&4294967295);var $122=HEAP32[(($arrayidx117)>>2)];var $123=$ix;var $124=HEAP32[((_wvoice)>>2)];var $tone_adjust=(($124+344)&4294967295);var $arrayidx118=(($tone_adjust+$123)&4294967295);var $125=HEAPU8[($arrayidx118)];var $conv119=((($125))&255);var $mul120=((($conv119)*($122))&4294967295);var $shr121=($mul120)>>13;var $126=$h;var $127=$htab_addr;var $arrayidx122=(($127+4*$126)&4294967295);HEAP32[(($arrayidx122)>>2)]=$shr121;;}
var $128=$h;var $inc125=((($128)+1)&4294967295);$h=$inc125;var $129=$pitch_addr;var $130=$f;var $add126=((($130)+($129))&4294967295);$f=$add126;var $131=$h;var $132=$hmax;var $cmp107=((($131))|0)<=((($132))|0);if($cmp107){__label__=28;continue;}else{__label__=31;break $for_body108$$for_end127$47;}}}}while(0);var $133=$htab_addr;var $arrayidx128=(($133+4)&4294967295);var $134=HEAP32[(($arrayidx128)>>2)];var $_b=HEAPU8[(__ZL16option_harmonic1_b)];var $135=($_b)?6:10;var $mul129=((($135)*($134))&4294967295);$h1=$mul129;var $136=$h1;var $div130=((((($136))|0)/8)|0);var $137=$htab_addr;var $arrayidx131=(($137+4)&4294967295);HEAP32[(($arrayidx131)>>2)]=$div130;var $138=$control_addr;var $and=($138)&1;var $tobool=((($and))|0)!=0;if($tobool){__label__=32;;}else{__label__=34;;}
$if_then132$$if_end144$54:do{if(__label__==32){$h=1;;while(1){var $139=$h;var $140=$htab_addr;var $arrayidx136=(($140+4*$139)&4294967295);var $141=HEAP32[(($arrayidx136)>>2)];var $142=$h;var $143=HEAP32[((__ZL9harmspect)>>2)];var $arrayidx137=(($143+4*$142)&4294967295);var $144=HEAP32[(($arrayidx137)>>2)];var $sub138=((($141)-($144))&4294967295);var $shr139=($sub138)>>3;var $145=$h;var $arrayidx140=((__ZL8harm_inc+$145*4)&4294967295);HEAP32[(($arrayidx140)>>2)]=$shr139;var $146=$h;var $inc142=((($146)+1)&4294967295);$h=$inc142;var $cmp134=((($inc142))|0)<30;if($cmp134){__label__=33;continue;}else{__label__=34;break $if_then132$$if_end144$54;}}}}while(0);var $147=$hmax;$retval=$147;;}
var $148=$retval;;return $148;return null;}
function __Z10InitBreathv(){;var __label__;var $ix;var $0=HEAP32[((_samplerate)>>2)];var $conv=((($0))|0);var $div=-3.1415927/($conv);HEAPF32[((__ZL10minus_pi_t)>>2)]=$div;var $1=HEAPF32[((__ZL10minus_pi_t)>>2)];var $mul=-2*($1);HEAPF32[((__ZL8two_pi_t)>>2)]=$mul;$ix=0;;while(1){var $2=$ix;var $arrayidx=((__ZL7rbreath+$2*40)&4294967295);__ZL12setresonatorP9RESONATORiii($arrayidx,2000,200,1);var $3=$ix;var $inc=((($3)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<9;if($cmp){__label__=1;continue;}else{__label__=2;break;}};return;return;}
function __ZL12setresonatorP9RESONATORiii($rp,$freq,$bwidth,$init){;var __label__;var $rp_addr;var $freq_addr;var $bwidth_addr;var $init_addr;var $x;var $arg;$rp_addr=$rp;$freq_addr=$freq;$bwidth_addr=$bwidth;$init_addr=$init;var $0=$init_addr;var $tobool=((($0))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$rp_addr;var $x1=(($1+24)&4294967295);HEAPF32[(($x1)>>2)]=0;var $2=$rp_addr;var $x2=(($2+32)&4294967295);HEAPF32[(($x2)>>2)]=0;;}
var $3=HEAPF32[((__ZL10minus_pi_t)>>2)];var $4=$bwidth_addr;var $conv=((($4))|0);var $mul=($3)*($conv);$arg=$mul;var $5=$arg;var $call=_exp($5);$x=$call;var $6=$x;var $7=$x;var $mul1=($6)*($7);var $sub=(-($mul1));var $8=$rp_addr;var $c=(($8+16)&4294967295);HEAPF32[(($c)>>2)]=$sub;var $9=HEAPF32[((__ZL8two_pi_t)>>2)];var $10=$freq_addr;var $conv2=((($10))|0);var $mul3=($9)*($conv2);$arg=$mul3;var $11=$x;var $12=$arg;var $call4=_cos($12);var $mul5=($11)*($call4);var $mul6=($mul5)*2;var $13=$rp_addr;var $b=(($13+8)&4294967295);HEAPF32[(($b)>>2)]=$mul6;var $14=$rp_addr;var $b7=(($14+8)&4294967295);var $15=HEAPF32[(($b7)>>2)];var $sub8=1-($15);var $16=$rp_addr;var $c9=(($16+16)&4294967295);var $17=HEAPF32[(($c9)>>2)];var $sub10=($sub8)-($17);var $18=$rp_addr;var $a=(($18)&4294967295);HEAPF32[(($a)>>2)]=$sub10;;return;return;}
function __Z7Wavegenv(){;var __label__;var __lastLabel__=null;var $retval;var $waveph;var $theta;var $total;var $h;var $ix;var $z;var $z1;var $z2;var $echo;var $ov;var $pk;var $c;var $sample;var $amp;var $modn_amp;var $modn_period;;$for_cond$2:while(1){var $_b=HEAPU8[(__ZL8end_wave_b)];var $0=((($_b))&1);var $cmp=((($0))|0)==0;var $1=HEAP32[((__ZL11samplecount)>>2)];var $2=HEAP32[((__ZL8nsamples)>>2)];var $cmp1=((($1))|0)==((($2))|0);var $or_cond3=($cmp)&($cmp1);if($or_cond3){__label__=2;break $for_cond$2;}
var $and=($1)&63;var $cmp2=((($and))|0)==0;if($cmp2){__label__=4;;}else{__label__=8;;}
$if_then3$$if_else19$5:do{if(__label__==4){var $cmp4=((($1))|0)==0;if($cmp4){__label__=5;;}else{__label__=6;;}
if(__label__==5){HEAP32[((__ZL7hswitch)>>2)]=0;HEAP32[((__ZL9harmspect)>>2)]=((__ZL6hspect)&4294967295);var $3=HEAP32[((((_wdata+4)&4294967295))>>2)];var $shl=($3)<<4;var $call=__Z16PeaksToHarmspectP15wavegen_peaks_tiPii(((__ZL5peaks)&4294967295),$shl,((__ZL6hspect)&4294967295),0);HEAP32[((__ZZ7WavegenvE5maxh2)>>2)]=$call;var $4=HEAP32[((((_wdata+52)&4294967295))>>2)];var $5=HEAP32[((((_wdata+4)&4294967295))>>2)];var $shr=($5)>>8;var $6=HEAP32[((((_wdata+60)&4294967295))>>2)];var $mul=((($6)*($4))&4294967295);var $mul6=((($mul)*($shr))&4294967295);var $div=((((($mul6))|0)/80000)|0);HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)]=$div;var $7=HEAP32[((((_wdata+4)&4294967295))>>2)];var $shr7=($7)>>12;var $div8=((890/((($shr7))|0))|0);HEAP32[((__ZZ7WavegenvE13h_switch_sign)>>2)]=$div8;;}
else if(__label__==6){__ZL17AdvanceParametersv();;}
var $8=HEAP32[((((_wdata+4)&4294967295))>>2)];var $shr10=($8)>>7;var $9=HEAP32[((__ZL16PHASE_INC_FACTOR)>>2)];var $mul11=((($shr10)*($9))&4294967295);HEAP32[((__ZL8phaseinc)>>2)]=$mul11;var $10=HEAP32[((_samplerate)>>2)];var $11=HEAP32[((((_wdata+4)&4294967295))>>2)];var $shr12=($11)>>12;var $div13=((((($10))|0)/((($shr12))|0))|0);HEAP32[((__ZL13cycle_samples)>>2)]=$div13;var $12=HEAP32[((((_wdata+4)&4294967295))>>2)];var $shr14=($12)>>11;HEAP32[((__ZL9hf_factor)>>2)]=$shr14;var $13=HEAP32[((__ZZ7WavegenvE5maxh2)>>2)];HEAP32[((__ZZ7WavegenvE4maxh)>>2)]=$13;var $14=HEAP32[((__ZL7hswitch)>>2)];var $arrayidx=((__ZL6hspect+$14*1600)&4294967295);var $arraydecay=(($arrayidx)&4294967295);HEAP32[((__ZL9harmspect)>>2)]=$arraydecay;var $15=HEAP32[((__ZL7hswitch)>>2)];var $xor=($15)^1;HEAP32[((__ZL7hswitch)>>2)]=$xor;var $16=HEAP32[((((_wdata+4)&4294967295))>>2)];var $shl15=($16)<<4;var $17=HEAP32[((__ZL7hswitch)>>2)];var $arrayidx16=((__ZL6hspect+$17*1600)&4294967295);var $arraydecay17=(($arrayidx16)&4294967295);var $call18=__Z16PeaksToHarmspectP15wavegen_peaks_tiPii(((__ZL5peaks)&4294967295),$shl15,$arraydecay17,1);HEAP32[((__ZZ7WavegenvE5maxh2)>>2)]=$call18;__ZL9SetBreathv();;}
else if(__label__==8){var $and20=($1)&7;var $cmp21=((($and20))|0)==0;if(!($cmp21)){__label__=16;break $if_then3$$if_else19$5;}
$h=1;__lastLabel__=9;;while(1){var $18=__lastLabel__==13?$inc:(1);var $cmp24=((($18))|0)<30;if(!($cmp24)){__label__=14;break;}
var $19=$h;var $20=HEAP32[((__ZZ7WavegenvE5maxh2)>>2)];var $cmp26=((($19))|0)<=((($20))|0);if(!($cmp26)){__label__=14;break;}
var $21=$h;var $22=HEAP32[((__ZZ7WavegenvE4maxh)>>2)];var $cmp27=((($21))|0)<=((($22))|0);if(!($cmp27)){__label__=14;break;}
var $23=$h;var $arrayidx28=((__ZL8harm_inc+$23*4)&4294967295);var $24=HEAP32[(($arrayidx28)>>2)];var $25=$h;var $26=HEAP32[((__ZL9harmspect)>>2)];var $arrayidx29=(($26+4*$25)&4294967295);var $27=HEAP32[(($arrayidx29)>>2)];var $add=((($27)+($24))&4294967295);HEAP32[(($arrayidx29)>>2)]=$add;var $28=$h;var $inc=((($28)+1)&4294967295);$h=$inc;__lastLabel__=13;__label__=10;continue;}
var $29=HEAP32[((__ZZ7WavegenvE3agc)>>2)];var $cmp30=((($29))|0)<256;if(!($cmp30)){__label__=16;break $if_then3$$if_else19$5;}
var $30=HEAP32[((__ZZ7WavegenvE3agc)>>2)];var $inc32=((($30)+1)&4294967295);HEAP32[((__ZZ7WavegenvE3agc)>>2)]=$inc32;;}}while(0);var $31=HEAP32[((__ZL11samplecount)>>2)];var $inc36=((($31)+1)&4294967295);HEAP32[((__ZL11samplecount)>>2)]=$inc36;var $32=HEAP32[((__ZL9wavephase)>>2)];var $cmp37=((($32))|0)>0;var $33=HEAP32[((__ZL8phaseinc)>>2)];var $34=HEAP32[((__ZL9wavephase)>>2)];var $add39=((($34)+($33))&4294967295);HEAP32[((__ZL9wavephase)>>2)]=$add39;var $35=HEAP32[((__ZL9wavephase)>>2)];var $cmp40=((($35))|0)<0;var $or_cond=($cmp37)&($cmp40);if($or_cond){__label__=17;;}else{__label__=38;;}
$if_then41$$if_end118$21:do{if(__label__==17){var $36=HEAP32[((__ZL15wavemult_offset)>>2)];var $37=HEAP32[((__ZL13cycle_samples)>>2)];var $div42=((((($37))|0)/2)|0);var $sub=((($36)-($div42))&4294967295);HEAP32[((__ZL6cbytes)>>2)]=$sub;var $38=HEAP32[((__ZL11samplecount)>>2)];var $39=HEAP32[((__ZL8nsamples)>>2)];var $cmp43=((($38))|0)>((($39))|0);if($cmp43){__label__=18;break $for_cond$2;}
var $40=HEAP32[((__ZZ7WavegenvE11cycle_count)>>2)];var $inc46=((($40)+1)&4294967295);HEAP32[((__ZZ7WavegenvE11cycle_count)>>2)]=$inc46;var $41=HEAP32[((_wvoice)>>2)];var $n_harmonic_peaks=(($41+84)&4294967295);var $42=HEAP32[(($n_harmonic_peaks)>>2)];var $add47=((($42)+1)&4294967295);$pk=$add47;var $cmp495=((($add47))|0)<9;if($cmp495){__label__=20;;}else{__label__=21;;}
$for_body50$$for_end57$24:do{if(__label__==20){while(1){var $43=$pk;var $arrayidx51=((__ZL5peaks+$43*80)&4294967295);var $freq=(($arrayidx51)&4294967295);var $44=HEAP32[(($freq)>>2)];var $45=HEAP32[((((_wdata+4)&4294967295))>>2)];var $mul52=((($45)*16)&4294967295);var $div53=((((($44))|0)/((($mul52))|0))|0);var $46=$pk;var $arrayidx54=((__ZL13peak_harmonic+$46*4)&4294967295);HEAP32[(($arrayidx54)>>2)]=$div53;var $47=$pk;var $inc56=((($47)+1)&4294967295);$pk=$inc56;var $cmp49=((($inc56))|0)<9;if($cmp49){__label__=20;continue;}else{__label__=21;break $for_body50$$for_end57$24;}}}}while(0);var $48=HEAP32[((((_wdata+52)&4294967295))>>2)];var $49=HEAP32[((((_wdata+4)&4294967295))>>2)];var $shr58=($49)>>8;var $50=HEAP32[((((_wdata+60)&4294967295))>>2)];var $mul59=((($50)*($48))&4294967295);var $mul60=((($mul59)*($shr58))&4294967295);var $div61=((((($mul60))|0)/80000)|0);HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)]=$div61;var $51=HEAP32[((__ZL12glottal_flag)>>2)];var $cmp62=((($51))|0)>0;if($cmp62){__label__=22;;}else{__label__=28;;}
$if_then63$$if_end81$28:do{if(__label__==22){var $52=HEAP32[((__ZL12glottal_flag)>>2)];var $cmp64=((($52))|0)==3;if($cmp64){__label__=23;;}else{__label__=25;;}
if(__label__==23){var $53=HEAP32[((__ZL8nsamples)>>2)];var $54=HEAP32[((__ZL11samplecount)>>2)];var $sub66=((($53)-($54))&4294967295);var $55=HEAP32[((__ZL13cycle_samples)>>2)];var $mul67=((($55)*2)&4294967295);var $cmp68=((($sub66))|0)<((($mul67))|0);if(!($cmp68)){__label__=28;break $if_then63$$if_end81$28;}
HEAP32[((__ZL12glottal_flag)>>2)]=2;var $56=HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)];var $57=HEAP32[((__ZL14glottal_reduce)>>2)];var $mul70=((($57)*($56))&4294967295);var $div71=((((($mul70))|0)/256)|0);HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)]=$div71;;}
else if(__label__==25){var $58=HEAP32[((__ZL12glottal_flag)>>2)];var $cmp74=((($58))|0)==4;if($cmp74){__label__=26;;}else{__label__=27;;}
if(__label__==26){HEAP32[((__ZL12glottal_flag)>>2)]=2;var $59=HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)];var $60=HEAP32[((__ZL14glottal_reduce)>>2)];var $mul76=((($60)*($59))&4294967295);var $div77=((((($mul76))|0)/256)|0);HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)]=$div77;;}
else if(__label__==27){var $61=HEAP32[((__ZL12glottal_flag)>>2)];var $dec=((($61)-1)&4294967295);HEAP32[((__ZL12glottal_flag)>>2)]=$dec;;}}}}while(0);var $62=HEAP32[((__ZL13amplitude_env)>>2)];var $cmp82=((($62))|0)!=0;if($cmp82){__label__=29;;}else{__label__=32;;}
if(__label__==29){var $63=HEAP32[((__ZL6amp_ix)>>2)];var $shr84=($63)>>8;$ix=$shr84;var $cmp85=((($shr84))|0)>127;if($cmp85){__label__=30;;}else{__label__=31;;}
if(__label__==30){$ix=127;;}
var $64=$ix;var $65=HEAP32[((__ZL13amplitude_env)>>2)];var $arrayidx88=(($65+$64)&4294967295);var $66=HEAPU8[($arrayidx88)];var $conv=((($66))&255);$amp=$conv;var $67=HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)];var $68=$amp;var $mul89=((($68)*($67))&4294967295);var $div90=((((($mul89))|0)/128)|0);HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)]=$div90;;}
$modn_period=0;var $69=HEAP32[((_voice)>>2)];var $roughness=(($69+72)&4294967295);var $70=HEAP32[(($roughness)>>2)];var $cmp92=((($70))|0)<8;if(!($cmp92)){__label__=38;break $if_then41$$if_end118$21;}
var $71=HEAP32[((__ZL15modulation_type)>>2)];var $72=HEAP32[((_voice)>>2)];var $roughness94=(($72+72)&4294967295);var $73=HEAP32[(($roughness94)>>2)];var $arrayidx95=((__ZL14modulation_tab+$73*8)&4294967295);var $arrayidx96=(($arrayidx95+$71)&4294967295);var $74=HEAPU8[($arrayidx96)];var $conv97=((($74))&255);$modn_period=$conv97;var $75=$modn_period;var $and98=($75)&15;$modn_amp=$and98;var $76=$modn_period;var $shr99=($76)>>4;$modn_period=$shr99;var $cmp101=((($shr99))|0)!=0;if(!($cmp101)){__label__=38;break $if_then41$$if_end118$21;}
var $77=$modn_period;var $cmp103=((($77))|0)==15;if($cmp103){__label__=35;;}else{__label__=36;;}
if(__label__==35){var $78=HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)];var $79=$modn_amp;var $mul105=((($79)*($78))&4294967295);var $div106=((((($mul105))|0)/16)|0);HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)]=$div106;HEAP32[((__ZL15modulation_type)>>2)]=0;;}
else if(__label__==36){var $80=HEAP32[((__ZZ7WavegenvE11cycle_count)>>2)];var $81=$modn_period;var $rem=((($80))|0)%((($81))|0);var $cmp108=((($rem))|0)==0;if(!($cmp108)){__label__=38;break $if_then41$$if_end118$21;}
var $82=HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)];var $83=$modn_amp;var $mul110=((($83)*($82))&4294967295);var $div111=((((($mul110))|0)/16)|0);HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)]=$div111;;}}}while(0);var $84=HEAP32[((__ZL9wavephase)>>2)];var $shr119=($84)>>16;var $conv120=((($shr119))&65535);$waveph=$conv120;$total=0;var $85=HEAP32[((__ZL6cbytes)>>2)];var $inc121=((($85)+1)&4294967295);HEAP32[((__ZL6cbytes)>>2)]=$inc121;var $cmp122=((($inc121))|0)>=0;if($cmp122){__label__=39;;}else{__label__=43;;}
$land_lhs_true123$$if_end149$51:do{if(__label__==39){var $86=HEAP32[((__ZL6cbytes)>>2)];var $87=HEAP32[((__ZL12wavemult_max)>>2)];var $cmp124=((($86))|0)<((($87))|0);if(!($cmp124)){__label__=43;break $land_lhs_true123$$if_end149$51;}
var $88=HEAP32[((_wvoice)>>2)];var $n_harmonic_peaks126=(($88+84)&4294967295);var $89=HEAP32[(($n_harmonic_peaks126)>>2)];var $add127=((($89)+1)&4294967295);$pk=$add127;var $cmp1294=((($add127))|0)<9;if($cmp1294){__label__=41;;}else{__label__=42;;}
$for_body130$$for_end144$54:do{if(__label__==41){while(1){var $90=$pk;var $arrayidx131=((__ZL13peak_harmonic+$90*4)&4294967295);var $91=HEAP32[(($arrayidx131)>>2)];var $92=$waveph;var $conv132=((($92))&65535);var $mul133=((($conv132)*($91))&4294967295);var $conv134=((($mul133))&65535);$theta=$conv134;var $93=$theta;var $conv135=((($93))&65535);var $shr136=($conv135)>>5;var $arrayidx137=((_sin_tab+$shr136*2)&4294967295);var $94=HEAP16[(($arrayidx137)>>1)];var $conv138=(tempInt=(($94)),(tempInt>=32768?tempInt-65536:tempInt));var $95=$pk;var $arrayidx139=((__ZL11peak_height+$95*4)&4294967295);var $96=HEAP32[(($arrayidx139)>>2)];var $mul140=((($96)*($conv138))&4294967295);var $97=$total;var $add141=((($97)+($mul140))&4294967295);$total=$add141;var $98=$pk;var $inc143=((($98)+1)&4294967295);$pk=$inc143;var $cmp129=((($inc143))|0)<9;if($cmp129){__label__=41;continue;}else{__label__=42;break $for_body130$$for_end144$54;}}}}while(0);var $99=$total;var $100=HEAP32[((__ZL9hf_factor)>>2)];var $div145=((((($99))|0)/((($100))|0))|0);var $101=HEAP32[((__ZL6cbytes)>>2)];var $arrayidx146=((__ZL8wavemult+$101)&4294967295);var $102=HEAPU8[($arrayidx146)];var $conv147=((($102))&255);var $mul148=((($conv147)*($div145))&4294967295);$total=$mul148;;}}while(0);var $103=$waveph;$theta=$103;$h=1;var $104=$h;var $105=HEAP32[((__ZZ7WavegenvE13h_switch_sign)>>2)];var $cmp1516=((($104))|0)<=((($105))|0);if($cmp1516){__label__=44;;}else{__label__=45;;}
$for_body152$$while_cond_loopexit$59:do{if(__label__==44){while(1){var $106=$theta;var $conv153=((($106))&65535);var $shr154=($conv153)>>5;var $arrayidx155=((_sin_tab+$shr154*2)&4294967295);var $107=HEAP16[(($arrayidx155)>>1)];var $conv156=(tempInt=(($107)),(tempInt>=32768?tempInt-65536:tempInt));var $108=$h;var $109=HEAP32[((__ZL9harmspect)>>2)];var $arrayidx157=(($109+4*$108)&4294967295);var $110=HEAP32[(($arrayidx157)>>2)];var $mul158=((($110)*($conv156))&4294967295);var $111=$total;var $add159=((($111)+($mul158))&4294967295);$total=$add159;var $112=$waveph;var $conv160=((($112))&65535);var $113=$theta;var $conv161=((($113))&65535);var $add162=((($conv161)+($conv160))&4294967295);var $conv163=((($add162))&65535);$theta=$conv163;var $114=$h;var $inc165=((($114)+1)&4294967295);$h=$inc165;var $115=$h;var $116=HEAP32[((__ZZ7WavegenvE13h_switch_sign)>>2)];var $cmp151=((($115))|0)<=((($116))|0);if($cmp151){__label__=44;continue;}else{__label__=45;break $for_body152$$while_cond_loopexit$59;}}}}while(0);var $117=$h;var $118=HEAP32[((__ZZ7WavegenvE4maxh)>>2)];var $cmp1677=((($117))|0)<=((($118))|0);if($cmp1677){__label__=46;;}else{__label__=47;;}
$while_body$$while_end$63:do{if(__label__==46){while(1){var $119=$theta;var $conv168=((($119))&65535);var $shr169=($conv168)>>5;var $arrayidx170=((_sin_tab+$shr169*2)&4294967295);var $120=HEAP16[(($arrayidx170)>>1)];var $conv171=(tempInt=(($120)),(tempInt>=32768?tempInt-65536:tempInt));var $121=$h;var $122=HEAP32[((__ZL9harmspect)>>2)];var $arrayidx172=(($122+4*$121)&4294967295);var $123=HEAP32[(($arrayidx172)>>2)];var $mul173=((($123)*($conv171))&4294967295);var $124=$total;var $sub174=((($124)-($mul173))&4294967295);$total=$sub174;var $125=$waveph;var $conv175=((($125))&65535);var $126=$theta;var $conv176=((($126))&65535);var $add177=((($conv176)+($conv175))&4294967295);var $conv178=((($add177))&65535);$theta=$conv178;var $127=$h;var $inc179=((($127)+1)&4294967295);$h=$inc179;var $128=$h;var $129=HEAP32[((__ZZ7WavegenvE4maxh)>>2)];var $cmp167=((($128))|0)<=((($129))|0);if($cmp167){__label__=46;continue;}else{__label__=47;break $while_body$$while_end$63;}}}}while(0);var $130=HEAP32[((__ZL7voicing)>>2)];var $cmp180=((($130))|0)!=64;if($cmp180){__label__=48;;}else{__label__=49;;}
if(__label__==48){var $131=$total;var $shr182=($131)>>6;var $132=HEAP32[((__ZL7voicing)>>2)];var $mul183=((($shr182)*($132))&4294967295);$total=$mul183;;}
var $133=HEAP32[((_wvoice)>>2)];var $breath=(($133+272)&4294967295);var $arrayidx185=(($breath)&4294967295);var $134=HEAP32[(($arrayidx185)>>2)];var $tobool=((($134))|0)!=0;if($tobool){__label__=50;;}else{__label__=51;;}
if(__label__==50){var $call187=__ZL11ApplyBreathv();var $135=$total;var $add188=((($135)+($call187))&4294967295);$total=$add188;;}
$z2=0;var $136=HEAP32[((((_wdata+40)&4294967295))>>2)];var $137=HEAP32[((((_wdata+28)&4294967295))>>2)];var $cmp190=((($136))|0)<((($137))|0);if($cmp190){__label__=52;;}else{__label__=57;;}
$if_then191$$if_end222$73:do{if(__label__==52){var $138=HEAP32[((((_wdata+32)&4294967295))>>2)];var $cmp192=((($138))|0)==0;if($cmp192){__label__=53;;}else{__label__=54;;}
if(__label__==53){var $139=HEAP32[((((_wdata+40)&4294967295))>>2)];var $140=HEAP32[((((_wdata+48)&4294967295))>>2)];var $add194=((($139)+1)&4294967295);var $add195=((($add194)+($140))&4294967295);var $141=HEAP32[((((_wdata+24)&4294967295))>>2)];var $arrayidx196=(($141+$add195)&4294967295);var $142=HEAP8[($arrayidx196)];$c=$142;var $143=HEAP32[((((_wdata+40)&4294967295))>>2)];var $144=HEAP32[((((_wdata+48)&4294967295))>>2)];var $add197=((($144)+($143))&4294967295);var $145=HEAP32[((((_wdata+24)&4294967295))>>2)];var $arrayidx198=(($145+$add197)&4294967295);var $146=HEAPU8[($arrayidx198)];var $conv199=((($146))&255);var $147=$c;var $conv200=(tempInt=(($147)),(tempInt>=128?tempInt-256:tempInt));var $mul201=((($conv200)*256)&4294967295);var $add202=((($mul201)+($conv199))&4294967295);$sample=$add202;var $148=HEAP32[((((_wdata+40)&4294967295))>>2)];var $add203=((($148)+2)&4294967295);HEAP32[((((_wdata+40)&4294967295))>>2)]=$add203;;}
else if(__label__==54){var $149=HEAP32[((((_wdata+48)&4294967295))>>2)];var $150=HEAP32[((((_wdata+40)&4294967295))>>2)];var $inc205=((($150)+1)&4294967295);HEAP32[((((_wdata+40)&4294967295))>>2)]=$inc205;var $add206=((($150)+($149))&4294967295);var $151=HEAP32[((((_wdata+24)&4294967295))>>2)];var $arrayidx207=(($151+$add206)&4294967295);var $152=HEAP8[($arrayidx207)];var $conv208=(tempInt=(($152)),(tempInt>=128?tempInt-256:tempInt));var $153=HEAP32[((((_wdata+32)&4294967295))>>2)];var $mul209=((($conv208)*($153))&4294967295);$sample=$mul209;;}
var $154=$sample;var $155=HEAP32[((((_wdata+56)&4294967295))>>2)];var $mul211=((($155)*($154))&4294967295);var $shr212=($mul211)>>10;$z2=$shr212;var $156=$z2;var $157=HEAP32[((((_wdata+36)&4294967295))>>2)];var $mul213=((($157)*($156))&4294967295);var $div214=((((($mul213))|0)/32)|0);$z2=$div214;var $158=HEAP32[((((_wdata+40)&4294967295))>>2)];var $159=HEAP32[((((_wdata+48)&4294967295))>>2)];var $add215=((($159)+($158))&4294967295);var $160=HEAP32[((((_wdata+44)&4294967295))>>2)];var $cmp216=((($add215))|0)>=((($160))|0);if(!($cmp216)){__label__=57;break $if_then191$$if_end222$73;}
var $161=HEAP32[((((_wdata+44)&4294967295))>>2)];var $mul218=((($161)*3)&4294967295);var $div219=((((($mul218))|0)/4)|0);var $162=HEAP32[((((_wdata+48)&4294967295))>>2)];var $sub220=((($162)-($div219))&4294967295);HEAP32[((((_wdata+48)&4294967295))>>2)]=$sub220;;}}while(0);var $163=$z2;var $164=$total;var $shr223=($164)>>8;var $165=HEAP32[((__ZZ7WavegenvE10amplitude2)>>2)];var $mul224=((($shr223)*($165))&4294967295);var $shr225=($mul224)>>13;var $add226=((($shr225)+($163))&4294967295);$z1=$add226;var $166=HEAP32[((_echo_tail)>>2)];var $inc227=((($166)+1)&4294967295);HEAP32[((_echo_tail)>>2)]=$inc227;var $arrayidx228=((_echo_buf+$166*2)&4294967295);var $167=HEAP16[(($arrayidx228)>>1)];var $conv229=(tempInt=(($167)),(tempInt>=32768?tempInt-65536:tempInt));var $168=HEAP32[((_echo_amp)>>2)];var $mul230=((($conv229)*($168))&4294967295);$echo=$mul230;var $169=$echo;var $shr231=($169)>>8;var $170=$z1;var $add232=((($170)+($shr231))&4294967295);$z1=$add232;var $171=HEAP32[((_echo_tail)>>2)];var $cmp233=((($171))|0)>=5500;if($cmp233){__label__=58;;}else{__label__=59;;}
if(__label__==58){HEAP32[((_echo_tail)>>2)]=0;;}
var $172=$z1;var $173=HEAP32[((__ZZ7WavegenvE3agc)>>2)];var $mul236=((($173)*($172))&4294967295);var $shr237=($mul236)>>8;$z=$shr237;var $cmp238=((($shr237))|0)>=32768;if($cmp238){__label__=60;;}else{__label__=63;;}
$if_then239$$if_else247$84:do{if(__label__==60){var $174=$z1;var $div240=((8388608/((($174))|0))|0);var $sub241=((($div240)-1)&4294967295);$ov=$sub241;var $175=$ov;var $176=HEAP32[((__ZZ7WavegenvE3agc)>>2)];var $cmp242=((($175))|0)<((($176))|0);if($cmp242){__label__=61;;}else{__label__=62;;}
if(__label__==61){var $177=$ov;HEAP32[((__ZZ7WavegenvE3agc)>>2)]=$177;;}
var $178=$z1;var $179=HEAP32[((__ZZ7WavegenvE3agc)>>2)];var $mul245=((($179)*($178))&4294967295);var $shr246=($mul245)>>8;$z=$shr246;;}
else if(__label__==63){var $180=$z;var $cmp248=((($180))|0)<=-32768;if(!($cmp248)){__label__=67;break $if_then239$$if_else247$84;}
var $181=$z1;var $div250=((-8388608/((($181))|0))|0);var $sub251=((($div250)-1)&4294967295);$ov=$sub251;var $182=$ov;var $183=HEAP32[((__ZZ7WavegenvE3agc)>>2)];var $cmp252=((($182))|0)<((($183))|0);if($cmp252){__label__=65;;}else{__label__=66;;}
if(__label__==65){var $184=$ov;HEAP32[((__ZZ7WavegenvE3agc)>>2)]=$184;;}
var $185=$z1;var $186=HEAP32[((__ZZ7WavegenvE3agc)>>2)];var $mul255=((($186)*($185))&4294967295);var $shr256=($mul255)>>8;$z=$shr256;;}}while(0);var $187=$z;var $conv259=((($187))&255);var $188=HEAP32[((_out_ptr)>>2)];var $incdec_ptr=(($188+1)&4294967295);HEAP32[((_out_ptr)>>2)]=$incdec_ptr;HEAP8[($188)]=$conv259;var $189=$z;var $shr260=($189)>>8;var $conv261=((($shr260))&255);var $190=HEAP32[((_out_ptr)>>2)];var $incdec_ptr262=(($190+1)&4294967295);HEAP32[((_out_ptr)>>2)]=$incdec_ptr262;HEAP8[($190)]=$conv261;var $191=$z;var $conv263=((($191))&65535);var $192=HEAP32[((_echo_head)>>2)];var $inc264=((($192)+1)&4294967295);HEAP32[((_echo_head)>>2)]=$inc264;var $arrayidx265=((_echo_buf+$192*2)&4294967295);HEAP16[(($arrayidx265)>>1)]=$conv263;var $193=HEAP32[((_echo_head)>>2)];var $cmp266=((($193))|0)>=5500;if($cmp266){__label__=68;;}else{__label__=69;;}
if(__label__==68){HEAP32[((_echo_head)>>2)]=0;;}
var $194=HEAPU32[((_out_ptr)>>2)];var $195=HEAPU32[((_out_end)>>2)];var $cmp269=((($194))>>>0)>=((($195))>>>0);if($cmp269){__label__=70;break $for_cond$2;}else{__label__=1;continue $for_cond$2;}}
if(__label__==2){$retval=0;;}
else if(__label__==18){$retval=0;;}
else if(__label__==70){$retval=1;;}
var $196=$retval;;return $196;return null;}
function __ZL17AdvanceParametersv(){;var __label__;var __lastLabel__=null;var $x;var $ix;var $0=HEAP32[((((_wdata+12)&4294967295))>>2)];var $1=HEAP32[((((_wdata+8)&4294967295))>>2)];var $add=((($1)+($0))&4294967295);HEAP32[((((_wdata+8)&4294967295))>>2)]=$add;var $2=HEAP32[((((_wdata+8)&4294967295))>>2)];var $shr=($2)>>8;$ix=$shr;var $cmp=((($shr))|0)>127;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$ix=127;;}
var $3=$ix;var $4=HEAP32[((((_wdata)&4294967295))>>2)];var $arrayidx=(($4+$3)&4294967295);var $5=HEAPU8[($arrayidx)];var $conv=((($5))&255);var $6=HEAP32[((((_wdata+20)&4294967295))>>2)];var $mul=((($conv)*($6))&4294967295);$x=$mul;var $7=$x;var $shr1=($7)>>8;var $8=HEAP32[((((_wdata+16)&4294967295))>>2)];var $add2=((($shr1)+($8))&4294967295);HEAP32[((((_wdata+4)&4294967295))>>2)]=$add2;var $9=HEAP32[((__ZL7amp_inc)>>2)];var $10=HEAP32[((__ZL6amp_ix)>>2)];var $add3=((($10)+($9))&4294967295);HEAP32[((__ZL6amp_ix)>>2)]=$add3;var $11=HEAP32[((__ZZL17AdvanceParametersvE10Flutter_ix)>>2)];var $cmp4=((($11))|0)>=23552;if($cmp4){__label__=3;;}else{__label__=4;;}
if(__label__==3){HEAP32[((__ZZL17AdvanceParametersvE10Flutter_ix)>>2)]=0;;}
var $12=HEAP32[((__ZZL17AdvanceParametersvE10Flutter_ix)>>2)];var $shr7=($12)>>6;var $arrayidx8=((__ZL11Flutter_tab+$shr7)&4294967295);var $13=HEAPU8[($arrayidx8)];var $conv9=((($13))&255);var $sub=((($conv9)-128)&4294967295);var $14=HEAP32[((__ZL11flutter_amp)>>2)];var $mul10=((($sub)*($14))&4294967295);$x=$mul10;var $15=HEAP32[((__ZL11Flutter_inc)>>2)];var $16=HEAP32[((__ZZL17AdvanceParametersvE10Flutter_ix)>>2)];var $add11=((($16)+($15))&4294967295);HEAP32[((__ZZL17AdvanceParametersvE10Flutter_ix)>>2)]=$add11;var $17=$x;var $18=HEAP32[((((_wdata+4)&4294967295))>>2)];var $add12=((($18)+($17))&4294967295);HEAP32[((((_wdata+4)&4294967295))>>2)]=$add12;var $cmp13=((($add12))|0)<102400;if($cmp13){__label__=5;;}else{__label__=6;;}
if(__label__==5){HEAP32[((((_wdata+4)&4294967295))>>2)]=102400;;}
var $19=HEAP32[((__ZL11samplecount)>>2)];var $20=HEAP32[((__ZL17samplecount_start)>>2)];var $cmp16=((($19))|0)==((($20))|0);if($cmp16){__label__=21;;}else{__label__=7;;}
$for_end93$$if_end18$11:do{if(__label__==7){$ix=0;var $21=$ix;var $22=HEAP32[((_wvoice)>>2)];var $n_harmonic_peaks2=(($22+84)&4294967295);var $23=HEAP32[(($n_harmonic_peaks2)>>2)];var $cmp193=((($21))|0)<=((($23))|0);if($cmp193){__lastLabel__=7;__label__=9;;}else{__lastLabel__=7;__label__=8;;}
$for_body$$for_cond60_preheader$13:do{if(__label__==9){while(1){var $24=$ix;var $arrayidx20=((__ZL5peaks+$24*80)&4294967295);var $freq_inc=(($arrayidx20+48)&4294967295);var $25=HEAPF32[(($freq_inc)>>2)];var $26=$ix;var $arrayidx21=((__ZL5peaks+$26*80)&4294967295);var $freq1=(($arrayidx21+16)&4294967295);var $27=HEAPF32[(($freq1)>>2)];var $add22=($27)+($25);HEAPF32[(($freq1)>>2)]=$add22;var $28=$ix;var $arrayidx23=((__ZL5peaks+$28*80)&4294967295);var $freq124=(($arrayidx23+16)&4294967295);var $29=HEAPF32[(($freq124)>>2)];var $conv25=((($29))|0);var $30=$ix;var $arrayidx26=((__ZL5peaks+$30*80)&4294967295);var $freq=(($arrayidx26)&4294967295);HEAP32[(($freq)>>2)]=$conv25;var $31=$ix;var $arrayidx27=((__ZL5peaks+$31*80)&4294967295);var $height_inc=(($arrayidx27+56)&4294967295);var $32=HEAPF32[(($height_inc)>>2)];var $33=$ix;var $arrayidx28=((__ZL5peaks+$33*80)&4294967295);var $height1=(($arrayidx28+24)&4294967295);var $34=HEAPF32[(($height1)>>2)];var $add29=($34)+($32);HEAPF32[(($height1)>>2)]=$add29;var $35=$ix;var $arrayidx30=((__ZL5peaks+$35*80)&4294967295);var $height131=(($arrayidx30+24)&4294967295);var $36=HEAPF32[(($height131)>>2)];var $conv32=((($36))|0);var $37=$ix;var $arrayidx33=((__ZL5peaks+$37*80)&4294967295);var $height=(($arrayidx33+4)&4294967295);HEAP32[(($height)>>2)]=$conv32;var $cmp34=((($conv32))|0)<0;if($cmp34){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $38=$ix;var $arrayidx36=((__ZL5peaks+$38*80)&4294967295);var $height37=(($arrayidx36+4)&4294967295);HEAP32[(($height37)>>2)]=0;;}
var $39=$ix;var $arrayidx39=((__ZL5peaks+$39*80)&4294967295);var $left_inc=(($arrayidx39+64)&4294967295);var $40=HEAPF32[(($left_inc)>>2)];var $41=$ix;var $arrayidx40=((__ZL5peaks+$41*80)&4294967295);var $left1=(($arrayidx40+32)&4294967295);var $42=HEAPF32[(($left1)>>2)];var $add41=($42)+($40);HEAPF32[(($left1)>>2)]=$add41;var $43=$ix;var $arrayidx42=((__ZL5peaks+$43*80)&4294967295);var $left143=(($arrayidx42+32)&4294967295);var $44=HEAPF32[(($left143)>>2)];var $conv44=((($44))|0);var $45=$ix;var $arrayidx45=((__ZL5peaks+$45*80)&4294967295);var $left=(($arrayidx45+8)&4294967295);HEAP32[(($left)>>2)]=$conv44;var $46=$ix;var $cmp46=((($46))|0)<3;var $47=$ix;var $arrayidx48=((__ZL5peaks+$47*80)&4294967295);if($cmp46){__label__=12;;}else{__label__=13;;}
if(__label__==12){var $right_inc=(($arrayidx48+72)&4294967295);var $48=HEAPF32[(($right_inc)>>2)];var $49=$ix;var $arrayidx49=((__ZL5peaks+$49*80)&4294967295);var $right1=(($arrayidx49+40)&4294967295);var $50=HEAPF32[(($right1)>>2)];var $add50=($50)+($48);HEAPF32[(($right1)>>2)]=$add50;var $51=$ix;var $arrayidx51=((__ZL5peaks+$51*80)&4294967295);var $right152=(($arrayidx51+40)&4294967295);var $52=HEAPF32[(($right152)>>2)];var $conv53=((($52))|0);var $53=$ix;var $arrayidx54=((__ZL5peaks+$53*80)&4294967295);var $right=(($arrayidx54+12)&4294967295);HEAP32[(($right)>>2)]=$conv53;;}
else if(__label__==13){var $left56=(($arrayidx48+8)&4294967295);var $54=HEAP32[(($left56)>>2)];var $55=$ix;var $arrayidx57=((__ZL5peaks+$55*80)&4294967295);var $right58=(($arrayidx57+12)&4294967295);HEAP32[(($right58)>>2)]=$54;;}
var $56=$ix;var $inc=((($56)+1)&4294967295);$ix=$inc;var $57=$ix;var $58=HEAP32[((_wvoice)>>2)];var $n_harmonic_peaks=(($58+84)&4294967295);var $59=HEAP32[(($n_harmonic_peaks)>>2)];var $cmp19=((($57))|0)<=((($59))|0);if($cmp19){__lastLabel__=14;__label__=9;continue;}else{__lastLabel__=14;__label__=8;break $for_body$$for_cond60_preheader$13;}}}}while(0);var $_lcssa=__lastLabel__==7?$21:($57);var $cmp611=((($_lcssa))|0)<8;if(!($cmp611)){__label__=21;break $for_end93$$if_end18$11;}
var $_pr=$ix;__lastLabel__=15;;while(1){var $60=__lastLabel__==15?$_pr:($inc92);var $cmp63=((($60))|0)<7;if($cmp63){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $61=$ix;var $arrayidx65=((__ZL5peaks+$61*80)&4294967295);var $freq_inc66=(($arrayidx65+48)&4294967295);var $62=HEAPF32[(($freq_inc66)>>2)];var $63=$ix;var $arrayidx67=((__ZL5peaks+$63*80)&4294967295);var $freq168=(($arrayidx67+16)&4294967295);var $64=HEAPF32[(($freq168)>>2)];var $add69=($64)+($62);HEAPF32[(($freq168)>>2)]=$add69;var $65=$ix;var $arrayidx70=((__ZL5peaks+$65*80)&4294967295);var $freq171=(($arrayidx70+16)&4294967295);var $66=HEAPF32[(($freq171)>>2)];var $conv72=((($66))|0);var $67=$ix;var $arrayidx73=((__ZL5peaks+$67*80)&4294967295);var $freq74=(($arrayidx73)&4294967295);HEAP32[(($freq74)>>2)]=$conv72;;}
var $68=$ix;var $arrayidx76=((__ZL5peaks+$68*80)&4294967295);var $height_inc77=(($arrayidx76+56)&4294967295);var $69=HEAPF32[(($height_inc77)>>2)];var $70=$ix;var $arrayidx78=((__ZL5peaks+$70*80)&4294967295);var $height179=(($arrayidx78+24)&4294967295);var $71=HEAPF32[(($height179)>>2)];var $add80=($71)+($69);HEAPF32[(($height179)>>2)]=$add80;var $72=$ix;var $arrayidx81=((__ZL5peaks+$72*80)&4294967295);var $height182=(($arrayidx81+24)&4294967295);var $73=HEAPF32[(($height182)>>2)];var $conv83=((($73))|0);var $74=$ix;var $arrayidx84=((__ZL5peaks+$74*80)&4294967295);var $height85=(($arrayidx84+4)&4294967295);HEAP32[(($height85)>>2)]=$conv83;var $cmp86=((($conv83))|0)<0;if($cmp86){__label__=19;;}else{__label__=20;;}
if(__label__==19){var $75=$ix;var $arrayidx88=((__ZL5peaks+$75*80)&4294967295);var $height89=(($arrayidx88+4)&4294967295);HEAP32[(($height89)>>2)]=0;;}
var $76=$ix;var $inc92=((($76)+1)&4294967295);$ix=$inc92;var $cmp61=((($inc92))|0)<8;if($cmp61){__lastLabel__=20;__label__=16;continue;}else{__lastLabel__=20;__label__=21;break $for_end93$$if_end18$11;}}}}while(0);;return;return;}
function __ZL9SetBreathv(){;var __label__;var $pk;var $0=HEAP32[((_wvoice)>>2)];var $breath=(($0+272)&4294967295);var $arrayidx=(($breath)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];var $cmp=((($1))|0)==0;if($cmp){__label__=5;;}else{__label__=1;;}
$for_end$$if_end$2:do{if(__label__==1){$pk=1;;while(1){var $2=$pk;var $3=HEAP32[((_wvoice)>>2)];var $breath2=(($3+272)&4294967295);var $arrayidx3=(($breath2+$2*4)&4294967295);var $4=HEAP32[(($arrayidx3)>>2)];var $cmp4=((($4))|0)!=0;if($cmp4){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $5=$pk;var $arrayidx6=((__ZL7rbreath+$5*40)&4294967295);var $6=$pk;var $arrayidx7=((__ZL5peaks+$6*80)&4294967295);var $freq=(($arrayidx7)&4294967295);var $7=HEAP32[(($freq)>>2)];var $shr=($7)>>16;var $8=$pk;var $9=HEAP32[((_wvoice)>>2)];var $breathw=(($9+308)&4294967295);var $arrayidx8=(($breathw+$8*4)&4294967295);var $10=HEAP32[(($arrayidx8)>>2)];__ZL12setresonatorP9RESONATORiii($arrayidx6,$shr,$10,0);;}
var $11=$pk;var $inc=((($11)+1)&4294967295);$pk=$inc;var $cmp1=((($inc))|0)<9;if($cmp1){__label__=2;continue;}else{__label__=5;break $for_end$$if_end$2;}}}}while(0);;return;return;}
function __ZL11ApplyBreathv(){;var __label__;var $value;var $noise;var $ix;var $amp;$value=0;var $call=_rand();var $and=($call)&16383;var $sub=((($and)-8192)&4294967295);$noise=$sub;$ix=1;;while(1){var $0=$ix;var $1=HEAP32[((_wvoice)>>2)];var $breath=(($1+272)&4294967295);var $arrayidx=(($breath+$0*4)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];$amp=$2;var $cmp1=((($2))|0)!=0;if($cmp1){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $3=$ix;var $arrayidx2=((__ZL5peaks+$3*80)&4294967295);var $height=(($arrayidx2+4)&4294967295);var $4=HEAP32[(($height)>>2)];var $shr=($4)>>14;var $5=$amp;var $mul=((($5)*($shr))&4294967295);$amp=$mul;var $6=$ix;var $arrayidx3=((__ZL7rbreath+$6*40)&4294967295);var $7=$noise;var $conv=((($7))|0);var $call4=__ZL9resonatorP9RESONATORd($arrayidx3,$conv);var $8=$amp;var $conv5=((($8))|0);var $mul6=($call4)*($conv5);var $conv7=((($mul6))|0);var $9=$value;var $add=((($conv7)+($9))&4294967295);$value=$add;;}
var $10=$ix;var $inc=((($10)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<9;if($cmp){__label__=1;continue;}else{__label__=4;break;}}
var $11=$value;;return $11;return null;}
function __Z11SetEmbeddedii($control,$value){;var __label__;var __lastLabel__=null;var $control_addr;var $value_addr;var $sign;var $command;$control_addr=$control;$value_addr=$value;$sign=0;var $0=$control_addr;var $and=($0)&31;$command=$and;var $1=$control_addr;var $and1=($1)&96;var $cmp=((($and1))|0)==96;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_else$2:do{if(__label__==1){$sign=-1;;}
else if(__label__==2){var $2=$control_addr;var $and2=($2)&96;var $cmp3=((($and2))|0)==64;if(!($cmp3)){__label__=4;break $if_then$$if_else$2;}
$sign=1;;}}while(0);var $3=$command;var $cmp6=((($3))|0)<15;if($cmp6){__lastLabel__=4;__label__=5;;}else{__lastLabel__=4;__label__=9;;}
if(__label__==5){var $4=$sign;var $cmp8=((($4))|0)==0;var $5=$value_addr;if($cmp8){__label__=6;;}else{__label__=7;;}
if(__label__==6){var $6=$command;var $arrayidx=((_embedded_value+$6*4)&4294967295);HEAP32[(($arrayidx)>>2)]=$5;;}
else if(__label__==7){var $7=$sign;var $mul=((($7)*($5))&4294967295);var $8=$command;var $arrayidx11=((_embedded_value+$8*4)&4294967295);var $9=HEAP32[(($arrayidx11)>>2)];var $add=((($9)+($mul))&4294967295);HEAP32[(($arrayidx11)>>2)]=$add;;}
var $10=$command;var $arrayidx13=((_embedded_value+$10*4)&4294967295);var $11=HEAP32[(($arrayidx13)>>2)];var $12=$command;var $arrayidx14=((__ZL12embedded_max+$12*4)&4294967295);var $13=HEAP32[(($arrayidx14)>>2)];var $call=__ZL13SetWithRange0ii($11,$13);var $14=$command;var $arrayidx15=((_embedded_value+$14*4)&4294967295);HEAP32[(($arrayidx15)>>2)]=$call;var $_pr=$command;__lastLabel__=8;;}
var $15=__lastLabel__==8?$_pr:($3);if($15==6){__label__=10;;}
else if($15==1){__label__=11;;}
else if($15==3){__label__=12;;}
else if($15==13){__label__=13;;}
else if($15==5){__label__=14;;}
else{__label__=15;;}
$sw_epilog$$sw_bb$$sw_bb17$$sw_bb18$$sw_bb20$$sw_bb22$14:do{if(__label__==10){__ZL14WavegenSetEchov();__label__=11;break $sw_epilog$$sw_bb$$sw_bb17$$sw_bb18$$sw_bb20$$sw_bb22$14;}
else if(__label__==12){var $call19=__Z12GetAmplitudev();HEAP32[((__ZL17general_amplitude)>>2)]=$call19;__label__=15;break $sw_epilog$$sw_bb$$sw_bb17$$sw_bb18$$sw_bb20$$sw_bb22$14;}
else if(__label__==13){var $call21=__Z12GetAmplitudev();HEAP32[((__ZL17general_amplitude)>>2)]=$call21;__label__=15;break $sw_epilog$$sw_bb$$sw_bb17$$sw_bb18$$sw_bb20$$sw_bb22$14;}
else if(__label__==14){__ZL14WavegenSetEchov();__label__=15;break $sw_epilog$$sw_bb$$sw_bb17$$sw_bb18$$sw_bb20$$sw_bb22$14;}}while(0);if(__label__==11){__ZL16SetPitchFormantsv();;};return;return;}
function __ZL13SetWithRange0ii($value,$max){;var __label__;var $retval;var $value_addr;var $max_addr;$value_addr=$value;$max_addr=$max;var $0=$value_addr;var $cmp=((($0))|0)<0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $1=$value_addr;var $2=$max_addr;var $cmp1=((($1))|0)>((($2))|0);if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $3=$max_addr;$retval=$3;;}
else if(__label__==4){var $4=$value_addr;$retval=$4;;}}
var $5=$retval;;return $5;return null;}
function __ZL14WavegenSetEchov(){;var __label__;var __lastLabel__=null;var $delay;var $amp;var $0=HEAP32[((_wvoice)>>2)];var $voicing=(($0+92)&4294967295);var $1=HEAP32[(($voicing)>>2)];HEAP32[((__ZL7voicing)>>2)]=$1;var $2=HEAP32[((_wvoice)>>2)];var $echo_delay=(($2+76)&4294967295);var $3=HEAP32[(($echo_delay)>>2)];$delay=$3;var $4=HEAP32[((_wvoice)>>2)];var $echo_amp=(($4+80)&4294967295);var $5=HEAP32[(($echo_amp)>>2)];$amp=$5;var $6=$delay;var $cmp=((($6))|0)>=5500;if($cmp){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=2;;}
if(__label__==1){$delay=5499;var $_pr=$amp;__lastLabel__=1;;}
var $7=__lastLabel__==1?$_pr:($5);var $cmp1=((($7))|0)>100;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){$amp=100;;}
var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=_echo_buf;$stop$=$dest$+11000;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};HEAP32[((_echo_tail)>>2)]=0;var $8=HEAP32[((((_embedded_value+20)&4294967295))>>2)];var $cmp4=((($8))|0)>0;if($cmp4){__label__=5;;}else{__label__=6;;}
$if_end6_thread$$if_end6$8:do{if(__label__==5){var $9=HEAP32[((((_embedded_value+20)&4294967295))>>2)];$amp=$9;$delay=130;;}
else if(__label__==6){var $_pr1=$delay;var $cmp7=((($_pr1))|0)==0;if(!($cmp7)){__label__=8;break $if_end6_thread$$if_end6$8;}
$amp=0;;}}while(0);var $10=$delay;var $11=HEAP32[((_samplerate)>>2)];var $mul=((($11)*($10))&4294967295);var $div=((((($mul))|0)/1000)|0);HEAP32[((_echo_head)>>2)]=$div;var $12=HEAP32[((_echo_head)>>2)];HEAP32[((__ZL11echo_length)>>2)]=$12;var $13=$amp;var $cmp10=((($13))|0)==0;if($cmp10){__lastLabel__=8;__label__=9;;}else{__lastLabel__=8;__label__=10;;}
if(__label__==9){HEAP32[((__ZL11echo_length)>>2)]=0;var $_pr3=$amp;__lastLabel__=9;;}
var $14=__lastLabel__==9?$_pr3:($13);var $cmp13=((($14))|0)>20;if($cmp13){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $15=HEAP32[((_echo_head)>>2)];var $mul15=((($15)*2)&4294967295);HEAP32[((__ZL11echo_length)>>2)]=$mul15;;}
var $16=$amp;HEAP32[((_echo_amp)>>2)]=$16;var $call=__Z12GetAmplitudev();HEAP32[((__ZL17general_amplitude)>>2)]=$call;var $17=HEAP32[((__ZL17general_amplitude)>>2)];var $18=$amp;var $sub=((500-($18))&4294967295);var $mul17=((($sub)*($17))&4294967295);var $div18=((((($mul17))|0)/500)|0);HEAP32[((__ZL17general_amplitude)>>2)]=$div18;;return;return;}
function __ZL16SetPitchFormantsv(){;var __label__;var $ix;var $factor;var $pitch_value;var $0=HEAP32[((((_embedded_value+4)&4294967295))>>2)];$pitch_value=$0;var $cmp=((($0))|0)>101;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$pitch_value=101;;}
var $1=$pitch_value;var $sub=((($1)-50)&4294967295);var $mul=((($sub)*25)&4294967295);var $div=((((($mul))|0)/50)|0);var $add=((($div)+256)&4294967295);$factor=$add;$ix=0;;while(1){var $2=$ix;var $3=HEAP32[((_wvoice)>>2)];var $freq2=(($3+216)&4294967295);var $arrayidx=(($freq2+$2*2)&4294967295);var $4=HEAP16[(($arrayidx)>>1)];var $conv=(tempInt=(($4)),(tempInt>=32768?tempInt-65536:tempInt));var $5=$factor;var $mul2=((($conv)*($5))&4294967295);var $div3=((((($mul2))|0)/256)|0);var $conv4=((($div3))&65535);var $6=$ix;var $7=HEAP32[((_wvoice)>>2)];var $freq=(($7+144)&4294967295);var $arrayidx5=(($freq+$6*2)&4294967295);HEAP16[(($arrayidx5)>>1)]=$conv4;var $8=$ix;var $inc=((($8)+1)&4294967295);$ix=$inc;var $cmp1=((($inc))|0)<=5;if($cmp1){__label__=3;continue;}else{__label__=4;break;}}
var $9=HEAP32[((((_embedded_value+24)&4294967295))>>2)];var $mul6=((($9)*3)&4294967295);$factor=$mul6;var $10=HEAP32[((_wvoice)>>2)];var $height2=(($10+234)&4294967295);var $arrayidx7=(($height2)&4294967295);var $11=HEAP16[(($arrayidx7)>>1)];var $conv8=(tempInt=(($11)),(tempInt>=32768?tempInt-65536:tempInt));var $12=$factor;var $mul9=((($12)*2)&4294967295);var $sub10=((256-($mul9))&4294967295);var $mul11=((($sub10)*($conv8))&4294967295);var $div12=((((($mul11))|0)/256)|0);var $conv13=((($div12))&65535);var $13=HEAP32[((_wvoice)>>2)];var $height=(($13+162)&4294967295);var $arrayidx14=(($height)&4294967295);HEAP16[(($arrayidx14)>>1)]=$conv13;var $14=HEAP32[((_wvoice)>>2)];var $height215=(($14+234)&4294967295);var $arrayidx16=(($height215+2)&4294967295);var $15=HEAP16[(($arrayidx16)>>1)];var $conv17=(tempInt=(($15)),(tempInt>=32768?tempInt-65536:tempInt));var $16=$factor;var $sub18=((256-($16))&4294967295);var $mul19=((($sub18)*($conv17))&4294967295);var $div20=((((($mul19))|0)/256)|0);var $conv21=((($div20))&65535);var $17=HEAP32[((_wvoice)>>2)];var $height22=(($17+162)&4294967295);var $arrayidx23=(($height22+2)&4294967295);HEAP16[(($arrayidx23)>>1)]=$conv21;;return;return;}
function __Z15WavegenSetVoiceP7voice_t($v){;var __label__;var $v_addr;$v_addr=$v;var $0=$v_addr;var $1=$0;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$1;$dest$=((__ZZ15WavegenSetVoiceP7voice_tE2v2)&4294967295);$stop$=$src$+1344;if(($dest$%4)==($src$%4)&&1344>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};HEAP32[((_wvoice)>>2)]=__ZZ15WavegenSetVoiceP7voice_tE2v2;var $2=$v_addr;var $peak_shape=(($2+88)&4294967295);var $3=HEAP32[(($peak_shape)>>2)];var $cmp=((($3))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((__ZL8pk_shape)>>2)]=((_pk_shape1)&4294967295);;}
else if(__label__==2){HEAP32[((__ZL8pk_shape)>>2)]=((__ZL9pk_shape2)&4294967295);;}
var $4=$v_addr;var $consonant_amp=(($4+100)&4294967295);var $5=HEAP32[(($consonant_amp)>>2)];var $mul=((($5)*26)&4294967295);var $div=((((($mul))|0)/100)|0);HEAP32[((__ZL13consonant_amp)>>2)]=$div;var $6=HEAP32[((_samplerate)>>2)];var $cmp1=((($6))|0)<=11000;if($cmp1){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $7=HEAP32[((__ZL13consonant_amp)>>2)];var $mul3=((($7)*2)&4294967295);HEAP32[((__ZL13consonant_amp)>>2)]=$mul3;HEAP8[(__ZL16option_harmonic1_b)]=1;;}
__ZL14WavegenSetEchov();__ZL16SetPitchFormantsv();var $8=HEAP32[((_wvoice)>>2)];var $samplerate=(($8+108)&4294967295);var $9=HEAP32[(($samplerate)>>2)];var $10=HEAP32[((_out_ptr)>>2)];__Z11MarkerEventijiPh(8,0,$9,$10);;return;return;}
function __Z9SetPitch2P7voice_tiiPiS1_($voice,$pitch1,$pitch2,$pitch_base,$pitch_range){;var __label__;var $voice_addr;var $pitch1_addr;var $pitch2_addr;var $pitch_base_addr;var $pitch_range_addr;var $x;var $base;var $range;var $pitch_value;$voice_addr=$voice;$pitch1_addr=$pitch1;$pitch2_addr=$pitch2;$pitch_base_addr=$pitch_base;$pitch_range_addr=$pitch_range;var $0=$pitch1_addr;var $1=$pitch2_addr;var $cmp=((($0))|0)>((($1))|0);if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=$pitch1_addr;$x=$2;var $3=$pitch2_addr;$pitch1_addr=$3;var $4=$x;$pitch2_addr=$4;;}
var $5=HEAP32[((((_embedded_value+4)&4294967295))>>2)];$pitch_value=$5;var $cmp1=((($5))|0)>101;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){$pitch_value=101;;}
var $6=HEAP32[((((_embedded_value+24)&4294967295))>>2)];var $7=$pitch_value;var $sub=((($7)-($6))&4294967295);$pitch_value=$sub;var $cmp4=((($sub))|0)<0;if($cmp4){__label__=5;;}else{__label__=6;;}
if(__label__==5){$pitch_value=0;;}
var $8=$voice_addr;var $pitch_base7=(($8+44)&4294967295);var $9=HEAP32[(($pitch_base7)>>2)];var $10=$pitch_value;var $arrayidx=((_pitch_adjust_tab+$10)&4294967295);var $11=HEAPU8[($arrayidx)];var $conv=((($11))&255);var $mul=((($conv)*($9))&4294967295);var $div=((((($mul))|0)/128)|0);$base=$div;var $12=$voice_addr;var $pitch_range8=(($12+48)&4294967295);var $13=HEAP32[(($pitch_range8)>>2)];var $14=HEAP32[((((_embedded_value+16)&4294967295))>>2)];var $mul9=((($14)*($13))&4294967295);var $div10=((((($mul9))|0)/50)|0);$range=$div10;var $15=$range;var $16=$voice_addr;var $pitch_range11=(($16+48)&4294967295);var $17=HEAP32[(($pitch_range11)>>2)];var $sub12=((($15)-($17))&4294967295);var $mul13=((($sub12)*18)&4294967295);var $18=$base;var $sub14=((($18)-($mul13))&4294967295);$base=$sub14;var $19=$base;var $20=$pitch1_addr;var $21=$range;var $mul15=((($21)*($20))&4294967295);var $div16=((((($mul15))|0)/2)|0);var $add=((($div16)+($19))&4294967295);var $22=$pitch_base_addr;HEAP32[(($22)>>2)]=$add;var $23=$base;var $24=$pitch2_addr;var $25=$range;var $mul17=((($25)*($24))&4294967295);var $div18=((((($mul17))|0)/2)|0);var $26=$pitch_base_addr;var $27=HEAP32[(($26)>>2)];var $_neg=(((-($27)))&4294967295);var $add19=((($div18)+($23))&4294967295);var $sub20=((($add19)+($_neg))&4294967295);var $28=$pitch_range_addr;HEAP32[(($28)>>2)]=$sub20;;return;return;}
function __Z8SetPitchiPhii($length,$env,$pitch1,$pitch2){;var __label__;var $length_addr;var $env_addr;var $pitch1_addr;var $pitch2_addr;$length_addr=$length;$env_addr=$env;$pitch1_addr=$pitch1;$pitch2_addr=$pitch2;var $0=$env_addr;HEAP32[((((_wdata)&4294967295))>>2)]=$0;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((((_wdata)&4294967295))>>2)]=((_env_fall)&4294967295);;}
HEAP32[((((_wdata+8)&4294967295))>>2)]=0;var $1=$length_addr;var $cmp1=((($1))|0)==0;if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){HEAP32[((((_wdata+12)&4294967295))>>2)]=0;;}
else if(__label__==4){var $2=$length_addr;var $div=((2097152/((($2))|0))|0);HEAP32[((((_wdata+12)&4294967295))>>2)]=$div;;}
var $3=HEAP32[((_wvoice)>>2)];var $4=$pitch1_addr;var $5=$pitch2_addr;__Z9SetPitch2P7voice_tiiPiS1_($3,$4,$5,((_wdata+16)&4294967295),((_wdata+20)&4294967295));var $6=HEAP32[((((_wdata)&4294967295))>>2)];var $arrayidx=(($6)&4294967295);var $7=HEAPU8[($arrayidx)];var $conv=((($7))&255);var $8=HEAP32[((((_wdata+20)&4294967295))>>2)];var $mul=((($conv)*($8))&4294967295);var $shr=($mul)>>8;var $9=HEAP32[((((_wdata+16)&4294967295))>>2)];var $add=((($shr)+($9))&4294967295);HEAP32[((((_wdata+4)&4294967295))>>2)]=$add;var $10=HEAP32[((_wvoice)>>2)];var $flutter=(($10+68)&4294967295);var $11=HEAP32[(($flutter)>>2)];HEAP32[((__ZL11flutter_amp)>>2)]=$11;;return;return;}
function __Z8SetSynthiiP7frame_tS0_P7voice_t($length,$modn,$fr1,$fr2,$v){;var __label__;var __lastLabel__=null;var $length_addr;var $modn_addr;var $fr1_addr;var $fr2_addr;var $v_addr;var $ix;var $next;var $length2;var $length4;var $qix;var $cmd;$length_addr=$length;$modn_addr=$modn;$fr1_addr=$fr1;$fr2_addr=$fr2;$v_addr=$v;HEAP8[(__ZL8end_wave_b)]=1;var $0=$modn_addr;var $and=($0)&255;HEAP32[((__ZL15modulation_type)>>2)]=$and;HEAP32[((__ZL12glottal_flag)>>2)]=0;var $1=$modn_addr;var $and1=($1)&1024;var $tobool=((($and1))|0)!=0;if($tobool){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((__ZL12glottal_flag)>>2)]=3;var $2=$modn_addr;var $shr=($2)>>8;var $and2=($shr)&3;var $arrayidx=((__ZZ8SetSynthiiP7frame_tS0_P7voice_tE19glottal_reduce_tab1+$and2*4)&4294967295);var $3=HEAP32[(($arrayidx)>>2)];HEAP32[((__ZL14glottal_reduce)>>2)]=$3;;}
var $4=$modn_addr;var $and3=($4)&2048;var $tobool4=((($and3))|0)!=0;if($tobool4){__label__=3;;}else{__label__=4;;}
if(__label__==3){HEAP32[((__ZL12glottal_flag)>>2)]=4;var $5=$modn_addr;var $shr6=($5)>>8;var $and7=($shr6)&3;var $arrayidx8=((__ZZ8SetSynthiiP7frame_tS0_P7voice_tE19glottal_reduce_tab2+$and7*4)&4294967295);var $6=HEAP32[(($arrayidx8)>>2)];HEAP32[((__ZL14glottal_reduce)>>2)]=$6;;}
var $7=HEAP32[((_wcmdq_head)>>2)];var $add=((($7)+1)&4294967295);$qix=$add;__lastLabel__=4;;$for_cond$8:while(1){var $8=__lastLabel__==11?$inc:($add);var $cmp=((($8))|0)>=160;if($cmp){__label__=6;;}else{__label__=7;;}
if(__label__==6){$qix=0;;}
var $9=$qix;var $10=HEAP32[((_wcmdq_tail)>>2)];var $cmp12=((($9))|0)==((($10))|0);if($cmp12){__label__=12;break $for_cond$8;}
var $11=$qix;var $arrayidx15=((_wcmdq+$11*16)&4294967295);var $arrayidx16=(($arrayidx15)&4294967295);var $12=HEAP32[(($arrayidx16)>>2)];$cmd=$12;var $13=$cmd;var $cmp17=((($13))|0)==3;if($cmp17){__label__=9;break $for_cond$8;}
var $14=$cmd;var $cmp20=((($14))|0)==6;var $15=$cmd;var $cmp21=((($15))|0)==5;var $or_cond=($cmp20)|($cmp21);if($or_cond){__label__=12;break $for_cond$8;}
var $16=$qix;var $inc=((($16)+1)&4294967295);$qix=$inc;__lastLabel__=11;__label__=5;continue $for_cond$8;}
if(__label__==9){HEAP8[(__ZL8end_wave_b)]=0;;}
var $17=$length_addr;var $add24=((($17)+32)&4294967295);var $and25=($add24)&-64;$length2=$and25;var $cmp26=((($and25))|0)==0;if($cmp26){__label__=13;;}else{__label__=14;;}
if(__label__==13){$length2=64;;}
var $18=HEAP32[((__ZL11samplecount)>>2)];HEAP32[((__ZL17samplecount_start)>>2)]=$18;var $19=$length2;var $20=HEAP32[((__ZL8nsamples)>>2)];var $add29=((($20)+($19))&4294967295);HEAP32[((__ZL8nsamples)>>2)]=$add29;var $21=$length2;var $div=((((($21))|0)/4)|0);$length4=$div;var $22=$v_addr;var $freq=(($22+144)&4294967295);var $arrayidx30=(($freq+14)&4294967295);var $23=HEAP16[(($arrayidx30)>>1)];var $conv=(tempInt=(($23)),(tempInt>=32768?tempInt-65536:tempInt));var $mul=((($conv)*7800)&4294967295);var $24=$v_addr;var $freqadd=(($24+198)&4294967295);var $arrayidx31=(($freqadd+14)&4294967295);var $25=HEAP16[(($arrayidx31)>>1)];var $conv32=(tempInt=(($25)),(tempInt>=32768?tempInt-65536:tempInt));var $mul33=((($conv32)*256)&4294967295);var $add34=((($mul33)+($mul))&4294967295);var $shl=($add34)<<8;HEAP32[((((__ZL5peaks+560)&4294967295))>>2)]=$shl;var $26=$v_addr;var $freq35=(($26+144)&4294967295);var $arrayidx36=(($freq35+16)&4294967295);var $27=HEAP16[(($arrayidx36)>>1)];var $conv37=(tempInt=(($27)),(tempInt>=32768?tempInt-65536:tempInt));var $mul38=((($conv37)*9000)&4294967295);var $28=$v_addr;var $freqadd39=(($28+198)&4294967295);var $arrayidx40=(($freqadd39+16)&4294967295);var $29=HEAP16[(($arrayidx40)>>1)];var $conv41=(tempInt=(($29)),(tempInt>=32768?tempInt-65536:tempInt));var $mul42=((($conv41)*256)&4294967295);var $add43=((($mul42)+($mul38))&4294967295);var $shl44=($add43)<<8;HEAP32[((((__ZL5peaks+640)&4294967295))>>2)]=$shl44;$ix=0;__lastLabel__=14;;$for_body$22:while(1){var $30=__lastLabel__==14?0:($inc187);var $cmp47=((($30))|0)<7;if($cmp47){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $31=$ix;var $32=$fr1_addr;var $ffreq=(($32+2)&4294967295);var $arrayidx49=(($ffreq+$31*2)&4294967295);var $33=HEAP16[(($arrayidx49)>>1)];var $conv50=(tempInt=(($33)),(tempInt>=32768?tempInt-65536:tempInt));var $34=$ix;var $35=$v_addr;var $freq51=(($35+144)&4294967295);var $arrayidx52=(($freq51+$34*2)&4294967295);var $36=HEAP16[(($arrayidx52)>>1)];var $conv53=(tempInt=(($36)),(tempInt>=32768?tempInt-65536:tempInt));var $mul54=((($conv53)*($conv50))&4294967295);var $37=$ix;var $38=$v_addr;var $freqadd55=(($38+198)&4294967295);var $arrayidx56=(($freqadd55+$37*2)&4294967295);var $39=HEAP16[(($arrayidx56)>>1)];var $conv57=(tempInt=(($39)),(tempInt>=32768?tempInt-65536:tempInt));var $mul58=((($conv57)*256)&4294967295);var $add59=((($mul58)+($mul54))&4294967295);var $shl60=($add59)<<8;var $conv61=((($shl60))|0);var $40=$ix;var $arrayidx62=((__ZL5peaks+$40*80)&4294967295);var $freq1=(($arrayidx62+16)&4294967295);HEAPF32[(($freq1)>>2)]=$conv61;var $41=$ix;var $arrayidx63=((__ZL5peaks+$41*80)&4294967295);var $freq164=(($arrayidx63+16)&4294967295);var $42=HEAPF32[(($freq164)>>2)];var $conv65=((($42))|0);var $43=$ix;var $arrayidx66=((__ZL5peaks+$43*80)&4294967295);var $freq67=(($arrayidx66)&4294967295);HEAP32[(($freq67)>>2)]=$conv65;var $44=$ix;var $45=$fr2_addr;var $ffreq68=(($45+2)&4294967295);var $arrayidx69=(($ffreq68+$44*2)&4294967295);var $46=HEAP16[(($arrayidx69)>>1)];var $conv70=(tempInt=(($46)),(tempInt>=32768?tempInt-65536:tempInt));var $47=$ix;var $48=$v_addr;var $freq71=(($48+144)&4294967295);var $arrayidx72=(($freq71+$47*2)&4294967295);var $49=HEAP16[(($arrayidx72)>>1)];var $conv73=(tempInt=(($49)),(tempInt>=32768?tempInt-65536:tempInt));var $mul74=((($conv73)*($conv70))&4294967295);var $50=$ix;var $51=$v_addr;var $freqadd75=(($51+198)&4294967295);var $arrayidx76=(($freqadd75+$50*2)&4294967295);var $52=HEAP16[(($arrayidx76)>>1)];var $conv77=(tempInt=(($52)),(tempInt>=32768?tempInt-65536:tempInt));var $mul78=((($conv77)*256)&4294967295);var $add79=((($mul78)+($mul74))&4294967295);var $shl80=($add79)<<8;var $conv81=((($shl80))|0);$next=$conv81;var $53=$next;var $54=$ix;var $arrayidx82=((__ZL5peaks+$54*80)&4294967295);var $freq183=(($arrayidx82+16)&4294967295);var $55=HEAPF32[(($freq183)>>2)];var $sub=($53)-($55);var $mul84=($sub)*16;var $56=$length4;var $conv85=((($56))|0);var $div86=($mul84)/($conv85);var $57=$ix;var $arrayidx87=((__ZL5peaks+$57*80)&4294967295);var $freq_inc=(($arrayidx87+48)&4294967295);HEAPF32[(($freq_inc)>>2)]=$div86;;}
var $58=$ix;var $59=$fr1_addr;var $fheight=(($59+18)&4294967295);var $arrayidx89=(($fheight+$58)&4294967295);var $60=HEAPU8[($arrayidx89)];var $conv90=((($60))&255);var $61=$ix;var $62=$v_addr;var $height=(($62+162)&4294967295);var $arrayidx91=(($height+$61*2)&4294967295);var $63=HEAP16[(($arrayidx91)>>1)];var $conv92=(tempInt=(($63)),(tempInt>=32768?tempInt-65536:tempInt));var $mul93=((($conv90)*64)&4294967295);var $shl94=((($mul93)*($conv92))&4294967295);var $conv95=((($shl94))|0);var $64=$ix;var $arrayidx96=((__ZL5peaks+$64*80)&4294967295);var $height1=(($arrayidx96+24)&4294967295);HEAPF32[(($height1)>>2)]=$conv95;var $65=$ix;var $arrayidx97=((__ZL5peaks+$65*80)&4294967295);var $height198=(($arrayidx97+24)&4294967295);var $66=HEAPF32[(($height198)>>2)];var $conv99=((($66))|0);var $67=$ix;var $arrayidx100=((__ZL5peaks+$67*80)&4294967295);var $height101=(($arrayidx100+4)&4294967295);HEAP32[(($height101)>>2)]=$conv99;var $68=$ix;var $69=$fr2_addr;var $fheight102=(($69+18)&4294967295);var $arrayidx103=(($fheight102+$68)&4294967295);var $70=HEAPU8[($arrayidx103)];var $conv104=((($70))&255);var $71=$ix;var $72=$v_addr;var $height105=(($72+162)&4294967295);var $arrayidx106=(($height105+$71*2)&4294967295);var $73=HEAP16[(($arrayidx106)>>1)];var $conv107=(tempInt=(($73)),(tempInt>=32768?tempInt-65536:tempInt));var $mul108=((($conv104)*64)&4294967295);var $shl109=((($mul108)*($conv107))&4294967295);var $conv110=((($shl109))|0);$next=$conv110;var $74=$next;var $75=$ix;var $arrayidx111=((__ZL5peaks+$75*80)&4294967295);var $height1112=(($arrayidx111+24)&4294967295);var $76=HEAPF32[(($height1112)>>2)];var $sub113=($74)-($76);var $mul114=($sub113)*64;var $77=$length2;var $conv115=((($77))|0);var $div116=($mul114)/($conv115);var $78=$ix;var $arrayidx117=((__ZL5peaks+$78*80)&4294967295);var $height_inc=(($arrayidx117+56)&4294967295);HEAPF32[(($height_inc)>>2)]=$div116;var $79=$ix;var $cmp118=((($79))|0)<=5;if($cmp118){__label__=18;;}else{__label__=22;;}
$land_lhs_true$$for_inc186$27:do{if(__label__==18){var $80=$ix;var $81=HEAP32[((_wvoice)>>2)];var $n_harmonic_peaks=(($81+84)&4294967295);var $82=HEAP32[(($n_harmonic_peaks)>>2)];var $cmp119=((($80))|0)<=((($82))|0);if(!($cmp119)){__label__=22;break $land_lhs_true$$for_inc186$27;}
var $83=$ix;var $84=$fr1_addr;var $fwidth=(($84+26)&4294967295);var $arrayidx121=(($fwidth+$83)&4294967295);var $85=HEAPU8[($arrayidx121)];var $conv122=((($85))&255);var $86=$ix;var $87=$v_addr;var $width=(($87+180)&4294967295);var $arrayidx123=(($width+$86*2)&4294967295);var $88=HEAP16[(($arrayidx123)>>1)];var $conv124=(tempInt=(($88)),(tempInt>=32768?tempInt-65536:tempInt));var $mul125=((($conv122)*1024)&4294967295);var $shl126=((($mul125)*($conv124))&4294967295);var $conv127=((($shl126))|0);var $89=$ix;var $arrayidx128=((__ZL5peaks+$89*80)&4294967295);var $left1=(($arrayidx128+32)&4294967295);HEAPF32[(($left1)>>2)]=$conv127;var $90=$ix;var $arrayidx129=((__ZL5peaks+$90*80)&4294967295);var $left1130=(($arrayidx129+32)&4294967295);var $91=HEAPF32[(($left1130)>>2)];var $conv131=((($91))|0);var $92=$ix;var $arrayidx132=((__ZL5peaks+$92*80)&4294967295);var $left=(($arrayidx132+8)&4294967295);HEAP32[(($left)>>2)]=$conv131;var $93=$ix;var $94=$fr2_addr;var $fwidth133=(($94+26)&4294967295);var $arrayidx134=(($fwidth133+$93)&4294967295);var $95=HEAPU8[($arrayidx134)];var $conv135=((($95))&255);var $96=$ix;var $97=$v_addr;var $width136=(($97+180)&4294967295);var $arrayidx137=(($width136+$96*2)&4294967295);var $98=HEAP16[(($arrayidx137)>>1)];var $conv138=(tempInt=(($98)),(tempInt>=32768?tempInt-65536:tempInt));var $mul139=((($conv135)*1024)&4294967295);var $shl140=((($mul139)*($conv138))&4294967295);var $conv141=((($shl140))|0);$next=$conv141;var $99=$next;var $100=$ix;var $arrayidx142=((__ZL5peaks+$100*80)&4294967295);var $left1143=(($arrayidx142+32)&4294967295);var $101=HEAPF32[(($left1143)>>2)];var $sub144=($99)-($101);var $mul145=($sub144)*64;var $102=$length2;var $conv146=((($102))|0);var $div147=($mul145)/($conv146);var $103=$ix;var $arrayidx148=((__ZL5peaks+$103*80)&4294967295);var $left_inc=(($arrayidx148+64)&4294967295);HEAPF32[(($left_inc)>>2)]=$div147;var $104=$ix;var $cmp149=((($104))|0)<3;var $105=$ix;if($cmp149){__label__=20;;}else{__label__=21;;}
if(__label__==20){var $106=$fr1_addr;var $fright=(($106+32)&4294967295);var $arrayidx151=(($fright+$105)&4294967295);var $107=HEAPU8[($arrayidx151)];var $conv152=((($107))&255);var $108=$ix;var $109=$v_addr;var $width153=(($109+180)&4294967295);var $arrayidx154=(($width153+$108*2)&4294967295);var $110=HEAP16[(($arrayidx154)>>1)];var $conv155=(tempInt=(($110)),(tempInt>=32768?tempInt-65536:tempInt));var $mul156=((($conv152)*1024)&4294967295);var $shl157=((($mul156)*($conv155))&4294967295);var $conv158=((($shl157))|0);var $111=$ix;var $arrayidx159=((__ZL5peaks+$111*80)&4294967295);var $right1=(($arrayidx159+40)&4294967295);HEAPF32[(($right1)>>2)]=$conv158;var $112=$ix;var $arrayidx160=((__ZL5peaks+$112*80)&4294967295);var $right1161=(($arrayidx160+40)&4294967295);var $113=HEAPF32[(($right1161)>>2)];var $conv162=((($113))|0);var $114=$ix;var $arrayidx163=((__ZL5peaks+$114*80)&4294967295);var $right=(($arrayidx163+12)&4294967295);HEAP32[(($right)>>2)]=$conv162;var $115=$ix;var $116=$fr2_addr;var $fright164=(($116+32)&4294967295);var $arrayidx165=(($fright164+$115)&4294967295);var $117=HEAPU8[($arrayidx165)];var $conv166=((($117))&255);var $118=$ix;var $119=$v_addr;var $width167=(($119+180)&4294967295);var $arrayidx168=(($width167+$118*2)&4294967295);var $120=HEAP16[(($arrayidx168)>>1)];var $conv169=(tempInt=(($120)),(tempInt>=32768?tempInt-65536:tempInt));var $mul170=((($conv166)*1024)&4294967295);var $shl171=((($mul170)*($conv169))&4294967295);var $conv172=((($shl171))|0);$next=$conv172;var $121=$next;var $122=$ix;var $arrayidx173=((__ZL5peaks+$122*80)&4294967295);var $right1174=(($arrayidx173+40)&4294967295);var $123=HEAPF32[(($right1174)>>2)];var $sub175=($121)-($123);var $mul176=($sub175)*64;var $124=$length2;var $conv177=((($124))|0);var $div178=($mul176)/($conv177);var $125=$ix;var $arrayidx179=((__ZL5peaks+$125*80)&4294967295);var $right_inc=(($arrayidx179+72)&4294967295);HEAPF32[(($right_inc)>>2)]=$div178;;}
else if(__label__==21){var $arrayidx180=((__ZL5peaks+$105*80)&4294967295);var $left181=(($arrayidx180+8)&4294967295);var $126=HEAP32[(($left181)>>2)];var $127=$ix;var $arrayidx182=((__ZL5peaks+$127*80)&4294967295);var $right183=(($arrayidx182+12)&4294967295);HEAP32[(($right183)>>2)]=$126;;}}}while(0);var $128=$ix;var $inc187=((($128)+1)&4294967295);$ix=$inc187;var $cmp46=((($inc187))|0)<8;if($cmp46){__lastLabel__=22;__label__=15;continue $for_body$22;}else{__lastLabel__=22;__label__=23;break $for_body$22;}};return;return;}
function __Z11Write4BytesP7__sFILEi($f,$value){;var __label__;var $f_addr;var $value_addr;var $ix;$f_addr=$f;$value_addr=$value;$ix=0;;while(1){var $0=$value_addr;var $and=($0)&255;var $1=$f_addr;var $call=_fputc($and,$1);var $2=$value_addr;var $shr=($2)>>8;$value_addr=$shr;var $3=$ix;var $inc=((($3)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<4;if($cmp){__label__=1;continue;}else{__label__=2;break;}};return;return;}
function __Z12WavegenFill2i($fill_zeros){;var __label__;var __lastLabel__=null;var $retval;var $fill_zeros_addr;var $q;var $length;var $result;$fill_zeros_addr=$fill_zeros;;$while_cond$2:while(1){var $0=HEAPU32[((_out_ptr)>>2)];var $1=HEAPU32[((_out_end)>>2)];var $cmp=((($0))>>>0)<((($1))>>>0);if(!($cmp)){__label__=36;break $while_cond$2;}
var $call=__Z9WcmdqUsedv();var $cmp1=((($call))|0)<=0;if($cmp1){__label__=3;break $while_cond$2;}
$result=0;var $12=HEAP32[((_wcmdq_head)>>2)];var $arrayidx=((_wcmdq+$12*16)&4294967295);var $arraydecay=(($arrayidx)&4294967295);$q=$arraydecay;var $13=$q;var $arrayidx14=(($13+4)&4294967295);var $14=HEAP32[(($arrayidx14)>>2)];$length=$14;var $15=$q;var $arrayidx15=(($15)&4294967295);var $16=HEAP32[(($arrayidx15)>>2)];if($16==9){__label__=11;;}
else if($16==5){__label__=12;;}
else if($16==6){__label__=15;;}
else if($16==7){__label__=16;;}
else if($16==4){__label__=19;;}
else if($16==3){__label__=20;;}
else if($16==2){__label__=21;;}
else if($16==1){__label__=22;;}
else if($16==10){__label__=23;;}
else if($16==8){__label__=25;;}
else if($16==11){__label__=26;;}
else if($16==12){__label__=27;;}
else if($16==13){__label__=28;;}
else if($16==14){__label__=29;;}
else if($16==15){__label__=31;;}
else{__label__=32;;}
$sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6:do{if(__label__==11){var $17=$length;var $18=$q;var $arrayidx16=(($18+8)&4294967295);var $19=HEAP32[(($arrayidx16)>>2)];var $20=($19);var $21=$q;var $arrayidx17=(($21+12)&4294967295);var $22=HEAP32[(($arrayidx17)>>2)];var $shr=($22)>>16;var $23=$q;var $arrayidx18=(($23+12)&4294967295);var $24=HEAP32[(($arrayidx18)>>2)];var $and=($24)&65535;__Z8SetPitchiPhii($17,$20,$shr,$and);__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==12){var $25=HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)];var $cmp20=((($25))|0)==0;if($cmp20){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $26=$length;var $27=HEAP32[((__ZZ12WavegenFill2iE13echo_complete)>>2)];var $sub=((($27)-($26))&4294967295);HEAP32[((__ZZ12WavegenFill2iE13echo_complete)>>2)]=$sub;;}
HEAP32[((((_wdata+28)&4294967295))>>2)]=0;HEAP32[((((_wdata+60)&4294967295))>>2)]=100;__Z10KlattReseti(1);var $28=$length;var $29=HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)];var $call23=__ZL11PlaySilenceii($28,$29);$result=$call23;__lastLabel__=14;__label__=33;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==15){var $30=HEAP32[((__ZL11echo_length)>>2)];HEAP32[((__ZZ12WavegenFill2iE13echo_complete)>>2)]=$30;HEAP32[((((_wdata+28)&4294967295))>>2)]=0;__Z10KlattReseti(1);var $31=$length;var $32=HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)];var $33=$q;var $arrayidx25=(($33+8)&4294967295);var $34=HEAP32[(($arrayidx25)>>2)];var $35=($34);var $36=$q;var $arrayidx26=(($36+12)&4294967295);var $37=HEAP32[(($arrayidx26)>>2)];var $and27=($37)&255;var $38=$q;var $arrayidx28=(($38+12)&4294967295);var $39=HEAP32[(($arrayidx28)>>2)];var $shr29=($39)>>8;var $call30=__ZL8PlayWaveiiPhii($31,$32,$35,$and27,$shr29);$result=$call30;__lastLabel__=15;__label__=33;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==16){var $40=$q;var $arrayidx32=(($40+12)&4294967295);var $41=HEAP32[(($arrayidx32)>>2)];var $shr33=($41)>>8;HEAP32[((((_wdata+36)&4294967295))>>2)]=$shr33;var $42=$q;var $arrayidx34=(($42+12)&4294967295);var $43=HEAP32[(($arrayidx34)>>2)];var $and35=($43)&255;HEAP32[((((_wdata+32)&4294967295))>>2)]=$and35;var $44=$length;var $and36=($44)&65535;HEAP32[((((_wdata+28)&4294967295))>>2)]=$and36;var $45=$length;var $shr37=($45)>>16;var $and38=($shr37)&65535;HEAP32[((((_wdata+44)&4294967295))>>2)]=$and38;var $46=HEAP32[((((_wdata+32)&4294967295))>>2)];var $cmp39=((($46))|0)==0;if($cmp39){__label__=17;;}else{__label__=18;;}
if(__label__==17){var $47=HEAP32[((((_wdata+28)&4294967295))>>2)];var $mul=((($47)*2)&4294967295);HEAP32[((((_wdata+28)&4294967295))>>2)]=$mul;var $48=HEAP32[((((_wdata+44)&4294967295))>>2)];var $mul41=((($48)*2)&4294967295);HEAP32[((((_wdata+44)&4294967295))>>2)]=$mul41;;}
HEAP32[((((_wdata+40)&4294967295))>>2)]=0;HEAP32[((((_wdata+48)&4294967295))>>2)]=0;var $49=$q;var $arrayidx43=(($49+8)&4294967295);var $50=HEAP32[(($arrayidx43)>>2)];var $51=($50);HEAP32[((((_wdata+24)&4294967295))>>2)]=$51;__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==19){HEAP32[((((_wdata+28)&4294967295))>>2)]=0;__label__=20;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==21){HEAP32[((((_wdata+28)&4294967295))>>2)]=0;__label__=22;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==23){var $74=$q;var $arrayidx61=(($74+4)&4294967295);var $75=HEAP32[(($arrayidx61)>>2)];var $76=$q;var $arrayidx62=(($76+8)&4294967295);var $77=HEAP32[(($arrayidx62)>>2)];var $78=$q;var $arrayidx63=(($78+12)&4294967295);var $79=HEAP32[(($arrayidx63)>>2)];var $80=HEAP32[((_out_ptr)>>2)];__Z11MarkerEventijiPh($75,$77,$79,$80);var $81=$q;var $arrayidx64=(($81+4)&4294967295);var $82=HEAP32[(($arrayidx64)>>2)];var $cmp65=((($82))|0)==1;if(!($cmp65)){__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
var $83=$q;var $arrayidx67=(($83+8)&4294967295);var $84=HEAP32[(($arrayidx67)>>2)];var $and68=($84)&16777215;HEAP32[((_current_source_index)>>2)]=$and68;__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==25){var $85=$length;var $86=$q;var $arrayidx71=(($86+8)&4294967295);var $87=HEAP32[(($arrayidx71)>>2)];var $88=($87);var $89=$q;var $arrayidx72=(($89+12)&4294967295);var $90=HEAP32[(($arrayidx72)>>2)];__ZL12SetAmplitudeiPhi($85,$88,$90);__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==26){var $91=$q;var $arrayidx74=(($91+4)&4294967295);var $92=HEAP32[(($arrayidx74)>>2)];var $93=($92);__Z15WavegenSetVoiceP7voice_t($93);var $94=$q;var $arrayidx75=(($94+4)&4294967295);var $95=HEAP32[(($arrayidx75)>>2)];var $96=($95);var $97=$96;;__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==27){var $98=$q;var $arrayidx77=(($98+4)&4294967295);var $99=HEAP32[(($arrayidx77)>>2)];var $100=$q;var $arrayidx78=(($100+8)&4294967295);var $101=HEAP32[(($arrayidx78)>>2)];__Z11SetEmbeddedii($99,$101);__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==28){var $102=$length;var $103=HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)];var $call80=__Z10MbrolaFillii($102,$103);$result=$call80;__lastLabel__=28;__label__=33;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==29){var $104=$q;var $arrayidx82=(($104+4)&4294967295);var $105=HEAP32[(($arrayidx82)>>2)];HEAP32[((((_wdata+60)&4294967295))>>2)]=$105;var $cmp83=((($105))|0)==0;if(!($cmp83)){__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
HEAP32[((((_wdata+60)&4294967295))>>2)]=100;__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}
else if(__label__==31){var $106=$q;var $arrayidx87=(($106+4)&4294967295);var $107=HEAP32[(($arrayidx87)>>2)];var $conv=((($107))|0);var $div=($conv)/1024;HEAPF32[((_sonicSpeed)>>2)]=$div;__label__=32;break $sw_epilogthread_pre_split$$sw_bb$$sw_bb19$$sw_bb24$$sw_bb31$$sw_bb44$$sw_bb45$$sw_bb52$$sw_bb53$$sw_bb60$$sw_bb70$$sw_bb73$$sw_bb76$$sw_bb79$$sw_bb81$$sw_bb86$6;}}while(0);if(__label__==32){var $_pr=$result;__lastLabel__=32;;}
else if(__label__==20){var $52=HEAP32[((__ZL11echo_length)>>2)];HEAP32[((__ZZ12WavegenFill2iE13echo_complete)>>2)]=$52;var $53=$length;var $and46=($53)&65535;var $54=$q;var $arrayidx47=(($54+4)&4294967295);var $55=HEAP32[(($arrayidx47)>>2)];var $shr48=($55)>>16;var $56=HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)];var $57=$q;var $arrayidx49=(($57+8)&4294967295);var $58=HEAP32[(($arrayidx49)>>2)];var $59=($58);var $60=$q;var $arrayidx50=(($60+12)&4294967295);var $61=HEAP32[(($arrayidx50)>>2)];var $62=($61);var $call51=__ZL8Wavegen2iiiP7frame_tS0_($and46,$shr48,$56,$59,$62);$result=$call51;__lastLabel__=20;;}
else if(__label__==22){var $63=HEAP32[((__ZL11echo_length)>>2)];HEAP32[((__ZZ12WavegenFill2iE13echo_complete)>>2)]=$63;var $64=$length;var $and54=($64)&65535;var $65=$q;var $arrayidx55=(($65+4)&4294967295);var $66=HEAP32[(($arrayidx55)>>2)];var $shr56=($66)>>16;var $67=HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)];var $68=$q;var $arrayidx57=(($68+8)&4294967295);var $69=HEAP32[(($arrayidx57)>>2)];var $70=($69);var $71=$q;var $arrayidx58=(($71+12)&4294967295);var $72=HEAP32[(($arrayidx58)>>2)];var $73=($72);var $call59=__Z14Wavegen_Klatt2iiiP7frame_tS0_($and54,$shr56,$67,$70,$73);$result=$call59;__lastLabel__=22;;}
var $108=__lastLabel__==32?$_pr:(__lastLabel__==28?$call80:(__lastLabel__==22?$call59:(__lastLabel__==20?$call51:(__lastLabel__==15?$call30:($call23)))));var $cmp88=((($108))|0)==0;if($cmp88){__label__=34;;}else{__label__=35;;}
if(__label__==34){__ZL12WcmdqIncHeadv();HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)]=0;__label__=1;continue $while_cond$2;}
else if(__label__==35){HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)]=1;__label__=1;continue $while_cond$2;}}
$while_end91$$if_then$36:do{if(__label__==36){$retval=0;;}
else if(__label__==3){var $2=HEAP32[((__ZZ12WavegenFill2iE13echo_complete)>>2)];var $cmp2=((($2))|0)>0;if($cmp2){__label__=4;;}else{__label__=6;;}
$if_then3$$if_end7$39:do{if(__label__==4){var $3=HEAP32[((__ZZ12WavegenFill2iE13echo_complete)>>2)];var $4=HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)];var $call4=__ZL11PlaySilenceii($3,$4);HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)]=$call4;var $5=HEAP32[((__ZZ12WavegenFill2iE6resume)>>2)];var $cmp5=((($5))|0)==1;if(!($cmp5)){__label__=6;break $if_then3$$if_end7$39;}
$retval=0;__label__=37;break $while_end91$$if_then$36;}}while(0);var $6=$fill_zeros_addr;var $tobool=((($6))|0)!=0;if($tobool){__label__=7;;}else{__label__=9;;}
$while_cond9_preheader$$if_end12$43:do{if(__label__==7){var $7=HEAPU32[((_out_ptr)>>2)];var $8=HEAPU32[((_out_end)>>2)];var $cmp101=((($7))>>>0)<((($8))>>>0);if(!($cmp101)){__label__=9;break $while_cond9_preheader$$if_end12$43;}
while(1){var $9=HEAP32[((_out_ptr)>>2)];var $incdec_ptr=(($9+1)&4294967295);HEAP32[((_out_ptr)>>2)]=$incdec_ptr;HEAP8[($9)]=0;var $10=HEAPU32[((_out_ptr)>>2)];var $11=HEAPU32[((_out_end)>>2)];var $cmp10=((($10))>>>0)<((($11))>>>0);if($cmp10){__label__=8;continue;}else{__label__=9;break $while_cond9_preheader$$if_end12$43;}}}}while(0);$retval=1;;}}while(0);var $109=$retval;;return $109;return null;}
function __ZL11PlaySilenceii($length,$resume){;var __label__;var __lastLabel__=null;var $retval;var $length_addr;var $resume_addr;var $value;$length_addr=$length;$resume_addr=$resume;$value=0;HEAP32[((__ZL8nsamples)>>2)]=0;HEAP32[((__ZL11samplecount)>>2)]=0;HEAP32[((__ZL9wavephase)>>2)]=2147483647;var $0=$length_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $1=$resume_addr;var $cmp1=((($1))|0)==0;if($cmp1){__label__=3;;}else{__label__=4;;}
$if_then2$$while_condthread_pre_split$5:do{if(__label__==3){var $2=$length_addr;HEAP32[((__ZZL11PlaySilenceiiE9n_samples)>>2)]=$2;__lastLabel__=3;__label__=5;break $if_then2$$while_condthread_pre_split$5;}}while(0);while(1){if(__label__==5){var $3=__lastLabel__==4?$_pr:($2);var $dec=((($3)-1)&4294967295);HEAP32[((__ZZL11PlaySilenceiiE9n_samples)>>2)]=$dec;var $cmp4=((($3))|0)>0;if(!($cmp4)){__label__=12;break;}
var $4=HEAP32[((_echo_tail)>>2)];var $inc=((($4)+1)&4294967295);HEAP32[((_echo_tail)>>2)]=$inc;var $arrayidx=((_echo_buf+$4*2)&4294967295);var $5=HEAP16[(($arrayidx)>>1)];var $conv=(tempInt=(($5)),(tempInt>=32768?tempInt-65536:tempInt));var $6=HEAP32[((_echo_amp)>>2)];var $mul=((($conv)*($6))&4294967295);var $shr=($mul)>>8;$value=$shr;var $7=HEAP32[((_echo_tail)>>2)];var $cmp5=((($7))|0)>=5500;if($cmp5){__label__=7;;}else{__label__=8;;}
if(__label__==7){HEAP32[((_echo_tail)>>2)]=0;;}
var $8=$value;var $conv8=((($8))&255);var $9=HEAP32[((_out_ptr)>>2)];var $incdec_ptr=(($9+1)&4294967295);HEAP32[((_out_ptr)>>2)]=$incdec_ptr;HEAP8[($9)]=$conv8;var $10=$value;var $shr9=($10)>>8;var $conv10=((($shr9))&255);var $11=HEAP32[((_out_ptr)>>2)];var $incdec_ptr11=(($11+1)&4294967295);HEAP32[((_out_ptr)>>2)]=$incdec_ptr11;HEAP8[($11)]=$conv10;var $12=$value;var $conv12=((($12))&65535);var $13=HEAP32[((_echo_head)>>2)];var $inc13=((($13)+1)&4294967295);HEAP32[((_echo_head)>>2)]=$inc13;var $arrayidx14=((_echo_buf+$13*2)&4294967295);HEAP16[(($arrayidx14)>>1)]=$conv12;var $14=HEAP32[((_echo_head)>>2)];var $cmp15=((($14))|0)>=5500;if($cmp15){__label__=9;;}else{__label__=10;;}
if(__label__==9){HEAP32[((_echo_head)>>2)]=0;;}
var $15=HEAPU32[((_out_ptr)>>2)];var $16=HEAPU32[((_out_end)>>2)];var $cmp18=((($15))>>>0)>=((($16))>>>0);if($cmp18){__label__=11;break;}else{__label__=4;continue;}}
else if(__label__==4){var $_pr=HEAP32[((__ZZL11PlaySilenceiiE9n_samples)>>2)];__lastLabel__=4;__label__=5;continue;}}
if(__label__==12){$retval=0;;}
else if(__label__==11){$retval=1;;}}
var $17=$retval;;return $17;return null;}
function __ZL8PlayWaveiiPhii($length,$resume,$data,$scale,$amp){;var __label__;var $retval;var $length_addr;var $resume_addr;var $data_addr;var $scale_addr;var $amp_addr;var $value;var $c;$length_addr=$length;$resume_addr=$resume;$data_addr=$data;$scale_addr=$scale;$amp_addr=$amp;var $0=$resume_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$length_addr;HEAP32[((__ZZL8PlayWaveiiPhiiE9n_samples)>>2)]=$1;HEAP32[((__ZZL8PlayWaveiiPhiiE2ix)>>2)]=0;;}
HEAP32[((__ZL8nsamples)>>2)]=0;HEAP32[((__ZL11samplecount)>>2)]=0;;$while_cond$5:while(1){var $2=HEAP32[((__ZZL8PlayWaveiiPhiiE9n_samples)>>2)];var $dec=((($2)-1)&4294967295);HEAP32[((__ZZL8PlayWaveiiPhiiE9n_samples)>>2)]=$dec;var $cmp1=((($2))|0)>0;if(!($cmp1)){__label__=17;break $while_cond$5;}
var $3=$scale_addr;var $cmp2=((($3))|0)==0;var $4=HEAPU32[((__ZZL8PlayWaveiiPhiiE2ix)>>2)];var $add=((($4)+1)&4294967295);if($cmp2){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $5=$data_addr;var $arrayidx=(($5+$add)&4294967295);var $6=HEAP8[($arrayidx)];$c=$6;var $7=HEAP32[((__ZZL8PlayWaveiiPhiiE2ix)>>2)];var $8=$data_addr;var $arrayidx4=(($8+$7)&4294967295);var $9=HEAPU8[($arrayidx4)];var $conv=((($9))&255);var $10=$c;var $conv5=(tempInt=(($10)),(tempInt>=128?tempInt-256:tempInt));var $mul=((($conv5)*256)&4294967295);var $add6=((($mul)+($conv))&4294967295);$value=$add6;var $11=HEAP32[((__ZZL8PlayWaveiiPhiiE2ix)>>2)];var $add7=((($11)+2)&4294967295);HEAP32[((__ZZL8PlayWaveiiPhiiE2ix)>>2)]=$add7;;}
else if(__label__==6){HEAP32[((__ZZL8PlayWaveiiPhiiE2ix)>>2)]=$add;var $12=$data_addr;var $arrayidx8=(($12+$4)&4294967295);var $13=HEAP8[($arrayidx8)];var $conv9=(tempInt=(($13)),(tempInt>=128?tempInt-256:tempInt));var $14=$scale_addr;var $mul10=((($conv9)*($14))&4294967295);$value=$mul10;;}
var $15=HEAP32[((__ZL13consonant_amp)>>2)];var $16=HEAP32[((__ZL17general_amplitude)>>2)];var $17=$value;var $mul12=((($16)*($15))&4294967295);var $mul13=((($mul12)*($17))&4294967295);$value=$mul13;var $18=$value;var $shr=($18)>>10;$value=$shr;var $19=$value;var $20=$amp_addr;var $mul14=((($20)*($19))&4294967295);var $div=((((($mul14))|0)/32)|0);$value=$div;var $21=HEAP32[((_echo_tail)>>2)];var $inc15=((($21)+1)&4294967295);HEAP32[((_echo_tail)>>2)]=$inc15;var $arrayidx16=((_echo_buf+$21*2)&4294967295);var $22=HEAP16[(($arrayidx16)>>1)];var $conv17=(tempInt=(($22)),(tempInt>=32768?tempInt-65536:tempInt));var $23=HEAP32[((_echo_amp)>>2)];var $mul18=((($conv17)*($23))&4294967295);var $shr19=($mul18)>>8;var $24=$value;var $add20=((($shr19)+($24))&4294967295);$value=$add20;var $cmp21=((($add20))|0)>32767;if($cmp21){__label__=8;;}else{__label__=9;;}
$if_then22$$if_else23$12:do{if(__label__==8){$value=32768;;}
else if(__label__==9){var $25=$value;var $cmp24=((($25))|0)<-32768;if(!($cmp24)){__label__=11;break $if_then22$$if_else23$12;}
$value=-32768;;}}while(0);var $26=HEAP32[((_echo_tail)>>2)];var $cmp28=((($26))|0)>=5500;if($cmp28){__label__=12;;}else{__label__=13;;}
if(__label__==12){HEAP32[((_echo_tail)>>2)]=0;;}
var $27=$value;var $conv31=((($27))&255);var $28=HEAP32[((_out_ptr)>>2)];var $arrayidx32=(($28)&4294967295);HEAP8[($arrayidx32)]=$conv31;var $29=$value;var $shr33=($29)>>8;var $conv34=((($shr33))&255);var $30=HEAP32[((_out_ptr)>>2)];var $arrayidx35=(($30+1)&4294967295);HEAP8[($arrayidx35)]=$conv34;var $31=HEAP32[((_out_ptr)>>2)];var $add_ptr=(($31+2)&4294967295);HEAP32[((_out_ptr)>>2)]=$add_ptr;var $32=$value;var $mul36=((($32)*3)&4294967295);var $div37=((((($mul36))|0)/4)|0);var $conv38=((($div37))&65535);var $33=HEAP32[((_echo_head)>>2)];var $inc39=((($33)+1)&4294967295);HEAP32[((_echo_head)>>2)]=$inc39;var $arrayidx40=((_echo_buf+$33*2)&4294967295);HEAP16[(($arrayidx40)>>1)]=$conv38;var $34=HEAP32[((_echo_head)>>2)];var $cmp41=((($34))|0)>=5500;if($cmp41){__label__=14;;}else{__label__=15;;}
if(__label__==14){HEAP32[((_echo_head)>>2)]=0;;}
var $35=HEAPU32[((_out_ptr)>>2)];var $36=HEAPU32[((_out_end)>>2)];var $cmp44=((($35))>>>0)>=((($36))>>>0);if($cmp44){__label__=16;break $while_cond$5;}else{__label__=3;continue $while_cond$5;}}
if(__label__==17){$retval=0;;}
else if(__label__==16){$retval=1;;}
var $37=$retval;;return $37;return null;}
function __ZL8Wavegen2iiiP7frame_tS0_($length,$modulation,$resume,$fr1,$fr2){;var __label__;var $length_addr;var $modulation_addr;var $resume_addr;var $fr1_addr;var $fr2_addr;$length_addr=$length;$modulation_addr=$modulation;$resume_addr=$resume;$fr1_addr=$fr1;$fr2_addr=$fr2;var $0=$resume_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$length_addr;var $2=$modulation_addr;var $3=$fr1_addr;var $4=$fr2_addr;var $5=HEAP32[((_wvoice)>>2)];__Z8SetSynthiiP7frame_tS0_P7voice_t($1,$2,$3,$4,$5);;}
var $call=__Z7Wavegenv();;return $call;return null;}
function __ZL12SetAmplitudeiPhi($length,$amp_env,$value){;var __label__;var $length_addr;var $amp_env_addr;var $value_addr;$length_addr=$length;$amp_env_addr=$amp_env;$value_addr=$value;HEAP32[((__ZL6amp_ix)>>2)]=0;var $0=$length_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((__ZL7amp_inc)>>2)]=0;;}
else if(__label__==2){var $1=$length_addr;var $div=((2097152/((($1))|0))|0);HEAP32[((__ZL7amp_inc)>>2)]=$div;;}
var $2=$value_addr;var $3=HEAP32[((__ZL17general_amplitude)>>2)];var $mul=((($3)*($2))&4294967295);var $div1=((((($mul))|0)/16)|0);HEAP32[((((_wdata+52)&4294967295))>>2)]=$div1;var $4=HEAP32[((((_wdata+52)&4294967295))>>2)];var $5=HEAP32[((_wvoice)>>2)];var $consonant_ampv=(($5+104)&4294967295);var $6=HEAP32[(($consonant_ampv)>>2)];var $mul2=((($4)*15)&4294967295);var $mul3=((($mul2)*($6))&4294967295);var $div4=((((($mul3))|0)/100)|0);HEAP32[((((_wdata+56)&4294967295))>>2)]=$div4;var $7=$amp_env_addr;HEAP32[((__ZL13amplitude_env)>>2)]=$7;;return;return;}
function __ZL12WcmdqIncHeadv(){;var __label__;var $0=HEAP32[((_wcmdq_head)>>2)];var $inc=((($0)+1)&4294967295);HEAP32[((_wcmdq_head)>>2)]=$inc;var $cmp=((($inc))|0)>=160;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((_wcmdq_head)>>2)]=0;;};return;return;}
function __Z11WavegenFilli($fill_zeros){;var __label__;var $fill_zeros_addr;var $finished;var $p_start;var $length;var $max_length;$fill_zeros_addr=$fill_zeros;var $0=HEAP32[((_out_ptr)>>2)];$p_start=$0;var $call=__Z12WavegenFill2i(0);$finished=$call;var $1=HEAPF32[((_sonicSpeed)>>2)];var $cmp=($1)>1;if($cmp){__label__=1;;}else{__label__=3;;}
$if_then$$if_end8$2:do{if(__label__==1){var $2=HEAP32[((_out_end)>>2)];var $3=$p_start;var $sub_ptr_lhs_cast=($2);var $sub_ptr_rhs_cast=($3);var $sub_ptr_sub=((($sub_ptr_lhs_cast)-($sub_ptr_rhs_cast))&4294967295);$max_length=$sub_ptr_sub;var $4=$p_start;var $5=$4;var $6=HEAP32[((_out_ptr)>>2)];var $7=$p_start;var $sub_ptr_lhs_cast1=($6);var $sub_ptr_rhs_cast2=($7);var $sub_ptr_sub3=((($sub_ptr_lhs_cast1)-($sub_ptr_rhs_cast2))&4294967295);var $div=((((($sub_ptr_sub3))|0)/2)|0);var $8=$max_length;var $div4=((((($8))|0)/2)|0);var $9=$finished;var $call5=__ZL7SpeedUpPsiii($5,$div,$div4,$9);var $mul=((($call5)*2)&4294967295);$length=$mul;var $10=$p_start;var $11=$length;var $add_ptr=(($10+$11)&4294967295);HEAP32[((_out_ptr)>>2)]=$add_ptr;var $12=$length;var $13=$max_length;var $cmp6=((($12))|0)>=((($13))|0);if(!($cmp6)){__label__=3;break $if_then$$if_end8$2;}
$finished=0;;}}while(0);var $14=$finished;;return $14;return null;}
function __ZL7SpeedUpPsiii($outbuf,$length_in,$length_out,$end_of_text){;var __label__;var $retval;var $outbuf_addr;var $length_in_addr;var $length_out_addr;var $end_of_text_addr;$outbuf_addr=$outbuf;$length_in_addr=$length_in;$length_out_addr=$length_out;$end_of_text_addr=$end_of_text;var $0=$length_in_addr;var $cmp=((($0))|0)>0;if($cmp){__label__=1;;}else{__label__=6;;}
if(__label__==1){var $1=HEAP32[((__ZL18sonicSpeedupStream)>>2)];var $cmp1=((($1))|0)==0;if($cmp1){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $call=_sonicCreateStream(22050,1);HEAP32[((__ZL18sonicSpeedupStream)>>2)]=$call;;}
var $2=HEAP32[((__ZL18sonicSpeedupStream)>>2)];var $call3=_sonicGetSpeed($2);var $conv=($call3);var $3=HEAPF32[((_sonicSpeed)>>2)];var $cmp4=($conv)!=($3);if($cmp4){__label__=4;;}else{__label__=5;;}
if(__label__==4){var $4=HEAP32[((__ZL18sonicSpeedupStream)>>2)];var $5=HEAPF32[((_sonicSpeed)>>2)];var $conv6=($5);_sonicSetSpeed($4,$conv6);;}
var $6=HEAP32[((__ZL18sonicSpeedupStream)>>2)];var $7=$outbuf_addr;var $8=$length_in_addr;var $call8=_sonicWriteShortToStream($6,$7,$8);;}
var $9=HEAP32[((__ZL18sonicSpeedupStream)>>2)];var $cmp10=((($9))|0)==0;if($cmp10){__label__=7;;}else{__label__=8;;}
if(__label__==7){$retval=0;;}
else if(__label__==8){var $10=$end_of_text_addr;var $tobool=((($10))|0)!=0;if($tobool){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $11=HEAP32[((__ZL18sonicSpeedupStream)>>2)];var $call14=_sonicFlushStream($11);;}
var $12=HEAP32[((__ZL18sonicSpeedupStream)>>2)];var $13=$outbuf_addr;var $14=$length_out_addr;var $call16=_sonicReadShortFromStream($12,$13,$14);$retval=$call16;;}
var $15=$retval;;return $15;return null;}
function __ZL9resonatorP9RESONATORd($r,$input){;var __label__;var $r_addr;var $input_addr;var $x;$r_addr=$r;$input_addr=$input;var $0=$r_addr;var $a=(($0)&4294967295);var $1=HEAPF32[(($a)>>2)];var $2=$input_addr;var $mul=($1)*($2);var $3=$r_addr;var $b=(($3+8)&4294967295);var $4=HEAPF32[(($b)>>2)];var $5=$r_addr;var $x1=(($5+24)&4294967295);var $6=HEAPF32[(($x1)>>2)];var $mul1=($4)*($6);var $add=($mul)+($mul1);var $7=$r_addr;var $c=(($7+16)&4294967295);var $8=HEAPF32[(($c)>>2)];var $9=$r_addr;var $x2=(($9+32)&4294967295);var $10=HEAPF32[(($x2)>>2)];var $mul2=($8)*($10);var $add3=($add)+($mul2);$x=$add3;var $11=$r_addr;var $x14=(($11+24)&4294967295);var $12=HEAPF32[(($x14)>>2)];var $13=$r_addr;var $x25=(($13+32)&4294967295);HEAPF32[(($x25)>>2)]=$12;var $14=$x;var $15=$r_addr;var $x16=(($15+24)&4294967295);HEAPF32[(($x16)>>2)]=$14;var $16=$x;;return $16;return null;}
function __Z15MakePhonemeListP10Translatorii($tr,$post_pause,$start_sentence){var __stackBase__=STACKTOP;STACKTOP+=24152;_memset(__stackBase__,0,24152);var __label__;var __lastLabel__=null;var $tr_addr;var $post_pause_addr;var $start_sentence_addr;var $ix;var $j;var $insert_ph;var $phlist;var $ph;var $prev;var $next;var $next2;var $unstress_count;var $word_stress;var $switched_language;var $max_stress;var $voicing;var $regression;var $end_sourceix;var $alternative;var $first_vowel;var $phdata=__stackBase__;var $n_ph_list3;var $plist3;var $plist3_inserted;var $ph_list3=__stackBase__+152;var $plist2;var $type;var $word_end_devoice;var $k;var $nextw;var $ph2;var $ph2266;var $p;var $x;$tr_addr=$tr;$post_pause_addr=$post_pause;$start_sentence_addr=$start_sentence;$ix=0;$insert_ph=0;$unstress_count=0;$word_stress=0;$switched_language=0;$first_vowel=0;$plist3_inserted=0;$plist2=((_ph_list2)&4294967295);$phlist=((_phoneme_list)&4294967295);var $0=HEAP32[((_n_ph_list2)>>2)];var $sub=((($0)-1)&4294967295);var $1=$plist2;var $arrayidx=(($1+8*$sub)&4294967295);var $sourceix=(($arrayidx+6)&4294967295);var $2=HEAPU16[(($sourceix)>>1)];var $conv=((($2))&65535);$end_sourceix=$conv;$max_stress=0;var $3=HEAP32[((_n_ph_list2)>>2)];var $sub1=((($3)-3)&4294967295);$j=$sub1;__lastLabel__=0;;$for_cond$2:while(1){var $4=__lastLabel__==5?$dec:($sub1);var $cmp=((($4))|0)>=0;if(!($cmp)){__label__=6;break $for_cond$2;}
var $5=$j;var $6=$plist2;var $arrayidx2=(($6+8*$5)&4294967295);var $stresslevel=(($arrayidx2+1)&4294967295);var $7=HEAPU8[($stresslevel)];var $conv3=((($7))&255);var $and=($conv3)&127;var $8=$max_stress;var $cmp4=((($and))|0)>((($8))|0);if($cmp4){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $9=$j;var $10=$plist2;var $arrayidx5=(($10+8*$9)&4294967295);var $stresslevel6=(($arrayidx5+1)&4294967295);var $11=HEAPU8[($stresslevel6)];var $conv7=((($11))&255);var $and8=($conv7)&127;$max_stress=$and8;;}
var $12=$j;var $13=$plist2;var $arrayidx9=(($13+8*$12)&4294967295);var $sourceix10=(($arrayidx9+6)&4294967295);var $14=HEAPU16[(($sourceix10)>>1)];var $conv11=((($14))&65535);var $cmp12=((($conv11))|0)!=0;if($cmp12){__label__=6;break $for_cond$2;}
var $15=$j;var $dec=((($15)-1)&4294967295);$j=$dec;__lastLabel__=5;__label__=1;continue $for_cond$2;}
var $16=$max_stress;var $cmp15=((($16))|0)<4;if($cmp15){__label__=7;;}else{__label__=11;;}
$while_cond$$if_end32$10:do{if(__label__==7){while(1){var $17=$j;var $dec17=((($17)-1)&4294967295);$j=$dec17;var $cmp18=((($dec17))|0)>=0;if(!($cmp18)){__label__=11;break $while_cond$$if_end32$10;}
var $18=$j;var $19=$plist2;var $arrayidx19=(($19+8*$18)&4294967295);var $synthflags=(($arrayidx19+4)&4294967295);var $20=HEAPU16[(($synthflags)>>1)];var $conv20=((($20))&65535);var $and21=($conv20)&64;var $tobool=((($and21))|0)!=0;var $21=$j;var $22=$plist2;var $arrayidx23=(($22+8*$21)&4294967295);var $stresslevel24=(($arrayidx23+1)&4294967295);if($tobool){__label__=9;break;}
var $23=HEAPU8[($stresslevel24)];var $conv28=((($23))&255);var $cmp29=((($conv28))|0)>=4;if($cmp29){__label__=11;break $while_cond$$if_end32$10;}else{__label__=7;continue;}}
HEAP8[($stresslevel24)]=4;;}}while(0);var $24=$tr_addr;var $langopts=(($24)&4294967295);var $param=(($langopts+24)&4294967295);var $arrayidx33=(($param+16)&4294967295);var $25=HEAP32[(($arrayidx33)>>2)];$regression=$25;var $cmp34=((($25))|0)!=0;if($cmp34){__label__=12;;}else{__label__=51;;}
$if_then35$$if_end143$17:do{if(__label__==12){$word_end_devoice=0;$voicing=0;var $26=HEAP32[((_n_ph_list2)>>2)];var $sub36=((($26)-1)&4294967295);$j=$sub36;var $cmp389=((($sub36))|0)>=0;if(!($cmp389)){__label__=51;break $if_then35$$if_end143$17;}
$for_body39$19:while(1){var $27=$j;var $28=$plist2;var $arrayidx40=(($28+8*$27)&4294967295);var $phcode=(($arrayidx40)&4294967295);var $29=HEAPU8[($phcode)];var $idxprom=((($29))&255);var $arrayidx41=((_phoneme_tab+$idxprom*4)&4294967295);var $30=HEAPU32[(($arrayidx41)>>2)];$ph=$30;var $cmp42=((($30))|0)==0;if($cmp42){__label__=50;;}else{__label__=14;;}
$for_inc140$$if_end44$21:do{if(__label__==14){var $31=$ph;var $code=(($31+10)&4294967295);var $32=HEAPU8[($code)];var $conv45=((($32))&255);var $cmp46=((($conv45))|0)==21;var $33=$switched_language;if($cmp46){__lastLabel__=14;__label__=15;;}else{__lastLabel__=14;__label__=16;;}
if(__label__==15){var $xor=($33)^1;$switched_language=$xor;__lastLabel__=15;;}
var $34=__lastLabel__==15?$xor:($33);var $tobool49=((($34))|0)!=0;if($tobool49){__label__=50;break $for_inc140$$if_end44$21;}
var $35=$ph;var $type52=(($35+11)&4294967295);var $36=HEAPU8[($type52)];var $conv53=((($36))&255);$type=$conv53;var $37=$regression;var $and54=($37)&2;var $tobool55=((($and54))|0)!=0;if($tobool55){__label__=18;;}else{__label__=24;;}
$if_then56$$if_end69$27:do{if(__label__==18){var $38=$ph;var $mnemonic=(($38)&4294967295);var $39=HEAP32[(($mnemonic)>>2)];var $cmp57=((($39))|0)==118;if($cmp57){__label__=21;;}else{__label__=19;;}
$if_then64$$lor_lhs_false$29:do{if(__label__==19){var $40=$ph;var $mnemonic58=(($40)&4294967295);var $41=HEAP32[(($mnemonic58)>>2)];var $cmp59=((($41))|0)==15222;if($cmp59){__label__=21;break $if_then64$$lor_lhs_false$29;}
var $42=$ph;var $mnemonic61=(($42)&4294967295);var $43=HEAP32[(($mnemonic61)>>2)];var $and62=($43)&255;var $cmp63=((($and62))|0)==82;if(!($cmp63)){__label__=24;break $if_then56$$if_end69$27;}}}while(0);var $44=$word_end_devoice;var $cmp65=((($44))|0)==1;if($cmp65){__label__=22;;}else{__label__=23;;}
if(__label__==22){$voicing=0;;}
else if(__label__==23){$type=3;;}}}while(0);var $45=$type;var $cmp70=((($45))|0)==4;var $46=$type;var $cmp72=((($46))|0)==6;var $or_cond=($cmp70)|($cmp72);if($or_cond){__label__=25;;}else{__label__=32;;}
$if_then73$$if_else89$37:do{if(__label__==25){var $47=$voicing;var $cmp74=((($47))|0)==0;if($cmp74){__lastLabel__=25;__label__=26;;}else{__lastLabel__=25;__label__=29;;}
if(__label__==26){var $48=$regression;var $and75=($48)&15;var $tobool76=((($and75))|0)!=0;if($tobool76){__label__=27;;}else{__label__=28;;}
if(__label__==27){$voicing=1;__label__=44;break $if_then73$$if_else89$37;}
else if(__label__==28){var $_pr5=$voicing;__lastLabel__=28;;}}
var $49=__lastLabel__==28?$_pr5:($47);var $cmp79=((($49))|0)==2;if(!($cmp79)){__label__=44;break $if_then73$$if_else89$37;}
var $50=$ph;var $end_type=(($50+13)&4294967295);var $51=HEAPU8[($end_type)];var $conv81=((($51))&255);var $cmp82=((($conv81))|0)!=0;if(!($cmp82)){__label__=44;break $if_then73$$if_else89$37;}
var $52=$ph;var $end_type84=(($52+13)&4294967295);var $53=HEAP8[($end_type84)];var $54=$j;var $55=$plist2;var $arrayidx85=(($55+8*$54)&4294967295);var $phcode86=(($arrayidx85)&4294967295);HEAP8[($phcode86)]=$53;;}
else if(__label__==32){var $56=$type;var $cmp90=((($56))|0)==5;var $57=$type;var $cmp92=((($57))|0)==7;var $or_cond1=($cmp90)|($cmp92);if($or_cond1){__label__=33;;}else{__label__=40;;}
if(__label__==33){var $58=$voicing;var $cmp94=((($58))|0)==0;if($cmp94){__lastLabel__=33;__label__=34;;}else{__lastLabel__=33;__label__=37;;}
if(__label__==34){var $59=$regression;var $and96=($59)&15;var $tobool97=((($and96))|0)!=0;if($tobool97){__label__=35;;}else{__label__=36;;}
if(__label__==35){$voicing=2;__label__=44;break $if_then73$$if_else89$37;}
else if(__label__==36){var $_pr6=$voicing;__lastLabel__=36;;}}
var $60=__lastLabel__==36?$_pr6:($58);var $cmp100=((($60))|0)==1;if(!($cmp100)){__label__=44;break $if_then73$$if_else89$37;}
var $61=$ph;var $end_type102=(($61+13)&4294967295);var $62=HEAPU8[($end_type102)];var $conv103=((($62))&255);var $cmp104=((($conv103))|0)!=0;if(!($cmp104)){__label__=44;break $if_then73$$if_else89$37;}
var $63=$ph;var $end_type106=(($63+13)&4294967295);var $64=HEAP8[($end_type106)];var $65=$j;var $66=$plist2;var $arrayidx107=(($66+8*$65)&4294967295);var $phcode108=(($arrayidx107)&4294967295);HEAP8[($phcode108)]=$64;;}
else if(__label__==40){var $67=$regression;var $and112=($67)&8;var $tobool113=((($and112))|0)!=0;if($tobool113){__label__=41;;}else{__label__=43;;}
if(__label__==41){var $68=$type;var $cmp115=((($68))|0)==0;var $69=$type;var $cmp117=((($69))|0)==2;var $or_cond2=($cmp115)|($cmp117);if(!($or_cond2)){__label__=44;break $if_then73$$if_else89$37;}
$voicing=0;;}
else if(__label__==43){$voicing=0;;}}}}while(0);$word_end_devoice=0;var $70=$j;var $71=$plist2;var $arrayidx124=(($71+8*$70)&4294967295);var $sourceix125=(($arrayidx124+6)&4294967295);var $72=HEAP16[(($sourceix125)>>1)];var $tobool126=(tempInt=(($72)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if(!($tobool126)){__label__=50;break $for_inc140$$if_end44$21;}
var $73=$regression;var $and128=($73)&4;var $tobool129=((($and128))|0)!=0;if($tobool129){__label__=46;;}else{__label__=47;;}
if(__label__==46){$voicing=0;;}
var $74=$regression;var $and132=($74)&16;var $tobool133=((($and132))|0)!=0;if(!($tobool133)){__label__=50;break $for_inc140$$if_end44$21;}
var $75=$voicing;var $cmp135=((($75))|0)==0;if(!($cmp135)){__label__=50;break $for_inc140$$if_end44$21;}
$voicing=1;$word_end_devoice=1;;}}while(0);var $76=$j;var $dec141=((($76)-1)&4294967295);$j=$dec141;var $cmp38=((($dec141))|0)>=0;if($cmp38){__label__=13;continue $for_body39$19;}else{__label__=51;break $if_then35$$if_end143$17;}}}}while(0);var $77=$tr_addr;var $arraydecay=(($ph_list3)&4294967295);var $call=__ZL18SubstitutePhonemesP10TranslatorP12PHONEME_LIST($77,$arraydecay);var $sub144=((($call)-2)&4294967295);$n_ph_list3=$sub144;$j=0;;$for_cond145$72:while(1){var $78=$j;var $79=$n_ph_list3;var $cmp146=((($78))|0)<((($79))|0);if(!($cmp146)){__label__=64;break $for_cond145$72;}
var $80=$ix;var $cmp147=((($80))|0)<997;if(!($cmp147)){__label__=64;break $for_cond145$72;}
var $81=$j;var $arrayidx149=(($ph_list3+$81*24)&4294967295);var $sourceix150=(($arrayidx149+6)&4294967295);var $82=HEAP16[(($sourceix150)>>1)];var $tobool151=(tempInt=(($82)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if($tobool151){__label__=55;;}else{__label__=63;;}
if(__label__==55){$word_stress=0;var $83=$j;$nextw=$83;;$for_cond153$78:while(1){var $84=$nextw;var $85=$n_ph_list3;var $cmp154=((($84))|0)<((($85))|0);if(!($cmp154)){__label__=60;break $for_cond153$78;}
var $86=$nextw;var $arrayidx156=(($ph_list3+$86*24)&4294967295);var $stresslevel157=(($arrayidx156+1)&4294967295);var $87=HEAPU8[($stresslevel157)];var $conv158=((($87))&255);var $88=$word_stress;var $cmp159=((($conv158))|0)>((($88))|0);if($cmp159){__label__=58;;}else{__label__=59;;}
if(__label__==58){var $89=$nextw;var $arrayidx161=(($ph_list3+$89*24)&4294967295);var $stresslevel162=(($arrayidx161+1)&4294967295);var $90=HEAPU8[($stresslevel162)];var $conv163=((($90))&255);$word_stress=$conv163;;}
var $91=$nextw;var $inc=((($91)+1)&4294967295);$nextw=$inc;var $92=$nextw;var $arrayidx165=(($ph_list3+$92*24)&4294967295);var $sourceix166=(($arrayidx165+6)&4294967295);var $93=HEAP16[(($sourceix166)>>1)];var $tobool167=(tempInt=(($93)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if($tobool167){__label__=60;break $for_cond153$78;}else{__label__=56;continue $for_cond153$78;}}
var $94=$j;$k=$94;var $95=$k;var $96=$nextw;var $cmp1728=((($95))|0)<((($96))|0);if($cmp1728){__label__=61;;}else{__label__=62;;}
$for_body173$$for_end178$85:do{if(__label__==61){while(1){var $97=$word_stress;var $conv174=((($97))&255);var $98=$k;var $arrayidx175=(($ph_list3+$98*24)&4294967295);var $wordstress=(($arrayidx175+2)&4294967295);HEAP8[($wordstress)]=$conv174;var $99=$k;var $inc177=((($99)+1)&4294967295);$k=$inc177;var $100=$k;var $101=$nextw;var $cmp172=((($100))|0)<((($101))|0);if($cmp172){__label__=61;continue;}else{__label__=62;break $for_body173$$for_end178$85;}}}}while(0);var $102=$nextw;$j=$102;__label__=52;continue $for_cond145$72;}
else if(__label__==63){var $103=$j;var $inc180=((($103)+1)&4294967295);$j=$inc180;__label__=52;continue $for_cond145$72;}}
var $104=HEAP32[((((_phoneme_tab+36)&4294967295))>>2)];$ph=$104;var $105=$ph;var $arrayidx183=(($ph_list3)&4294967295);var $ph184=(($arrayidx183+8)&4294967295);HEAP32[(($ph184)>>2)]=$105;$switched_language=0;$j=0;var $pd_param=(($phdata+4)&4294967295);var $arrayidx233=(($pd_param+12)&4294967295);var $pd_param262=(($phdata+4)&4294967295);var $arrayidx263=(($pd_param262+4)&4294967295);var $pd_param480=(($phdata+4)&4294967295);var $arrayidx481=(($pd_param480+16)&4294967295);var $pd_param484=(($phdata+4)&4294967295);var $arrayidx485=(($pd_param484+16)&4294967295);var $pd_param537=(($phdata+4)&4294967295);var $arrayidx538=(($pd_param537+40)&4294967295);;$for_cond185$91:while(1){var $106=$insert_ph;var $tobool186=((($106))|0)!=0;if($tobool186){__lastLabel__=65;__label__=69;;}else{__lastLabel__=65;__label__=66;;}
if(__label__==66){var $107=$j;var $108=$n_ph_list3;var $cmp187=((($107))|0)<((($108))|0);if(!($cmp187)){__label__=158;break $for_cond185$91;}
var $109=$ix;var $cmp189=((($109))|0)<997;if(!($cmp189)){__label__=158;break $for_cond185$91;}
var $_pr7=$insert_ph;__lastLabel__=68;;}
var $110=__lastLabel__==68?$_pr7:($106);var $111=$ph;$prev=$111;var $112=$j;var $arrayidx192=(($ph_list3+$112*24)&4294967295);$plist3=$arrayidx192;var $cmp193=((($110))|0)!=0;var $113=$plist3;var $phcode195=(($113)&4294967295);var $114=HEAPU8[($phcode195)];var $idxprom196=((($114))&255);var $arrayidx197=((_phoneme_tab+$idxprom196*4)&4294967295);var $115=HEAP32[(($arrayidx197)>>2)];if($cmp193){__label__=70;;}else{__label__=73;;}
if(__label__==70){$next=$115;var $116=$j;var $dec198=((($116)-1)&4294967295);$j=$dec198;var $117=$j;var $arrayidx199=(($ph_list3+$117*24)&4294967295);$plist3_inserted=$arrayidx199;$plist3=$arrayidx199;var $118=$j;var $cmp200=((($118))|0)>0;if($cmp200){__label__=71;;}else{__label__=72;;}
if(__label__==71){var $119=$plist3;var $arrayidx202=(($119+-24)&4294967295);var $120=$arrayidx202;var $121=$plist3;var $arrayidx203=(($121)&4294967295);var $122=$arrayidx203;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$122;$dest$=$120;$stop$=$src$+24;if(($dest$%4)==($src$%4)&&24>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}
var $123=$plist3;var $arrayidx205=(($123)&4294967295);var $124=$arrayidx205;var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$124;$stop$=$dest$+24;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $125=$insert_ph;var $conv206=((($125))&255);var $126=$plist3;var $phcode207=(($126)&4294967295);HEAP8[($phcode207)]=$conv206;var $127=$insert_ph;var $arrayidx208=((_phoneme_tab+$127*4)&4294967295);var $128=HEAP32[(($arrayidx208)>>2)];$ph=$128;var $129=$ph;var $130=$plist3;var $ph209=(($130+8)&4294967295);HEAP32[(($ph209)>>2)]=$129;$insert_ph=0;;}
else if(__label__==73){$ph=$115;var $131=$ph;var $132=$plist3;var $arrayidx214=(($132)&4294967295);var $ph215=(($arrayidx214+8)&4294967295);HEAP32[(($ph215)>>2)]=$131;var $133=$plist3;var $phcode216=(($133)&4294967295);var $134=HEAPU8[($phcode216)];var $conv217=((($134))&255);var $cmp218=((($conv217))|0)==21;if($cmp218){__label__=74;;}else{__label__=75;;}
if(__label__==74){var $135=$plist3;var $tone_ph=(($135+3)&4294967295);var $136=HEAPU8[($tone_ph)];var $conv220=((($136))&255);__Z18SelectPhonemeTablei($conv220);var $137=$switched_language;var $xor221=($137)^32;$switched_language=$xor221;;}
var $138=$plist3;var $arrayidx223=(($138+24)&4294967295);var $phcode224=(($arrayidx223)&4294967295);var $139=HEAPU8[($phcode224)];var $idxprom225=((($139))&255);var $arrayidx226=((_phoneme_tab+$idxprom225*4)&4294967295);var $140=HEAP32[(($arrayidx226)>>2)];$next=$140;var $141=$next;var $142=$plist3;var $arrayidx227=(($142+24)&4294967295);var $ph228=(($arrayidx227+8)&4294967295);HEAP32[(($ph228)>>2)]=$141;;}
var $143=$ph;var $cmp230=((($143))|0)==0;if($cmp230){__label__=157;;}else{__label__=77;;}
$for_inc584$$if_end232$108:do{if(__label__==77){var $144=$tr_addr;var $145=$plist3;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA($144,256,$145,$phdata);var $146=HEAP32[(($arrayidx233)>>2)];$alternative=$146;var $cmp234=((($146))|0)>0;if($cmp234){__label__=78;;}else{__label__=83;;}
if(__label__==78){var $147=$ph;$ph2=$147;var $148=$plist3;var $phcode236=(($148)&4294967295);var $149=HEAPU8[($phcode236)];var $conv237=((($149))&255);$insert_ph=$conv237;var $150=$alternative;var $arrayidx238=((_phoneme_tab+$150*4)&4294967295);var $151=HEAP32[(($arrayidx238)>>2)];$ph=$151;var $152=$ph;var $153=$plist3;var $ph239=(($153+8)&4294967295);HEAP32[(($ph239)>>2)]=$152;var $154=$alternative;var $conv240=((($154))&255);var $155=$plist3;var $phcode241=(($155)&4294967295);HEAP8[($phcode241)]=$conv240;var $156=$ph;var $type242=(($156+11)&4294967295);var $157=HEAPU8[($type242)];var $conv243=((($157))&255);var $cmp244=((($conv243))|0)==2;var $158=$plist3;var $synthflags246=(($158+4)&4294967295);var $159=HEAPU16[(($synthflags246)>>1)];var $conv247=((($159))&65535);if($cmp244){__label__=79;;}else{__label__=81;;}
$if_then245$$if_else255$112:do{if(__label__==79){var $or=($conv247)|4;var $conv248=((($or))&65535);HEAP16[(($synthflags246)>>1)]=$conv248;var $160=$ph2;var $type249=(($160+11)&4294967295);var $161=HEAPU8[($type249)];var $conv250=((($161))&255);var $cmp251=((($conv250))|0)!=2;if(!($cmp251)){__label__=82;break $if_then245$$if_else255$112;}
var $162=$plist3;var $stresslevel253=(($162+1)&4294967295);HEAP8[($stresslevel253)]=0;;}
else if(__label__==81){var $and258=($conv247)&-5;var $conv259=((($and258))&65535);HEAP16[(($synthflags246)>>1)]=$conv259;;}}while(0);var $163=$tr_addr;var $164=$plist3;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA($163,256,$164,$phdata);;}
var $165=HEAP32[(($arrayidx263)>>2)];$alternative=$165;var $cmp264=((($165))|0)>0;if($cmp264){__label__=84;;}else{__label__=90;;}
if(__label__==84){var $166=$ph;$ph2266=$166;var $167=$alternative;var $arrayidx267=((_phoneme_tab+$167*4)&4294967295);var $168=HEAP32[(($arrayidx267)>>2)];$ph=$168;var $169=$ph;var $170=$plist3;var $ph268=(($170+8)&4294967295);HEAP32[(($ph268)>>2)]=$169;var $171=$alternative;var $conv269=((($171))&255);var $172=$plist3;var $phcode270=(($172)&4294967295);HEAP8[($phcode270)]=$conv269;var $173=$alternative;var $cmp271=((($173))|0)==1;if($cmp271){__label__=157;break $for_inc584$$if_end232$108;}
var $174=$ph;var $type274=(($174+11)&4294967295);var $175=HEAPU8[($type274)];var $conv275=((($175))&255);var $cmp276=((($conv275))|0)==2;var $176=$plist3;var $synthflags278=(($176+4)&4294967295);var $177=HEAPU16[(($synthflags278)>>1)];var $conv279=((($177))&65535);if($cmp276){__label__=86;;}else{__label__=88;;}
$if_then277$$if_else288$121:do{if(__label__==86){var $or280=($conv279)|4;var $conv281=((($or280))&65535);HEAP16[(($synthflags278)>>1)]=$conv281;var $178=$ph2266;var $type282=(($178+11)&4294967295);var $179=HEAPU8[($type282)];var $conv283=((($179))&255);var $cmp284=((($conv283))|0)!=2;if(!($cmp284)){__label__=89;break $if_then277$$if_else288$121;}
var $180=$plist3;var $stresslevel286=(($180+1)&4294967295);HEAP8[($stresslevel286)]=0;;}
else if(__label__==88){var $and291=($conv279)&-5;var $conv292=((($and291))&65535);HEAP16[(($synthflags278)>>1)]=$conv292;;}}while(0);var $181=$tr_addr;var $182=$plist3;__Z16InterpretPhonemeP10TranslatoriP12PHONEME_LISTP12PHONEME_DATA($181,256,$182,$phdata);;}
var $183=$ph;var $type295=(($183+11)&4294967295);var $184=HEAPU8[($type295)];var $conv296=((($184))&255);var $cmp297=((($conv296))|0)==2;if($cmp297){__label__=91;;}else{__label__=110;;}
$if_then298$$if_end362$127:do{if(__label__==91){var $185=$plist3;var $stresslevel299=(($185+1)&4294967295);var $186=HEAPU8[($stresslevel299)];var $conv300=((($186))&255);var $cmp301=((($conv300))|0)<=1;if($cmp301){__label__=92;;}else{__label__=109;;}
if(__label__==92){var $187=$unstress_count;var $inc303=((($187)+1)&4294967295);$unstress_count=$inc303;var $188=$tr_addr;var $langopts304=(($188)&4294967295);var $stress_flags=(($langopts304+12)&4294967295);var $189=HEAP32[(($stress_flags)>>2)];var $and305=($189)&8;var $tobool306=((($and305))|0)!=0;if($tobool306){__label__=93;;}else{__label__=102;;}
if(__label__==93){var $190=$plist3;var $add_ptr=(($190+24)&4294967295);$p=$add_ptr;;while(1){var $191=$p;var $type309=(($191+15)&4294967295);var $192=HEAPU8[($type309)];var $conv310=((($192))&255);var $cmp311=((($conv310))|0)!=0;if(!($cmp311)){__label__=110;break $if_then298$$if_end362$127;}
var $193=$p;var $type313=(($193+15)&4294967295);var $194=HEAPU8[($type313)];var $conv314=((($194))&255);var $cmp315=((($conv314))|0)==2;var $195=$p;if($cmp315){__label__=96;break;}
var $incdec_ptr=(($195+24)&4294967295);$p=$incdec_ptr;__label__=94;continue;}
var $stresslevel317=(($195+1)&4294967295);var $196=HEAPU8[($stresslevel317)];var $conv318=((($196))&255);var $cmp319=((($conv318))|0)<=1;if(!($cmp319)){__label__=110;break $if_then298$$if_end362$127;}
var $197=$plist3;var $wordstress321=(($197+2)&4294967295);var $198=HEAPU8[($wordstress321)];var $conv322=((($198))&255);var $cmp323=((($conv322))|0)<4;if($cmp323){__label__=98;;}else{__label__=99;;}
if(__label__==98){var $199=$plist3;var $stresslevel325=(($199+1)&4294967295);HEAP8[($stresslevel325)]=0;;}
var $200=$p;var $wordstress327=(($200+2)&4294967295);var $201=HEAPU8[($wordstress327)];var $conv328=((($201))&255);var $cmp329=((($conv328))|0)<4;if(!($cmp329)){__label__=110;break $if_then298$$if_end362$127;}
var $202=$p;var $stresslevel331=(($202+1)&4294967295);HEAP8[($stresslevel331)]=0;;}
else if(__label__==102){var $203=$unstress_count;var $cmp338=((($203))|0)>1;if(!($cmp338)){__label__=110;break $if_then298$$if_end362$127;}
var $204=$unstress_count;var $and340=($204)&1;var $cmp341=((($and340))|0)==0;if(!($cmp341)){__label__=110;break $if_then298$$if_end362$127;}
var $205=$tr_addr;var $langopts343=(($205)&4294967295);var $stress_flags344=(($langopts343+12)&4294967295);var $206=HEAP32[(($stress_flags344)>>2)];var $and345=($206)&2;var $tobool346=((($and345))|0)!=0;if($tobool346){__label__=107;;}else{__label__=105;;}
$if_then354$$lor_lhs_false347$146:do{if(__label__==105){var $207=$word_stress;var $cmp348=((($207))|0)>3;if($cmp348){__label__=106;;}else{__label__=108;;}
if(__label__==106){var $208=$plist3;var $add_ptr350=(($208+24)&4294967295);var $sourceix351=(($add_ptr350+6)&4294967295);var $209=HEAPU16[(($sourceix351)>>1)];var $conv352=((($209))&65535);var $cmp353=((($conv352))|0)!=0;if($cmp353){__label__=107;break $if_then354$$lor_lhs_false347$146;}}
var $210=$plist3;var $stresslevel356=(($210+1)&4294967295);HEAP8[($stresslevel356)]=0;__label__=110;break $if_then298$$if_end362$127;}}while(0);$unstress_count=1;;}}
else if(__label__==109){$unstress_count=0;;}}}while(0);var $211=$ph;var $type363=(($211+11)&4294967295);var $212=HEAPU8[($type363)];var $conv364=((($212))&255);var $cmp365=((($conv364))|0)==2;if($cmp365){__label__=111;;}else{__label__=112;;}
if(__label__==111){$first_vowel=0;;}
var $213=$plist3;var $add_ptr368=(($213+24)&4294967295);var $synthflags369=(($add_ptr368+4)&4294967295);var $214=HEAPU16[(($synthflags369)>>1)];var $conv370=((($214))&65535);var $and371=($conv370)&8;var $tobool372=((($and371))|0)!=0;if($tobool372){__label__=113;;}else{__label__=115;;}
$if_then373$$if_end387$157:do{if(__label__==113){var $215=$next;var $type374=(($215+11)&4294967295);var $216=HEAPU8[($type374)];var $conv375=((($216))&255);var $call376=_strchr(((__ZZ15MakePhonemeListP10TranslatoriiE12types_double)&4294967295),$conv375);var $tobool377=((($call376))|0)!=0;if(!($tobool377)){__label__=115;break $if_then373$$if_end387$157;}
var $217=$next;var $code379=(($217+10)&4294967295);var $218=HEAPU8[($code379)];var $conv380=((($218))&255);$insert_ph=$conv380;var $219=$plist3;var $add_ptr381=(($219+24)&4294967295);var $synthflags382=(($add_ptr381+4)&4294967295);var $220=HEAPU16[(($synthflags382)>>1)];var $conv383=((($220))&65535);var $xor384=($conv383)^8;var $conv385=((($xor384))&65535);HEAP16[(($synthflags382)>>1)]=$conv385;;}}while(0);var $221=$plist3;var $add_ptr388=(($221+24)&4294967295);var $sourceix389=(($add_ptr388+6)&4294967295);var $222=HEAPU16[(($sourceix389)>>1)];var $conv390=((($222))&65535);var $cmp391=((($conv390))|0)!=0;if($cmp391){__label__=116;;}else{__label__=141;;}
$if_then392$$if_end471$161:do{if(__label__==116){var $223=$tr_addr;var $langopts393=(($223)&4294967295);var $vowel_pause=(($langopts393+4)&4294967295);var $224=HEAP32[(($vowel_pause)>>2)];var $tobool394=((($224))|0)!=0;if($tobool394){__label__=117;;}else{__label__=134;;}
$land_lhs_true395$$if_end450$163:do{if(__label__==117){var $225=$ph;var $type396=(($225+11)&4294967295);var $226=HEAPU8[($type396)];var $conv397=((($226))&255);var $cmp398=((($conv397))|0)!=0;if(!($cmp398)){__label__=134;break $land_lhs_true395$$if_end450$163;}
var $227=$ph;var $type400=(($227+11)&4294967295);var $228=HEAPU8[($type400)];var $conv401=((($228))&255);var $cmp402=((($conv401))|0)!=2;if($cmp402){__label__=119;;}else{__label__=121;;}
$land_lhs_true403$$if_end409$166:do{if(__label__==119){var $229=$tr_addr;var $langopts404=(($229)&4294967295);var $vowel_pause405=(($langopts404+4)&4294967295);var $230=HEAP32[(($vowel_pause405)>>2)];var $and406=($230)&512;var $tobool407=((($and406))|0)!=0;if(!($tobool407)){__label__=121;break $land_lhs_true403$$if_end409$166;}
$insert_ph=11;;}}while(0);var $231=$next;var $type410=(($231+11)&4294967295);var $232=HEAPU8[($type410)];var $conv411=((($232))&255);var $cmp412=((($conv411))|0)==2;if(!($cmp412)){__label__=134;break $land_lhs_true395$$if_end450$163;}
var $233=$tr_addr;var $langopts414=(($233)&4294967295);var $vowel_pause415=(($langopts414+4)&4294967295);var $234=HEAP32[(($vowel_pause415)>>2)];var $and416=($234)&12;$x=$and416;var $cmp417=((($and416))|0)!=0;if($cmp417){__label__=123;;}else{__label__=126;;}
if(__label__==123){var $235=$x;var $cmp419=((($235))|0)==12;if($cmp419){__label__=124;;}else{__label__=125;;}
if(__label__==124){$insert_ph=11;;}
else if(__label__==125){$insert_ph=23;;}}
var $236=$ph;var $type424=(($236+11)&4294967295);var $237=HEAPU8[($type424)];var $conv425=((($237))&255);var $cmp426=((($conv425))|0)==2;if($cmp426){__label__=127;;}else{__label__=131;;}
$land_lhs_true427$$if_end437$177:do{if(__label__==127){var $238=$tr_addr;var $langopts428=(($238)&4294967295);var $vowel_pause429=(($langopts428+4)&4294967295);var $239=HEAP32[(($vowel_pause429)>>2)];var $and430=($239)&3;$x=$and430;var $cmp431=((($and430))|0)!=0;if(!($cmp431)){__label__=131;break $land_lhs_true427$$if_end437$177;}
var $240=$x;var $cmp433=((($240))|0)==2;if($cmp433){__label__=129;;}else{__label__=130;;}
if(__label__==129){$insert_ph=10;;}
else if(__label__==130){$insert_ph=23;;}}}while(0);var $241=$plist3;var $add_ptr438=(($241+24)&4294967295);var $stresslevel439=(($add_ptr438+1)&4294967295);var $242=HEAPU8[($stresslevel439)];var $conv440=((($242))&255);var $cmp441=((($conv440))|0)>=4;if(!($cmp441)){__label__=134;break $land_lhs_true395$$if_end450$163;}
var $243=$tr_addr;var $langopts443=(($243)&4294967295);var $vowel_pause444=(($langopts443+4)&4294967295);var $244=HEAP32[(($vowel_pause444)>>2)];var $and445=($244)&256;var $tobool446=((($and445))|0)!=0;if(!($tobool446)){__label__=134;break $land_lhs_true395$$if_end450$163;}
$insert_ph=10;;}}while(0);var $245=$plist3;var $246=$plist3_inserted;var $cmp451=((($245))|0)!=((($246))|0);if(!($cmp451)){__label__=141;break $if_then392$$if_end471$161;}
var $247=$tr_addr;var $langopts453=(($247)&4294967295);var $word_gap=(($langopts453)&4294967295);var $248=HEAP32[(($word_gap)>>2)];var $and454=($248)&7;$x=$and454;var $cmp455=((($and454))|0)!=0;if($cmp455){__label__=136;;}else{__label__=139;;}
$if_then456$$if_end466$188:do{if(__label__==136){var $249=$x;var $cmp457=((($249))|0)>1;if($cmp457){__label__=138;;}else{__label__=137;;}
if(__label__==137){var $250=$insert_ph;var $cmp459=((($250))|0)!=10;var $251=$insert_ph;var $cmp461=((($251))|0)!=11;var $or_cond3=($cmp459)&($cmp461);if(!($or_cond3)){__label__=139;break $if_then456$$if_end466$188;}}
var $252=$x;var $arrayidx463=((_pause_phonemes+$252)&4294967295);var $253=HEAPU8[($arrayidx463)];var $conv464=((($253))&255);$insert_ph=$conv464;;}}while(0);var $254=HEAP32[((_option_wordgap)>>2)];var $cmp467=((($254))|0)>0;if(!($cmp467)){__label__=141;break $if_then392$$if_end471$161;}
$insert_ph=24;;}}while(0);var $255=$plist3;var $arrayidx472=(($255+48)&4294967295);var $phcode473=(($arrayidx472)&4294967295);var $256=HEAPU8[($phcode473)];var $idxprom474=((($256))&255);var $arrayidx475=((_phoneme_tab+$idxprom474*4)&4294967295);var $257=HEAP32[(($arrayidx475)>>2)];$next2=$257;var $258=$next2;var $259=$plist3;var $arrayidx476=(($259+48)&4294967295);var $ph477=(($arrayidx476+8)&4294967295);HEAP32[(($ph477)>>2)]=$258;var $260=$insert_ph;var $cmp478=((($260))|0)==0;if($cmp478){__label__=142;;}else{__label__=144;;}
$land_lhs_true479$$if_end486$196:do{if(__label__==142){var $261=HEAP32[(($arrayidx481)>>2)];var $cmp482=((($261))|0)!=0;if(!($cmp482)){__label__=144;break $land_lhs_true479$$if_end486$196;}
var $262=HEAP32[(($arrayidx485)>>2)];$insert_ph=$262;;}}while(0);var $263=$ph;var $264=$ix;var $265=$phlist;var $arrayidx491=(($265+24*$264)&4294967295);var $ph492=(($arrayidx491+8)&4294967295);HEAP32[(($ph492)>>2)]=$263;var $266=$ph;var $type493=(($266+11)&4294967295);var $267=HEAP8[($type493)];var $268=$ix;var $269=$phlist;var $arrayidx494=(($269+24*$268)&4294967295);var $type495=(($arrayidx494+15)&4294967295);HEAP8[($type495)]=$267;var $270=$ix;var $271=$phlist;var $arrayidx496=(($271+24*$270)&4294967295);var $env=(($arrayidx496+14)&4294967295);HEAP8[($env)]=0;var $272=$plist3;var $synthflags497=(($272+4)&4294967295);var $273=HEAPU16[(($synthflags497)>>1)];var $conv498=((($273))&65535);var $274=$switched_language;var $or499=($conv498)|($274);var $conv500=((($or499))&65535);var $275=$ix;var $276=$phlist;var $arrayidx501=(($276+24*$275)&4294967295);var $synthflags502=(($arrayidx501+4)&4294967295);HEAP16[(($synthflags502)>>1)]=$conv500;var $277=$plist3;var $stresslevel503=(($277+1)&4294967295);var $278=HEAPU8[($stresslevel503)];var $conv504=((($278))&255);var $and505=($conv504)&15;var $conv506=((($and505))&255);var $279=$ix;var $280=$phlist;var $arrayidx507=(($280+24*$279)&4294967295);var $stresslevel508=(($arrayidx507+1)&4294967295);HEAP8[($stresslevel508)]=$conv506;var $281=$plist3;var $wordstress509=(($281+2)&4294967295);var $282=HEAP8[($wordstress509)];var $283=$ix;var $284=$phlist;var $arrayidx510=(($284+24*$283)&4294967295);var $wordstress511=(($arrayidx510+2)&4294967295);HEAP8[($wordstress511)]=$282;var $285=$plist3;var $tone_ph512=(($285+3)&4294967295);var $286=HEAP8[($tone_ph512)];var $287=$ix;var $288=$phlist;var $arrayidx513=(($288+24*$287)&4294967295);var $tone_ph514=(($arrayidx513+3)&4294967295);HEAP8[($tone_ph514)]=$286;var $289=$ix;var $290=$phlist;var $arrayidx515=(($290+24*$289)&4294967295);var $sourceix516=(($arrayidx515+6)&4294967295);HEAP16[(($sourceix516)>>1)]=0;var $291=$ph;var $code517=(($291+10)&4294967295);var $292=HEAP8[($code517)];var $293=$ix;var $294=$phlist;var $arrayidx518=(($294+24*$293)&4294967295);var $phcode519=(($arrayidx518)&4294967295);HEAP8[($phcode519)]=$292;var $295=$plist3;var $sourceix520=(($295+6)&4294967295);var $296=HEAPU16[(($sourceix520)>>1)];var $conv521=((($296))&65535);var $cmp522=((($conv521))|0)!=0;if($cmp522){__label__=145;;}else{__label__=147;;}
$if_then523$$if_else533$200:do{if(__label__==145){var $297=$plist3;var $sourceix524=(($297+6)&4294967295);var $298=HEAP16[(($sourceix524)>>1)];var $299=$ix;var $300=$phlist;var $arrayidx525=(($300+24*$299)&4294967295);var $sourceix526=(($arrayidx525+6)&4294967295);HEAP16[(($sourceix526)>>1)]=$298;var $301=$ix;var $302=$phlist;var $arrayidx527=(($302+24*$301)&4294967295);var $newword=(($arrayidx527+19)&4294967295);HEAP8[($newword)]=1;var $303=$start_sentence_addr;var $tobool528=((($303))|0)!=0;if(!($tobool528)){__label__=148;break $if_then523$$if_else533$200;}
var $304=$ix;var $305=$phlist;var $arrayidx530=(($305+24*$304)&4294967295);var $newword531=(($arrayidx530+19)&4294967295);HEAP8[($newword531)]=5;$start_sentence_addr=0;;}
else if(__label__==147){var $306=$ix;var $307=$phlist;var $arrayidx534=(($307+24*$306)&4294967295);var $newword535=(($arrayidx534+19)&4294967295);HEAP8[($newword535)]=0;;}}while(0);var $308=HEAP32[(($arrayidx538)>>2)];var $mul=((($308)*2)&4294967295);var $conv539=((($mul))&65535);var $309=$ix;var $310=$phlist;var $arrayidx540=(($310+24*$309)&4294967295);var $length=(($arrayidx540+12)&4294967295);HEAP16[(($length)>>1)]=$conv539;var $311=$ph;var $code541=(($311+10)&4294967295);var $312=HEAPU8[($code541)];var $conv542=((($312))&255);var $cmp543=((($conv542))|0)==24;var $313=HEAP32[((_option_wordgap)>>2)];var $cmp545=((($313))|0)>0;var $or_cond4=($cmp543)&($cmp545);if($or_cond4){__label__=149;;}else{__label__=150;;}
if(__label__==149){var $314=HEAP32[((((_phoneme_tab+40)&4294967295))>>2)];var $315=$ix;var $316=$phlist;var $arrayidx547=(($316+24*$315)&4294967295);var $ph548=(($arrayidx547+8)&4294967295);HEAP32[(($ph548)>>2)]=$314;var $317=HEAP32[((_option_wordgap)>>2)];var $mul549=((($317)*14)&4294967295);var $conv550=((($mul549))&65535);var $318=$ix;var $319=$phlist;var $arrayidx551=(($319+24*$318)&4294967295);var $length552=(($arrayidx551+12)&4294967295);HEAP16[(($length552)>>1)]=$conv550;;}
var $320=$ph;var $type554=(($320+11)&4294967295);var $321=HEAPU8[($type554)];var $conv555=((($321))&255);var $cmp556=((($conv555))|0)==2;if($cmp556){__label__=155;;}else{__label__=151;;}
$if_then573$$lor_lhs_false557$208:do{if(__label__==151){var $322=$ph;var $type558=(($322+11)&4294967295);var $323=HEAPU8[($type558)];var $conv559=((($323))&255);var $cmp560=((($conv559))|0)==3;if($cmp560){__label__=155;break $if_then573$$lor_lhs_false557$208;}
var $324=$ph;var $type562=(($324+11)&4294967295);var $325=HEAPU8[($type562)];var $conv563=((($325))&255);var $cmp564=((($conv563))|0)==8;if($cmp564){__label__=155;break $if_then573$$lor_lhs_false557$208;}
var $326=$ph;var $type566=(($326+11)&4294967295);var $327=HEAPU8[($type566)];var $conv567=((($327))&255);var $cmp568=((($conv567))|0)==5;if($cmp568){__label__=155;break $if_then573$$lor_lhs_false557$208;}
var $328=$ph;var $type570=(($328+11)&4294967295);var $329=HEAPU8[($type570)];var $conv571=((($329))&255);var $cmp572=((($conv571))|0)==7;if($cmp572){__label__=155;break $if_then573$$lor_lhs_false557$208;}else{__label__=156;break $if_then573$$lor_lhs_false557$208;}}}while(0);if(__label__==155){var $330=$ix;var $331=$phlist;var $arrayidx574=(($331+24*$330)&4294967295);var $length575=(($arrayidx574+12)&4294967295);HEAP16[(($length575)>>1)]=128;var $332=$ix;var $333=$phlist;var $arrayidx576=(($333+24*$332)&4294967295);var $env577=(($arrayidx576+14)&4294967295);HEAP8[($env577)]=0;;}
var $334=$ix;var $335=$phlist;var $arrayidx579=(($335+24*$334)&4294967295);var $prepause=(($arrayidx579+16)&4294967295);HEAP8[($prepause)]=0;var $336=$ix;var $337=$phlist;var $arrayidx580=(($337+24*$336)&4294967295);var $amp=(($arrayidx580+18)&4294967295);HEAP8[($amp)]=20;var $338=$ix;var $339=$phlist;var $arrayidx581=(($339+24*$338)&4294967295);var $pitch1=(($arrayidx581+20)&4294967295);HEAP8[($pitch1)]=-1;var $340=$ix;var $341=$phlist;var $arrayidx582=(($341+24*$340)&4294967295);var $pitch2=(($arrayidx582+21)&4294967295);HEAP8[($pitch2)]=-1;var $342=$ix;var $inc583=((($342)+1)&4294967295);$ix=$inc583;;}}while(0);var $343=$j;var $inc585=((($343)+1)&4294967295);$j=$inc585;__label__=65;continue $for_cond185$91;}
var $344=$ix;var $345=$phlist;var $arrayidx587=(($345+24*$344)&4294967295);var $newword588=(($arrayidx587+19)&4294967295);HEAP8[($newword588)]=2;var $346=$ix;var $347=$phlist;var $arrayidx589=(($347+24*$346)&4294967295);var $phcode590=(($arrayidx589)&4294967295);HEAP8[($phcode590)]=9;var $348=$ix;var $349=$phlist;var $arrayidx591=(($349+24*$348)&4294967295);var $type592=(($arrayidx591+15)&4294967295);HEAP8[($type592)]=0;var $350=$post_pause_addr;var $conv593=((($350))&65535);var $351=$ix;var $352=$phlist;var $arrayidx594=(($352+24*$351)&4294967295);var $length595=(($arrayidx594+12)&4294967295);HEAP16[(($length595)>>1)]=$conv593;var $353=$end_sourceix;var $conv596=((($353))&65535);var $354=$ix;var $355=$phlist;var $arrayidx597=(($355+24*$354)&4294967295);var $sourceix598=(($arrayidx597+6)&4294967295);HEAP16[(($sourceix598)>>1)]=$conv596;var $356=$ix;var $357=$phlist;var $arrayidx599=(($357+24*$356)&4294967295);var $synthflags600=(($arrayidx599+4)&4294967295);HEAP16[(($synthflags600)>>1)]=0;var $358=HEAP32[((((_phoneme_tab+36)&4294967295))>>2)];var $359=$ix;var $inc601=((($359)+1)&4294967295);$ix=$inc601;var $360=$phlist;var $arrayidx602=(($360+24*$359)&4294967295);var $ph603=(($arrayidx602+8)&4294967295);HEAP32[(($ph603)>>2)]=$358;var $361=$ix;var $362=$phlist;var $arrayidx604=(($362+24*$361)&4294967295);var $phcode605=(($arrayidx604)&4294967295);HEAP8[($phcode605)]=9;var $363=$ix;var $364=$phlist;var $arrayidx606=(($364+24*$363)&4294967295);var $type607=(($arrayidx606+15)&4294967295);HEAP8[($type607)]=0;var $365=$ix;var $366=$phlist;var $arrayidx608=(($366+24*$365)&4294967295);var $length609=(($arrayidx608+12)&4294967295);HEAP16[(($length609)>>1)]=0;var $367=$ix;var $368=$phlist;var $arrayidx610=(($368+24*$367)&4294967295);var $sourceix611=(($arrayidx610+6)&4294967295);HEAP16[(($sourceix611)>>1)]=0;var $369=$ix;var $370=$phlist;var $arrayidx612=(($370+24*$369)&4294967295);var $synthflags613=(($arrayidx612+4)&4294967295);HEAP16[(($synthflags613)>>1)]=0;var $371=HEAP32[((((_phoneme_tab+40)&4294967295))>>2)];var $372=$ix;var $inc614=((($372)+1)&4294967295);$ix=$inc614;var $373=$phlist;var $arrayidx615=(($373+24*$372)&4294967295);var $ph616=(($arrayidx615+8)&4294967295);HEAP32[(($ph616)>>2)]=$371;var $374=$ix;HEAP32[((_n_phoneme_list)>>2)]=$374;STACKTOP=__stackBase__;return;return;}
function __ZL18SubstitutePhonemesP10TranslatorP12PHONEME_LIST($tr,$plist_out){;var __label__;var __lastLabel__=null;var $tr_addr;var $plist_out_addr;var $ix;var $k;var $replace_flags;var $n_plist_out;var $word_end;var $switched_language;var $plist2;var $next;$tr_addr=$tr;$plist_out_addr=$plist_out;$n_plist_out=0;$switched_language=0;$next=0;$ix=0;;$for_cond$2:while(1){var $0=$ix;var $1=HEAP32[((_n_ph_list2)>>2)];var $cmp=((($0))|0)<((($1))|0);if(!($cmp)){__label__=26;break $for_cond$2;}
var $2=$n_plist_out;var $cmp1=((($2))|0)<1000;if(!($cmp1)){__label__=26;break $for_cond$2;}
var $3=$ix;var $arrayidx=((_ph_list2+$3*8)&4294967295);$plist2=$arrayidx;var $4=$plist2;var $phcode=(($4)&4294967295);var $5=HEAPU8[($phcode)];var $conv=((($5))&255);var $cmp2=((($conv))|0)==21;var $6=$switched_language;if($cmp2){__lastLabel__=3;__label__=4;;}else{__lastLabel__=3;__label__=5;;}
if(__label__==4){var $xor=($6)^1;$switched_language=$xor;__lastLabel__=4;;}
var $7=__lastLabel__==4?$xor:($6);var $cmp3=((($7))|0)==0;if($cmp3){__label__=6;;}else{__label__=24;;}
$if_then4$$if_end61$9:do{if(__label__==6){var $8=$ix;var $9=HEAP32[((_n_ph_list2)>>2)];var $sub=((($9)-1)&4294967295);var $cmp5=((($8))|0)<((($sub))|0);if($cmp5){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $10=$ix;var $add=((($10)+1)&4294967295);var $arrayidx7=((_ph_list2+$add*8)&4294967295);var $phcode8=(($arrayidx7)&4294967295);var $11=HEAPU8[($phcode8)];var $idxprom=((($11))&255);var $arrayidx9=((_phoneme_tab+$idxprom*4)&4294967295);var $12=HEAP32[(($arrayidx9)>>2)];$next=$12;;}
$word_end=0;var $13=$plist2;var $add_ptr=(($13+8)&4294967295);var $sourceix=(($add_ptr+6)&4294967295);var $14=HEAP16[(($sourceix)>>1)];var $tobool=(tempInt=(($14)),(tempInt>=32768?tempInt-65536:tempInt))!=0;if($tobool){__label__=11;;}else{__label__=9;;}
$if_then14$$lor_lhs_false$14:do{if(__label__==9){var $15=$next;var $cmp11=((($15))|0)!=0;if(!($cmp11)){__label__=12;break $if_then14$$lor_lhs_false$14;}
var $16=$next;var $type=(($16+11)&4294967295);var $17=HEAPU8[($type)];var $conv12=((($17))&255);var $cmp13=((($conv12))|0)==0;if($cmp13){__label__=11;break $if_then14$$lor_lhs_false$14;}else{__label__=12;break $if_then14$$lor_lhs_false$14;}}}while(0);if(__label__==11){$word_end=1;;}
$k=0;;$for_cond16$20:while(1){var $18=$k;var $19=HEAP32[((_n_replace_phonemes)>>2)];var $cmp17=((($18))|0)<((($19))|0);if(!($cmp17)){__label__=23;break $for_cond16$20;}
var $20=$plist2;var $phcode19=(($20)&4294967295);var $21=HEAPU8[($phcode19)];var $conv20=((($21))&255);var $22=$k;var $arrayidx21=((_replace_phonemes+$22*3)&4294967295);var $old_ph=(($arrayidx21)&4294967295);var $23=HEAPU8[($old_ph)];var $conv22=((($23))&255);var $cmp23=((($conv20))|0)==((($conv22))|0);if($cmp23){__label__=15;;}else{__label__=22;;}
$if_then24$$for_inc$23:do{if(__label__==15){var $24=$k;var $arrayidx25=((_replace_phonemes+$24*3)&4294967295);var $type26=(($arrayidx25+2)&4294967295);var $25=HEAP8[($type26)];var $conv27=(tempInt=(($25)),(tempInt>=128?tempInt-256:tempInt));$replace_flags=$conv27;var $26=$replace_flags;var $and=($26)&1;var $tobool28=((($and))|0)!=0;if($tobool28){__label__=16;;}else{__label__=17;;}
if(__label__==16){var $27=$word_end;var $cmp30=((($27))|0)==0;if($cmp30){__label__=22;break $if_then24$$for_inc$23;}}
var $28=$replace_flags;var $and33=($28)&2;var $tobool34=((($and33))|0)!=0;if(!($tobool34)){__label__=19;break $for_cond16$20;}
var $29=$plist2;var $stresslevel=(($29+1)&4294967295);var $30=HEAPU8[($stresslevel)];var $conv36=((($30))&255);var $and37=($conv36)&7;var $cmp38=((($and37))|0)>3;if(!($cmp38)){__label__=19;break $for_cond16$20;}}}while(0);var $41=$k;var $inc=((($41)+1)&4294967295);$k=$inc;__label__=13;continue $for_cond16$20;}
$for_end$$if_end40$30:do{if(__label__==19){var $31=$k;var $arrayidx41=((_replace_phonemes+$31*3)&4294967295);var $new_ph=(($arrayidx41+1)&4294967295);var $32=HEAP8[($new_ph)];var $33=$plist2;var $phcode42=(($33)&4294967295);HEAP8[($phcode42)]=$32;var $34=$plist2;var $stresslevel43=(($34+1)&4294967295);var $35=HEAPU8[($stresslevel43)];var $conv44=((($35))&255);var $cmp45=((($conv44))|0)>1;if(!($cmp45)){__label__=23;break $for_end$$if_end40$30;}
var $36=$plist2;var $phcode47=(($36)&4294967295);var $37=HEAPU8[($phcode47)];var $idxprom48=((($37))&255);var $arrayidx49=((_phoneme_tab+$idxprom48*4)&4294967295);var $38=HEAP32[(($arrayidx49)>>2)];var $phflags=(($38+4)&4294967295);var $39=HEAP32[(($phflags)>>2)];var $and50=($39)&2;var $tobool51=((($and50))|0)!=0;if(!($tobool51)){__label__=23;break $for_end$$if_end40$30;}
var $40=$plist2;var $stresslevel53=(($40+1)&4294967295);HEAP8[($stresslevel53)]=0;;}}while(0);var $42=$plist2;var $phcode56=(($42)&4294967295);var $43=HEAPU8[($phcode56)];var $conv57=((($43))&255);var $cmp58=((($conv57))|0)==0;if($cmp58){__label__=25;break $if_then4$$if_end61$9;}else{__label__=24;break $if_then4$$if_end61$9;}}}while(0);if(__label__==24){var $44=$n_plist_out;var $45=$plist_out_addr;var $arrayidx62=(($45+24*$44)&4294967295);var $46=$arrayidx62;var $47=$plist2;var $48=$47;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$48;$dest$=$46;$stop$=$src$+8;if(($dest$%4)==($src$%4)&&8>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $49=$plist2;var $phcode63=(($49)&4294967295);var $50=HEAPU8[($phcode63)];var $idxprom64=((($50))&255);var $arrayidx65=((_phoneme_tab+$idxprom64*4)&4294967295);var $51=HEAP32[(($arrayidx65)>>2)];var $52=$n_plist_out;var $53=$plist_out_addr;var $arrayidx66=(($53+24*$52)&4294967295);var $ph=(($arrayidx66+8)&4294967295);HEAP32[(($ph)>>2)]=$51;var $54=$n_plist_out;var $55=$plist_out_addr;var $arrayidx67=(($55+24*$54)&4294967295);var $ph68=(($arrayidx67+8)&4294967295);var $56=HEAP32[(($ph68)>>2)];var $type69=(($56+11)&4294967295);var $57=HEAP8[($type69)];var $58=$n_plist_out;var $59=$plist_out_addr;var $arrayidx70=(($59+24*$58)&4294967295);var $type71=(($arrayidx70+15)&4294967295);HEAP8[($type71)]=$57;var $60=$n_plist_out;var $inc72=((($60)+1)&4294967295);$n_plist_out=$inc72;;}
var $61=$ix;var $inc74=((($61)+1)&4294967295);$ix=$inc74;__label__=1;continue $for_cond$2;}
var $62=$n_plist_out;;return $62;return null;}
function __Z10KlattReseti($control){;var __label__;var __lastLabel__=null;var $control_addr;var $r_ix;$control_addr=$control;var $0=$control_addr;var $cmp=((($0))|0)==2;if($cmp){__lastLabel__=0;__label__=1;;}else{__lastLabel__=0;__label__=2;;}
if(__label__==1){var $1=HEAP32[((((__ZL10kt_globals+8)&4294967295))>>2)];var $mul=((($1)*950)&4294967295);var $div=((((($mul))|0)/10000)|0);HEAP32[((((__ZL10kt_globals+12)&4294967295))>>2)]=$div;var $2=HEAP32[((((__ZL10kt_globals+8)&4294967295))>>2)];var $mul1=((($2)*630)&4294967295);var $div2=((((($mul1))|0)/10000)|0);HEAP32[((((__ZL10kt_globals+16)&4294967295))>>2)]=$div2;var $3=HEAP32[((((__ZL10kt_globals+8)&4294967295))>>2)];var $conv=((($3))|0);var $div3=-3.1415927/($conv);HEAPF32[((((__ZL10kt_globals+72)&4294967295))>>2)]=$div3;var $4=HEAPF32[((((__ZL10kt_globals+72)&4294967295))>>2)];var $mul4=-2*($4);HEAPF32[((((__ZL10kt_globals+80)&4294967295))>>2)]=$mul4;var $5=HEAP32[((((__ZL10kt_globals+12)&4294967295))>>2)];var $6=HEAP32[((((__ZL10kt_globals+16)&4294967295))>>2)];__ZL6setabcllP11resonator_t($5,$6,((__ZL10kt_globals+188+1152)&4294967295));var $_pr=$control_addr;__lastLabel__=1;;}
var $7=__lastLabel__==1?$_pr:($0);var $cmp5=((($7))|0)>0;if($cmp5){__label__=3;;}else{__label__=5;;}
$if_then6$$if_end9$5:do{if(__label__==3){HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)]=0;HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)]=0;HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)]=0;HEAP32[((((__ZL10kt_globals+48)&4294967295))>>2)]=0;$r_ix=17;;while(1){var $8=$r_ix;var $arrayidx=((((__ZL10kt_globals+188)&4294967295)+$8*64)&4294967295);var $p1=(($arrayidx+24)&4294967295);HEAPF32[(($p1)>>2)]=0;var $9=$r_ix;var $arrayidx8=((((__ZL10kt_globals+188)&4294967295)+$9*64)&4294967295);var $p2=(($arrayidx8+32)&4294967295);HEAPF32[(($p2)>>2)]=0;var $10=$r_ix;var $inc=((($10)+1)&4294967295);$r_ix=$inc;var $cmp7=((($inc))|0)<20;if($cmp7){__label__=4;continue;}else{__label__=5;break $if_then6$$if_end9$5;}}}}while(0);$r_ix=0;;while(1){var $11=$r_ix;var $arrayidx13=((((__ZL10kt_globals+188)&4294967295)+$11*64)&4294967295);var $p114=(($arrayidx13+24)&4294967295);HEAPF32[(($p114)>>2)]=0;var $12=$r_ix;var $arrayidx15=((((__ZL10kt_globals+188)&4294967295)+$12*64)&4294967295);var $p216=(($arrayidx15+32)&4294967295);HEAPF32[(($p216)>>2)]=0;var $13=$r_ix;var $inc18=((($13)+1)&4294967295);$r_ix=$inc18;var $cmp11=((($inc18))|0)<=16;if($cmp11){__label__=6;continue;}else{__label__=7;break;}};return;return;}
function __ZL6setabcllP11resonator_t($f,$bw,$rp){;var __label__;var $f_addr;var $bw_addr;var $rp_addr;var $r;var $arg;$f_addr=$f;$bw_addr=$bw;$rp_addr=$rp;var $0=HEAPF32[((((__ZL10kt_globals+72)&4294967295))>>2)];var $1=$bw_addr;var $conv=((($1))|0);var $mul=($0)*($conv);$arg=$mul;var $2=$arg;var $call=_exp($2);$r=$call;var $3=$r;var $4=$r;var $mul1=($3)*($4);var $sub=(-($mul1));var $5=$rp_addr;var $c=(($5+16)&4294967295);HEAPF32[(($c)>>2)]=$sub;var $6=HEAPF32[((((__ZL10kt_globals+80)&4294967295))>>2)];var $7=$f_addr;var $conv2=((($7))|0);var $mul3=($6)*($conv2);$arg=$mul3;var $8=$r;var $9=$arg;var $call4=_cos($9);var $mul5=($8)*($call4);var $mul6=($mul5)*2;var $10=$rp_addr;var $b=(($10+8)&4294967295);HEAPF32[(($b)>>2)]=$mul6;var $11=$rp_addr;var $b7=(($11+8)&4294967295);var $12=HEAPF32[(($b7)>>2)];var $sub8=1-($12);var $13=$rp_addr;var $c9=(($13+16)&4294967295);var $14=HEAPF32[(($c9)>>2)];var $sub10=($sub8)-($14);var $15=$rp_addr;var $a=(($15)&4294967295);HEAPF32[(($a)>>2)]=$sub10;;return;return;}
function __Z13Wavegen_Klatti($resume){;var __label__;var $retval;var $resume_addr;var $pk;var $x;var $ix;var $fade;$resume_addr=$resume;var $0=$resume_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){HEAP32[((__ZL12sample_count)>>2)]=0;;}
$while_cond$4:while(1){var $1=HEAP32[((__ZL12sample_count)>>2)];var $2=HEAP32[((__ZL8nsamples802)>>2)];var $cmp1=((($1))|0)<((($2))|0);if(!($cmp1)){__label__=23;break $while_cond$4;}
var $3=HEAP32[((((_wdata+4)&4294967295))>>2)];var $mul=((($3)*10)&4294967295);var $div=((((($mul))|0)/4096)|0);HEAP32[((((__ZL8kt_frame)&4294967295))>>2)]=$div;$ix=0;;$for_body$7:while(1){var $4=$ix;var $arrayidx=((__ZL5peaks801+$4*80)&4294967295);var $freq=(($arrayidx)&4294967295);var $5=HEAP32[(($freq)>>2)];var $6=$ix;var $arrayidx3=((((__ZL8kt_frame+8)&4294967295)+$6*4)&4294967295);HEAP32[(($arrayidx3)>>2)]=$5;var $7=$ix;var $cmp4=((($7))|0)<4;if($cmp4){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $8=$ix;var $arrayidx6=((__ZL5peaks801+$8*80)&4294967295);var $bw=(($arrayidx6+4)&4294967295);var $9=HEAP32[(($bw)>>2)];var $10=$ix;var $arrayidx7=((((__ZL8kt_frame+48)&4294967295)+$10*4)&4294967295);HEAP32[(($arrayidx7)>>2)]=$9;;}
var $11=$ix;var $inc=((($11)+1)&4294967295);$ix=$inc;var $cmp2=((($inc))|0)<6;if($cmp2){__label__=4;continue $for_body$7;}else{__label__=7;break $for_body$7;}}
$ix=1;;$for_body11$13:while(1){var $12=$ix;var $arrayidx12=((((__ZL8kt_frame+88)&4294967295)+$12*4)&4294967295);HEAP32[(($arrayidx12)>>2)]=0;var $13=$ix;var $inc14=((($13)+1)&4294967295);$ix=$inc14;var $cmp10=((($inc14))|0)<7;if($cmp10){__label__=8;continue $for_body11$13;}else{__label__=9;break $for_body11$13;}}
var $14=HEAP32[((((__ZL6klattp)&4294967295))>>2)];HEAP32[((((__ZL8kt_frame+4)&4294967295))>>2)]=$14;var $15=HEAP32[((((__ZL6klattp+24)&4294967295))>>2)];HEAP32[((((__ZL8kt_frame+196)&4294967295))>>2)]=$15;var $16=HEAP32[((((__ZL6klattp+28)&4294967295))>>2)];HEAP32[((((__ZL8kt_frame+184)&4294967295))>>2)]=$16;var $17=HEAP32[((((__ZL6klattp+32)&4294967295))>>2)];HEAP32[((((__ZL8kt_frame+192)&4294967295))>>2)]=$17;var $18=HEAP32[((((__ZL6klattp+12)&4294967295))>>2)];HEAP32[((((__ZL8kt_frame+168)&4294967295))>>2)]=$18;var $19=HEAP32[((((__ZL6klattp+36)&4294967295))>>2)];HEAP32[((((__ZL8kt_frame+176)&4294967295))>>2)]=$19;var $20=HEAP32[((((__ZL6klattp+16)&4294967295))>>2)];HEAP32[((((__ZL8kt_frame+188)&4294967295))>>2)]=$20;var $21=HEAP32[((((__ZL6klattp+8)&4294967295))>>2)];HEAP32[((((__ZL8kt_frame+180)&4294967295))>>2)]=$21;var $22=HEAP32[((((__ZL6klattp+20)&4294967295))>>2)];HEAP32[((((__ZL8kt_frame+172)&4294967295))>>2)]=$22;$pk=0;;$for_body18$16:while(1){var $23=$pk;var $arrayidx19=((__ZL5peaks801+$23*80)&4294967295);var $freq_inc=(($arrayidx19+48)&4294967295);var $24=HEAPF32[(($freq_inc)>>2)];var $25=$pk;var $arrayidx20=((__ZL5peaks801+$25*80)&4294967295);var $freq1=(($arrayidx20+16)&4294967295);var $26=HEAPF32[(($freq1)>>2)];var $add=($26)+($24);HEAPF32[(($freq1)>>2)]=$add;var $27=$pk;var $arrayidx21=((__ZL5peaks801+$27*80)&4294967295);var $freq122=(($arrayidx21+16)&4294967295);var $28=HEAPF32[(($freq122)>>2)];var $conv=((($28))|0);var $29=$pk;var $arrayidx23=((__ZL5peaks801+$29*80)&4294967295);var $freq24=(($arrayidx23)&4294967295);HEAP32[(($freq24)>>2)]=$conv;var $30=$pk;var $arrayidx25=((__ZL5peaks801+$30*80)&4294967295);var $bw_inc=(($arrayidx25+56)&4294967295);var $31=HEAPF32[(($bw_inc)>>2)];var $32=$pk;var $arrayidx26=((__ZL5peaks801+$32*80)&4294967295);var $bw1=(($arrayidx26+24)&4294967295);var $33=HEAPF32[(($bw1)>>2)];var $add27=($33)+($31);HEAPF32[(($bw1)>>2)]=$add27;var $34=$pk;var $arrayidx28=((__ZL5peaks801+$34*80)&4294967295);var $bw129=(($arrayidx28+24)&4294967295);var $35=HEAPF32[(($bw129)>>2)];var $conv30=((($35))|0);var $36=$pk;var $arrayidx31=((__ZL5peaks801+$36*80)&4294967295);var $bw32=(($arrayidx31+4)&4294967295);HEAP32[(($bw32)>>2)]=$conv30;var $37=$pk;var $arrayidx33=((__ZL5peaks801+$37*80)&4294967295);var $bp_inc=(($arrayidx33+72)&4294967295);var $38=HEAPF32[(($bp_inc)>>2)];var $39=$pk;var $arrayidx34=((__ZL5peaks801+$39*80)&4294967295);var $bp1=(($arrayidx34+40)&4294967295);var $40=HEAPF32[(($bp1)>>2)];var $add35=($40)+($38);HEAPF32[(($bp1)>>2)]=$add35;var $41=$pk;var $arrayidx36=((__ZL5peaks801+$41*80)&4294967295);var $bp137=(($arrayidx36+40)&4294967295);var $42=HEAPF32[(($bp137)>>2)];var $conv38=((($42))|0);var $43=$pk;var $arrayidx39=((__ZL5peaks801+$43*80)&4294967295);var $bp=(($arrayidx39+12)&4294967295);HEAP32[(($bp)>>2)]=$conv38;var $44=$pk;var $arrayidx40=((__ZL5peaks801+$44*80)&4294967295);var $ap_inc=(($arrayidx40+64)&4294967295);var $45=HEAPF32[(($ap_inc)>>2)];var $46=$pk;var $arrayidx41=((__ZL5peaks801+$46*80)&4294967295);var $ap1=(($arrayidx41+32)&4294967295);var $47=HEAPF32[(($ap1)>>2)];var $add42=($47)+($45);HEAPF32[(($ap1)>>2)]=$add42;var $48=$pk;var $arrayidx43=((__ZL5peaks801+$48*80)&4294967295);var $ap144=(($arrayidx43+32)&4294967295);var $49=HEAPF32[(($ap144)>>2)];var $conv45=((($49))|0);var $50=$pk;var $arrayidx46=((__ZL5peaks801+$50*80)&4294967295);var $ap=(($arrayidx46+8)&4294967295);HEAP32[(($ap)>>2)]=$conv45;var $51=$pk;var $inc48=((($51)+1)&4294967295);$pk=$inc48;var $cmp17=((($inc48))|0)<9;if($cmp17){__label__=10;continue $for_body18$16;}else{__label__=11;break $for_body18$16;}}
$ix=0;;$for_body52$19:while(1){var $52=$ix;var $arrayidx53=((__ZL10klattp_inc+$52*8)&4294967295);var $53=HEAPF32[(($arrayidx53)>>2)];var $54=$ix;var $arrayidx54=((__ZL7klattp1+$54*8)&4294967295);var $55=HEAPF32[(($arrayidx54)>>2)];var $add55=($55)+($53);HEAPF32[(($arrayidx54)>>2)]=$add55;var $56=$ix;var $arrayidx56=((__ZL7klattp1+$56*8)&4294967295);var $57=HEAPF32[(($arrayidx56)>>2)];var $conv57=((($57))|0);var $58=$ix;var $arrayidx58=((__ZL6klattp+$58*4)&4294967295);HEAP32[(($arrayidx58)>>2)]=$conv57;var $59=$ix;var $inc60=((($59)+1)&4294967295);$ix=$inc60;var $cmp51=((($inc60))|0)<10;if($cmp51){__label__=12;continue $for_body52$19;}else{__label__=13;break $for_body52$19;}}
$ix=0;;while(1){var $60=$ix;var $arrayidx65=((__ZL5peaks801+$60*80)&4294967295);var $freq66=(($arrayidx65)&4294967295);var $61=HEAP32[(($freq66)>>2)];var $62=$ix;var $arrayidx67=((((__ZL8kt_frame+208)&4294967295)+$62*4)&4294967295);HEAP32[(($arrayidx67)>>2)]=$61;var $63=$ix;var $cmp68=((($63))|0)<4;if($cmp68){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $64=$ix;var $arrayidx70=((__ZL5peaks801+$64*80)&4294967295);var $bw71=(($arrayidx70+4)&4294967295);var $65=HEAP32[(($bw71)>>2)];var $66=$ix;var $arrayidx72=((((__ZL8kt_frame+248)&4294967295)+$66*4)&4294967295);HEAP32[(($arrayidx72)>>2)]=$65;;}
var $67=$ix;var $inc75=((($67)+1)&4294967295);$ix=$inc75;var $cmp63=((($inc75))|0)<=6;if($cmp63){__label__=14;continue;}else{__label__=17;break;}}
var $68=HEAP32[((((_wdata+12)&4294967295))>>2)];var $69=HEAP32[((((_wdata+8)&4294967295))>>2)];var $add77=((($69)+($68))&4294967295);HEAP32[((((_wdata+8)&4294967295))>>2)]=$add77;var $70=HEAP32[((((_wdata+8)&4294967295))>>2)];var $shr=($70)>>8;$ix=$shr;var $cmp78=((($shr))|0)>127;if($cmp78){__label__=18;;}else{__label__=19;;}
if(__label__==18){$ix=127;;}
var $71=$ix;var $72=HEAP32[((((_wdata)&4294967295))>>2)];var $arrayidx81=(($72+$71)&4294967295);var $73=HEAPU8[($arrayidx81)];var $conv82=((($73))&255);var $74=HEAP32[((((_wdata+20)&4294967295))>>2)];var $mul83=((($conv82)*($74))&4294967295);$x=$mul83;var $75=$x;var $shr84=($75)>>8;var $76=HEAP32[((((_wdata+16)&4294967295))>>2)];var $add85=((($shr84)+($76))&4294967295);HEAP32[((((_wdata+4)&4294967295))>>2)]=$add85;var $77=HEAP32[((__ZL8nsamples802)>>2)];var $78=HEAP32[((__ZL12sample_count)>>2)];var $sub=((($77)-($78))&4294967295);HEAP32[((((__ZL10kt_globals+28)&4294967295))>>2)]=$sub;var $cmp86=((($sub))|0)>64;if($cmp86){__label__=20;;}else{__label__=21;;}
if(__label__==20){HEAP32[((((__ZL10kt_globals+28)&4294967295))>>2)]=64;;}
__ZL10frame_initP13klatt_frame_t();var $call=__ZL7parwaveP13klatt_frame_t();var $cmp89=((($call))|0)==1;if($cmp89){__label__=22;break $while_cond$4;}else{__label__=2;continue $while_cond$4;}}
$while_end$$if_then90$34:do{if(__label__==23){var $79=HEAP32[((__ZL8end_wave803)>>2)];var $cmp92=((($79))|0)>0;if($cmp92){__label__=24;;}else{__label__=26;;}
$if_then93$$if_end99$36:do{if(__label__==24){$fade=64;var $80=$fade;HEAP32[((((__ZL10kt_globals+180)&4294967295))>>2)]=$80;HEAP32[((__ZL8end_wave803)>>2)]=0;var $81=$fade;var $82=HEAP32[((__ZL12sample_count)>>2)];var $sub94=((($82)-($81))&4294967295);HEAP32[((__ZL12sample_count)>>2)]=$sub94;var $83=$fade;HEAP32[((((__ZL10kt_globals+28)&4294967295))>>2)]=$83;var $call95=__ZL7parwaveP13klatt_frame_t();var $cmp96=((($call95))|0)==1;if(!($cmp96)){__label__=26;break $if_then93$$if_end99$36;}
$retval=1;__label__=27;break $while_end$$if_then90$34;}}while(0);$retval=0;;}
else if(__label__==22){$retval=1;;}}while(0);var $84=$retval;;return $84;return null;}
function __ZL10frame_initP13klatt_frame_t(){var __stackBase__=STACKTOP;STACKTOP+=56;_memset(__stackBase__,0,56);var __label__;var $frame_addr;var $amp_par=__stackBase__;var $Gain0_tmp;var $ix;$frame_addr=__ZL8kt_frame;var $0=$frame_addr;var $F0hz10=(($0)&4294967295);var $1=HEAP32[(($F0hz10)>>2)];var $div=((((($1))|0)/10)|0);HEAP32[((((__ZL10kt_globals+176)&4294967295))>>2)]=$div;var $2=$frame_addr;var $AVdb=(($2+4)&4294967295);var $3=HEAP32[(($AVdb)>>2)];var $sub=((($3)-7)&4294967295);var $4=$frame_addr;var $AVdb_tmp=(($4+204)&4294967295);HEAP32[(($AVdb_tmp)>>2)]=$sub;var $5=$frame_addr;var $AVdb_tmp1=(($5+204)&4294967295);var $6=HEAP32[(($AVdb_tmp1)>>2)];var $cmp=((($6))|0)<0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $7=$frame_addr;var $AVdb_tmp2=(($7+204)&4294967295);HEAP32[(($AVdb_tmp2)>>2)]=0;;}
var $8=$frame_addr;var $ASP=(($8+168)&4294967295);var $9=HEAP32[(($ASP)>>2)];var $call=__ZL7DBtoLINl($9);var $mul=($call)*0.05;HEAPF32[((((__ZL10kt_globals+128)&4294967295))>>2)]=$mul;var $10=$frame_addr;var $AF=(($10+184)&4294967295);var $11=HEAP32[(($AF)>>2)];var $call3=__ZL7DBtoLINl($11);var $mul4=($call3)*0.25;HEAPF32[((((__ZL10kt_globals+136)&4294967295))>>2)]=$mul4;var $12=$frame_addr;var $AVpdb=(($12+196)&4294967295);var $13=HEAP32[(($AVpdb)>>2)];var $call5=__ZL7DBtoLINl($13);HEAPF32[((((__ZL10kt_globals+120)&4294967295))>>2)]=$call5;var $14=$frame_addr;var $AB=(($14+192)&4294967295);var $15=HEAP32[(($AB)>>2)];var $call6=__ZL7DBtoLINl($15);var $mul7=($call6)*0.05;HEAPF32[((((__ZL10kt_globals+104)&4294967295))>>2)]=$mul7;$ix=0;;$for_body$5:while(1){var $16=$ix;var $17=$frame_addr;var $Ap=(($17+88)&4294967295);var $arrayidx=(($Ap+$16*4)&4294967295);var $18=HEAP32[(($arrayidx)>>2)];var $call9=__ZL7DBtoLINl($18);var $19=$ix;var $arrayidx10=((__ZZL10frame_initP13klatt_frame_tE14amp_par_factor+$19*8)&4294967295);var $20=HEAPF32[(($arrayidx10)>>2)];var $mul11=($call9)*($20);var $21=$ix;var $arrayidx12=(($amp_par+$21*8)&4294967295);HEAPF32[(($arrayidx12)>>2)]=$mul11;var $22=$ix;var $inc=((($22)+1)&4294967295);$ix=$inc;var $cmp8=((($inc))|0)<=6;if($cmp8){__label__=3;continue $for_body$5;}else{__label__=4;break $for_body$5;}}
var $23=$frame_addr;var $Gain0=(($23+200)&4294967295);var $24=HEAP32[(($Gain0)>>2)];var $sub13=((($24)-3)&4294967295);$Gain0_tmp=$sub13;var $25=$Gain0_tmp;var $cmp14=((($25))|0)<=0;if($cmp14){__label__=5;;}else{__label__=6;;}
if(__label__==5){$Gain0_tmp=57;;}
var $26=$Gain0_tmp;var $call17=__ZL7DBtoLINl($26);var $27=HEAP32[((((__ZL10kt_globals+184)&4294967295))>>2)];var $conv=((($27))|0);var $div18=($call17)/($conv);HEAPF32[((((__ZL10kt_globals+152)&4294967295))>>2)]=$div18;$ix=1;;$for_body21$11:while(1){var $28=$ix;var $29=$frame_addr;var $Fhz=(($29+8)&4294967295);var $arrayidx22=(($Fhz+$28*4)&4294967295);var $30=HEAP32[(($arrayidx22)>>2)];var $31=$ix;var $32=$frame_addr;var $Bhz=(($32+48)&4294967295);var $arrayidx23=(($Bhz+$31*4)&4294967295);var $33=HEAP32[(($arrayidx23)>>2)];var $34=$ix;var $arrayidx24=((((__ZL10kt_globals+188)&4294967295)+$34*64)&4294967295);__ZL6setabcllP11resonator_t($30,$33,$arrayidx24);var $35=$ix;var $cmp25=((($35))|0)<=5;if($cmp25){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $36=$ix;var $37=$frame_addr;var $Fhz_next=(($37+208)&4294967295);var $arrayidx27=(($Fhz_next+$36*4)&4294967295);var $38=HEAP32[(($arrayidx27)>>2)];var $39=$ix;var $40=$frame_addr;var $Bhz_next=(($40+248)&4294967295);var $arrayidx28=(($Bhz_next+$39*4)&4294967295);var $41=HEAP32[(($arrayidx28)>>2)];var $42=$ix;var $arrayidx29=((((__ZL10kt_globals+1468)&4294967295)+$42*64)&4294967295);__ZL6setabcllP11resonator_t($38,$41,$arrayidx29);var $43=$ix;var $arrayidx30=((((__ZL10kt_globals+1468)&4294967295)+$43*64)&4294967295);var $a=(($arrayidx30)&4294967295);var $44=HEAPF32[(($a)>>2)];var $45=$ix;var $arrayidx31=((((__ZL10kt_globals+188)&4294967295)+$45*64)&4294967295);var $a32=(($arrayidx31)&4294967295);var $46=HEAPF32[(($a32)>>2)];var $sub33=($44)-($46);var $div34=($sub33)/64;var $47=$ix;var $arrayidx35=((((__ZL10kt_globals+188)&4294967295)+$47*64)&4294967295);var $a_inc=(($arrayidx35+40)&4294967295);HEAPF32[(($a_inc)>>2)]=$div34;var $48=$ix;var $arrayidx36=((((__ZL10kt_globals+1468)&4294967295)+$48*64)&4294967295);var $b=(($arrayidx36+8)&4294967295);var $49=HEAPF32[(($b)>>2)];var $50=$ix;var $arrayidx37=((((__ZL10kt_globals+188)&4294967295)+$50*64)&4294967295);var $b38=(($arrayidx37+8)&4294967295);var $51=HEAPF32[(($b38)>>2)];var $sub39=($49)-($51);var $div40=($sub39)/64;var $52=$ix;var $arrayidx41=((((__ZL10kt_globals+188)&4294967295)+$52*64)&4294967295);var $b_inc=(($arrayidx41+48)&4294967295);HEAPF32[(($b_inc)>>2)]=$div40;var $53=$ix;var $arrayidx42=((((__ZL10kt_globals+1468)&4294967295)+$53*64)&4294967295);var $c=(($arrayidx42+16)&4294967295);var $54=HEAPF32[(($c)>>2)];var $55=$ix;var $arrayidx43=((((__ZL10kt_globals+188)&4294967295)+$55*64)&4294967295);var $c44=(($arrayidx43+16)&4294967295);var $56=HEAPF32[(($c44)>>2)];var $sub45=($54)-($56);var $div46=($sub45)/64;var $57=$ix;var $arrayidx47=((((__ZL10kt_globals+188)&4294967295)+$57*64)&4294967295);var $c_inc=(($arrayidx47+56)&4294967295);HEAPF32[(($c_inc)>>2)]=$div46;;}
var $58=$ix;var $inc50=((($58)+1)&4294967295);$ix=$inc50;var $cmp20=((($inc50))|0)<=9;if($cmp20){__label__=7;continue $for_body21$11;}else{__label__=10;break $for_body21$11;}}
var $59=$frame_addr;var $Fhz52=(($59+8)&4294967295);var $arrayidx53=(($Fhz52)&4294967295);var $60=HEAP32[(($arrayidx53)>>2)];var $61=$frame_addr;var $Bhz54=(($61+48)&4294967295);var $arrayidx55=(($Bhz54)&4294967295);var $62=HEAP32[(($arrayidx55)>>2)];__ZL10setzeroabcllP11resonator_t($60,$62,((__ZL10kt_globals+188)&4294967295));var $63=$frame_addr;var $Fhz_next56=(($63+208)&4294967295);var $arrayidx57=(($Fhz_next56)&4294967295);var $64=HEAP32[(($arrayidx57)>>2)];var $65=$frame_addr;var $Bhz_next58=(($65+248)&4294967295);var $arrayidx59=(($Bhz_next58)&4294967295);var $66=HEAP32[(($arrayidx59)>>2)];__ZL10setzeroabcllP11resonator_t($64,$66,((__ZL10kt_globals+1468)&4294967295));var $67=HEAPF32[((((__ZL10kt_globals+1468)&4294967295))>>2)];var $68=HEAPF32[((((__ZL10kt_globals+188)&4294967295))>>2)];var $sub60=($67)-($68);var $div61=($sub60)/64;HEAPF32[((((__ZL10kt_globals+188+40)&4294967295))>>2)]=$div61;var $69=HEAPF32[((((__ZL10kt_globals+1468+8)&4294967295))>>2)];var $70=HEAPF32[((((__ZL10kt_globals+188+8)&4294967295))>>2)];var $sub62=($69)-($70);var $div63=($sub62)/64;HEAPF32[((((__ZL10kt_globals+188+48)&4294967295))>>2)]=$div63;var $71=HEAPF32[((((__ZL10kt_globals+1468+16)&4294967295))>>2)];var $72=HEAPF32[((((__ZL10kt_globals+188+16)&4294967295))>>2)];var $sub64=($71)-($72);var $div65=($sub64)/64;HEAPF32[((((__ZL10kt_globals+188+56)&4294967295))>>2)]=$div65;$ix=0;;while(1){var $73=$ix;var $74=$frame_addr;var $Fhz69=(($74+8)&4294967295);var $arrayidx70=(($Fhz69+$73*4)&4294967295);var $75=HEAP32[(($arrayidx70)>>2)];var $76=$ix;var $77=$frame_addr;var $Bphz=(($77+128)&4294967295);var $arrayidx71=(($Bphz+$76*4)&4294967295);var $78=HEAP32[(($arrayidx71)>>2)];var $79=$ix;var $add=((($79)+10)&4294967295);var $arrayidx72=((((__ZL10kt_globals+188)&4294967295)+$add*64)&4294967295);__ZL6setabcllP11resonator_t($75,$78,$arrayidx72);var $80=$ix;var $arrayidx73=(($amp_par+$80*8)&4294967295);var $81=HEAPF32[(($arrayidx73)>>2)];var $82=$ix;var $add74=((($82)+10)&4294967295);var $arrayidx75=((((__ZL10kt_globals+188)&4294967295)+$add74*64)&4294967295);var $a76=(($arrayidx75)&4294967295);var $83=HEAPF32[(($a76)>>2)];var $mul77=($83)*($81);HEAPF32[(($a76)>>2)]=$mul77;var $84=$ix;var $inc79=((($84)+1)&4294967295);$ix=$inc79;var $cmp67=((($inc79))|0)<=6;if($cmp67){__label__=11;continue;}else{__label__=12;break;}}
var $85=HEAP32[((((__ZL10kt_globals+8)&4294967295))>>2)];var $div81=((((($85))|0)/2)|0);__ZL6setabcllP11resonator_t(0,$div81,((__ZL10kt_globals+188+1216)&4294967295));STACKTOP=__stackBase__;return;return;}
function __ZL7parwaveP13klatt_frame_t(){;var __label__;var __lastLabel__=null;var $retval;var $frame_addr;var $temp;var $value;var $outbypas;var $out;var $n4;var $frics;var $glotout;var $aspiration;var $casc_next_in;var $par_glotout;var $ix;var $z2;var $c;var $sample;$frame_addr=__ZL8kt_frame;var $0=$frame_addr;__ZL7flutterP13klatt_frame_t($0);HEAP32[((((__ZL10kt_globals+36)&4294967295))>>2)]=0;;$for_cond$2:while(1){var $1=HEAP32[((((__ZL10kt_globals+36)&4294967295))>>2)];var $2=HEAP32[((((__ZL10kt_globals+28)&4294967295))>>2)];var $cmp=((($1))|0)<((($2))|0);if(!($cmp)){__label__=36;break $for_cond$2;}
var $3=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5noise)>>2)];var $call=__ZL9gen_noised($3);HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5noise)>>2)]=$call;var $4=HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)];var $5=HEAP32[((((__ZL10kt_globals+48)&4294967295))>>2)];var $cmp1=((($4))|0)>((($5))|0);if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $6=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5noise)>>2)];var $mul=($6)*0.5;HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5noise)>>2)]=$mul;;}
var $7=HEAPF32[((((__ZL10kt_globals+136)&4294967295))>>2)];var $8=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5noise)>>2)];var $mul2=($7)*($8);$frics=$mul2;$n4=0;;$for_body5$8:while(1){var $9=HEAP32[((((__ZL10kt_globals+20)&4294967295))>>2)];if($9==1){__label__=6;;}
else if($9==2){__label__=7;;}
else if($9==3){__label__=8;;}
else{__label__=9;;}
if(__label__==6){var $call6=__ZL16impulsive_sourcev();HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)]=$call6;;}
else if(__label__==7){var $call8=__ZL14natural_sourcev();HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)]=$call8;;}
else if(__label__==8){var $call10=__ZL14sampled_sourcev();HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)]=$call10;;}
var $10=HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)];var $11=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];var $cmp11=((($10))|0)>=((($11))|0);if($cmp11){__label__=10;;}else{__label__=11;;}
if(__label__==10){HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)]=0;var $12=$frame_addr;__ZL21pitch_synch_par_resetP13klatt_frame_t($12);;}
var $13=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)];var $call14=__ZL9resonatorP11resonator_td(((__ZL10kt_globals+188+1152)&4294967295),$13);HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)]=$call14;var $14=HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)];var $inc=((($14)+1)&4294967295);HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)]=$inc;var $15=$n4;var $inc15=((($15)+1)&4294967295);$n4=$inc15;var $cmp4=((($inc15))|0)<4;if($cmp4){__label__=5;continue $for_body5$8;}else{__label__=12;break $for_body5$8;}}
var $16=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)];var $17=HEAPF32[((((__ZL10kt_globals+88)&4294967295))>>2)];var $mul16=($16)*($17);var $18=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5vlast)>>2)];var $19=HEAPF32[((((__ZL10kt_globals+96)&4294967295))>>2)];var $mul17=($18)*($19);var $add=($mul16)+($mul17);HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)]=$add;var $20=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)];HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5vlast)>>2)]=$20;var $21=HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)];var $22=HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)];var $cmp18=((($21))|0)<((($22))|0);if($cmp18){__label__=13;;}else{__label__=14;;}
if(__label__==13){var $23=HEAPF32[((((__ZL10kt_globals+144)&4294967295))>>2)];var $24=HEAP32[((((__ZL10kt_globals+52)&4294967295))>>2)];var $conv=((($24))|0);var $mul20=($23)*($conv);var $25=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)];var $add21=($25)+($mul20);HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)]=$add21;;}
var $26=HEAPF32[((((__ZL10kt_globals+112)&4294967295))>>2)];var $27=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)];var $mul23=($26)*($27);$glotout=$mul23;var $28=HEAPF32[((((__ZL10kt_globals+120)&4294967295))>>2)];var $29=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5voice)>>2)];var $mul24=($28)*($29);$par_glotout=$mul24;var $30=HEAPF32[((((__ZL10kt_globals+128)&4294967295))>>2)];var $31=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5noise)>>2)];var $mul25=($30)*($31);$aspiration=$mul25;var $32=$aspiration;var $33=$glotout;var $add26=($33)+($32);$glotout=$add26;var $34=$aspiration;var $35=$par_glotout;var $add27=($35)+($34);$par_glotout=$add27;$out=0;var $36=HEAP32[((((__ZL10kt_globals)&4294967295))>>2)];var $cmp28=((($36))|0)!=2;if($cmp28){__label__=15;;}else{__label__=16;;}
if(__label__==15){var $37=$glotout;var $call30=__ZL14antiresonator2P11resonator_td($37);$casc_next_in=$call30;var $38=$casc_next_in;var $call31=__ZL9resonatorP11resonator_td(((__ZL10kt_globals+188+576)&4294967295),$38);$casc_next_in=$call31;var $39=$casc_next_in;var $call32=__ZL9resonatorP11resonator_td(((__ZL10kt_globals+188+512)&4294967295),$39);$casc_next_in=$call32;var $40=$casc_next_in;var $call33=__ZL9resonatorP11resonator_td(((__ZL10kt_globals+188+448)&4294967295),$40);$casc_next_in=$call33;var $41=$casc_next_in;var $call34=__ZL9resonatorP11resonator_td(((__ZL10kt_globals+188+384)&4294967295),$41);$casc_next_in=$call34;var $42=$casc_next_in;var $call35=__ZL10resonator2P11resonator_td(((__ZL10kt_globals+188+320)&4294967295),$42);$casc_next_in=$call35;var $43=$casc_next_in;var $call36=__ZL10resonator2P11resonator_td(((__ZL10kt_globals+188+256)&4294967295),$43);$casc_next_in=$call36;var $44=$casc_next_in;var $call37=__ZL10resonator2P11resonator_td(((__ZL10kt_globals+188+192)&4294967295),$44);$casc_next_in=$call37;var $45=$casc_next_in;var $call38=__ZL10resonator2P11resonator_td(((__ZL10kt_globals+188+128)&4294967295),$45);$casc_next_in=$call38;var $46=$casc_next_in;var $call39=__ZL10resonator2P11resonator_td(((__ZL10kt_globals+188+64)&4294967295),$46);$out=$call39;;}
var $47=$par_glotout;HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5sourc)>>2)]=$47;var $48=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5sourc)>>2)];var $call41=__ZL9resonatorP11resonator_td(((__ZL10kt_globals+188+704)&4294967295),$48);var $49=$out;var $add42=($49)+($call41);$out=$add42;var $50=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5sourc)>>2)];var $call43=__ZL9resonatorP11resonator_td(((__ZL10kt_globals+188+640)&4294967295),$50);var $51=$out;var $add44=($51)+($call43);$out=$add44;var $52=$frics;var $53=$par_glotout;var $add45=($52)+($53);var $54=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE8glotlast)>>2)];var $sub=($add45)-($54);HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5sourc)>>2)]=$sub;var $55=$par_glotout;HEAPF32[((__ZZL7parwaveP13klatt_frame_tE8glotlast)>>2)]=$55;$ix=12;;$for_body48$25:while(1){var $56=$ix;var $arrayidx=((((__ZL10kt_globals+188)&4294967295)+$56*64)&4294967295);var $57=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5sourc)>>2)];var $call49=__ZL9resonatorP11resonator_td($arrayidx,$57);var $58=$out;var $sub50=($call49)-($58);$out=$sub50;var $59=$ix;var $inc52=((($59)+1)&4294967295);$ix=$inc52;var $cmp47=((($inc52))|0)<=16;if($cmp47){__label__=17;continue $for_body48$25;}else{__label__=18;break $for_body48$25;}}
var $60=HEAPF32[((((__ZL10kt_globals+104)&4294967295))>>2)];var $61=HEAPF32[((__ZZL7parwaveP13klatt_frame_tE5sourc)>>2)];var $mul54=($60)*($61);$outbypas=$mul54;var $62=$outbypas;var $63=$out;var $sub55=($62)-($63);$out=$sub55;var $64=$out;var $call56=__ZL9resonatorP11resonator_td(((__ZL10kt_globals+188+1216)&4294967295),$64);$out=$call56;var $65=$out;var $66=HEAP32[((((_wdata+52)&4294967295))>>2)];var $conv57=((($66))|0);var $mul58=($65)*($conv57);var $67=HEAPF32[((((__ZL10kt_globals+152)&4294967295))>>2)];var $mul59=($mul58)*($67);var $conv60=((($mul59))|0);var $conv61=((($conv60))|0);$temp=$conv61;$z2=0;var $68=HEAP32[((((_wdata+40)&4294967295))>>2)];var $69=HEAP32[((((_wdata+28)&4294967295))>>2)];var $cmp62=((($68))|0)<((($69))|0);if($cmp62){__label__=19;;}else{__label__=23;;}
if(__label__==19){var $70=HEAP32[((((_wdata+32)&4294967295))>>2)];var $cmp64=((($70))|0)==0;var $71=HEAPU32[((((_wdata+40)&4294967295))>>2)];var $add66=((($71)+1)&4294967295);if($cmp64){__label__=20;;}else{__label__=21;;}
if(__label__==20){var $72=HEAP32[((((_wdata+24)&4294967295))>>2)];var $arrayidx67=(($72+$add66)&4294967295);var $73=HEAP8[($arrayidx67)];$c=$73;var $74=HEAP32[((((_wdata+40)&4294967295))>>2)];var $75=HEAP32[((((_wdata+24)&4294967295))>>2)];var $arrayidx68=(($75+$74)&4294967295);var $76=HEAPU8[($arrayidx68)];var $conv69=((($76))&255);var $77=$c;var $conv70=(tempInt=(($77)),(tempInt>=128?tempInt-256:tempInt));var $mul71=((($conv70)*256)&4294967295);var $add72=((($mul71)+($conv69))&4294967295);$sample=$add72;var $78=HEAP32[((((_wdata+40)&4294967295))>>2)];var $add73=((($78)+2)&4294967295);HEAP32[((((_wdata+40)&4294967295))>>2)]=$add73;;}
else if(__label__==21){HEAP32[((((_wdata+40)&4294967295))>>2)]=$add66;var $79=HEAP32[((((_wdata+24)&4294967295))>>2)];var $arrayidx75=(($79+$71)&4294967295);var $80=HEAP8[($arrayidx75)];var $conv76=(tempInt=(($80)),(tempInt>=128?tempInt-256:tempInt));var $81=HEAP32[((((_wdata+32)&4294967295))>>2)];var $mul77=((($conv76)*($81))&4294967295);$sample=$mul77;;}
var $82=$sample;var $83=HEAP32[((((_wdata+56)&4294967295))>>2)];var $mul79=((($83)*($82))&4294967295);var $div=((((($mul79))|0)/1024)|0);$z2=$div;var $84=$z2;var $85=HEAP32[((((_wdata+36)&4294967295))>>2)];var $mul80=((($85)*($84))&4294967295);var $div81=((((($mul80))|0)/40)|0);$z2=$div81;var $86=$z2;var $conv82=((($86))|0);var $87=$temp;var $add83=($87)+($conv82);$temp=$add83;;}
var $88=HEAP32[((((__ZL10kt_globals+180)&4294967295))>>2)];var $cmp85=((($88))|0)>0;if($cmp85){__label__=24;;}else{__label__=25;;}
if(__label__==24){var $89=HEAP32[((((__ZL10kt_globals+180)&4294967295))>>2)];var $dec=((($89)-1)&4294967295);HEAP32[((((__ZL10kt_globals+180)&4294967295))>>2)]=$dec;var $90=$temp;var $91=HEAP32[((((__ZL10kt_globals+180)&4294967295))>>2)];var $conv87=((($91))|0);var $mul88=($90)*($conv87);var $div89=($mul88)/64;$temp=$div89;;}
var $92=$temp;var $conv91=((($92))|0);var $93=HEAP32[((_echo_tail)>>2)];var $inc92=((($93)+1)&4294967295);HEAP32[((_echo_tail)>>2)]=$inc92;var $arrayidx93=((_echo_buf+$93*2)&4294967295);var $94=HEAP16[(($arrayidx93)>>1)];var $conv94=(tempInt=(($94)),(tempInt>=32768?tempInt-65536:tempInt));var $95=HEAP32[((_echo_amp)>>2)];var $mul95=((($conv94)*($95))&4294967295);var $shr=($mul95)>>8;var $add96=((($shr)+($conv91))&4294967295);$value=$add96;var $96=HEAP32[((_echo_tail)>>2)];var $cmp97=((($96))|0)>=5500;if($cmp97){__lastLabel__=25;__label__=26;;}else{__lastLabel__=25;__label__=27;;}
if(__label__==26){HEAP32[((_echo_tail)>>2)]=0;var $_pr=$value;__lastLabel__=26;;}
var $97=__lastLabel__==26?$_pr:($add96);var $cmp100=((($97))|0)<-32768;if($cmp100){__label__=28;;}else{__label__=29;;}
$if_end102_thread$$if_end102$41:do{if(__label__==28){$value=-32768;;}
else if(__label__==29){var $_pr1=$value;var $cmp103=((($_pr1))|0)>32767;if(!($cmp103)){__label__=31;break $if_end102_thread$$if_end102$41;}
$value=32767;;}}while(0);var $98=$value;var $conv106=((($98))&255);var $99=HEAP32[((_out_ptr)>>2)];var $incdec_ptr=(($99+1)&4294967295);HEAP32[((_out_ptr)>>2)]=$incdec_ptr;HEAP8[($99)]=$conv106;var $100=$value;var $shr107=($100)>>8;var $conv108=((($shr107))&255);var $101=HEAP32[((_out_ptr)>>2)];var $incdec_ptr109=(($101+1)&4294967295);HEAP32[((_out_ptr)>>2)]=$incdec_ptr109;HEAP8[($101)]=$conv108;var $102=$value;var $conv110=((($102))&65535);var $103=HEAP32[((_echo_head)>>2)];var $inc111=((($103)+1)&4294967295);HEAP32[((_echo_head)>>2)]=$inc111;var $arrayidx112=((_echo_buf+$103*2)&4294967295);HEAP16[(($arrayidx112)>>1)]=$conv110;var $104=HEAP32[((_echo_head)>>2)];var $cmp113=((($104))|0)>=5500;if($cmp113){__label__=32;;}else{__label__=33;;}
if(__label__==32){HEAP32[((_echo_head)>>2)]=0;;}
var $105=HEAP32[((__ZL12sample_count)>>2)];var $inc116=((($105)+1)&4294967295);HEAP32[((__ZL12sample_count)>>2)]=$inc116;var $106=HEAPU32[((_out_ptr)>>2)];var $107=HEAPU32[((_out_end)>>2)];var $cmp117=((($106))>>>0)>=((($107))>>>0);if($cmp117){__label__=34;break $for_cond$2;}
var $108=HEAP32[((((__ZL10kt_globals+36)&4294967295))>>2)];var $inc121=((($108)+1)&4294967295);HEAP32[((((__ZL10kt_globals+36)&4294967295))>>2)]=$inc121;__label__=1;continue $for_cond$2;}
if(__label__==36){$retval=0;;}
else if(__label__==34){$retval=1;;}
var $109=$retval;;return $109;return null;}
function __Z14SetSynth_KlattiiP7frame_tS0_P7voice_ti($length,$modn,$fr1,$fr2,$v,$control){;var __label__;var __lastLabel__=null;var $length_addr;var $modn_addr;var $fr1_addr;var $fr2_addr;var $v_addr;var $control_addr;var $ix;var $next;var $qix;var $cmd;var $fr3;$length_addr=$length;$modn_addr=$modn;$fr1_addr=$fr1;$fr2_addr=$fr2;$v_addr=$v;$control_addr=$control;var $0=HEAP32[((_wvoice)>>2)];var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=5;;}
if(__label__==1){var $1=HEAP32[((_wvoice)>>2)];var $klattv=(($1+112)&4294967295);var $arrayidx=(($klattv)&4294967295);var $2=HEAP32[(($arrayidx)>>2)];var $cmp1=((($2))|0)>0;if($cmp1){__label__=2;;}else{__label__=4;;}
$land_lhs_true$$if_end$4:do{if(__label__==2){var $3=HEAP32[((_wvoice)>>2)];var $klattv2=(($3+112)&4294967295);var $arrayidx3=(($klattv2)&4294967295);var $4=HEAP32[(($arrayidx3)>>2)];var $cmp4=((($4))|0)<=3;if(!($cmp4)){__label__=4;break $land_lhs_true$$if_end$4;}
var $5=HEAP32[((_wvoice)>>2)];var $klattv6=(($5+112)&4294967295);var $arrayidx7=(($klattv6)&4294967295);var $6=HEAP32[(($arrayidx7)>>2)];HEAP32[((((__ZL10kt_globals+20)&4294967295))>>2)]=$6;var $7=HEAP32[((((__ZL10kt_globals+20)&4294967295))>>2)];var $arrayidx8=((__ZL13scale_wav_tab+$7*4)&4294967295);var $8=HEAP32[(($arrayidx8)>>2)];HEAP32[((((__ZL10kt_globals+184)&4294967295))>>2)]=$8;;}}while(0);var $9=HEAP32[((_wvoice)>>2)];var $flutter=(($9+68)&4294967295);var $10=HEAP32[(($flutter)>>2)];var $div=((((($10))|0)/32)|0);HEAP32[((((__ZL10kt_globals+24)&4294967295))>>2)]=$div;;}
HEAP32[((__ZL8end_wave803)>>2)]=0;var $11=$control_addr;var $and=($11)&2;var $tobool=((($and))|0)!=0;if($tobool){__label__=6;;}else{__label__=7;;}
if(__label__==6){HEAP32[((__ZL8end_wave803)>>2)]=1;;}
var $12=$control_addr;var $and12=($12)&1;var $tobool13=((($and12))|0)!=0;if($tobool13){__label__=8;;}else{__label__=20;;}
$if_then14$$if_end44$12:do{if(__label__==8){HEAP32[((__ZL8end_wave803)>>2)]=1;var $13=HEAP32[((_wcmdq_head)>>2)];var $add=((($13)+1)&4294967295);$qix=$add;__lastLabel__=8;;$for_cond$14:while(1){var $14=__lastLabel__==19?$inc42:($add);var $cmp15=((($14))|0)>=160;if($cmp15){__label__=10;;}else{__label__=11;;}
if(__label__==10){$qix=0;;}
var $15=$qix;var $16=HEAP32[((_wcmdq_tail)>>2)];var $cmp18=((($15))|0)==((($16))|0);if($cmp18){__label__=20;break $if_then14$$if_end44$12;}
var $17=$qix;var $arrayidx21=((_wcmdq+$17*16)&4294967295);var $arrayidx22=(($arrayidx21)&4294967295);var $18=HEAP32[(($arrayidx22)>>2)];$cmd=$18;var $19=$cmd;var $cmp23=((($19))|0)==1;if($cmp23){__label__=13;break $for_cond$14;}
var $31=$cmd;var $cmp37=((($31))|0)==6;var $32=$cmd;var $cmp38=((($32))|0)==5;var $or_cond=($cmp37)|($cmp38);if($or_cond){__label__=20;break $if_then14$$if_end44$12;}
var $33=$qix;var $inc42=((($33)+1)&4294967295);$qix=$inc42;__lastLabel__=19;__label__=9;continue $for_cond$14;}
HEAP32[((__ZL8end_wave803)>>2)]=0;var $20=$qix;var $arrayidx25=((_wcmdq+$20*16)&4294967295);var $arrayidx26=(($arrayidx25+8)&4294967295);var $21=HEAP32[(($arrayidx26)>>2)];var $22=($21);$fr3=$22;$ix=1;__lastLabel__=13;;while(1){var $23=__lastLabel__==17?$inc:(1);var $cmp28=((($23))|0)<6;if(!($cmp28)){__label__=20;break $if_then14$$if_end44$12;}
var $24=$ix;var $25=$fr3;var $ffreq=(($25+2)&4294967295);var $arrayidx29=(($ffreq+$24*2)&4294967295);var $26=HEAP16[(($arrayidx29)>>1)];var $conv=(tempInt=(($26)),(tempInt>=32768?tempInt-65536:tempInt));var $27=$ix;var $28=$fr2_addr;var $ffreq30=(($28+2)&4294967295);var $arrayidx31=(($ffreq30+$27*2)&4294967295);var $29=HEAP16[(($arrayidx31)>>1)];var $conv32=(tempInt=(($29)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp33=((($conv))|0)!=((($conv32))|0);if($cmp33){__label__=16;break;}
var $30=$ix;var $inc=((($30)+1)&4294967295);$ix=$inc;__lastLabel__=17;__label__=14;continue;}
HEAP32[((__ZL8end_wave803)>>2)]=2;;}}while(0);var $34=$control_addr;var $and45=($34)&1;var $tobool46=((($and45))|0)!=0;if($tobool46){__label__=21;;}else{__label__=27;;}
if(__label__==21){$ix=1;__lastLabel__=21;;while(1){var $35=__lastLabel__==25?$inc60:(1);var $cmp49=((($35))|0)<6;if(!($cmp49)){__label__=26;break;}
var $36=$ix;var $arrayidx51=((((__ZZ14SetSynth_KlattiiP7frame_tS0_P7voice_tiE7prev_fr+2)&4294967295)+$36*2)&4294967295);var $37=HEAP16[(($arrayidx51)>>1)];var $conv52=(tempInt=(($37)),(tempInt>=32768?tempInt-65536:tempInt));var $38=$ix;var $39=$fr1_addr;var $ffreq53=(($39+2)&4294967295);var $arrayidx54=(($ffreq53+$38*2)&4294967295);var $40=HEAP16[(($arrayidx54)>>1)];var $conv55=(tempInt=(($40)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp56=((($conv52))|0)!=((($conv55))|0);if($cmp56){__label__=24;break;}
var $41=$ix;var $inc60=((($41)+1)&4294967295);$ix=$inc60;__lastLabel__=25;__label__=22;continue;}
if(__label__==24){__Z10KlattReseti(0);;}
var $42=$fr2_addr;var $43=$42;var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$43;$dest$=__ZZ14SetSynth_KlattiiP7frame_tS0_P7voice_tiE7prev_fr;$stop$=$src$+64;if(($dest$%4)==($src$%4)&&64>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};;}
$ix=0;__lastLabel__=27;;$for_body65$39:while(1){var $44=__lastLabel__==27?0:($inc90);var $cmp66=((($44))|0)>=5;if($cmp66){__label__=29;;}else{__label__=31;;}
$land_lhs_true67$$if_else$41:do{if(__label__==29){var $45=$fr1_addr;var $frflags=(($45)&4294967295);var $46=HEAP16[(($frflags)>>1)];var $conv68=(tempInt=(($46)),(tempInt>=32768?tempInt-65536:tempInt));var $and69=($conv68)&1;var $cmp70=((($and69))|0)==0;if(!($cmp70)){__label__=31;break $land_lhs_true67$$if_else$41;}
var $47=$ix;var $arrayidx72=((__ZL6klattp+$47*4)&4294967295);HEAP32[(($arrayidx72)>>2)]=0;var $48=$ix;var $arrayidx73=((__ZL7klattp1+$48*8)&4294967295);HEAPF32[(($arrayidx73)>>2)]=0;var $49=$ix;var $arrayidx74=((__ZL10klattp_inc+$49*8)&4294967295);HEAPF32[(($arrayidx74)>>2)]=0;__label__=32;break $land_lhs_true67$$if_else$41;}}while(0);if(__label__==31){var $50=$ix;var $51=$fr1_addr;var $klattp=(($51+39)&4294967295);var $arrayidx75=(($klattp+$50)&4294967295);var $52=HEAPU8[($arrayidx75)];var $conv76=((($52))&255);var $53=$ix;var $arrayidx77=((__ZL6klattp+$53*4)&4294967295);HEAP32[(($arrayidx77)>>2)]=$conv76;var $conv78=((($conv76))|0);var $54=$ix;var $arrayidx79=((__ZL7klattp1+$54*8)&4294967295);HEAPF32[(($arrayidx79)>>2)]=$conv78;var $55=$ix;var $56=$fr2_addr;var $klattp80=(($56+39)&4294967295);var $arrayidx81=(($klattp80+$55)&4294967295);var $57=HEAPU8[($arrayidx81)];var $conv82=((($57))&255);var $58=$ix;var $arrayidx83=((__ZL6klattp+$58*4)&4294967295);var $59=HEAP32[(($arrayidx83)>>2)];var $sub=((($conv82)-($59))&4294967295);var $mul=((($sub)*64)&4294967295);var $conv84=((($mul))|0);var $60=$length_addr;var $conv85=((($60))|0);var $div86=($conv84)/($conv85);var $61=$ix;var $arrayidx87=((__ZL10klattp_inc+$61*8)&4294967295);HEAPF32[(($arrayidx87)>>2)]=$div86;;}
var $62=$ix;var $inc90=((($62)+1)&4294967295);$ix=$inc90;var $cmp64=((($inc90))|0)<10;if($cmp64){__lastLabel__=32;__label__=28;continue $for_body65$39;}else{__lastLabel__=32;__label__=33;break $for_body65$39;}}
var $63=$length_addr;HEAP32[((__ZL8nsamples802)>>2)]=$63;$ix=1;;$for_body94$48:while(1){var $64=$ix;var $65=$fr1_addr;var $ffreq95=(($65+2)&4294967295);var $arrayidx96=(($ffreq95+$64*2)&4294967295);var $66=HEAP16[(($arrayidx96)>>1)];var $conv97=(tempInt=(($66)),(tempInt>=32768?tempInt-65536:tempInt));var $67=$ix;var $68=$v_addr;var $freq=(($68+144)&4294967295);var $arrayidx98=(($freq+$67*2)&4294967295);var $69=HEAP16[(($arrayidx98)>>1)];var $conv99=(tempInt=(($69)),(tempInt>=32768?tempInt-65536:tempInt));var $mul100=((($conv99)*($conv97))&4294967295);var $conv101=((($mul100))|0);var $div102=($conv101)/256;var $70=$ix;var $71=$v_addr;var $freqadd=(($71+198)&4294967295);var $arrayidx103=(($freqadd+$70*2)&4294967295);var $72=HEAP16[(($arrayidx103)>>1)];var $conv104=(tempInt=(($72)),(tempInt>=32768?tempInt-65536:tempInt));var $conv105=((($conv104))|0);var $add106=($div102)+($conv105);var $73=$ix;var $arrayidx107=((__ZL5peaks801+$73*80)&4294967295);var $freq1=(($arrayidx107+16)&4294967295);HEAPF32[(($freq1)>>2)]=$add106;var $74=$ix;var $arrayidx108=((__ZL5peaks801+$74*80)&4294967295);var $freq1109=(($arrayidx108+16)&4294967295);var $75=HEAPF32[(($freq1109)>>2)];var $conv110=((($75))|0);var $76=$ix;var $arrayidx111=((__ZL5peaks801+$76*80)&4294967295);var $freq112=(($arrayidx111)&4294967295);HEAP32[(($freq112)>>2)]=$conv110;var $77=$ix;var $78=$fr2_addr;var $ffreq113=(($78+2)&4294967295);var $arrayidx114=(($ffreq113+$77*2)&4294967295);var $79=HEAP16[(($arrayidx114)>>1)];var $conv115=(tempInt=(($79)),(tempInt>=32768?tempInt-65536:tempInt));var $80=$ix;var $81=$v_addr;var $freq116=(($81+144)&4294967295);var $arrayidx117=(($freq116+$80*2)&4294967295);var $82=HEAP16[(($arrayidx117)>>1)];var $conv118=(tempInt=(($82)),(tempInt>=32768?tempInt-65536:tempInt));var $mul119=((($conv118)*($conv115))&4294967295);var $conv120=((($mul119))|0);var $div121=($conv120)/256;var $83=$ix;var $84=$v_addr;var $freqadd122=(($84+198)&4294967295);var $arrayidx123=(($freqadd122+$83*2)&4294967295);var $85=HEAP16[(($arrayidx123)>>1)];var $conv124=(tempInt=(($85)),(tempInt>=32768?tempInt-65536:tempInt));var $conv125=((($conv124))|0);var $add126=($div121)+($conv125);$next=$add126;var $86=$next;var $87=$ix;var $arrayidx127=((__ZL5peaks801+$87*80)&4294967295);var $freq1128=(($arrayidx127+16)&4294967295);var $88=HEAPF32[(($freq1128)>>2)];var $sub129=($86)-($88);var $mul130=($sub129)*64;var $89=$length_addr;var $conv131=((($89))|0);var $div132=($mul130)/($conv131);var $90=$ix;var $arrayidx133=((__ZL5peaks801+$90*80)&4294967295);var $freq_inc=(($arrayidx133+48)&4294967295);HEAPF32[(($freq_inc)>>2)]=$div132;var $91=$ix;var $cmp134=((($91))|0)<4;if($cmp134){__label__=35;;}else{__label__=36;;}
if(__label__==35){var $92=$ix;var $93=$fr1_addr;var $bw=(($93+35)&4294967295);var $arrayidx136=(($bw+$92)&4294967295);var $94=HEAPU8[($arrayidx136)];var $conv137=((($94))&255);var $mul138=((($conv137)*2)&4294967295);var $conv139=((($mul138))|0);var $95=$ix;var $arrayidx140=((__ZL5peaks801+$95*80)&4294967295);var $bw1=(($arrayidx140+24)&4294967295);HEAPF32[(($bw1)>>2)]=$conv139;var $96=$ix;var $arrayidx141=((__ZL5peaks801+$96*80)&4294967295);var $bw1142=(($arrayidx141+24)&4294967295);var $97=HEAPF32[(($bw1142)>>2)];var $conv143=((($97))|0);var $98=$ix;var $arrayidx144=((__ZL5peaks801+$98*80)&4294967295);var $bw145=(($arrayidx144+4)&4294967295);HEAP32[(($bw145)>>2)]=$conv143;var $99=$ix;var $100=$fr2_addr;var $bw146=(($100+35)&4294967295);var $arrayidx147=(($bw146+$99)&4294967295);var $101=HEAPU8[($arrayidx147)];var $conv148=((($101))&255);var $mul149=((($conv148)*2)&4294967295);var $conv150=((($mul149))|0);$next=$conv150;var $102=$next;var $103=$ix;var $arrayidx151=((__ZL5peaks801+$103*80)&4294967295);var $bw1152=(($arrayidx151+24)&4294967295);var $104=HEAPF32[(($bw1152)>>2)];var $sub153=($102)-($104);var $mul154=($sub153)*64;var $105=$length_addr;var $conv155=((($105))|0);var $div156=($mul154)/($conv155);var $106=$ix;var $arrayidx157=((__ZL5peaks801+$106*80)&4294967295);var $bw_inc=(($arrayidx157+56)&4294967295);HEAPF32[(($bw_inc)>>2)]=$div156;;}
var $107=$ix;var $inc160=((($107)+1)&4294967295);$ix=$inc160;var $cmp93=((($inc160))|0)<6;if($cmp93){__label__=34;continue $for_body94$48;}else{__label__=37;break $for_body94$48;}}
var $108=$fr1_addr;var $klattp162=(($108+39)&4294967295);var $arrayidx163=(($klattp162+1)&4294967295);var $109=HEAPU8[($arrayidx163)];var $conv164=((($109))&255);var $mul165=((($conv164)*2)&4294967295);var $conv166=((($mul165))|0);HEAPF32[((((__ZL5peaks801+16)&4294967295))>>2)]=$conv166;var $110=HEAPF32[((((__ZL5peaks801+16)&4294967295))>>2)];var $cmp167=($110)==0;if($cmp167){__label__=38;;}else{__label__=39;;}
if(__label__==38){var $111=HEAP32[((((__ZL8kt_frame+8+36)&4294967295))>>2)];var $conv169=((($111))|0);HEAPF32[((((__ZL5peaks801+16)&4294967295))>>2)]=$conv169;;}
var $112=HEAPF32[((((__ZL5peaks801+16)&4294967295))>>2)];var $conv171=((($112))|0);HEAP32[((((__ZL5peaks801)&4294967295))>>2)]=$conv171;var $113=$fr2_addr;var $klattp172=(($113+39)&4294967295);var $arrayidx173=(($klattp172+1)&4294967295);var $114=HEAPU8[($arrayidx173)];var $conv174=((($114))&255);var $mul175=((($conv174)*2)&4294967295);var $conv176=((($mul175))|0);$next=$conv176;var $cmp177=($conv176)==0;if($cmp177){__label__=40;;}else{__label__=41;;}
if(__label__==40){var $115=HEAP32[((((__ZL8kt_frame+8+36)&4294967295))>>2)];var $conv179=((($115))|0);$next=$conv179;;}
var $116=$next;var $117=HEAPF32[((((__ZL5peaks801+16)&4294967295))>>2)];var $sub181=($116)-($117);var $mul182=($sub181)*64;var $118=$length_addr;var $conv183=((($118))|0);var $div184=($mul182)/($conv183);HEAPF32[((((__ZL5peaks801+48)&4294967295))>>2)]=$div184;HEAPF32[((((__ZL5peaks801+24)&4294967295))>>2)]=89;HEAP32[((((__ZL5peaks801+4)&4294967295))>>2)]=89;HEAPF32[((((__ZL5peaks801+56)&4294967295))>>2)]=0;var $119=$fr1_addr;var $frflags185=(($119)&4294967295);var $120=HEAP16[(($frflags185)>>1)];var $conv186=(tempInt=(($120)),(tempInt>=32768?tempInt-65536:tempInt));var $and187=($conv186)&1;var $tobool188=((($and187))|0)!=0;if($tobool188){__label__=42;;}else{__label__=44;;}
$if_then189$$if_end236$60:do{if(__label__==42){$ix=1;;while(1){var $121=$ix;var $122=$fr1_addr;var $klatt_bp=(($122+56)&4294967295);var $arrayidx193=(($klatt_bp+$121)&4294967295);var $123=HEAPU8[($arrayidx193)];var $conv194=((($123))&255);var $mul195=((($conv194)*4)&4294967295);var $conv196=((($mul195))|0);var $124=$ix;var $arrayidx197=((__ZL5peaks801+$124*80)&4294967295);var $bp1=(($arrayidx197+40)&4294967295);HEAPF32[(($bp1)>>2)]=$conv196;var $125=$ix;var $arrayidx198=((__ZL5peaks801+$125*80)&4294967295);var $bp1199=(($arrayidx198+40)&4294967295);var $126=HEAPF32[(($bp1199)>>2)];var $conv200=((($126))|0);var $127=$ix;var $arrayidx201=((__ZL5peaks801+$127*80)&4294967295);var $bp=(($arrayidx201+12)&4294967295);HEAP32[(($bp)>>2)]=$conv200;var $128=$ix;var $129=$fr2_addr;var $klatt_bp202=(($129+56)&4294967295);var $arrayidx203=(($klatt_bp202+$128)&4294967295);var $130=HEAPU8[($arrayidx203)];var $conv204=((($130))&255);var $mul205=((($conv204)*2)&4294967295);var $conv206=((($mul205))|0);$next=$conv206;var $131=$next;var $132=$ix;var $arrayidx207=((__ZL5peaks801+$132*80)&4294967295);var $bp1208=(($arrayidx207+40)&4294967295);var $133=HEAPF32[(($bp1208)>>2)];var $sub209=($131)-($133);var $mul210=($sub209)*64;var $134=$length_addr;var $conv211=((($134))|0);var $div212=($mul210)/($conv211);var $135=$ix;var $arrayidx213=((__ZL5peaks801+$135*80)&4294967295);var $bp_inc=(($arrayidx213+72)&4294967295);HEAPF32[(($bp_inc)>>2)]=$div212;var $136=$ix;var $137=$fr1_addr;var $klatt_ap=(($137+49)&4294967295);var $arrayidx214=(($klatt_ap+$136)&4294967295);var $138=HEAPU8[($arrayidx214)];var $conv215=((($138))&255);var $139=$ix;var $arrayidx216=((__ZL5peaks801+$139*80)&4294967295);var $ap1=(($arrayidx216+32)&4294967295);HEAPF32[(($ap1)>>2)]=$conv215;var $140=$ix;var $arrayidx217=((__ZL5peaks801+$140*80)&4294967295);var $ap1218=(($arrayidx217+32)&4294967295);var $141=HEAPF32[(($ap1218)>>2)];var $conv219=((($141))|0);var $142=$ix;var $arrayidx220=((__ZL5peaks801+$142*80)&4294967295);var $ap=(($arrayidx220+8)&4294967295);HEAP32[(($ap)>>2)]=$conv219;var $143=$ix;var $144=$fr2_addr;var $klatt_ap221=(($144+49)&4294967295);var $arrayidx222=(($klatt_ap221+$143)&4294967295);var $145=HEAPU8[($arrayidx222)];var $conv223=((($145))&255);var $mul224=((($conv223)*2)&4294967295);var $conv225=((($mul224))|0);$next=$conv225;var $146=$next;var $147=$ix;var $arrayidx226=((__ZL5peaks801+$147*80)&4294967295);var $ap1227=(($arrayidx226+32)&4294967295);var $148=HEAPF32[(($ap1227)>>2)];var $sub228=($146)-($148);var $mul229=($sub228)*64;var $149=$length_addr;var $conv230=((($149))|0);var $div231=($mul229)/($conv230);var $150=$ix;var $arrayidx232=((__ZL5peaks801+$150*80)&4294967295);var $ap_inc=(($arrayidx232+64)&4294967295);HEAPF32[(($ap_inc)>>2)]=$div231;var $151=$ix;var $inc234=((($151)+1)&4294967295);$ix=$inc234;var $cmp191=((($inc234))|0)<7;if($cmp191){__label__=43;continue;}else{__label__=44;break $if_then189$$if_end236$60;}}}}while(0);;return;return;}
function __Z14Wavegen_Klatt2iiiP7frame_tS0_($length,$modulation,$resume,$fr1,$fr2){;var __label__;var $length_addr;var $modulation_addr;var $resume_addr;var $fr1_addr;var $fr2_addr;$length_addr=$length;$modulation_addr=$modulation;$resume_addr=$resume;$fr1_addr=$fr1;$fr2_addr=$fr2;var $0=$resume_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=$length_addr;var $2=$modulation_addr;var $3=$fr1_addr;var $4=$fr2_addr;var $5=HEAP32[((_wvoice)>>2)];__Z14SetSynth_KlattiiP7frame_tS0_P7voice_ti($1,$2,$3,$4,$5,1);;}
var $6=$resume_addr;var $call=__Z13Wavegen_Klatti($6);;return $call;return null;}
function __Z9KlattInitv(){;var __label__;var $ix;HEAP32[((__ZL12sample_count)>>2)]=0;HEAP32[((((__ZL10kt_globals)&4294967295))>>2)]=1;HEAP32[((((__ZL10kt_globals+8)&4294967295))>>2)]=22050;HEAP32[((((__ZL10kt_globals+20)&4294967295))>>2)]=1;var $0=HEAP32[((((__ZL10kt_globals+20)&4294967295))>>2)];var $arrayidx=((__ZL13scale_wav_tab+$0*4)&4294967295);var $1=HEAP32[(($arrayidx)>>2)];HEAP32[((((__ZL10kt_globals+184)&4294967295))>>2)]=$1;HEAP32[((((__ZL10kt_globals+172)&4294967295))>>2)]=((__ZZ9KlattInitvE15natural_samples)&4294967295);HEAP32[((((__ZL10kt_globals+160)&4294967295))>>2)]=100;HEAPF32[((((__ZL10kt_globals+164)&4294967295))>>2)]=3;var $2=HEAP32[((((__ZL10kt_globals+8)&4294967295))>>2)];var $mul=((($2)*10)&4294967295);var $div=((((($mul))|0)/1000)|0);HEAP32[((((__ZL10kt_globals+28)&4294967295))>>2)]=$div;HEAP32[((((__ZL10kt_globals+4)&4294967295))>>2)]=0;HEAP32[((((__ZL10kt_globals+24)&4294967295))>>2)]=20;__Z10KlattReseti(2);$ix=0;;while(1){var $3=$ix;var $arrayidx1=((__ZZ9KlattInitvE10formant_hz+$3*2)&4294967295);var $4=HEAP16[(($arrayidx1)>>1)];var $conv=(tempInt=(($4)),(tempInt>=32768?tempInt-65536:tempInt));var $5=$ix;var $arrayidx2=((((__ZL8kt_frame+8)&4294967295)+$5*4)&4294967295);HEAP32[(($arrayidx2)>>2)]=$conv;var $6=$ix;var $arrayidx3=((__ZZ9KlattInitvE9bandwidth+$6*2)&4294967295);var $7=HEAP16[(($arrayidx3)>>1)];var $conv4=(tempInt=(($7)),(tempInt>=32768?tempInt-65536:tempInt));var $8=$ix;var $arrayidx5=((((__ZL8kt_frame+48)&4294967295)+$8*4)&4294967295);HEAP32[(($arrayidx5)>>2)]=$conv4;var $9=$ix;var $arrayidx6=((__ZZ9KlattInitvE12parallel_amp+$9*2)&4294967295);var $10=HEAP16[(($arrayidx6)>>1)];var $conv7=(tempInt=(($10)),(tempInt>=32768?tempInt-65536:tempInt));var $11=$ix;var $arrayidx8=((((__ZL8kt_frame+88)&4294967295)+$11*4)&4294967295);HEAP32[(($arrayidx8)>>2)]=$conv7;var $12=$ix;var $arrayidx9=((__ZZ9KlattInitvE11parallel_bw+$12*2)&4294967295);var $13=HEAP16[(($arrayidx9)>>1)];var $conv10=(tempInt=(($13)),(tempInt>=32768?tempInt-65536:tempInt));var $14=$ix;var $arrayidx11=((((__ZL8kt_frame+128)&4294967295)+$14*4)&4294967295);HEAP32[(($arrayidx11)>>2)]=$conv10;var $15=$ix;var $inc=((($15)+1)&4294967295);$ix=$inc;var $cmp=((($inc))|0)<=9;if($cmp){__label__=1;continue;}else{__label__=2;break;}}
HEAP32[((((__ZL8kt_frame+248)&4294967295))>>2)]=89;HEAP32[((((__ZL8kt_frame)&4294967295))>>2)]=1000;HEAP32[((((__ZL8kt_frame+4)&4294967295))>>2)]=59;HEAP32[((((__ZL8kt_frame+168)&4294967295))>>2)]=0;HEAP32[((((__ZL8kt_frame+172)&4294967295))>>2)]=40;HEAP32[((((__ZL8kt_frame+176)&4294967295))>>2)]=0;HEAP32[((((__ZL8kt_frame+180)&4294967295))>>2)]=0;HEAP32[((((__ZL8kt_frame+184)&4294967295))>>2)]=50;HEAP32[((((__ZL8kt_frame+188)&4294967295))>>2)]=0;HEAP32[((((__ZL8kt_frame+192)&4294967295))>>2)]=0;HEAP32[((((__ZL8kt_frame+196)&4294967295))>>2)]=0;HEAP32[((((__ZL8kt_frame+200)&4294967295))>>2)]=62;;return;return;}
function __ZL7flutterP13klatt_frame_t($frame){;var __label__;var $frame_addr;var $delta_f0;var $fla;var $flb;var $flc;var $fld;var $fle;$frame_addr=$frame;var $0=HEAP32[((((__ZL10kt_globals+24)&4294967295))>>2)];var $conv=((($0))|0);var $div=($conv)/50;$fla=$div;var $1=HEAP32[((((__ZL10kt_globals+176)&4294967295))>>2)];var $conv1=((($1))|0);var $div2=($conv1)/100;$flb=$div2;var $2=HEAP32[((__ZZL7flutterP13klatt_frame_tE10time_count)>>2)];var $conv3=((($2))|0);var $mul=39.898227289999994*($conv3);var $call=_sin($mul);$flc=$call;var $3=HEAP32[((__ZZL7flutterP13klatt_frame_tE10time_count)>>2)];var $conv4=((($3))|0);var $mul5=22.305308169999996*($conv4);var $call6=_sin($mul5);$fld=$call6;var $4=HEAP32[((__ZZL7flutterP13klatt_frame_tE10time_count)>>2)];var $conv7=((($4))|0);var $mul8=14.76548569*($conv7);var $call9=_sin($mul8);$fle=$call9;var $5=$fla;var $6=$flb;var $mul10=($5)*($6);var $7=$flc;var $8=$fld;var $add=($7)+($8);var $9=$fle;var $add11=($add)+($9);var $mul12=($mul10)*($add11);var $mul13=($mul12)*10;$delta_f0=$mul13;var $10=$frame_addr;var $F0hz10=(($10)&4294967295);var $11=HEAP32[(($F0hz10)>>2)];var $12=$delta_f0;var $conv14=((($12))|0);var $add15=((($conv14)+($11))&4294967295);var $13=$frame_addr;var $F0hz1016=(($13)&4294967295);HEAP32[(($F0hz1016)>>2)]=$add15;var $14=HEAP32[((__ZZL7flutterP13klatt_frame_tE10time_count)>>2)];var $inc=((($14)+1)&4294967295);HEAP32[((__ZZL7flutterP13klatt_frame_tE10time_count)>>2)]=$inc;;return;return;}
function __ZL9gen_noised($noise){;var __label__;var $noise_addr;var $temp;$noise_addr=$noise;var $call=_rand();var $rem=((($call))|0)%16383;var $add=((($rem)-8191)&4294967295);$temp=$add;var $0=$temp;HEAP32[((((__ZL10kt_globals+52)&4294967295))>>2)]=$0;var $1=HEAP32[((((__ZL10kt_globals+52)&4294967295))>>2)];var $conv=((($1))|0);var $2=HEAPF32[((__ZZL9gen_noisedE5nlast)>>2)];var $mul=0.75*($2);var $add1=($conv)+($mul);$noise_addr=$add1;var $3=$noise_addr;HEAPF32[((__ZZL9gen_noisedE5nlast)>>2)]=$3;var $4=$noise_addr;;return $4;return null;}
function __ZL16impulsive_sourcev(){;var __label__;var $0=HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)];var $cmp=((($0))|0)<3;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)];var $arrayidx=((__ZZL16impulsive_sourcevE7doublet+$1*8)&4294967295);var $2=HEAPF32[(($arrayidx)>>2)];HEAPF32[((__ZZL16impulsive_sourcevE5vwave)>>2)]=$2;;}
else if(__label__==2){HEAPF32[((__ZZL16impulsive_sourcevE5vwave)>>2)]=0;;}
var $3=HEAPF32[((__ZZL16impulsive_sourcevE5vwave)>>2)];var $call=__ZL9resonatorP11resonator_td(((__ZL10kt_globals+188+1088)&4294967295),$3);;return $call;return null;}
function __ZL14natural_sourcev(){;var __label__;var $retval;var $lgtemp;var $0=HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)];var $1=HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)];var $cmp=((($0))|0)<((($1))|0);if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=HEAPF32[((((__ZL10kt_globals+64)&4294967295))>>2)];var $3=HEAPF32[((((__ZL10kt_globals+56)&4294967295))>>2)];var $sub=($3)-($2);HEAPF32[((((__ZL10kt_globals+56)&4294967295))>>2)]=$sub;var $4=HEAPF32[((((__ZL10kt_globals+56)&4294967295))>>2)];var $5=HEAPF32[((__ZZL14natural_sourcevE5vwave)>>2)];var $add=($5)+($4);HEAPF32[((__ZZL14natural_sourcevE5vwave)>>2)]=$add;var $6=HEAPF32[((__ZZL14natural_sourcevE5vwave)>>2)];var $mul=($6)*0.028;$lgtemp=$mul;var $7=$lgtemp;$retval=$7;;}
else if(__label__==2){HEAPF32[((__ZZL14natural_sourcevE5vwave)>>2)]=0;$retval=0;;}
var $8=$retval;;return $8;return null;}
function __ZL14sampled_sourcev(){;var __label__;var $itemp;var $ftemp;var $result;var $diff_value;var $current_value;var $next_value;var $temp_diff;var $0=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];var $cmp=((($0))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $1=HEAP32[((((__ZL10kt_globals+32)&4294967295))>>2)];var $conv=((($1))|0);$ftemp=$conv;var $2=$ftemp;var $3=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];var $conv1=((($3))|0);var $div=($2)/($conv1);$ftemp=$div;var $4=$ftemp;var $5=HEAP32[((((__ZL10kt_globals+160)&4294967295))>>2)];var $conv2=((($5))|0);var $mul=($4)*($conv2);$ftemp=$mul;var $6=$ftemp;var $conv3=((($6))|0);$itemp=$conv3;var $7=$ftemp;var $8=$itemp;var $conv4=((($8))|0);var $sub=($7)-($conv4);$temp_diff=$sub;var $9=$itemp;var $10=HEAP32[((((__ZL10kt_globals+172)&4294967295))>>2)];var $arrayidx=(($10+2*$9)&4294967295);var $11=HEAP16[(($arrayidx)>>1)];var $conv5=(tempInt=(($11)),(tempInt>=32768?tempInt-65536:tempInt));$current_value=$conv5;var $12=$itemp;var $add=((($12)+1)&4294967295);var $13=HEAP32[((((__ZL10kt_globals+172)&4294967295))>>2)];var $arrayidx6=(($13+2*$add)&4294967295);var $14=HEAP16[(($arrayidx6)>>1)];var $conv7=(tempInt=(($14)),(tempInt>=32768?tempInt-65536:tempInt));$next_value=$conv7;var $15=$next_value;var $conv8=((($15))|0);var $16=$current_value;var $conv9=((($16))|0);var $sub10=($conv8)-($conv9);$diff_value=$sub10;var $17=$diff_value;var $18=$temp_diff;var $mul11=($17)*($18);$diff_value=$mul11;var $19=$itemp;var $20=HEAP32[((((__ZL10kt_globals+172)&4294967295))>>2)];var $arrayidx12=(($20+2*$19)&4294967295);var $21=HEAP16[(($arrayidx12)>>1)];var $conv13=(tempInt=(($21)),(tempInt>=32768?tempInt-65536:tempInt));var $conv14=((($conv13))|0);var $22=$diff_value;var $add15=($conv14)+($22);$result=$add15;var $23=$result;var $24=HEAPF32[((((__ZL10kt_globals+164)&4294967295))>>2)];var $mul16=($23)*($24);$result=$mul16;;}
else if(__label__==2){$result=0;;}
var $25=$result;;return $25;return null;}
function __ZL21pitch_synch_par_resetP13klatt_frame_t($frame){;var __label__;var __lastLabel__=null;var $frame_addr;var $temp;var $temp1;$frame_addr=$frame;var $0=$frame_addr;var $F0hz10=(($0)&4294967295);var $1=HEAP32[(($F0hz10)>>2)];var $cmp=((($1))|0)>0;if($cmp){__label__=1;;}else{__label__=15;;}
if(__label__==1){var $2=HEAP32[((((__ZL10kt_globals+8)&4294967295))>>2)];var $mul=((($2)*40)&4294967295);var $3=$frame_addr;var $F0hz101=(($3)&4294967295);var $4=HEAP32[(($F0hz101)>>2)];var $div=((((($mul))|0)/((($4))|0))|0);HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)]=$div;var $5=$frame_addr;var $AVdb_tmp=(($5+204)&4294967295);var $6=HEAP32[(($AVdb_tmp)>>2)];var $call=__ZL7DBtoLINl($6);HEAPF32[((((__ZL10kt_globals+112)&4294967295))>>2)]=$call;var $7=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];HEAP32[((((__ZL10kt_globals+48)&4294967295))>>2)]=$7;var $8=$frame_addr;var $AVdb_tmp2=(($8+204)&4294967295);var $9=HEAP32[(($AVdb_tmp2)>>2)];var $cmp3=((($9))|0)>0;if($cmp3){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $10=HEAP32[((((__ZL10kt_globals+48)&4294967295))>>2)];var $shr=($10)>>1;HEAP32[((((__ZL10kt_globals+48)&4294967295))>>2)]=$shr;;}
var $11=$frame_addr;var $Aturb=(($11+176)&4294967295);var $12=HEAP32[(($Aturb)>>2)];var $call5=__ZL7DBtoLINl($12);var $mul6=($call5)*0.1;HEAPF32[((((__ZL10kt_globals+144)&4294967295))>>2)]=$mul6;var $13=$frame_addr;var $Kopen=(($13+172)&4294967295);var $14=HEAP32[(($Kopen)>>2)];var $mul7=((($14)*4)&4294967295);HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)]=$mul7;var $15=HEAP32[((((__ZL10kt_globals+20)&4294967295))>>2)];var $cmp8=((($15))|0)==1;var $16=HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)];var $cmp9=((($16))|0)>263;var $or_cond=($cmp8)&($cmp9);if($or_cond){__label__=4;;}else{__label__=5;;}
if(__label__==4){HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)]=263;;}
var $17=HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)];var $18=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];var $sub=((($18)-1)&4294967295);var $cmp12=((($17))|0)>=((($sub))|0);if($cmp12){__lastLabel__=5;__label__=6;;}else{__lastLabel__=5;__label__=7;;}
if(__label__==6){var $19=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];var $sub14=((($19)-2)&4294967295);HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)]=$sub14;__lastLabel__=6;;}
var $20=__lastLabel__==6?$sub14:($17);var $cmp16=((($20))|0)<40;if($cmp16){__label__=8;;}else{__label__=9;;}
if(__label__==8){HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)]=40;;}
var $21=HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)];var $sub19=((($21)-40)&4294967295);var $arrayidx=((__ZZL21pitch_synch_par_resetP13klatt_frame_tE2B0+$sub19*2)&4294967295);var $22=HEAP16[(($arrayidx)>>1)];var $conv=(tempInt=(($22)),(tempInt>=32768?tempInt-65536:tempInt));HEAPF32[((((__ZL10kt_globals+64)&4294967295))>>2)]=$conv;var $23=HEAPF32[((((__ZL10kt_globals+64)&4294967295))>>2)];var $24=HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)];var $conv20=((($24))|0);var $mul21=($23)*($conv20);var $mul22=($mul21)*0.333;HEAPF32[((((__ZL10kt_globals+56)&4294967295))>>2)]=$mul22;var $25=HEAP32[((((__ZL10kt_globals+8)&4294967295))>>2)];var $26=HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)];var $div23=((((($25))|0)/((($26))|0))|0);$temp=$div23;var $27=$temp;__ZL6setabcllP11resonator_t(0,$27,((__ZL10kt_globals+188+1088)&4294967295));var $28=HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)];var $conv24=((($28))|0);var $mul25=($conv24)*0.00833;$temp1=$mul25;var $29=$temp1;var $30=$temp1;var $mul26=($29)*($30);var $31=HEAPF32[((((__ZL10kt_globals+188+1088)&4294967295))>>2)];var $mul27=($31)*($mul26);HEAPF32[((((__ZL10kt_globals+188+1088)&4294967295))>>2)]=$mul27;var $32=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];var $33=HEAP32[((((__ZL10kt_globals+44)&4294967295))>>2)];var $sub28=((($32)-($33))&4294967295);$temp=$sub28;var $34=$frame_addr;var $Kskew=(($34+188)&4294967295);var $35=HEAP32[(($Kskew)>>2)];var $36=$temp;var $cmp29=((($35))|0)>((($36))|0);if($cmp29){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $37=$temp;var $38=$frame_addr;var $Kskew31=(($38+188)&4294967295);HEAP32[(($Kskew31)>>2)]=$37;;}
var $39=HEAP32[((__ZZL21pitch_synch_par_resetP13klatt_frame_tE4skew)>>2)];var $cmp33=((($39))|0)>=0;var $40=$frame_addr;var $Kskew35=(($40+188)&4294967295);var $41=HEAP32[(($Kskew35)>>2)];if($cmp33){__label__=12;;}else{__label__=13;;}
if(__label__==12){HEAP32[((__ZZL21pitch_synch_par_resetP13klatt_frame_tE4skew)>>2)]=$41;;}
else if(__label__==13){var $sub37=(((-($41)))&4294967295);HEAP32[((__ZZL21pitch_synch_par_resetP13klatt_frame_tE4skew)>>2)]=$sub37;;}
var $42=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];var $43=HEAP32[((__ZZL21pitch_synch_par_resetP13klatt_frame_tE4skew)>>2)];var $add=((($43)+($42))&4294967295);HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)]=$add;var $44=HEAP32[((__ZZL21pitch_synch_par_resetP13klatt_frame_tE4skew)>>2)];var $sub39=(((-($44)))&4294967295);HEAP32[((__ZZL21pitch_synch_par_resetP13klatt_frame_tE4skew)>>2)]=$sub39;;}
else if(__label__==15){HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)]=4;HEAPF32[((((__ZL10kt_globals+112)&4294967295))>>2)]=0;var $45=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];HEAP32[((((__ZL10kt_globals+48)&4294967295))>>2)]=$45;HEAPF32[((((__ZL10kt_globals+144)&4294967295))>>2)]=0;HEAPF32[((((__ZL10kt_globals+56)&4294967295))>>2)]=0;HEAPF32[((((__ZL10kt_globals+64)&4294967295))>>2)]=0;;}
var $46=HEAP32[((((__ZL10kt_globals+40)&4294967295))>>2)];var $cmp42=((($46))|0)!=4;var $47=HEAP32[((((__ZL10kt_globals+36)&4294967295))>>2)];var $cmp43=((($47))|0)==0;var $or_cond1=($cmp42)|($cmp43);if($or_cond1){__label__=17;;}else{__label__=20;;}
if(__label__==17){var $48=$frame_addr;var $TLTdb=(($48+180)&4294967295);var $49=HEAP32[(($TLTdb)>>2)];var $conv45=((($49))|0);var $mul46=0.033*($conv45);HEAPF32[((((__ZL10kt_globals+96)&4294967295))>>2)]=$mul46;var $50=HEAPF32[((((__ZL10kt_globals+96)&4294967295))>>2)];var $cmp47=($50)>0;if($cmp47){__label__=18;;}else{__label__=19;;}
if(__label__==18){var $51=HEAPF32[((((__ZL10kt_globals+96)&4294967295))>>2)];var $sub49=1-($51);HEAPF32[((((__ZL10kt_globals+88)&4294967295))>>2)]=$sub49;;}
else if(__label__==19){HEAPF32[((((__ZL10kt_globals+88)&4294967295))>>2)]=1;;}};return;return;}
function __ZL9resonatorP11resonator_td($r,$input){;var __label__;var $r_addr;var $input_addr;var $x;$r_addr=$r;$input_addr=$input;var $0=$r_addr;var $a=(($0)&4294967295);var $1=HEAPF32[(($a)>>2)];var $2=$input_addr;var $mul=($1)*($2);var $3=$r_addr;var $b=(($3+8)&4294967295);var $4=HEAPF32[(($b)>>2)];var $5=$r_addr;var $p1=(($5+24)&4294967295);var $6=HEAPF32[(($p1)>>2)];var $mul1=($4)*($6);var $add=($mul)+($mul1);var $7=$r_addr;var $c=(($7+16)&4294967295);var $8=HEAPF32[(($c)>>2)];var $9=$r_addr;var $p2=(($9+32)&4294967295);var $10=HEAPF32[(($p2)>>2)];var $mul2=($8)*($10);var $add3=($add)+($mul2);$x=$add3;var $11=$r_addr;var $p14=(($11+24)&4294967295);var $12=HEAPF32[(($p14)>>2)];var $13=$r_addr;var $p25=(($13+32)&4294967295);HEAPF32[(($p25)>>2)]=$12;var $14=$x;var $15=$r_addr;var $p16=(($15+24)&4294967295);HEAPF32[(($p16)>>2)]=$14;var $16=$x;;return $16;return null;}
function __ZL14antiresonator2P11resonator_td($input){;var __label__;var $r_addr;var $input_addr;var $x;$r_addr=((__ZL10kt_globals+188)&4294967295);$input_addr=$input;var $0=$r_addr;var $a=(($0)&4294967295);var $1=HEAPF32[(($a)>>2)];var $2=$input_addr;var $mul=($1)*($2);var $3=$r_addr;var $b=(($3+8)&4294967295);var $4=HEAPF32[(($b)>>2)];var $5=$r_addr;var $p1=(($5+24)&4294967295);var $6=HEAPF32[(($p1)>>2)];var $mul1=($4)*($6);var $add=($mul)+($mul1);var $7=$r_addr;var $c=(($7+16)&4294967295);var $8=HEAPF32[(($c)>>2)];var $9=$r_addr;var $p2=(($9+32)&4294967295);var $10=HEAPF32[(($p2)>>2)];var $mul2=($8)*($10);var $add3=($add)+($mul2);$x=$add3;var $11=$r_addr;var $p14=(($11+24)&4294967295);var $12=HEAPF32[(($p14)>>2)];var $13=$r_addr;var $p25=(($13+32)&4294967295);HEAPF32[(($p25)>>2)]=$12;var $14=$input_addr;var $15=$r_addr;var $p16=(($15+24)&4294967295);HEAPF32[(($p16)>>2)]=$14;var $16=$r_addr;var $a_inc=(($16+40)&4294967295);var $17=HEAPF32[(($a_inc)>>2)];var $18=$r_addr;var $a7=(($18)&4294967295);var $19=HEAPF32[(($a7)>>2)];var $add8=($19)+($17);HEAPF32[(($a7)>>2)]=$add8;var $20=$r_addr;var $b_inc=(($20+48)&4294967295);var $21=HEAPF32[(($b_inc)>>2)];var $22=$r_addr;var $b9=(($22+8)&4294967295);var $23=HEAPF32[(($b9)>>2)];var $add10=($23)+($21);HEAPF32[(($b9)>>2)]=$add10;var $24=$r_addr;var $c_inc=(($24+56)&4294967295);var $25=HEAPF32[(($c_inc)>>2)];var $26=$r_addr;var $c11=(($26+16)&4294967295);var $27=HEAPF32[(($c11)>>2)];var $add12=($27)+($25);HEAPF32[(($c11)>>2)]=$add12;var $28=$x;;return $28;return null;}
function __ZL10resonator2P11resonator_td($r,$input){;var __label__;var $r_addr;var $input_addr;var $x;$r_addr=$r;$input_addr=$input;var $0=$r_addr;var $a=(($0)&4294967295);var $1=HEAPF32[(($a)>>2)];var $2=$input_addr;var $mul=($1)*($2);var $3=$r_addr;var $b=(($3+8)&4294967295);var $4=HEAPF32[(($b)>>2)];var $5=$r_addr;var $p1=(($5+24)&4294967295);var $6=HEAPF32[(($p1)>>2)];var $mul1=($4)*($6);var $add=($mul)+($mul1);var $7=$r_addr;var $c=(($7+16)&4294967295);var $8=HEAPF32[(($c)>>2)];var $9=$r_addr;var $p2=(($9+32)&4294967295);var $10=HEAPF32[(($p2)>>2)];var $mul2=($8)*($10);var $add3=($add)+($mul2);$x=$add3;var $11=$r_addr;var $p14=(($11+24)&4294967295);var $12=HEAPF32[(($p14)>>2)];var $13=$r_addr;var $p25=(($13+32)&4294967295);HEAPF32[(($p25)>>2)]=$12;var $14=$x;var $15=$r_addr;var $p16=(($15+24)&4294967295);HEAPF32[(($p16)>>2)]=$14;var $16=$r_addr;var $a_inc=(($16+40)&4294967295);var $17=HEAPF32[(($a_inc)>>2)];var $18=$r_addr;var $a7=(($18)&4294967295);var $19=HEAPF32[(($a7)>>2)];var $add8=($19)+($17);HEAPF32[(($a7)>>2)]=$add8;var $20=$r_addr;var $b_inc=(($20+48)&4294967295);var $21=HEAPF32[(($b_inc)>>2)];var $22=$r_addr;var $b9=(($22+8)&4294967295);var $23=HEAPF32[(($b9)>>2)];var $add10=($23)+($21);HEAPF32[(($b9)>>2)]=$add10;var $24=$r_addr;var $c_inc=(($24+56)&4294967295);var $25=HEAPF32[(($c_inc)>>2)];var $26=$r_addr;var $c11=(($26+16)&4294967295);var $27=HEAPF32[(($c11)>>2)];var $add12=($27)+($25);HEAPF32[(($c11)>>2)]=$add12;var $28=$x;;return $28;return null;}
function __ZL7DBtoLINl($dB){;var __label__;var $retval;var $dB_addr;$dB_addr=$dB;var $0=$dB_addr;var $cmp=((($0))|0)<0;var $1=$dB_addr;var $cmp1=((($1))|0)>87;var $or_cond=($cmp)|($cmp1);if($or_cond){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $2=$dB_addr;var $arrayidx=((__ZZL7DBtoLINlE8amptable+$2*2)&4294967295);var $3=HEAP16[(($arrayidx)>>1)];var $conv=(tempInt=(($3)),(tempInt>=32768?tempInt-65536:tempInt));var $mul=($conv)*0.001;$retval=$mul;;}
var $4=$retval;;return $4;return null;}
function __ZL10setzeroabcllP11resonator_t($f,$bw,$rp){;var __label__;var $f_addr;var $bw_addr;var $rp_addr;var $r;var $arg;$f_addr=$f;$bw_addr=$bw;$rp_addr=$rp;var $0=$f_addr;var $sub=(((-($0)))&4294967295);$f_addr=$sub;var $1=$f_addr;var $cmp=((($1))|0)>=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$f_addr=-1;;}
var $2=HEAPF32[((((__ZL10kt_globals+72)&4294967295))>>2)];var $3=$bw_addr;var $conv=((($3))|0);var $mul=($2)*($conv);$arg=$mul;var $4=$arg;var $call=_exp($4);$r=$call;var $5=$r;var $6=$r;var $mul1=($5)*($6);var $sub2=(-($mul1));var $7=$rp_addr;var $c=(($7+16)&4294967295);HEAPF32[(($c)>>2)]=$sub2;var $8=HEAPF32[((((__ZL10kt_globals+80)&4294967295))>>2)];var $9=$f_addr;var $conv3=((($9))|0);var $mul4=($8)*($conv3);$arg=$mul4;var $10=$r;var $11=$arg;var $call5=_cos($11);var $mul6=($10)*($call5);var $mul7=($mul6)*2;var $12=$rp_addr;var $b=(($12+8)&4294967295);HEAPF32[(($b)>>2)]=$mul7;var $13=$rp_addr;var $b8=(($13+8)&4294967295);var $14=HEAPF32[(($b8)>>2)];var $sub9=1-($14);var $15=$rp_addr;var $c10=(($15+16)&4294967295);var $16=HEAPF32[(($c10)>>2)];var $sub11=($sub9)-($16);var $17=$rp_addr;var $a=(($17)&4294967295);HEAPF32[(($a)>>2)]=$sub11;var $18=$rp_addr;var $a12=(($18)&4294967295);var $19=HEAPF32[(($a12)>>2)];var $div=1/($19);var $20=$rp_addr;var $a13=(($20)&4294967295);HEAPF32[(($a13)>>2)]=$div;var $21=$rp_addr;var $a14=(($21)&4294967295);var $22=HEAPF32[(($a14)>>2)];var $sub15=(-($22));var $23=$rp_addr;var $c16=(($23+16)&4294967295);var $24=HEAPF32[(($c16)>>2)];var $mul17=($24)*($sub15);HEAPF32[(($c16)>>2)]=$mul17;var $25=$rp_addr;var $a18=(($25)&4294967295);var $26=HEAPF32[(($a18)>>2)];var $sub19=(-($26));var $27=$rp_addr;var $b20=(($27+8)&4294967295);var $28=HEAPF32[(($b20)>>2)];var $mul21=($28)*($sub19);HEAPF32[(($b20)>>2)]=$mul21;;return;return;}
function __Z8sonicMSGPcz($format){var __stackBase__=STACKTOP;STACKTOP+=4100;_memset(__stackBase__,0,4100);var __label__;var $format_addr;var $buffer=__stackBase__;var $ap=__stackBase__+4096;var $file;$format_addr=$format;var $ap1=$ap;HEAP32[(($ap1)>>2)]=arguments[__Z8sonicMSGPcz.length];;var $arraydecay=(($buffer)&4294967295);var $0=$format_addr;var $1=HEAP32[(($ap)>>2)];var $call=_vsprintf($arraydecay,$0,$1);var $ap2=$ap;;var $call3=_fopen(((__str810)&4294967295),((__str1811)&4294967295));$file=$call3;var $2=$file;var $arraydecay4=(($buffer)&4294967295);var $fputs=_fputs($arraydecay4,$2);var $3=$file;var $call6=_fclose($3);STACKTOP=__stackBase__;return;return;}
function _sonicGetSpeed($stream){;var __label__;var $stream_addr;$stream_addr=$stream;var $0=$stream_addr;var $speed=(($0+16)&4294967295);var $1=HEAPF32[(($speed)>>2)];;return $1;return null;}
function _sonicSetSpeed($stream,$speed){;var __label__;var $stream_addr;var $speed_addr;$stream_addr=$stream;$speed_addr=$speed;var $0=$speed_addr;var $1=$stream_addr;var $speed1=(($1+16)&4294967295);HEAPF32[(($speed1)>>2)]=$0;;return;return;}
function _sonicGetPitch($stream){;var __label__;var $stream_addr;$stream_addr=$stream;var $0=$stream_addr;var $pitch=(($0+24)&4294967295);var $1=HEAPF32[(($pitch)>>2)];;return $1;return null;}
function _sonicSetPitch($stream,$pitch){;var __label__;var $stream_addr;var $pitch_addr;$stream_addr=$stream;$pitch_addr=$pitch;var $0=$pitch_addr;var $1=$stream_addr;var $pitch1=(($1+24)&4294967295);HEAPF32[(($pitch1)>>2)]=$0;;return;return;}
function _sonicGetVolume($stream){;var __label__;var $stream_addr;$stream_addr=$stream;var $0=$stream_addr;var $volume=(($0+20)&4294967295);var $1=HEAPF32[(($volume)>>2)];;return $1;return null;}
function _sonicSetVolume($stream,$volume){;var __label__;var $stream_addr;var $volume_addr;$stream_addr=$stream;$volume_addr=$volume;var $0=$volume_addr;var $1=$stream_addr;var $volume1=(($1+20)&4294967295);HEAPF32[(($volume1)>>2)]=$0;;return;return;}
function _sonicGetSampleRate($stream){;var __label__;var $stream_addr;$stream_addr=$stream;var $0=$stream_addr;var $sampleRate=(($0+72)&4294967295);var $1=HEAP32[(($sampleRate)>>2)];;return $1;return null;}
function _sonicGetNumChannels($stream){;var __label__;var $stream_addr;$stream_addr=$stream;var $0=$stream_addr;var $numChannels=(($0+28)&4294967295);var $1=HEAP32[(($numChannels)>>2)];;return $1;return null;}
function _sonicDestroyStream($stream){;var __label__;var $stream_addr;$stream_addr=$stream;var $0=$stream_addr;var $inputBuffer=(($0)&4294967295);var $1=HEAP32[(($inputBuffer)>>2)];var $cmp=((($1))|0)!=0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $2=$stream_addr;var $inputBuffer1=(($2)&4294967295);var $3=HEAP32[(($inputBuffer1)>>2)];var $4=$3;;;}
var $5=$stream_addr;var $outputBuffer=(($5+4)&4294967295);var $6=HEAP32[(($outputBuffer)>>2)];var $cmp2=((($6))|0)!=0;if($cmp2){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $7=$stream_addr;var $outputBuffer4=(($7+4)&4294967295);var $8=HEAP32[(($outputBuffer4)>>2)];var $9=$8;;;}
var $10=$stream_addr;var $pitchBuffer=(($10+8)&4294967295);var $11=HEAP32[(($pitchBuffer)>>2)];var $cmp6=((($11))|0)!=0;if($cmp6){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $12=$stream_addr;var $pitchBuffer8=(($12+8)&4294967295);var $13=HEAP32[(($pitchBuffer8)>>2)];var $14=$13;;;}
var $15=$stream_addr;var $downSampleBuffer=(($15+12)&4294967295);var $16=HEAP32[(($downSampleBuffer)>>2)];var $cmp10=((($16))|0)!=0;if($cmp10){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $17=$stream_addr;var $downSampleBuffer12=(($17+12)&4294967295);var $18=HEAP32[(($downSampleBuffer12)>>2)];var $19=$18;;;}
var $20=$stream_addr;var $21=$20;;;return;return;}
function _sonicCreateStream($sampleRate,$numChannels){;var __label__;var $retval;var $sampleRate_addr;var $numChannels_addr;var $stream;var $minPeriod;var $maxPeriod;var $maxRequired;$sampleRate_addr=$sampleRate;$numChannels_addr=$numChannels;var $call=_calloc(1,88);var $0=$call;$stream=$0;var $1=$sampleRate_addr;var $div=((((($1))|0)/400)|0);$minPeriod=$div;var $2=$sampleRate_addr;var $div1=((((($2))|0)/65)|0);$maxPeriod=$div1;var $3=$maxPeriod;var $mul=((($3)*2)&4294967295);$maxRequired=$mul;var $4=$stream;var $cmp=((($4))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $5=$maxRequired;var $6=$stream;var $inputBufferSize=(($6+32)&4294967295);HEAP32[(($inputBufferSize)>>2)]=$5;var $7=$maxRequired;var $8=$numChannels_addr;var $mul2=((($8)*2)&4294967295);var $call3=_calloc($7,$mul2);var $9=$call3;var $10=$stream;var $inputBuffer=(($10)&4294967295);HEAP32[(($inputBuffer)>>2)]=$9;var $11=$stream;var $inputBuffer4=(($11)&4294967295);var $12=HEAP32[(($inputBuffer4)>>2)];var $cmp5=((($12))|0)==0;if($cmp5){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $13=$stream;_sonicDestroyStream($13);$retval=0;;}
else if(__label__==4){var $14=$maxRequired;var $15=$stream;var $outputBufferSize=(($15+40)&4294967295);HEAP32[(($outputBufferSize)>>2)]=$14;var $16=$maxRequired;var $17=$numChannels_addr;var $mul8=((($17)*2)&4294967295);var $call9=_calloc($16,$mul8);var $18=$call9;var $19=$stream;var $outputBuffer=(($19+4)&4294967295);HEAP32[(($outputBuffer)>>2)]=$18;var $20=$stream;var $outputBuffer10=(($20+4)&4294967295);var $21=HEAP32[(($outputBuffer10)>>2)];var $cmp11=((($21))|0)==0;if($cmp11){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $22=$stream;_sonicDestroyStream($22);$retval=0;;}
else if(__label__==6){var $23=$maxRequired;var $24=$stream;var $pitchBufferSize=(($24+36)&4294967295);HEAP32[(($pitchBufferSize)>>2)]=$23;var $25=$maxRequired;var $26=$numChannels_addr;var $mul14=((($26)*2)&4294967295);var $call15=_calloc($25,$mul14);var $27=$call15;var $28=$stream;var $pitchBuffer=(($28+8)&4294967295);HEAP32[(($pitchBuffer)>>2)]=$27;var $29=$stream;var $pitchBuffer16=(($29+8)&4294967295);var $30=HEAP32[(($pitchBuffer16)>>2)];var $cmp17=((($30))|0)==0;if($cmp17){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $31=$stream;_sonicDestroyStream($31);$retval=0;;}
else if(__label__==8){var $32=$maxRequired;var $call20=_calloc($32,2);var $33=$call20;var $34=$stream;var $downSampleBuffer=(($34+12)&4294967295);HEAP32[(($downSampleBuffer)>>2)]=$33;var $35=$stream;var $speed=(($35+16)&4294967295);HEAPF32[(($speed)>>2)]=1;var $36=$stream;var $pitch=(($36+24)&4294967295);HEAPF32[(($pitch)>>2)]=1;var $37=$stream;var $volume=(($37+20)&4294967295);HEAPF32[(($volume)>>2)]=1;var $38=$sampleRate_addr;var $39=$stream;var $sampleRate21=(($39+72)&4294967295);HEAP32[(($sampleRate21)>>2)]=$38;var $40=$numChannels_addr;var $41=$stream;var $numChannels22=(($41+28)&4294967295);HEAP32[(($numChannels22)>>2)]=$40;var $42=$minPeriod;var $43=$stream;var $minPeriod23=(($43+56)&4294967295);HEAP32[(($minPeriod23)>>2)]=$42;var $44=$maxPeriod;var $45=$stream;var $maxPeriod24=(($45+60)&4294967295);HEAP32[(($maxPeriod24)>>2)]=$44;var $46=$maxRequired;var $47=$stream;var $maxRequired25=(($47+64)&4294967295);HEAP32[(($maxRequired25)>>2)]=$46;var $48=$stream;$retval=$48;;}}}}
var $49=$retval;;return $49;return null;}
function _sonicReadFloatFromStream($stream,$samples,$maxSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $maxSamples_addr;var $numSamples;var $remainingSamples;var $buffer;var $count;$stream_addr=$stream;$samples_addr=$samples;$maxSamples_addr=$maxSamples;var $0=$stream_addr;var $numOutputSamples=(($0+48)&4294967295);var $1=HEAP32[(($numOutputSamples)>>2)];$numSamples=$1;$remainingSamples=0;var $2=$numSamples;var $cmp=((($2))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $3=$numSamples;var $4=$maxSamples_addr;var $cmp1=((($3))|0)>((($4))|0);if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $5=$numSamples;var $6=$maxSamples_addr;var $sub=((($5)-($6))&4294967295);$remainingSamples=$sub;var $7=$maxSamples_addr;$numSamples=$7;;}
var $8=$stream_addr;var $outputBuffer=(($8+4)&4294967295);var $9=HEAP32[(($outputBuffer)>>2)];$buffer=$9;var $10=$numSamples;var $11=$stream_addr;var $numChannels=(($11+28)&4294967295);var $12=HEAP32[(($numChannels)>>2)];var $mul=((($12)*($10))&4294967295);var $dec1=((($mul)-1)&4294967295);$count=$dec1;var $tobool2=((($mul))|0)!=0;if($tobool2){__label__=5;;}else{__label__=6;;}
$while_body$$while_end$8:do{if(__label__==5){while(1){var $13=$buffer;var $incdec_ptr=(($13+2)&4294967295);$buffer=$incdec_ptr;var $14=HEAP16[(($13)>>1)];var $conv=(tempInt=(($14)),(tempInt>=32768?tempInt-65536:tempInt));var $conv4=((($conv))|0);var $div=($conv4)/32767;var $15=$samples_addr;var $incdec_ptr5=(($15+4)&4294967295);$samples_addr=$incdec_ptr5;HEAPF32[(($15)>>2)]=$div;var $_pr=$count;var $dec=((($_pr)-1)&4294967295);$count=$dec;var $tobool=((($_pr))|0)!=0;if($tobool){__label__=5;continue;}else{__label__=6;break $while_body$$while_end$8;}}}}while(0);var $16=$remainingSamples;var $cmp6=((($16))|0)>0;if($cmp6){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $17=$stream_addr;var $outputBuffer8=(($17+4)&4294967295);var $18=HEAP32[(($outputBuffer8)>>2)];var $19=$18;var $20=$stream_addr;var $outputBuffer9=(($20+4)&4294967295);var $21=HEAP32[(($outputBuffer9)>>2)];var $22=$numSamples;var $23=$stream_addr;var $numChannels10=(($23+28)&4294967295);var $24=HEAP32[(($numChannels10)>>2)];var $mul11=((($24)*($22))&4294967295);var $add_ptr=(($21+2*$mul11)&4294967295);var $25=$add_ptr;var $26=$remainingSamples;var $27=$stream_addr;var $numChannels13=(($27+28)&4294967295);var $28=HEAP32[(($numChannels13)>>2)];var $mul12=((($26)*2)&4294967295);var $mul14=((($mul12)*($28))&4294967295);_llvm_memmove_p0i8_p0i8_i32($19,$25,$mul14,1,0);;}
var $29=$remainingSamples;var $30=$stream_addr;var $numOutputSamples16=(($30+48)&4294967295);HEAP32[(($numOutputSamples16)>>2)]=$29;var $31=$numSamples;$retval=$31;;}
var $32=$retval;;return $32;return null;}
function _sonicReadShortFromStream($stream,$samples,$maxSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $maxSamples_addr;var $numSamples;var $remainingSamples;$stream_addr=$stream;$samples_addr=$samples;$maxSamples_addr=$maxSamples;var $0=$stream_addr;var $numOutputSamples=(($0+48)&4294967295);var $1=HEAP32[(($numOutputSamples)>>2)];$numSamples=$1;$remainingSamples=0;var $2=$numSamples;var $cmp=((($2))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $3=$numSamples;var $4=$maxSamples_addr;var $cmp1=((($3))|0)>((($4))|0);if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $5=$numSamples;var $6=$maxSamples_addr;var $sub=((($5)-($6))&4294967295);$remainingSamples=$sub;var $7=$maxSamples_addr;$numSamples=$7;;}
var $8=$samples_addr;var $9=$8;var $10=$stream_addr;var $outputBuffer=(($10+4)&4294967295);var $11=HEAP32[(($outputBuffer)>>2)];var $12=$11;var $13=$numSamples;var $14=$stream_addr;var $numChannels=(($14+28)&4294967295);var $15=HEAP32[(($numChannels)>>2)];var $mul=((($13)*2)&4294967295);var $mul4=((($mul)*($15))&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$12;$dest$=$9;$stop$=$src$+$mul4;if(($dest$%4)==($src$%4)&&$mul4>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $16=$remainingSamples;var $cmp5=((($16))|0)>0;if($cmp5){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $17=$stream_addr;var $outputBuffer7=(($17+4)&4294967295);var $18=HEAP32[(($outputBuffer7)>>2)];var $19=$18;var $20=$stream_addr;var $outputBuffer8=(($20+4)&4294967295);var $21=HEAP32[(($outputBuffer8)>>2)];var $22=$numSamples;var $23=$stream_addr;var $numChannels9=(($23+28)&4294967295);var $24=HEAP32[(($numChannels9)>>2)];var $mul10=((($24)*($22))&4294967295);var $add_ptr=(($21+2*$mul10)&4294967295);var $25=$add_ptr;var $26=$remainingSamples;var $27=$stream_addr;var $numChannels12=(($27+28)&4294967295);var $28=HEAP32[(($numChannels12)>>2)];var $mul11=((($26)*2)&4294967295);var $mul13=((($mul11)*($28))&4294967295);_llvm_memmove_p0i8_p0i8_i32($19,$25,$mul13,1,0);;}
var $29=$remainingSamples;var $30=$stream_addr;var $numOutputSamples15=(($30+48)&4294967295);HEAP32[(($numOutputSamples15)>>2)]=$29;var $31=$numSamples;$retval=$31;;}
var $32=$retval;;return $32;return null;}
function _sonicReadUnsignedCharFromStream($stream,$samples,$maxSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $maxSamples_addr;var $numSamples;var $remainingSamples;var $buffer;var $count;$stream_addr=$stream;$samples_addr=$samples;$maxSamples_addr=$maxSamples;var $0=$stream_addr;var $numOutputSamples=(($0+48)&4294967295);var $1=HEAP32[(($numOutputSamples)>>2)];$numSamples=$1;$remainingSamples=0;var $2=$numSamples;var $cmp=((($2))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=0;;}
else if(__label__==2){var $3=$numSamples;var $4=$maxSamples_addr;var $cmp1=((($3))|0)>((($4))|0);if($cmp1){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $5=$numSamples;var $6=$maxSamples_addr;var $sub=((($5)-($6))&4294967295);$remainingSamples=$sub;var $7=$maxSamples_addr;$numSamples=$7;;}
var $8=$stream_addr;var $outputBuffer=(($8+4)&4294967295);var $9=HEAP32[(($outputBuffer)>>2)];$buffer=$9;var $10=$numSamples;var $11=$stream_addr;var $numChannels=(($11+28)&4294967295);var $12=HEAP32[(($numChannels)>>2)];var $mul=((($12)*($10))&4294967295);var $dec1=((($mul)-1)&4294967295);$count=$dec1;var $tobool2=((($mul))|0)!=0;if($tobool2){__label__=5;;}else{__label__=6;;}
$while_body$$while_end$8:do{if(__label__==5){while(1){var $13=$buffer;var $incdec_ptr=(($13+2)&4294967295);$buffer=$incdec_ptr;var $14=HEAP16[(($13)>>1)];var $conv=(tempInt=(($14)),(tempInt>=32768?tempInt-65536:tempInt));var $shr=($conv)>>8;var $conv4=((($shr))&255);var $conv5=(tempInt=(($conv4)),(tempInt>=128?tempInt-256:tempInt));var $add=((($conv5)+128)&4294967295);var $conv6=((($add))&255);var $15=$samples_addr;var $incdec_ptr7=(($15+1)&4294967295);$samples_addr=$incdec_ptr7;HEAP8[($15)]=$conv6;var $_pr=$count;var $dec=((($_pr)-1)&4294967295);$count=$dec;var $tobool=((($_pr))|0)!=0;if($tobool){__label__=5;continue;}else{__label__=6;break $while_body$$while_end$8;}}}}while(0);var $16=$remainingSamples;var $cmp8=((($16))|0)>0;if($cmp8){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $17=$stream_addr;var $outputBuffer10=(($17+4)&4294967295);var $18=HEAP32[(($outputBuffer10)>>2)];var $19=$18;var $20=$stream_addr;var $outputBuffer11=(($20+4)&4294967295);var $21=HEAP32[(($outputBuffer11)>>2)];var $22=$numSamples;var $23=$stream_addr;var $numChannels12=(($23+28)&4294967295);var $24=HEAP32[(($numChannels12)>>2)];var $mul13=((($24)*($22))&4294967295);var $add_ptr=(($21+2*$mul13)&4294967295);var $25=$add_ptr;var $26=$remainingSamples;var $27=$stream_addr;var $numChannels15=(($27+28)&4294967295);var $28=HEAP32[(($numChannels15)>>2)];var $mul14=((($26)*2)&4294967295);var $mul16=((($mul14)*($28))&4294967295);_llvm_memmove_p0i8_p0i8_i32($19,$25,$mul16,1,0);;}
var $29=$remainingSamples;var $30=$stream_addr;var $numOutputSamples18=(($30+48)&4294967295);HEAP32[(($numOutputSamples18)>>2)]=$29;var $31=$numSamples;$retval=$31;;}
var $32=$retval;;return $32;return null;}
function _sonicFlushStream($stream){;var __label__;var $retval;var $stream_addr;var $maxRequired;var $numSamples;var $remainingSpace;var $numOutputSamples;var $expectedSamples;$stream_addr=$stream;var $0=$stream_addr;var $maxRequired1=(($0+64)&4294967295);var $1=HEAP32[(($maxRequired1)>>2)];$maxRequired=$1;var $2=$stream_addr;var $numInputSamples=(($2+44)&4294967295);var $3=HEAP32[(($numInputSamples)>>2)];$numSamples=$3;var $4=$numSamples;var $cmp=((($4))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_end$2:do{if(__label__==1){$retval=1;;}
else if(__label__==2){var $5=$numSamples;var $6=$maxRequired;var $cmp2=((($5))|0)>=((($6))|0);if($cmp2){__label__=3;;}else{__label__=5;;}
$land_lhs_true$$if_end4$5:do{if(__label__==3){var $7=$stream_addr;var $call=_sonicWriteShortToStream($7,0,0);var $tobool=((($call))|0)!=0;if($tobool){__label__=5;break $land_lhs_true$$if_end4$5;}
$retval=0;__label__=12;break $if_then$$if_end$2;}}while(0);var $8=$stream_addr;var $numInputSamples5=(($8+44)&4294967295);var $9=HEAP32[(($numInputSamples5)>>2)];$numSamples=$9;var $cmp6=((($9))|0)==0;if($cmp6){__label__=6;;}else{__label__=7;;}
if(__label__==6){$retval=1;;}
else if(__label__==7){var $10=$maxRequired;var $11=$numSamples;var $sub=((($10)-($11))&4294967295);$remainingSpace=$sub;var $12=$stream_addr;var $inputBuffer=(($12)&4294967295);var $13=HEAP32[(($inputBuffer)>>2)];var $14=$numSamples;var $15=$stream_addr;var $numChannels=(($15+28)&4294967295);var $16=HEAP32[(($numChannels)>>2)];var $mul=((($16)*($14))&4294967295);var $add_ptr=(($13+2*$mul)&4294967295);var $17=$add_ptr;var $18=$remainingSpace;var $19=$stream_addr;var $numChannels10=(($19+28)&4294967295);var $20=HEAP32[(($numChannels10)>>2)];var $mul9=((($18)*2)&4294967295);var $mul11=((($mul9)*($20))&4294967295);var $dest$,$stop$,$stop4$,$fast$,$value4$;$dest$=$17;$stop$=$dest$+$mul11;$value4$=0;if($value4$<0)$value4$+=256;$value4$=$value4$+($value4$<<8)+($value4$<<16)+($value4$*16777216);while($dest$%4!==0&&$dest$<$stop$){;;HEAP8[$dest$++]=0;}
$dest$>>=2;$stop4$=$stop$>>2;while($dest$<$stop4$){;;;;;;;HEAP32[$dest$++]=$value4$;}
$dest$<<=2;while($dest$<$stop$){;;HEAP8[$dest$++]=0;};var $21=$maxRequired;var $22=$stream_addr;var $numInputSamples12=(($22+44)&4294967295);HEAP32[(($numInputSamples12)>>2)]=$21;var $23=$stream_addr;var $numOutputSamples13=(($23+48)&4294967295);var $24=HEAP32[(($numOutputSamples13)>>2)];$numOutputSamples=$24;var $25=$stream_addr;var $call14=_sonicWriteShortToStream($25,0,0);var $tobool15=((($call14))|0)!=0;if($tobool15){__label__=9;;}else{__label__=8;;}
if(__label__==9){var $26=$numSamples;var $conv=((($26))|0);var $27=$stream_addr;var $speed=(($27+16)&4294967295);var $28=HEAPF32[(($speed)>>2)];var $mul18=($conv)*($28);var $conv19=($mul18);var $add=($conv19)+0.5;var $conv20=((($add))|0);$expectedSamples=$conv20;var $29=$stream_addr;var $numOutputSamples21=(($29+48)&4294967295);var $30=HEAP32[(($numOutputSamples21)>>2)];var $31=$numOutputSamples;var $32=$expectedSamples;var $add22=((($32)+($31))&4294967295);var $cmp23=((($30))|0)>((($add22))|0);if($cmp23){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $33=$numOutputSamples;var $34=$expectedSamples;var $add25=((($34)+($33))&4294967295);var $35=$stream_addr;var $numOutputSamples26=(($35+48)&4294967295);HEAP32[(($numOutputSamples26)>>2)]=$add25;;}
$retval=1;;}
else if(__label__==8){$retval=0;;}}}}while(0);var $36=$retval;;return $36;return null;}
function _sonicWriteShortToStream($stream,$samples,$numSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $numSamples_addr;$stream_addr=$stream;$samples_addr=$samples;$numSamples_addr=$numSamples;var $0=$stream_addr;var $1=$samples_addr;var $2=$numSamples_addr;var $call=__ZL28addShortSamplesToInputBufferP17sonicStreamStructPsi($0,$1,$2);var $tobool=((($call))|0)!=0;if($tobool){__label__=2;;}else{__label__=1;;}
if(__label__==2){var $3=$stream_addr;var $call1=__ZL18processStreamInputP17sonicStreamStruct($3);$retval=$call1;;}
else if(__label__==1){$retval=0;;}
var $4=$retval;;return $4;return null;}
function _sonicSamplesAvailable($stream){;var __label__;var $stream_addr;$stream_addr=$stream;var $0=$stream_addr;var $numOutputSamples=(($0+48)&4294967295);var $1=HEAP32[(($numOutputSamples)>>2)];;return $1;return null;}
function _sonicWriteFloatToStream($stream,$samples,$numSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $numSamples_addr;$stream_addr=$stream;$samples_addr=$samples;$numSamples_addr=$numSamples;var $0=$stream_addr;var $1=$samples_addr;var $2=$numSamples_addr;var $call=__ZL28addFloatSamplesToInputBufferP17sonicStreamStructPfi($0,$1,$2);var $tobool=((($call))|0)!=0;if($tobool){__label__=2;;}else{__label__=1;;}
if(__label__==2){var $3=$stream_addr;var $call1=__ZL18processStreamInputP17sonicStreamStruct($3);$retval=$call1;;}
else if(__label__==1){$retval=0;;}
var $4=$retval;;return $4;return null;}
function __ZL28addFloatSamplesToInputBufferP17sonicStreamStructPfi($stream,$samples,$numSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $numSamples_addr;var $buffer;var $count;$stream_addr=$stream;$samples_addr=$samples;$numSamples_addr=$numSamples;var $0=$numSamples_addr;var $1=$stream_addr;var $numChannels=(($1+28)&4294967295);var $2=HEAP32[(($numChannels)>>2)];var $mul=((($2)*($0))&4294967295);$count=$mul;var $3=$numSamples_addr;var $cmp=((($3))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $4=$stream_addr;var $5=$numSamples_addr;var $call=__ZL26enlargeInputBufferIfNeededP17sonicStreamStructi($4,$5);var $tobool=((($call))|0)!=0;if($tobool){__label__=4;;}else{__label__=3;;}
if(__label__==4){var $6=$stream_addr;var $inputBuffer=(($6)&4294967295);var $7=HEAP32[(($inputBuffer)>>2)];var $8=$stream_addr;var $numInputSamples=(($8+44)&4294967295);var $9=HEAP32[(($numInputSamples)>>2)];var $10=$stream_addr;var $numChannels3=(($10+28)&4294967295);var $11=HEAP32[(($numChannels3)>>2)];var $mul4=((($11)*($9))&4294967295);var $add_ptr=(($7+2*$mul4)&4294967295);$buffer=$add_ptr;var $12=$count;var $dec1=((($12)-1)&4294967295);$count=$dec1;var $tobool52=((($12))|0)!=0;if($tobool52){__label__=5;;}else{__label__=6;;}
$while_body$$while_end$7:do{if(__label__==5){while(1){var $13=$samples_addr;var $incdec_ptr=(($13+4)&4294967295);$samples_addr=$incdec_ptr;var $14=HEAPF32[(($13)>>2)];var $mul6=($14)*32767;var $conv=((($mul6))|0);var $15=$buffer;var $incdec_ptr7=(($15+2)&4294967295);$buffer=$incdec_ptr7;HEAP16[(($15)>>1)]=$conv;var $16=$count;var $dec=((($16)-1)&4294967295);$count=$dec;var $tobool5=((($16))|0)!=0;if($tobool5){__label__=5;continue;}else{__label__=6;break $while_body$$while_end$7;}}}}while(0);var $17=$numSamples_addr;var $18=$stream_addr;var $numInputSamples8=(($18+44)&4294967295);var $19=HEAP32[(($numInputSamples8)>>2)];var $add=((($19)+($17))&4294967295);HEAP32[(($numInputSamples8)>>2)]=$add;$retval=1;;}
else if(__label__==3){$retval=0;;}}
var $20=$retval;;return $20;return null;}
function __ZL18processStreamInputP17sonicStreamStruct($stream){;var __label__;var $retval;var $stream_addr;var $originalNumOutputSamples;var $speed;$stream_addr=$stream;var $0=$stream_addr;var $numOutputSamples=(($0+48)&4294967295);var $1=HEAP32[(($numOutputSamples)>>2)];$originalNumOutputSamples=$1;var $2=$stream_addr;var $speed1=(($2+16)&4294967295);var $3=HEAPF32[(($speed1)>>2)];var $4=$stream_addr;var $pitch=(($4+24)&4294967295);var $5=HEAPF32[(($pitch)>>2)];var $div=($3)/($5);$speed=$div;var $6=$speed;var $conv=($6);var $cmp=($conv)>1.00001;if($cmp){__label__=2;;}else{__label__=1;;}
$if_then$$lor_lhs_false$2:do{if(__label__==1){var $7=$speed;var $conv2=($7);var $cmp3=($conv2)<0.99999;if($cmp3){__label__=2;break $if_then$$lor_lhs_false$2;}
var $10=$stream_addr;var $11=$stream_addr;var $inputBuffer=(($11)&4294967295);var $12=HEAP32[(($inputBuffer)>>2)];var $13=$stream_addr;var $numInputSamples=(($13+44)&4294967295);var $14=HEAP32[(($numInputSamples)>>2)];var $call4=__ZL12copyToOutputP17sonicStreamStructPsi($10,$12,$14);var $tobool=((($call4))|0)!=0;if($tobool){__label__=5;;}else{__label__=4;;}
if(__label__==5){var $15=$stream_addr;var $numInputSamples6=(($15+44)&4294967295);HEAP32[(($numInputSamples6)>>2)]=0;__label__=6;break $if_then$$lor_lhs_false$2;}
else if(__label__==4){$retval=0;__label__=12;break $if_then$$lor_lhs_false$2;}}}while(0);$if_then$$if_end7$$return$8:do{if(__label__==2){var $8=$stream_addr;var $9=$speed;__ZL11changeSpeedP17sonicStreamStructf($8,$9);__label__=6;break $if_then$$if_end7$$return$8;}}while(0);$if_end7$$return$10:do{if(__label__==6){var $16=$stream_addr;var $pitch8=(($16+24)&4294967295);var $17=HEAPF32[(($pitch8)>>2)];var $cmp9=($17)!=1;if($cmp9){__label__=7;;}else{__label__=9;;}
$if_then10$$if_end15$12:do{if(__label__==7){var $18=$stream_addr;var $19=$originalNumOutputSamples;var $call11=__ZL11adjustPitchP17sonicStreamStructi($18,$19);var $tobool12=((($call11))|0)!=0;if($tobool12){__label__=9;break $if_then10$$if_end15$12;}
$retval=0;__label__=12;break $if_end7$$return$10;}}while(0);var $20=$stream_addr;var $volume=(($20+20)&4294967295);var $21=HEAPF32[(($volume)>>2)];var $cmp16=($21)!=1;if($cmp16){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $22=$stream_addr;var $outputBuffer=(($22+4)&4294967295);var $23=HEAP32[(($outputBuffer)>>2)];var $24=$originalNumOutputSamples;var $25=$stream_addr;var $numChannels=(($25+28)&4294967295);var $26=HEAP32[(($numChannels)>>2)];var $mul=((($26)*($24))&4294967295);var $add_ptr=(($23+2*$mul)&4294967295);var $27=$stream_addr;var $numOutputSamples18=(($27+48)&4294967295);var $28=HEAP32[(($numOutputSamples18)>>2)];var $29=$originalNumOutputSamples;var $sub=((($28)-($29))&4294967295);var $30=$stream_addr;var $numChannels19=(($30+28)&4294967295);var $31=HEAP32[(($numChannels19)>>2)];var $mul20=((($31)*($sub))&4294967295);var $32=$stream_addr;var $volume21=(($32+20)&4294967295);var $33=HEAPF32[(($volume21)>>2)];__ZL12scaleSamplesPsif($add_ptr,$mul20,$33);;}
$retval=1;;}}while(0);var $34=$retval;;return $34;return null;}
function __ZL28addShortSamplesToInputBufferP17sonicStreamStructPsi($stream,$samples,$numSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $numSamples_addr;$stream_addr=$stream;$samples_addr=$samples;$numSamples_addr=$numSamples;var $0=$numSamples_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $1=$stream_addr;var $2=$numSamples_addr;var $call=__ZL26enlargeInputBufferIfNeededP17sonicStreamStructi($1,$2);var $tobool=((($call))|0)!=0;if($tobool){__label__=4;;}else{__label__=3;;}
if(__label__==4){var $3=$stream_addr;var $inputBuffer=(($3)&4294967295);var $4=HEAP32[(($inputBuffer)>>2)];var $5=$stream_addr;var $numInputSamples=(($5+44)&4294967295);var $6=HEAP32[(($numInputSamples)>>2)];var $7=$stream_addr;var $numChannels=(($7+28)&4294967295);var $8=HEAP32[(($numChannels)>>2)];var $mul=((($8)*($6))&4294967295);var $add_ptr=(($4+2*$mul)&4294967295);var $9=$add_ptr;var $10=$samples_addr;var $11=$10;var $12=$numSamples_addr;var $13=$stream_addr;var $numChannels4=(($13+28)&4294967295);var $14=HEAP32[(($numChannels4)>>2)];var $mul3=((($12)*2)&4294967295);var $mul5=((($mul3)*($14))&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$11;$dest$=$9;$stop$=$src$+$mul5;if(($dest$%4)==($src$%4)&&$mul5>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $15=$numSamples_addr;var $16=$stream_addr;var $numInputSamples6=(($16+44)&4294967295);var $17=HEAP32[(($numInputSamples6)>>2)];var $add=((($17)+($15))&4294967295);HEAP32[(($numInputSamples6)>>2)]=$add;$retval=1;;}
else if(__label__==3){$retval=0;;}}
var $18=$retval;;return $18;return null;}
function _sonicWriteUnsignedCharToStream($stream,$samples,$numSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $numSamples_addr;$stream_addr=$stream;$samples_addr=$samples;$numSamples_addr=$numSamples;var $0=$stream_addr;var $1=$samples_addr;var $2=$numSamples_addr;var $call=__ZL35addUnsignedCharSamplesToInputBufferP17sonicStreamStructPhi($0,$1,$2);var $tobool=((($call))|0)!=0;if($tobool){__label__=2;;}else{__label__=1;;}
if(__label__==2){var $3=$stream_addr;var $call1=__ZL18processStreamInputP17sonicStreamStruct($3);$retval=$call1;;}
else if(__label__==1){$retval=0;;}
var $4=$retval;;return $4;return null;}
function __ZL35addUnsignedCharSamplesToInputBufferP17sonicStreamStructPhi($stream,$samples,$numSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $numSamples_addr;var $buffer;var $count;$stream_addr=$stream;$samples_addr=$samples;$numSamples_addr=$numSamples;var $0=$numSamples_addr;var $1=$stream_addr;var $numChannels=(($1+28)&4294967295);var $2=HEAP32[(($numChannels)>>2)];var $mul=((($2)*($0))&4294967295);$count=$mul;var $3=$numSamples_addr;var $cmp=((($3))|0)==0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $4=$stream_addr;var $5=$numSamples_addr;var $call=__ZL26enlargeInputBufferIfNeededP17sonicStreamStructi($4,$5);var $tobool=((($call))|0)!=0;if($tobool){__label__=4;;}else{__label__=3;;}
if(__label__==4){var $6=$stream_addr;var $inputBuffer=(($6)&4294967295);var $7=HEAP32[(($inputBuffer)>>2)];var $8=$stream_addr;var $numInputSamples=(($8+44)&4294967295);var $9=HEAP32[(($numInputSamples)>>2)];var $10=$stream_addr;var $numChannels3=(($10+28)&4294967295);var $11=HEAP32[(($numChannels3)>>2)];var $mul4=((($11)*($9))&4294967295);var $add_ptr=(($7+2*$mul4)&4294967295);$buffer=$add_ptr;var $12=$count;var $dec1=((($12)-1)&4294967295);$count=$dec1;var $tobool52=((($12))|0)!=0;if($tobool52){__label__=5;;}else{__label__=6;;}
$while_body$$while_end$7:do{if(__label__==5){while(1){var $13=$samples_addr;var $incdec_ptr=(($13+1)&4294967295);$samples_addr=$incdec_ptr;var $14=HEAPU8[($13)];var $conv=((($14))&255);var $sub=((($conv)-128)&4294967295);var $shl=($sub)<<8;var $conv6=((($shl))&65535);var $15=$buffer;var $incdec_ptr7=(($15+2)&4294967295);$buffer=$incdec_ptr7;HEAP16[(($15)>>1)]=$conv6;var $16=$count;var $dec=((($16)-1)&4294967295);$count=$dec;var $tobool5=((($16))|0)!=0;if($tobool5){__label__=5;continue;}else{__label__=6;break $while_body$$while_end$7;}}}}while(0);var $17=$numSamples_addr;var $18=$stream_addr;var $numInputSamples8=(($18+44)&4294967295);var $19=HEAP32[(($numInputSamples8)>>2)];var $add=((($19)+($17))&4294967295);HEAP32[(($numInputSamples8)>>2)]=$add;$retval=1;;}
else if(__label__==3){$retval=0;;}}
var $20=$retval;;return $20;return null;}
function _sonicChangeFloatSpeed($samples,$numSamples,$speed,$pitch,$volume,$sampleRate,$numChannels){;var __label__;var $samples_addr;var $numSamples_addr;var $speed_addr;var $pitch_addr;var $volume_addr;var $sampleRate_addr;var $numChannels_addr;var $stream;$samples_addr=$samples;$numSamples_addr=$numSamples;$speed_addr=$speed;$pitch_addr=$pitch;$volume_addr=$volume;$sampleRate_addr=$sampleRate;$numChannels_addr=$numChannels;var $0=$sampleRate_addr;var $1=$numChannels_addr;var $call=_sonicCreateStream($0,$1);$stream=$call;var $2=$stream;var $3=$speed_addr;_sonicSetSpeed($2,$3);var $4=$stream;var $5=$pitch_addr;_sonicSetPitch($4,$5);var $6=$stream;var $7=$volume_addr;_sonicSetVolume($6,$7);var $8=$stream;var $9=$samples_addr;var $10=$numSamples_addr;var $call1=_sonicWriteFloatToStream($8,$9,$10);var $11=$stream;var $call2=_sonicFlushStream($11);var $12=$stream;var $call3=_sonicSamplesAvailable($12);$numSamples_addr=$call3;var $13=$stream;var $14=$samples_addr;var $15=$numSamples_addr;var $call4=_sonicReadFloatFromStream($13,$14,$15);var $16=$stream;_sonicDestroyStream($16);var $17=$numSamples_addr;;return $17;return null;}
function _sonicChangeShortSpeed($samples,$numSamples,$speed,$pitch,$volume,$sampleRate,$numChannels){;var __label__;var $samples_addr;var $numSamples_addr;var $speed_addr;var $pitch_addr;var $volume_addr;var $sampleRate_addr;var $numChannels_addr;var $stream;$samples_addr=$samples;$numSamples_addr=$numSamples;$speed_addr=$speed;$pitch_addr=$pitch;$volume_addr=$volume;$sampleRate_addr=$sampleRate;$numChannels_addr=$numChannels;var $0=$sampleRate_addr;var $1=$numChannels_addr;var $call=_sonicCreateStream($0,$1);$stream=$call;var $2=$stream;var $3=$speed_addr;_sonicSetSpeed($2,$3);var $4=$stream;var $5=$pitch_addr;_sonicSetPitch($4,$5);var $6=$stream;var $7=$volume_addr;_sonicSetVolume($6,$7);var $8=$stream;var $9=$samples_addr;var $10=$numSamples_addr;var $call1=_sonicWriteShortToStream($8,$9,$10);var $11=$stream;var $call2=_sonicFlushStream($11);var $12=$stream;var $call3=_sonicSamplesAvailable($12);$numSamples_addr=$call3;var $13=$stream;var $14=$samples_addr;var $15=$numSamples_addr;var $call4=_sonicReadShortFromStream($13,$14,$15);var $16=$stream;_sonicDestroyStream($16);var $17=$numSamples_addr;;return $17;return null;}
function __ZL26enlargeInputBufferIfNeededP17sonicStreamStructi($stream,$numSamples){;var __label__;var $retval;var $stream_addr;var $numSamples_addr;$stream_addr=$stream;$numSamples_addr=$numSamples;var $0=$stream_addr;var $numInputSamples=(($0+44)&4294967295);var $1=HEAP32[(($numInputSamples)>>2)];var $2=$numSamples_addr;var $add=((($2)+($1))&4294967295);var $3=$stream_addr;var $inputBufferSize=(($3+32)&4294967295);var $4=HEAP32[(($inputBufferSize)>>2)];var $cmp=((($add))|0)>((($4))|0);if($cmp){__label__=1;;}else{__label__=3;;}
$if_then$$if_end11$2:do{if(__label__==1){var $5=$stream_addr;var $inputBufferSize1=(($5+32)&4294967295);var $6=HEAP32[(($inputBufferSize1)>>2)];var $shr=($6)>>1;var $7=$numSamples_addr;var $8=$stream_addr;var $inputBufferSize3=(($8+32)&4294967295);var $9=HEAP32[(($inputBufferSize3)>>2)];var $add2=((($shr)+($7))&4294967295);var $add4=((($add2)+($9))&4294967295);HEAP32[(($inputBufferSize3)>>2)]=$add4;var $10=$stream_addr;var $inputBuffer=(($10)&4294967295);var $11=HEAP32[(($inputBuffer)>>2)];var $12=$11;var $13=$stream_addr;var $inputBufferSize5=(($13+32)&4294967295);var $14=HEAP32[(($inputBufferSize5)>>2)];var $15=$stream_addr;var $numChannels=(($15+28)&4294967295);var $16=HEAP32[(($numChannels)>>2)];var $mul=((($14)*2)&4294967295);var $mul6=((($mul)*($16))&4294967295);var $call=_realloc($12,$mul6);var $17=$call;var $18=$stream_addr;var $inputBuffer7=(($18)&4294967295);HEAP32[(($inputBuffer7)>>2)]=$17;var $19=$stream_addr;var $inputBuffer8=(($19)&4294967295);var $20=HEAP32[(($inputBuffer8)>>2)];var $cmp9=((($20))|0)==0;if(!($cmp9)){__label__=3;break $if_then$$if_end11$2;}
$retval=0;__label__=4;break $if_then$$if_end11$2;}}while(0);if(__label__==3){$retval=1;;}
var $21=$retval;;return $21;return null;}
function __ZL11changeSpeedP17sonicStreamStructf($stream,$speed){;var __label__;var __lastLabel__=null;var $retval;var $stream_addr;var $speed_addr;var $samples;var $numSamples;var $position;var $period;var $newSamples;var $maxRequired;$stream_addr=$stream;$speed_addr=$speed;var $0=$stream_addr;var $numInputSamples=(($0+44)&4294967295);var $1=HEAP32[(($numInputSamples)>>2)];$numSamples=$1;$position=0;var $2=$stream_addr;var $maxRequired1=(($2+64)&4294967295);var $3=HEAP32[(($maxRequired1)>>2)];$maxRequired=$3;var $4=$stream_addr;var $numInputSamples2=(($4+44)&4294967295);var $5=HEAP32[(($numInputSamples2)>>2)];var $6=$maxRequired;var $cmp=((($5))|0)<((($6))|0);if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){while(1){var $7=$stream_addr;var $remainingInputToCopy=(($7+68)&4294967295);var $8=HEAP32[(($remainingInputToCopy)>>2)];var $cmp3=((($8))|0)>0;var $9=$stream_addr;if($cmp3){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $10=$position;var $call=__ZL17copyInputToOutputP17sonicStreamStructi($9,$10);$newSamples=$call;var $11=$newSamples;var $12=$position;var $add=((($12)+($11))&4294967295);$position=$add;__lastLabel__=3;;}
else if(__label__==4){var $inputBuffer=(($9)&4294967295);var $13=HEAP32[(($inputBuffer)>>2)];var $14=$position;var $15=$stream_addr;var $numChannels=(($15+28)&4294967295);var $16=HEAP32[(($numChannels)>>2)];var $mul=((($16)*($14))&4294967295);var $add_ptr=(($13+2*$mul)&4294967295);$samples=$add_ptr;var $17=$stream_addr;var $18=$samples;var $call5=__ZL15findPitchPeriodP17sonicStreamStructPs($17,$18);$period=$call5;var $19=$speed_addr;var $conv=($19);var $cmp6=($conv)>1;var $20=$stream_addr;var $21=$samples;var $22=$speed_addr;var $23=$period;if($cmp6){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $call8=__ZL15skipPitchPeriodP17sonicStreamStructPsfi($20,$21,$22,$23);$newSamples=$call8;var $24=$period;var $25=$newSamples;var $26=$position;var $add9=((($25)+($24))&4294967295);var $add10=((($add9)+($26))&4294967295);$position=$add10;__lastLabel__=5;;}
else if(__label__==6){var $call12=__ZL17insertPitchPeriodP17sonicStreamStructPsfi($20,$21,$22,$23);$newSamples=$call12;var $27=$newSamples;var $28=$position;var $add13=((($28)+($27))&4294967295);$position=$add13;__lastLabel__=6;;}}
var $29=__lastLabel__==5?$25:(__lastLabel__==6?$27:($11));var $cmp16=((($29))|0)==0;if($cmp16){__label__=8;break;}
var $30=$position;var $31=$maxRequired;var $add19=((($31)+($30))&4294967295);var $32=$numSamples;var $cmp20=((($add19))|0)<=((($32))|0);if($cmp20){__label__=2;continue;}else{__label__=10;break;}}
if(__label__==8){$retval=0;;}
else if(__label__==10){var $33=$stream_addr;var $34=$position;__ZL18removeInputSamplesP17sonicStreamStructi($33,$34);$retval=1;;}};return;return;}
function __ZL12copyToOutputP17sonicStreamStructPsi($stream,$samples,$numSamples){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $numSamples_addr;$stream_addr=$stream;$samples_addr=$samples;$numSamples_addr=$numSamples;var $0=$stream_addr;var $1=$numSamples_addr;var $call=__ZL27enlargeOutputBufferIfNeededP17sonicStreamStructi($0,$1);var $tobool=((($call))|0)!=0;if($tobool){__label__=2;;}else{__label__=1;;}
if(__label__==2){var $2=$stream_addr;var $outputBuffer=(($2+4)&4294967295);var $3=HEAP32[(($outputBuffer)>>2)];var $4=$stream_addr;var $numOutputSamples=(($4+48)&4294967295);var $5=HEAP32[(($numOutputSamples)>>2)];var $6=$stream_addr;var $numChannels=(($6+28)&4294967295);var $7=HEAP32[(($numChannels)>>2)];var $mul=((($7)*($5))&4294967295);var $add_ptr=(($3+2*$mul)&4294967295);var $8=$add_ptr;var $9=$samples_addr;var $10=$9;var $11=$numSamples_addr;var $12=$stream_addr;var $numChannels2=(($12+28)&4294967295);var $13=HEAP32[(($numChannels2)>>2)];var $mul1=((($11)*2)&4294967295);var $mul3=((($mul1)*($13))&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$10;$dest$=$8;$stop$=$src$+$mul3;if(($dest$%4)==($src$%4)&&$mul3>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $14=$numSamples_addr;var $15=$stream_addr;var $numOutputSamples4=(($15+48)&4294967295);var $16=HEAP32[(($numOutputSamples4)>>2)];var $add=((($16)+($14))&4294967295);HEAP32[(($numOutputSamples4)>>2)]=$add;var $17=$numSamples_addr;$retval=$17;;}
else if(__label__==1){$retval=0;;}
var $18=$retval;;return $18;return null;}
function __ZL11adjustPitchP17sonicStreamStructi($stream,$originalNumOutputSamples){;var __label__;var $retval;var $stream_addr;var $originalNumOutputSamples_addr;var $pitch;var $numChannels;var $period;var $newPeriod;var $separation;var $position;var $out;var $rampDown;var $rampUp;$stream_addr=$stream;$originalNumOutputSamples_addr=$originalNumOutputSamples;var $0=$stream_addr;var $pitch1=(($0+24)&4294967295);var $1=HEAPF32[(($pitch1)>>2)];$pitch=$1;var $2=$stream_addr;var $numChannels2=(($2+28)&4294967295);var $3=HEAP32[(($numChannels2)>>2)];$numChannels=$3;$position=0;var $4=$stream_addr;var $numOutputSamples=(($4+48)&4294967295);var $5=HEAP32[(($numOutputSamples)>>2)];var $6=$originalNumOutputSamples_addr;var $cmp=((($5))|0)==((($6))|0);if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){$retval=1;;}
else if(__label__==2){var $7=$stream_addr;var $8=$originalNumOutputSamples_addr;var $call=__ZL27moveNewSamplesToPitchBufferP17sonicStreamStructi($7,$8);var $tobool=((($call))|0)!=0;if($tobool){__label__=4;;}else{__label__=3;;}
if(__label__==4){while(1){var $9=$stream_addr;var $numPitchSamples=(($9+52)&4294967295);var $10=HEAP32[(($numPitchSamples)>>2)];var $11=$position;var $sub=((($10)-($11))&4294967295);var $12=$stream_addr;var $maxRequired=(($12+64)&4294967295);var $13=HEAP32[(($maxRequired)>>2)];var $cmp5=((($sub))|0)>=((($13))|0);var $14=$stream_addr;if(!($cmp5)){__label__=11;break;}
var $15=$stream_addr;var $pitchBuffer=(($15+8)&4294967295);var $16=HEAP32[(($pitchBuffer)>>2)];var $17=$position;var $18=$numChannels;var $mul=((($18)*($17))&4294967295);var $add_ptr=(($16+2*$mul)&4294967295);var $call6=__ZL15findPitchPeriodP17sonicStreamStructPs($14,$add_ptr);$period=$call6;var $19=$period;var $conv=((($19))|0);var $20=$pitch;var $div=($conv)/($20);var $conv7=((($div))|0);$newPeriod=$conv7;var $21=$stream_addr;var $22=$newPeriod;var $call8=__ZL27enlargeOutputBufferIfNeededP17sonicStreamStructi($21,$22);var $tobool9=((($call8))|0)!=0;if(!($tobool9)){__label__=6;break;}
var $23=$stream_addr;var $outputBuffer=(($23+4)&4294967295);var $24=HEAP32[(($outputBuffer)>>2)];var $25=$stream_addr;var $numOutputSamples12=(($25+48)&4294967295);var $26=HEAP32[(($numOutputSamples12)>>2)];var $27=$numChannels;var $mul13=((($27)*($26))&4294967295);var $add_ptr14=(($24+2*$mul13)&4294967295);$out=$add_ptr14;var $28=$pitch;var $cmp15=($28)>=1;var $29=$stream_addr;var $pitchBuffer17=(($29+8)&4294967295);var $30=HEAP32[(($pitchBuffer17)>>2)];var $31=$position;var $32=$numChannels;var $mul18=((($32)*($31))&4294967295);var $add_ptr19=(($30+2*$mul18)&4294967295);$rampDown=$add_ptr19;var $33=$stream_addr;var $pitchBuffer20=(($33+8)&4294967295);var $34=HEAP32[(($pitchBuffer20)>>2)];var $35=$position;if($cmp15){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $36=$period;var $37=$newPeriod;var $_neg=(((-($37)))&4294967295);var $add=((($36)+($35))&4294967295);var $sub21=((($add)+($_neg))&4294967295);var $38=$numChannels;var $mul22=((($sub21)*($38))&4294967295);var $add_ptr23=(($34+2*$mul22)&4294967295);$rampUp=$add_ptr23;var $39=$newPeriod;var $40=$numChannels;var $41=$out;var $42=$rampDown;var $43=$rampUp;__ZL10overlapAddiiPsS_S_($39,$40,$41,$42,$43);;}
else if(__label__==9){var $44=$numChannels;var $mul28=((($44)*($35))&4294967295);var $add_ptr29=(($34+2*$mul28)&4294967295);$rampUp=$add_ptr29;var $45=$newPeriod;var $46=$period;var $sub30=((($45)-($46))&4294967295);$separation=$sub30;var $47=$period;var $48=$numChannels;var $49=$separation;var $50=$out;var $51=$rampDown;var $52=$rampUp;__ZL24overlapAddWithSeparationiiiPsS_S_($47,$48,$49,$50,$51,$52);;}
var $53=$newPeriod;var $54=$stream_addr;var $numOutputSamples32=(($54+48)&4294967295);var $55=HEAP32[(($numOutputSamples32)>>2)];var $add33=((($55)+($53))&4294967295);HEAP32[(($numOutputSamples32)>>2)]=$add33;var $56=$period;var $57=$position;var $add34=((($57)+($56))&4294967295);$position=$add34;__label__=4;continue;}
if(__label__==11){var $58=$position;__ZL18removePitchSamplesP17sonicStreamStructi($14,$58);$retval=1;;}
else if(__label__==6){$retval=0;;}}
else if(__label__==3){$retval=0;;}}
var $59=$retval;;return $59;return null;}
function __ZL12scaleSamplesPsif($samples,$numSamples,$volume){;var __label__;var $samples_addr;var $numSamples_addr;var $volume_addr;var $fixedPointVolume;var $value;$samples_addr=$samples;$numSamples_addr=$numSamples;$volume_addr=$volume;var $0=$volume_addr;var $mul=($0)*4096;var $conv=((($mul))|0);$fixedPointVolume=$conv;var $1=$numSamples_addr;var $dec1=((($1)-1)&4294967295);$numSamples_addr=$dec1;var $tobool2=((($1))|0)!=0;if($tobool2){__label__=1;;}else{__label__=6;;}
$while_body$$while_end$2:do{if(__label__==1){$while_body$3:while(1){var $2=$samples_addr;var $3=HEAP16[(($2)>>1)];var $conv1=(tempInt=(($3)),(tempInt>=32768?tempInt-65536:tempInt));var $4=$fixedPointVolume;var $mul2=((($conv1)*($4))&4294967295);var $shr=($mul2)>>12;$value=$shr;var $cmp=((($shr))|0)>32767;if($cmp){__label__=2;;}else{__label__=3;;}
$if_then$$if_else$5:do{if(__label__==2){$value=32767;;}
else if(__label__==3){var $5=$value;var $cmp3=((($5))|0)<-32767;if(!($cmp3)){__label__=5;break $if_then$$if_else$5;}
$value=-32767;;}}while(0);var $6=$value;var $conv6=((($6))&65535);var $7=$samples_addr;var $incdec_ptr=(($7+2)&4294967295);$samples_addr=$incdec_ptr;HEAP16[(($7)>>1)]=$conv6;var $8=$numSamples_addr;var $dec=((($8)-1)&4294967295);$numSamples_addr=$dec;var $tobool=((($8))|0)!=0;if($tobool){__label__=1;continue $while_body$3;}else{__label__=6;break $while_body$$while_end$2;}}}}while(0);;return;return;}
function __ZL27moveNewSamplesToPitchBufferP17sonicStreamStructi($stream,$originalNumOutputSamples){;var __label__;var $retval;var $stream_addr;var $originalNumOutputSamples_addr;var $numSamples;var $numChannels;$stream_addr=$stream;$originalNumOutputSamples_addr=$originalNumOutputSamples;var $0=$stream_addr;var $numOutputSamples=(($0+48)&4294967295);var $1=HEAP32[(($numOutputSamples)>>2)];var $2=$originalNumOutputSamples_addr;var $sub=((($1)-($2))&4294967295);$numSamples=$sub;var $3=$stream_addr;var $numChannels1=(($3+28)&4294967295);var $4=HEAP32[(($numChannels1)>>2)];$numChannels=$4;var $5=$stream_addr;var $numPitchSamples=(($5+52)&4294967295);var $6=HEAP32[(($numPitchSamples)>>2)];var $7=$numSamples;var $add=((($7)+($6))&4294967295);var $8=$stream_addr;var $pitchBufferSize=(($8+36)&4294967295);var $9=HEAP32[(($pitchBufferSize)>>2)];var $cmp=((($add))|0)>((($9))|0);if($cmp){__label__=1;;}else{__label__=3;;}
$if_then$$if_end12$2:do{if(__label__==1){var $10=$stream_addr;var $pitchBufferSize2=(($10+36)&4294967295);var $11=HEAP32[(($pitchBufferSize2)>>2)];var $shr=($11)>>1;var $12=$numSamples;var $13=$stream_addr;var $pitchBufferSize4=(($13+36)&4294967295);var $14=HEAP32[(($pitchBufferSize4)>>2)];var $add3=((($shr)+($12))&4294967295);var $add5=((($add3)+($14))&4294967295);HEAP32[(($pitchBufferSize4)>>2)]=$add5;var $15=$stream_addr;var $pitchBuffer=(($15+8)&4294967295);var $16=HEAP32[(($pitchBuffer)>>2)];var $17=$16;var $18=$stream_addr;var $pitchBufferSize6=(($18+36)&4294967295);var $19=HEAP32[(($pitchBufferSize6)>>2)];var $20=$numChannels;var $mul=((($19)*2)&4294967295);var $mul7=((($mul)*($20))&4294967295);var $call=_realloc($17,$mul7);var $21=$call;var $22=$stream_addr;var $pitchBuffer8=(($22+8)&4294967295);HEAP32[(($pitchBuffer8)>>2)]=$21;var $23=$stream_addr;var $pitchBuffer9=(($23+8)&4294967295);var $24=HEAP32[(($pitchBuffer9)>>2)];var $cmp10=((($24))|0)==0;if(!($cmp10)){__label__=3;break $if_then$$if_end12$2;}
$retval=0;__label__=4;break $if_then$$if_end12$2;}}while(0);if(__label__==3){var $25=$stream_addr;var $pitchBuffer13=(($25+8)&4294967295);var $26=HEAP32[(($pitchBuffer13)>>2)];var $27=$stream_addr;var $numPitchSamples14=(($27+52)&4294967295);var $28=HEAP32[(($numPitchSamples14)>>2)];var $29=$numChannels;var $mul15=((($29)*($28))&4294967295);var $add_ptr=(($26+2*$mul15)&4294967295);var $30=$add_ptr;var $31=$stream_addr;var $outputBuffer=(($31+4)&4294967295);var $32=HEAP32[(($outputBuffer)>>2)];var $33=$originalNumOutputSamples_addr;var $34=$numChannels;var $mul16=((($34)*($33))&4294967295);var $add_ptr17=(($32+2*$mul16)&4294967295);var $35=$add_ptr17;var $36=$numSamples;var $37=$numChannels;var $mul18=((($36)*2)&4294967295);var $mul19=((($mul18)*($37))&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$35;$dest$=$30;$stop$=$src$+$mul19;if(($dest$%4)==($src$%4)&&$mul19>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $38=$originalNumOutputSamples_addr;var $39=$stream_addr;var $numOutputSamples20=(($39+48)&4294967295);HEAP32[(($numOutputSamples20)>>2)]=$38;var $40=$numSamples;var $41=$stream_addr;var $numPitchSamples21=(($41+52)&4294967295);var $42=HEAP32[(($numPitchSamples21)>>2)];var $add22=((($42)+($40))&4294967295);HEAP32[(($numPitchSamples21)>>2)]=$add22;$retval=1;;}
var $43=$retval;;return $43;return null;}
function __ZL15findPitchPeriodP17sonicStreamStructPs($stream,$samples){var __stackBase__=STACKTOP;STACKTOP+=8;_memset(__stackBase__,0,8);var __label__;var $stream_addr;var $samples_addr;var $minPeriod;var $maxPeriod;var $sampleRate;var $minDiff=__stackBase__;var $maxDiff=__stackBase__+4;var $retPeriod;var $skip;var $period;$stream_addr=$stream;$samples_addr=$samples;var $0=$stream_addr;var $minPeriod1=(($0+56)&4294967295);var $1=HEAP32[(($minPeriod1)>>2)];$minPeriod=$1;var $2=$stream_addr;var $maxPeriod2=(($2+60)&4294967295);var $3=HEAP32[(($maxPeriod2)>>2)];$maxPeriod=$3;var $4=$stream_addr;var $sampleRate3=(($4+72)&4294967295);var $5=HEAP32[(($sampleRate3)>>2)];$sampleRate=$5;$skip=1;var $6=$sampleRate;var $cmp=((($6))|0)>4000;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $7=$sampleRate;var $div=((((($7))|0)/4000)|0);$skip=$div;;}
var $8=$stream_addr;var $numChannels=(($8+28)&4294967295);var $9=HEAP32[(($numChannels)>>2)];var $cmp4=((($9))|0)==1;if($cmp4){__label__=3;;}else{__label__=5;;}
$land_lhs_true$$if_else$5:do{if(__label__==3){var $10=$skip;var $cmp5=((($10))|0)==1;if(!($cmp5)){__label__=5;break $land_lhs_true$$if_else$5;}
var $11=$samples_addr;var $12=$minPeriod;var $13=$maxPeriod;var $call=__ZL22findPitchPeriodInRangePsiiPiS0_($11,$12,$13,$minDiff,$maxDiff);$period=$call;__label__=13;break $land_lhs_true$$if_else$5;}}while(0);$if_end32$$if_else$8:do{if(__label__==5){var $14=$stream_addr;var $15=$samples_addr;var $16=$skip;__ZL15downSampleInputP17sonicStreamStructPsi($14,$15,$16);var $17=$stream_addr;var $downSampleBuffer=(($17+12)&4294967295);var $18=HEAP32[(($downSampleBuffer)>>2)];var $19=$minPeriod;var $20=$skip;var $div7=((((($19))|0)/((($20))|0))|0);var $21=$maxPeriod;var $22=$skip;var $div8=((((($21))|0)/((($22))|0))|0);var $call9=__ZL22findPitchPeriodInRangePsiiPiS0_($18,$div7,$div8,$minDiff,$maxDiff);$period=$call9;var $23=$skip;var $cmp10=((($23))|0)!=1;if(!($cmp10)){__label__=13;break $if_end32$$if_else$8;}
var $24=$skip;var $25=$period;var $mul=((($25)*($24))&4294967295);$period=$mul;var $26=$period;var $27=$skip;var $shl=($27)<<2;var $sub=((($26)-($shl))&4294967295);$minPeriod=$sub;var $28=$period;var $29=$skip;var $shl12=((($29)*4)&4294967295);var $add=((($shl12)+($28))&4294967295);$maxPeriod=$add;var $30=$minPeriod;var $31=$stream_addr;var $minPeriod13=(($31+56)&4294967295);var $32=HEAP32[(($minPeriod13)>>2)];var $cmp14=((($30))|0)<((($32))|0);if($cmp14){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $33=$stream_addr;var $minPeriod16=(($33+56)&4294967295);var $34=HEAP32[(($minPeriod16)>>2)];$minPeriod=$34;;}
var $35=$maxPeriod;var $36=$stream_addr;var $maxPeriod18=(($36+60)&4294967295);var $37=HEAP32[(($maxPeriod18)>>2)];var $cmp19=((($35))|0)>((($37))|0);if($cmp19){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $38=$stream_addr;var $maxPeriod21=(($38+60)&4294967295);var $39=HEAP32[(($maxPeriod21)>>2)];$maxPeriod=$39;;}
var $40=$stream_addr;var $numChannels23=(($40+28)&4294967295);var $41=HEAP32[(($numChannels23)>>2)];var $cmp24=((($41))|0)==1;if($cmp24){__label__=11;;}else{__label__=12;;}
if(__label__==11){var $42=$samples_addr;var $43=$minPeriod;var $44=$maxPeriod;var $call26=__ZL22findPitchPeriodInRangePsiiPiS0_($42,$43,$44,$minDiff,$maxDiff);$period=$call26;;}
else if(__label__==12){var $45=$stream_addr;var $46=$samples_addr;__ZL15downSampleInputP17sonicStreamStructPsi($45,$46,1);var $47=$stream_addr;var $downSampleBuffer28=(($47+12)&4294967295);var $48=HEAP32[(($downSampleBuffer28)>>2)];var $49=$minPeriod;var $50=$maxPeriod;var $call29=__ZL22findPitchPeriodInRangePsiiPiS0_($48,$49,$50,$minDiff,$maxDiff);$period=$call29;;}}}while(0);var $51=$stream_addr;var $52=$period;var $53=HEAP32[(($minDiff)>>2)];var $54=HEAP32[(($maxDiff)>>2)];var $call33=__ZL16prevPeriodBetterP17sonicStreamStructiii($51,$52,$53,$54);var $tobool=((($call33))|0)!=0;if($tobool){__label__=14;;}else{__label__=15;;}
if(__label__==14){var $55=$stream_addr;var $prevPeriod=(($55+76)&4294967295);var $56=HEAP32[(($prevPeriod)>>2)];$retPeriod=$56;;}
else if(__label__==15){var $57=$period;$retPeriod=$57;;}
var $58=HEAP32[(($minDiff)>>2)];var $59=$stream_addr;var $prevMinDiff=(($59+84)&4294967295);HEAP32[(($prevMinDiff)>>2)]=$58;var $60=HEAP32[(($maxDiff)>>2)];var $61=$stream_addr;var $prevMaxDiff=(($61+80)&4294967295);HEAP32[(($prevMaxDiff)>>2)]=$60;var $62=$period;var $63=$stream_addr;var $prevPeriod37=(($63+76)&4294967295);HEAP32[(($prevPeriod37)>>2)]=$62;var $64=$retPeriod;STACKTOP=__stackBase__;return $64;return null;}
function __ZL27enlargeOutputBufferIfNeededP17sonicStreamStructi($stream,$numSamples){;var __label__;var $retval;var $stream_addr;var $numSamples_addr;$stream_addr=$stream;$numSamples_addr=$numSamples;var $0=$stream_addr;var $numOutputSamples=(($0+48)&4294967295);var $1=HEAP32[(($numOutputSamples)>>2)];var $2=$numSamples_addr;var $add=((($2)+($1))&4294967295);var $3=$stream_addr;var $outputBufferSize=(($3+40)&4294967295);var $4=HEAP32[(($outputBufferSize)>>2)];var $cmp=((($add))|0)>((($4))|0);if($cmp){__label__=1;;}else{__label__=3;;}
$if_then$$if_end11$2:do{if(__label__==1){var $5=$stream_addr;var $outputBufferSize1=(($5+40)&4294967295);var $6=HEAP32[(($outputBufferSize1)>>2)];var $shr=($6)>>1;var $7=$numSamples_addr;var $8=$stream_addr;var $outputBufferSize3=(($8+40)&4294967295);var $9=HEAP32[(($outputBufferSize3)>>2)];var $add2=((($shr)+($7))&4294967295);var $add4=((($add2)+($9))&4294967295);HEAP32[(($outputBufferSize3)>>2)]=$add4;var $10=$stream_addr;var $outputBuffer=(($10+4)&4294967295);var $11=HEAP32[(($outputBuffer)>>2)];var $12=$11;var $13=$stream_addr;var $outputBufferSize5=(($13+40)&4294967295);var $14=HEAP32[(($outputBufferSize5)>>2)];var $15=$stream_addr;var $numChannels=(($15+28)&4294967295);var $16=HEAP32[(($numChannels)>>2)];var $mul=((($14)*2)&4294967295);var $mul6=((($mul)*($16))&4294967295);var $call=_realloc($12,$mul6);var $17=$call;var $18=$stream_addr;var $outputBuffer7=(($18+4)&4294967295);HEAP32[(($outputBuffer7)>>2)]=$17;var $19=$stream_addr;var $outputBuffer8=(($19+4)&4294967295);var $20=HEAP32[(($outputBuffer8)>>2)];var $cmp9=((($20))|0)==0;if(!($cmp9)){__label__=3;break $if_then$$if_end11$2;}
$retval=0;__label__=4;break $if_then$$if_end11$2;}}while(0);if(__label__==3){$retval=1;;}
var $21=$retval;;return $21;return null;}
function __ZL10overlapAddiiPsS_S_($numSamples,$numChannels,$out,$rampDown,$rampUp){;var __label__;var $numSamples_addr;var $numChannels_addr;var $out_addr;var $rampDown_addr;var $rampUp_addr;var $o;var $u;var $d;var $i;var $t;$numSamples_addr=$numSamples;$numChannels_addr=$numChannels;$out_addr=$out;$rampDown_addr=$rampDown;$rampUp_addr=$rampUp;$i=0;var $0=$i;var $1=$numChannels_addr;var $cmp2=((($0))|0)<((($1))|0);if($cmp2){__label__=1;;}else{__label__=4;;}
$for_body$$for_end14$2:do{if(__label__==1){$for_body$3:while(1){var $2=$out_addr;var $3=$i;var $add_ptr=(($2+2*$3)&4294967295);$o=$add_ptr;var $4=$rampUp_addr;var $5=$i;var $add_ptr1=(($4+2*$5)&4294967295);$u=$add_ptr1;var $6=$rampDown_addr;var $7=$i;var $add_ptr2=(($6+2*$7)&4294967295);$d=$add_ptr2;$t=0;var $8=$t;var $9=$numSamples_addr;var $cmp41=((($8))|0)<((($9))|0);if($cmp41){__label__=2;;}else{__label__=3;;}
$for_body5$$for_inc12$5:do{if(__label__==2){while(1){var $10=$d;var $11=HEAP16[(($10)>>1)];var $conv=(tempInt=(($11)),(tempInt>=32768?tempInt-65536:tempInt));var $12=$numSamples_addr;var $13=$t;var $sub=((($12)-($13))&4294967295);var $mul=((($sub)*($conv))&4294967295);var $14=$u;var $15=HEAP16[(($14)>>1)];var $conv6=(tempInt=(($15)),(tempInt>=32768?tempInt-65536:tempInt));var $16=$t;var $mul7=((($conv6)*($16))&4294967295);var $add=((($mul7)+($mul))&4294967295);var $17=$numSamples_addr;var $div=((((($add))|0)/((($17))|0))|0);var $conv8=((($div))&65535);var $18=$o;HEAP16[(($18)>>1)]=$conv8;var $19=$numChannels_addr;var $20=$o;var $add_ptr9=(($20+2*$19)&4294967295);$o=$add_ptr9;var $21=$numChannels_addr;var $22=$d;var $add_ptr10=(($22+2*$21)&4294967295);$d=$add_ptr10;var $23=$numChannels_addr;var $24=$u;var $add_ptr11=(($24+2*$23)&4294967295);$u=$add_ptr11;var $25=$t;var $inc=((($25)+1)&4294967295);$t=$inc;var $26=$t;var $27=$numSamples_addr;var $cmp4=((($26))|0)<((($27))|0);if($cmp4){__label__=2;continue;}else{__label__=3;break $for_body5$$for_inc12$5;}}}}while(0);var $28=$i;var $inc13=((($28)+1)&4294967295);$i=$inc13;var $29=$i;var $30=$numChannels_addr;var $cmp=((($29))|0)<((($30))|0);if($cmp){__label__=1;continue $for_body$3;}else{__label__=4;break $for_body$$for_end14$2;}}}}while(0);;return;return;}
function __ZL24overlapAddWithSeparationiiiPsS_S_($numSamples,$numChannels,$separation,$out,$rampDown,$rampUp){;var __label__;var $numSamples_addr;var $numChannels_addr;var $separation_addr;var $out_addr;var $rampDown_addr;var $rampUp_addr;var $o;var $u;var $d;var $i;var $t;$numSamples_addr=$numSamples;$numChannels_addr=$numChannels;$separation_addr=$separation;$out_addr=$out;$rampDown_addr=$rampDown;$rampUp_addr=$rampUp;$i=0;var $0=$i;var $1=$numChannels_addr;var $cmp3=((($0))|0)<((($1))|0);if($cmp3){__label__=1;;}else{__label__=9;;}
$for_body$$for_end33$2:do{if(__label__==1){$for_body$3:while(1){var $2=$out_addr;var $3=$i;var $add_ptr=(($2+2*$3)&4294967295);$o=$add_ptr;var $4=$rampUp_addr;var $5=$i;var $add_ptr1=(($4+2*$5)&4294967295);$u=$add_ptr1;var $6=$rampDown_addr;var $7=$i;var $add_ptr2=(($6+2*$7)&4294967295);$d=$add_ptr2;$t=0;var $8=$t;var $9=$numSamples_addr;var $10=$separation_addr;var $add1=((($10)+($9))&4294967295);var $cmp42=((($8))|0)<((($add1))|0);if($cmp42){__label__=2;;}else{__label__=8;;}
$for_body5$$for_inc31$5:do{if(__label__==2){while(1){var $11=$t;var $12=$separation_addr;var $cmp6=((($11))|0)<((($12))|0);if($cmp6){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $13=$d;var $14=HEAP16[(($13)>>1)];var $conv=(tempInt=(($14)),(tempInt>=32768?tempInt-65536:tempInt));var $15=$numSamples_addr;var $16=$t;var $sub=((($15)-($16))&4294967295);var $mul=((($sub)*($conv))&4294967295);var $17=$numSamples_addr;var $div=((((($mul))|0)/((($17))|0))|0);var $conv7=((($div))&65535);var $18=$o;HEAP16[(($18)>>1)]=$conv7;var $19=$numChannels_addr;var $20=$d;var $add_ptr8=(($20+2*$19)&4294967295);$d=$add_ptr8;;}
else if(__label__==4){var $21=$t;var $22=$numSamples_addr;var $cmp9=((($21))|0)<((($22))|0);if($cmp9){__label__=5;;}else{__label__=6;;}
if(__label__==5){var $23=$d;var $24=HEAP16[(($23)>>1)];var $conv11=(tempInt=(($24)),(tempInt>=32768?tempInt-65536:tempInt));var $25=$numSamples_addr;var $26=$t;var $sub12=((($25)-($26))&4294967295);var $mul13=((($sub12)*($conv11))&4294967295);var $27=$u;var $28=HEAP16[(($27)>>1)];var $conv14=(tempInt=(($28)),(tempInt>=32768?tempInt-65536:tempInt));var $29=$t;var $30=$separation_addr;var $sub15=((($29)-($30))&4294967295);var $mul16=((($sub15)*($conv14))&4294967295);var $add17=((($mul16)+($mul13))&4294967295);var $31=$numSamples_addr;var $div18=((((($add17))|0)/((($31))|0))|0);var $conv19=((($div18))&65535);var $32=$o;HEAP16[(($32)>>1)]=$conv19;var $33=$numChannels_addr;var $34=$d;var $add_ptr20=(($34+2*$33)&4294967295);$d=$add_ptr20;var $35=$numChannels_addr;var $36=$u;var $add_ptr21=(($36+2*$35)&4294967295);$u=$add_ptr21;;}
else if(__label__==6){var $37=$u;var $38=HEAP16[(($37)>>1)];var $conv23=(tempInt=(($38)),(tempInt>=32768?tempInt-65536:tempInt));var $39=$t;var $40=$separation_addr;var $sub24=((($39)-($40))&4294967295);var $mul25=((($sub24)*($conv23))&4294967295);var $41=$numSamples_addr;var $div26=((((($mul25))|0)/((($41))|0))|0);var $conv27=((($div26))&65535);var $42=$o;HEAP16[(($42)>>1)]=$conv27;var $43=$numChannels_addr;var $44=$u;var $add_ptr28=(($44+2*$43)&4294967295);$u=$add_ptr28;;}}
var $45=$numChannels_addr;var $46=$o;var $add_ptr30=(($46+2*$45)&4294967295);$o=$add_ptr30;var $47=$t;var $inc=((($47)+1)&4294967295);$t=$inc;var $48=$t;var $49=$numSamples_addr;var $50=$separation_addr;var $add=((($50)+($49))&4294967295);var $cmp4=((($48))|0)<((($add))|0);if($cmp4){__label__=2;continue;}else{__label__=8;break $for_body5$$for_inc31$5;}}}}while(0);var $51=$i;var $inc32=((($51)+1)&4294967295);$i=$inc32;var $52=$i;var $53=$numChannels_addr;var $cmp=((($52))|0)<((($53))|0);if($cmp){__label__=1;continue $for_body$3;}else{__label__=9;break $for_body$$for_end33$2;}}}}while(0);;return;return;}
function __ZL18removePitchSamplesP17sonicStreamStructi($stream,$numSamples){;var __label__;var $stream_addr;var $numSamples_addr;var $numChannels;var $source;$stream_addr=$stream;$numSamples_addr=$numSamples;var $0=$stream_addr;var $numChannels1=(($0+28)&4294967295);var $1=HEAP32[(($numChannels1)>>2)];$numChannels=$1;var $2=$stream_addr;var $pitchBuffer=(($2+8)&4294967295);var $3=HEAP32[(($pitchBuffer)>>2)];var $4=$numSamples_addr;var $5=$numChannels;var $mul=((($5)*($4))&4294967295);var $add_ptr=(($3+2*$mul)&4294967295);$source=$add_ptr;var $6=$numSamples_addr;var $cmp=((($6))|0)==0;if($cmp){__label__=4;;}else{__label__=1;;}
if(__label__==1){var $7=$numSamples_addr;var $8=$stream_addr;var $numPitchSamples=(($8+52)&4294967295);var $9=HEAP32[(($numPitchSamples)>>2)];var $cmp2=((($7))|0)!=((($9))|0);if($cmp2){__label__=2;;}else{__label__=3;;}
if(__label__==2){var $10=$stream_addr;var $pitchBuffer4=(($10+8)&4294967295);var $11=HEAP32[(($pitchBuffer4)>>2)];var $12=$11;var $13=$source;var $14=$13;var $15=$stream_addr;var $numPitchSamples5=(($15+52)&4294967295);var $16=HEAP32[(($numPitchSamples5)>>2)];var $17=$numSamples_addr;var $sub=((($16)-($17))&4294967295);var $18=$numChannels;var $mul6=((($18)*2)&4294967295);var $mul7=((($mul6)*($sub))&4294967295);_llvm_memmove_p0i8_p0i8_i32($12,$14,$mul7,1,0);;}
var $19=$numSamples_addr;var $20=$stream_addr;var $numPitchSamples9=(($20+52)&4294967295);var $21=HEAP32[(($numPitchSamples9)>>2)];var $sub10=((($21)-($19))&4294967295);HEAP32[(($numPitchSamples9)>>2)]=$sub10;;};return;return;}
function __ZL22findPitchPeriodInRangePsiiPiS0_($samples,$minPeriod,$maxPeriod,$retMinDiff,$retMaxDiff){;var __label__;var __lastLabel__=null;var $samples_addr;var $minPeriod_addr;var $maxPeriod_addr;var $retMinDiff_addr;var $retMaxDiff_addr;var $period;var $bestPeriod;var $s;var $p;var $sVal;var $pVal;var $diff;var $minDiff;var $maxDiff;var $i;$samples_addr=$samples;$minPeriod_addr=$minPeriod;$maxPeriod_addr=$maxPeriod;$retMinDiff_addr=$retMinDiff;$retMaxDiff_addr=$retMaxDiff;$bestPeriod=0;$minDiff=1;$maxDiff=0;var $0=$minPeriod_addr;$period=$0;var $1=$period;var $2=$maxPeriod_addr;var $cmp3=((($1))|0)<=((($2))|0);if($cmp3){__label__=1;;}else{__label__=11;;}
$for_body$$for_end24$2:do{if(__label__==1){$for_body$3:while(1){$diff=0;var $3=$samples_addr;$s=$3;var $4=$samples_addr;var $5=$period;var $add_ptr=(($4+2*$5)&4294967295);$p=$add_ptr;$i=0;var $6=$i;var $7=$period;var $cmp21=((($6))|0)<((($7))|0);if($cmp21){__label__=2;;}else{__label__=6;;}
$for_body3$$for_end$5:do{if(__label__==2){while(1){var $8=$s;var $incdec_ptr=(($8+2)&4294967295);$s=$incdec_ptr;var $9=HEAP16[(($8)>>1)];$sVal=$9;var $10=$p;var $incdec_ptr4=(($10+2)&4294967295);$p=$incdec_ptr4;var $11=HEAP16[(($10)>>1)];$pVal=$11;var $12=$sVal;var $conv=(tempInt=(($12)),(tempInt>=32768?tempInt-65536:tempInt));var $13=$pVal;var $conv5=(tempInt=(($13)),(tempInt>=32768?tempInt-65536:tempInt));var $cmp6=((($conv))|0)>=((($conv5))|0);if($cmp6){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $14=$sVal;var $conv7=(tempInt=(($14)),(tempInt>=32768?tempInt-65536:tempInt));var $15=$pVal;var $conv8=(tempInt=(($15)),(tempInt>=32768?tempInt-65536:tempInt));var $sub=((($conv7)-($conv8))&4294967295);var $conv9=((($sub))&65535);__lastLabel__=3;;}
else if(__label__==4){var $16=$pVal;var $conv10=(tempInt=(($16)),(tempInt>=32768?tempInt-65536:tempInt));var $17=$sVal;var $conv11=(tempInt=(($17)),(tempInt>=32768?tempInt-65536:tempInt));var $sub12=((($conv10)-($conv11))&4294967295);var $conv13=((($sub12))&65535);__lastLabel__=4;;}
var $cond=__lastLabel__==3?$conv9:($conv13);var $conv14=((($cond))&65535);var $18=$diff;var $add=((($18)+($conv14))&4294967295);$diff=$add;var $19=$i;var $inc=((($19)+1)&4294967295);$i=$inc;var $20=$i;var $21=$period;var $cmp2=((($20))|0)<((($21))|0);if($cmp2){__label__=2;continue;}else{__label__=6;break $for_body3$$for_end$5;}}}}while(0);var $22=$diff;var $23=$bestPeriod;var $mul=((($23)*($22))&4294967295);var $24=$minDiff;var $25=$period;var $mul15=((($25)*($24))&4294967295);var $cmp16=((($mul))>>>0)<((($mul15))>>>0);if($cmp16){__label__=7;;}else{__label__=8;;}
if(__label__==7){var $26=$diff;$minDiff=$26;var $27=$period;$bestPeriod=$27;;}
var $28=$diff;var $29=$bestPeriod;var $mul17=((($29)*($28))&4294967295);var $30=$maxDiff;var $31=$period;var $mul18=((($31)*($30))&4294967295);var $cmp19=((($mul17))>>>0)>((($mul18))>>>0);if($cmp19){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $32=$diff;$maxDiff=$32;;}
var $33=$period;var $inc23=((($33)+1)&4294967295);$period=$inc23;var $34=$period;var $35=$maxPeriod_addr;var $cmp=((($34))|0)<=((($35))|0);if($cmp){__label__=1;continue $for_body$3;}else{__label__=11;break $for_body$$for_end24$2;}}}}while(0);var $36=$minDiff;var $37=$retMinDiff_addr;HEAP32[(($37)>>2)]=$36;var $38=$maxDiff;var $39=$retMaxDiff_addr;HEAP32[(($39)>>2)]=$38;var $40=$bestPeriod;;return $40;return null;}
function __ZL15downSampleInputP17sonicStreamStructPsi($stream,$samples,$skip){;var __label__;var $stream_addr;var $samples_addr;var $skip_addr;var $numSamples;var $samplesPerValue;var $i;var $j;var $value;var $downSamples;$stream_addr=$stream;$samples_addr=$samples;$skip_addr=$skip;var $0=$stream_addr;var $maxRequired=(($0+64)&4294967295);var $1=HEAP32[(($maxRequired)>>2)];var $2=$skip_addr;var $div=((((($1))|0)/((($2))|0))|0);$numSamples=$div;var $3=$stream_addr;var $numChannels=(($3+28)&4294967295);var $4=HEAP32[(($numChannels)>>2)];var $5=$skip_addr;var $mul=((($5)*($4))&4294967295);$samplesPerValue=$mul;var $6=$stream_addr;var $downSampleBuffer=(($6+12)&4294967295);var $7=HEAP32[(($downSampleBuffer)>>2)];$downSamples=$7;$i=0;var $8=$i;var $9=$numSamples;var $cmp3=((($8))|0)<((($9))|0);if($cmp3){__label__=1;;}else{__label__=4;;}
$for_body$$for_end9$2:do{if(__label__==1){$for_body$3:while(1){$value=0;$j=0;var $10=$j;var $11=$samplesPerValue;var $cmp21=((($10))|0)<((($11))|0);if($cmp21){__label__=2;;}else{__label__=3;;}
$for_body3$$for_end$5:do{if(__label__==2){while(1){var $12=$samples_addr;var $incdec_ptr=(($12+2)&4294967295);$samples_addr=$incdec_ptr;var $13=HEAP16[(($12)>>1)];var $conv=(tempInt=(($13)),(tempInt>=32768?tempInt-65536:tempInt));var $14=$value;var $add=((($14)+($conv))&4294967295);$value=$add;var $15=$j;var $inc=((($15)+1)&4294967295);$j=$inc;var $16=$j;var $17=$samplesPerValue;var $cmp2=((($16))|0)<((($17))|0);if($cmp2){__label__=2;continue;}else{__label__=3;break $for_body3$$for_end$5;}}}}while(0);var $18=$samplesPerValue;var $19=$value;var $div4=((((($19))|0)/((($18))|0))|0);$value=$div4;var $20=$value;var $conv5=((($20))&65535);var $21=$downSamples;var $incdec_ptr6=(($21+2)&4294967295);$downSamples=$incdec_ptr6;HEAP16[(($21)>>1)]=$conv5;var $22=$i;var $inc8=((($22)+1)&4294967295);$i=$inc8;var $23=$i;var $24=$numSamples;var $cmp=((($23))|0)<((($24))|0);if($cmp){__label__=1;continue $for_body$3;}else{__label__=4;break $for_body$$for_end9$2;}}}}while(0);;return;return;}
function __ZL16prevPeriodBetterP17sonicStreamStructiii($stream,$period,$minDiff,$maxDiff){;var __label__;var $retval;var $stream_addr;var $period_addr;var $minDiff_addr;var $maxDiff_addr;$stream_addr=$stream;$period_addr=$period;$minDiff_addr=$minDiff;$maxDiff_addr=$maxDiff;var $0=$maxDiff_addr;var $mul=((($0)*3)&4294967295);var $div=((((($mul))|0)/2)|0);var $1=$stream_addr;var $prevMaxDiff=(($1+80)&4294967295);var $2=HEAP32[(($prevMaxDiff)>>2)];var $cmp=((($div))|0)<((($2))|0);if($cmp){__label__=1;;}else{__label__=3;;}
$land_lhs_true$$if_end$2:do{if(__label__==1){var $3=$maxDiff_addr;var $conv=((($3))|0);var $mul1=($conv)*3;var $4=$stream_addr;var $prevMinDiff=(($4+84)&4294967295);var $5=HEAP32[(($prevMinDiff)>>2)];var $conv2=((($5))|0);var $mul3=($mul1)*($conv2);var $6=$stream_addr;var $prevMaxDiff4=(($6+80)&4294967295);var $7=HEAP32[(($prevMaxDiff4)>>2)];var $conv5=((($7))|0);var $8=$minDiff_addr;var $conv6=((($8))|0);var $mul7=($conv5)*($conv6);var $mul8=($mul7)*2;var $cmp9=($mul3)<($mul8);if(!($cmp9)){__label__=3;break $land_lhs_true$$if_end$2;}
$retval=1;__label__=4;break $land_lhs_true$$if_end$2;}}while(0);if(__label__==3){$retval=0;;}
var $9=$retval;;return $9;return null;}
function __ZL17copyInputToOutputP17sonicStreamStructi($stream,$position){;var __label__;var $retval;var $stream_addr;var $position_addr;var $numSamples;$stream_addr=$stream;$position_addr=$position;var $0=$stream_addr;var $remainingInputToCopy=(($0+68)&4294967295);var $1=HEAP32[(($remainingInputToCopy)>>2)];$numSamples=$1;var $2=$numSamples;var $3=$stream_addr;var $maxRequired=(($3+64)&4294967295);var $4=HEAP32[(($maxRequired)>>2)];var $cmp=((($2))|0)>((($4))|0);if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $5=$stream_addr;var $maxRequired1=(($5+64)&4294967295);var $6=HEAP32[(($maxRequired1)>>2)];$numSamples=$6;;}
var $7=$stream_addr;var $8=$stream_addr;var $inputBuffer=(($8)&4294967295);var $9=HEAP32[(($inputBuffer)>>2)];var $10=$position_addr;var $11=$stream_addr;var $numChannels=(($11+28)&4294967295);var $12=HEAP32[(($numChannels)>>2)];var $mul=((($12)*($10))&4294967295);var $add_ptr=(($9+2*$mul)&4294967295);var $13=$numSamples;var $call=__ZL12copyToOutputP17sonicStreamStructPsi($7,$add_ptr,$13);var $tobool=((($call))|0)!=0;if($tobool){__label__=4;;}else{__label__=3;;}
if(__label__==4){var $14=$numSamples;var $15=$stream_addr;var $remainingInputToCopy4=(($15+68)&4294967295);var $16=HEAP32[(($remainingInputToCopy4)>>2)];var $sub=((($16)-($14))&4294967295);HEAP32[(($remainingInputToCopy4)>>2)]=$sub;var $17=$numSamples;$retval=$17;;}
else if(__label__==3){$retval=0;;}
var $18=$retval;;return $18;return null;}
function __ZL15skipPitchPeriodP17sonicStreamStructPsfi($stream,$samples,$speed,$period){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $speed_addr;var $period_addr;var $newSamples;var $numChannels;$stream_addr=$stream;$samples_addr=$samples;$speed_addr=$speed;$period_addr=$period;var $0=$stream_addr;var $numChannels1=(($0+28)&4294967295);var $1=HEAP32[(($numChannels1)>>2)];$numChannels=$1;var $2=$speed_addr;var $cmp=($2)>=2;if($cmp){__label__=1;;}else{__label__=2;;}
$if_then$$if_else$2:do{if(__label__==1){var $3=$period_addr;var $conv=((($3))|0);var $4=$speed_addr;var $sub=($4)-1;var $div=($conv)/($sub);var $conv2=((($div))|0);$newSamples=$conv2;;}
else if(__label__==2){var $5=$speed_addr;var $cmp3=($5)>1;if(!($cmp3)){__label__=4;break $if_then$$if_else$2;}
var $6=$period_addr;$newSamples=$6;var $7=$period_addr;var $conv5=((($7))|0);var $8=$speed_addr;var $sub6=2-($8);var $mul=($conv5)*($sub6);var $9=$speed_addr;var $sub7=($9)-1;var $div8=($mul)/($sub7);var $conv9=((($div8))|0);var $10=$stream_addr;var $remainingInputToCopy=(($10+68)&4294967295);HEAP32[(($remainingInputToCopy)>>2)]=$conv9;;}}while(0);var $11=$stream_addr;var $12=$newSamples;var $call=__ZL27enlargeOutputBufferIfNeededP17sonicStreamStructi($11,$12);var $tobool=((($call))|0)!=0;if($tobool){__label__=6;;}else{__label__=5;;}
if(__label__==6){var $13=$newSamples;var $14=$numChannels;var $15=$stream_addr;var $outputBuffer=(($15+4)&4294967295);var $16=HEAP32[(($outputBuffer)>>2)];var $17=$stream_addr;var $numOutputSamples=(($17+48)&4294967295);var $18=HEAP32[(($numOutputSamples)>>2)];var $19=$numChannels;var $mul13=((($19)*($18))&4294967295);var $add_ptr=(($16+2*$mul13)&4294967295);var $20=$samples_addr;var $21=$samples_addr;var $22=$period_addr;var $23=$numChannels;var $mul14=((($23)*($22))&4294967295);var $add_ptr15=(($21+2*$mul14)&4294967295);__ZL10overlapAddiiPsS_S_($13,$14,$add_ptr,$20,$add_ptr15);var $24=$newSamples;var $25=$stream_addr;var $numOutputSamples16=(($25+48)&4294967295);var $26=HEAP32[(($numOutputSamples16)>>2)];var $add=((($26)+($24))&4294967295);HEAP32[(($numOutputSamples16)>>2)]=$add;var $27=$newSamples;$retval=$27;;}
else if(__label__==5){$retval=0;;}
var $28=$retval;;return $28;return null;}
function __ZL17insertPitchPeriodP17sonicStreamStructPsfi($stream,$samples,$speed,$period){;var __label__;var $retval;var $stream_addr;var $samples_addr;var $speed_addr;var $period_addr;var $newSamples;var $out;var $numChannels;$stream_addr=$stream;$samples_addr=$samples;$speed_addr=$speed;$period_addr=$period;var $0=$stream_addr;var $numChannels1=(($0+28)&4294967295);var $1=HEAP32[(($numChannels1)>>2)];$numChannels=$1;var $2=$speed_addr;var $cmp=($2)<0.5;var $3=$period_addr;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $conv=((($3))|0);var $4=$speed_addr;var $mul=($conv)*($4);var $5=$speed_addr;var $sub=1-($5);var $div=($mul)/($sub);var $conv2=((($div))|0);$newSamples=$conv2;;}
else if(__label__==2){$newSamples=$3;var $6=$period_addr;var $conv3=((($6))|0);var $7=$speed_addr;var $mul4=2*($7);var $sub5=($mul4)-1;var $mul6=($conv3)*($sub5);var $8=$speed_addr;var $sub7=1-($8);var $div8=($mul6)/($sub7);var $conv9=((($div8))|0);var $9=$stream_addr;var $remainingInputToCopy=(($9+68)&4294967295);HEAP32[(($remainingInputToCopy)>>2)]=$conv9;;}
var $10=$stream_addr;var $11=$period_addr;var $12=$newSamples;var $add=((($12)+($11))&4294967295);var $call=__ZL27enlargeOutputBufferIfNeededP17sonicStreamStructi($10,$add);var $tobool=((($call))|0)!=0;if($tobool){__label__=5;;}else{__label__=4;;}
if(__label__==5){var $13=$stream_addr;var $outputBuffer=(($13+4)&4294967295);var $14=HEAP32[(($outputBuffer)>>2)];var $15=$stream_addr;var $numOutputSamples=(($15+48)&4294967295);var $16=HEAP32[(($numOutputSamples)>>2)];var $17=$numChannels;var $mul12=((($17)*($16))&4294967295);var $add_ptr=(($14+2*$mul12)&4294967295);$out=$add_ptr;var $18=$out;var $19=$18;var $20=$samples_addr;var $21=$20;var $22=$period_addr;var $23=$numChannels;var $mul13=((($22)*2)&4294967295);var $mul14=((($mul13)*($23))&4294967295);var $src$,$dest$,$stop$,$stop4$,$fast$;$src$=$21;$dest$=$19;$stop$=$src$+$mul14;if(($dest$%4)==($src$%4)&&$mul14>8){while($src$%4!==0&&$src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];}
$src$>>=2;$dest$>>=2;$stop4$=$stop$>>2;while($src$<$stop4$){;;;HEAP32[$dest$++]=HEAP32[$src$++];}
$src$<<=2;$dest$<<=2;}while($src$<$stop$){;HEAP8[$dest$++]=HEAP8[$src$++];};var $24=$stream_addr;var $outputBuffer15=(($24+4)&4294967295);var $25=HEAP32[(($outputBuffer15)>>2)];var $26=$stream_addr;var $numOutputSamples16=(($26+48)&4294967295);var $27=HEAP32[(($numOutputSamples16)>>2)];var $28=$period_addr;var $add17=((($28)+($27))&4294967295);var $29=$numChannels;var $mul18=((($add17)*($29))&4294967295);var $add_ptr19=(($25+2*$mul18)&4294967295);$out=$add_ptr19;var $30=$newSamples;var $31=$numChannels;var $32=$out;var $33=$samples_addr;var $34=$period_addr;var $35=$numChannels;var $mul20=((($35)*($34))&4294967295);var $add_ptr21=(($33+2*$mul20)&4294967295);var $36=$samples_addr;__ZL10overlapAddiiPsS_S_($30,$31,$32,$add_ptr21,$36);var $37=$period_addr;var $38=$newSamples;var $39=$stream_addr;var $numOutputSamples23=(($39+48)&4294967295);var $40=HEAP32[(($numOutputSamples23)>>2)];var $add22=((($38)+($37))&4294967295);var $add24=((($add22)+($40))&4294967295);HEAP32[(($numOutputSamples23)>>2)]=$add24;var $41=$newSamples;$retval=$41;;}
else if(__label__==4){$retval=0;;}
var $42=$retval;;return $42;return null;}
function __ZL18removeInputSamplesP17sonicStreamStructi($stream,$position){;var __label__;var $stream_addr;var $position_addr;var $remainingSamples;$stream_addr=$stream;$position_addr=$position;var $0=$stream_addr;var $numInputSamples=(($0+44)&4294967295);var $1=HEAP32[(($numInputSamples)>>2)];var $2=$position_addr;var $sub=((($1)-($2))&4294967295);$remainingSamples=$sub;var $3=$remainingSamples;var $cmp=((($3))|0)>0;if($cmp){__label__=1;;}else{__label__=2;;}
if(__label__==1){var $4=$stream_addr;var $inputBuffer=(($4)&4294967295);var $5=HEAP32[(($inputBuffer)>>2)];var $6=$5;var $7=$stream_addr;var $inputBuffer1=(($7)&4294967295);var $8=HEAP32[(($inputBuffer1)>>2)];var $9=$position_addr;var $10=$stream_addr;var $numChannels=(($10+28)&4294967295);var $11=HEAP32[(($numChannels)>>2)];var $mul=((($11)*($9))&4294967295);var $add_ptr=(($8+2*$mul)&4294967295);var $12=$add_ptr;var $13=$remainingSamples;var $14=$stream_addr;var $numChannels3=(($14+28)&4294967295);var $15=HEAP32[(($numChannels3)>>2)];var $mul2=((($13)*2)&4294967295);var $mul4=((($mul2)*($15))&4294967295);_llvm_memmove_p0i8_p0i8_i32($6,$12,$mul4,1,0);;}
var $16=$remainingSamples;var $17=$stream_addr;var $numInputSamples5=(($17+44)&4294967295);HEAP32[(($numInputSamples5)>>2)]=$16;;return;return;}
function _getopt($argc,$argv,$optstring){var __stackBase__=STACKTOP;STACKTOP+=20;_memset(__stackBase__,0,20);var __label__;var $argc_addr;var $argv_addr;var $optstring_addr;var $data=__stackBase__;var $r;$argc_addr=$argc;$argv_addr=$argv;$optstring_addr=$optstring;__ZL12read_globalsP11getopt_data($data);var $0=$argc_addr;var $1=$argv_addr;var $2=$optstring_addr;var $call=__ZL15getopt_internaliPKPcPKcPK6optionPiiP11getopt_data($0,$1,$2,0,0,0,$data);$r=$call;__ZL13write_globalsP11getopt_data($data);var $3=$r;STACKTOP=__stackBase__;return $3;return null;}
function __ZL12read_globalsP11getopt_data($data){;var __label__;var $data_addr;$data_addr=$data;var $0=HEAP32[((_optarg)>>2)];var $1=$data_addr;var $optarg=(($1)&4294967295);HEAP32[(($optarg)>>2)]=$0;var $2=HEAP32[((_optind)>>2)];var $3=$data_addr;var $optind=(($3+4)&4294967295);HEAP32[(($optind)>>2)]=$2;var $4=HEAP32[((_opterr)>>2)];var $5=$data_addr;var $opterr=(($5+8)&4294967295);HEAP32[(($opterr)>>2)]=$4;var $6=HEAP32[((_optopt)>>2)];var $7=$data_addr;var $optopt=(($7+12)&4294967295);HEAP32[(($optopt)>>2)]=$6;var $8=HEAP32[((__ZL8optwhere)>>2)];var $9=$data_addr;var $optwhere=(($9+16)&4294967295);HEAP32[(($optwhere)>>2)]=$8;;return;return;}
function __ZL15getopt_internaliPKPcPKcPK6optionPiiP11getopt_data($argc,$argv,$shortopts,$longopts,$longind,$only,$data){;var __label__;var __lastLabel__=null;var $retval;var $argc_addr;var $argv_addr;var $shortopts_addr;var $longopts_addr;var $longind_addr;var $only_addr;var $data_addr;var $ordering;var $permute_from;var $num_nonopts;var $optindex;var $match_chars;var $possible_arg;var $longopt_match;var $has_arg;var $cp;var $arg_next;$argc_addr=$argc;$argv_addr=$argv;$shortopts_addr=$shortopts;$longopts_addr=$longopts;$longind_addr=$longind;$only_addr=$only;$data_addr=$data;$ordering=0;$permute_from=0;$num_nonopts=0;$optindex=0;$match_chars=0;$possible_arg=0;$longopt_match=-1;$has_arg=-1;$cp=0;$arg_next=0;var $0=$argc_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=6;;}else{__label__=1;;}
$if_then$$lor_lhs_false$2:do{if(__label__==1){var $1=$argv_addr;var $cmp1=((($1))|0)==0;if($cmp1){__label__=6;break $if_then$$lor_lhs_false$2;}
var $2=$shortopts_addr;var $cmp3=((($2))|0)==0;if($cmp3){__label__=3;;}else{__label__=4;;}
if(__label__==3){var $3=$longopts_addr;var $cmp4=((($3))|0)==0;if($cmp4){__label__=6;break $if_then$$lor_lhs_false$2;}}
var $4=$data_addr;var $optind=(($4+4)&4294967295);var $5=HEAP32[(($optind)>>2)];var $6=$argc_addr;var $cmp6=((($5))|0)>=((($6))|0);if($cmp6){__label__=6;break $if_then$$lor_lhs_false$2;}
var $7=$data_addr;var $optind8=(($7+4)&4294967295);var $8=HEAP32[(($optind8)>>2)];var $9=$argv_addr;var $arrayidx=(($9+4*$8)&4294967295);var $10=HEAP32[(($arrayidx)>>2)];var $cmp9=((($10))|0)==0;if($cmp9){__label__=6;break $if_then$$lor_lhs_false$2;}
var $11=$data_addr;var $optind10=(($11+4)&4294967295);var $12=HEAP32[(($optind10)>>2)];var $13=$argv_addr;var $arrayidx11=(($13+4*$12)&4294967295);var $14=HEAP32[(($arrayidx11)>>2)];var $call=_strcmp($14,((__str831)&4294967295));var $cmp12=((($call))|0)==0;var $15=$data_addr;var $optind14=(($15+4)&4294967295);var $16=HEAP32[(($optind14)>>2)];if($cmp12){__label__=8;;}else{__label__=9;;}
if(__label__==8){var $inc=((($16)+1)&4294967295);HEAP32[(($optind14)>>2)]=$inc;$retval=-1;__label__=96;break $if_then$$lor_lhs_false$2;}
else if(__label__==9){var $cmp17=((($16))|0)==0;if($cmp17){__label__=10;;}else{__label__=11;;}
if(__label__==10){var $17=$data_addr;var $optwhere=(($17+16)&4294967295);HEAP32[(($optwhere)>>2)]=1;var $18=$data_addr;var $optind19=(($18+4)&4294967295);HEAP32[(($optind19)>>2)]=1;;}
var $19=$shortopts_addr;var $cmp21=((($19))|0)!=0;if($cmp21){__label__=12;;}else{__label__=15;;}
$land_lhs_true22$$if_else$16:do{if(__label__==12){var $20=$shortopts_addr;var $21=HEAP8[($20)];var $conv=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));var $cmp23=((($conv))|0)==45;if($cmp23){__label__=14;;}else{__label__=13;;}
if(__label__==13){var $22=$shortopts_addr;var $23=HEAP8[($22)];var $conv25=(tempInt=(($23)),(tempInt>=128?tempInt-256:tempInt));var $cmp26=((($conv25))|0)==43;if(!($cmp26)){__label__=15;break $land_lhs_true22$$if_else$16;}}
var $24=$shortopts_addr;var $25=HEAP8[($24)];var $conv28=(tempInt=(($25)),(tempInt>=128?tempInt-256:tempInt));var $cmp29=((($conv28))|0)==45;var $cond=($cmp29)?1:2;$ordering=$cond;var $26=$shortopts_addr;var $incdec_ptr=(($26+1)&4294967295);$shortopts_addr=$incdec_ptr;__label__=16;break $land_lhs_true22$$if_else$16;}}while(0);if(__label__==15){var $call30=_getenv(((__str1832)&4294967295));var $cmp31=((($call30))|0)!=0;var $cond32=($cmp31)?2:0;$ordering=$cond32;;}
var $27=$data_addr;var $optwhere34=(($27+16)&4294967295);var $28=HEAP32[(($optwhere34)>>2)];var $cmp35=((($28))|0)==1;if($cmp35){__label__=17;;}else{__label__=28;;}
$if_then36$$if_end75$24:do{if(__label__==17){var $29=$ordering;if($29==2){__label__=26;;}
else if($29==1){__label__=24;;}
else{__label__=18;;}
if(__label__==18){var $30=$data_addr;var $optind37=(($30+4)&4294967295);var $31=HEAP32[(($optind37)>>2)];$permute_from=$31;$num_nonopts=0;var $32=$data_addr;var $optind381=(($32+4)&4294967295);var $33=HEAP32[(($optind381)>>2)];var $34=$argv_addr;var $arrayidx392=(($34+4*$33)&4294967295);var $35=HEAP32[(($arrayidx392)>>2)];var $36=$only_addr;var $call403=__ZL9is_optionPci($35,$36);var $tobool4=((($call403))|0)!=0;var $lnot5=($tobool4)^1;var $37=$data_addr;var $optind416=(($37+4)&4294967295);var $38=HEAP32[(($optind416)>>2)];if($lnot5){__lastLabel__=18;__label__=19;;}else{__lastLabel__=18;__label__=20;;}
$while_body$$while_end$28:do{if(__label__==19){while(1){var $39=__lastLabel__==19?$47:($38);var $optind417=__lastLabel__==19?$optind41:($optind416);var $inc42=((($39)+1)&4294967295);HEAP32[(($optind417)>>2)]=$inc42;var $40=$num_nonopts;var $inc43=((($40)+1)&4294967295);$num_nonopts=$inc43;var $41=$data_addr;var $optind38=(($41+4)&4294967295);var $42=HEAP32[(($optind38)>>2)];var $43=$argv_addr;var $arrayidx39=(($43+4*$42)&4294967295);var $44=HEAP32[(($arrayidx39)>>2)];var $45=$only_addr;var $call40=__ZL9is_optionPci($44,$45);var $tobool=((($call40))|0)!=0;var $lnot=($tobool)^1;var $46=$data_addr;var $optind41=(($46+4)&4294967295);var $47=HEAP32[(($optind41)>>2)];if($lnot){__lastLabel__=19;__label__=19;continue;}else{__lastLabel__=19;__label__=20;break $while_body$$while_end$28;}}}}while(0);var $_lcssa=__lastLabel__==18?$38:($47);var $48=$argv_addr;var $arrayidx45=(($48+4*$_lcssa)&4294967295);var $49=HEAP32[(($arrayidx45)>>2)];var $cmp46=((($49))|0)==0;if($cmp46){__label__=21;;}else{__label__=22;;}
if(__label__==21){var $50=$permute_from;var $51=$data_addr;var $optind48=(($51+4)&4294967295);HEAP32[(($optind48)>>2)]=$50;$retval=-1;__label__=96;break $if_then$$lor_lhs_false$2;}
else if(__label__==22){var $52=$data_addr;var $optind50=(($52+4)&4294967295);var $53=HEAP32[(($optind50)>>2)];var $54=$argv_addr;var $arrayidx51=(($54+4*$53)&4294967295);var $55=HEAP32[(($arrayidx51)>>2)];var $call52=_strcmp($55,((__str831)&4294967295));var $cmp53=((($call52))|0)==0;if(!($cmp53)){__label__=28;break $if_then36$$if_end75$24;}
var $56=$argv_addr;var $57=$permute_from;var $add_ptr=(($56+4*$57)&4294967295);var $58=$num_nonopts;__ZL7permutePKPcii($add_ptr,$58,1);var $59=$permute_from;var $add=((($59)+1)&4294967295);var $60=$data_addr;var $optind55=(($60+4)&4294967295);HEAP32[(($optind55)>>2)]=$add;$retval=-1;__label__=96;break $if_then$$lor_lhs_false$2;}}
else if(__label__==26){var $72=$data_addr;var $optind69=(($72+4)&4294967295);var $73=HEAP32[(($optind69)>>2)];var $74=$argv_addr;var $arrayidx70=(($74+4*$73)&4294967295);var $75=HEAP32[(($arrayidx70)>>2)];var $76=$only_addr;var $call71=__ZL9is_optionPci($75,$76);var $tobool72=((($call71))|0)!=0;if($tobool72){__label__=28;break $if_then36$$if_end75$24;}
$retval=-1;__label__=96;break $if_then$$lor_lhs_false$2;}
else if(__label__==24){var $61=$data_addr;var $optind59=(($61+4)&4294967295);var $62=HEAP32[(($optind59)>>2)];var $63=$argv_addr;var $arrayidx60=(($63+4*$62)&4294967295);var $64=HEAP32[(($arrayidx60)>>2)];var $65=$only_addr;var $call61=__ZL9is_optionPci($64,$65);var $tobool62=((($call61))|0)!=0;if($tobool62){__label__=28;break $if_then36$$if_end75$24;}
var $66=$data_addr;var $optind64=(($66+4)&4294967295);var $67=HEAP32[(($optind64)>>2)];var $inc65=((($67)+1)&4294967295);HEAP32[(($optind64)>>2)]=$inc65;var $68=$argv_addr;var $arrayidx66=(($68+4*$67)&4294967295);var $69=HEAP32[(($arrayidx66)>>2)];var $70=$data_addr;var $optarg=(($70)&4294967295);HEAP32[(($optarg)>>2)]=$69;var $71=$data_addr;var $optopt=(($71+12)&4294967295);HEAP32[(($optopt)>>2)]=1;$retval=1;__label__=96;break $if_then$$lor_lhs_false$2;}}}while(0);var $77=$longopts_addr;var $cmp76=((($77))|0)!=0;if($cmp76){__label__=29;;}else{__label__=52;;}
$land_lhs_true77$$if_end162$41:do{if(__label__==29){var $78=$data_addr;var $optind78=(($78+4)&4294967295);var $79=HEAP32[(($optind78)>>2)];var $80=$argv_addr;var $arrayidx79=(($80+4*$79)&4294967295);var $81=HEAP32[(($arrayidx79)>>2)];var $call80=_memcmp($81,((__str831)&4294967295),2);var $cmp81=((($call80))|0)==0;if($cmp81){__label__=32;;}else{__label__=30;;}
if(__label__==30){var $82=$only_addr;var $tobool83=((($82))|0)!=0;if(!($tobool83)){__label__=52;break $land_lhs_true77$$if_end162$41;}
var $83=$data_addr;var $optind85=(($83+4)&4294967295);var $84=HEAP32[(($optind85)>>2)];var $85=$argv_addr;var $arrayidx86=(($85+4*$84)&4294967295);var $86=HEAP32[(($arrayidx86)>>2)];var $arrayidx87=(($86)&4294967295);var $87=HEAP8[($arrayidx87)];var $conv88=(tempInt=(($87)),(tempInt>=128?tempInt-256:tempInt));var $cmp89=((($conv88))|0)==43;if(!($cmp89)){__label__=52;break $land_lhs_true77$$if_end162$41;}}
var $88=$data_addr;var $optwhere91=(($88+16)&4294967295);var $89=HEAP32[(($optwhere91)>>2)];var $cmp92=((($89))|0)==1;if(!($cmp92)){__label__=52;break $land_lhs_true77$$if_end162$41;}
var $90=$data_addr;var $optind94=(($90+4)&4294967295);var $91=HEAP32[(($optind94)>>2)];var $92=$argv_addr;var $arrayidx95=(($92+4*$91)&4294967295);var $93=HEAP32[(($arrayidx95)>>2)];var $call96=_memcmp($93,((__str831)&4294967295),2);var $cmp97=((($call96))|0)==0;if($cmp97){__label__=34;;}else{__label__=35;;}
if(__label__==34){var $94=$data_addr;var $optwhere99=(($94+16)&4294967295);HEAP32[(($optwhere99)>>2)]=2;;}
$longopt_match=-1;var $95=$data_addr;var $optind101=(($95+4)&4294967295);var $96=HEAP32[(($optind101)>>2)];var $97=$argv_addr;var $arrayidx102=(($97+4*$96)&4294967295);var $98=HEAP32[(($arrayidx102)>>2)];var $99=$data_addr;var $optwhere103=(($99+16)&4294967295);var $100=HEAP32[(($optwhere103)>>2)];var $add_ptr104=(($98+$100)&4294967295);var $call105=_strchr($add_ptr104,61);$possible_arg=$call105;var $cmp106=((($call105))|0)==0;if($cmp106){__label__=36;;}else{__label__=37;;}
if(__label__==36){var $101=$data_addr;var $optind108=(($101+4)&4294967295);var $102=HEAP32[(($optind108)>>2)];var $103=$argv_addr;var $arrayidx109=(($103+4*$102)&4294967295);var $104=HEAP32[(($arrayidx109)>>2)];var $call110=_strlen($104);$match_chars=$call110;var $105=$data_addr;var $optind111=(($105+4)&4294967295);var $106=HEAP32[(($optind111)>>2)];var $107=$argv_addr;var $arrayidx112=(($107+4*$106)&4294967295);var $108=HEAP32[(($arrayidx112)>>2)];var $109=$match_chars;var $add_ptr113=(($108+$109)&4294967295);$possible_arg=$add_ptr113;var $110=$match_chars;var $111=$data_addr;var $optwhere114=(($111+16)&4294967295);var $112=HEAP32[(($optwhere114)>>2)];var $sub=((($110)-($112))&4294967295);$match_chars=$sub;;}
else if(__label__==37){var $113=$possible_arg;var $114=$data_addr;var $optind116=(($114+4)&4294967295);var $115=HEAP32[(($optind116)>>2)];var $116=$argv_addr;var $arrayidx117=(($116+4*$115)&4294967295);var $117=HEAP32[(($arrayidx117)>>2)];var $sub_ptr_lhs_cast=($113);var $sub_ptr_rhs_cast=($117);var $sub_ptr_rhs_cast_neg=(((-($sub_ptr_rhs_cast)))&4294967295);var $118=$data_addr;var $optwhere118=(($118+16)&4294967295);var $119=HEAP32[(($optwhere118)>>2)];var $_neg=(((-($119)))&4294967295);var $sub_ptr_sub=((($sub_ptr_rhs_cast_neg)+($sub_ptr_lhs_cast))&4294967295);var $sub119=((($sub_ptr_sub)+($_neg))&4294967295);$match_chars=$sub119;;}
$optindex=0;;while(1){var $120=$optindex;var $121=$longopts_addr;var $arrayidx121=(($121+16*$120)&4294967295);var $name=(($arrayidx121)&4294967295);var $122=HEAP32[(($name)>>2)];var $cmp122=((($122))|0)!=0;if(!($cmp122)){__label__=49;break;}
var $123=$data_addr;var $optind123=(($123+4)&4294967295);var $124=HEAP32[(($optind123)>>2)];var $125=$argv_addr;var $arrayidx124=(($125+4*$124)&4294967295);var $126=HEAP32[(($arrayidx124)>>2)];var $127=$data_addr;var $optwhere125=(($127+16)&4294967295);var $128=HEAP32[(($optwhere125)>>2)];var $add_ptr126=(($126+$128)&4294967295);var $129=$optindex;var $130=$longopts_addr;var $arrayidx127=(($130+16*$129)&4294967295);var $name128=(($arrayidx127)&4294967295);var $131=HEAP32[(($name128)>>2)];var $132=$match_chars;var $call129=_memcmp($add_ptr126,$131,$132);var $cmp130=((($call129))|0)==0;if($cmp130){__label__=41;;}else{__label__=48;;}
if(__label__==41){var $133=$match_chars;var $134=$optindex;var $135=$longopts_addr;var $arrayidx132=(($135+16*$134)&4294967295);var $name133=(($arrayidx132)&4294967295);var $136=HEAP32[(($name133)>>2)];var $call134=_strlen($136);var $cmp135=((($133))|0)==((($call134))|0);if($cmp135){__label__=42;break;}
var $138=$longopt_match;var $cmp138=((($138))|0)<0;if(!($cmp138)){__label__=45;break;}
var $139=$optindex;$longopt_match=$139;;}
var $157=$optindex;var $inc156=((($157)+1)&4294967295);$optindex=$inc156;__label__=39;continue;}
if(__label__==49){var $_pr=$longopt_match;__lastLabel__=49;;}
else if(__label__==42){var $137=$optindex;$longopt_match=$137;__lastLabel__=42;;}
else if(__label__==45){var $140=$data_addr;var $opterr=(($140+8)&4294967295);var $141=HEAP32[(($opterr)>>2)];var $tobool141=((($141))|0)!=0;if($tobool141){__label__=46;;}else{__label__=47;;}
if(__label__==46){var $142=HEAP32[((__impure_ptr)>>2)];var $_stderr=(($142+12)&4294967295);var $143=HEAP32[(($_stderr)>>2)];var $144=$argv_addr;var $arrayidx143=(($144)&4294967295);var $145=HEAP32[(($arrayidx143)>>2)];var $146=$data_addr;var $optind144=(($146+4)&4294967295);var $147=HEAP32[(($optind144)>>2)];var $148=$argv_addr;var $arrayidx145=(($148+4*$147)&4294967295);var $149=HEAP32[(($arrayidx145)>>2)];var $150=$longopt_match;var $151=$longopts_addr;var $arrayidx146=(($151+16*$150)&4294967295);var $name147=(($arrayidx146)&4294967295);var $152=HEAP32[(($name147)>>2)];var $153=$optindex;var $154=$longopts_addr;var $arrayidx148=(($154+16*$153)&4294967295);var $name149=(($arrayidx148)&4294967295);var $155=HEAP32[(($name149)>>2)];var $call150=_fprintf($143,((__str2833)&4294967295),allocate([$145,0,0,0,$149,0,0,0,$152,0,0,0,$155,0,0,0],["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STACK));;}
var $156=$data_addr;var $optopt152=(($156+12)&4294967295);HEAP32[(($optopt152)>>2)]=63;$retval=63;__label__=96;break $if_then$$lor_lhs_false$2;}
var $158=__lastLabel__==49?$_pr:($137);var $cmp157=((($158))|0)>=0;if(!($cmp157)){__label__=52;break $land_lhs_true77$$if_end162$41;}
var $159=$longopt_match;var $160=$longopts_addr;var $arrayidx159=(($160+16*$159)&4294967295);var $has_arg160=(($arrayidx159+4)&4294967295);var $161=HEAP32[(($has_arg160)>>2)];$has_arg=$161;;}}while(0);var $162=$longopt_match;var $cmp163=((($162))|0)<0;if($cmp163){__label__=53;;}else{__label__=63;;}
$land_lhs_true164$$if_end217$73:do{if(__label__==53){var $163=$shortopts_addr;var $cmp165=((($163))|0)!=0;if(!($cmp165)){__label__=63;break $land_lhs_true164$$if_end217$73;}
var $164=$shortopts_addr;var $165=$data_addr;var $optwhere167=(($165+16)&4294967295);var $166=HEAP32[(($optwhere167)>>2)];var $167=$data_addr;var $optind168=(($167+4)&4294967295);var $168=HEAP32[(($optind168)>>2)];var $169=$argv_addr;var $arrayidx169=(($169+4*$168)&4294967295);var $170=HEAP32[(($arrayidx169)>>2)];var $arrayidx170=(($170+$166)&4294967295);var $171=HEAP8[($arrayidx170)];var $conv171=(tempInt=(($171)),(tempInt>=128?tempInt-256:tempInt));var $call172=_strchr($164,$conv171);$cp=$call172;var $172=$cp;var $cmp173=((($172))|0)==0;if($cmp173){__label__=55;;}else{__label__=60;;}
if(__label__==55){var $173=$data_addr;var $opterr175=(($173+8)&4294967295);var $174=HEAP32[(($opterr175)>>2)];var $tobool176=((($174))|0)!=0;if($tobool176){__label__=56;;}else{__label__=57;;}
if(__label__==56){var $175=HEAP32[((__impure_ptr)>>2)];var $_stderr178=(($175+12)&4294967295);var $176=HEAP32[(($_stderr178)>>2)];var $177=$argv_addr;var $arrayidx179=(($177)&4294967295);var $178=HEAP32[(($arrayidx179)>>2)];var $179=$data_addr;var $optwhere180=(($179+16)&4294967295);var $180=HEAP32[(($optwhere180)>>2)];var $181=$data_addr;var $optind181=(($181+4)&4294967295);var $182=HEAP32[(($optind181)>>2)];var $183=$argv_addr;var $arrayidx182=(($183+4*$182)&4294967295);var $184=HEAP32[(($arrayidx182)>>2)];var $arrayidx183=(($184+$180)&4294967295);var $185=HEAP8[($arrayidx183)];var $conv184=(tempInt=(($185)),(tempInt>=128?tempInt-256:tempInt));var $call185=_fprintf($176,((__str3834)&4294967295),allocate([$178,0,0,0,$conv184,0,0,0],["i8*",0,0,0,"i32",0,0,0],ALLOC_STACK));;}
var $186=$data_addr;var $optwhere187=(($186+16)&4294967295);var $187=HEAP32[(($optwhere187)>>2)];var $inc188=((($187)+1)&4294967295);HEAP32[(($optwhere187)>>2)]=$inc188;var $188=$data_addr;var $optwhere189=(($188+16)&4294967295);var $189=HEAP32[(($optwhere189)>>2)];var $190=$data_addr;var $optind190=(($190+4)&4294967295);var $191=HEAP32[(($optind190)>>2)];var $192=$argv_addr;var $arrayidx191=(($192+4*$191)&4294967295);var $193=HEAP32[(($arrayidx191)>>2)];var $arrayidx192=(($193+$189)&4294967295);var $194=HEAP8[($arrayidx192)];var $conv193=(tempInt=(($194)),(tempInt>=128?tempInt-256:tempInt));var $cmp194=((($conv193))|0)==0;if($cmp194){__label__=58;;}else{__label__=59;;}
if(__label__==58){var $195=$data_addr;var $optind196=(($195+4)&4294967295);var $196=HEAP32[(($optind196)>>2)];var $inc197=((($196)+1)&4294967295);HEAP32[(($optind196)>>2)]=$inc197;var $197=$data_addr;var $optwhere198=(($197+16)&4294967295);HEAP32[(($optwhere198)>>2)]=1;;}
var $198=$data_addr;var $optopt200=(($198+12)&4294967295);HEAP32[(($optopt200)>>2)]=63;$retval=63;__label__=96;break $if_then$$lor_lhs_false$2;}
else if(__label__==60){var $199=$cp;var $arrayidx202=(($199+1)&4294967295);var $200=HEAP8[($arrayidx202)];var $conv203=(tempInt=(($200)),(tempInt>=128?tempInt-256:tempInt));var $cmp204=((($conv203))|0)==58;if($cmp204){__lastLabel__=60;__label__=61;;}else{__lastLabel__=60;__label__=62;;}
if(__label__==61){var $201=$cp;var $arrayidx205=(($201+2)&4294967295);var $202=HEAP8[($arrayidx205)];var $conv206=(tempInt=(($202)),(tempInt>=128?tempInt-256:tempInt));var $cmp207=((($conv206))|0)==58;var $cond208=($cmp207)?2:1;__lastLabel__=61;;}
var $cond209=__lastLabel__==61?$cond208:(0);$has_arg=$cond209;var $203=$data_addr;var $optind210=(($203+4)&4294967295);var $204=HEAP32[(($optind210)>>2)];var $205=$argv_addr;var $arrayidx211=(($205+4*$204)&4294967295);var $206=HEAP32[(($arrayidx211)>>2)];var $207=$data_addr;var $optwhere212=(($207+16)&4294967295);var $208=HEAP32[(($optwhere212)>>2)];var $add_ptr213=(($206+$208)&4294967295);var $add_ptr214=(($add_ptr213+1)&4294967295);$possible_arg=$add_ptr214;var $209=$cp;var $210=HEAP8[($209)];var $conv215=(tempInt=(($210)),(tempInt>=128?tempInt-256:tempInt));var $211=$data_addr;var $optopt216=(($211+12)&4294967295);HEAP32[(($optopt216)>>2)]=$conv215;;}}}while(0);$arg_next=0;var $212=$has_arg;if($212==2){__label__=64;;}
else if($212==1){__label__=67;;}
else{__label__=78;;}
if(__label__==78){var $254=$longopt_match;var $cmp279=((($254))|0)<0;var $255=$data_addr;var $optwhere281=(($255+16)&4294967295);if($cmp279){__label__=79;;}else{__label__=81;;}
$if_then280$$if_else292$91:do{if(__label__==79){var $256=HEAP32[(($optwhere281)>>2)];var $inc282=((($256)+1)&4294967295);HEAP32[(($optwhere281)>>2)]=$inc282;var $257=$data_addr;var $optwhere283=(($257+16)&4294967295);var $258=HEAP32[(($optwhere283)>>2)];var $259=$data_addr;var $optind284=(($259+4)&4294967295);var $260=HEAP32[(($optind284)>>2)];var $261=$argv_addr;var $arrayidx285=(($261+4*$260)&4294967295);var $262=HEAP32[(($arrayidx285)>>2)];var $arrayidx286=(($262+$258)&4294967295);var $263=HEAP8[($arrayidx286)];var $conv287=(tempInt=(($263)),(tempInt>=128?tempInt-256:tempInt));var $cmp288=((($conv287))|0)==0;if(!($cmp288)){__label__=82;break $if_then280$$if_else292$91;}
var $264=$data_addr;var $optwhere290=(($264+16)&4294967295);HEAP32[(($optwhere290)>>2)]=1;;}
else if(__label__==81){HEAP32[(($optwhere281)>>2)]=1;;}}while(0);var $265=$data_addr;var $optarg295=(($265)&4294967295);HEAP32[(($optarg295)>>2)]=0;;}
else if(__label__==64){var $213=$possible_arg;var $214=HEAP8[($213)];var $conv219=(tempInt=(($214)),(tempInt>=128?tempInt-256:tempInt));var $cmp220=((($conv219))|0)==61;if($cmp220){__label__=65;;}else{__label__=66;;}
if(__label__==65){var $215=$possible_arg;var $incdec_ptr222=(($215+1)&4294967295);$possible_arg=$incdec_ptr222;;}
var $216=$possible_arg;var $217=HEAP8[($216)];var $conv224=(tempInt=(($217)),(tempInt>=128?tempInt-256:tempInt));var $cmp225=((($conv224))|0)!=0;var $218=$possible_arg;var $cond229=($cmp225)?($218):0;var $219=$data_addr;var $optarg230=(($219)&4294967295);HEAP32[(($optarg230)>>2)]=$cond229;var $220=$data_addr;var $optwhere231=(($220+16)&4294967295);HEAP32[(($optwhere231)>>2)]=1;;}
else if(__label__==67){var $221=$possible_arg;var $222=HEAP8[($221)];var $conv233=(tempInt=(($222)),(tempInt>=128?tempInt-256:tempInt));var $cmp234=((($conv233))|0)==61;if($cmp234){__label__=68;;}else{__label__=69;;}
if(__label__==68){var $223=$possible_arg;var $incdec_ptr236=(($223+1)&4294967295);$possible_arg=$incdec_ptr236;;}
var $224=$possible_arg;var $225=HEAP8[($224)];var $conv238=(tempInt=(($225)),(tempInt>=128?tempInt-256:tempInt));var $cmp239=((($conv238))|0)!=0;if($cmp239){__label__=70;;}else{__label__=71;;}
if(__label__==70){var $226=$possible_arg;var $227=$data_addr;var $optarg241=(($227)&4294967295);HEAP32[(($optarg241)>>2)]=$226;var $228=$data_addr;var $optwhere242=(($228+16)&4294967295);HEAP32[(($optwhere242)>>2)]=1;;}
else if(__label__==71){var $229=$data_addr;var $optind244=(($229+4)&4294967295);var $230=HEAP32[(($optind244)>>2)];var $add245=((($230)+1)&4294967295);var $231=$argc_addr;var $cmp246=((($add245))|0)>=((($231))|0);var $232=$data_addr;if($cmp246){__label__=72;;}else{__label__=77;;}
if(__label__==72){var $opterr248=(($232+8)&4294967295);var $233=HEAP32[(($opterr248)>>2)];var $tobool249=((($233))|0)!=0;if($tobool249){__label__=73;;}else{__label__=76;;}
if(__label__==73){var $234=HEAP32[((__impure_ptr)>>2)];var $_stderr251=(($234+12)&4294967295);var $235=HEAP32[(($_stderr251)>>2)];var $236=$argv_addr;var $arrayidx252=(($236)&4294967295);var $237=HEAP32[(($arrayidx252)>>2)];var $call253=_fprintf($235,((__str4835)&4294967295),allocate([$237,0,0,0],["i8*",0,0,0],ALLOC_STACK));var $238=$longopt_match;var $cmp254=((($238))|0)>=0;var $239=HEAP32[((__impure_ptr)>>2)];var $_stderr256=(($239+12)&4294967295);var $240=HEAP32[(($_stderr256)>>2)];if($cmp254){__label__=74;;}else{__label__=75;;}
if(__label__==74){var $241=$longopt_match;var $242=$longopts_addr;var $arrayidx257=(($242+16*$241)&4294967295);var $name258=(($arrayidx257)&4294967295);var $243=HEAP32[(($name258)>>2)];var $call259=_fprintf($240,((__str5836)&4294967295),allocate([$243,0,0,0],["i8*",0,0,0],ALLOC_STACK));;}
else if(__label__==75){var $244=$cp;var $245=HEAP8[($244)];var $conv262=(tempInt=(($245)),(tempInt>=128?tempInt-256:tempInt));var $call263=_fprintf($240,((__str6837)&4294967295),allocate([$conv262,0,0,0],["i32",0,0,0],ALLOC_STACK));;}}
var $246=$data_addr;var $optind266=(($246+4)&4294967295);var $247=HEAP32[(($optind266)>>2)];var $inc267=((($247)+1)&4294967295);HEAP32[(($optind266)>>2)]=$inc267;var $248=$data_addr;var $optopt268=(($248+12)&4294967295);HEAP32[(($optopt268)>>2)]=58;$retval=58;__label__=96;break $if_then$$lor_lhs_false$2;}
else if(__label__==77){var $optind270=(($232+4)&4294967295);var $249=HEAP32[(($optind270)>>2)];var $add271=((($249)+1)&4294967295);var $250=$argv_addr;var $arrayidx272=(($250+4*$add271)&4294967295);var $251=HEAP32[(($arrayidx272)>>2)];var $252=$data_addr;var $optarg273=(($252)&4294967295);HEAP32[(($optarg273)>>2)]=$251;$arg_next=1;var $253=$data_addr;var $optwhere274=(($253+16)&4294967295);HEAP32[(($optwhere274)>>2)]=1;;}}}
var $266=$ordering;var $cmp297=((($266))|0)==0;if($cmp297){__label__=84;;}else{__label__=87;;}
$land_lhs_true298$$if_else309$117:do{if(__label__==84){var $267=$data_addr;var $optwhere299=(($267+16)&4294967295);var $268=HEAP32[(($optwhere299)>>2)];var $cmp300=((($268))|0)==1;if(!($cmp300)){__label__=87;break $land_lhs_true298$$if_else309$117;}
var $269=$num_nonopts;var $cmp302=((($269))|0)!=0;if(!($cmp302)){__label__=87;break $land_lhs_true298$$if_else309$117;}
var $270=$argv_addr;var $271=$permute_from;var $add_ptr304=(($270+4*$271)&4294967295);var $272=$num_nonopts;var $273=$arg_next;var $add305=((($273)+1)&4294967295);__ZL7permutePKPcii($add_ptr304,$272,$add305);var $274=$permute_from;var $275=$arg_next;var $add306=((($274)+1)&4294967295);var $add307=((($add306)+($275))&4294967295);var $276=$data_addr;var $optind308=(($276+4)&4294967295);HEAP32[(($optind308)>>2)]=$add307;__label__=89;break $land_lhs_true298$$if_else309$117;}}while(0);$if_end318$$if_else309$121:do{if(__label__==87){var $277=$data_addr;var $optwhere310=(($277+16)&4294967295);var $278=HEAP32[(($optwhere310)>>2)];var $cmp311=((($278))|0)==1;if(!($cmp311)){__label__=89;break $if_end318$$if_else309$121;}
var $279=$data_addr;var $optind313=(($279+4)&4294967295);var $280=HEAP32[(($optind313)>>2)];var $281=$arg_next;var $add314=((($280)+1)&4294967295);var $add315=((($add314)+($281))&4294967295);var $282=$data_addr;var $optind316=(($282+4)&4294967295);HEAP32[(($optind316)>>2)]=$add315;;}}while(0);var $283=$longopt_match;var $cmp319=((($283))|0)>=0;if($cmp319){__label__=90;;}else{__label__=95;;}
if(__label__==90){var $284=$longind_addr;var $cmp321=((($284))|0)!=0;if($cmp321){__label__=91;;}else{__label__=92;;}
if(__label__==91){var $285=$longopt_match;var $286=$longind_addr;HEAP32[(($286)>>2)]=$285;;}
var $287=$longopt_match;var $288=$longopts_addr;var $arrayidx324=(($288+16*$287)&4294967295);var $flag=(($arrayidx324+8)&4294967295);var $289=HEAP32[(($flag)>>2)];var $cmp325=((($289))|0)!=0;var $290=$longopt_match;var $291=$longopts_addr;var $arrayidx327=(($291+16*$290)&4294967295);var $val=(($arrayidx327+12)&4294967295);var $292=HEAP32[(($val)>>2)];if($cmp325){__label__=93;;}else{__label__=94;;}
if(__label__==93){var $293=$longopt_match;var $294=$longopts_addr;var $arrayidx328=(($294+16*$293)&4294967295);var $flag329=(($arrayidx328+8)&4294967295);var $295=HEAP32[(($flag329)>>2)];HEAP32[(($295)>>2)]=$292;$retval=0;__label__=96;break $if_then$$lor_lhs_false$2;}
else if(__label__==94){$retval=$292;__label__=96;break $if_then$$lor_lhs_false$2;}}
else if(__label__==95){var $296=$data_addr;var $optopt334=(($296+12)&4294967295);var $297=HEAP32[(($optopt334)>>2)];$retval=$297;__label__=96;break $if_then$$lor_lhs_false$2;}}}}while(0);if(__label__==6){$retval=-1;;}
var $298=$retval;;return $298;return null;}
function __ZL13write_globalsP11getopt_data($data){;var __label__;var $data_addr;$data_addr=$data;var $0=$data_addr;var $optarg=(($0)&4294967295);var $1=HEAP32[(($optarg)>>2)];HEAP32[((_optarg)>>2)]=$1;var $2=$data_addr;var $optind=(($2+4)&4294967295);var $3=HEAP32[(($optind)>>2)];HEAP32[((_optind)>>2)]=$3;var $4=$data_addr;var $opterr=(($4+8)&4294967295);var $5=HEAP32[(($opterr)>>2)];HEAP32[((_opterr)>>2)]=$5;var $6=$data_addr;var $optopt=(($6+12)&4294967295);var $7=HEAP32[(($optopt)>>2)];HEAP32[((_optopt)>>2)]=$7;var $8=$data_addr;var $optwhere=(($8+16)&4294967295);var $9=HEAP32[(($optwhere)>>2)];HEAP32[((__ZL8optwhere)>>2)]=$9;;return;return;}
function _getopt_long($argc,$argv,$shortopts,$longopts,$longind){var __stackBase__=STACKTOP;STACKTOP+=20;_memset(__stackBase__,0,20);var __label__;var $argc_addr;var $argv_addr;var $shortopts_addr;var $longopts_addr;var $longind_addr;var $data=__stackBase__;var $r;$argc_addr=$argc;$argv_addr=$argv;$shortopts_addr=$shortopts;$longopts_addr=$longopts;$longind_addr=$longind;__ZL12read_globalsP11getopt_data($data);var $0=$argc_addr;var $1=$argv_addr;var $2=$shortopts_addr;var $3=$longopts_addr;var $4=$longind_addr;var $call=__ZL15getopt_internaliPKPcPKcPK6optionPiiP11getopt_data($0,$1,$2,$3,$4,0,$data);$r=$call;__ZL13write_globalsP11getopt_data($data);var $5=$r;STACKTOP=__stackBase__;return $5;return null;}
function _getopt_long_only($argc,$argv,$shortopts,$longopts,$longind){var __stackBase__=STACKTOP;STACKTOP+=20;_memset(__stackBase__,0,20);var __label__;var $argc_addr;var $argv_addr;var $shortopts_addr;var $longopts_addr;var $longind_addr;var $data=__stackBase__;var $r;$argc_addr=$argc;$argv_addr=$argv;$shortopts_addr=$shortopts;$longopts_addr=$longopts;$longind_addr=$longind;__ZL12read_globalsP11getopt_data($data);var $0=$argc_addr;var $1=$argv_addr;var $2=$shortopts_addr;var $3=$longopts_addr;var $4=$longind_addr;var $call=__ZL15getopt_internaliPKPcPKcPK6optionPiiP11getopt_data($0,$1,$2,$3,$4,1,$data);$r=$call;__ZL13write_globalsP11getopt_data($data);var $5=$r;STACKTOP=__stackBase__;return $5;return null;}
function ___getopt_r($argc,$argv,$optstring,$data){;var __label__;var $argc_addr;var $argv_addr;var $optstring_addr;var $data_addr;$argc_addr=$argc;$argv_addr=$argv;$optstring_addr=$optstring;$data_addr=$data;var $0=$argc_addr;var $1=$argv_addr;var $2=$optstring_addr;var $3=$data_addr;var $call=__ZL15getopt_internaliPKPcPKcPK6optionPiiP11getopt_data($0,$1,$2,0,0,0,$3);;return $call;return null;}
function ___getopt_long_r($argc,$argv,$shortopts,$longopts,$longind,$data){;var __label__;var $argc_addr;var $argv_addr;var $shortopts_addr;var $longopts_addr;var $longind_addr;var $data_addr;$argc_addr=$argc;$argv_addr=$argv;$shortopts_addr=$shortopts;$longopts_addr=$longopts;$longind_addr=$longind;$data_addr=$data;var $0=$argc_addr;var $1=$argv_addr;var $2=$shortopts_addr;var $3=$longopts_addr;var $4=$longind_addr;var $5=$data_addr;var $call=__ZL15getopt_internaliPKPcPKcPK6optionPiiP11getopt_data($0,$1,$2,$3,$4,0,$5);;return $call;return null;}
function ___getopt_long_only_r($argc,$argv,$shortopts,$longopts,$longind,$data){;var __label__;var $argc_addr;var $argv_addr;var $shortopts_addr;var $longopts_addr;var $longind_addr;var $data_addr;$argc_addr=$argc;$argv_addr=$argv;$shortopts_addr=$shortopts;$longopts_addr=$longopts;$longind_addr=$longind;$data_addr=$data;var $0=$argc_addr;var $1=$argv_addr;var $2=$shortopts_addr;var $3=$longopts_addr;var $4=$longind_addr;var $5=$data_addr;var $call=__ZL15getopt_internaliPKPcPKcPK6optionPiiP11getopt_data($0,$1,$2,$3,$4,1,$5);;return $call;return null;}
function __ZL9is_optionPci($argv_element,$only){;var __label__;var __lastLabel__=null;var $argv_element_addr;var $only_addr;$argv_element_addr=$argv_element;$only_addr=$only;var $0=$argv_element_addr;var $cmp=((($0))|0)==0;if($cmp){__lastLabel__=0;__label__=4;;}else{__lastLabel__=0;__label__=1;;}
$lor_end$$lor_lhs_false$2:do{if(__label__==1){var $1=$argv_element_addr;var $arrayidx=(($1)&4294967295);var $2=HEAP8[($arrayidx)];var $conv=(tempInt=(($2)),(tempInt>=128?tempInt-256:tempInt));var $cmp1=((($conv))|0)==45;if($cmp1){__lastLabel__=1;__label__=4;break $lor_end$$lor_lhs_false$2;}else{__lastLabel__=1;;}
var $3=$only_addr;var $tobool=((($3))|0)!=0;if($tobool){__lastLabel__=2;;}else{__lastLabel__=2;__label__=4;break $lor_end$$lor_lhs_false$2;}
var $4=$argv_element_addr;var $arrayidx2=(($4)&4294967295);var $5=HEAP8[($arrayidx2)];var $conv3=(tempInt=(($5)),(tempInt>=128?tempInt-256:tempInt));var $cmp4=((($conv3))|0)==43;__lastLabel__=3;;}}while(0);var $6=__lastLabel__==1?1:(__lastLabel__==0?1:(__lastLabel__==2?0:($cmp4)));var $conv5=((($6))&1);;return $conv5;return null;}
function __ZL7permutePKPcii($argv,$len1,$len2){;var __label__;var $argv_addr;var $len1_addr;var $len2_addr;$argv_addr=$argv;$len1_addr=$len1;$len2_addr=$len2;var $0=$argv_addr;var $1=$len1_addr;__ZL21reverse_argv_elementsPPci($0,$1);var $2=$argv_addr;var $3=$len1_addr;var $4=$len2_addr;var $add=((($4)+($3))&4294967295);__ZL21reverse_argv_elementsPPci($2,$add);var $5=$argv_addr;var $6=$len2_addr;__ZL21reverse_argv_elementsPPci($5,$6);;return;return;}
function __ZL21reverse_argv_elementsPPci($argv,$num){;var __label__;var $argv_addr;var $num_addr;var $i;var $tmp;$argv_addr=$argv;$num_addr=$num;$i=0;var $0=$i;var $1=$num_addr;var $shr2=($1)>>1;var $cmp3=((($0))|0)<((($shr2))|0);if($cmp3){__label__=1;;}else{__label__=2;;}
$for_body$$for_end$2:do{if(__label__==1){while(1){var $2=$i;var $3=$argv_addr;var $arrayidx=(($3+4*$2)&4294967295);var $4=HEAP32[(($arrayidx)>>2)];$tmp=$4;var $5=$num_addr;var $6=$i;var $_neg=(((-($6)))&4294967295);var $sub=((($5)-1)&4294967295);var $sub1=((($sub)+($_neg))&4294967295);var $7=$argv_addr;var $arrayidx2=(($7+4*$sub1)&4294967295);var $8=HEAP32[(($arrayidx2)>>2)];var $9=$i;var $10=$argv_addr;var $arrayidx3=(($10+4*$9)&4294967295);HEAP32[(($arrayidx3)>>2)]=$8;var $11=$tmp;var $12=$num_addr;var $13=$i;var $_neg1=(((-($13)))&4294967295);var $sub4=((($12)-1)&4294967295);var $sub5=((($sub4)+($_neg1))&4294967295);var $14=$argv_addr;var $arrayidx6=(($14+4*$sub5)&4294967295);HEAP32[(($arrayidx6)>>2)]=$11;var $15=$i;var $inc=((($15)+1)&4294967295);$i=$inc;var $16=$i;var $17=$num_addr;var $shr=($17)>>1;var $cmp=((($16))|0)<((($shr))|0);if($cmp){__label__=1;continue;}else{__label__=2;break $for_body$$for_end$2;}}}}while(0);;return;return;}
function ___strtok_r($s,$delim,$lasts,$skip_leading_delim){;var __label__;var $retval;var $s_addr;var $delim_addr;var $lasts_addr;var $skip_leading_delim_addr;var $spanp;var $c;var $sc;var $tok;$s_addr=$s;$delim_addr=$delim;$lasts_addr=$lasts;$skip_leading_delim_addr=$skip_leading_delim;var $0=$s_addr;var $cmp=((($0))|0)==0;if($cmp){__label__=1;;}else{__label__=3;;}
$land_lhs_true$$cont$2:do{if(__label__==1){var $1=$lasts_addr;var $2=HEAP32[(($1)>>2)];$s_addr=$2;var $cmp1=((($2))|0)==0;if(!($cmp1)){__label__=3;break $land_lhs_true$$cont$2;}
$retval=0;__label__=18;break $land_lhs_true$$cont$2;}}while(0);if(__label__==3){$cont$6:while(1){var $3=$s_addr;var $incdec_ptr=(($3+1)&4294967295);$s_addr=$incdec_ptr;var $4=HEAP8[($3)];var $conv=(tempInt=(($4)),(tempInt>=128?tempInt-256:tempInt));$c=$conv;var $5=$delim_addr;$spanp=$5;;while(1){var $6=$spanp;var $incdec_ptr2=(($6+1)&4294967295);$spanp=$incdec_ptr2;var $7=HEAP8[($6)];var $conv3=(tempInt=(($7)),(tempInt>=128?tempInt-256:tempInt));$sc=$conv3;var $cmp4=((($conv3))|0)!=0;var $8=$c;if(!($cmp4)){__label__=8;break $cont$6;}
var $9=$sc;var $cmp5=((($8))|0)==((($9))|0);if($cmp5){__label__=6;break;}else{__label__=4;continue;}}
var $10=$skip_leading_delim_addr;var $tobool=((($10))|0)!=0;if($tobool){__label__=3;continue $cont$6;}else{__label__=7;break $cont$6;}}
if(__label__==8){var $cmp9=((($8))|0)==0;if($cmp9){__label__=9;;}else{__label__=10;;}
if(__label__==9){var $15=$lasts_addr;HEAP32[(($15)>>2)]=0;$retval=0;;}
else if(__label__==10){var $16=$s_addr;var $add_ptr12=(($16+-1)&4294967295);$tok=$add_ptr12;;$for_cond13$17:while(1){var $17=$s_addr;var $incdec_ptr14=(($17+1)&4294967295);$s_addr=$incdec_ptr14;var $18=HEAP8[($17)];var $conv15=(tempInt=(($18)),(tempInt>=128?tempInt-256:tempInt));$c=$conv15;var $19=$delim_addr;$spanp=$19;;while(1){var $20=$spanp;var $incdec_ptr16=(($20+1)&4294967295);$spanp=$incdec_ptr16;var $21=HEAP8[($20)];var $conv17=(tempInt=(($21)),(tempInt>=128?tempInt-256:tempInt));$sc=$conv17;var $22=$c;var $cmp18=((($conv17))|0)==((($22))|0);if($cmp18){__label__=13;break $for_cond13$17;}
var $28=$sc;var $cmp26=((($28))|0)!=0;if($cmp26){__label__=12;continue;}else{__label__=11;continue $for_cond13$17;}}}
var $23=$c;var $cmp20=((($23))|0)==0;if($cmp20){__label__=14;;}else{__label__=15;;}
if(__label__==14){$s_addr=0;;}
else if(__label__==15){var $24=$s_addr;var $arrayidx23=(($24+-1)&4294967295);HEAP8[($arrayidx23)]=0;;}
var $25=$s_addr;var $26=$lasts_addr;HEAP32[(($26)>>2)]=$25;var $27=$tok;$retval=$27;;}}
else if(__label__==7){var $11=$s_addr;var $12=$lasts_addr;HEAP32[(($12)>>2)]=$11;var $13=$s_addr;var $arrayidx=(($13+-1)&4294967295);HEAP8[($arrayidx)]=0;var $14=$s_addr;var $add_ptr=(($14+-1)&4294967295);$retval=$add_ptr;;}}
var $29=$retval;;return $29;return null;}
function _strtok_r($s,$delim,$lasts){;var __label__;var $s_addr;var $delim_addr;var $lasts_addr;$s_addr=$s;$delim_addr=$delim;$lasts_addr=$lasts;var $0=$s_addr;var $1=$delim_addr;var $2=$lasts_addr;var $call=___strtok_r($0,$1,$2,1);;return $call;return null;}
function _strtok($s,$delim){var __stackBase__=STACKTOP;STACKTOP+=4;_memset(__stackBase__,0,4);var __label__;var $s_addr;var $delim_addr;var $chr=__stackBase__;$s_addr=$s;$delim_addr=$delim;var $0=$s_addr;var $1=$delim_addr;var $call=___strtok_r($0,$1,$chr,1);STACKTOP=__stackBase__;return $call;return null;}
Module.callMain=function callMain(args){var argc=args.length+1;function pad(){for(var i=0;i<4-1;i++){argv.push(0);}}
var argv=[allocate(intArrayFromString("/bin/this.program"),'i8',ALLOC_STATIC)];pad();for(var i=0;i<argc-1;i=i+1){argv.push(allocate(intArrayFromString(args[i]),'i8',ALLOC_STATIC));pad();}
argv.push(0);argv=allocate(argv,'i32',ALLOC_STATIC);return _main(argc,argv,0);}
function run(args){args=args||Module.arguments;_path_home=allocate(150,"i8",ALLOC_STATIC);_filetype=allocate(5,"i8",ALLOC_STATIC);_wavefile=allocate(200,"i8",ALLOC_STATIC);_uri_callback=allocate(1,"i32 (i32, i8*, i8*)*",ALLOC_STATIC);_phoneme_callback=allocate(1,"i32 (i8*)*",ALLOC_STATIC);_f_wave=allocate(1,"%struct.__sFILE*",ALLOC_STATIC);_quiet=allocate(1,"i32",ALLOC_STATIC);_samples_total=allocate(1,"i32",ALLOC_STATIC);_samples_split=allocate(1,"i32",ALLOC_STATIC);_wavefile_count=allocate(1,"i32",ALLOC_STATIC);_end_of_sentence=allocate(1,"i32",ALLOC_STATIC);_voice_pcnt=allocate(60,"i16",ALLOC_STATIC);__ZZ13DisplayVoicesP7__sFILEPcE7genders=allocate([32,77,70,32],"i8",ALLOC_STATIC);__str1=allocate([80,116,121,32,76,97,110,103,117,97,103,101,32,65,103,101,47,71,101,110,100,101,114,32,86,111,105,99,101,78,97,109,101,32,32,32,32,32,32,32,70,105,108,101,32,32,32,32,32,32,32,32,79,116,104,101,114,32,76,97,110,103,115,10,0],"i8",ALLOC_STATIC);__str3=allocate([37,51,100,0],"i8",ALLOC_STATIC);__str4=allocate([37,50,100,32,32,37,45,49,50,115,37,115,37,99,32,32,37,45,49,55,115,32,37,45,49,49,115,32,0],"i8",ALLOC_STATIC);__str5=allocate([40,37,115,32,37,100,41,0],"i8",ALLOC_STATIC);__ZZ4mainE12long_options=allocate([0,0,0,0,0,0,0,0,0,0,0,0,104,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,256,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,257,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,258,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,259,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,260,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,261,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,262,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,263,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,264,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,265,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,266,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str6=allocate([104,101,108,112,0],"i8",ALLOC_STATIC);__str7=allocate([115,116,100,105,110,0],"i8",ALLOC_STATIC);__str8=allocate([99,111,109,112,105,108,101,45,100,101,98,117,103,0],"i8",ALLOC_STATIC);__str9=allocate([99,111,109,112,105,108,101,0],"i8",ALLOC_STATIC);__str10=allocate([112,117,110,99,116,0],"i8",ALLOC_STATIC);__str11=allocate([118,111,105,99,101,115,0],"i8",ALLOC_STATIC);__str12=allocate([115,116,100,111,117,116,0],"i8",ALLOC_STATIC);__str13=allocate([115,112,108,105,116,0],"i8",ALLOC_STATIC);__str14=allocate([112,97,116,104,0],"i8",ALLOC_STATIC);__str15=allocate([112,104,111,110,111,117,116,0],"i8",ALLOC_STATIC);__str16=allocate([112,104,111,0],"i8",ALLOC_STATIC);__str17=allocate([105,112,97,0],"i8",ALLOC_STATIC);__str18=allocate([70,97,105,108,101,100,32,116,111,32,114,101,97,100,32,0],"i8",ALLOC_STATIC);__str19=allocate([97,58,98,58,102,58,103,58,104,107,58,108,58,112,58,113,115,58,118,58,119,58,120,88,109,122,0],"i8",ALLOC_STATIC);__str21=allocate([10,115,112,101,97,107,32,116,101,120,116,45,116,111,45,115,112,101,101,99,104,58,32,37,115,32,32,32,68,97,116,97,32,97,116,58,32,37,115,10,37,115,0],"i8",ALLOC_STATIC);__str23=allocate([67,97,110,39,116,32,119,114,105,116,101,32,116,111,58,32,37,115,10,0],"i8",ALLOC_STATIC);__str25=allocate([37,115,118,111,105,99,101,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__str27=allocate([37,115,102,105,108,101,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__str28=allocate([67,97,110,39,116,32,119,114,105,116,101,32,116,111,32,111,117,116,112,117,116,32,102,105,108,101,32,39,37,115,39,10,39,0],"i8",ALLOC_STATIC);__str29=allocate([45,119,32,111,112,116,105,111,110,32,109,117,115,116,32,98,101,32,117,115,101,100,32,98,101,99,97,117,115,101,32,116,104,101,32,112,114,111,103,114,97,109,32,119,97,115,32,98,117,105,108,116,32,119,105,116,104,111,117,116,32,97,32,115,111,117,110,100,32,105,110,116,101,114,102,97,99,101,10,0],"i8",ALLOC_STATIC);__str30=allocate([37,115,95,37,46,50,100,37,115,0],"i8",ALLOC_STATIC);__ZZL12OpenWaveFilePKciE8wave_hdr=allocate([82,73,70,70,36,240,255,127,87,65,86,69,102,109,116,32,16,0,0,0,1,0,1,0,9,61,0,0,18,122,0,0,2,0,16,0,100,97,116,97,0,240,255,127],"i8",ALLOC_STATIC);__str32=allocate([101,110,95,85,83,46,85,84,70,45,56,0],"i8",ALLOC_STATIC);__str33=allocate([85,84,70,45,56,0],"i8",ALLOC_STATIC);__str35=allocate([70,97,105,108,101,100,32,116,111,32,108,111,97,100,32,101,115,112,101,97,107,45,100,97,116,97,10,0],"i8",ALLOC_STATIC);__str36=allocate([87,114,111,110,103,32,118,101,114,115,105,111,110,32,111,102,32,101,115,112,101,97,107,45,100,97,116,97,32,48,120,37,120,32,40,101,120,112,101,99,116,115,32,48,120,37,120,41,32,97,116,32,37,115,10,0],"i8",ALLOC_STATIC);__str37=allocate([10,115,112,101,97,107,32,91,111,112,116,105,111,110,115,93,32,91,34,60,119,111,114,100,115,62,34,93,10,10,45,102,32,60,116,101,120,116,32,102,105,108,101,62,32,32,32,84,101,120,116,32,102,105,108,101,32,116,111,32,115,112,101,97,107,10,45,45,115,116,100,105,110,32,32,32,32,82,101,97,100,32,116,101,120,116,32,105,110,112,117,116,32,102,114,111,109,32,115,116,100,105,110,32,105,110,115,116,101,97,100,32,111,102,32,97,32,102,105,108,101,10,10,73,102,32,110,101,105,116,104,101,114,32,45,102,32,110,111,114,32,45,45,115,116,100,105,110,44,32,116,104,101,110,32,60,119,111,114,100,115,62,32,97,114,101,32,115,112,111,107,101,110,44,32,111,114,32,105,102,32,110,111,110,101,32,116,104,101,110,32,116,101,120,116,10,105,115,32,115,112,111,107,101,110,32,102,114,111,109,32,115,116,100,105,110,44,32,101,97,99,104,32,108,105,110,101,32,115,101,112,97,114,97,116,101,108,121,46,10,10,45,97,32,60,105,110,116,101,103,101,114,62,10,9,32,32,32,65,109,112,108,105,116,117,100,101,44,32,48,32,116,111,32,50,48,48,44,32,100,101,102,97,117,108,116,32,105,115,32,49,48,48,10,45,103,32,60,105,110,116,101,103,101,114,62,10,9,32,32,32,87,111,114,100,32,103,97,112,46,32,80,97,117,115,101,32,98,101,116,119,101,101,110,32,119,111,114,100,115,44,32,117,110,105,116,115,32,111,102,32,49,48,109,83,32,97,116,32,116,104,101,32,100,101,102,97,117,108,116,32,115,112,101,101,100,10,45,107,32,60,105,110,116,101,103,101,114,62,10,9,32,32,32,73,110,100,105,99,97,116,101,32,99,97,112,105,116,97,108,32,108,101,116,116,101,114,115,32,119,105,116,104,58,32,49,61,115,111,117,110,100,44,32,50,61,116,104,101,32,119,111,114,100,32,34,99,97,112,105,116,97,108,115,34,44,10,9,32,32,32,104,105,103,104,101,114,32,118,97,108,117,101,115,32,105,110,100,105,99,97,116,101,32,97,32,112,105,116,99,104,32,105,110,99,114,101,97,115,101,32,40,116,114,121,32,45,107,50,48,41,46,10,45,108,32,60,105,110,116,101,103,101,114,62,10,9,32,32,32,76,105,110,101,32,108,101,110,103,116,104,46,32,73,102,32,110,111,116,32,122,101,114,111,32,40,119,104,105,99,104,32,105,115,32,116,104,101,32,100,101,102,97,117,108,116,41,44,32,99,111,110,115,105,100,101,114,10,9,32,32,32,108,105,110,101,115,32,108,101,115,115,32,116,104,97,110,32,116,104,105,115,32,108,101,110,103,116,104,32,97,115,32,101,110,100,45,111,102,45,99,108,97,117,115,101,10,45,112,32,60,105,110,116,101,103,101,114,62,10,9,32,32,32,80,105,116,99,104,32,97,100,106,117,115,116,109,101,110,116,44,32,48,32,116,111,32,57,57,44,32,100,101,102,97,117,108,116,32,105,115,32,53,48,10,45,115,32,60,105,110,116,101,103,101,114,62,10,9,32,32,32,83,112,101,101,100,32,105,110,32,119,111,114,100,115,32,112,101,114,32,109,105,110,117,116,101,44,32,56,48,32,116,111,32,52,53,48,44,32,100,101,102,97,117,108,116,32,105,115,32,49,55,53,10,45,118,32,60,118,111,105,99,101,32,110,97,109,101,62,10,9,32,32,32,85,115,101,32,118,111,105,99,101,32,102,105,108,101,32,111,102,32,116,104,105,115,32,110,97,109,101,32,102,114,111,109,32,101,115,112,101,97,107,45,100,97,116,97,47,118,111,105,99,101,115,10,45,119,32,60,119,97,118,101,32,102,105,108,101,32,110,97,109,101,62,10,9,32,32,32,87,114,105,116,101,32,115,112,101,101,99,104,32,116,111,32,116,104,105,115,32,87,65,86,32,102,105,108,101,44,32,114,97,116,104,101,114,32,116,104,97,110,32,115,112,101,97,107,105,110,103,32,105,116,32,100,105,114,101,99,116,108,121,10,45,98,9,32,32,32,73,110,112,117,116,32,116,101,120,116,32,101,110,99,111,100,105,110,103,44,32,49,61,85,84,70,56,44,32,50,61,56,32,98,105,116,44,32,52,61,49,54,32,98,105,116,32,10,45,109,9,32,32,32,73,110,116,101,114,112,114,101,116,32,83,83,77,76,32,109,97,114,107,117,112,44,32,97,110,100,32,105,103,110,111,114,101,32,111,116,104,101,114,32,60,32,62,32,116,97,103,115,10,45,113,9,32,32,32,81,117,105,101,116,44,32,100,111,110,39,116,32,112,114,111,100,117,99,101,32,97,110,121,32,115,112,101,101,99,104,32,40,109,97,121,32,98,101,32,117,115,101,102,117,108,32,119,105,116,104,32,45,120,41,10,45,120,9,32,32,32,87,114,105,116,101,32,112,104,111,110,101,109,101,32,109,110,101,109,111,110,105,99,115,32,116,111,32,115,116,100,111,117,116,10,45,88,9,32,32,32,87,114,105,116,101,32,112,104,111,110,101,109,101,115,32,109,110,101,109,111,110,105,99,115,32,97,110,100,32,116,114,97,110,115,108,97,116,105,111,110,32,116,114,97,99,101,32,116,111,32,115,116,100,111,117,116,10,45,122,9,32,32,32,78,111,32,102,105,110,97,108,32,115,101,110,116,101,110,99,101,32,112,97,117,115,101,32,97,116,32,116,104,101,32,101,110,100,32,111,102,32,116,104,101,32,116,101,120,116,10,45,45,99,111,109,112,105,108,101,61,60,118,111,105,99,101,32,110,97,109,101,62,10,9,32,32,32,67,111,109,112,105,108,101,32,112,114,111,110,117,110,99,105,97,116,105,111,110,32,114,117,108,101,115,32,97,110,100,32,100,105,99,116,105,111,110,97,114,121,32,102,114,111,109,32,116,104,101,32,99,117,114,114,101,110,116,10,9,32,32,32,100,105,114,101,99,116,111,114,121,46,32,60,118,111,105,99,101,32,110,97,109,101,62,32,115,112,101,99,105,102,105,101,115,32,116,104,101,32,108,97,110,103,117,97,103,101,10,45,45,105,112,97,32,32,32,32,32,32,87,114,105,116,101,32,112,104,111,110,101,109,101,115,32,116,111,32,115,116,100,111,117,116,32,117,115,105,110,103,32,73,110,116,101,114,110,97,116,105,111,110,97,108,32,80,104,111,110,101,116,105,99,32,65,108,112,104,97,98,101,116,10,45,45,112,97,116,104,61,34,60,112,97,116,104,62,34,10,9,32,32,32,83,112,101,99,105,102,105,101,115,32,116,104,101,32,100,105,114,101,99,116,111,114,121,32,99,111,110,116,97,105,110,105,110,103,32,116,104,101,32,101,115,112,101,97,107,45,100,97,116,97,32,100,105,114,101,99,116,111,114,121,10,45,45,112,104,111,32,32,32,32,32,32,87,114,105,116,101,32,109,98,114,111,108,97,32,112,104,111,110,101,109,101,32,100,97,116,97,32,40,46,112,104,111,41,32,116,111,32,115,116,100,111,117,116,32,111,114,32,116,111,32,116,104,101,32,102,105,108,101,32,105,110,32,45,45,112,104,111,110,111,117,116,10,45,45,112,104,111,110,111,117,116,61,34,60,102,105,108,101,110,97,109,101,62,34,10,9,32,32,32,87,114,105,116,101,32,112,104,111,110,101,109,101,32,111,117,116,112,117,116,32,102,114,111,109,32,45,120,32,45,88,32,45,45,105,112,97,32,97,110,100,32,45,45,112,104,111,32,116,111,32,116,104,105,115,32,102,105,108,101,10,45,45,112,117,110,99,116,61,34,60,99,104,97,114,97,99,116,101,114,115,62,34,10,9,32,32,32,83,112,101,97,107,32,116,104,101,32,110,97,109,101,115,32,111,102,32,112,117,110,99,116,117,97,116,105,111,110,32,99,104,97,114,97,99,116,101,114,115,32,100,117,114,105,110,103,32,115,112,101,97,107,105,110,103,46,32,32,73,102,10,9,32,32,32,61,60,99,104,97,114,97,99,116,101,114,115,62,32,105,115,32,111,109,105,116,116,101,100,44,32,97,108,108,32,112,117,110,99,116,117,97,116,105,111,110,32,105,115,32,115,112,111,107,101,110,46,10,45,45,115,112,108,105,116,61,34,60,109,105,110,117,116,101,115,62,34,10,9,32,32,32,83,116,97,114,116,115,32,97,32,110,101,119,32,87,65,86,32,102,105,108,101,32,101,118,101,114,121,32,60,109,105,110,117,116,101,115,62,46,32,32,85,115,101,100,32,119,105,116,104,32,45,119,10,45,45,115,116,100,111,117,116,32,32,32,87,114,105,116,101,32,115,112,101,101,99,104,32,111,117,116,112,117,116,32,116,111,32,115,116,100,111,117,116,10,45,45,118,111,105,99,101,115,61,60,108,97,110,103,117,97,103,101,62,10,9,32,32,32,76,105,115,116,32,116,104,101,32,97,118,97,105,108,97,98,108,101,32,118,111,105,99,101,115,32,102,111,114,32,116,104,101,32,115,112,101,99,105,102,105,101,100,32,108,97,110,103,117,97,103,101,46,10,9,32,32,32,73,102,32,60,108,97,110,103,117,97,103,101,62,32,105,115,32,111,109,105,116,116,101,100,44,32,116,104,101,110,32,108,105,115,116,32,97,108,108,32,118,111,105,99,101,115,46,10,0],"i8",ALLOC_STATIC);__str38=allocate([37,115,47,101,115,112,101,97,107,45,100,97,116,97,0],"i8",ALLOC_STATIC);__str39=allocate([69,83,80,69,65,75,95,68,65,84,65,95,80,65,84,72,0],"i8",ALLOC_STATIC);__str40=allocate([72,79,77,69,0],"i8",ALLOC_STATIC);__str41=allocate([47,117,115,114,47,115,104,97,114,101,47,101,115,112,101,97,107,45,100,97,116,97,0],"i8",ALLOC_STATIC);__ZL5f_log=allocate(1,"%struct.__sFILE*",ALLOC_STATIC);__str42=allocate([117,110,112,114,0],"i8",ALLOC_STATIC);__str143=allocate([119,95,97,108,116,50,0],"i8",ALLOC_STATIC);__str244=allocate([119,95,97,108,116,51,0],"i8",ALLOC_STATIC);__str345=allocate([119,95,97,108,116,0],"i8",ALLOC_STATIC);__str446=allocate([112,95,97,108,116,50,0],"i8",ALLOC_STATIC);__str547=allocate([112,95,97,108,116,51,0],"i8",ALLOC_STATIC);__str648=allocate([112,95,97,108,116,0],"i8",ALLOC_STATIC);_mnem_rules=allocate([0,0,0,0,1,0,0,0,0,0,0,0,18,0,0,0,0,0,0,0,19,0,0,0,0,0,0,0,17,0,0,0,0,0,0,0,34,0,0,0,0,0,0,0,35,0,0,0,0,0,0,0,33,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str749=allocate([36,49,0],"i8",ALLOC_STATIC);__str850=allocate([36,50,0],"i8",ALLOC_STATIC);__str951=allocate([36,51,0],"i8",ALLOC_STATIC);__str1052=allocate([36,52,0],"i8",ALLOC_STATIC);__str1153=allocate([36,53,0],"i8",ALLOC_STATIC);__str1254=allocate([36,54,0],"i8",ALLOC_STATIC);__str1355=allocate([36,55,0],"i8",ALLOC_STATIC);__str1456=allocate([36,117,0],"i8",ALLOC_STATIC);__str1557=allocate([36,117,49,0],"i8",ALLOC_STATIC);__str1658=allocate([36,117,50,0],"i8",ALLOC_STATIC);__str1759=allocate([36,117,51,0],"i8",ALLOC_STATIC);__str1860=allocate([36,117,43,0],"i8",ALLOC_STATIC);__str1961=allocate([36,117,49,43,0],"i8",ALLOC_STATIC);__str2062=allocate([36,117,50,43,0],"i8",ALLOC_STATIC);__str2163=allocate([36,117,51,43,0],"i8",ALLOC_STATIC);__str2264=allocate([36,112,97,117,115,101,0],"i8",ALLOC_STATIC);__str2365=allocate([36,111,110,108,121,0],"i8",ALLOC_STATIC);__str2466=allocate([36,111,110,108,121,115,0],"i8",ALLOC_STATIC);__str2567=allocate([36,115,116,114,101,110,100,0],"i8",ALLOC_STATIC);__str2668=allocate([36,115,116,114,101,110,100,50,0],"i8",ALLOC_STATIC);__str2769=allocate([36,117,110,115,116,114,101,115,115,101,110,100,0],"i8",ALLOC_STATIC);__str2870=allocate([36,97,116,101,110,100,0],"i8",ALLOC_STATIC);__str2971=allocate([36,97,116,115,116,97,114,116,0],"i8",ALLOC_STATIC);__str3072=allocate([36,97,98,98,114,101,118,0],"i8",ALLOC_STATIC);__str3173=allocate([36,115,116,101,109,0],"i8",ALLOC_STATIC);__str3274=allocate([36,100,111,117,98,108,101,0],"i8",ALLOC_STATIC);__str3375=allocate([36,97,108,116,0],"i8",ALLOC_STATIC);__str3476=allocate([36,97,108,116,49,0],"i8",ALLOC_STATIC);__str3577=allocate([36,97,108,116,50,0],"i8",ALLOC_STATIC);__str3678=allocate([36,97,108,116,51,0],"i8",ALLOC_STATIC);__str3779=allocate([36,99,111,109,98,105,110,101,0],"i8",ALLOC_STATIC);__str3880=allocate([36,100,111,116,0],"i8",ALLOC_STATIC);__str3981=allocate([36,104,97,115,100,111,116,0],"i8",ALLOC_STATIC);__str4082=allocate([36,109,97,120,51,0],"i8",ALLOC_STATIC);__str4183=allocate([36,98,114,107,0],"i8",ALLOC_STATIC);__str4284=allocate([36,116,101,120,116,0],"i8",ALLOC_STATIC);__str43=allocate([36,118,101,114,98,102,0],"i8",ALLOC_STATIC);__str44=allocate([36,118,101,114,98,115,102,0],"i8",ALLOC_STATIC);__str45=allocate([36,110,111,117,110,102,0],"i8",ALLOC_STATIC);__str46=allocate([36,112,97,115,116,102,0],"i8",ALLOC_STATIC);__str47=allocate([36,118,101,114,98,0],"i8",ALLOC_STATIC);__str48=allocate([36,110,111,117,110,0],"i8",ALLOC_STATIC);__str49=allocate([36,112,97,115,116,0],"i8",ALLOC_STATIC);__str50=allocate([36,118,101,114,98,101,120,116,101,110,100,0],"i8",ALLOC_STATIC);__str51=allocate([36,99,97,112,105,116,97,108,0],"i8",ALLOC_STATIC);__str52=allocate([36,97,108,108,99,97,112,115,0],"i8",ALLOC_STATIC);__str53=allocate([36,97,99,99,101,110,116,0],"i8",ALLOC_STATIC);__str54=allocate([36,115,101,110,116,101,110,99,101,0],"i8",ALLOC_STATIC);__str55=allocate([36,63,0],"i8",ALLOC_STATIC);__str56=allocate([36,116,101,120,116,109,111,100,101,0],"i8",ALLOC_STATIC);__str57=allocate([36,112,104,111,110,101,109,101,109,111,100,101,0],"i8",ALLOC_STATIC);_mnem_flags=allocate([0,0,0,0,65,0,0,0,0,0,0,0,66,0,0,0,0,0,0,0,67,0,0,0,0,0,0,0,68,0,0,0,0,0,0,0,69,0,0,0,0,0,0,0,70,0,0,0,0,0,0,0,71,0,0,0,0,0,0,0,72,0,0,0,0,0,0,0,73,0,0,0,0,0,0,0,74,0,0,0,0,0,0,0,75,0,0,0,0,0,0,0,76,0,0,0,0,0,0,0,77,0,0,0,0,0,0,0,78,0,0,0,0,0,0,0,79,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,13,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,17,0,0,0,0,0,0,0,18,0,0,0,0,0,0,0,19,0,0,0,0,0,0,0,20,0,0,0,0,0,0,0,20,0,0,0,0,0,0,0,21,0,0,0,0,0,0,0,22,0,0,0,0,0,0,0,23,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,25,0,0,0,0,0,0,0,27,0,0,0,0,0,0,0,28,0,0,0,0,0,0,0,29,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,33,0,0,0,0,0,0,0,34,0,0,0,0,0,0,0,35,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,37,0,0,0,0,0,0,0,38,0,0,0,0,0,0,0,40,0,0,0,0,0,0,0,41,0,0,0,0,0,0,0,42,0,0,0,0,0,0,0,43,0,0,0,0,0,0,0,45,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,200,0,0,0,0,0,0,0,201,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ22print_dictionary_flagsPjE3buf=allocate(20,"i8",ALLOC_STATIC);__str59=allocate([37,115,32,32,48,120,37,120,47,37,120,0],"i8",ALLOC_STATIC);__ZZ10DecodeRulePKciPciE6output=allocate(60,"i8",ALLOC_STATIC);__ZZ10DecodeRulePKciPciE7symbols=allocate([32,32,32,32,32,32,32,32,32,32,38,37,43,35,83,68,90,65,76,33,32,64,63,74,78,75,86,63,84,88,63,87],"i8",ALLOC_STATIC);__ZZ10DecodeRulePKciPciE10symbols_lg=allocate([65,66,67,72,70,71,89],"i8",ALLOC_STATIC);__str60=allocate([32,40,0],"i8",ALLOC_STATIC);__str61=allocate([101,105,112,118,100,102,113,32,116,98,97,32,0],"i8",ALLOC_STATIC);__str62=allocate([37,99,37,100,0],"i8",ALLOC_STATIC);__str64=allocate([37,53,100,58,9,0],"i8",ALLOC_STATIC);__str65=allocate([63,37,100,32,0],"i8",ALLOC_STATIC);__ZL11error_count=allocate(1,"i32",ALLOC_STATIC);__ZL21error_need_dictionary=allocate(1,"i32",ALLOC_STATIC);__ZL19letterGroupsDefined=allocate(26,"i8",ALLOC_STATIC);__ZL10debug_flag=allocate(1,"i32",ALLOC_STATIC);__str66=allocate([37,115,37,115,95,0],"i8",ALLOC_STATIC);__str67=allocate([37,115,114,117,108,101,115,46,116,120,116,0],"i8",ALLOC_STATIC);__str69=allocate([37,115,114,117,108,101,115,0],"i8",ALLOC_STATIC);__str71=allocate([119,98,43,0],"i8",ALLOC_STATIC);__str72=allocate([37,115,37,99,116,101,109,112,0],"i8",ALLOC_STATIC);__str73=allocate([85,115,105,110,103,32,112,104,111,110,101,109,101,116,97,98,108,101,58,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__str74=allocate([114,111,111,116,115,0],"i8",ALLOC_STATIC);__str75=allocate([108,105,115,116,0],"i8",ALLOC_STATIC);__str76=allocate([108,105,115,116,120,0],"i8",ALLOC_STATIC);__str77=allocate([101,120,116,114,97,0],"i8",ALLOC_STATIC);__str78=allocate([67,111,109,112,105,108,105,110,103,58,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__ZL7linenum=allocate(1,"i32",ALLOC_STATIC);__ZL10group_name=allocate(13,"i8",ALLOC_STATIC);__str79=allocate([119,98,0],"i8",ALLOC_STATIC);__ZL9group3_ix=allocate(1,"i32",ALLOC_STATIC);__str81=allocate([46,76,0],"i8",ALLOC_STATIC);__str82=allocate([46,114,101,112,108,97,99,101,0],"i8",ALLOC_STATIC);__str83=allocate([46,103,114,111,117,112,0],"i8",ALLOC_STATIC);__str84=allocate([48,120,37,120,0],"i8",ALLOC_STATIC);__str85=allocate([37,53,100,58,32,71,114,111,117,112,32,110,97,109,101,32,108,111,110,103,101,114,32,116,104,97,110,32,50,32,98,121,116,101,115,32,40,85,84,70,56,41,0],"i8",ALLOC_STATIC);__str89=allocate([9,37,100,32,114,117,108,101,115,44,32,37,100,32,103,114,111,117,112,115,32,40,37,100,41,10,10,0],"i8",ALLOC_STATIC);__ZL9rule_cond=allocate(80,"i8",ALLOC_STATIC);__ZL8rule_pre=allocate(80,"i8",ALLOC_STATIC);__ZL9rule_post=allocate(80,"i8",ALLOC_STATIC);__ZL10rule_match=allocate(80,"i8",ALLOC_STATIC);__ZL13rule_phonemes=allocate(80,"i8",ALLOC_STATIC);__str90=allocate([37,53,100,58,32,83,121,110,116,97,120,32,101,114,114,111,114,46,32,83,112,97,99,101,32,97,102,116,101,114,32,40,10,0],"i8",ALLOC_STATIC);__str91=allocate([36,103,114,111,117,112,0],"i8",ALLOC_STATIC);__str92=allocate([37,53,100,58,32,83,121,110,116,97,120,32,101,114,114,111,114,10,0],"i8",ALLOC_STATIC);__str93=allocate([37,53,100,58,32,66,97,100,32,112,104,111,110,101,109,101,32,91,37,99,93,32,105,110,32,37,115,10,0],"i8",ALLOC_STATIC);__str94=allocate([37,53,100,58,32,87,114,111,110,103,32,105,110,105,116,105,97,108,32,108,101,116,116,101,114,115,32,39,37,115,39,32,102,111,114,32,103,114,111,117,112,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__str95=allocate([37,53,100,58,32,98,97,100,32,99,111,110,100,105,116,105,111,110,32,110,117,109,98,101,114,32,63,37,100,10,0],"i8",ALLOC_STATIC);__ZZL16copy_rule_stringPcRiE6outbuf=allocate(20,"i8*",ALLOC_STATIC);__ZZL16copy_rule_stringPcRiE10next_state=allocate([2,0,0,0,2,0,0,0,4,0,0,0,4,0,0,0,4,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZL16copy_rule_stringPcRiE16lettergp_letters=allocate([0,1,2,0,0,4,5,3,6],"i8",ALLOC_STATIC);__str97=allocate([37,53,100,58,32,69,120,112,101,99,116,101,100,32,50,32,100,105,103,105,116,115,32,97,102,116,101,114,32,39,76,39,10,0],"i8",ALLOC_STATIC);__str98=allocate([37,53,100,58,32,76,101,116,116,101,114,32,103,114,111,117,112,32,76,37,46,50,100,32,110,111,116,32,100,101,102,105,110,101,100,10,0],"i8",ALLOC_STATIC);__str99=allocate([37,53,100,58,32,36,32,99,111,109,109,97,110,100,32,110,111,116,32,114,101,99,111,103,110,105,122,101,100,10,0],"i8",ALLOC_STATIC);__str100=allocate([37,53,100,58,32,69,120,112,101,99,116,101,100,32,50,32,100,105,103,105,116,115,32,97,102,116,101,114,32,39,46,76,39,10,0],"i8",ALLOC_STATIC);__str101=allocate([37,53,100,58,32,108,101,116,116,101,114,103,114,111,117,112,32,111,117,116,32,111,102,32,114,97,110,103,101,32,40,48,49,45,37,46,50,100,41,10,0],"i8",ALLOC_STATIC);__str102=allocate([37,53,100,58,32,108,101,116,116,101,114,103,114,111,117,112,32,76,37,46,50,100,32,105,115,32,97,108,114,101,97,100,121,32,100,101,102,105,110,101,100,10,0],"i8",ALLOC_STATIC);__str103=allocate([57,0],"i8",ALLOC_STATIC);__ZL11hash_chains=allocate(4096,"i8*",ALLOC_STATIC);__ZL11hash_counts=allocate(4096,"i32",ALLOC_STATIC);__ZL9text_mode_b=allocate(1,"i1",ALLOC_STATIC);__str104=allocate([37,115,37,115,46,116,120,116,0],"i8",ALLOC_STATIC);__str106=allocate([67,97,110,39,116,32,97,108,108,111,99,97,116,101,32,109,101,109,111,114,121,10,0],"i8",ALLOC_STATIC);__str107=allocate([9,37,100,32,101,110,116,114,105,101,115,10,0],"i8",ALLOC_STATIC);__ZZL12compile_linePcS_PiE10nullstring=allocate(1,"i8",ALLOC_STATIC);__str108=allocate([95,45,0],"i8",ALLOC_STATIC);__str109=allocate([37,53,100,58,32,85,110,107,110,111,119,110,32,107,101,121,119,111,114,100,58,32,37,115,10,0],"i8",ALLOC_STATIC);__str110=allocate([32,0],"i8",ALLOC_STATIC);__str111=allocate([37,53,100,58,32,78,101,101,100,32,116,111,32,99,111,109,112,105,108,101,32,100,105,99,116,105,111,110,97,114,121,32,97,103,97,105,110,10,0],"i8",ALLOC_STATIC);__str112=allocate([37,53,100,58,32,66,97,100,32,112,104,111,110,101,109,101,32,91,37,99,93,32,40,48,120,37,120,41,32,105,110,58,32,37,115,32,32,37,115,10,0],"i8",ALLOC_STATIC);__str113=allocate([85,43,37,120,0],"i8",ALLOC_STATIC);__str114=allocate([37,53,100,58,32,84,119,111,32,109,97,110,121,32,112,97,114,116,115,32,105,110,32,97,32,109,117,108,116,105,45,119,111,114,100,32,101,110,116,114,121,58,32,37,100,10,0],"i8",ALLOC_STATIC);__str115=allocate([67,97,110,39,116,32,97,99,99,101,115,115,32,40,37,115,41,32,102,105,108,101,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);_dictionary_skipwords=allocate(1,"i32",ALLOC_STATIC);_dictionary_name=allocate(40,"i8",ALLOC_STATIC);__ZL13remove_accent=allocate([97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,100,110,111,111,111,111,111,0,111,117,117,117,117,121,116,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,100,110,111,111,111,111,111,0,111,117,117,117,117,121,116,121,97,97,97,97,97,97,99,99,99,99,99,99,99,99,100,100,100,100,101,101,101,101,101,101,101,101,101,101,103,103,103,103,103,103,103,103,104,104,104,104,105,105,105,105,105,105,105,105,105,105,105,105,106,106,107,107,107,108,108,108,108,108,108,108,108,108,108,110,110,110,110,110,110,110,110,110,111,111,111,111,111,111,111,111,114,114,114,114,114,114,115,115,115,115,115,115,115,115,116,116,116,116,116,116,117,117,117,117,117,117,117,117,117,117,117,117,119,119,121,121,121,122,122,122,122,122,122,115,98,98,98,98,0,0,111,99,99,100,100,100,100,100,101,101,101,102,102,103,103,104,105,105,107,107,108,108,109,110,110,111,111,111,111,111,112,112,121,0,0,115,115,116,116,116,116,117,117,117,118,121,121,122,122,122,122,122,122,122,0,0,0,119,116,116,116,107,100,100,100,108,108,108,110,110,110,97,97,105,105,111,111,117,117,117,117,117,117,117,117,117,117,101,97,97,97,97,97,97,103,103,103,103,107,107,111,111,111,111,122,122,106,100,100,100,103,103,119,119,110,110,97,97,97,97,111,111,97,97,97,97,101,101,101,101,105,105,105,105,111,111,111,111,114,114,114,114,117,117,117,117,115,115,116,116,121,121,104,104,110,100,111,111,122,122,97,97,101,101,111,111,111,111,111,111,111,111,121,121,108,110,116,106,100,113,97,99,99,108,116,115,122,0,0,98,117,118,101,101,106,106,113,113,114,114,121,121,97,97,97,98,111,99,100,100,101,101,101,101,101,101,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"i8",ALLOC_STATIC);__str116=allocate([37,115,37,99,37,115,95,100,105,99,116,0],"i8",ALLOC_STATIC);__str2118=allocate([67,97,110,39,116,32,114,101,97,100,32,100,105,99,116,105,111,110,97,114,121,32,102,105,108,101,58,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__str3119=allocate([69,109,112,116,121,32,95,100,105,99,116,32,102,105,108,101,58,32,39,37,115,10,0],"i8",ALLOC_STATIC);__str4120=allocate([66,97,100,32,100,97,116,97,58,32,39,37,115,39,32,40,37,120,32,108,101,110,103,116,104,61,37,120,41,10,0],"i8",ALLOC_STATIC);__str5121=allocate([69,114,114,111,114,32,105,110,32,37,115,95,114,117,108,101,115,44,32,110,111,32,100,101,102,97,117,108,116,32,114,117,108,101,32,103,114,111,117,112,10,0],"i8",ALLOC_STATIC);__str7123=allocate([61,61,44,44,39,42,32,32,0],"i8",ALLOC_STATIC);_ipa1=allocate([32,0,33,0,34,0,688,0,36,0,37,0,230,0,712,0,40,0,638,0,42,0,43,0,716,0,45,0,46,0,47,0,594,0,49,0,50,0,604,0,52,0,53,0,54,0,55,0,629,0,57,0,720,0,690,0,60,0,61,0,62,0,660,0,601,0,593,0,946,0,231,0,240,0,603,0,70,0,610,0,295,0,618,0,607,0,75,0,76,0,625,0,331,0,596,0,934,0,611,0,640,0,643,0,952,0,650,0,652,0,339,0,967,0,248,0,658,0,810,0,92,0,93,0,94,0,95,0,96,0,97,0,98,0,99,0,100,0,101,0,102,0,609,0,104,0,105,0,106,0,107,0,108,0,109,0,110,0,111,0,112,0,113,0,114,0,115,0,116,0,117,0,118,0,119,0,120,0,121,0,122,0,123,0,124,0,125,0,771,0,127,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__str8124=allocate([61,61,44,44,39,39,0],"i8",ALLOC_STATIC);__str9125=allocate([40,37,115,41,0],"i8",ALLOC_STATIC);__ZL15stress_phonemes=allocate([3,2,4,5,6,7,26],"i8",ALLOC_STATIC);__ZZ13SetWordStressP10TranslatorPcPjiiE15consonant_types=allocate([0,0,0,1,1,1,1,1,1,1,0,0,0,0,0,0],"i8",ALLOC_STATIC);__ZZ13SetWordStressP10TranslatorPcPjiiE8guess_ru=allocate([0,0,1,1,2,3,3,4,5,6,7,7,8,9,10,11],"i8",ALLOC_STATIC);__ZZ13SetWordStressP10TranslatorPcPjiiE10guess_ru_v=allocate([0,0,1,1,2,2,3,3,4,5,6,7,7,8,9,10],"i8",ALLOC_STATIC);__ZZ13SetWordStressP10TranslatorPcPjiiE10guess_ru_t=allocate([0,0,1,2,3,3,3,4,5,6,7,7,7,8,9,10],"i8",ALLOC_STATIC);__ZZ14TranslateRulesP10TranslatorPcS1_iS1_iPjE9str_pause=allocate([11,0],"i8",ALLOC_STATIC);__str10126=allocate([85,110,112,114,111,110,111,117,110,99,97,98,108,101,63,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__str11127=allocate([84,114,97,110,115,108,97,116,101,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__ZL13diereses_list=allocate([228,0,235,0,239,0,246,0,252,0,255,0,0,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ14LookupDictListP10TranslatorPPcS1_PjiP8WORD_TABE16word_replacement=allocate(160,"i8",ALLOC_STATIC);__str15131=allocate([37,115,32,0],"i8",ALLOC_STATIC);__str16132=allocate([82,101,112,108,97,99,101,58,32,37,115,32,32,37,115,10,0],"i8",ALLOC_STATIC);__ZZ11LookupFlagsP10TranslatorPKcE5flags=allocate(8,"i32",ALLOC_STATIC);__ZZ12RemoveEndingP10TranslatorPciS1_E6ending=allocate(12,"i8",ALLOC_STATIC);__ZZ12RemoveEndingP10TranslatorPciS1_E16add_e_exceptions=allocate(8,"i8*",ALLOC_STATIC);__str17133=allocate([105,111,110,0],"i8",ALLOC_STATIC);__ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions=allocate(32,"i8*",ALLOC_STATIC);__str18134=allocate([99,0],"i8",ALLOC_STATIC);__str19135=allocate([114,115,0],"i8",ALLOC_STATIC);__str20136=allocate([105,114,0],"i8",ALLOC_STATIC);__str21137=allocate([117,114,0],"i8",ALLOC_STATIC);__str22138=allocate([97,116,104,0],"i8",ALLOC_STATIC);__str23139=allocate([110,115,0],"i8",ALLOC_STATIC);__str24140=allocate([117,0],"i8",ALLOC_STATIC);__str25141=allocate([97,100,100,32,101,10,0],"i8",ALLOC_STATIC);__str27143=allocate([101,115,0],"i8",ALLOC_STATIC);__str28144=allocate([70,108,97,103,115,58,32,32,37,115,32,32,37,115,10,0],"i8",ALLOC_STATIC);__str29145=allocate([70,111,117,110,100,58,32,39,37,115,32,37,115,0],"i8",ALLOC_STATIC);__str30146=allocate([70,111,117,110,100,58,32,39,37,115,0],"i8",ALLOC_STATIC);__str31147=allocate([39,32,91,37,115,93,32,32,37,115,10,0],"i8",ALLOC_STATIC);__ZZL9MatchRuleP10TranslatorPPcS1_iS1_P11MatchRecordiiE4best=allocate(16,["i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0],ALLOC_STATIC);__str32148=allocate([37,51,100,9,37,115,32,91,37,115,93,10,0],"i8",ALLOC_STATIC);__str34150=allocate([66,97,100,32,114,117,108,101,115,32,100,97,116,97,32,105,110,32,39,37,115,95,100,105,99,116,39,32,97,116,32,48,120,37,120,10,0],"i8",ALLOC_STATIC);_env_fall=allocate([255,253,250,248,246,244,242,240,238,236,234,232,230,228,226,224,222,220,218,216,214,212,210,208,206,204,202,200,198,196,194,192,190,188,186,184,182,180,178,176,174,172,170,168,166,164,162,160,158,156,154,152,150,148,146,144,142,140,138,136,134,132,130,128,126,124,122,120,118,116,114,112,110,108,106,104,102,100,98,96,94,92,90,88,86,84,82,80,78,76,74,72,70,68,66,64,62,60,58,56,54,52,50,48,46,44,42,40,38,36,34,32,30,28,26,24,22,20,18,16,14,12,10,8,6,4,2,0],"i8",ALLOC_STATIC);_env_rise=allocate([0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,238,240,242,244,246,248,250,253,255],"i8",ALLOC_STATIC);_env_frise=allocate([255,244,234,224,214,204,195,186,177,168,159,151,143,135,127,120,113,106,99,92,86,80,74,68,63,57,52,47,43,38,34,30,26,23,19,16,13,11,8,6,4,2,1,0,0,0,0,0,0,0,1,2,3,4,5,7,8,10,12,14,16,19,21,23,26,29,31,34,37,40,44,46,48,50,52,54,57,59,61,64,66,69,71,74,76,79,81,84,87,90,93,95,98,101,104,107,110,113,116,120,123,126,129,133,136,139,143,146,150,153,157,160,164,168,172,175,179,183,187,191,195,199,203,207,211,215,219,224],"i8",ALLOC_STATIC);__ZL11env_r_frise=allocate([207,204,201,198,195,192,189,185,180,176,171,167,162,156,151,146,140,134,129,123,117,111,105,99,93,87,80,74,68,62,56,51,45,39,34,28,23,18,13,8,4,2,2,1,0,0,0,0,0,1,1,2,3,4,5,7,8,10,12,13,15,18,20,22,25,27,30,33,36,39,42,45,48,52,54,56,58,60,63,65,67,70,72,75,77,80,82,85,88,90,93,96,99,102,105,108,111,114,117,120,123,126,129,133,136,139,143,146,150,153,157,160,164,168,172,175,179,183,187,191,195,199,203,207,211,215,219,224],"i8",ALLOC_STATIC);__ZL10env_frise2=allocate([255,249,244,238,233,228,223,218,213,208,203,198,193,189,184,179,175,170,166,161,157,153,149,144,140,136,132,128,125,121,117,113,110,106,103,99,96,93,89,86,83,80,77,74,71,68,65,62,60,57,55,52,50,47,45,43,40,38,36,34,32,30,28,26,25,23,21,20,18,17,15,14,13,12,10,9,8,7,6,5,5,4,3,2,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,3,4,4,5,6,7,8,9,10,11,12,14,15,16,18,19,21,23,24,26,28,30,32],"i8",ALLOC_STATIC);__ZL12env_r_frise2=allocate([208,206,205,204,202,200,199,197,195,193,192,189,187,184,181,179,176,173,170,167,163,160,157,153,150,146,143,139,135,132,128,124,120,116,112,109,105,101,97,93,89,85,81,77,74,70,66,62,59,55,52,49,47,45,42,40,38,36,34,32,30,28,26,25,23,21,20,18,17,15,14,13,12,10,9,8,7,6,5,5,4,3,2,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,2,3,4,4,5,6,7,8,9,10,11,12,14,15,16,18,19,21,23,24,26,28,30,32],"i8",ALLOC_STATIC);__ZL12env_risefall=allocate([152,153,153,154,156,157,159,161,164,167,169,172,176,179,182,186,190,193,197,201,205,209,212,216,220,223,227,230,234,237,240,242,245,247,249,251,252,253,254,254,255,255,255,255,255,255,254,253,251,250,248,246,243,241,238,236,233,230,228,224,221,218,215,211,208,204,200,196,192,188,184,180,176,172,167,163,159,154,150,145,141,136,132,127,123,118,114,109,105,101,96,92,88,84,80,76,72,68,64,60,57,53,50,47,43,40,38,35,32,29,26,23,21,18,15,13,10,8,7,5,3,2,1,0,0,0,0,0],"i8",ALLOC_STATIC);__ZL13env_fallrise3=allocate([254,255,255,255,255,255,254,253,252,250,248,246,244,241,238,235,232,229,225,222,218,214,210,205,201,196,191,186,182,176,171,166,161,156,150,145,139,134,128,123,117,111,106,100,95,89,84,79,73,68,63,58,53,48,43,38,34,29,25,21,17,13,10,7,4,3,1,0,0,0,0,0,0,0,0,1,1,2,4,5,7,9,11,13,16,18,21,24,27,30,34,37,41,45,49,53,58,62,67,72,76,81,87,91,94,98,101,104,107,110,113,116,118,120,123,124,126,128,129,130,131,131,132,132,131,131,130,129],"i8",ALLOC_STATIC);__ZL13env_fallrise4=allocate([114,114,113,113,112,111,109,108,106,104,102,100,97,95,92,90,87,84,81,78,75,72,69,66,63,59,56,53,50,47,44,41,38,35,32,29,27,24,22,20,18,16,14,12,11,10,9,8,7,7,7,7,7,6,5,5,5,5,5,5,5,5,5,6,7,7,8,9,10,12,13,15,16,18,20,22,24,27,29,32,35,38,41,44,47,51,55,59,63,67,71,76,81,86,91,96,101,106,111,116,121,127,132,137,143,149,155,161,167,173,179,186,192,199,206,213,220,227,234,241,245,247,250,252,253,254,255,255],"i8",ALLOC_STATIC);__ZL9env_fall2=allocate([254,254,253,253,252,251,251,250,250,249,248,248,247,247,246,246,245,244,244,243,243,242,242,241,240,240,239,238,238,237,236,235,234,234,233,232,231,230,229,228,227,226,225,224,222,221,220,219,217,216,214,213,211,210,208,206,204,203,201,199,197,195,192,190,188,185,183,181,178,175,173,170,167,164,161,158,154,151,148,144,141,137,133,129,125,121,117,113,109,104,100,97,94,91,87,84,81,77,74,70,67,64,60,57,53,50,46,42,39,35,31,28,24,20,17,13,11,9,7,5,4,3,2,1,0,0,0,0],"i8",ALLOC_STATIC);__ZL9env_rise2=allocate([0,0,0,0,1,1,1,2,2,3,3,4,4,5,6,6,7,8,8,9,10,11,12,12,13,14,15,16,17,18,19,20,22,23,24,25,27,28,29,31,32,34,35,37,38,40,41,43,45,47,48,50,52,54,56,58,60,62,64,66,68,71,73,75,78,80,82,85,87,90,93,95,98,101,103,106,109,112,115,118,121,124,127,130,134,137,140,144,147,150,154,157,160,163,166,169,172,175,178,181,184,187,190,193,196,199,202,205,208,211,214,217,220,223,226,228,231,233,236,238,240,242,244,246,248,250,251,253],"i8",ALLOC_STATIC);__ZL16env_risefallrise=allocate([127,127,127,128,129,131,132,135,137,140,143,146,150,153,157,161,165,170,174,178,183,187,192,197,201,205,210,214,218,222,226,230,234,237,240,243,245,248,250,251,252,253,254,254,253,252,251,249,247,244,240,236,231,226,220,213,206,198,189,180,169,158,146,136,130,125,119,114,108,102,96,90,84,78,73,66,60,55,50,45,40,36,31,27,24,20,17,14,12,9,7,6,5,4,4,4,4,5,6,8,10,13,16,20,24,29,35,41,47,55,62,71,80,90,100,112,124,131,133,136,138,140,142,143,145,146,147,147],"i8",ALLOC_STATIC);_envelope_data=allocate(80,"i8*",ALLOC_STATIC);__ZL18tone_nucleus_table=allocate([0,64,8,0,70,18,0,0,0,0,0,0,24,12,0,undef,4,80,18,6,78,22,0,0,0,0,0,0,34,52,0,undef,4,88,22,6,82,22,0,0,0,0,0,0,34,64,0,undef,0,92,8,0,92,80,0,0,0,0,0,0,76,8,1,undef,0,86,4,0,94,66,0,0,0,0,0,0,34,10,0,undef,0,62,10,0,62,20,0,0,0,0,0,0,28,16,0,undef,4,68,18,6,68,22,0,0,0,0,0,0,30,44,0,undef,6,64,16,0,66,32,0,0,0,0,0,0,32,18,0,undef,2,68,46,0,42,32,0,0,0,0,0,0,46,58,0,undef,4,78,24,6,72,22,0,0,0,0,0,0,42,52,0,undef,4,88,34,0,64,32,0,0,0,0,0,0,46,82,0,undef,0,56,12,0,56,20,0,0,0,0,0,0,24,12,0,undef,0,70,18,0,70,24,0,0,0,0,0,0,32,20,0,undef],["i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i16*",0,0,0,"i8","i8","i8","i8"],ALLOC_STATIC);_punctuation_to_tone=allocate([0,1,2,3,0,4,0,1,2,3,0,4,5,6,2,3,0,4,5,7,1,3,0,4,8,9,10,3,0,0,8,8,10,3,0,0,11,11,11,11,0,0,12,12,12,12,0,0],"i8",ALLOC_STATIC);_n_tunes=allocate(1,"i32",ALLOC_STATIC);_tunes=allocate(1,"%struct.TUNE*",ALLOC_STATIC);__ZL12syllable_tab=allocate(1,"%struct.SYLLABLE*",ALLOC_STATIC);__ZL8no_tonic_b=allocate(1,"i1",ALLOC_STATIC);__ZL15tone_head_table=allocate([46,57,78,50,0,0,0,0,3,7,5,0,0,0,0,0,46,57,78,46,0,0,0,0,3,7,5,0,0,0,0,0,46,57,78,46,0,0,0,0,3,7,5,0,0,0,0,0,46,57,90,50,0,0,0,0,3,9,5,0,0,0,0,0,46,57,78,50,0,0,0,0,3,7,5,0,0,0,0,0,46,57,74,55,0,0,0,0,4,7,5,0,0,0,0,0,46,57,74,55,0,0,0,0,4,7,5,0,0,0,0,0,46,57,74,55,0,0,0,0,4,7,5,0,0,0,0,0,46,57,78,50,0,0,0,0,3,7,5,0,0,0,0,0,46,57,78,46,0,0,0,0,3,7,5,0,0,0,0,0,46,57,78,50,0,0,0,0,3,7,5,0,0,0,0,0,34,41,41,32,0,0,0,0,3,7,5,0,0,0,0,0,46,57,55,50,0,0,0,0,3,7,5,0,0,0,0,0],["i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0,"i8","i8","i8","i8","i32*",0,0,0,"i8","i8","i8",0,"i8*",0,0,0],ALLOC_STATIC);__ZL10number_pre=allocate(1,"i32",ALLOC_STATIC);__ZL10tone_posn2=allocate(1,"i32",ALLOC_STATIC);__ZL9tone_posn=allocate(1,"i32",ALLOC_STATIC);__ZL11number_tail=allocate(1,"i32",ALLOC_STATIC);__ZL14tone_pitch_env=allocate(1,"i32",ALLOC_STATIC);__ZZL18calc_pitch_segmentiiP9TONE_HEADP12TONE_NUCLEUSiiE12continue_tab=allocate([230,32,20,8,0],"i8",ALLOC_STATIC);__ZL8min_drop=allocate([6,0,0,0,7,0,0,0,9,0,0,0,9,0,0,0,20,0,0,0,20,0,0,0,20,0,0,0,25,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZL7drops_0=allocate([9,0,0,0,9,0,0,0,16,0,0,0,16,0,0,0,16,0,0,0,23,0,0,0,55,0,0,0,32,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZL5oflow=allocate([0,40,24,8,0],"i8",ALLOC_STATIC);__ZL9oflow_emf=allocate([10,52,32,20,10],"i8",ALLOC_STATIC);__ZL10oflow_less=allocate([6,38,24,14,4],"i8",ALLOC_STATIC);__ZL12last_primary=allocate(1,"i32",ALLOC_STATIC);_namedata=allocate(1,"i8*",ALLOC_STATIC);__ZL7f_input=allocate(1,"%struct.__sFILE*",ALLOC_STATIC);_p_textinput=allocate(1,"i8*",ALLOC_STATIC);_p_wchar_input=allocate(1,"i32*",ALLOC_STATIC);__ZL10ungot_word=allocate(1,"i8*",ALLOC_STATIC);_count_characters=allocate(1,"i32",ALLOC_STATIC);__ZL10ssml_stack=allocate(1520,["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8"],ALLOC_STATIC);__ZL16current_voice_id=allocate(40,"i8",ALLOC_STATIC);_param_stack=allocate(1280,"i32",ALLOC_STATIC);_param_defaults=allocate([0,0,0,0,175,0,0,0,100,0,0,0,50,0,0,0,50,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);_walpha_tab=allocate([1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,254,255,1,255,1,255,1,255,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,255,1,255,1,255,1,255,255,255,210,1,255,1,255,206,1,255,205,205,1,255,255,79,202,203,1,255,205,207,255,211,209,1,255,255,255,211,213,255,214,1,255,1,255,1,255,218,1,255,218,255,255,1,255,218,1,255,217,217,1,255,1,255,219,1,255,255,255,1,255,255,255,255,255,255,255,2,1,255,2,1,255,2,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,255,2,1,255,1,255,255,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,255,0,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255,1,255],"i8",ALLOC_STATIC);__ZL10ungot_char=allocate(1,"i32",ALLOC_STATIC);__ZL12end_of_input_b=allocate(1,"i1",ALLOC_STATIC);__str167=allocate([115,112,101,97,107,0],"i8",ALLOC_STATIC);__str1168=allocate([118,111,105,99,101,0],"i8",ALLOC_STATIC);__str2169=allocate([112,114,111,115,111,100,121,0],"i8",ALLOC_STATIC);__str3170=allocate([115,97,121,45,97,115,0],"i8",ALLOC_STATIC);__str4171=allocate([109,97,114,107,0],"i8",ALLOC_STATIC);__str5172=allocate([115,0],"i8",ALLOC_STATIC);__str6173=allocate([112,0],"i8",ALLOC_STATIC);__str7174=allocate([112,104,111,110,101,109,101,0],"i8",ALLOC_STATIC);__str8175=allocate([115,117,98,0],"i8",ALLOC_STATIC);__str9176=allocate([116,116,115,58,115,116,121,108,101,0],"i8",ALLOC_STATIC);__str10177=allocate([97,117,100,105,111,0],"i8",ALLOC_STATIC);__str11178=allocate([101,109,112,104,97,115,105,115,0],"i8",ALLOC_STATIC);__str12179=allocate([98,114,101,97,107,0],"i8",ALLOC_STATIC);__str13180=allocate([109,101,116,97,100,97,116,97,0],"i8",ALLOC_STATIC);__str14181=allocate([98,114,0],"i8",ALLOC_STATIC);__str15182=allocate([108,105,0],"i8",ALLOC_STATIC);__str16183=allocate([100,100,0],"i8",ALLOC_STATIC);__str17184=allocate([105,109,103,0],"i8",ALLOC_STATIC);__str18185=allocate([116,100,0],"i8",ALLOC_STATIC);__str19186=allocate([104,49,0],"i8",ALLOC_STATIC);__str20187=allocate([104,50,0],"i8",ALLOC_STATIC);__str21188=allocate([104,51,0],"i8",ALLOC_STATIC);__str22189=allocate([104,52,0],"i8",ALLOC_STATIC);__str23190=allocate([104,114,0],"i8",ALLOC_STATIC);__str24191=allocate([115,99,114,105,112,116,0],"i8",ALLOC_STATIC);__str25192=allocate([115,116,121,108,101,0],"i8",ALLOC_STATIC);__str26193=allocate([102,111,110,116,0],"i8",ALLOC_STATIC);__str27194=allocate([98,0],"i8",ALLOC_STATIC);__str28195=allocate([105,0],"i8",ALLOC_STATIC);__str29196=allocate([115,116,114,111,110,103,0],"i8",ALLOC_STATIC);__str30197=allocate([101,109,0],"i8",ALLOC_STATIC);__str31198=allocate([99,111,100,101,0],"i8",ALLOC_STATIC);__ZL8ssmltags=allocate([0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,13,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZL10n_namedata=allocate(1,"i32",ALLOC_STATIC);__ZL11namedata_ix=allocate(1,"i32",ALLOC_STATIC);__str32199=allocate([103,116,0],"i8",ALLOC_STATIC);__str33200=allocate([108,116,0],"i8",ALLOC_STATIC);__str34201=allocate([97,109,112,0],"i8",ALLOC_STATIC);__str35202=allocate([113,117,111,116,0],"i8",ALLOC_STATIC);__str36203=allocate([110,98,115,112,0],"i8",ALLOC_STATIC);__str37204=allocate([97,112,111,115,0],"i8",ALLOC_STATIC);__ZL18xml_char_mnemonics=allocate([0,0,0,0,62,0,0,0,0,0,0,0,57404,0,0,0,0,0,0,0,38,0,0,0,0,0,0,0,34,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,39,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E12ungot_string=allocate(24,"i8",ALLOC_STATIC);__ZZ10ReadClauseP10TranslatorP7__sFILEPcPsPiiS5_S3_E15ungot_string_ix=allocate([-1],["i32",0,0,0,0],ALLOC_STATIC);__ZL19clear_skipping_text_b=allocate(1,"i1",ALLOC_STATIC);__ZL11ungot_char2=allocate(1,"i32",ALLOC_STATIC);__ZL19ssml_ignore_l_angle=allocate(1,"i32",ALLOC_STATIC);__str38205=allocate([37,115,37,99,37,99,0],"i8",ALLOC_STATIC);__ZL10sayas_mode=allocate(1,"i32",ALLOC_STATIC);__ZL11ignore_text_b=allocate(1,"i1",ALLOC_STATIC);__ZL11punct_chars=allocate([44,0,46,0,63,0,33,0,58,0,59,0,8211,0,8212,0,8230,0,894,0,903,0,2404,0,1417,0,1373,0,1372,0,1374,0,1371,0,2843,0,1567,0,4962,0,4963,0,4964,0,4965,0,4966,0,4967,0,4968,0,4347,0,12289,0,12290,0,-255,0,-244,0,-242,0,-230,0,-229,0,-225,0,0,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL16punct_attributes=allocate([0,0,0,0,266260,0,0,0,524328,0,0,0,532520,0,0,0,536621,0,0,0,262174,0,0,0,266270,0,0,0,266270,0,0,0,266270,0,0,0,2396190,0,0,0,532520,0,0,0,266270,0,0,0,557096,0,0,0,557096,0,0,0,266260,0,0,0,1585197,0,0,0,1581096,0,0,0,1572904,0,0,0,266270,0,0,0,532520,0,0,0,524328,0,0,0,266260,0,0,0,266270,0,0,0,262174,0,0,0,262174,0,0,0,532520,0,0,0,524358,0,0,0,524358,0,0,0,299028,0,0,0,557096,0,0,0,569389,0,0,0,299028,0,0,0,557096,0,0,0,294942,0,0,0,299038,0,0,0,565288,0,0,0,266270,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str41208=allocate([32,32,32,0],"i8",ALLOC_STATIC);__ZL12chars_ignore=allocate([8204,0,8205,0,0,0],["i16",0,"i16",0,"i16",0],ALLOC_STATIC);__str42209=allocate([105,32,0],"i8",ALLOC_STATIC);__ZL10audio_text_b=allocate(1,"i1",ALLOC_STATIC);__ZL17speech_parameters=allocate(60,"i32",ALLOC_STATIC);__ZL12n_ssml_stack=allocate(1,"i32",ALLOC_STATIC);__ZL13n_param_stack=allocate(1,"i32",ALLOC_STATIC);__ZL7xmlbase=allocate(1,"i8*",ALLOC_STATIC);__ZZL14LookupCharNameP10TranslatoriiE3buf=allocate(60,"i8",ALLOC_STATIC);__str47214=allocate([91,2,95,94,95,37,115,32,37,115,32,95,94,95,37,115,93,93,0],"i8",ALLOC_STATIC);__str48215=allocate([91,2,37,115,93,93,32,0],"i8",ALLOC_STATIC);__str49216=allocate([91,2,40,88,49,41,40,88,49,41,40,88,49,41,93,93,0],"i8",ALLOC_STATIC);__ZZL13WordToString2jE3buf=allocate(5,"i8",ALLOC_STATIC);__str50217=allocate([1,37,100,73,32,0],"i8",ALLOC_STATIC);__str51218=allocate([32,37,115,0],"i8",ALLOC_STATIC);__str52219=allocate([1,43,49,48,83,0],"i8",ALLOC_STATIC);__str53220=allocate([32,1,45,49,48,83,0],"i8",ALLOC_STATIC);__str54221=allocate([32,37,115,32,37,100,32,37,115,0],"i8",ALLOC_STATIC);__str55222=allocate([37,115,37,99,115,111,117,110,100,105,99,111,110,115,37,99,37,115,0],"i8",ALLOC_STATIC);__str57224=allocate([112,111,108,121,112,104,97,115,101,0],"i8",ALLOC_STATIC);__str58225=allocate([47,116,109,112,47,101,115,112,101,97,107,88,88,88,88,88,88,0],"i8",ALLOC_STATIC);__str59226=allocate([115,111,120,32,34,37,115,34,32,45,114,32,37,100,32,45,119,32,45,115,32,45,99,49,32,37,115,32,37,115,10,0],"i8",ALLOC_STATIC);__str60227=allocate([91,2,37,115,93,93,0],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_punct=allocate([0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str61228=allocate([110,111,110,101,0],"i8",ALLOC_STATIC);__str62229=allocate([97,108,108,0],"i8",ALLOC_STATIC);__str63230=allocate([115,111,109,101,0],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_capitals=allocate([0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,20,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str64231=allocate([110,111,0],"i8",ALLOC_STATIC);__str65232=allocate([115,112,101,108,108,105,110,103,0],"i8",ALLOC_STATIC);__str66233=allocate([105,99,111,110,0],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_interpret_as=allocate([0,0,0,0,18,0,0,0,0,0,0,0,20,0,0,0,0,0,0,0,36,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,193,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str68235=allocate([99,104,97,114,97,99,116,101,114,115,0],"i8",ALLOC_STATIC);__str69236=allocate([116,116,115,58,99,104,97,114,0],"i8",ALLOC_STATIC);__str70237=allocate([116,116,115,58,107,101,121,0],"i8",ALLOC_STATIC);__str71238=allocate([116,116,115,58,100,105,103,105,116,115,0],"i8",ALLOC_STATIC);__str72239=allocate([116,101,108,101,112,104,111,110,101,0],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_sayas_format=allocate([0,0,0,0,1,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str73240=allocate([103,108,121,112,104,115,0],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_break=allocate([0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str74241=allocate([120,45,119,101,97,107,0],"i8",ALLOC_STATIC);__str75242=allocate([119,101,97,107,0],"i8",ALLOC_STATIC);__str76243=allocate([109,101,100,105,117,109,0],"i8",ALLOC_STATIC);__str77244=allocate([120,45,115,116,114,111,110,103,0],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_emphasis=allocate([0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str78245=allocate([114,101,100,117,99,101,100,0],"i8",ALLOC_STATIC);__str79246=allocate([109,111,100,101,114,97,116,101,0],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE12prosody_attr=allocate(20,"i8*",ALLOC_STATIC);__str80247=allocate([114,97,116,101,0],"i8",ALLOC_STATIC);__str81248=allocate([118,111,108,117,109,101,0],"i8",ALLOC_STATIC);__str82249=allocate([114,97,110,103,101,0],"i8",ALLOC_STATIC);__ZL22ignore_if_self_closing=allocate([0,1,1,1,1,0,0,0,0,1,1,0,1,0,1,0,0,0,0],"i8",ALLOC_STATIC);__str83250=allocate([102,105,101,108,100,0],"i8",ALLOC_STATIC);__str84251=allocate([109,111,100,101,0],"i8",ALLOC_STATIC);__str85252=allocate([112,117,110,99,116,117,97,116,105,111,110,0],"i8",ALLOC_STATIC);__str86253=allocate([99,97,112,105,116,97,108,95,108,101,116,116,101,114,115,0],"i8",ALLOC_STATIC);__str87254=allocate([108,101,118,101,108,0],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE23emphasis_to_pitch_range=allocate([50,50,40,70,90,90],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE18emphasis_to_volume=allocate([100,100,70,110,140,140],"i8",ALLOC_STATIC);__str88255=allocate([105,110,116,101,114,112,114,101,116,45,97,115,0],"i8",ALLOC_STATIC);__str89256=allocate([102,111,114,109,97,116,0],"i8",ALLOC_STATIC);__str90257=allocate([100,101,116,97,105,108,0],"i8",ALLOC_STATIC);__str91258=allocate([37,99,37,100,89,0],"i8",ALLOC_STATIC);__ZL11sayas_start=allocate(1,"i32",ALLOC_STATIC);__str92259=allocate([97,108,105,97,115,0],"i8",ALLOC_STATIC);__str94261=allocate([37,99,37,100,77,0],"i8",ALLOC_STATIC);__str95262=allocate([115,114,99,0],"i8",ALLOC_STATIC);__str96263=allocate([37,115,47,37,115,0],"i8",ALLOC_STATIC);__str97264=allocate([37,99,37,100,73,0],"i8",ALLOC_STATIC);__str98265=allocate([37,99,37,100,85,0],"i8",ALLOC_STATIC);__str99266=allocate([115,116,114,101,110,103,116,104,0],"i8",ALLOC_STATIC);__ZZL14ProcessSsmlTagPwPcRiiiE11break_value=allocate([0,0,0,0,7,0,0,0,14,0,0,0,21,0,0,0,40,0,0,0,80,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str100267=allocate([37,99,37,100,66,0],"i8",ALLOC_STATIC);__str101268=allocate([116,105,109,101,0],"i8",ALLOC_STATIC);__str102269=allocate([120,109,108,58,98,97,115,101,0],"i8",ALLOC_STATIC);__ZZL18GetVoiceAttributesPwiE11mnem_gender=allocate([0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str105272=allocate([110,101,117,116,114,97,108,0],"i8",ALLOC_STATIC);__str106273=allocate([120,109,108,58,108,97,110,103,0],"i8",ALLOC_STATIC);__str108275=allocate([97,103,101,0],"i8",ALLOC_STATIC);__ZZL14LoadSoundFile2PKcE4slot=allocate([-1],["i32",0,0,0,0],ALLOC_STATIC);__str111278=allocate([115,112,97,99,101,32,0],"i8",ALLOC_STATIC);__str112279=allocate([116,97,98,32,0],"i8",ALLOC_STATIC);__str113280=allocate([117,110,100,101,114,115,99,111,114,101,32,0],"i8",ALLOC_STATIC);__str114281=allocate([100,111,117,98,108,101,45,113,117,111,116,101,32,0],"i8",ALLOC_STATIC);__ZZL14ReplaceKeyNamePciRiE8keynames=allocate([0,0,0,0,57376,0,0,0,0,0,0,0,57353,0,0,0,0,0,0,0,57439,0,0,0,0,0,0,0,34,0,0,0,0,0,0,0,0,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume=allocate([0,0,0,0,100,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,30,0,0,0,0,0,0,0,65,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,150,0,0,0,0,0,0,0,230,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str115282=allocate([115,105,108,101,110,116,0],"i8",ALLOC_STATIC);__str116283=allocate([120,45,115,111,102,116,0],"i8",ALLOC_STATIC);__str117=allocate([115,111,102,116,0],"i8",ALLOC_STATIC);__str118=allocate([108,111,117,100,0],"i8",ALLOC_STATIC);__str119=allocate([120,45,108,111,117,100,0],"i8",ALLOC_STATIC);__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_rate=allocate([0,0,0,0,100,0,0,0,0,0,0,0,60,0,0,0,0,0,0,0,80,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,125,0,0,0,0,0,0,0,160,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str120=allocate([120,45,115,108,111,119,0],"i8",ALLOC_STATIC);__str121=allocate([115,108,111,119,0],"i8",ALLOC_STATIC);__str122=allocate([102,97,115,116,0],"i8",ALLOC_STATIC);__str123=allocate([120,45,102,97,115,116,0],"i8",ALLOC_STATIC);__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_pitch=allocate([0,0,0,0,100,0,0,0,0,0,0,0,70,0,0,0,0,0,0,0,85,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,110,0,0,0,0,0,0,0,120,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str124=allocate([120,45,108,111,119,0],"i8",ALLOC_STATIC);__str125=allocate([108,111,119,0],"i8",ALLOC_STATIC);__str126=allocate([104,105,103,104,0],"i8",ALLOC_STATIC);__str127=allocate([120,45,104,105,103,104,0],"i8",ALLOC_STATIC);__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_range=allocate([0,0,0,0,100,0,0,0,0,0,0,0,20,0,0,0,0,0,0,0,50,0,0,0,0,0,0,0,100,0,0,0,0,0,0,0,140,0,0,0,0,0,0,0,180,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_tabs=allocate(20,"%struct.MNEM_TAB*",ALLOC_STATIC);__ZZL17ProcessParamStackPcRiE10cmd_letter=allocate([0,83,65,80,82,0,67,0,0,0,0,0,70,0,0],"i8",ALLOC_STATIC);__str128=allocate([37,99,37,100,37,99,0],"i8",ALLOC_STATIC);__ZZL16GetSsmlAttributePwPKcE5empty=allocate(4,"i32",ALLOC_STATIC);__ZZL4GetCvE6ungot2=allocate(1,"i32",ALLOC_STATIC);__ZZL4GetCvE5mask2=allocate([0,128,32,48],"i8",ALLOC_STATIC);__ZL6speed1=allocate([130],["i32",0,0,0,0],ALLOC_STATIC);__ZL6speed2=allocate([121],["i32",0,0,0,0],ALLOC_STATIC);__ZL6speed3=allocate([118],["i32",0,0,0,0],ALLOC_STATIC);__ZL12speed_lookup=allocate([255,255,255,255,255,253,249,245,242,238,235,232,228,225,222,218,216,213,210,207,204,201,198,196,193,191,188,186,183,181,179,176,174,172,169,168,165,163,161,159,158,155,153,152,150,148,146,145,143,141,139,137,136,135,133,131,130,129,127,126,124,123,122,120,119,118,117,115,114,113,112,111,110,109,107,106,105,104,103,102,101,100,99,98,97,96,95,94,93,92,91,90,89,89,88,87,86,85,84,83,82,82,81,80,80,79,78,77,76,76,75,75,74,73,72,71,71,70,69,69,68,67,67,66,66,65,64,64,63,62,62,61,61,60,59,59,58,58,57,57,56,56,55,54,54,53,53,52,52,52,51,50,50,49,49,48,48,47,47,46,46,46,45,45,44,44,44,43,43,42,41,40,40,40,39,39,39,38,38,38,37,37,37,36,36,35,35,35,35,34,34,34,33,33,33,32,32,31,31,31,30,30,30,29,29,29,29,28,28,27,27,27,27,26,26,26,26,25,25,25,24,24,24,24,23,23,23,23,22,22,22,21,21,21,21,20,20,20,20,19,19,19,18,18,17,17,17,16,16,16,16,16,16,15,15,15,15,14,14,14,13,13,13,12,12,12,12,11,11,11,11,10,10,10,9,9,9,8,8,8],"i8",ALLOC_STATIC);__ZL14wav_factor_350=allocate([120,121,120,119,119,118,118,117,116,116,115,114,113,112,112,111,111,110,109,108,107,106,106,104,103,103,102,102,102,101,101,99,98,98,97,96,96,95,94,93,91,90,91,90,89,88,86,85,86,85,85,84,82,81,80,79,77,78,78,76,77,75,75,74,73,71,72,70,69,69,69,67,65,64,63,63,63,61,61,59,59,59,58,56,57,58,56,54,53,52,52,53,52,52,50,48,47,47,45,46,45],"i8",ALLOC_STATIC);__ZL16pause_factor_350=allocate([22,22,22,22,22,22,22,21,21,21,21,20,20,19,19,18,17,16,15,15,15,15,15,15,15],"i8",ALLOC_STATIC);__ZZ11CalcLengthsP10TranslatorE14more_syllables=allocate(1,"i32",ALLOC_STATIC);__str294=allocate([101,115,112,101,97,107,58,32,66,97,100,32,105,110,116,111,110,97,116,105,111,110,32,100,97,116,97,10,0],"i8",ALLOC_STATIC);__ZL18letter_accents_0e0=allocate([870,0,358,0,614,0,1190,0,678,0,1062,0,-30042,0,552,0,874,0,362,0,618,0,682,0,878,0,366,0,622,0,686,0,41,0,1203,0,884,0,372,0,628,0,1204,0,692,0,0,0,1140,0,890,0,378,0,634,0,698,0,382,0,57,0,702,0,0,0,934,0,0,0,422,0,0,0,998,0,0,0,360,0,0,0,616,0,0,0,808,0,0,0,488,0,0,0,489,0,0,0,1129,0,0,0,938,0,0,0,426,0,0,0,810,0,0,0,1002,0,0,0,490,0,0,0,620,0,0,0,428,0,0,0,812,0,0,0,556,0,0,0,621,0,0,0,1133,0,0,0,1198,0,0,0,942,0,0,0,430,0,0,0,1006,0,0,0,46,0,0,0,-29714,0,0,0,623,0,0,0,560,0,48,0,0,0,369,0,0,0,561,0,0,0,497,0,0,0,817,0,0,0,1137,0,0,0,371,0,0,0,563,0,0,0,499,0,51,0,0,0,51,0,0,0,948,0,0,0,436,0,0,0,756,0,0,0,-30028,0,0,0,375,0,0,0,567,0,0,0,503,0,0,0,376,0,0,0,632,0,0,0,568,0,0,0,504,0,0,0,569,0,0,0,505,0,0,0,1145,0,0,0,1210,0,0,0,954,0,0,0,442,0,0,0,1082,0,0,0,762,0,0,0,1018,0,0,0,636,0,0,0,638,0,0,0,0,0,383,0,0,0,831,0,0,0,511,0,56,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL18letter_accents_250=allocate([166,0,1,0,129,0,1383,0,0,0,296,0,1321,0,1385,0,234,0,0,0,1346,0,0,0,195,0,7491,0,0,0,1263,0,1388,0,44,0,108,0,4,0,0,0,173,0,1389,0,0,0,1262,0,5,0,110,0,1201,0,1265,0,1329,0,-28687,0,178,0,0,0,1394,0,0,0,1331,0,115,0,1268,0,-25932,0,0,0,8,0,183,0,0,0,5431,0,0,0,1335,0,0,0,205,0,119,0,2231,0,1336,0,0,0,0,0,201,0,265,0,185,0,1337,0,1274,0,10,0,1403,0,187,0,188,0,190,0,126,0,1343,0,319,0,0,0,267,0,0,0,204,0,140,0,0,0,0,0,103,0,0,0,3436,0,109,0,303,0,176,0,113,0,1398,0,1100,0,7244,0,-28695,0,0,0,-12311,0,-29127,0,0,0,-12743,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL13non_ascii_tab=allocate([0,0,945,0,601,0,603,0,947,0,953,0,339,0,969,0,966,0,643,0,965,0,658,0,660,0,638,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL11accents_tab=allocate([0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str297=allocate([37,115,37,99,37,115,37,99,37,115,37,115,0],"i8",ALLOC_STATIC);__str1298=allocate([37,115,37,99,37,99,37,115,0],"i8",ALLOC_STATIC);__str2299=allocate([37,99,37,115,37,99,37,115,37,99,0],"i8",ALLOC_STATIC);__ZZ12LookupLetterP10TranslatorjiPciE13single_letter=allocate(10,"i8",ALLOC_STATIC);__str5302=allocate([95,35,37,100,32,0],"i8",ALLOC_STATIC);__str6303=allocate([95,99,97,112,0],"i8",ALLOC_STATIC);__str7304=allocate([37,99,101,110,0],"i8",ALLOC_STATIC);__str8305=allocate([95,63,65,0],"i8",ALLOC_STATIC);__str9306=allocate([95,63,63,0],"i8",ALLOC_STATIC);__str10307=allocate([37,120,0],"i8",ALLOC_STATIC);__str11308=allocate([37,99,37,115,37,115,0],"i8",ALLOC_STATIC);__str12309=allocate([105,120,99,109,118,108,100,0],"i8",ALLOC_STATIC);__ZZ14TranslateRomanP10TranslatorPcS1_P8WORD_TABE12roman_values=allocate([1,0,0,0,10,0,0,0,100,0,0,0,1000,0,0,0,5,0,0,0,50,0,0,0,500,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str13310=allocate([95,114,111,109,97,110,0],"i8",ALLOC_STATIC);__str14311=allocate([32,32,37,100,32,32,32,32,0],"i8",ALLOC_STATIC);__ZZL17TranslateNumber_1P10TranslatorPcS1_PjP8WORD_TABiE9str_pause=allocate([11,0],"i8",ALLOC_STATIC);__ZL14n_digit_lookup=allocate(1,"i32",ALLOC_STATIC);__ZL12digit_lookup=allocate(1,"i8*",ALLOC_STATIC);__ZL14number_control=allocate(1,"i32",ALLOC_STATIC);__ZL23speak_missing_thousands=allocate(1,"i32",ALLOC_STATIC);__ZL11ph_ordinal2=allocate(12,"i8",ALLOC_STATIC);__str15312=allocate([95,35,37,115,0],"i8",ALLOC_STATIC);__str16313=allocate([95,48,0],"i8",ALLOC_STATIC);__str17314=allocate([95,100,112,116,0],"i8",ALLOC_STATIC);__str18315=allocate([95,48,77,37,100,0],"i8",ALLOC_STATIC);__str19316=allocate([95,46,0],"i8",ALLOC_STATIC);__str20317=allocate([37,115,37,115,37,115,37,115,0],"i8",ALLOC_STATIC);__str21318=allocate([95,48,90,37,100,0],"i8",ALLOC_STATIC);__str22319=allocate([95,100,112,116,50,0],"i8",ALLOC_STATIC);__str23320=allocate([95,37,100,102,0],"i8",ALLOC_STATIC);__str24321=allocate([95,37,100,37,99,120,0],"i8",ALLOC_STATIC);__str25322=allocate([95,37,100,37,99,0],"i8",ALLOC_STATIC);__str26323=allocate([95,37,100,101,0],"i8",ALLOC_STATIC);__str27324=allocate([95,37,100,97,0],"i8",ALLOC_STATIC);__str28325=allocate([95,37,100,0],"i8",ALLOC_STATIC);__str29326=allocate([95,37,100,88,37,99,0],"i8",ALLOC_STATIC);__str30327=allocate([95,37,100,88,0],"i8",ALLOC_STATIC);__str31328=allocate([95,111,114,100,50,48,0],"i8",ALLOC_STATIC);__str32329=allocate([95,111,114,100,0],"i8",ALLOC_STATIC);__str33330=allocate([95,48,97,110,100,0],"i8",ALLOC_STATIC);__str35332=allocate([95,48,67,111,0],"i8",ALLOC_STATIC);__str36333=allocate([95,48,67,48,0],"i8",ALLOC_STATIC);__str37334=allocate([95,48,67,0],"i8",ALLOC_STATIC);__str39336=allocate([95,37,100,67,111,0],"i8",ALLOC_STATIC);__str40337=allocate([95,37,100,67,48,0],"i8",ALLOC_STATIC);__str41338=allocate([95,37,100,67,0],"i8",ALLOC_STATIC);__str42339=allocate([95,37,100,77,37,100,111,0],"i8",ALLOC_STATIC);__str43340=allocate([95,37,100,77,37,100,101,0],"i8",ALLOC_STATIC);__str44341=allocate([95,37,100,77,37,100,120,0],"i8",ALLOC_STATIC);__str45342=allocate([95,37,100,77,37,100,0],"i8",ALLOC_STATIC);__str46343=allocate([95,48,111,102,0],"i8",ALLOC_STATIC);__str47344=allocate([95,37,115,37,100,111,0],"i8",ALLOC_STATIC);__str48345=allocate([95,37,115,37,100,101,0],"i8",ALLOC_STATIC);__str49346=allocate([95,37,115,37,100,120,0],"i8",ALLOC_STATIC);__str50347=allocate([95,37,115,37,100,0],"i8",ALLOC_STATIC);__str51348=allocate([95,48,77,50,0],"i8",ALLOC_STATIC);__str52349=allocate([95,37,100,77,49,0],"i8",ALLOC_STATIC);__str53350=allocate([95,48,77,49,0],"i8",ALLOC_STATIC);__str54351=allocate([48,77,65,0],"i8",ALLOC_STATIC);__str55352=allocate([49,77,65,0],"i8",ALLOC_STATIC);__str56353=allocate([48,77,0],"i8",ALLOC_STATIC);__str57354=allocate([95,108,105,103,0],"i8",ALLOC_STATIC);__str58355=allocate([95,115,109,99,0],"i8",ALLOC_STATIC);__str59356=allocate([95,116,117,114,0],"i8",ALLOC_STATIC);__str60357=allocate([95,114,101,118,0],"i8",ALLOC_STATIC);__str61358=allocate([95,99,114,108,0],"i8",ALLOC_STATIC);__str62359=allocate([95,97,99,117,0],"i8",ALLOC_STATIC);__str63360=allocate([95,98,114,118,0],"i8",ALLOC_STATIC);__str64361=allocate([95,104,97,99,0],"i8",ALLOC_STATIC);__str65362=allocate([95,99,101,100,0],"i8",ALLOC_STATIC);__str66363=allocate([95,99,105,114,0],"i8",ALLOC_STATIC);__str67364=allocate([95,100,105,97,0],"i8",ALLOC_STATIC);__str68365=allocate([95,97,99,50,0],"i8",ALLOC_STATIC);__str69366=allocate([95,100,111,116,0],"i8",ALLOC_STATIC);__str70367=allocate([95,103,114,118,0],"i8",ALLOC_STATIC);__str71368=allocate([95,109,99,110,0],"i8",ALLOC_STATIC);__str72369=allocate([95,111,103,111,0],"i8",ALLOC_STATIC);__str73370=allocate([95,114,110,103,0],"i8",ALLOC_STATIC);__str74371=allocate([95,115,116,107,0],"i8",ALLOC_STATIC);__str75372=allocate([95,116,108,100,0],"i8",ALLOC_STATIC);__str76373=allocate([95,98,97,114,0],"i8",ALLOC_STATIC);__str77374=allocate([95,114,102,120,0],"i8",ALLOC_STATIC);__str78375=allocate([95,104,111,107,0],"i8",ALLOC_STATIC);_option_mbrola_phonemes=allocate(1,"i32",ALLOC_STATIC);__ZL10mbrola_tab=allocate(1,"%struct.MBROLA_TAB*",ALLOC_STATIC);__ZL15mbr_name_prefix=allocate(1,"i32",ALLOC_STATIC);__str382=allocate([37,115,47,109,98,114,111,108,97,47,37,115,0],"i8",ALLOC_STATIC);__str1383=allocate([47,117,115,114,47,115,104,97,114,101,47,109,98,114,111,108,97,47,37,115,0],"i8",ALLOC_STATIC);__str2384=allocate([47,117,115,114,47,115,104,97,114,101,47,109,98,114,111,108,97,47,37,115,47,37,115,0],"i8",ALLOC_STATIC);__str3385=allocate([47,117,115,114,47,115,104,97,114,101,47,109,98,114,111,108,97,47,118,111,105,99,101,115,47,37,115,0],"i8",ALLOC_STATIC);__str4386=allocate([37,115,47,109,98,114,111,108,97,95,112,104,47,37,115,0],"i8",ALLOC_STATIC);__ZL14mbrola_control=allocate(1,"i32",ALLOC_STATIC);__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE4phix=allocate(1,"i32",ALLOC_STATIC);__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE11embedded_ix=allocate(1,"i32",ALLOC_STATIC);__ZZ15MbrolaTranslateP12PHONEME_LISTiiP7__sFILEE10word_count=allocate(1,"i32",ALLOC_STATIC);__str6388=allocate([37,115,9,0],"i8",ALLOC_STATIC);__str8390=allocate([37,100,9,37,115,0],"i8",ALLOC_STATIC);__str9391=allocate([37,115,9,37,100,9,37,115,0],"i8",ALLOC_STATIC);__str10392=allocate([37,100,10,37,115,9,0],"i8",ALLOC_STATIC);__str11393=allocate([37,100,37,115,10,0],"i8",ALLOC_STATIC);__str12394=allocate([95,32,9,37,100,10,0],"i8",ALLOC_STATIC);__ZZ10MbrolaFilliiE9n_samples=allocate(1,"i32",ALLOC_STATIC);__ZZL10WritePitchiiiiiE6output=allocate(50,"i8",ALLOC_STATIC);__str13395=allocate([32,48,32,37,100,0],"i8",ALLOC_STATIC);__str14396=allocate([32,37,100,32,37,100,0],"i8",ALLOC_STATIC);__str15397=allocate([10,0],"i8",ALLOC_STATIC);__str16398=allocate([9,49,48,48,32,37,100,10,0],"i8",ALLOC_STATIC);__ZZL10GetMbrNameP12PHONEME_LISTP11PHONEME_TABS2_S2_PiS3_S3_E4mnem=allocate(1,"i32",ALLOC_STATIC);__str399=allocate([49,46,52,53,46,48,52,32,32,50,53,46,65,112,114,46,49,49,0],"i8",ALLOC_STATIC);_version_string=allocate(1,"i8*",ALLOC_STATIC);_version_phdata=allocate([83200],["i32",0,0,0,0],ALLOC_STATIC);_option_device_number=allocate([-1],["i32",0,0,0,0],ALLOC_STATIC);_f_logespeak=allocate(1,"%struct.__sFILE*",ALLOC_STATIC);_logging_type=allocate(1,"i32",ALLOC_STATIC);_n_phoneme_tab=allocate(1,"i32",ALLOC_STATIC);_current_phoneme_table=allocate(1,"i32",ALLOC_STATIC);_phoneme_tab=allocate(1024,"%struct.PHONEME_TAB*",ALLOC_STATIC);_phoneme_tab_flags=allocate(256,"i8",ALLOC_STATIC);_phoneme_index=allocate(1,"i16*",ALLOC_STATIC);_phondata_ptr=allocate(1,"i8*",ALLOC_STATIC);_wavefile_data=allocate(1,"i8*",ALLOC_STATIC);__ZL16phoneme_tab_data=allocate(1,"i8*",ALLOC_STATIC);_n_phoneme_tables=allocate(1,"i32",ALLOC_STATIC);_phoneme_tab_list=allocate(4800,["i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","%struct.PHONEME_TAB*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);_phoneme_tab_number=allocate(1,"i32",ALLOC_STATIC);_wavefile_ix=allocate(1,"i32",ALLOC_STATIC);_wavefile_amp=allocate(1,"i32",ALLOC_STATIC);_wavefile_ix2=allocate(1,"i32",ALLOC_STATIC);_wavefile_amp2=allocate(1,"i32",ALLOC_STATIC);_seq_len_adjust=allocate(1,"i32",ALLOC_STATIC);_vowel_transition=allocate(16,"i32",ALLOC_STATIC);_vowel_transition0=allocate(1,"i32",ALLOC_STATIC);_vowel_transition1=allocate(1,"i32",ALLOC_STATIC);__str1412=allocate([112,104,111,110,116,97,98,0],"i8",ALLOC_STATIC);__str2413=allocate([112,104,111,110,105,110,100,101,120,0],"i8",ALLOC_STATIC);__str3414=allocate([112,104,111,110,100,97,116,97,0],"i8",ALLOC_STATIC);__str4415=allocate([105,110,116,111,110,97,116,105,111,110,115,0],"i8",ALLOC_STATIC);__ZZ11LookupSpectP11PHONEME_TABiP10FMT_PARAMSPiP12PHONEME_LISTE10frames_buf=allocate(200,["i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0,"i16",0,"i16",0,"%struct.frame_t*",0,0,0],ALLOC_STATIC);__str5416=allocate([101,115,112,101,97,107,58,32,78,111,32,101,110,118,101,108,111,112,101,10,0],"i8",ALLOC_STATIC);__str7418=allocate([99,111,110,102,105,103,0],"i8",ALLOC_STATIC);__str9420=allocate([108,111,103,0],"i8",ALLOC_STATIC);__str10421=allocate([37,100,32,37,115,0],"i8",ALLOC_STATIC);__str11422=allocate([119,0],"i8",ALLOC_STATIC);__str13424=allocate([112,97,95,100,101,118,105,99,101,0],"i8",ALLOC_STATIC);__str15426=allocate([115,111,117,110,100,105,99,111,110,0],"i8",ALLOC_STATIC);__str16427=allocate([95,37,99,32,37,115,0],"i8",ALLOC_STATIC);_this_ph_data=allocate(152,["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8",0,0],ALLOC_STATIC);__ZZL13NumInstnWordsPtE7n_words=allocate([1,1,1,1,1,1,1,1,1,2,4],"i8",ALLOC_STATIC);__ZZL18InterpretConditionP10TranslatoriP12PHONEME_LISTiE11ph_position=allocate([0,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,2,0,0,0,0,0,0,0,1,0,0,0,3,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZL15StressConditionP10TranslatorP12PHONEME_LISTiiE15condition_level=allocate([1,0,0,0,2,0,0,0,4,0,0,0,15,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str17428=allocate([73,110,118,97,108,105,100,32,105,110,115,116,114,117,99,116,105,111,110,32,37,46,52,120,32,102,111,114,32,112,104,111,110,101,109,101,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__str18429=allocate([114,98,0],"i8",ALLOC_STATIC);__str19430=allocate([67,97,110,39,116,32,114,101,97,100,32,100,97,116,97,32,102,105,108,101,58,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);_n_phoneme_list=allocate(1,"i32",ALLOC_STATIC);_phoneme_list=allocate(24000,["i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0,"i8","i8","i8","i8","i16",0,"i16",0,"%struct.PHONEME_TAB*",0,0,0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8",0,0],ALLOC_STATIC);_mbrola_delay=allocate(1,"i32",ALLOC_STATIC);_mbrola_name=allocate(20,"i8",ALLOC_STATIC);_speed=allocate(64,"i32",ALLOC_STATIC);__ZL9new_voice=allocate(1,"%struct.voice_t*",ALLOC_STATIC);_n_soundicon_tab=allocate([4],["i32",0,0,0,0],ALLOC_STATIC);_soundicon_tab=allocate(1280,["i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0],ALLOC_STATIC);__ZZ12WordToStringjE3buf=allocate(5,"i8",ALLOC_STATIC);__ZL14last_pitch_cmd=allocate(1,"i32",ALLOC_STATIC);__ZL12last_amp_cmd=allocate(1,"i32",ALLOC_STATIC);__ZL10last_frame=allocate(1,"%struct.frame_t*",ALLOC_STATIC);__ZL15syllable_centre=allocate(1,"i32",ALLOC_STATIC);__ZZ18FormantTransition2P10frameref_tRijjP11PHONEME_TABiE10vcolouring=allocate([243,0,272,0,256,0,256,0,256,0,256,0,256,0,240,0,240,0,240,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL10modn_flags=allocate(1,"i32",ALLOC_STATIC);__ZZ8DoSpect2P11PHONEME_TABiP10FMT_PARAMSP12PHONEME_LISTiE9wave_flag_b=allocate(1,"i1",ALLOC_STATIC);__ZL13fmt_amplitude=allocate(1,"i32",ALLOC_STATIC);__ZL10last_wcmdq=allocate(1,"i32",ALLOC_STATIC);__ZL12pitch_length=allocate(1,"i32",ALLOC_STATIC);__ZL10amp_length=allocate(1,"i32",ALLOC_STATIC);__ZZ8GenerateP12PHONEME_LISTPiiE2ix=allocate(1,"i32",ALLOC_STATIC);__ZZ8GenerateP12PHONEME_LISTPiiE11embedded_ix=allocate(1,"i32",ALLOC_STATIC);__ZZ8GenerateP12PHONEME_LISTPiiE10word_count=allocate(1,"i32",ALLOC_STATIC);__ZZ8GenerateP12PHONEME_LISTPiiE8sourceix=allocate(1,"i32",ALLOC_STATIC);__ZL14syllable_start=allocate(1,"i32",ALLOC_STATIC);__ZL12syllable_end=allocate(1,"i32",ALLOC_STATIC);__ZL8timer_on_b=allocate(1,"i1",ALLOC_STATIC);__ZL6paused_b=allocate(1,"i1",ALLOC_STATIC);__ZZ15SpeakNextClauseP7__sFILEPKviE6f_text=allocate(1,"%struct.__sFILE*",ALLOC_STATIC);__ZZ15SpeakNextClauseP7__sFILEPKviE6p_text=allocate(1,"i8*",ALLOC_STATIC);__str459=allocate([37,115,10,0],"i8",ALLOC_STATIC);__str1460=allocate([87,97,114,110,105,110,103,58,32,65,99,99,101,110,116,101,100,32,108,101,116,116,101,114,115,32,97,114,101,32,110,111,116,32,114,101,99,111,103,110,105,122,101,100,44,32,101,103,58,32,85,43,48,49,48,68,10,83,101,116,32,76,67,95,67,84,89,80,69,32,116,111,32,97,32,85,84,70,45,56,32,108,111,99,97,108,101,10,0],"i8",ALLOC_STATIC);__ZZL13set_frame_rmsP7frame_tiE8sqrt_tab=allocate([0,0,64,0,90,0,110,0,128,0,143,0,156,0,169,0,181,0,192,0,202,0,212,0,221,0,230,0,239,0,247,0,256,0,263,0,271,0,278,0,286,0,293,0,300,0,306,0,313,0,320,0,326,0,332,0,338,0,344,0,350,0,356,0,362,0,367,0,373,0,378,0,384,0,389,0,394,0,399,0,404,0,409,0,414,0,419,0,424,0,429,0,434,0,438,0,443,0,448,0,452,0,457,0,461,0,465,0,470,0,474,0,478,0,483,0,487,0,491,0,495,0,499,0,503,0,507,0,512,0,515,0,519,0,523,0,527,0,531,0,535,0,539,0,543,0,546,0,550,0,554,0,557,0,561,0,565,0,568,0,572,0,576,0,579,0,583,0,586,0,590,0,593,0,596,0,600,0,603,0,607,0,610,0,613,0,617,0,620,0,623,0,627,0,630,0,633,0,636,0,640,0,643,0,646,0,649,0,652,0,655,0,658,0,662,0,665,0,668,0,671,0,674,0,677,0,680,0,683,0,686,0,689,0,692,0,695,0,698,0,701,0,704,0,706,0,709,0,712,0,715,0,718,0,721,0,724,0,726,0,729,0,732,0,735,0,738,0,740,0,743,0,746,0,749,0,751,0,754,0,757,0,759,0,762,0,765,0,768,0,770,0,773,0,775,0,778,0,781,0,783,0,786,0,789,0,791,0,794,0,796,0,799,0,801,0,804,0,807,0,809,0,812,0,814,0,817,0,819,0,822,0,824,0,827,0,829,0,832,0,834,0,836,0,839,0,841,0,844,0,846,0,849,0,851,0,853,0,856,0,858,0,861,0,863,0,865,0,868,0,870,0,872,0,875,0,877,0,879,0,882,0,884,0,886,0,889,0,891,0,893,0,896,0,898,0,900,0,902,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZL10AllocFramevE2ix=allocate(1,"i32",ALLOC_STATIC);__ZZL10AllocFramevE10frame_pool=allocate(10240,["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8"],ALLOC_STATIC);_translator=allocate(1,"%struct.Translator*",ALLOC_STATIC);_translator2=allocate(1,"%struct.Translator*",ALLOC_STATIC);__ZL20translator2_language=allocate(20,"i8",ALLOC_STATIC);_f_trans=allocate(1,"%struct.__sFILE*",ALLOC_STATIC);_option_tone2=allocate(1,"i32",ALLOC_STATIC);_option_tone_flags=allocate(1,"i32",ALLOC_STATIC);_option_phonemes=allocate(1,"i32",ALLOC_STATIC);_option_phoneme_events=allocate(1,"i32",ALLOC_STATIC);_option_quiet=allocate(1,"i32",ALLOC_STATIC);_option_endpause=allocate(1,"i32",ALLOC_STATIC);_option_capitals=allocate(1,"i32",ALLOC_STATIC);_option_punctuation=allocate(1,"i32",ALLOC_STATIC);_option_sayas=allocate(1,"i32",ALLOC_STATIC);_option_ssml=allocate(1,"i32",ALLOC_STATIC);_option_phoneme_input=allocate(1,"i32",ALLOC_STATIC);_option_phoneme_variants=allocate(1,"i32",ALLOC_STATIC);_option_wordgap=allocate(1,"i32",ALLOC_STATIC);_skip_sentences=allocate(1,"i32",ALLOC_STATIC);_skip_words=allocate(1,"i32",ALLOC_STATIC);_skip_characters=allocate(1,"i32",ALLOC_STATIC);_skip_marker=allocate(50,"i8",ALLOC_STATIC);_skipping_text=allocate(1,"i32",ALLOC_STATIC);_end_character_position=allocate(1,"i32",ALLOC_STATIC);_count_sentences=allocate(1,"i32",ALLOC_STATIC);_count_words=allocate(1,"i32",ALLOC_STATIC);_clause_start_char=allocate(1,"i32",ALLOC_STATIC);_clause_start_word=allocate(1,"i32",ALLOC_STATIC);_new_sentence=allocate(1,"i32",ALLOC_STATIC);_pre_pause=allocate(1,"i32",ALLOC_STATIC);_word_phonemes=allocate(160,"i8",ALLOC_STATIC);_n_ph_list2=allocate(1,"i32",ALLOC_STATIC);_ph_list2=allocate(8000,["i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0,"i8","i8","i8","i8","i16",0,"i16",0],ALLOC_STATIC);_option_punctlist=allocate(240,"i32",ALLOC_STATIC);_ctrl_embedded=allocate([1],["i8",0,0,0,0],ALLOC_STATIC);_option_multibyte=allocate(1,"i32",ALLOC_STATIC);_option_linelength=allocate(1,"i32",ALLOC_STATIC);_embedded_list=allocate(1000,"i32",ALLOC_STATIC);_n_replace_phonemes=allocate(1,"i32",ALLOC_STATIC);_replace_phonemes=allocate(180,"i8",ALLOC_STATIC);__ZL10ISO_8859_1=allocate([160,0,161,0,162,0,163,0,164,0,165,0,166,0,167,0,168,0,169,0,170,0,171,0,172,0,173,0,174,0,175,0,176,0,177,0,178,0,179,0,180,0,181,0,182,0,183,0,184,0,185,0,186,0,187,0,188,0,189,0,190,0,191,0,192,0,193,0,194,0,195,0,196,0,197,0,198,0,199,0,200,0,201,0,202,0,203,0,204,0,205,0,206,0,207,0,208,0,209,0,210,0,211,0,212,0,213,0,214,0,215,0,216,0,217,0,218,0,219,0,220,0,221,0,222,0,223,0,224,0,225,0,226,0,227,0,228,0,229,0,230,0,231,0,232,0,233,0,234,0,235,0,236,0,237,0,238,0,239,0,240,0,241,0,242,0,243,0,244,0,245,0,246,0,247,0,248,0,249,0,250,0,251,0,252,0,253,0,254,0,255,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL10ISO_8859_2=allocate([160,0,260,0,728,0,321,0,164,0,317,0,346,0,167,0,168,0,352,0,350,0,356,0,377,0,173,0,381,0,379,0,176,0,261,0,731,0,322,0,180,0,318,0,347,0,711,0,184,0,353,0,351,0,357,0,378,0,733,0,382,0,380,0,340,0,193,0,194,0,258,0,196,0,313,0,262,0,199,0,268,0,201,0,280,0,203,0,282,0,205,0,206,0,270,0,272,0,323,0,327,0,211,0,212,0,336,0,214,0,215,0,344,0,366,0,218,0,368,0,220,0,221,0,354,0,223,0,341,0,225,0,226,0,259,0,228,0,314,0,263,0,231,0,269,0,233,0,281,0,235,0,283,0,237,0,238,0,271,0,273,0,324,0,328,0,243,0,244,0,337,0,246,0,247,0,345,0,367,0,250,0,369,0,252,0,253,0,355,0,729,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL10ISO_8859_3=allocate([160,0,294,0,728,0,163,0,164,0,0,0,292,0,167,0,168,0,304,0,350,0,286,0,308,0,173,0,0,0,379,0,176,0,295,0,178,0,179,0,180,0,181,0,293,0,183,0,184,0,305,0,351,0,287,0,309,0,189,0,0,0,380,0,192,0,193,0,194,0,0,0,196,0,266,0,264,0,199,0,200,0,201,0,202,0,203,0,204,0,205,0,206,0,207,0,0,0,209,0,210,0,211,0,212,0,288,0,214,0,215,0,284,0,217,0,218,0,219,0,220,0,364,0,348,0,223,0,224,0,225,0,226,0,0,0,228,0,267,0,265,0,231,0,232,0,233,0,234,0,235,0,236,0,237,0,238,0,239,0,0,0,241,0,242,0,243,0,244,0,289,0,246,0,247,0,285,0,249,0,250,0,251,0,252,0,365,0,349,0,729,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL10ISO_8859_4=allocate([160,0,260,0,312,0,342,0,164,0,296,0,315,0,167,0,168,0,352,0,274,0,290,0,358,0,173,0,381,0,175,0,176,0,261,0,731,0,343,0,180,0,297,0,316,0,711,0,184,0,353,0,275,0,291,0,359,0,330,0,382,0,331,0,256,0,193,0,194,0,195,0,196,0,197,0,198,0,302,0,268,0,201,0,280,0,203,0,278,0,205,0,206,0,298,0,272,0,325,0,332,0,310,0,212,0,213,0,214,0,215,0,216,0,370,0,218,0,219,0,220,0,360,0,362,0,223,0,257,0,225,0,226,0,227,0,228,0,229,0,230,0,303,0,269,0,233,0,281,0,235,0,279,0,237,0,238,0,299,0,273,0,326,0,333,0,311,0,244,0,245,0,246,0,247,0,248,0,371,0,250,0,251,0,252,0,361,0,363,0,729,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL10ISO_8859_5=allocate([160,0,1025,0,1026,0,1027,0,1028,0,1029,0,1030,0,1031,0,1032,0,1033,0,1034,0,1035,0,1036,0,173,0,1038,0,1039,0,1040,0,1041,0,1042,0,1043,0,1044,0,1045,0,1046,0,1047,0,1048,0,1049,0,1050,0,1051,0,1052,0,1053,0,1054,0,1055,0,1056,0,1057,0,1058,0,1059,0,1060,0,1061,0,1062,0,1063,0,1064,0,1065,0,1066,0,1067,0,1068,0,1069,0,1070,0,1071,0,1072,0,1073,0,1074,0,1075,0,1076,0,1077,0,1078,0,1079,0,1080,0,1081,0,1082,0,1083,0,1084,0,1085,0,1086,0,1087,0,1088,0,1089,0,1090,0,1091,0,1092,0,1093,0,1094,0,1095,0,1096,0,1097,0,1098,0,1099,0,1100,0,1101,0,1102,0,1103,0,8470,0,1105,0,1106,0,1107,0,1108,0,1109,0,1110,0,1111,0,1112,0,1113,0,1114,0,1115,0,1116,0,167,0,1118,0,1119,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL10ISO_8859_7=allocate([160,0,8216,0,8217,0,163,0,8364,0,8367,0,166,0,167,0,168,0,169,0,890,0,171,0,172,0,173,0,0,0,8213,0,176,0,177,0,178,0,179,0,900,0,901,0,902,0,183,0,904,0,905,0,906,0,187,0,908,0,189,0,910,0,911,0,912,0,913,0,914,0,915,0,916,0,917,0,918,0,919,0,920,0,921,0,922,0,923,0,924,0,925,0,926,0,927,0,928,0,929,0,0,0,931,0,932,0,933,0,934,0,935,0,936,0,937,0,938,0,939,0,940,0,941,0,942,0,943,0,944,0,945,0,946,0,947,0,948,0,949,0,950,0,951,0,952,0,953,0,954,0,955,0,956,0,957,0,958,0,959,0,960,0,961,0,962,0,963,0,964,0,965,0,966,0,967,0,968,0,969,0,970,0,971,0,972,0,973,0,974,0,0,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL10ISO_8859_9=allocate([160,0,161,0,162,0,163,0,164,0,165,0,166,0,167,0,168,0,169,0,170,0,171,0,172,0,173,0,174,0,175,0,176,0,177,0,178,0,179,0,180,0,181,0,182,0,183,0,184,0,185,0,186,0,187,0,188,0,189,0,190,0,191,0,192,0,193,0,194,0,195,0,196,0,197,0,198,0,199,0,200,0,201,0,202,0,203,0,204,0,205,0,206,0,207,0,286,0,209,0,210,0,211,0,212,0,213,0,214,0,215,0,216,0,217,0,218,0,219,0,220,0,304,0,350,0,223,0,224,0,225,0,226,0,227,0,228,0,229,0,230,0,231,0,232,0,233,0,234,0,235,0,236,0,237,0,238,0,239,0,287,0,241,0,242,0,243,0,244,0,245,0,246,0,247,0,248,0,249,0,250,0,251,0,252,0,305,0,351,0,255,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL11ISO_8859_14=allocate([160,0,7682,0,7683,0,163,0,266,0,267,0,7690,0,167,0,7808,0,169,0,7810,0,7691,0,7922,0,173,0,174,0,376,0,7710,0,7711,0,288,0,289,0,7744,0,7745,0,182,0,7766,0,7809,0,7767,0,7811,0,7776,0,7923,0,7812,0,7813,0,7777,0,192,0,193,0,194,0,195,0,196,0,197,0,198,0,199,0,200,0,201,0,202,0,203,0,204,0,205,0,206,0,207,0,372,0,209,0,210,0,211,0,212,0,213,0,214,0,7786,0,216,0,217,0,218,0,219,0,220,0,221,0,374,0,223,0,224,0,225,0,226,0,227,0,228,0,229,0,230,0,231,0,232,0,233,0,234,0,235,0,236,0,237,0,238,0,239,0,373,0,241,0,242,0,243,0,244,0,245,0,246,0,7787,0,248,0,249,0,250,0,251,0,252,0,253,0,375,0,255,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL6KOI8_R=allocate([9552,0,9553,0,9554,0,1105,0,9555,0,9556,0,9557,0,9558,0,9559,0,9560,0,9561,0,9562,0,9563,0,9564,0,9565,0,9566,0,9567,0,9568,0,9569,0,1025,0,9570,0,9571,0,9572,0,9573,0,9574,0,9575,0,9576,0,9577,0,9578,0,9579,0,9580,0,169,0,1102,0,1072,0,1073,0,1094,0,1076,0,1077,0,1092,0,1075,0,1093,0,1080,0,1081,0,1082,0,1083,0,1084,0,1085,0,1086,0,1087,0,1103,0,1088,0,1089,0,1090,0,1091,0,1078,0,1074,0,1100,0,1099,0,1079,0,1096,0,1101,0,1097,0,1095,0,1098,0,1070,0,1040,0,1041,0,1062,0,1044,0,1045,0,1060,0,1043,0,1061,0,1048,0,1049,0,1050,0,1051,0,1052,0,1053,0,1054,0,1055,0,1071,0,1056,0,1057,0,1058,0,1059,0,1046,0,1042,0,1068,0,1067,0,1047,0,1064,0,1069,0,1065,0,1063,0,1066,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL5ISCII=allocate([32,0,2305,0,2306,0,2307,0,2309,0,2310,0,2311,0,2312,0,2313,0,2314,0,2315,0,2318,0,2319,0,2320,0,2317,0,2322,0,2323,0,2324,0,2321,0,2325,0,2326,0,2327,0,2328,0,2329,0,2330,0,2331,0,2332,0,2333,0,2334,0,2335,0,2336,0,2337,0,2338,0,2339,0,2340,0,2341,0,2342,0,2343,0,2344,0,2345,0,2346,0,2347,0,2348,0,2349,0,2350,0,2351,0,2399,0,2352,0,2353,0,2354,0,2355,0,2356,0,2357,0,2358,0,2359,0,2360,0,2361,0,32,0,2366,0,2367,0,2368,0,2369,0,2370,0,2371,0,2374,0,2375,0,2376,0,2373,0,2378,0,2379,0,2380,0,2377,0,2381,0,2364,0,2404,0,32,0,32,0,32,0,32,0,32,0,32,0,48,0,49,0,50,0,51,0,52,0,53,0,54,0,55,0,56,0,57,0,32,0,32,0,32,0,32,0,32,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);_charsets=allocate(80,"i16*",ALLOC_STATIC);__ZL15length_mod_tabs=allocate(24,"i8*",ALLOC_STATIC);__ZZ7IsAlphajE18extra_indic_alphas=allocate([2672,0,2673,0,0,0],["i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL8brackets=allocate([40,0,41,0,91,0,93,0,123,0,125,0,60,0,62,0,34,0,39,0,96,0,171,0,187,0,12298,0,12299,0,-8132,0,0,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ8utf8_outjPcE4code=allocate([0,192,224,240],"i8",ALLOC_STATIC);__ZZ8utf8_in2PiPKciE4mask=allocate([255,31,15,7],"i8",ALLOC_STATIC);__str543=allocate([40,37,115,41,32,37,115,32,32,45,62,32,40,37,115,41,32,0],"i8",ALLOC_STATIC);__str1544=allocate([37,115,10,10,0],"i8",ALLOC_STATIC);__ZZ13TranslateWordP10TranslatorPciP8WORD_TABE7word_zz=allocate([0,122,122,0],"i8",ALLOC_STATIC);__ZZ13TranslateWordP10TranslatorPciP8WORD_TABE7word_iz=allocate([0,105,122,0],"i8",ALLOC_STATIC);__ZZ13TranslateWordP10TranslatorPciP8WORD_TABE7word_ss=allocate([0,115,115,0],"i8",ALLOC_STATIC);__str2545=allocate([95,48,108,97,110,103,0],"i8",ALLOC_STATIC);__str4547=allocate([32,32,115,117,102,102,105,120,32,91,37,115,93,10,10,0],"i8",ALLOC_STATIC);__str5548=allocate([104,115,120,0],"i8",ALLOC_STATIC);__str6549=allocate([37,115,37,115,37,115,0],"i8",ALLOC_STATIC);__ZL18any_stressed_words_b=allocate(1,"i1",ALLOC_STATIC);__ZZ15TranslateClauseP10TranslatorP7__sFILEPKvPiPPcE17voice_change_name=allocate(40,"i8",ALLOC_STATIC);__ZL11embedded_ix=allocate(1,"i32",ALLOC_STATIC);__ZL13embedded_read=allocate(1,"i32",ALLOC_STATIC);__ZL6source=allocate(740,"i8",ALLOC_STATIC);__str7550=allocate([67,76,65,85,83,69,32,37,120,58,10,0],"i8",ALLOC_STATIC);__str8551=allocate([69,78,68,67,76,65,85,83,69,10,0],"i8",ALLOC_STATIC);__ZL16max_clause_pause=allocate(1,"i32",ALLOC_STATIC);__ZL13option_sayas2=allocate(1,"i32",ALLOC_STATIC);__ZL18count_sayas_digits=allocate(1,"i32",ALLOC_STATIC);__ZL6breaks=allocate([95,0,0,0],["i16",0,"i16",0],ALLOC_STATIC);__ZL13word_emphasis_b=allocate(1,"i1",ALLOC_STATIC);__ZL15option_emphasis=allocate(1,"i32",ALLOC_STATIC);__ZL13embedded_flag_b=allocate(1,"i1",ALLOC_STATIC);__str9552=allocate([87,79,82,68,58,32,102,108,103,61,37,46,53,120,32,108,101,110,61,37,100,32,32,39,0],"i8",ALLOC_STATIC);__str10553=allocate([39,10,0],"i8",ALLOC_STATIC);__str11554=allocate([95,94,95,0],"i8",ALLOC_STATIC);__ZZL13TranslateCharP10TranslatorPcijjPiE20hangul_compatibility=allocate([0,0,1,170,2,172,173,3,4,5,176,177,178,179,180,180,182,6,7,8,185,9,10,188,12,13,14,15,16,17,18,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117],"i8",ALLOC_STATIC);__ZZL14SubstituteCharP10TranslatorjjPiE11ignore_next_b=allocate(1,"i1",ALLOC_STATIC);__str12555=allocate([80,83,65,82,72,84,73,86,89,77,85,66,70,0],"i8",ALLOC_STATIC);__ZL14length_mods_en=allocate([100,120,100,105,100,110,110,100,95,100,105,120,105,110,125,130,135,115,125,100,105,120,75,100,75,105,120,85,75,100,105,120,85,105,95,115,120,100,95,100,110,120,95,105,100,115,120,100,100,100,105,120,100,105,95,115,120,110,95,100,105,120,100,105,105,122,125,110,105,100,105,120,100,105,105,122,125,110,105,100,105,120,95,105,100,115,120,110,100,100,100,120,100,100,100,100,100,100,100,100],"i8",ALLOC_STATIC);__ZL15length_mods_en0=allocate([100,150,100,105,110,115,110,110,110,100,105,150,105,110,125,135,140,115,135,100,105,150,90,105,90,122,135,100,90,100,105,150,100,105,100,122,135,100,100,100,105,150,100,105,105,115,135,110,105,100,105,150,100,105,105,122,130,120,125,100,105,150,100,105,110,122,125,115,110,100,105,150,100,105,105,122,135,120,105,100,105,150,100,105,105,115,135,110,105,100,100,100,100,100,100,100,100,100,100,100],"i8",ALLOC_STATIC);__ZL17length_mods_equal=allocate([110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110,110],"i8",ALLOC_STATIC);__str580=allocate([35,10,0],"i8",ALLOC_STATIC);__str1581=allocate([117,110,97,98,108,101,32,116,111,32,103,101,116,32,46,119,97,118,32,104,101,97,100,101,114,32,102,114,111,109,32,109,98,114,111,108,97,0],"i8",ALLOC_STATIC);__str2582=allocate([82,73,70,70,0],"i8",ALLOC_STATIC);__str3583=allocate([87,65,86,69,102,109,116,32,0],"i8",ALLOC_STATIC);__str4584=allocate([109,98,114,111,108,97,32,100,105,100,32,110,111,116,32,114,101,116,117,114,110,32,97,32,46,119,97,118,32,104,101,97,100,101,114,0],"i8",ALLOC_STATIC);__ZL14mbr_samplerate=allocate(1,"i32",ALLOC_STATIC);__ZL14mbr_voice_path=allocate(1,"i8*",ALLOC_STATIC);__ZL10mbr_volume=allocate([1],["float",0,0,0,0],ALLOC_STATIC);__ZL9mbr_state=allocate(1,"i32",ALLOC_STATIC);__ZL7mbr_pid=allocate(1,"i32",ALLOC_STATIC);__ZL10mbr_cmd_fd=allocate(1,"i32",ALLOC_STATIC);__str5585=allocate([10,35,10,0],"i8",ALLOC_STATIC);__ZL12mbr_audio_fd=allocate(1,"i32",ALLOC_STATIC);__ZL12mbr_errorbuf=allocate(160,"i8",ALLOC_STATIC);__ZL12mbr_error_fd=allocate(1,"i32",ALLOC_STATIC);__str7587=allocate([114,101,97,100,40,101,114,114,111,114,41,58,32,37,115,0],"i8",ALLOC_STATIC);__str8588=allocate([71,111,116,32,97,32,114,101,115,101,116,32,115,105,103,110,97,108,0],"i8",ALLOC_STATIC);__str9589=allocate([73,110,112,117,116,32,70,108,117,115,104,32,83,105,103,110,97,108,0],"i8",ALLOC_STATIC);__str10590=allocate([109,98,114,111,108,97,58,32,37,115,0],"i8",ALLOC_STATIC);__str11591=allocate([109,98,114,111,108,97,32,99,108,111,115,101,100,32,115,116,100,101,114,114,32,97,110,100,32,100,105,100,32,110,111,116,32,101,120,105,116,0],"i8",ALLOC_STATIC);__str12592=allocate([119,97,105,116,112,105,100,40,41,32,105,115,32,99,111,110,102,117,115,101,100,0],"i8",ALLOC_STATIC);__str13593=allocate([109,98,114,111,108,97,32,100,105,101,100,32,98,121,32,115,105,103,110,97,108,32,37,100,0],"i8",ALLOC_STATIC);__str14594=allocate([109,98,114,111,108,97,32,101,120,105,116,101,100,32,119,105,116,104,32,115,116,97,116,117,115,32,37,100,0],"i8",ALLOC_STATIC);__str15595=allocate([109,98,114,111,108,97,32,100,105,101,100,32,97,110,100,32,119,97,105,116,32,115,116,97,116,117,115,32,105,115,32,119,101,105,114,100,0],"i8",ALLOC_STATIC);__str16596=allocate([109,98,114,111,119,114,97,112,32,101,114,114,111,114,58,32,37,115,0],"i8",ALLOC_STATIC);__str17597=allocate([44,32,40,37,115,41,0],"i8",ALLOC_STATIC);__ZL21mbr_pending_data_head=allocate(1,"%struct.datablock*",ALLOC_STATIC);__ZL21mbr_pending_data_tail=allocate(1,"%struct.datablock*",ALLOC_STATIC);__str18598=allocate([112,111,108,108,40,41,58,32,37,115,0],"i8",ALLOC_STATIC);__str19599=allocate([109,98,114,111,108,97,32,112,114,111,99,101,115,115,32,105,115,32,115,116,97,108,108,101,100,0],"i8",ALLOC_STATIC);__str20600=allocate([119,114,105,116,101,40,41,58,32,37,115,0],"i8",ALLOC_STATIC);__str21601=allocate([114,101,97,100,40,41,58,32,37,115,0],"i8",ALLOC_STATIC);__ZL13mbr_proc_stat=allocate(1,"i32",ALLOC_STATIC);__str22602=allocate([109,98,114,111,108,97,32,105,110,105,116,32,114,101,113,117,101,115,116,32,119,104,101,110,32,97,108,114,101,97,100,121,32,105,110,105,116,105,97,108,105,122,101,100,0],"i8",ALLOC_STATIC);__str23603=allocate([102,111,114,107,40,41,58,32,37,115,0],"i8",ALLOC_STATIC);__str24604=allocate([100,117,112,50,40,41,58,32,37,115,10,0],"i8",ALLOC_STATIC);__str25605=allocate([37,103,0],"i8",ALLOC_STATIC);__str27607=allocate([45,101,0],"i8",ALLOC_STATIC);__str28608=allocate([45,118,0],"i8",ALLOC_STATIC);__str30610=allocate([45,46,119,97,118,0],"i8",ALLOC_STATIC);__str31611=allocate([109,98,114,111,108,97,58,32,37,115,10,0],"i8",ALLOC_STATIC);__str32612=allocate([47,112,114,111,99,47,37,100,47,115,116,97,116,0],"i8",ALLOC_STATIC);__str33613=allocate([47,112,114,111,99,32,105,115,32,117,110,97,99,99,101,115,115,105,98,108,101,58,32,37,115,0],"i8",ALLOC_STATIC);__str34614=allocate([102,99,110,116,108,40,41,58,32,37,115,0],"i8",ALLOC_STATIC);__str35615=allocate([112,105,112,101,40,41,58,32,37,115,0],"i8",ALLOC_STATIC);__ZZ15SetIndicLettersP10TranslatorE15dev_consonants2=allocate([2,3,88,89,90,91,92,93,94,95],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_fr=allocate([190,0,170,0,190,0,200,0,0,0,0,0,190,0,240,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_fr=allocate([18,16,18,18,18,18,18,18],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_sk=allocate([17,17,20,20,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_sk=allocate([190,0,190,0,210,0,210,0,0,0,0,0,210,0,210,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_ta=allocate([200,0,200,0,210,0,210,0,0,0,0,0,230,0,230,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_ta=allocate([18,18,18,18,20,20,22,22],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_af=allocate([170,0,140,0,220,0,220,0,0,0,0,0,250,0,270,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_bn=allocate([180,0,180,0,210,0,210,0,0,0,0,0,230,0,240,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_bn=allocate([18,18,18,18,20,20,22,22],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_cy=allocate([170,0,220,0,180,0,180,0,0,0,0,0,250,0,270,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_cy=allocate([17,15,18,18,0,0,22,20],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_da=allocate([160,0,140,0,200,0,200,0,0,0,0,0,220,0,230,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_de=allocate([150,0,130,0,200,0,200,0,0,0,0,0,270,0,270,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_de=allocate([20,20,20,20,20,22,22,20],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_en=allocate([182,0,140,0,220,0,220,0,0,0,0,0,248,0,275,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__str630=allocate([97,101,105,111,117,121,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_el=allocate([155,0,180,0,210,0,210,0,0,0,0,0,270,0,300,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_el=allocate([15,12,20,20,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE9el_vowels=allocate([16,44,45,46,47,48,49,53,55,57,63,69,73,74,75,76,77,78,79,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE10el_fvowels=allocate([45,46,47,53,55,57,69,77,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE12el_voiceless=allocate([56,58,62,64,66,67,68,70,71,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE13el_consonants=allocate([50,51,52,54,56,58,59,60,61,62,64,65,66,67,68,70,71,72,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE18el_char_apostrophe=allocate([963,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_eo=allocate([150,0,150,0,230,0,180,0,0,0,0,0,300,0,320,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_eo=allocate([16,14,20,20,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE18eo_char_apostrophe=allocate([108,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_es=allocate([180,0,210,0,190,0,190,0,0,0,0,0,230,0,260,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_es=allocate([16,12,18,18,20,20,20,20],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE20ca_punct_within_word=allocate([39,0,0,0,183,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_eu=allocate([200,0,200,0,200,0,200,0,0,0,0,0,210,0,230,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_eu=allocate([16,16,18,18,18,18,18,18],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_fi=allocate([18,16,22,22,20,22,22,22],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_fi=allocate([150,0,180,0,200,0,200,0,0,0,0,0,210,0,250,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_hi=allocate([190,0,190,0,210,0,210,0,0,0,0,0,230,0,250,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_hi=allocate([17,14,20,19,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_hr=allocate([17,17,20,20,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_hr=allocate([180,0,160,0,200,0,200,0,0,0,0,0,220,0,230,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_sr=allocate([160,0,150,0,200,0,200,0,0,0,0,0,250,0,260,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZL22replace_cyrillic_latin=allocate([1072,0,0,0,97,0,0,0,1073,0,0,0,98,0,0,0,1094,0,0,0,99,0,0,0,1115,0,0,0,263,0,0,0,1095,0,0,0,269,0,0,0,1119,0,0,0,25034852,0,0,0,1109,0,0,0,7995492,0,0,0,1076,0,0,0,100,0,0,0,1106,0,0,0,273,0,0,0,1077,0,0,0,101,0,0,0,1092,0,0,0,102,0,0,0,1075,0,0,0,103,0,0,0,1093,0,0,0,104,0,0,0,1080,0,0,0,105,0,0,0,1112,0,0,0,106,0,0,0,1082,0,0,0,107,0,0,0,1113,0,0,0,6946924,0,0,0,1083,0,0,0,108,0,0,0,1084,0,0,0,109,0,0,0,1114,0,0,0,6946926,0,0,0,1085,0,0,0,110,0,0,0,1086,0,0,0,111,0,0,0,1087,0,0,0,112,0,0,0,1088,0,0,0,114,0,0,0,1089,0,0,0,115,0,0,0,1096,0,0,0,353,0,0,0,1090,0,0,0,116,0,0,0,1091,0,0,0,117,0,0,0,1074,0,0,0,118,0,0,0,1079,0,0,0,122,0,0,0,1078,0,0,0,382,0,0,0,1107,0,0,0,273,0,0,0,1116,0,0,0,263,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_hu=allocate([17,17,19,19,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_hu=allocate([185,0,195,0,195,0,190,0,0,0,0,0,210,0,220,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_hy=allocate([250,0,200,0,250,0,250,0,0,0,0,0,250,0,250,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE9hy_vowels=allocate([49,53,55,56,59,72,85,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE13hy_consonants=allocate([50,51,52,54,57,58,60,61,62,63,64,65,66,67,68,69,70,71,73,74,75,76,77,78,79,80,81,82,83,84,86,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_id=allocate([160,0,200,0,180,0,180,0,0,0,0,0,220,0,240,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_id=allocate([16,18,18,18,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_is=allocate([180,0,160,0,200,0,200,0,0,0,0,0,240,0,250,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE16is_lettergroup_B=allocate([99,0,0,0,102,0,0,0,104,0,0,0,107,0,0,0,112,0,0,0,116,0,0,0,120,0,0,0,254,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str1631=allocate([107,112,115,116,0],"i8",ALLOC_STATIC);__str2632=allocate([106,118,114,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_it=allocate([150,0,140,0,170,0,170,0,0,0,0,0,300,0,330,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_it=allocate([15,14,19,19,20,22,22,20],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE18stress_lengths_jbo=allocate([145,0,145,0,170,0,160,0,0,0,0,0,330,0,350,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE21jbo_punct_within_word=allocate([46,0,0,0,44,0,0,0,39,0,0,0,712,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE9ka_vowels=allocate([80,84,88,93,99,117,119,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE13ka_consonants=allocate([81,82,83,85,86,87,89,90,91,92,94,95,96,97,98,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,118,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE10ko_ivowels=allocate([99,100,103,104,109,114,116,117,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE9ko_voiced=allocate([2,5,6,171,175,183,188,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_ku=allocate([18,18,20,20,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_ku=allocate([180,0,180,0,190,0,180,0,0,0,0,0,230,0,240,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_lv=allocate([17,13,20,20,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_lv=allocate([180,0,130,0,210,0,210,0,0,0,0,0,210,0,210,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE15vowels_cyrillic=allocate([1088,0,0,0,1072,0,0,0,1077,0,0,0,1080,0,0,0,1081,0,0,0,1086,0,0,0,1091,0,0,0,1099,0,0,0,1101,0,0,0,1102,0,0,0,1103,0,0,0,1104,0,0,0,1105,0,0,0,1110,0,0,0,1111,0,0,0,1117,0,0,0,1118,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_mk=allocate([17,17,20,20,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_mk=allocate([180,0,160,0,200,0,200,0,0,0,0,0,220,0,230,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_nl=allocate([160,0,135,0,210,0,210,0,0,0,0,0,260,0,280,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__str3633=allocate([101,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_no=allocate([160,0,140,0,200,0,200,0,0,0,0,0,220,0,230,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_om=allocate([18,15,20,20,20,22,22,22],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_om=allocate([200,0,200,0,200,0,200,0,0,0,0,0,200,0,200,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_pl=allocate([160,0,190,0,175,0,175,0,0,0,0,0,200,0,210,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_pl=allocate([17,13,19,19,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_pt=allocate([170,0,115,0,210,0,240,0,0,0,0,0,260,0,280,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_pt=allocate([16,11,19,21,20,22,22,21],"i8",ALLOC_STATIC);__str4634=allocate([98,99,100,102,103,106,107,109,110,112,113,115,116,118,120,122,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_ro=allocate([170,0,170,0,180,0,180,0,0,0,0,0,240,0,260,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_ro=allocate([15,13,18,18,20,22,22,21],"i8",ALLOC_STATIC);__str5635=allocate([98,100,103,106,108,109,110,114,118,119,122,97,101,105,111,117,121,0],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_sq=allocate([150,0,150,0,180,0,180,0,0,0,0,0,300,0,300,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_sq=allocate([16,12,16,16,20,20,21,19],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_sv=allocate([16,16,20,20,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_sv=allocate([160,0,135,0,220,0,220,0,0,0,0,0,250,0,280,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_sw=allocate([160,0,170,0,200,0,200,0,0,0,0,0,320,0,340,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_sw=allocate([16,12,19,19,20,22,22,21],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_tr=allocate([18,16,20,21,20,21,21,20],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_tr=allocate([190,0,180,0,200,0,230,0,0,0,0,0,240,0,250,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_vi=allocate([150,0,150,0,180,0,180,0,210,0,230,0,230,0,240,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_vi=allocate([16,16,16,16,22,22,22,22],"i8",ALLOC_STATIC);__ZZ16SelectTranslatorPKcE9vowels_vi=allocate([97,0,0,0,224,0,0,0,225,0,0,0,7843,0,0,0,227,0,0,0,7841,0,0,0,259,0,0,0,7857,0,0,0,7855,0,0,0,7859,0,0,0,7861,0,0,0,7863,0,0,0,226,0,0,0,7847,0,0,0,7845,0,0,0,7849,0,0,0,7851,0,0,0,7853,0,0,0,101,0,0,0,232,0,0,0,233,0,0,0,7867,0,0,0,7869,0,0,0,7865,0,0,0,234,0,0,0,7873,0,0,0,7871,0,0,0,7875,0,0,0,7877,0,0,0,7879,0,0,0,105,0,0,0,236,0,0,0,237,0,0,0,7881,0,0,0,297,0,0,0,7883,0,0,0,111,0,0,0,242,0,0,0,243,0,0,0,7887,0,0,0,245,0,0,0,7885,0,0,0,244,0,0,0,7891,0,0,0,7889,0,0,0,7893,0,0,0,7895,0,0,0,7897,0,0,0,417,0,0,0,7901,0,0,0,7899,0,0,0,7903,0,0,0,7905,0,0,0,7907,0,0,0,117,0,0,0,249,0,0,0,250,0,0,0,7911,0,0,0,361,0,0,0,7909,0,0,0,432,0,0,0,7915,0,0,0,7913,0,0,0,7917,0,0,0,7919,0,0,0,7921,0,0,0,121,0,0,0,7923,0,0,0,253,0,0,0,7927,0,0,0,7929,0,0,0,30,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE17stress_lengths_zh=allocate([230,0,150,0,230,0,230,0,230,0,0,0,240,0,250,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ16SelectTranslatorPKcE14stress_amps_zh=allocate([22,16,22,22,22,22,22,22],"i8",ALLOC_STATIC);__ZZL18Translator_RussianP10TranslatorE14stress_amps_ru=allocate([16,16,18,18,20,24,24,22],"i8",ALLOC_STATIC);__ZZL18Translator_RussianP10TranslatorE17stress_lengths_ru=allocate([150,0,140,0,220,0,220,0,0,0,0,0,260,0,280,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZL18Translator_RussianP10TranslatorE11ru_ivowels2=allocate([44,21,24,46,47,0],"i8",ALLOC_STATIC);__ZZL18SetCyrillicLettersP10TranslatorE9ru_vowels=allocate([16,21,49,24,30,35,43,45,46,47,0],"i8",ALLOC_STATIC);__ZZL18SetCyrillicLettersP10TranslatorE13ru_consonants=allocate([17,18,19,20,22,23,25,26,27,28,29,31,32,33,34,36,37,38,39,40,41,42,44,0],"i8",ALLOC_STATIC);__ZZL18SetCyrillicLettersP10TranslatorE7ru_soft=allocate([44,25,39,41,0],"i8",ALLOC_STATIC);__ZZL18SetCyrillicLettersP10TranslatorE7ru_hard=allocate([42,22,38,40,0],"i8",ALLOC_STATIC);__ZZL18SetCyrillicLettersP10TranslatorE10ru_nothard=allocate([17,18,19,20,23,25,26,27,28,29,31,32,33,34,36,37,39,41,44,0],"i8",ALLOC_STATIC);__ZZL18SetCyrillicLettersP10TranslatorE9ru_voiced=allocate([17,18,19,20,22,23,0],"i8",ALLOC_STATIC);__ZZL18SetCyrillicLettersP10TranslatorE10ru_ivowels=allocate([44,46,47,49,0],"i8",ALLOC_STATIC);__ZL8pairs_ru=allocate([268,0,270,0,275,0,769,0,783,0,1550,0,1553,0,2307,0,2817,0,2831,0,3073,0,3081,0,3585,0,3590,0,3593,0,3598,0,3599,0,3612,0,3843,0,3857,0,3858,0,4111,0,4113,0,4353,0,4358,0,4361,0,4367,0,4627,0,4640,0,32767,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZL13NewTranslatorvE12stress_amps2=allocate([18,18,20,20,20,22,22,20],"i8",ALLOC_STATIC);__ZZL13NewTranslatorvE15stress_lengths2=allocate([182,0,140,0,220,0,220,0,220,0,240,0,260,0,280,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZL13NewTranslatorvE13empty_wstring=allocate(4,"i32",ALLOC_STATIC);__ZZL13NewTranslatorvE13punct_in_word=allocate([39,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZL13NewTranslatorvE13default_tunes=allocate([0,1,2,3,0,0],"i8",ALLOC_STATIC);__str6636=allocate([97,101,105,111,117,0],"i8",ALLOC_STATIC);__str7637=allocate([98,99,100,102,103,106,107,108,109,110,112,113,115,116,118,120,122,0],"i8",ALLOC_STATIC);__str8638=allocate([98,99,100,102,103,104,106,107,108,109,110,112,113,114,115,116,118,119,120,122,0],"i8",ALLOC_STATIC);__str9639=allocate([104,108,109,110,114,0],"i8",ALLOC_STATIC);__str10640=allocate([99,102,104,107,112,113,115,116,120,0],"i8",ALLOC_STATIC);__str11641=allocate([98,100,103,106,108,109,110,114,118,119,121,122,0],"i8",ALLOC_STATIC);__str12642=allocate([101,105,121,0],"i8",ALLOC_STATIC);__str13643=allocate(1,"i8",ALLOC_STATIC);__str646=allocate([117,110,107,110,111,119,110,0],"i8",ALLOC_STATIC);__str1647=allocate([109,97,108,101,0],"i8",ALLOC_STATIC);__str2648=allocate([102,101,109,97,108,101,0],"i8",ALLOC_STATIC);_genders=allocate([0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);_tone_points=allocate([600,0,0,0,170,0,0,0,1200,0,0,0,135,0,0,0,2000,0,0,0,110,0,0,0,3000,0,0,0,110,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);_formant_rate=allocate(36,"i32",ALLOC_STATIC);_voice_selected=allocate(24,["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0],ALLOC_STATIC);__str3653=allocate([114,101,100,117,99,101,95,116,0],"i8",ALLOC_STATIC);__str4654=allocate([98,114,97,99,107,101,116,0],"i8",ALLOC_STATIC);__ZL11options_tab=allocate([0,0,0,0,12,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,-1,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__str5655=allocate([110,97,109,101,0],"i8",ALLOC_STATIC);__str6656=allocate([108,97,110,103,117,97,103,101,0],"i8",ALLOC_STATIC);__str7657=allocate([103,101,110,100,101,114,0],"i8",ALLOC_STATIC);__str8658=allocate([102,111,114,109,97,110,116,0],"i8",ALLOC_STATIC);__str9659=allocate([112,105,116,99,104,0],"i8",ALLOC_STATIC);__str10660=allocate([112,104,111,110,101,109,101,115,0],"i8",ALLOC_STATIC);__str11661=allocate([116,114,97,110,115,108,97,116,111,114,0],"i8",ALLOC_STATIC);__str12662=allocate([100,105,99,116,105,111,110,97,114,121,0],"i8",ALLOC_STATIC);__str13663=allocate([115,116,114,101,115,115,76,101,110,103,116,104,0],"i8",ALLOC_STATIC);__str14664=allocate([115,116,114,101,115,115,65,109,112,0],"i8",ALLOC_STATIC);__str15665=allocate([115,116,114,101,115,115,65,100,100,0],"i8",ALLOC_STATIC);__str16666=allocate([105,110,116,111,110,97,116,105,111,110,0],"i8",ALLOC_STATIC);__str17667=allocate([116,117,110,101,115,0],"i8",ALLOC_STATIC);__str18668=allocate([100,105,99,116,114,117,108,101,115,0],"i8",ALLOC_STATIC);__str19669=allocate([115,116,114,101,115,115,114,117,108,101,0],"i8",ALLOC_STATIC);__str20670=allocate([99,104,97,114,115,101,116,0],"i8",ALLOC_STATIC);__str21671=allocate([114,101,112,108,97,99,101,0],"i8",ALLOC_STATIC);__str22672=allocate([119,111,114,100,115,0],"i8",ALLOC_STATIC);__str23673=allocate([101,99,104,111,0],"i8",ALLOC_STATIC);__str24674=allocate([102,108,117,116,116,101,114,0],"i8",ALLOC_STATIC);__str25675=allocate([114,111,117,103,104,110,101,115,115,0],"i8",ALLOC_STATIC);__str26676=allocate([99,108,97,114,105,116,121,0],"i8",ALLOC_STATIC);__str27677=allocate([116,111,110,101,0],"i8",ALLOC_STATIC);__str28678=allocate([118,111,105,99,105,110,103,0],"i8",ALLOC_STATIC);__str29679=allocate([98,114,101,97,116,104,0],"i8",ALLOC_STATIC);__str30680=allocate([98,114,101,97,116,104,119,0],"i8",ALLOC_STATIC);__str31681=allocate([110,117,109,98,101,114,115,0],"i8",ALLOC_STATIC);__str32682=allocate([111,112,116,105,111,110,0],"i8",ALLOC_STATIC);__str33683=allocate([109,98,114,111,108,97,0],"i8",ALLOC_STATIC);__str34684=allocate([99,111,110,115,111,110,97,110,116,115,0],"i8",ALLOC_STATIC);__str35685=allocate([107,108,97,116,116,0],"i8",ALLOC_STATIC);__str36686=allocate([102,97,115,116,95,116,101,115,116,50,0],"i8",ALLOC_STATIC);__str37687=allocate([115,112,101,101,100,0],"i8",ALLOC_STATIC);__str38688=allocate([108,95,100,105,101,114,101,115,105,115,0],"i8",ALLOC_STATIC);__str39689=allocate([108,95,112,114,101,102,105,120,0],"i8",ALLOC_STATIC);__str40690=allocate([108,95,114,101,103,114,101,115,115,105,118,101,95,118,0],"i8",ALLOC_STATIC);__str41691=allocate([108,95,117,110,112,114,111,110,111,117,110,99,97,98,108,101,0],"i8",ALLOC_STATIC);__str42692=allocate([108,95,115,111,110,111,114,97,110,116,95,109,105,110,0],"i8",ALLOC_STATIC);__str43693=allocate([108,95,108,101,110,103,116,104,95,109,111,100,115,0],"i8",ALLOC_STATIC);__ZL11keyword_tab=allocate([0,0,0,0,1,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,7,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0,20,0,0,0,0,0,0,0,21,0,0,0,0,0,0,0,22,0,0,0,0,0,0,0,18,0,0,0,0,0,0,0,19,0,0,0,0,0,0,0,23,0,0,0,0,0,0,0,24,0,0,0,0,0,0,0,25,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,17,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,13,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,15,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,26,0,0,0,0,0,0,0,27,0,0,0,0,0,0,0,28,0,0,0,0,0,0,0,33,0,0,0,0,0,0,0,29,0,0,0,0,0,0,0,30,0,0,0,0,0,0,0,31,0,0,0,0,0,0,0,257,0,0,0,0,0,0,0,259,0,0,0,0,0,0,0,260,0,0,0,0,0,0,0,261,0,0,0,0,0,0,0,263,0,0,0,0,0,0,0,262,0,0,0,0,0,0,0,0,0,0,0],["i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZL15variants_either=allocate([1,2,12,3,13,4,14,5,11,0,0,0],"i8",ALLOC_STATIC);__ZL13variants_male=allocate([1,2,3,4,5,0,0,0,0,0,0,0],"i8",ALLOC_STATIC);__ZL15variants_female=allocate([11,12,13,14,0,0,0,0,0,0,0,0],"i8",ALLOC_STATIC);_variant_lists=allocate(12,"i8*",ALLOC_STATIC);__ZL9voicedata=allocate(1344,["i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8"],ALLOC_STATIC);_voice=allocate(1,"%struct.voice_t*",ALLOC_STATIC);__str44696=allocate([37,100,32,37,100,32,37,100,32,37,100,32,37,100,32,37,100,32,37,100,32,37,100,32,37,100,32,37,100,0],"i8",ALLOC_STATIC);__ZZ10VoiceResetiE15default_heights=allocate([128,128,120,120,110,110,128,128,128],"i8",ALLOC_STATIC);__ZZ10VoiceResetiE14default_widths=allocate([128,128,128,160,171,171,128,128,128],"i8",ALLOC_STATIC);__ZZ10VoiceResetiE13breath_widths=allocate([0,0,0,0,200,0,0,0,200,0,0,0,400,0,0,0,400,0,0,0,400,0,0,0,600,0,0,0,600,0,0,0,600,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZL18formant_rate_22050=allocate([240,0,0,0,170,0,0,0,170,0,0,0,170,0,0,0,170,0,0,0,170,0,0,0,170,0,0,0,170,0,0,0,170,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ9LoadVoicePKciE16voice_identifier=allocate(40,"i8",ALLOC_STATIC);__ZZ9LoadVoicePKciE10voice_name=allocate(40,"i8",ALLOC_STATIC);__ZZ9LoadVoicePKciE15voice_languages=allocate(100,"i8",ALLOC_STATIC);__str45697=allocate([100,101,102,97,117,108,116,0],"i8",ALLOC_STATIC);__str46698=allocate([37,115,37,99,118,111,105,99,101,115,37,99,0],"i8",ALLOC_STATIC);__str47699=allocate([37,115,37,115,0],"i8",ALLOC_STATIC);__str48700=allocate([37,115,37,115,37,99,37,115,0],"i8",ALLOC_STATIC);__str49701=allocate([37,115,101,120,116,114,97,37,99,37,115,0],"i8",ALLOC_STATIC);__str50702=allocate([37,115,116,101,115,116,37,99,37,115,0],"i8",ALLOC_STATIC);__str51703=allocate([114,0],"i8",ALLOC_STATIC);__str52704=allocate([101,110,0],"i8",ALLOC_STATIC);__str53705=allocate([43,37,115,0],"i8",ALLOC_STATIC);__str54706=allocate([37,115,32,37,100,0],"i8",ALLOC_STATIC);__str55707=allocate([118,97,114,105,97,110,116,0],"i8",ALLOC_STATIC);__str56708=allocate([45,0],"i8",ALLOC_STATIC);__str57709=allocate([37,115,0],"i8",ALLOC_STATIC);__str58710=allocate([37,100,32,37,100,0],"i8",ALLOC_STATIC);__str59711=allocate([37,115,32,37,115,32,37,115,32,37,115,32,37,115,32,37,115,0],"i8",ALLOC_STATIC);__str60712=allocate([78,85,76,76,0],"i8",ALLOC_STATIC);__str61713=allocate([85,110,107,110,111,119,110,32,116,117,110,101,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__str62714=allocate([37,100,32,37,100,32,37,100,32,37,100,0],"i8",ALLOC_STATIC);__str63715=allocate([37,100,0],"i8",ALLOC_STATIC);__str64716=allocate([37,115,32,37,100,32,37,100,0],"i8",ALLOC_STATIC);__str65717=allocate([66,97,100,32,118,111,105,99,101,32,111,112,116,105,111,110,58,32,37,115,32,37,115,10,0],"i8",ALLOC_STATIC);__str66718=allocate([37,115,32,37,115,32,37,100,0],"i8",ALLOC_STATIC);__str67719=allocate([109,98,114,111,108,97,32,118,111,105,99,101,32,110,111,116,32,102,111,117,110,100,10,0],"i8",ALLOC_STATIC);__str68720=allocate([66,97,100,32,118,111,105,99,101,32,97,116,116,114,105,98,117,116,101,58,32,37,115,10,0],"i8",ALLOC_STATIC);__str69721=allocate([85,110,107,110,111,119,110,32,112,104,111,110,101,109,101,32,116,97,98,108,101,58,32,39,37,115,39,10,0],"i8",ALLOC_STATIC);__ZL13n_voices_list=allocate(1,"i32",ALLOC_STATIC);__ZL11voices_list=allocate(600,"%struct.espeak_VOICE*",ALLOC_STATIC);__str70722=allocate([37,99,37,115,0],"i8",ALLOC_STATIC);__ZZ11SelectVoiceP12espeak_VOICEPiE14voice_variants=allocate(288,["i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8*",0,0,0,"i8","i8","i8","i8","i32",0,0,0,"i8*",0,0,0],ALLOC_STATIC);__ZZ11SelectVoiceP12espeak_VOICEPiE8voice_id=allocate(50,"i8",ALLOC_STATIC);__ZZ11SelectVoiceP12espeak_VOICEPiE3buf=allocate(60,"i8",ALLOC_STATIC);__str71723=allocate([37,115,43,37,115,0],"i8",ALLOC_STATIC);__ZZ14SetVoiceByNamePKcE3buf=allocate(60,"i8",ALLOC_STATIC);__ZZ17espeak_ListVoicesE6voices=allocate(600,"%struct.espeak_VOICE*",ALLOC_STATIC);__str72724=allocate([37,115,37,99,118,111,105,99,101,115,0],"i8",ALLOC_STATIC);__ZL15len_path_voices=allocate(1,"i32",ALLOC_STATIC);__str73725=allocate([109,98,47,0],"i8",ALLOC_STATIC);__str74726=allocate([37,115,37,99,37,115,0],"i8",ALLOC_STATIC);__str75727=allocate([118,97,114,105,97,110,116,115,0],"i8",ALLOC_STATIC);__ZZL23ExtractVoiceVariantNamePciE12variant_name=allocate(20,"i8",ALLOC_STATIC);__str76728=allocate([33,118,37,99,0],"i8",ALLOC_STATIC);__str77729=allocate([37,115,109,37,100,0],"i8",ALLOC_STATIC);__str78730=allocate([37,115,102,37,100,0],"i8",ALLOC_STATIC);__str79731=allocate([37,100,32,37,115,32,37,115,0],"i8",ALLOC_STATIC);__str80732=allocate([37,100,32,37,100,32,37,100,32,37,100,32,37,100,32,37,100,32,37,100,32,37,100,0],"i8",ALLOC_STATIC);__str81733=allocate([37,100,32,37,100,32,37,100,32,37,100,32,37,100,0],"i8",ALLOC_STATIC);__str82734=allocate([47,47,0],"i8",ALLOC_STATIC);_sin_tab=allocate([0,0,-25,0,-50,0,-75,0,-100,0,-125,0,-150,0,-175,0,-201,0,-226,0,-251,0,-276,0,-301,0,-326,0,-351,0,-376,0,-401,0,-427,0,-452,0,-477,0,-502,0,-527,0,-552,0,-577,0,-602,0,-627,0,-652,0,-677,0,-702,0,-727,0,-752,0,-777,0,-802,0,-827,0,-852,0,-877,0,-902,0,-927,0,-952,0,-977,0,-1002,0,-1027,0,-1052,0,-1077,0,-1102,0,-1127,0,-1152,0,-1177,0,-1201,0,-1226,0,-1251,0,-1276,0,-1301,0,-1326,0,-1350,0,-1375,0,-1400,0,-1425,0,-1449,0,-1474,0,-1499,0,-1523,0,-1548,0,-1573,0,-1597,0,-1622,0,-1647,0,-1671,0,-1696,0,-1721,0,-1745,0,-1770,0,-1794,0,-1819,0,-1843,0,-1868,0,-1892,0,-1917,0,-1941,0,-1965,0,-1990,0,-2014,0,-2038,0,-2063,0,-2087,0,-2111,0,-2136,0,-2160,0,-2184,0,-2208,0,-2233,0,-2257,0,-2281,0,-2305,0,-2329,0,-2353,0,-2377,0,-2401,0,-2425,0,-2449,0,-2473,0,-2497,0,-2521,0,-2545,0,-2569,0,-2593,0,-2617,0,-2640,0,-2664,0,-2688,0,-2712,0,-2735,0,-2759,0,-2783,0,-2806,0,-2830,0,-2853,0,-2877,0,-2900,0,-2924,0,-2947,0,-2971,0,-2994,0,-3018,0,-3041,0,-3064,0,-3088,0,-3111,0,-3134,0,-3157,0,-3180,0,-3204,0,-3227,0,-3250,0,-3273,0,-3296,0,-3319,0,-3342,0,-3365,0,-3388,0,-3410,0,-3433,0,-3456,0,-3479,0,-3502,0,-3524,0,-3547,0,-3570,0,-3592,0,-3615,0,-3637,0,-3660,0,-3682,0,-3705,0,-3727,0,-3749,0,-3772,0,-3794,0,-3816,0,-3839,0,-3861,0,-3883,0,-3905,0,-3927,0,-3949,0,-3971,0,-3993,0,-4015,0,-4037,0,-4059,0,-4080,0,-4102,0,-4124,0,-4146,0,-4167,0,-4189,0,-4211,0,-4232,0,-4254,0,-4275,0,-4296,0,-4318,0,-4339,0,-4360,0,-4382,0,-4403,0,-4424,0,-4445,0,-4466,0,-4487,0,-4508,0,-4529,0,-4550,0,-4571,0,-4592,0,-4613,0,-4633,0,-4654,0,-4675,0,-4695,0,-4716,0,-4736,0,-4757,0,-4777,0,-4798,0,-4818,0,-4838,0,-4859,0,-4879,0,-4899,0,-4919,0,-4939,0,-4959,0,-4979,0,-4999,0,-5019,0,-5039,0,-5059,0,-5078,0,-5098,0,-5118,0,-5137,0,-5157,0,-5176,0,-5196,0,-5215,0,-5235,0,-5254,0,-5273,0,-5292,0,-5311,0,-5331,0,-5350,0,-5369,0,-5388,0,-5406,0,-5425,0,-5444,0,-5463,0,-5482,0,-5500,0,-5519,0,-5537,0,-5556,0,-5574,0,-5593,0,-5611,0,-5629,0,-5648,0,-5666,0,-5684,0,-5702,0,-5720,0,-5738,0,-5756,0,-5774,0,-5791,0,-5809,0,-5827,0,-5844,0,-5862,0,-5880,0,-5897,0,-5914,0,-5932,0,-5949,0,-5966,0,-5984,0,-6001,0,-6018,0,-6035,0,-6052,0,-6069,0,-6085,0,-6102,0,-6119,0,-6136,0,-6152,0,-6169,0,-6185,0,-6202,0,-6218,0,-6235,0,-6251,0,-6267,0,-6283,0,-6299,0,-6315,0,-6331,0,-6347,0,-6363,0,-6379,0,-6395,0,-6410,0,-6426,0,-6441,0,-6457,0,-6472,0,-6488,0,-6503,0,-6518,0,-6533,0,-6549,0,-6564,0,-6579,0,-6594,0,-6608,0,-6623,0,-6638,0,-6653,0,-6667,0,-6682,0,-6696,0,-6711,0,-6725,0,-6739,0,-6754,0,-6768,0,-6782,0,-6796,0,-6810,0,-6824,0,-6838,0,-6852,0,-6865,0,-6879,0,-6893,0,-6906,0,-6920,0,-6933,0,-6946,0,-6960,0,-6973,0,-6986,0,-6999,0,-7012,0,-7025,0,-7038,0,-7051,0,-7064,0,-7076,0,-7089,0,-7101,0,-7114,0,-7126,0,-7139,0,-7151,0,-7163,0,-7175,0,-7187,0,-7199,0,-7211,0,-7223,0,-7235,0,-7247,0,-7259,0,-7270,0,-7282,0,-7293,0,-7305,0,-7316,0,-7327,0,-7338,0,-7349,0,-7361,0,-7372,0,-7382,0,-7393,0,-7404,0,-7415,0,-7425,0,-7436,0,-7446,0,-7457,0,-7467,0,-7478,0,-7488,0,-7498,0,-7508,0,-7518,0,-7528,0,-7538,0,-7548,0,-7557,0,-7567,0,-7577,0,-7586,0,-7596,0,-7605,0,-7614,0,-7623,0,-7633,0,-7642,0,-7651,0,-7660,0,-7668,0,-7677,0,-7686,0,-7695,0,-7703,0,-7712,0,-7720,0,-7728,0,-7737,0,-7745,0,-7753,0,-7761,0,-7769,0,-7777,0,-7785,0,-7793,0,-7800,0,-7808,0,-7816,0,-7823,0,-7830,0,-7838,0,-7845,0,-7852,0,-7859,0,-7866,0,-7873,0,-7880,0,-7887,0,-7894,0,-7900,0,-7907,0,-7914,0,-7920,0,-7926,0,-7933,0,-7939,0,-7945,0,-7951,0,-7957,0,-7963,0,-7969,0,-7975,0,-7980,0,-7986,0,-7991,0,-7997,0,-8002,0,-8008,0,-8013,0,-8018,0,-8023,0,-8028,0,-8033,0,-8038,0,-8043,0,-8047,0,-8052,0,-8057,0,-8061,0,-8066,0,-8070,0,-8074,0,-8078,0,-8082,0,-8086,0,-8090,0,-8094,0,-8098,0,-8102,0,-8105,0,-8109,0,-8113,0,-8116,0,-8119,0,-8123,0,-8126,0,-8129,0,-8132,0,-8135,0,-8138,0,-8141,0,-8143,0,-8146,0,-8149,0,-8151,0,-8153,0,-8156,0,-8158,0,-8160,0,-8162,0,-8164,0,-8166,0,-8168,0,-8170,0,-8172,0,-8174,0,-8175,0,-8177,0,-8178,0,-8179,0,-8181,0,-8182,0,-8183,0,-8184,0,-8185,0,-8186,0,-8187,0,-8187,0,-8188,0,-8189,0,-8189,0,-8190,0,-8190,0,-8190,0,-8190,0,-8190,0,-8191,0,-8190,0,-8190,0,-8190,0,-8190,0,-8190,0,-8189,0,-8189,0,-8188,0,-8187,0,-8187,0,-8186,0,-8185,0,-8184,0,-8183,0,-8182,0,-8181,0,-8179,0,-8178,0,-8177,0,-8175,0,-8174,0,-8172,0,-8170,0,-8168,0,-8166,0,-8164,0,-8162,0,-8160,0,-8158,0,-8156,0,-8153,0,-8151,0,-8149,0,-8146,0,-8143,0,-8141,0,-8138,0,-8135,0,-8132,0,-8129,0,-8126,0,-8123,0,-8119,0,-8116,0,-8113,0,-8109,0,-8105,0,-8102,0,-8098,0,-8094,0,-8090,0,-8086,0,-8082,0,-8078,0,-8074,0,-8070,0,-8066,0,-8061,0,-8057,0,-8052,0,-8047,0,-8043,0,-8038,0,-8033,0,-8028,0,-8023,0,-8018,0,-8013,0,-8008,0,-8002,0,-7997,0,-7991,0,-7986,0,-7980,0,-7975,0,-7969,0,-7963,0,-7957,0,-7951,0,-7945,0,-7939,0,-7933,0,-7926,0,-7920,0,-7914,0,-7907,0,-7900,0,-7894,0,-7887,0,-7880,0,-7873,0,-7866,0,-7859,0,-7852,0,-7845,0,-7838,0,-7830,0,-7823,0,-7816,0,-7808,0,-7800,0,-7793,0,-7785,0,-7777,0,-7769,0,-7761,0,-7753,0,-7745,0,-7737,0,-7728,0,-7720,0,-7712,0,-7703,0,-7695,0,-7686,0,-7677,0,-7668,0,-7660,0,-7651,0,-7642,0,-7633,0,-7623,0,-7614,0,-7605,0,-7596,0,-7586,0,-7577,0,-7567,0,-7557,0,-7548,0,-7538,0,-7528,0,-7518,0,-7508,0,-7498,0,-7488,0,-7478,0,-7467,0,-7457,0,-7446,0,-7436,0,-7425,0,-7415,0,-7404,0,-7393,0,-7382,0,-7372,0,-7361,0,-7349,0,-7338,0,-7327,0,-7316,0,-7305,0,-7293,0,-7282,0,-7270,0,-7259,0,-7247,0,-7235,0,-7223,0,-7211,0,-7199,0,-7187,0,-7175,0,-7163,0,-7151,0,-7139,0,-7126,0,-7114,0,-7101,0,-7089,0,-7076,0,-7064,0,-7051,0,-7038,0,-7025,0,-7012,0,-6999,0,-6986,0,-6973,0,-6960,0,-6946,0,-6933,0,-6920,0,-6906,0,-6893,0,-6879,0,-6865,0,-6852,0,-6838,0,-6824,0,-6810,0,-6796,0,-6782,0,-6768,0,-6754,0,-6739,0,-6725,0,-6711,0,-6696,0,-6682,0,-6667,0,-6653,0,-6638,0,-6623,0,-6608,0,-6594,0,-6579,0,-6564,0,-6549,0,-6533,0,-6518,0,-6503,0,-6488,0,-6472,0,-6457,0,-6441,0,-6426,0,-6410,0,-6395,0,-6379,0,-6363,0,-6347,0,-6331,0,-6315,0,-6299,0,-6283,0,-6267,0,-6251,0,-6235,0,-6218,0,-6202,0,-6185,0,-6169,0,-6152,0,-6136,0,-6119,0,-6102,0,-6085,0,-6069,0,-6052,0,-6035,0,-6018,0,-6001,0,-5984,0,-5966,0,-5949,0,-5932,0,-5914,0,-5897,0,-5880,0,-5862,0,-5844,0,-5827,0,-5809,0,-5791,0,-5774,0,-5756,0,-5738,0,-5720,0,-5702,0,-5684,0,-5666,0,-5648,0,-5629,0,-5611,0,-5593,0,-5574,0,-5556,0,-5537,0,-5519,0,-5500,0,-5482,0,-5463,0,-5444,0,-5425,0,-5406,0,-5388,0,-5369,0,-5350,0,-5331,0,-5311,0,-5292,0,-5273,0,-5254,0,-5235,0,-5215,0,-5196,0,-5176,0,-5157,0,-5137,0,-5118,0,-5098,0,-5078,0,-5059,0,-5039,0,-5019,0,-4999,0,-4979,0,-4959,0,-4939,0,-4919,0,-4899,0,-4879,0,-4859,0,-4838,0,-4818,0,-4798,0,-4777,0,-4757,0,-4736,0,-4716,0,-4695,0,-4675,0,-4654,0,-4633,0,-4613,0,-4592,0,-4571,0,-4550,0,-4529,0,-4508,0,-4487,0,-4466,0,-4445,0,-4424,0,-4403,0,-4382,0,-4360,0,-4339,0,-4318,0,-4296,0,-4275,0,-4254,0,-4232,0,-4211,0,-4189,0,-4167,0,-4146,0,-4124,0,-4102,0,-4080,0,-4059,0,-4037,0,-4015,0,-3993,0,-3971,0,-3949,0,-3927,0,-3905,0,-3883,0,-3861,0,-3839,0,-3816,0,-3794,0,-3772,0,-3749,0,-3727,0,-3705,0,-3682,0,-3660,0,-3637,0,-3615,0,-3592,0,-3570,0,-3547,0,-3524,0,-3502,0,-3479,0,-3456,0,-3433,0,-3410,0,-3388,0,-3365,0,-3342,0,-3319,0,-3296,0,-3273,0,-3250,0,-3227,0,-3204,0,-3180,0,-3157,0,-3134,0,-3111,0,-3088,0,-3064,0,-3041,0,-3018,0,-2994,0,-2971,0,-2947,0,-2924,0,-2900,0,-2877,0,-2853,0,-2830,0,-2806,0,-2783,0,-2759,0,-2735,0,-2712,0,-2688,0,-2664,0,-2640,0,-2617,0,-2593,0,-2569,0,-2545,0,-2521,0,-2497,0,-2473,0,-2449,0,-2425,0,-2401,0,-2377,0,-2353,0,-2329,0,-2305,0,-2281,0,-2257,0,-2233,0,-2208,0,-2184,0,-2160,0,-2136,0,-2111,0,-2087,0,-2063,0,-2038,0,-2014,0,-1990,0,-1965,0,-1941,0,-1917,0,-1892,0,-1868,0,-1843,0,-1819,0,-1794,0,-1770,0,-1745,0,-1721,0,-1696,0,-1671,0,-1647,0,-1622,0,-1597,0,-1573,0,-1548,0,-1523,0,-1499,0,-1474,0,-1449,0,-1425,0,-1400,0,-1375,0,-1350,0,-1326,0,-1301,0,-1276,0,-1251,0,-1226,0,-1201,0,-1177,0,-1152,0,-1127,0,-1102,0,-1077,0,-1052,0,-1027,0,-1002,0,-977,0,-952,0,-927,0,-902,0,-877,0,-852,0,-827,0,-802,0,-777,0,-752,0,-727,0,-702,0,-677,0,-652,0,-627,0,-602,0,-577,0,-552,0,-527,0,-502,0,-477,0,-452,0,-427,0,-401,0,-376,0,-351,0,-326,0,-301,0,-276,0,-251,0,-226,0,-201,0,-175,0,-150,0,-125,0,-100,0,-75,0,-50,0,-25,0,0,0,25,0,50,0,75,0,100,0,125,0,150,0,175,0,201,0,226,0,251,0,276,0,301,0,326,0,351,0,376,0,401,0,427,0,452,0,477,0,502,0,527,0,552,0,577,0,602,0,627,0,652,0,677,0,702,0,727,0,752,0,777,0,802,0,827,0,852,0,877,0,902,0,927,0,952,0,977,0,1002,0,1027,0,1052,0,1077,0,1102,0,1127,0,1152,0,1177,0,1201,0,1226,0,1251,0,1276,0,1301,0,1326,0,1350,0,1375,0,1400,0,1425,0,1449,0,1474,0,1499,0,1523,0,1548,0,1573,0,1597,0,1622,0,1647,0,1671,0,1696,0,1721,0,1745,0,1770,0,1794,0,1819,0,1843,0,1868,0,1892,0,1917,0,1941,0,1965,0,1990,0,2014,0,2038,0,2063,0,2087,0,2111,0,2136,0,2160,0,2184,0,2208,0,2233,0,2257,0,2281,0,2305,0,2329,0,2353,0,2377,0,2401,0,2425,0,2449,0,2473,0,2497,0,2521,0,2545,0,2569,0,2593,0,2617,0,2640,0,2664,0,2688,0,2712,0,2735,0,2759,0,2783,0,2806,0,2830,0,2853,0,2877,0,2900,0,2924,0,2947,0,2971,0,2994,0,3018,0,3041,0,3064,0,3088,0,3111,0,3134,0,3157,0,3180,0,3204,0,3227,0,3250,0,3273,0,3296,0,3319,0,3342,0,3365,0,3388,0,3410,0,3433,0,3456,0,3479,0,3502,0,3524,0,3547,0,3570,0,3592,0,3615,0,3637,0,3660,0,3682,0,3705,0,3727,0,3749,0,3772,0,3794,0,3816,0,3839,0,3861,0,3883,0,3905,0,3927,0,3949,0,3971,0,3993,0,4015,0,4037,0,4059,0,4080,0,4102,0,4124,0,4146,0,4167,0,4189,0,4211,0,4232,0,4254,0,4275,0,4296,0,4318,0,4339,0,4360,0,4382,0,4403,0,4424,0,4445,0,4466,0,4487,0,4508,0,4529,0,4550,0,4571,0,4592,0,4613,0,4633,0,4654,0,4675,0,4695,0,4716,0,4736,0,4757,0,4777,0,4798,0,4818,0,4838,0,4859,0,4879,0,4899,0,4919,0,4939,0,4959,0,4979,0,4999,0,5019,0,5039,0,5059,0,5078,0,5098,0,5118,0,5137,0,5157,0,5176,0,5196,0,5215,0,5235,0,5254,0,5273,0,5292,0,5311,0,5331,0,5350,0,5369,0,5388,0,5406,0,5425,0,5444,0,5463,0,5482,0,5500,0,5519,0,5537,0,5556,0,5574,0,5593,0,5611,0,5629,0,5648,0,5666,0,5684,0,5702,0,5720,0,5738,0,5756,0,5774,0,5791,0,5809,0,5827,0,5844,0,5862,0,5880,0,5897,0,5914,0,5932,0,5949,0,5966,0,5984,0,6001,0,6018,0,6035,0,6052,0,6069,0,6085,0,6102,0,6119,0,6136,0,6152,0,6169,0,6185,0,6202,0,6218,0,6235,0,6251,0,6267,0,6283,0,6299,0,6315,0,6331,0,6347,0,6363,0,6379,0,6395,0,6410,0,6426,0,6441,0,6457,0,6472,0,6488,0,6503,0,6518,0,6533,0,6549,0,6564,0,6579,0,6594,0,6608,0,6623,0,6638,0,6653,0,6667,0,6682,0,6696,0,6711,0,6725,0,6739,0,6754,0,6768,0,6782,0,6796,0,6810,0,6824,0,6838,0,6852,0,6865,0,6879,0,6893,0,6906,0,6920,0,6933,0,6946,0,6960,0,6973,0,6986,0,6999,0,7012,0,7025,0,7038,0,7051,0,7064,0,7076,0,7089,0,7101,0,7114,0,7126,0,7139,0,7151,0,7163,0,7175,0,7187,0,7199,0,7211,0,7223,0,7235,0,7247,0,7259,0,7270,0,7282,0,7293,0,7305,0,7316,0,7327,0,7338,0,7349,0,7361,0,7372,0,7382,0,7393,0,7404,0,7415,0,7425,0,7436,0,7446,0,7457,0,7467,0,7478,0,7488,0,7498,0,7508,0,7518,0,7528,0,7538,0,7548,0,7557,0,7567,0,7577,0,7586,0,7596,0,7605,0,7614,0,7623,0,7633,0,7642,0,7651,0,7660,0,7668,0,7677,0,7686,0,7695,0,7703,0,7712,0,7720,0,7728,0,7737,0,7745,0,7753,0,7761,0,7769,0,7777,0,7785,0,7793,0,7800,0,7808,0,7816,0,7823,0,7830,0,7838,0,7845,0,7852,0,7859,0,7866,0,7873,0,7880,0,7887,0,7894,0,7900,0,7907,0,7914,0,7920,0,7926,0,7933,0,7939,0,7945,0,7951,0,7957,0,7963,0,7969,0,7975,0,7980,0,7986,0,7991,0,7997,0,8002,0,8008,0,8013,0,8018,0,8023,0,8028,0,8033,0,8038,0,8043,0,8047,0,8052,0,8057,0,8061,0,8066,0,8070,0,8074,0,8078,0,8082,0,8086,0,8090,0,8094,0,8098,0,8102,0,8105,0,8109,0,8113,0,8116,0,8119,0,8123,0,8126,0,8129,0,8132,0,8135,0,8138,0,8141,0,8143,0,8146,0,8149,0,8151,0,8153,0,8156,0,8158,0,8160,0,8162,0,8164,0,8166,0,8168,0,8170,0,8172,0,8174,0,8175,0,8177,0,8178,0,8179,0,8181,0,8182,0,8183,0,8184,0,8185,0,8186,0,8187,0,8187,0,8188,0,8189,0,8189,0,8190,0,8190,0,8190,0,8190,0,8190,0,8191,0,8190,0,8190,0,8190,0,8190,0,8190,0,8189,0,8189,0,8188,0,8187,0,8187,0,8186,0,8185,0,8184,0,8183,0,8182,0,8181,0,8179,0,8178,0,8177,0,8175,0,8174,0,8172,0,8170,0,8168,0,8166,0,8164,0,8162,0,8160,0,8158,0,8156,0,8153,0,8151,0,8149,0,8146,0,8143,0,8141,0,8138,0,8135,0,8132,0,8129,0,8126,0,8123,0,8119,0,8116,0,8113,0,8109,0,8105,0,8102,0,8098,0,8094,0,8090,0,8086,0,8082,0,8078,0,8074,0,8070,0,8066,0,8061,0,8057,0,8052,0,8047,0,8043,0,8038,0,8033,0,8028,0,8023,0,8018,0,8013,0,8008,0,8002,0,7997,0,7991,0,7986,0,7980,0,7975,0,7969,0,7963,0,7957,0,7951,0,7945,0,7939,0,7933,0,7926,0,7920,0,7914,0,7907,0,7900,0,7894,0,7887,0,7880,0,7873,0,7866,0,7859,0,7852,0,7845,0,7838,0,7830,0,7823,0,7816,0,7808,0,7800,0,7793,0,7785,0,7777,0,7769,0,7761,0,7753,0,7745,0,7737,0,7728,0,7720,0,7712,0,7703,0,7695,0,7686,0,7677,0,7668,0,7660,0,7651,0,7642,0,7633,0,7623,0,7614,0,7605,0,7596,0,7586,0,7577,0,7567,0,7557,0,7548,0,7538,0,7528,0,7518,0,7508,0,7498,0,7488,0,7478,0,7467,0,7457,0,7446,0,7436,0,7425,0,7415,0,7404,0,7393,0,7382,0,7372,0,7361,0,7349,0,7338,0,7327,0,7316,0,7305,0,7293,0,7282,0,7270,0,7259,0,7247,0,7235,0,7223,0,7211,0,7199,0,7187,0,7175,0,7163,0,7151,0,7139,0,7126,0,7114,0,7101,0,7089,0,7076,0,7064,0,7051,0,7038,0,7025,0,7012,0,6999,0,6986,0,6973,0,6960,0,6946,0,6933,0,6920,0,6906,0,6893,0,6879,0,6865,0,6852,0,6838,0,6824,0,6810,0,6796,0,6782,0,6768,0,6754,0,6739,0,6725,0,6711,0,6696,0,6682,0,6667,0,6653,0,6638,0,6623,0,6608,0,6594,0,6579,0,6564,0,6549,0,6533,0,6518,0,6503,0,6488,0,6472,0,6457,0,6441,0,6426,0,6410,0,6395,0,6379,0,6363,0,6347,0,6331,0,6315,0,6299,0,6283,0,6267,0,6251,0,6235,0,6218,0,6202,0,6185,0,6169,0,6152,0,6136,0,6119,0,6102,0,6085,0,6069,0,6052,0,6035,0,6018,0,6001,0,5984,0,5966,0,5949,0,5932,0,5914,0,5897,0,5880,0,5862,0,5844,0,5827,0,5809,0,5791,0,5774,0,5756,0,5738,0,5720,0,5702,0,5684,0,5666,0,5648,0,5629,0,5611,0,5593,0,5574,0,5556,0,5537,0,5519,0,5500,0,5482,0,5463,0,5444,0,5425,0,5406,0,5388,0,5369,0,5350,0,5331,0,5311,0,5292,0,5273,0,5254,0,5235,0,5215,0,5196,0,5176,0,5157,0,5137,0,5118,0,5098,0,5078,0,5059,0,5039,0,5019,0,4999,0,4979,0,4959,0,4939,0,4919,0,4899,0,4879,0,4859,0,4838,0,4818,0,4798,0,4777,0,4757,0,4736,0,4716,0,4695,0,4675,0,4654,0,4633,0,4613,0,4592,0,4571,0,4550,0,4529,0,4508,0,4487,0,4466,0,4445,0,4424,0,4403,0,4382,0,4360,0,4339,0,4318,0,4296,0,4275,0,4254,0,4232,0,4211,0,4189,0,4167,0,4146,0,4124,0,4102,0,4080,0,4059,0,4037,0,4015,0,3993,0,3971,0,3949,0,3927,0,3905,0,3883,0,3861,0,3839,0,3816,0,3794,0,3772,0,3749,0,3727,0,3705,0,3682,0,3660,0,3637,0,3615,0,3592,0,3570,0,3547,0,3524,0,3502,0,3479,0,3456,0,3433,0,3410,0,3388,0,3365,0,3342,0,3319,0,3296,0,3273,0,3250,0,3227,0,3204,0,3180,0,3157,0,3134,0,3111,0,3088,0,3064,0,3041,0,3018,0,2994,0,2971,0,2947,0,2924,0,2900,0,2877,0,2853,0,2830,0,2806,0,2783,0,2759,0,2735,0,2712,0,2688,0,2664,0,2640,0,2617,0,2593,0,2569,0,2545,0,2521,0,2497,0,2473,0,2449,0,2425,0,2401,0,2377,0,2353,0,2329,0,2305,0,2281,0,2257,0,2233,0,2208,0,2184,0,2160,0,2136,0,2111,0,2087,0,2063,0,2038,0,2014,0,1990,0,1965,0,1941,0,1917,0,1892,0,1868,0,1843,0,1819,0,1794,0,1770,0,1745,0,1721,0,1696,0,1671,0,1647,0,1622,0,1597,0,1573,0,1548,0,1523,0,1499,0,1474,0,1449,0,1425,0,1400,0,1375,0,1350,0,1326,0,1301,0,1276,0,1251,0,1226,0,1201,0,1177,0,1152,0,1127,0,1102,0,1077,0,1052,0,1027,0,1002,0,977,0,952,0,927,0,902,0,877,0,852,0,827,0,802,0,777,0,752,0,727,0,702,0,677,0,652,0,627,0,602,0,577,0,552,0,527,0,502,0,477,0,452,0,427,0,401,0,376,0,351,0,326,0,301,0,276,0,251,0,226,0,201,0,175,0,150,0,125,0,100,0,75,0,50,0,25,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);_wvoice=allocate(1,"%struct.voice_t*",ALLOC_STATIC);_f_log=allocate(1,"%struct.__sFILE*",ALLOC_STATIC);_option_waveout=allocate(1,"i32",ALLOC_STATIC);_option_log_frames=allocate(1,"i32",ALLOC_STATIC);_embedded_value=allocate(60,"i32",ALLOC_STATIC);_samplerate=allocate(1,"i32",ALLOC_STATIC);_samplerate_native=allocate(1,"i32",ALLOC_STATIC);__ZL5peaks=allocate(720,["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0],ALLOC_STATIC);_echo_head=allocate(1,"i32",ALLOC_STATIC);_echo_tail=allocate(1,"i32",ALLOC_STATIC);_echo_amp=allocate(1,"i32",ALLOC_STATIC);_echo_buf=allocate(11000,"i16",ALLOC_STATIC);__ZL7rbreath=allocate(360,"double",ALLOC_STATIC);_wdata=allocate(64,["i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZL13amplitude_env=allocate(1,"i8*",ALLOC_STATIC);_out_ptr=allocate(1,"i8*",ALLOC_STATIC);_out_start=allocate(1,"i8*",ALLOC_STATIC);_out_end=allocate(1,"i8*",ALLOC_STATIC);_outbuf_size=allocate(1,"i32",ALLOC_STATIC);_wcmdq=allocate(2560,"i32",ALLOC_STATIC);_wcmdq_head=allocate(1,"i32",ALLOC_STATIC);_wcmdq_tail=allocate(1,"i32",ALLOC_STATIC);_embedded_default=allocate([0,0,0,0,50,0,0,0,175,0,0,0,100,0,0,0,50,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,175,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);_current_source_index=allocate(1,"i32",ALLOC_STATIC);__ZL18sonicSpeedupStream=allocate(1,"%struct.sonicStreamStruct*",ALLOC_STATIC);_sonicSpeed=allocate([1],["double",0,0,0,0,0,0,0,0],ALLOC_STATIC);_pitch_adjust_tab=allocate([64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,86,87,88,89,91,92,93,94,96,97,98,100,101,103,104,105,107,108,110,111,113,115,116,118,119,121,123,124,126,128,130,132,133,135,137,139,141,143,145,147,149,151,153,155,158,160,162,164,167,169,171,174,176,179,181,184,186,189,191,194,197,199,202,205,208,211,214,217,220,223,226,229,232,236,239,242,246,249,252,254,255],"i8",ALLOC_STATIC);_pk_shape1=allocate([255,254,254,254,254,254,253,253,252,251,251,250,249,248,247,246,245,244,242,241,239,238,236,234,233,231,229,227,225,223,220,218,216,213,211,209,207,205,203,201,199,197,195,193,191,189,187,185,183,180,178,176,173,171,169,166,164,161,159,156,154,151,148,146,143,140,138,135,132,129,126,123,120,118,115,112,108,105,102,99,96,95,93,91,90,88,86,85,83,82,80,79,77,76,74,73,72,70,69,68,67,66,64,63,62,61,60,59,58,57,56,55,55,54,53,52,52,51,50,50,49,48,48,47,47,46,46,46,45,45,45,44,44,44,44,44,44,44,43,43,43,43,44,43,42,42,41,40,40,39,38,38,37,36,36,35,35,34,33,33,32,32,31,30,30,29,29,28,28,27,26,26,25,25,24,24,23,23,22,22,21,21,20,20,19,19,18,18,18,17,17,16,16,15,15,15,14,14,13,13,13,12,12,11,11,11,10,10,10,9,9,9,8,8,8,7,7,7,7,6,6,6,5,5,5,5,4,4,4,4,4,3,3,3,3,2,2,2,2,2,2,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0],"i8",ALLOC_STATIC);__ZL16PHASE_INC_FACTOR=allocate(1,"i32",ALLOC_STATIC);__ZL11Flutter_inc=allocate(1,"i32",ALLOC_STATIC);__ZL11samplecount=allocate(1,"i32",ALLOC_STATIC);__ZL8nsamples=allocate(1,"i32",ALLOC_STATIC);__ZL9wavephase=allocate(1,"i32",ALLOC_STATIC);__ZL12wavemult_max=allocate(1,"i32",ALLOC_STATIC);__ZL15wavemult_offset=allocate(1,"i32",ALLOC_STATIC);__ZL8wavemult=allocate([0,0,0,2,3,5,8,11,14,18,22,27,32,37,43,49,55,62,69,76,83,90,98,105,113,121,128,136,144,152,159,166,174,181,188,194,201,207,213,218,224,228,233,237,240,244,246,249,251,252,253,253,253,253,252,251,249,246,244,240,237,233,228,224,218,213,207,201,194,188,181,174,166,159,152,144,136,128,121,113,105,98,90,83,76,69,62,55,49,43,37,32,27,22,18,14,11,8,5,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"i8",ALLOC_STATIC);__ZL9pk_shape2=allocate([255,254,254,254,254,254,254,254,254,254,253,253,253,253,252,252,252,251,251,251,250,250,249,249,248,248,247,247,246,245,245,244,243,243,242,241,239,237,235,233,231,229,227,225,223,221,218,216,213,211,208,205,203,200,197,194,191,187,184,181,178,174,171,167,163,160,156,152,148,144,140,136,132,127,123,119,114,110,105,100,96,94,91,88,86,83,81,78,76,74,71,69,66,64,62,60,57,55,53,51,49,47,44,42,40,38,36,34,32,30,29,27,25,23,21,19,18,16,14,12,11,9,7,6,4,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"i8",ALLOC_STATIC);__ZL8pk_shape=allocate(1,"i8*",ALLOC_STATIC);__ZZ12GetAmplitudevE12amp_emphasis=allocate([16,16,10,16,22],"i8",ALLOC_STATIC);__ZL17general_amplitude=allocate([60],["i32",0,0,0,0],ALLOC_STATIC);__ZL11peak_height=allocate(36,"i32",ALLOC_STATIC);__ZL13peak_harmonic=allocate(36,"i32",ALLOC_STATIC);__ZL16option_harmonic1_b=allocate(1,"i1",ALLOC_STATIC);__ZL9harmspect=allocate(1,"i32*",ALLOC_STATIC);__ZL8harm_inc=allocate(120,"i32",ALLOC_STATIC);__ZL10minus_pi_t=allocate(1,"double",ALLOC_STATIC);__ZL8two_pi_t=allocate(1,"double",ALLOC_STATIC);__ZZ7WavegenvE4maxh=allocate(1,"i32",ALLOC_STATIC);__ZZ7WavegenvE5maxh2=allocate(1,"i32",ALLOC_STATIC);__ZZ7WavegenvE3agc=allocate([256],["i32",0,0,0,0],ALLOC_STATIC);__ZZ7WavegenvE13h_switch_sign=allocate(1,"i32",ALLOC_STATIC);__ZZ7WavegenvE11cycle_count=allocate(1,"i32",ALLOC_STATIC);__ZZ7WavegenvE10amplitude2=allocate(1,"i32",ALLOC_STATIC);__ZL8end_wave_b=allocate(1,"i1",ALLOC_STATIC);__ZL7hswitch=allocate(1,"i32",ALLOC_STATIC);__ZL6hspect=allocate(3200,"i32",ALLOC_STATIC);__ZL8phaseinc=allocate(1,"i32",ALLOC_STATIC);__ZL13cycle_samples=allocate(1,"i32",ALLOC_STATIC);__ZL9hf_factor=allocate(1,"i32",ALLOC_STATIC);__ZL6cbytes=allocate(1,"i32",ALLOC_STATIC);__ZL12glottal_flag=allocate(1,"i32",ALLOC_STATIC);__ZL14glottal_reduce=allocate(1,"i32",ALLOC_STATIC);__ZL6amp_ix=allocate(1,"i32",ALLOC_STATIC);__ZL15modulation_type=allocate(1,"i32",ALLOC_STATIC);__ZL14modulation_tab=allocate([0,0,0,0,0,70,242,41,0,47,0,47,0,69,242,41,0,47,0,46,0,69,242,40,0,46,0,45,0,52,242,40,0,45,45,44,0,52,242,40,0,43,43,43,0,52,242,40,0,42,42,42,0,52,242,40,0,41,41,41,0,52,242,40],"i8",ALLOC_STATIC);__ZL7voicing=allocate(1,"i32",ALLOC_STATIC);__ZL12embedded_max=allocate([0,0,0,0,32767,0,0,0,750,0,0,0,300,0,0,0,99,0,0,0,99,0,0,0,99,0,0,0,0,0,0,0,750,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ15WavegenSetVoiceP7voice_tE2v2=allocate(1344,["i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8"],ALLOC_STATIC);__ZL13consonant_amp=allocate([26],["i32",0,0,0,0],ALLOC_STATIC);__ZL11flutter_amp=allocate([64],["i32",0,0,0,0],ALLOC_STATIC);__ZZ8SetSynthiiP7frame_tS0_P7voice_tE19glottal_reduce_tab1=allocate([48,0,0,0,48,0,0,0,64,0,0,0,80,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ8SetSynthiiP7frame_tS0_P7voice_tE19glottal_reduce_tab2=allocate([144,0,0,0,160,0,0,0,176,0,0,0,192,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZL17samplecount_start=allocate(1,"i32",ALLOC_STATIC);__ZZ12WavegenFill2iE6resume=allocate(1,"i32",ALLOC_STATIC);__ZZ12WavegenFill2iE13echo_complete=allocate(1,"i32",ALLOC_STATIC);__ZL11echo_length=allocate(1,"i32",ALLOC_STATIC);__ZL7amp_inc=allocate(1,"i32",ALLOC_STATIC);__ZZL8PlayWaveiiPhiiE9n_samples=allocate(1,"i32",ALLOC_STATIC);__ZZL8PlayWaveiiPhiiE2ix=allocate(1,"i32",ALLOC_STATIC);__ZZL11PlaySilenceiiE9n_samples=allocate(1,"i32",ALLOC_STATIC);__ZZL17AdvanceParametersvE10Flutter_ix=allocate(1,"i32",ALLOC_STATIC);__ZL11Flutter_tab=allocate([128,155,181,203,220,232,237,236,230,220,206,191,176,163,152,144,140,139,140,143,146,148,149,146,140,131,120,105,89,73,60,49,42,41,45,54,68,86,105,125,143,159,170,177,178,173,164,150,135,120,105,92,83,79,79,85,94,107,122,136,150,162,171,176,177,174,168,160,152,145,139,136,137,141,148,157,168,178,187,192,193,189,180,165,146,124,99,74,50,30,14,5,2,5,15,30,48,68,89,109,127,140,150,156,159,159,157,155,153,153,156,161,169,179,191,202,213,220,224,222,216,204,187,166,143,119,96,75,58,46,40,41,47,58,72,89,106,122,134,144,148,149,145,137,128,117,107,98,92,90,92,97,105,116,128,138,148,154,158,157,152,144,134,124,113,104,98,96,99,107,120,136,155,175,194,210,223,230,231,226,215,198,178,156,132,111,91,75,64,57,55,56,61,67,74,80,84,86,85,82,77,72,66,63,62,65,73,86,103,124,147,171,195,217,234,246,252,251,244,231,213,192,170,148,128,113,100,93,90,92,97,104,112,119,125,127,127,123,116,107,97,87,78,72,70,72,78,89,102,117,132,147,159,167,171,170,164,153,139,123,106,91,78,70,67,69,77,90,107,127,146,166,184,197,207,211,210,205,196,185,173,161,150,142,137,135,135,138,141,145,146,145,140,132,120,104,85,65,46,28,14,5,1,5,15,31,52,77,104,129,154,176,193,205,211,211,208,200,191,181,171,164,159,156,157,160,165,170,174,177,176,171,163,150,135,118,99,81,66,54,47,45,49,58,72,89,107,126,142,156,166,170,169,163,152,138,123,108,93,82,74,72,74,80,90,103,117,130],"i8",ALLOC_STATIC);_pause_phonemes=allocate([0,23,10,9,24,19,24,24],"i8",ALLOC_STATIC);__ZZ15MakePhonemeListP10TranslatoriiE12types_double=allocate([6,7,8,3,0],"i8",ALLOC_STATIC);__ZL8kt_frame=allocate(288,"i32",ALLOC_STATIC);__ZL10kt_globals=allocate(2748,["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"i16*",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0],ALLOC_STATIC);__ZL5peaks801=allocate(720,["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0],ALLOC_STATIC);__ZL12sample_count=allocate(1,"i32",ALLOC_STATIC);__ZL8nsamples802=allocate(1,"i32",ALLOC_STATIC);__ZL6klattp=allocate(40,"i32",ALLOC_STATIC);__ZL10klattp_inc=allocate(80,"double",ALLOC_STATIC);__ZL7klattp1=allocate(80,"double",ALLOC_STATIC);__ZL8end_wave803=allocate(1,"i32",ALLOC_STATIC);__ZZ14SetSynth_KlattiiP7frame_tS0_P7voice_tiE7prev_fr=allocate(64,["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8","i8"],ALLOC_STATIC);__ZL13scale_wav_tab=allocate([45,0,0,0,38,0,0,0,45,0,0,0,45,0,0,0],["i32",0,0,0,"i32",0,0,0,"i32",0,0,0,"i32",0,0,0],ALLOC_STATIC);__ZZ9KlattInitvE15natural_samples=allocate([-310,0,-400,0,530,0,356,0,224,0,89,0,23,0,-10,0,-58,0,-16,0,461,0,599,0,536,0,701,0,770,0,605,0,497,0,461,0,560,0,404,0,110,0,224,0,131,0,104,0,-97,0,155,0,278,0,-154,0,-1165,0,-598,0,737,0,125,0,-592,0,41,0,11,0,-247,0,-10,0,65,0,92,0,80,0,-304,0,71,0,167,0,-1,0,122,0,233,0,161,0,-43,0,278,0,479,0,485,0,407,0,266,0,650,0,134,0,80,0,236,0,68,0,260,0,269,0,179,0,53,0,140,0,275,0,293,0,296,0,104,0,257,0,152,0,311,0,182,0,263,0,245,0,125,0,314,0,140,0,44,0,203,0,230,0,-235,0,-286,0,23,0,107,0,92,0,-91,0,38,0,464,0,443,0,176,0,98,0,-784,0,-2449,0,-1891,0,-1045,0,-1600,0,-1462,0,-1384,0,-1261,0,-949,0,-730,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ9KlattInitvE10formant_hz=allocate([280,0,688,0,1064,0,2806,0,3260,0,3700,0,6500,0,7000,0,8000,0,280,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ9KlattInitvE9bandwidth=allocate([89,0,160,0,70,0,160,0,200,0,200,0,500,0,500,0,500,0,89,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ9KlattInitvE12parallel_amp=allocate([0,0,59,0,59,0,59,0,59,0,59,0,59,0,0,0,0,0,0,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZ9KlattInitvE11parallel_bw=allocate([59,0,59,0,89,0,149,0,200,0,200,0,500,0,0,0,0,0,0,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZL7parwaveP13klatt_frame_tE5noise=allocate(1,"double",ALLOC_STATIC);__ZZL7parwaveP13klatt_frame_tE5voice=allocate(1,"double",ALLOC_STATIC);__ZZL7parwaveP13klatt_frame_tE5vlast=allocate(1,"double",ALLOC_STATIC);__ZZL7parwaveP13klatt_frame_tE8glotlast=allocate(1,"double",ALLOC_STATIC);__ZZL7parwaveP13klatt_frame_tE5sourc=allocate(1,"double",ALLOC_STATIC);__ZZL21pitch_synch_par_resetP13klatt_frame_tE4skew=allocate(1,"i32",ALLOC_STATIC);__ZZL21pitch_synch_par_resetP13klatt_frame_tE2B0=allocate([1200,0,1142,0,1088,0,1038,0,991,0,948,0,907,0,869,0,833,0,799,0,768,0,738,0,710,0,683,0,658,0,634,0,612,0,590,0,570,0,551,0,533,0,515,0,499,0,483,0,468,0,454,0,440,0,427,0,415,0,403,0,391,0,380,0,370,0,360,0,350,0,341,0,332,0,323,0,315,0,307,0,300,0,292,0,285,0,278,0,272,0,265,0,259,0,253,0,247,0,242,0,237,0,231,0,226,0,221,0,217,0,212,0,208,0,204,0,199,0,195,0,192,0,188,0,184,0,180,0,177,0,174,0,170,0,167,0,164,0,161,0,158,0,155,0,153,0,150,0,147,0,145,0,142,0,140,0,137,0,135,0,133,0,131,0,128,0,126,0,124,0,122,0,120,0,119,0,117,0,115,0,113,0,111,0,110,0,108,0,106,0,105,0,103,0,102,0,100,0,99,0,97,0,96,0,95,0,93,0,92,0,91,0,90,0,88,0,87,0,86,0,85,0,84,0,83,0,82,0,80,0,79,0,78,0,77,0,76,0,75,0,75,0,74,0,73,0,72,0,71,0,70,0,69,0,68,0,68,0,67,0,66,0,65,0,64,0,64,0,63,0,62,0,61,0,61,0,60,0,59,0,59,0,58,0,57,0,57,0,56,0,56,0,55,0,55,0,54,0,54,0,53,0,53,0,52,0,52,0,51,0,51,0,50,0,50,0,49,0,49,0,48,0,48,0,47,0,47,0,46,0,46,0,45,0,45,0,44,0,44,0,43,0,43,0,42,0,42,0,41,0,41,0,41,0,41,0,40,0,40,0,39,0,39,0,38,0,38,0,38,0,38,0,37,0,37,0,36,0,36,0,36,0,36,0,35,0,35,0,35,0,35,0,34,0,34,0,33,0,33,0,33,0,33,0,32,0,32,0,32,0,32,0,31,0,31,0,31,0,31,0,30,0,30,0,30,0,30,0,29,0,29,0,29,0,29,0,28,0,28,0,28,0,28,0,27,0,27,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZL7DBtoLINlE8amptable=allocate([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,6,0,7,0,8,0,9,0,10,0,11,0,13,0,14,0,16,0,18,0,20,0,22,0,25,0,28,0,32,0,35,0,40,0,45,0,51,0,57,0,64,0,71,0,80,0,90,0,101,0,114,0,128,0,142,0,159,0,179,0,202,0,227,0,256,0,284,0,318,0,359,0,405,0,455,0,512,0,568,0,638,0,719,0,881,0,911,0,1024,0,1137,0,1276,0,1438,0,1622,0,1823,0,2048,0,2273,0,2552,0,2875,0,3244,0,3645,0,4096,0,4547,0,5104,0,5751,0,6488,0,7291,0,8192,0,9093,0,10207,0,11502,0,12976,0,14582,0,16384,0,18350,0,20644,0,23429,0,26214,0,29491,0,32767,0],["i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0,"i16",0],ALLOC_STATIC);__ZZL14natural_sourcevE5vwave=allocate(1,"double",ALLOC_STATIC);__ZZL16impulsive_sourcevE7doublet=allocate([0,0,0,0,0,0,0,0,13000000,0,0,0,0,0,0,0,-13000000,0,0,0,0,0,0,0],["double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0],ALLOC_STATIC);__ZZL16impulsive_sourcevE5vwave=allocate(1,"double",ALLOC_STATIC);__ZZL9gen_noisedE5nlast=allocate(1,"double",ALLOC_STATIC);__ZZL7flutterP13klatt_frame_tE10time_count=allocate(1,"i32",ALLOC_STATIC);__ZZL10frame_initP13klatt_frame_tE14amp_par_factor=allocate([0.6,0,0,0,0,0,0,0,0.4,0,0,0,0,0,0,0,0.15,0,0,0,0,0,0,0,0.06,0,0,0,0,0,0,0,0.04,0,0,0,0,0,0,0,0.022,0,0,0,0,0,0,0,0.03,0,0,0,0,0,0,0],["double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0,"double",0,0,0,0,0,0,0],ALLOC_STATIC);__str810=allocate([47,116,109,112,47,115,111,110,105,99,46,108,111,103,0],"i8",ALLOC_STATIC);__str1811=allocate([97,0],"i8",ALLOC_STATIC);_optarg=allocate(1,"i8*",ALLOC_STATIC);_optind=allocate(1,"i32",ALLOC_STATIC);_opterr=allocate([1],["i32",0,0,0,0],ALLOC_STATIC);_optopt=allocate([63],["i32",0,0,0,0],ALLOC_STATIC);__ZL8optwhere=allocate(1,"i32",ALLOC_STATIC);__str831=allocate([45,45,0],"i8",ALLOC_STATIC);__str1832=allocate([80,79,83,73,88,76,89,95,67,79,82,82,69,67,84,0],"i8",ALLOC_STATIC);__str2833=allocate([37,115,58,32,111,112,116,105,111,110,32,96,37,115,39,32,105,115,32,97,109,98,105,103,117,111,117,115,32,40,99,111,117,108,100,32,98,101,32,96,45,45,37,115,39,32,111,114,32,96,45,45,37,115,39,41,10,0],"i8",ALLOC_STATIC);__str3834=allocate([37,115,58,32,105,110,118,97,108,105,100,32,111,112,116,105,111,110,32,45,45,32,96,45,37,99,39,10,0],"i8",ALLOC_STATIC);__str4835=allocate([37,115,58,32,97,114,103,117,109,101,110,116,32,114,101,113,117,105,114,101,100,32,102,111,114,32,111,112,116,105,111,110,32,96,0],"i8",ALLOC_STATIC);__str5836=allocate([45,45,37,115,39,10,0],"i8",ALLOC_STATIC);__str6837=allocate([45,37,99,39,10,0],"i8",ALLOC_STATIC);HEAP32[((__ZZ4mainE12long_options)>>2)]=((__str6)&4294967295);HEAP32[((__ZZ4mainE12long_options+16)>>2)]=((__str7)&4294967295);HEAP32[((__ZZ4mainE12long_options+32)>>2)]=((__str8)&4294967295);HEAP32[((__ZZ4mainE12long_options+48)>>2)]=((__str9)&4294967295);HEAP32[((__ZZ4mainE12long_options+64)>>2)]=((__str10)&4294967295);HEAP32[((__ZZ4mainE12long_options+80)>>2)]=((__str11)&4294967295);HEAP32[((__ZZ4mainE12long_options+96)>>2)]=((__str12)&4294967295);HEAP32[((__ZZ4mainE12long_options+112)>>2)]=((__str13)&4294967295);HEAP32[((__ZZ4mainE12long_options+128)>>2)]=((__str14)&4294967295);HEAP32[((__ZZ4mainE12long_options+144)>>2)]=((__str15)&4294967295);HEAP32[((__ZZ4mainE12long_options+160)>>2)]=((__str16)&4294967295);HEAP32[((__ZZ4mainE12long_options+176)>>2)]=((__str17)&4294967295);HEAP32[((_mnem_rules)>>2)]=((__str42)&4294967295);HEAP32[((_mnem_rules+8)>>2)]=((__str143)&4294967295);HEAP32[((_mnem_rules+16)>>2)]=((__str244)&4294967295);HEAP32[((_mnem_rules+24)>>2)]=((__str345)&4294967295);HEAP32[((_mnem_rules+32)>>2)]=((__str446)&4294967295);HEAP32[((_mnem_rules+40)>>2)]=((__str547)&4294967295);HEAP32[((_mnem_rules+48)>>2)]=((__str648)&4294967295);HEAP32[((_mnem_flags)>>2)]=((__str749)&4294967295);HEAP32[((_mnem_flags+8)>>2)]=((__str850)&4294967295);HEAP32[((_mnem_flags+16)>>2)]=((__str951)&4294967295);HEAP32[((_mnem_flags+24)>>2)]=((__str1052)&4294967295);HEAP32[((_mnem_flags+32)>>2)]=((__str1153)&4294967295);HEAP32[((_mnem_flags+40)>>2)]=((__str1254)&4294967295);HEAP32[((_mnem_flags+48)>>2)]=((__str1355)&4294967295);HEAP32[((_mnem_flags+56)>>2)]=((__str1456)&4294967295);HEAP32[((_mnem_flags+64)>>2)]=((__str1557)&4294967295);HEAP32[((_mnem_flags+72)>>2)]=((__str1658)&4294967295);HEAP32[((_mnem_flags+80)>>2)]=((__str1759)&4294967295);HEAP32[((_mnem_flags+88)>>2)]=((__str1860)&4294967295);HEAP32[((_mnem_flags+96)>>2)]=((__str1961)&4294967295);HEAP32[((_mnem_flags+104)>>2)]=((__str2062)&4294967295);HEAP32[((_mnem_flags+112)>>2)]=((__str2163)&4294967295);HEAP32[((_mnem_flags+120)>>2)]=((__str2264)&4294967295);HEAP32[((_mnem_flags+128)>>2)]=((__str2365)&4294967295);HEAP32[((_mnem_flags+136)>>2)]=((__str2466)&4294967295);HEAP32[((_mnem_flags+144)>>2)]=((__str2567)&4294967295);HEAP32[((_mnem_flags+152)>>2)]=((__str2668)&4294967295);HEAP32[((_mnem_flags+160)>>2)]=((__str2769)&4294967295);HEAP32[((_mnem_flags+168)>>2)]=((__str2870)&4294967295);HEAP32[((_mnem_flags+176)>>2)]=((__str2971)&4294967295);HEAP32[((_mnem_flags+184)>>2)]=((__str3072)&4294967295);HEAP32[((_mnem_flags+192)>>2)]=((__str3173)&4294967295);HEAP32[((_mnem_flags+200)>>2)]=((__str3274)&4294967295);HEAP32[((_mnem_flags+208)>>2)]=((__str3375)&4294967295);HEAP32[((_mnem_flags+216)>>2)]=((__str3476)&4294967295);HEAP32[((_mnem_flags+224)>>2)]=((__str3577)&4294967295);HEAP32[((_mnem_flags+232)>>2)]=((__str3678)&4294967295);HEAP32[((_mnem_flags+240)>>2)]=((__str3779)&4294967295);HEAP32[((_mnem_flags+248)>>2)]=((__str3880)&4294967295);HEAP32[((_mnem_flags+256)>>2)]=((__str3981)&4294967295);HEAP32[((_mnem_flags+264)>>2)]=((__str4082)&4294967295);HEAP32[((_mnem_flags+272)>>2)]=((__str4183)&4294967295);HEAP32[((_mnem_flags+280)>>2)]=((__str4284)&4294967295);HEAP32[((_mnem_flags+288)>>2)]=((__str43)&4294967295);HEAP32[((_mnem_flags+296)>>2)]=((__str44)&4294967295);HEAP32[((_mnem_flags+304)>>2)]=((__str45)&4294967295);HEAP32[((_mnem_flags+312)>>2)]=((__str46)&4294967295);HEAP32[((_mnem_flags+320)>>2)]=((__str47)&4294967295);HEAP32[((_mnem_flags+328)>>2)]=((__str48)&4294967295);HEAP32[((_mnem_flags+336)>>2)]=((__str49)&4294967295);HEAP32[((_mnem_flags+344)>>2)]=((__str50)&4294967295);HEAP32[((_mnem_flags+352)>>2)]=((__str51)&4294967295);HEAP32[((_mnem_flags+360)>>2)]=((__str52)&4294967295);HEAP32[((_mnem_flags+368)>>2)]=((__str53)&4294967295);HEAP32[((_mnem_flags+376)>>2)]=((__str54)&4294967295);HEAP32[((_mnem_flags+384)>>2)]=((__str55)&4294967295);HEAP32[((_mnem_flags+392)>>2)]=((__str56)&4294967295);HEAP32[((_mnem_flags+400)>>2)]=((__str57)&4294967295);HEAP32[((__ZZL16copy_rule_stringPcRiE6outbuf)>>2)]=((__ZL9rule_cond)&4294967295);HEAP32[((__ZZL16copy_rule_stringPcRiE6outbuf+4)>>2)]=((__ZL8rule_pre)&4294967295);HEAP32[((__ZZL16copy_rule_stringPcRiE6outbuf+8)>>2)]=((__ZL10rule_match)&4294967295);HEAP32[((__ZZL16copy_rule_stringPcRiE6outbuf+12)>>2)]=((__ZL9rule_post)&4294967295);HEAP32[((__ZZL16copy_rule_stringPcRiE6outbuf+16)>>2)]=((__ZL13rule_phonemes)&4294967295);HEAP32[((__ZZ12RemoveEndingP10TranslatorPciS1_E16add_e_exceptions)>>2)]=((__str17133)&4294967295);HEAP32[((__ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions)>>2)]=((__str18134)&4294967295);HEAP32[((__ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions+4)>>2)]=((__str19135)&4294967295);HEAP32[((__ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions+8)>>2)]=((__str20136)&4294967295);HEAP32[((__ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions+12)>>2)]=((__str21137)&4294967295);HEAP32[((__ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions+16)>>2)]=((__str22138)&4294967295);HEAP32[((__ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions+20)>>2)]=((__str23139)&4294967295);HEAP32[((__ZZ12RemoveEndingP10TranslatorPciS1_E15add_e_additions+24)>>2)]=((__str24140)&4294967295);HEAP32[((_envelope_data)>>2)]=((_env_fall)&4294967295);HEAP32[((_envelope_data+4)>>2)]=((_env_fall)&4294967295);HEAP32[((_envelope_data+8)>>2)]=((_env_rise)&4294967295);HEAP32[((_envelope_data+12)>>2)]=((_env_rise)&4294967295);HEAP32[((_envelope_data+16)>>2)]=((_env_frise)&4294967295);HEAP32[((_envelope_data+20)>>2)]=((__ZL11env_r_frise)&4294967295);HEAP32[((_envelope_data+24)>>2)]=((__ZL10env_frise2)&4294967295);HEAP32[((_envelope_data+28)>>2)]=((__ZL12env_r_frise2)&4294967295);HEAP32[((_envelope_data+32)>>2)]=((__ZL12env_risefall)&4294967295);HEAP32[((_envelope_data+36)>>2)]=((__ZL12env_risefall)&4294967295);HEAP32[((_envelope_data+40)>>2)]=((__ZL13env_fallrise3)&4294967295);HEAP32[((_envelope_data+44)>>2)]=((__ZL13env_fallrise3)&4294967295);HEAP32[((_envelope_data+48)>>2)]=((__ZL13env_fallrise4)&4294967295);HEAP32[((_envelope_data+52)>>2)]=((__ZL13env_fallrise4)&4294967295);HEAP32[((_envelope_data+56)>>2)]=((__ZL9env_fall2)&4294967295);HEAP32[((_envelope_data+60)>>2)]=((__ZL9env_fall2)&4294967295);HEAP32[((_envelope_data+64)>>2)]=((__ZL9env_rise2)&4294967295);HEAP32[((_envelope_data+68)>>2)]=((__ZL9env_rise2)&4294967295);HEAP32[((_envelope_data+72)>>2)]=((__ZL16env_risefallrise)&4294967295);HEAP32[((_envelope_data+76)>>2)]=((__ZL16env_risefallrise)&4294967295);HEAP32[((__ZL15tone_head_table+4)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+12)>>2)]=((__ZL5oflow)&4294967295);HEAP32[((__ZL15tone_head_table+20)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+28)>>2)]=((__ZL5oflow)&4294967295);HEAP32[((__ZL15tone_head_table+36)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+44)>>2)]=((__ZL5oflow)&4294967295);HEAP32[((__ZL15tone_head_table+52)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+60)>>2)]=((__ZL9oflow_emf)&4294967295);HEAP32[((__ZL15tone_head_table+68)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+76)>>2)]=((__ZL5oflow)&4294967295);HEAP32[((__ZL15tone_head_table+84)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+92)>>2)]=((__ZL10oflow_less)&4294967295);HEAP32[((__ZL15tone_head_table+100)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+108)>>2)]=((__ZL10oflow_less)&4294967295);HEAP32[((__ZL15tone_head_table+116)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+124)>>2)]=((__ZL10oflow_less)&4294967295);HEAP32[((__ZL15tone_head_table+132)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+140)>>2)]=((__ZL5oflow)&4294967295);HEAP32[((__ZL15tone_head_table+148)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+156)>>2)]=((__ZL5oflow)&4294967295);HEAP32[((__ZL15tone_head_table+164)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+172)>>2)]=((__ZL5oflow)&4294967295);HEAP32[((__ZL15tone_head_table+180)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+188)>>2)]=((__ZL10oflow_less)&4294967295);HEAP32[((__ZL15tone_head_table+196)>>2)]=((__ZL7drops_0)&4294967295);HEAP32[((__ZL15tone_head_table+204)>>2)]=((__ZL10oflow_less)&4294967295);HEAP32[((__ZL8ssmltags)>>2)]=((__str167)&4294967295);HEAP32[((__ZL8ssmltags+8)>>2)]=((__str1168)&4294967295);HEAP32[((__ZL8ssmltags+16)>>2)]=((__str2169)&4294967295);HEAP32[((__ZL8ssmltags+24)>>2)]=((__str3170)&4294967295);HEAP32[((__ZL8ssmltags+32)>>2)]=((__str4171)&4294967295);HEAP32[((__ZL8ssmltags+40)>>2)]=((__str5172)&4294967295);HEAP32[((__ZL8ssmltags+48)>>2)]=((__str6173)&4294967295);HEAP32[((__ZL8ssmltags+56)>>2)]=((__str7174)&4294967295);HEAP32[((__ZL8ssmltags+64)>>2)]=((__str8175)&4294967295);HEAP32[((__ZL8ssmltags+72)>>2)]=((__str9176)&4294967295);HEAP32[((__ZL8ssmltags+80)>>2)]=((__str10177)&4294967295);HEAP32[((__ZL8ssmltags+88)>>2)]=((__str11178)&4294967295);HEAP32[((__ZL8ssmltags+96)>>2)]=((__str12179)&4294967295);HEAP32[((__ZL8ssmltags+104)>>2)]=((__str13180)&4294967295);HEAP32[((__ZL8ssmltags+112)>>2)]=((__str14181)&4294967295);HEAP32[((__ZL8ssmltags+120)>>2)]=((__str15182)&4294967295);HEAP32[((__ZL8ssmltags+128)>>2)]=((__str16183)&4294967295);HEAP32[((__ZL8ssmltags+136)>>2)]=((__str17184)&4294967295);HEAP32[((__ZL8ssmltags+144)>>2)]=((__str18185)&4294967295);HEAP32[((__ZL8ssmltags+152)>>2)]=((__str19186)&4294967295);HEAP32[((__ZL8ssmltags+160)>>2)]=((__str20187)&4294967295);HEAP32[((__ZL8ssmltags+168)>>2)]=((__str21188)&4294967295);HEAP32[((__ZL8ssmltags+176)>>2)]=((__str22189)&4294967295);HEAP32[((__ZL8ssmltags+184)>>2)]=((__str23190)&4294967295);HEAP32[((__ZL8ssmltags+192)>>2)]=((__str24191)&4294967295);HEAP32[((__ZL8ssmltags+200)>>2)]=((__str25192)&4294967295);HEAP32[((__ZL8ssmltags+208)>>2)]=((__str26193)&4294967295);HEAP32[((__ZL8ssmltags+216)>>2)]=((__str27194)&4294967295);HEAP32[((__ZL8ssmltags+224)>>2)]=((__str28195)&4294967295);HEAP32[((__ZL8ssmltags+232)>>2)]=((__str29196)&4294967295);HEAP32[((__ZL8ssmltags+240)>>2)]=((__str30197)&4294967295);HEAP32[((__ZL8ssmltags+248)>>2)]=((__str31198)&4294967295);HEAP32[((__ZL18xml_char_mnemonics)>>2)]=((__str32199)&4294967295);HEAP32[((__ZL18xml_char_mnemonics+8)>>2)]=((__str33200)&4294967295);HEAP32[((__ZL18xml_char_mnemonics+16)>>2)]=((__str34201)&4294967295);HEAP32[((__ZL18xml_char_mnemonics+24)>>2)]=((__str35202)&4294967295);HEAP32[((__ZL18xml_char_mnemonics+32)>>2)]=((__str36203)&4294967295);HEAP32[((__ZL18xml_char_mnemonics+40)>>2)]=((__str37204)&4294967295);HEAP32[((__ZL7xmlbase)>>2)]=((__str13643)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_punct)>>2)]=((__str61228)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_punct+8)>>2)]=((__str62229)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_punct+16)>>2)]=((__str63230)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_capitals)>>2)]=((__str64231)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_capitals+8)>>2)]=((__str65232)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_capitals+16)>>2)]=((__str66233)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_capitals+24)>>2)]=((__str9659)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_interpret_as)>>2)]=((__str68235)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_interpret_as+8)>>2)]=((__str69236)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_interpret_as+16)>>2)]=((__str70237)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_interpret_as+24)>>2)]=((__str71238)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_interpret_as+32)>>2)]=((__str72239)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE17mnem_sayas_format)>>2)]=((__str73240)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_break)>>2)]=((__str61228)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_break+8)>>2)]=((__str74241)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_break+16)>>2)]=((__str75242)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_break+24)>>2)]=((__str76243)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_break+32)>>2)]=((__str29196)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE10mnem_break+40)>>2)]=((__str77244)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_emphasis)>>2)]=((__str61228)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_emphasis+8)>>2)]=((__str78245)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_emphasis+16)>>2)]=((__str79246)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE13mnem_emphasis+24)>>2)]=((__str29196)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE12prosody_attr+4)>>2)]=((__str80247)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE12prosody_attr+8)>>2)]=((__str81248)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE12prosody_attr+12)>>2)]=((__str9659)&4294967295);HEAP32[((__ZZL14ProcessSsmlTagPwPcRiiiE12prosody_attr+16)>>2)]=((__str82249)&4294967295);HEAP32[((__ZZL18GetVoiceAttributesPwiE11mnem_gender)>>2)]=((__str1647)&4294967295);HEAP32[((__ZZL18GetVoiceAttributesPwiE11mnem_gender+8)>>2)]=((__str2648)&4294967295);HEAP32[((__ZZL18GetVoiceAttributesPwiE11mnem_gender+16)>>2)]=((__str105272)&4294967295);HEAP32[((__ZZL14ReplaceKeyNamePciRiE8keynames)>>2)]=((__str111278)&4294967295);HEAP32[((__ZZL14ReplaceKeyNamePciRiE8keynames+8)>>2)]=((__str112279)&4294967295);HEAP32[((__ZZL14ReplaceKeyNamePciRiE8keynames+16)>>2)]=((__str113280)&4294967295);HEAP32[((__ZZL14ReplaceKeyNamePciRiE8keynames+24)>>2)]=((__str114281)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume)>>2)]=((__str45697)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume+8)>>2)]=((__str115282)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume+16)>>2)]=((__str116283)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume+24)>>2)]=((__str117)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume+32)>>2)]=((__str76243)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume+40)>>2)]=((__str118)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume+48)>>2)]=((__str119)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_rate)>>2)]=((__str45697)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_rate+8)>>2)]=((__str120)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_rate+16)>>2)]=((__str121)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_rate+24)>>2)]=((__str76243)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_rate+32)>>2)]=((__str122)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_rate+40)>>2)]=((__str123)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_pitch)>>2)]=((__str45697)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_pitch+8)>>2)]=((__str124)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_pitch+16)>>2)]=((__str125)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_pitch+24)>>2)]=((__str76243)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_pitch+32)>>2)]=((__str126)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_pitch+40)>>2)]=((__str127)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_range)>>2)]=((__str45697)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_range+8)>>2)]=((__str124)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_range+16)>>2)]=((__str125)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_range+24)>>2)]=((__str76243)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_range+32)>>2)]=((__str126)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_range+40)>>2)]=((__str127)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_tabs+4)>>2)]=((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_rate)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_tabs+8)>>2)]=((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE11mnem_volume)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_tabs+12)>>2)]=((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_pitch)&4294967295);HEAP32[((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE9mnem_tabs+16)>>2)]=((__ZZL19SetProsodyParameteriPwP11PARAM_STACKE10mnem_range)&4294967295);HEAP32[((__ZL11accents_tab)>>2)]=((__str57354)&4294967295);HEAP32[((__ZL11accents_tab+8)>>2)]=((__str58355)&4294967295);HEAP32[((__ZL11accents_tab+16)>>2)]=((__str59356)&4294967295);HEAP32[((__ZL11accents_tab+24)>>2)]=((__str60357)&4294967295);HEAP32[((__ZL11accents_tab+32)>>2)]=((__str61358)&4294967295);HEAP32[((__ZL11accents_tab+40)>>2)]=((__str62359)&4294967295);HEAP32[((__ZL11accents_tab+48)>>2)]=((__str63360)&4294967295);HEAP32[((__ZL11accents_tab+56)>>2)]=((__str64361)&4294967295);HEAP32[((__ZL11accents_tab+64)>>2)]=((__str65362)&4294967295);HEAP32[((__ZL11accents_tab+72)>>2)]=((__str66363)&4294967295);HEAP32[((__ZL11accents_tab+80)>>2)]=((__str67364)&4294967295);HEAP32[((__ZL11accents_tab+88)>>2)]=((__str68365)&4294967295);HEAP32[((__ZL11accents_tab+96)>>2)]=((__str69366)&4294967295);HEAP32[((__ZL11accents_tab+104)>>2)]=((__str70367)&4294967295);HEAP32[((__ZL11accents_tab+112)>>2)]=((__str71368)&4294967295);HEAP32[((__ZL11accents_tab+120)>>2)]=((__str72369)&4294967295);HEAP32[((__ZL11accents_tab+128)>>2)]=((__str73370)&4294967295);HEAP32[((__ZL11accents_tab+136)>>2)]=((__str74371)&4294967295);HEAP32[((__ZL11accents_tab+144)>>2)]=((__str75372)&4294967295);HEAP32[((__ZL11accents_tab+152)>>2)]=((__str76373)&4294967295);HEAP32[((__ZL11accents_tab+160)>>2)]=((__str77374)&4294967295);HEAP32[((__ZL11accents_tab+168)>>2)]=((__str78375)&4294967295);HEAP32[((_version_string)>>2)]=((__str399)&4294967295);HEAP32[((_charsets)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+4)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+8)>>2)]=((__ZL10ISO_8859_2)&4294967295);HEAP32[((_charsets+12)>>2)]=((__ZL10ISO_8859_3)&4294967295);HEAP32[((_charsets+16)>>2)]=((__ZL10ISO_8859_4)&4294967295);HEAP32[((_charsets+20)>>2)]=((__ZL10ISO_8859_5)&4294967295);HEAP32[((_charsets+24)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+28)>>2)]=((__ZL10ISO_8859_7)&4294967295);HEAP32[((_charsets+32)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+36)>>2)]=((__ZL10ISO_8859_9)&4294967295);HEAP32[((_charsets+40)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+44)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+48)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+52)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+56)>>2)]=((__ZL11ISO_8859_14)&4294967295);HEAP32[((_charsets+60)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+64)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+68)>>2)]=((__ZL10ISO_8859_1)&4294967295);HEAP32[((_charsets+72)>>2)]=((__ZL6KOI8_R)&4294967295);HEAP32[((_charsets+76)>>2)]=((__ZL5ISCII)&4294967295);HEAP32[((__ZL15length_mod_tabs)>>2)]=((__ZL14length_mods_en)&4294967295);HEAP32[((__ZL15length_mod_tabs+4)>>2)]=((__ZL14length_mods_en)&4294967295);HEAP32[((__ZL15length_mod_tabs+8)>>2)]=((__ZL15length_mods_en0)&4294967295);HEAP32[((__ZL15length_mod_tabs+12)>>2)]=((__ZL17length_mods_equal)&4294967295);HEAP32[((__ZL15length_mod_tabs+16)>>2)]=((__ZL17length_mods_equal)&4294967295);HEAP32[((__ZL15length_mod_tabs+20)>>2)]=((__ZL17length_mods_equal)&4294967295);HEAP32[((_genders)>>2)]=((__str646)&4294967295);HEAP32[((_genders+8)>>2)]=((__str1647)&4294967295);HEAP32[((_genders+16)>>2)]=((__str2648)&4294967295);HEAP32[((__ZL11options_tab)>>2)]=((__str3653)&4294967295);HEAP32[((__ZL11options_tab+8)>>2)]=((__str4654)&4294967295);HEAP32[((__ZL11keyword_tab)>>2)]=((__str5655)&4294967295);HEAP32[((__ZL11keyword_tab+8)>>2)]=((__str6656)&4294967295);HEAP32[((__ZL11keyword_tab+16)>>2)]=((__str7657)&4294967295);HEAP32[((__ZL11keyword_tab+24)>>2)]=((__str8658)&4294967295);HEAP32[((__ZL11keyword_tab+32)>>2)]=((__str9659)&4294967295);HEAP32[((__ZL11keyword_tab+40)>>2)]=((__str10660)&4294967295);HEAP32[((__ZL11keyword_tab+48)>>2)]=((__str11661)&4294967295);HEAP32[((__ZL11keyword_tab+56)>>2)]=((__str12662)&4294967295);HEAP32[((__ZL11keyword_tab+64)>>2)]=((__str13663)&4294967295);HEAP32[((__ZL11keyword_tab+72)>>2)]=((__str14664)&4294967295);HEAP32[((__ZL11keyword_tab+80)>>2)]=((__str15665)&4294967295);HEAP32[((__ZL11keyword_tab+88)>>2)]=((__str16666)&4294967295);HEAP32[((__ZL11keyword_tab+96)>>2)]=((__str17667)&4294967295);HEAP32[((__ZL11keyword_tab+104)>>2)]=((__str18668)&4294967295);HEAP32[((__ZL11keyword_tab+112)>>2)]=((__str19669)&4294967295);HEAP32[((__ZL11keyword_tab+120)>>2)]=((__str20670)&4294967295);HEAP32[((__ZL11keyword_tab+128)>>2)]=((__str21671)&4294967295);HEAP32[((__ZL11keyword_tab+136)>>2)]=((__str22672)&4294967295);HEAP32[((__ZL11keyword_tab+144)>>2)]=((__str23673)&4294967295);HEAP32[((__ZL11keyword_tab+152)>>2)]=((__str24674)&4294967295);HEAP32[((__ZL11keyword_tab+160)>>2)]=((__str25675)&4294967295);HEAP32[((__ZL11keyword_tab+168)>>2)]=((__str26676)&4294967295);HEAP32[((__ZL11keyword_tab+176)>>2)]=((__str27677)&4294967295);HEAP32[((__ZL11keyword_tab+184)>>2)]=((__str28678)&4294967295);HEAP32[((__ZL11keyword_tab+192)>>2)]=((__str29679)&4294967295);HEAP32[((__ZL11keyword_tab+200)>>2)]=((__str30680)&4294967295);HEAP32[((__ZL11keyword_tab+208)>>2)]=((__str31681)&4294967295);HEAP32[((__ZL11keyword_tab+216)>>2)]=((__str32682)&4294967295);HEAP32[((__ZL11keyword_tab+224)>>2)]=((__str33683)&4294967295);HEAP32[((__ZL11keyword_tab+232)>>2)]=((__str34684)&4294967295);HEAP32[((__ZL11keyword_tab+240)>>2)]=((__str35685)&4294967295);HEAP32[((__ZL11keyword_tab+248)>>2)]=((__str36686)&4294967295);HEAP32[((__ZL11keyword_tab+256)>>2)]=((__str37687)&4294967295);HEAP32[((__ZL11keyword_tab+264)>>2)]=((__str38688)&4294967295);HEAP32[((__ZL11keyword_tab+272)>>2)]=((__str39689)&4294967295);HEAP32[((__ZL11keyword_tab+280)>>2)]=((__str40690)&4294967295);HEAP32[((__ZL11keyword_tab+288)>>2)]=((__str41691)&4294967295);HEAP32[((__ZL11keyword_tab+296)>>2)]=((__str42692)&4294967295);HEAP32[((__ZL11keyword_tab+304)>>2)]=((__str43693)&4294967295);HEAP32[((_variant_lists)>>2)]=((__ZL15variants_either)&4294967295);HEAP32[((_variant_lists+4)>>2)]=((__ZL13variants_male)&4294967295);HEAP32[((_variant_lists+8)>>2)]=((__ZL15variants_female)&4294967295);HEAP32[((_voice)>>2)]=__ZL9voicedata;FS.init();__ATEXIT__.push({func:function(){FS.quit()}});___setErrNo(0);_fputc.ret=allocate([0],"i8",ALLOC_STATIC);___buildEnvironment(ENV);_fgetc.ret=allocate([0],"i8",ALLOC_STATIC);FUNCTION_TABLE=[0,0,__ZL13rgroup_sorterP6RGROUPS0_,0,__Z13string_sorterPPcS0_,0,__ZL15VoiceNameSorterPKvS0_,0,__ZL16VoiceScoreSorterPKvS0_,0];Module["FUNCTION_TABLE"]=FUNCTION_TABLE;__globalConstructor__();var ret=null;if(Module._main){ret=Module.callMain(args);__shutdownRuntime__();}
return ret;}
Module.run=run;if(!Module.noInitialRun){run();}
return{Module:Module,FS:FS,run:run};}
var eSpeakDir='/espeak',eSpeakDataDir='/espeak/espeak-data',eSpeakVoicesDir='/espeak/espeak-data/voices',eSpeak=new ESpeak(),fileRegistry=[],fsErrorDetected=false,configDataLoaded=false,unloading=false,speakQueue=[],voicesLoaded={},defaultVoice='',AudioAPI=null,canPlay=false,playbackVolume=1,masterGain=null,audioContext=null,audioPool={},webSoundPool={},isChrome=((typeof navigator!=='undefined')&&navigator.userAgent&&navigator.userAgent.indexOf('Chrome')!==-1),chromeVersion=(isChrome)?parseInt(navigator.userAgent.replace(/^.*?\bChrome\/([0-9]+).*$/,'$1'),10):0;function fsCreateDataFile(path,fname,data,doNotRegister){if(!eSpeak.FS.findObject(path))eSpeak.FS.createPath('/',path.substring(1),true,true);eSpeak.FS.createDataFile(path,fname,data,true,false);if(!doNotRegister)fileRegistry.push({path:path,fname:fname});}
function recoverFromFSError(message){console.log('meSpeak -- recovering from error:',message);var files=[],f,i,l=fileRegistry.length;for(i=0;i<l;i++){f=fileRegistry[i];files.push(eSpeak.FS.findObject(f.path+'/'+f.fname).contents);}
eSpeak=new ESpeak();setUpVFS();for(i=0;i<l;i++){f=fileRegistry[i];fsCreateDataFile(f.path,f.fname,files[i],true);}
fsErrorDetected=true;}
function setUpVFS(){var optionFiles={'croak':'language variant\nname croak\ngender male 70\npitch 85 117\nflutter 20\nformant 0 100 80 110\n','f1':'language variant\nname female1\ngender female 70\npitch 140 200\nflutter 8\nroughness 4\nformant 0 115 80 150\nformant 1 120 80 180\nformant 2 100 70 150 150\nformant 3 115 70 150\nformant 4 110 80 150\nformant 5 110 90 150\nformant 6 105 80 150\nformant 7 110 70 150\nformant 8 110 70 150\nstressAdd -10 -10 -20 -20 0 0 40 60\n','f2':'language variant\nname female2\ngender female\npitch 142 220\nroughness 3\nformant 0 105 80 150\nformant 1 110 80 160\nformant 2 110 70 150\nformant 3 110 70 150\nformant 4 115 80 150\nformant 5 115 80 150\nformant 6 110 70 150\nformant 7 110 70 150\nformant 8 110 70 150\nstressAdd 0 0 -10 -10 0 0 10 40\nbreath 0 2 3 3 3 3 3 2\necho 140 10\nconsonants 125 125\n','f3':'language variant\nname female3\ngender female\npitch 140 240\nformant 0 105 80 150\nformant 1 120 75 150 -50\nformant 2 135 70 150 -250\nformant 3 125 80 150\nformant 4 125 80 150\nformant 5 125 80 150\nformant 6 120 70 150\nformant 7 110 70 150\nformant 8 110 70 150\nstressAmp 18 18 20 20 20 20 20 20\n//breath 0 2 4 4 4 4 4 4\nbreath 0 2 3 3 3 3 3 2\necho 120 10\nroughness 4\n','f4':'language variant\nname female4\ngender female\necho 130 15\npitch 142 200\nformant 0 120 80 150\nformant 1 115 80 160 -20\nformant 2 130 75 150 -200\nformant 3 123 75 150\nformant 4 125 80 150\nformant 5 125 80 150\nformant 6 110 80 150\nformant 7 110 75 150\nformant 8 110 75 150\nstressAdd -20 -20 -20 -20 0 0 20 120\nstressAmp 18 16 20 20 20 20 20 20\n','f5':'language variant\nname female5\ngender female\npitch 160 228\nroughness 0\nformant 0 105 80 150\nformant 1 110 80 160\nformant 2 110 70 150\nformant 3 110 70 150\nformant 4 115 80 200\nformant 5 115 80 100\nformant 6 110 70 150\nformant 7 110 70 100\nformant 8 110 70 150\nstressAdd 0 0 -10 -10 0 0 10 40\nbreath 0 4 6   6 6   6 0 10\necho 140 10\nvoicing 75\nconsonants 150 150\nbreathw 150 150 200 200 400 400\n','klatt':'language variant\nname klatt\nklatt 1\n','klatt2':'language variant\nname klatt2\nklatt 2\n','klatt3':'language variant\nname klatt3\nklatt 3\n','m1':'language variant\nname male1\ngender male 70\npitch 75 109\nflutter 5\nroughness 4\nconsonants 80 100\nformant 0 98 100 100\nformant 1 97 100 100\nformant 2 97 95 100\nformant 3 97 95 100\nformant 4 97 85 100\nformant 5 105 80 100\nformant 6 95 80 100\nformant 7 100 100 100\nformant 8 100 100 100\n//stressAdd -10 -10 -20 -20 0 0 40 70\n','m2':'language variant\nname male2\ngender male\npitch 88 115\necho 130 15\nformant 0 100 80 120\nformant 1 90 85 120\nformant 2 110 85 120\nformant 3 105 90 120\nformant 4 100 90 120\nformant 5 100 90 120\nformant 6 100 90 120\nformant 7 100 90 120\nformant 8 100 90 120\n','m3':'language variant\nname male3\ngender male\npitch 80 122\nformant 0 100 100 100\nformant 1 96 97 100\nformant 2 96 97 100\nformant 3 96 103 100\nformant 4 95 103 100\nformant 5 95 103 100\nformant 6 100 100 100\nformant 7 100 100 100\nformant 8 100 100 100\nstressAdd 10 10 0 0 0 0 -30 -30\n','m4':'language variant\nname male4\ngender male\npitch 70 110\nformant 0 103 100 100\nformant 1 103 100 100\nformant 2 103 100 100\nformant 3 103 100 100\nformant 4 106 100 100\nformant 5 106 100 100\nformant 6 106 100 100\nformant 7 103 100 100\nformant 8 103 100 100\nstressAdd -10 -10 -30 -30 0 0 60 90\n','m5':'language variant\nname male5\ngender male\nformant 0 100 85 130\nformant 1 90 85 130 40\nformant 2 80 85 130 310\nformant 3 105 85 130\nformant 4 105 85 130\nformant 5 105 85 130\nformant 6 105 85 150\nformant 7 105 85 150\nformant 8 105 85 150\nintonation 2\n','m6':'language variant\nname male6\ngender male\npitch 82 117\nformant 0 100 90 120\nformant 1 100 90 140\nformant 2 100 70 140\nformant 3 100 75 140\nformant 4 100 80 140\nformant 5 100 80 140\n','m7':'language variant\nname male7\npitch 75 125\nformant 0 100 125 100\nformant 1 100 90 80\nformant 2 100 70 90\nformant 3 100 60 90\nformant 4 100 60 90\nformant 5 75 50 90\nformant 6 90 50 100\nformant 7 100 50 100\nformant 8 100 50 100\nvoicing 155\n','whisper':'language variant\nname whisper\npitch 75 125\nformant 0 100 125 100\nformant 1 100 90 80\nformant 2 100 70 90\nformant 3 100 60 90\nformant 4 100 60 90\nformant 5 75 50 90\nformant 6 90 50 100\nformant 7 100 50 100\nformant 8 100 50 100\nvoicing 155\n','whisperf':'language variant\nname female whisper\ngender female\npitch 160 220\nroughness 3\nformant 0 105 0 150\nformant 1 110 40 160\nformant 2 110 70 150\nformant 3 110 70 150\nformant 4 115 80 150\nformant 5 115 80 150\nformant 6 110 70 150\nformant 7 110 70 150\nformant 8 110 70 150\nstressAdd 0 0 -10 -10 0 0 10 40\n// whisper\nvoicing 20\nbreath 75 75 50 40 15 10\nbreathw 150 150 200 200 400 400\n'};var dir=eSpeakVoicesDir+'/!v';eSpeak.FS.createPath('/',dir.substring(1),true,true);eSpeak.FS.root.write=true;for(var fn in optionFiles){eSpeak.FS.createDataFile(dir,fn,decodeStringToArray(optionFiles[fn]),true,true);}}
if(eSpeak&&eSpeak.FS)setUpVFS();function setConfigData(data){[['config',decodeBase64ToArray(data.config)],['phontab',decodeBase64ToArray(data.phontab)],['phonindex',decodeBase64ToArray(data.phonindex)],['phondata',decodeBase64ToArray(data.phondata)],['intonations',decodeBase64ToArray(data.intonations)]].forEach(function(pair){var id=pair[0];var data=pair[1];fsCreateDataFile(eSpeakDataDir,id,data);});configDataLoaded=true;var voice=data.voice;if(typeof voice=='object'&&typeof voice.voice_id=='string'&&typeof voice.dict_id=='string'&&typeof voice.dict=='string'&&typeof voice.voice=='string'){setVoiceData(voice);}
executeQueuedCalls();}
function setVoiceData(data){var parts,path,fname,f;if(!voicesLoaded[data.voice_id]){if(data.dict_id&&!eSpeak.FS.findObject(eSpeakDataDir+'/'+data.dict_id))fsCreateDataFile(eSpeakDataDir,data.dict_id,decodeBase64ToArray(data.dict));parts=data.voice_id.split('/');path=eSpeakVoicesDir;if(parts.length>1){path+='/'+parts.slice(0,parts.length-1).join('/');}
fname=parts[parts.length-1];if(data.voice_encoding=='text'){fsCreateDataFile(path,fname,decodeStringToArray(data.voice));}
else{fsCreateDataFile(path,fname,decodeBase64ToArray(data.voice));}
if(data.files&&Array.isArray(data.files)){for(var i=0,l=data.files.length;i<l;i++){f=data.files[i];if(typeof f=='object'&&typeof f.path=='string'&&f.path.length&&typeof f.data=='string'&&f.data.length){parts=f.path.split('/');if(parts.length>1){path=eSpeakDataDir+'/'+parts.slice(0,parts.length-1).join('/');}
else{path=eSpeakDataDir;}
fname=parts[parts.length-1];if(f.encoding=='text'){fsCreateDataFile(path,fname,decodeStringToArray(f.data));}
else{fsCreateDataFile(path,fname,decodeBase64ToArray(f.data));}}}}
voicesLoaded[data.voice_id]=true;}
setDefaultVoice(data.voice_id);executeQueuedCalls();}
function decodeBase64ToArray(str){function f(c){if(c==43){return 62;}
else if(c==47){return 63;}
else if(c==61){return 64;}
else if(c<=57){return c+4;}
else if(c<=90){return c-65;}
else{return c-71;}}
var h1,h2,h3,h4,out=[],i=0,l=str.length;while(i<l){h1=f(str.charCodeAt(i++));h2=f(str.charCodeAt(i++));h3=f(str.charCodeAt(i++));h4=f(str.charCodeAt(i++));out.push((h1<<2)|(h2>>4));if(h3!=64)out.push(((h2&15)<<4)|(h3>>2));if(h4!=64)out.push(((h3&3)<<6)|h4);}
return out;}
function encode64(data){var BASE='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';var PAD='=';var ret='';var leftchar=0;var leftbits=0;for(var i=0,l=data.length;i<l;i++){leftchar=(leftchar<<8)|data[i];leftbits+=8;while(leftbits>=6){var curr=(leftchar>>(leftbits-6))&0x3f;leftbits-=6;ret+=BASE[curr];}}
if(leftbits==2){ret+=BASE[(leftchar&3)<<4];ret+=PAD+PAD;}else if(leftbits==4){ret+=BASE[(leftchar&0xf)<<2];ret+=PAD;}
return ret;}
function decodeStringToArray(str){var out=[],l=str.length,i;for(i=0;i<l;i++)out.push(str.charCodeAt(i));return out;}
function executeQueuedCalls(){if(configDataLoaded&&defaultVoice){for(var i=0,l=speakQueue.length;i<l;i++){var args=speakQueue[i];if(args[3].multipart){speakMultipart(args[0],args[1],args[2],args[3]);}
else{speak(args[0],args[1],args[2],args[3]);}}
speakQueue.length=0;}}
function resetQueue(){speakQueue.length=0;}
function speak(text,args,callback,_id){if(typeof args!=='object')args={};if(!canPlay&&!args.rawdata){if(self.console)console.log('meSpeak: Can\'t play; No audio support.');return 0;}
if(!_id||!isValidJobId(_id))_id=getJobId();if(!configDataLoaded||!defaultVoice){if(self.console)console.log(((!configDataLoaded)?'No config-data loaded':'No voice module loaded')+', deferring call.');if(args.rawdata){return null;}
else{speakQueue.push([text,args,callback,_id]);return _id.number;}}
if(args&&args.voice&&!voicesLoaded[args.voice]){if(self.console)console.log('Voice '+args.voice+' not available. Using default voice: '+defaultVoice);}
var varg=(args.voice)?String(args.voice):(args.v)?String(args.v):defaultVoice;if(varg.indexOf('mb/mb-')==0)varg=varg.substring(3);if(args.variant)varg+='+'+String(args.variant).replace(/\+/g,'');var argstack=['-w','wav.wav','-a',args.amplitude!==undefined?String(args.amplitude):args.a!==undefined?String(args.a):'100','-g',args.wordgap!==undefined?String(args.wordgap):args.g!==undefined?String(args.g):'0','-p',args.pitch!==undefined?String(args.pitch):args.p!==undefined?String(args.p):'50','-s',args.speed!==undefined?String(args.speed):args.s!==undefined?String(args.s):'175','-b',args.utf16?'4':args.b!==undefined?String(args.b):'1','-v',varg];var a=args.linebreak||args.l;if(a)argstack.push('-l',String(a));a=args.capitals||args.k;if(a)argstack.push('-k',String(a));a=args.nostop||args.z;if(a)argstack.push('-z');if(args.punct!==undefined){if(typeof args.punct=='string'){if(args.punct.length){argstack.push('--punct="'+String(args.punct).replace(/([\\"'])/g,'\\$1')+'"');}
else{argstack.push('--punct');}}
else if(args.punct){argstack.push('--punct');}}
a=args.ssml||args.m||args.markup;if(a)argstack.push('-m');argstack.push('--path='+eSpeakDir,String(text));if(args.log&&self.console)console.log('executing espeak '+argstack.join(' '));eSpeak.Module.arguments=argstack;if(typeof callback!='function')callback=undefined;if(!callback&&typeof args.callback=='function')callback=args.callback;fsErrorDetected=false;eSpeak.run();if(fsErrorDetected){fsErrorDetected=false;eSpeak.Module.arguments=argstack;eSpeak.run();}
var outfile=eSpeak.FS.root.contents['wav.wav'].contents,wav=unsignedStream(outfile);outfile.length=0;argstack=null;return(args.rawdata)?exportStream(wav,args.rawdata):playSound(wav,args.volume,callback,_id);}
function exportStream(stream,format){switch(String(format).toLowerCase()){case'array':return stream;case'base64':return encode64(stream);case'data-url':case'data-uri':case'dataurl':case'datauri':case'mime':return'data:audio/x-wav;base64,'+encode64(stream);default:var buffer=new ArrayBuffer(stream.length);new Uint8Array(buffer).set(stream);return buffer;}}
function speakMultipart(parts,args,callback,_id){if(typeof args!=='object')args={};if(!canPlay&&!args.rawdata){if(self.console)console.log('meSpeak: Can\'t play; No audio support.');return 0;}
var failed=false;if(typeof callback!='function')callback=undefined;if(!callback&&typeof args.callback=='function')callback=args.callback;if(Object.prototype.toString.call(parts)!='[object Array]'||!parts.length){if(self.console)console.log('meSpeak.speakMultipart: First argument must be an array of objects.');failed=true;}
if(!failed){for(var i=0,l=parts.length;i<l;i++){if(typeof parts[i]!='object'){if(self.console)console.log('meSpeak.speakMultipart: First argument must be an array of objects (part #'+i+').');failed=true;break;}}}
if(failed){if(args.rawdata){return null;}
else{if(callback)callback(false);return 0;}}
if(!_id||!isValidJobId(_id))_id=getJobId();if(!configDataLoaded||!defaultVoice){if(self.console)console.log(((!configDataLoaded)?'No config-data loaded':'No voice module loaded')+', deferring call.');if(args.rawdata){return null;}
else{_id.multipart=true;speakQueue.push([parts,args,callback,_id]);return _id.number;}}
var wav,sampleLength;for(var i=0,l=parts.length;i<l;i++){var n,part=parts[i],opts={};for(n in args)opts[n]=args[n];for(n in part)opts[n]=part[n];opts.rawdata='array';opts.callback=undefined;var buffer=meSpeak.speak(part.text,opts);if(!buffer){if(args.rawdata){return null;}
else{if(callback)callback(false);return 0;}}
if(i==0){wav=buffer;sampleLength=readBytes(buffer,40,4);}
else{sampleLength+=readBytes(buffer,40,4);wav=wav.concat(buffer.slice(44));}
buffer=null;}
writeBytes(wav,4,4,sampleLength);writeBytes(wav,40,4,sampleLength);return(args.rawdata)?exportStream(wav,args.rawdata):playSound(wav,args.volume,callback,_id);}
function writeBytes(f,p,n,value){while(n){f[p++]=value&0xff;value=value>>8;n--;}}
function readBytes(f,p,n){var value=0,shft=0;while(n){value|=f[p++]<<shft;shft+=8;n--;}
return value;}
function unsignedStream(wav){var i,l=wav.length,v,out=new Array(l);for(i=0;i<l;i++){v=wav[i];out[i]=(v>=0)?v:256+v;}
return out;}
function getJobId(){var n,s;while(!n||audioPool[s]||webSoundPool[s]){n=Math.floor(Math.random()*Math.pow(2,32));s=n.toString(16);}
return{number:n,string:s}}
function isValidJobId(id){return!(Object.prototype.toString.call(id)!=='[object Object]'||Object.prototype.toString.call(id.number)!=='[object Number]'||Object.prototype.toString.call(id.string)!=='[object String]'||!id.number||id.string!==id.number.toString(16));}
function playSound(stream,relVolume,callback,_id){if(callback&&(typeof callback!='function'))callback=undefined;if(!_id||!isValidJobId(_id))_id=getJobId();var streamType=Object.prototype.toString.call(stream);if(!(streamType=='[object Array]'||streamType=='[object ArrayBuffer]'||streamType=='[object String]')){if(self.console)console.log('meSpeak: Can\'t play, not an Array, or ArrayBuffer, or base64-String: '+streamType);if(callback)callback(false);return 0;}
if(relVolume!==undefined){relVolume=parseFloat(relVolume);if(isNaN(relVolume)||relVolume<0||relVolume>1)relVolume=undefined;}
if(AudioAPI){if(streamType=='[object String]'){if(stream.indexOf('data:audio/x-wav;base64,',0)==0)stream=stream.substring(24);stream=stream.replace(/=+$/,'');if(stream.match(/[^A-Za-z0-9\+\/]/)){if(self.console)console.log('meSpeak: Can\'t play, not a proper base64-String.');if(callback)callback(false);return 0;}
stream=decodeBase64ToArray(stream);if(!stream.length){if(self.console)console.log('meSpeak: Can\'t play, empty sound data.');if(callback)callback(false);return 0;}
streamType='[object Array]';}
var buffer;if(streamType=='[object Array]'){var buffer=new ArrayBuffer(stream.length);new Uint8Array(buffer).set(stream);}
else{buffer=stream;}
return playWebSound(buffer,relVolume,callback,_id);}
else if(canPlay){var isDataUrl=false;if(streamType=='[object String]'){if(stream.indexOf('data:audio/x-wav;base64,',0)<0){if(stream.match(/[^A-Za-z0-9\+\/]/)){if(self.console)console.log('meSpeak: Can\'t play, not a proper base64-String.');if(callback)callback(false);return 0;}
stream='data:audio/x-wav;base64,'+stream;}
isDataUrl=true;}
else if(streamType=='[object ArrayBuffer]'){stream=new Uint8Array(stream);}
return(new AudioPlayback(stream,relVolume,isDataUrl,callback,_id).started)?_id.number:0;}
else{if(self.console)console.log('meSpeak: Can\'t play; No audio support.');if(callback)callback(false);return 0;}}
function stopSound(){var id,i,k,kl,l,item,n,stopped=0;if(arguments.length>0){for(i=0,l=arguments.length;i<l;i++){n=parseInt(arguments[i]);if(n&&!isNaN(n)){id=n.toString(16);if(audioPool[id]){audioPool[id].stop();stopped++;}
else if(webSoundPool[id]){stopWebSound(webSoundPool[id]);stopped++;}
else{for(k=0,kl=speakQueue.length;k<kl;k++){item=speakQueue[i];if(item[3].string===id){if(!unloading&&typeof item[2]=='function')item[2](false);speakQueue.splice(k,1);stopped++;break;}}}}}}
else{for(id in audioPool){audioPool[id].stop();stopped++;}
for(id in webSoundPool){stopWebSound(webSoundPool[id]);stopped++;}
for(i=0,l=speakQueue.length;i<l;i++){item=speakQueue[i];if(!unloading&&typeof item[2]=='function')item[2](false);stopped++;}
speakQueue.length=0;}
return stopped;}
function setVolume(vol){var id,i,l,n,v;v=parseFloat(vol);if(!isNaN(v)&&v>=0&&v<=1&&v!=playbackVolume){if(arguments.length==1)playbackVolume=v;if(AudioAPI){if(arguments.length>1){for(i=0,l=arguments.length;i<l;i++){n=parseInt(arguments[i]);if(n&&!isNaN(n)){id=n.toString(16);if(webSoundPool[id])setWebSoundVolume(webSoundPool[id],v);}}}
else if(masterGain){masterGain.gain.value=playbackVolume;}}
else if(canPlay){if(arguments.length>1){for(i=0,l=arguments.length;i<l;i++){n=parseInt(arguments[i]);if(n&&!isNaN(n)){id=n.toString(16);if(audioPool[id])audioPool[id].setVolume(v);}}}
else{for(id in audioPool)audioPool[id].adjustVolume();}}}
return vol;}
function getVolume(){if(arguments.length){var n=parseInt(arguments[0]);if(n&&!isNaN(n)){var id=n.toString(16);if(webSoundPool[id])return webSoundPool[id].relVolume;if(audioPool[id])return audioPool[id].relVolume;}
return undefined;}
else{return playbackVolume;}}
function resolveAudioApi(){if(self.AudioContext){AudioAPI=self.AudioContext;canPlay=true;return;}
else{var vendors=['webkit','moz','o','ms'];for(var i=0;i<vendors.length;i++){var api=self[vendors[i]+'AudioContext'];if(api){AudioAPI=api;canPlay=true;return;}}}
if(!AudioAPI){var audioElement=document.createElement('audio');if(audioElement&&audioElement.canPlayType&&(audioElement.canPlayType('audio/wav')||audioElement.canPlayType('audio/x-wav'))){canPlay=true;}
else{canPlay=false;if(self.console)console.log('meSpeak: Muted. No support for HTMLAudioElement with MIME "audio/x-wav" dected.');}}}
resolveAudioApi();function canPlaybackWav(){return canPlay;}
function AudioPlayback(stream,relVolume,isDataUrl,callback,id){this.relVolume=relVolume;this.audio=null;this.id=id.string;this.callback=(typeof callback=='function')?callback:undefined;this.playing=false;this.started=false;this.play(stream,isDataUrl);}
AudioPlayback.prototype={play:function(stream,isDataUrl){try{audioPool[this.id]=this;this.audio=document.createElement('audio');this.adjustVolume();var that=this;this.audio.addEventListener('ended',function(){that.remove();},false);this.audio.addEventListener('canplaythrough',function(){that.audio.play();that.playing=true;},false);if(isDataUrl){this.audio.src=stream;}
else{this.audio.src='data:audio/x-wav;base64,'+encode64(stream);}
this.audio.load();this.started=true;}
catch(e){if(self.console)console.log('meSpeak: HTMLAudioElement Exception: '+e.message);this.started=false;this.remove();}},adjustVolume:function(){this.audio.volume=(this.relVolume!==undefined)?this.relVolume*playbackVolume:playbackVolume;},setVolume:function(v){this.relVolume=v;this.adjustVolume();},remove:function(stopped){if(this.id)delete audioPool[this.id];if(this.callback){var f=this.callback;this.callback=undefined;if(!unloading)f(!stopped);}},stop:function(){try{if(this.playing)this.audio.pause();}
catch(e){}
this.remove(true);}};function playWebSound(stream,volume,callback,id){try{var source,gainNode,timer,relVolume;if(!audioContext)audioContext=new AudioAPI();if(!masterGain){masterGain=(audioContext.createGain)?audioContext.createGain():audioContext.createGainNode();masterGain.connect(audioContext.destination);masterGain.gain.value=playbackVolume;}
source=audioContext.createBufferSource();relVolume=parseFloat(volume);if(relVolume===undefined||isNaN(relVolume)||relVolume<0||relVolume>1)relVolume=1;gainNode=(audioContext.createGain)?audioContext.createGain():audioContext.createGainNode();gainNode.connect(masterGain);gainNode.gain.value=relVolume;source.connect(gainNode);audioContext.decodeAudioData(stream,function(audioData){var f=function(){webSoundEndHandler(source,gainNode,callback,true,id.string);};if(!isChrome&&source.onended!==undefined){source.onended=f;}
else{var duration=audioData.duration;setTimeout(f,duration?Math.ceil(duration*1000):10);}
source.buffer=audioData;if(chromeVersion>=32&&source.start)source.start(0);},function(err){console.log('meSpeak: Web Audio Decoding Error: '+((typeof err=='object')?err.message:err));if(timer)clearTimeout(timer);if(source)source.disconnect();if(gainNode)gainNode.disconnect();if(webSoundPool[id.string])delete webSoundPool[id.string];if(!unloading&&typeof callback=='function')callback(false);return 0;});webSoundPool[id.string]={'source':source,'gainNode':gainNode,'callback':callback,'id':id.string,'relVolume':relVolume};if(chromeVersion<32){if(source.start){source.start(0);}
else{source.noteOn(0);}}
return id.number;}
catch(e){if(self.console)console.log('meSpeak: Web Audio Exception: '+e.message);if(timer)clearTimeout(timer);webSoundEndHandler(source,gainNode,callback,false,id.string);return 0;}}
function webSoundEndHandler(source,gainNode,callback,success,id){if(!unloading&&typeof callback=='function')callback(success);var f=function(){if(source){if(source.onended!==undefined)source.onended=undefined;source.disconnect();}
if(gainNode)gainNode.disconnect();if(id&&webSoundPool[id])delete webSoundPool[id];};if(!success){f();}
else{setTimeout(f,500);}}
function stopWebSound(obj){try{if(obj.source.stop){obj.source.stop(0);}
else{obj.sourcesource.noteOff(0);}}
catch(e){}
webSoundEndHandler(obj.source,obj.gainNode,obj.callback,false,obj.id);}
function setWebSoundVolume(obj,v){obj.gainNode.gain.value=v;obj.relVolume=v;}
function setDefaultVoice(voice){if(voice&&voicesLoaded[voice])defaultVoice=voice;}
function getDefaultVoice(){return defaultVoice;}
function loadVoice(url,callback){if(url)new HttpRequest(url,voiceRequestCallback,callback);}
function loadConfig(url){if(url)new HttpRequest(url,configDataRequestCallback,null);}
function isVoiceLoaded(voice){return(voicesLoaded[voice])?true:false;}
function isConfigLoaded(){return(configDataLoaded)?true:false;}
function HttpRequest(url,loadCallback,userCallback){var req=this.request=new XMLHttpRequest();this.handler=loadCallback;this.url=url;this.localmode=Boolean(self.location.href.search(/^file:/i)==0);this.userCallback=userCallback;var objref=this;try{req.open('GET',url);req.onreadystatechange=function(){objref.handler();};req.send('');}
catch(e){if(self.console)console.log('Failed to load resource from '+url+': Network error.');if(typeof userCallback=='function')userCallback(false,'network error');this.request=this.handler=this.userCallback=null;}}
function voiceRequestCallback(){var req=this.request;if(req.readyState==4){if(this.localmode||req.status==200){var data=JSON.parse(req.responseText);if(typeof data=='object'&&typeof data.voice_id=='string'&&typeof data.voice=='string'&&(((!data.dict_id&&!data.dict_id)||(typeof data.dict_id=='string'&&typeof data.dict=='string'))||(!data.files||(typeof data.files=='object'&&Array.isArray(data.files))))){setVoiceData(data);if(typeof this.userCallback=='function')this.userCallback(true,data.voice_id);}
else{if(self.console)console.log('Failed to load voice from '+this.url+': Not a voice module.');if(typeof this.userCallback=='function')this.userCallback(false,'data error');}}
else{if(self.console)console.log('Failed to load voice from '+this.url+': Received status '+req.status+'.');if(typeof this.userCallback=='function')this.userCallback(false,'file error');}
this.request=this.handler=this.userCallback=null;}}
function configDataRequestCallback(){var req=this.request;if(req.readyState==4){if(this.localmode||req.status==200){var data=JSON.parse(req.responseText);if(typeof data=='object'&&typeof data.config=='string'&&typeof data.phontab=='string'&&typeof data.phonindex=='string'&&typeof data.phondata=='string'&&typeof data.intonations=='string'){setConfigData(data);}
else{if(self.console)console.log('Failed to load config-data from '+this.url+': No valid data.');}}
else{if(self.console)console.log('Failed to load config-data from '+this.url+': Received status '+req.status+'.');}
this.request=this.handler=this.userCallback=null;}}
function unloadHandler(event){unloading=true;stopSound();audioPool={};webSoundPool={};}
window.addEventListener('unload',unloadHandler,false);return{speak:speak,speakMultipart:speakMultipart,loadConfig:loadConfig,loadVoice:loadVoice,setDefaultVoice:setDefaultVoice,getDefaultVoice:getDefaultVoice,setVolume:setVolume,getVolume:getVolume,play:playSound,isConfigLoaded:isConfigLoaded,isVoiceLoaded:isVoiceLoaded,resetQueue:resetQueue,canPlay:canPlaybackWav,stop:stopSound}})();meSpeak.loadConfig("dbsamples/speechConf.json");
meSpeak.loadVoice("dbsamples/speechVoice.json");
define.unordered = true;

define('ripple/accelerometer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    event = require('ripple/event'),
    Rotation = require('ripple/platform/w3c/1.0/Rotation'),
    Acceleration = require('ripple/platform/w3c/1.0/Acceleration'),
    _motion = {
        acceleration: new Acceleration(0, 0, 0),
        accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
        rotationRate: new Rotation(0, 0, 0),
        orientation: new Rotation(0, 0, 0),
        interval: 60000,
        timestamp: new Date().getTime()
    };

function _validateAccelerometerInfo(x, y, z) {
    return !(isNaN(x) || isNaN(y) || isNaN(z));
}

_self = {
    getInfo: function () {
        return utils.copy(_motion);
    },

    setInfo: function (e) {
        var triggerDeviceMotion = false,
            triggerDeviceOrientation = false;

        if (e.x !== undefined && e.y !== undefined && e.z !== undefined) {
            _motion = {
                acceleration: new Acceleration(e.x, e.y, e.z),
                accelerationIncludingGravity: new Acceleration(e.x, e.y, e.z),
                rotationRate: new Rotation(0, 0, 0),
                orientation: new Rotation(e.alpha, e.beta, e.gamma),
                timestamp: new Date().getTime()
            };
            triggerDeviceMotion = true;
            triggerDeviceOrientation = true;
        }
        else {
            _motion = {
                acceleration: new Acceleration(0, 0, 0),
                accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
                rotationRate: new Rotation(0, 0, 0),
                orientation: new Rotation(0, 0, 0),
                timestamp: new Date().getTime()
            };
        }

        if (triggerDeviceMotion) {
            event.trigger("DeviceMotionEvent", [_motion]);
        }

        if (triggerDeviceOrientation) {
            event.trigger("DeviceOrientationEvent", [_motion]);
        }

        event.trigger("AccelerometerInfoChangedEvent", [_motion]);
    },

    triggerEvent: function() {
        event.trigger("DeviceMotionEvent", [_motion]);
        event.trigger("DeviceOrientationEvent", [_motion]);
        event.trigger("AccelerometerInfoChangedEvent", [_motion]);
    },

    shake: function (shakeXtimes) {
        var id,
            count = 1,
            stopCount = shakeXtimes || 17,
            oldX = _motion.accelerationIncludingGravity.x;

        id = setInterval(function () {
            var freq = 1,
                amp = 30,
                value = Math.round(amp * Math.sin(freq * count * (180 / Math.PI)) * 100) / 100;

            if (count > stopCount) {
                _motion.acceleration.x = oldX;
                _motion.accelerationIncludingGravity.x = oldX;
                event.trigger("AccelerometerInfoChangedEvent", [_motion]);
                clearInterval(id);
                return;
            }

            _motion.acceleration.x = value;
            _motion.accelerationIncludingGravity.x = value;

            event.trigger("AccelerometerInfoChangedEvent", [_motion]);

            count++;

        }, 80);
    },

    init: function () {
        event.on("DeviceMotionEventAddedEvent", function () {
            _self.triggerEvent();
        });
        event.on("DeviceOrientationEventAddedEvent", function () {
            _self.triggerEvent();
        });
    }
};

module.exports = _self;

});
define('ripple/app', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _data = {},
    utils = require('ripple/utils'),
    _self;

_self = {
    setInfo: function (info) {
        if (!info) {
            _data = {};
        }
        _data = info;
    },

    getInfo: function () {
        return utils.copy(_data);
    },

    isPreferenceReadOnly: function (key) {
        return (_data.preferences &&
                _data.preferences[key] &&
                _data.preferences[key].readonly &&
                _data.preferences[key].readonly === true);
    },

    validateVersion: function (configValidationObject) {
        // TODO: WTF figure this out, platform is empty object when require at require time
        // could be that the new platform _getBuilder code dies when called, beforre it is initialized
        var spec = require('ripple/platform').current();
        if (typeof spec.config.validateVersion === "function" && configValidationObject) {
            return spec.config.validateVersion(configValidationObject);
        }

        return true;
    },

    saveInfo: function (configValidationObject) {
        var spec = require('ripple/platform').current(),
            info = null;
        if (typeof spec.config.extractInfo === "function") {
            info = spec.config.extractInfo(configValidationObject);
        }

        if (info) {
            _self.setInfo(info);
        }
    }

};

module.exports = _self;

});
define('ripple/appcache', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    initialize: function () {
        window.addEventListener('load', function (e) {
            window.applicationCache.addEventListener('updateready', function (e) {
                if (window.applicationCache.status === window.applicationCache.UPDATEREADY) {
                    window.applicationCache.swapCache();
                    window.location.reload();
                }
            }, false);
        }, false);
    }
};

});
define('ripple/bootstrap', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _bound,
    _console = require('ripple/console'),
    utils = require('ripple/utils'),
    ui = require('ripple/ui'),
    db = require('ripple/db'),
    _CURRENT_URL = "current-url",
    resizer = require('ripple/resizer'),
    platform = require('ripple/platform');

var _srcChangedObserver = new WebKitMutationObserver(function (mutations) {
            utils.forEach(mutations, function (mutation) {
                _bindObjectsToFrame(mutation.target);
            });
        });

function _observeIframeAdded(doc) {
    doc._iframeAddedObserver.observe(doc, {childList: true, subtree: true});
}

function _bindObjects(win, doc) {
    if (!win.tinyHippos) {
        require('ripple/emulatorBridge').link(win, doc);
        require('ripple/touchEventEmulator').mask(win, doc);
        require('ripple/hwKeyEmulator').init(win, doc);
        require('ripple/documentEventListener').mask(win, doc);
        require('ripple/deviceMotionEmulator').init(win, doc);
        require('ripple/resizer').init(win, doc);
        win.addEventListener("DOMContentLoaded", function () {
            var iframes =  $(this.document).find("iframe");
            // Observe iframe added event so that we can bind objects to newly added iframes
            if (!this.document._iframeAddedObserver) {
                this.document._iframeAddedObserver = new WebKitMutationObserver(function (mutations) {
                    utils.forEach(mutations, function (mutation) {
                        for (var i in mutation.addedNodes) {
                            var node = mutation.addedNodes[i];
                            if (node.tagName && (node.tagName.toUpperCase() === "IFRAME")) {
                                _bindObjectsToFrame(node);
                            }
                        }
                    });
                });
                _observeIframeAdded(this.document);
            }
            iframes.each(function () {
                _bindObjectsToFrame(this);
            });

        });
        win.frameElement._bound = true;
    }
}

function _beforeLoad() {
    this._bound = false;
    _bindObjects(this.contentWindow, this.contentDocument);
    this._intervalId = window.setInterval(function () {
        if (this._bound) {
            window.clearInterval(this._intervalId);
        } else {
            _bindObjects(this.contentWindow, this.contentDocument);
        }
    }.bind(this), 1);
}

function _bindObjectsToFrame(frame) {
    //_srcChangedObserver.observe(frame, {attributes: true, attributeFilter: ["src"]});
    frame.addEventListener("DOMNodeInserted", _beforeLoad);
//    frame.addEventListener("beforeload", _beforeLoad);
    // beforeload event of an iframe will not be triggered unless we detach and
    // then attach the iframe to the dom tree
    var parentNode = frame.parentNode;
    var nextNode = frame.nextSibling;
    if (parentNode) {
        // Disable iframe added observer to avoid infinite loop of binding objects
        if (frame.ownerDocument && frame.ownerDocument._iframeAddedObserver) {
            frame.ownerDocument._iframeAddedObserver.disconnect();
        }
        parentNode.removeChild(frame);
        parentNode.insertBefore(frame, nextNode);

        if (frame.ownerDocument && frame.ownerDocument._iframeAddedObserver) {
            _observeIframeAdded(frame.ownerDocument);
        }
    }
}

function _createFrame(src) {
    var frame = document.createElement("iframe");
    frame.setAttribute("id", "document");
    frame.src = src;

    if (ui.registered("omnibar")) {
        _bindObjectsToFrame(frame);
    }

    return frame;
}

function _cleanBody() {
    require('ripple/utils').forEach(document.body.children, function (child) {
        if (child && child.id && !child.id.match(/ui|tooltip|bus/)) {
            document.body.removeChild(child);
        }

        document.body.removeAttribute("style");
        document.body.removeAttribute("id");
        document.body.removeAttribute("class");
    });
}

function reload() {
    window.tinyHipposReload = true;
    location.reload();
}

function _post(src) {
    var event = require('ripple/event'),
	devices = require('ripple/devices'),
    frame = _createFrame(src),
	currentDeviceKey = devices.getCurrentDevice().id;

    _console.log("Initialization Finished (Make it so.)");

    frame.onload = function () {
        var bootLoader = document.querySelector("#emulator-booting"),
            id,
            iframe = document.getElementById('document'),
            viewportTagFound = false,
            viewportTagContent = {},
            viewportTagStr = "",
            tagProperties = [],
			mediaTagProps = [],
            propertyKey ="",
            propertyValue = "",
            curViewPortWidth = "",
            curViewPortHeight = "",
            layout = db.retrieve("layout") || "portrait",
            preLayout = "";

        if (bootLoader) {
            document.querySelector("#ui").removeChild(bootLoader);
        }

        // Workaround to enforce the content of iframe to rerender when scrolling
        document.getElementById('document').contentWindow.onscroll = function() {
            jQuery("#device-maskmask").show();
            setTimeout(function() {
                jQuery("#device-maskmask").hide();
            }, 50);
        };

	    event.trigger("TinyHipposLoaded");
        _cleanBody();
        id = window.setInterval(_cleanBody, 20);

        window.setTimeout(function () {
            window.clearInterval(id);
        }, 1200);

        // Clean data for different app
        if (db.retrieve("current-url") !== db.retrieve("previous-url")) {
            db.remove("viewport_width");
            db.remove("viewport_height");
            db.remove("viewportTag");
            db.remove("prelayout");
        }

        curViewPortWidth = db.retrieve("viewport_width");
        curViewPortHeight = db.retrieve("viewport_height");
        preLayout = db.retrieve("prelayout") || "portrait";
        db.save("previous-url", db.retrieve("current-url"));

		if (iframe.contentDocument.getElementsByName('viewport')[0] !== undefined) {
            viewportTagStr = iframe.contentDocument.getElementsByName('viewport')[0].getAttribute("content");
            viewportTagStr = viewportTagStr.replace(/\s/g, '');
            tagProperties = viewportTagStr.split(",");

            for (var i in tagProperties) {
                propertyKey = tagProperties[i].split("=")[0];
                propertyValue = tagProperties[i].split("=")[1];
                viewportTagContent[propertyKey] = propertyValue;
            }
            viewportTagFound = true;
        }

        // if viewport tag found (width, height)
        if (viewportTagFound && ((viewportTagContent['width'] !== undefined) || (viewportTagContent['height'] !== undefined))) {
            if ((viewportTagContent['width'] !== undefined)) {
                if (curViewPortWidth !== viewportTagContent['width']) {
                    db.saveObject("viewportTag", viewportTagContent);
                    if (layout !== preLayout) {
                        db.save("prelayout", layout);
                        resizer.changeLayoutType(layout);
                        event.trigger("LayoutChanged", [layout], true);
                        frame.contentWindow.location.reload(); // get the updated screenAvailWidth, screenWidth....
                    } else {
                        resizer.changeLayoutType(layout);
                    }
                }
            } else {
                if (curViewPortHeight !== viewportTagContent['height']) {
                    db.saveObject("viewportTag", viewportTagContent);
                    if (layout !== preLayout) {
                        db.save("prelayout", layout);
                        resizer.changeLayoutType(layout);
                        event.trigger("LayoutChanged", [layout], true);
                        frame.contentWindow.location.reload(); // get the updated screenAvailWidth, screenWidth....
                    } else {
                        resizer.changeLayoutType(layout);
                    }
                }
            }
        } else {
            // Set layout to portrait if no viewport tag detected
            resizer.changeLayoutType('portrait');
            event.trigger("LayoutChanged", ['portrait'], true);
        }

        if (ui.registered("omnibar")) {
            //reset the onload function so that when navigating we can destroy
            //the iframe and create a new one so we can reinject the platform by
            //calling post again.
            frame.onload = function () {
                var url = frame.contentWindow.location.href;
                document.getElementById("viewport-container").removeChild(frame);
                event.trigger("FrameHistoryChange", [url]);
                _console.log("-----------------------------------------------------------");
                _console.log("Pay no attention to that man behind the curtain.");
                _console.log("Environment Warning up again (Set main batteries to auto-fire cycle)");
                _post(url);
            };
        }
    };
    document.getElementById("viewport-container").appendChild(frame);
    delete tinyHippos.boot;
}

function _bootstrap() {
    // TODO: figure this out for web and ext
    //_console.log("-----------------------------------------------------------");
    //_console.log("There be dragons above here!");
    _console.log("Web Simulator :: Environment Warming Up (Tea. Earl Gray. Hot.)");

    window.tinyHippos = require('ripple');

    tinyHippos.boot(function () {
        var uri = ui.registered('omnibar') ?
                db.retrieve(_CURRENT_URL) || "about:blank" :
                document.documentURI.replace(/enableripple=[^&]*[&]?/i, "").replace(/[\?&]*$/, "");

        _post(uri);
        delete tinyHippos.boot;
    });
}

module.exports = {
    bootstrap: _bootstrap,
    inject: function (frameWindow, frameDocument) {
        _bindObjects(frameWindow, frameDocument);
    }
};

});
define('ripple/bus', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _send = document.getElementById("bus-send"),
    _receive = document.getElementById("bus-receive"),
    _evt = document.createEvent("Events");

_evt.initEvent('bus-init', true, true);
document.dispatchEvent(_evt);

module.exports = {
    send: function (msg, data, callback) {
        var m = document.createElement("span");
        m.dataset.msg = msg;
        m.innerHTML = JSON.stringify(data);

        if (callback) {
            m.dataset.callback = Math.uuid();
            this.receive(m.dataset.callback, callback);
        }

        _send.appendChild(m);
    },

    receive: function (msg, handler) {
        if (!handler) {
            return;
        }

        _receive.addEventListener("DOMNodeInserted", function (evt) {
            if (evt.target.dataset.msg === msg) {
                handler(JSON.parse(evt.target.innerHTML));
            }
        });
    },

    ajax: function (method, url, data, success, fail) {
        this.send("xhr", {
            method: method,
            url: url,
            data: data
        }, function (result) {
            if (result.code === 200) {
                success(result.data);
            }
            else {
                fail(result);
            }
        });
    }
};

});
define('ripple/console', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self;

function _log(msg, method) {
    try {
        console[method](_self.prefix ? _self.prefix + " :: " + msg : msg);
    } catch (e) {
        // silent
    }
}

_self = {
    log: function (msg) {
        _log(msg, "log");
    },

    warn: function (msg) {
        _log(msg, "warn");
    },

    error: function (msg) {
        _log(msg, "error");
    }
};

module.exports = _self;

});
define('ripple/constants', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "API_URL": "http://api.tinyhippos.com",

    "RELEASE_VERSION": "simulator-release-version",

    "SERVICES": {
        "GOOGLE_MAPS_URI": "http://maps.google.com/maps/api/staticmap?size=476x476&maptype=roadmap",
        "GOOGLE_MAPS_API_KEY": "ABQIAAAA-CaPZHXR-0Tzhui_h6gpjhSE_2rGlnYiB7L-ZGVwgaut5s7OYRSlBAaHCzBuZf2_23_vrCOfPxXHjA"
    },

    "FS_SIZE": 1024 * 1024 * 10,

    "COMMON":  {
        "APPLICATION_STATE": "ui-application-state-",
        "PREFIX": "tinyhippos-",
        "DEVICE_CONTAINER" : "device-container",
        "MENU_BUTTON" : "menu-button",
        "BACK_BUTTON" : "back-button",
        "HTML_CONTAINER" : "document",
        "INFO_SECTION": "information-sub-container",
        "ORIENTATION_SELECT_PORTRAIT_ID" : "layout-portrait",
        "ORIENTATION_SELECT_LANDSCAPE_ID" : "layout-landscape",
        "PLATFORM_SELECT_ID": "platform-select",
        "DEVICE_SELECT_ID": "device-select",
	"DEV_SELECT" : "dev-select",
        "STORAGE_TABLE_BODY_CLASS": "preferences-list-body",
        "STORAGE_COUNT_CONTAINER_ID": "preferences-count",
        "GEO_MAP_CONTAINER_ID": "geo-map",
        "FILESYSTEM_UPDATE_BUTTON_ID_WITH_HASH": "#update-filesystem-button",
        "USER_AGENT_DEFAULT": "default",
        "APPLICATIONS_CONTAINER_ID": "widget-applications-content",
        "STORAGE_CLEAR_BUTTON_ID": "preferences-clear-button",
        "AJAX_LOADER_CONTAINER_CLASS": ".loader",
        "IRRELEVANT_CLASS": "irrelevant",
        "MULTIMEDIA_VOLUME_SLIDER_ID": "media-volume",
        "MULTIMEDIA_VOLUME_FIELD_ID": "media-volume-value",
        "MULTIMEDIA_AUDIO_STATE_FIELD_ID": "media-audio-state",
        "MULTIMEDIA_AUDIO_PLAYING_FIELD_ID": "multimedia-isaudioplaying",
        "MULTIMEDIA_AUDIO_PROGRESS_ID": "media-audio-progress",
        "MULTIMEDIA_AUDIO_FILE_FIELD_ID": "media-audio-file",
        "MULTIMEDIA_VIDEO_STATE_FIELD_ID": "media-video-state",
        "MULTIMEDIA_VIDEO_PLAYING_FIELD_ID": "multimedia-isvideoplaying",
        "MULTIMEDIA_VIDEO_PROGRESS_ID": "media-video-progress",
        "MULTIMEDIA_VIDEO_FILE_FIELD_ID": "media-video-file",
        "EXTENSION_URL_CONTAINER": "extension-url",
        "SECURITY_LEVEL": "security-level"
    },
    "LAUNCHING_HISTORY": "application-launching-history",

    "FILESYSTEM": {
        "PERSISTENCE_KEY": "filesystem",
        "INPUT_PREFIX_ID": "#panel-filesystem-"
    },

    "PLATFORM":  {
        "DEFAULT": {
            "name": "tizen",
            "version": "1.0"
        }
    },

    "DEVICE":  {
        "SAVED_KEY": "device-key"
    },

    "BATTERY":  {
        "TIME": "charging-time",
        "VOLUME": "battery-volume",
        "CHARGING": "is-charging"
    },

    "TOUCHEVENT":  {
        "OPTION": "touch_option",
        "ALTKEY": "touch_altKey",
        "METAKEY": "touch_metaKey",
        "CTRLKEY": "touch_ctrlKey",
        "SHIFTKEY": "touch_shiftKey",
        "CANVAS": "touch_canvas"
    },

    "ENCAPSULATOR":  {
        "DEFAULT_HEIGHT": 684,
        "DEFAULT_WIDTH": 480,
        "LAYOUT": "layout",
        "DISPLAY_LAYOUT": {
            "LANDSCAPE": "landscape",
            "PORTRAIT": "portrait"
        },
        "ZOOMING": "screen-zooming"
    },

    "GEO":  {
        "OPTIONS" : {
            "LATITUDE" : "geo-latitude",
            "LONGITUDE" : "geo-longitude",
            "ALTITUDE" : "geo-altitude",
            "CELL_ID" : "geo-cellid",
            "ACCURACY" : "geo-accuracy",
            "ALTITUDE_ACCURACY" : "geo-altitudeaccuracy",
            "HEADING" : "geo-heading",
            "SPEED" : "geo-speed",
            "TIME_STAMP" : "geo-timestamp",
            "DELAY" : "geo-delay",
            "DELAY_LABEL" : "geo-delay-label",
            "HEADING_LABEL" : "geo-heading-label",
            "HEADING_MAP_LABEL" : "geo-map-direction-label",
            "IMAGE" : "geo-map-img",
            "MAP_CONTAINER" : "geo-map-container",
            "TIMEOUT" : "geo-timeout",
            "GPXFILE": "geo-gpxfile",
            "GPXGO": "geo-gpx-go",
            "GPXMULTIPLIER": "geo-gpxmultiplier-select",
            "GPXREPLAYSTATUS": "geo-gpxreplaystatus"
        },
        "MAP_ZOOM_MAX": 18,
        "MAP_ZOOM_MIN": 0,
        "MAP_ZOOM_LEVEL_CONTAINER": "geo-map-zoomlevel-value",
        "MAP_ZOOM_KEY": "geo-map-zoom-key",
        "GPXGO_LABELS": {

            "GO": "Go",
            "STOP": "Stop"
        }
    },

    "PUSH": {
        "OPTIONS" : {
            "PAYLOAD" : "push-text"
        }
    },

    "TELEPHONY": {
        "CALL_LIST_KEY": "telephony-call-list-key"
    },

    "PIM": {
        "ADDRESS_LIST_KEY": "pim-address-list-key",
        "CALENDAR_LIST_KEY": "pim-calendar-list-key"
    },

    "CAMERA": {
        "WINDOW_ANIMATION": "images/tizen-wave.gif",
        "WARNING_TEXT": "The runtime simulated saving the camera file to {file}. If you need to access this file in your application, please copy a file to the saved location"
    },

    "AUDIOPLAYER" : {
        "WARNING_TEXT": "The runtime simulated saving the audio file to {file}. If you need to access this file in your application, please copy a file to the saved location"
    },

    "API_APPLICATION": {
        "NO_APPLICATIONS_MESSAGE": "No applications available for your platform"
    },

    "NOTIFICATIONS":  {
        "MESSAGE_CONTAINER_CLASS": "notification-message-div",
        "MAIN_CONTAINER_CLASS": "panel-notification",
        "CLOSE_BUTTON_CLASS": "panel-notification-closebtn",
        "MESSAGE_TEXT_CONTAINER_CLASS": "panel-notification-text",
        "CSS_PREFIX": "panel-notification-",
        "STATE_TYPES": {
            "OPEN": 1,
            "CLOSE": 2
        }
    },

    "CSS_PREFIX":  {
        "IRRELEVANT" : "irrelevant"
    },

    "STORAGE":  {
        "PAIR_DELIMETER" : ",",
        "KEY_VALUE_DELIMETER" : "|"
    },

    "REGEX":  {
        "GEO" : /^geo-/,
        "URL": /^((https?|ftp|gopher|telnet|file|notes|ms-help):((\/\/)|(\\\\))+[\w\d:#@%\/;$()~_?\+-=\\\.&]*)$/,
        //"Email": /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
        "EMAIL": /^([^@\s]+)@((?:[\-a-z0-9]+\.)+[a-z]{2,})$/,
        "WC3_DTF": /^((\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)|(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)|(\d{4})-(\d\d)-(\d\d)|(\d{4})-(\d\d)|(\d\d\d\d))$/,
        "LOCAL_URI": /^https?:\/\/(127\.0\.0\.1|localhost)|^file:\/\//,
        "EXTERNAL_URI": /(?:(?:[a-zA-Z0-9\/;\?&=:\-_\$\+!\*'\(\|\\~\[\]#%\.](?!www))+(?:\.[Cc]om|\.[Ee]du|\.[gG]ov|\.[Ii]nt|\.[Mm]il|\.[Nn]et|\.[Oo]rg|\.[Bb]iz|\.[Ii]nfo|\.[Nn]ame|\.[Pp]ro|\.[Aa]ero|\.[cC]oop|\.[mM]useum|\.[Cc]at|\.[Jj]obs|\.[Tt]ravel|\.[Aa]rpa|\.[Mm]obi|\.[Aa]c|\.[Aa]d|\.[aA]e|\.[aA]f|\.[aA]g|\.[aA]i|\.[aA]l|\.[aA]m|\.[aA]n|\.[aA]o|\.[aA]q|\.[aA]r|\.[aA]s|\.[aA]t|\.[aA]u|\.[aA]w|\.[aA]z|\.[aA]x|\.[bB]a|\.[bB]b|\.[bB]d|\.[bB]e|\.[bB]f|\.[bB]g|\.[bB]h|\.[bB]i|\.[bB]j|\.[bB]m|\.[bB]n|\.[bB]o|\.[bB]r|\.[bB]s|\.[bB]t|\.[bB]v|\.[bB]w|\.[bB]y|\.[bB]z|\.[cC]a|\.[cC]c|\.[cC]d|\.[cC]f|\.[cC]g|\.[cC]h|\.[cC]i|\.[cC]k|\.[cC]l|\.[cC]m|\.[cC]n|\.[cC]o|\.[cC]r|\.[cC]s|\.[cC]u|\.[cC]v|\.[cC]x|\.[cC]y|\.[cC]z|\.[dD]e|\.[dD]j|\.[dD]k|\.[dD]m|\.[dD]o|\.[dD]z|\.[eE]c|\.[eE]e|\.[eE]g|\.[eE]h|\.[eE]r|\.[eE]s|\.[eE]t|\.[eE]u|\.[fF]i|\.[fF]j|\.[fF]k|\.[fF]m|\.[fF]o|\.[fF]r|\.[gG]a|\.[gG]b|\.[gG]d|\.[gG]e|\.[gG]f|\.[gG]g|\.[gG]h|\.[gG]i|\.[gG]l|\.[gG]m|\.[gG]n|\.[gG]p|\.[gG]q|\.[gG]r|\.[gG]s|\.[gG]t|\.[gG]u|\.[gG]w|\.[gG]y|\.[hH]k|\.[hH]m|\.[hH]n|\.[hH]r|\.[hH]t^[ml]?|\.[hH]u|\.[iI]d|\.[iI]e|\.[iI]l|\.[iI]m|\.[iI]n|\.[iI]o|\.[iI]q|\.[iI]r|\.[iI]s|\.[iI]t|\.[jJ]e|\.[jJ]m|\.[jJ]o|\.[jJ]p|\.[kK]e|\.[kK]g|\.[kK]h|\.[kK]i|\.[kK]m|\.[kK]n|\.[kK]p|\.[kK]r|\.[kK]w|\.[kK]y|\.[kK]z|\.[lL]a|\.[lL]b|\.[lL]c|\.[lL]i|\.[lL]k|\.[lL]r|\.[lL]s|\.[lL]t|\.[lL]u|\.[lL]v|\.[lL]y|\.[mM]a|\.[mM]c|\.[mM]d|\.[mM]g|\.[mM]h|\.[mM]k|\.[mM]l|\.[mM]m|\.[mM]n|\.[mM]o|\.[mM]p|\.[mM]q|\.[mM]r|\.[mM]s|\.[mM]t|\.[mM]u|\.[mM]v|\.[mM]w|\.[mM]x|\.[mM]y|\.[mM]z|\.[nN]a|\.[nN]c|\.[nN]e|\.[nN]f|\.[nN]g|\.[nN]i|\.[nN]l|\.[nN]o|\.[nN]p|\.[nN]r|\.[nN]u|\.[nN]z|\.[oO]m|\.[pP]a|\.[pP]e|\.[pP]f|\.[pP]g|\.[pP]h|\.[pP]k|\.[pP]l|\.[pP]m|\.[pP]n|\.[pP]r|\.[pP]s|\.[pP]t|\.[pP]w|\.[pP]y|\.[qP]a|\.[rR]e|\.[rR]o|\.[rR]u|\.[rR]w|\.[sS]a|\.[sS]b|\.[sS]c|\.[sS]d|\.[sS]e|\.[sS]g|\.[sS]h|\.[Ss]i|\.[sS]j|\.[sS]k|\.[sS]l|\.[sS]m|\.[sS]n|\.[sS]o|\.[sS]r|\.[sS]t|\.[sS]v[^c]|\.[sS]y|\.[sS]z|\.[tT]c|\.[tT]d|\.[tT]f|\.[tT]g|\.[tT]h|\.[tT]j|\.[tT]k|\.[tT]l|\.[tT]m|\.[tT]n|\.[tT]o|\.[tT]p|\.[tT]r|\.[tT]t|\.[tT]v|\.[tT]w|\.[tT]z|\.[uU]a|\.[uU]g|\.[uU]k|\.[uU]m|\.[uU]s|\.[uU]y|\.[uU]z|\.[vV]a|\.[vV]c|\.[vV]e|\.[vV]g|\.[vV]i|\.[vV]n|\.[vV]u|\.[wW]f|\.[wW]s|\.[yY]e|\.[yY]t|\.[yY]u|\.[zZ]a|\.[zZ]m|\.[zZ]w))/
    },

    "CONFIG": {
        "SUCCESS_CSS": {
            "true": "ui-text-pass",
            "false": "ui-text-fail",
            "missing": "ui-text-missing"
        }
    },

    "SETTINGS": {
        "TOOLTIPS_TOGGLE_DIV": "#settings-toggletooltips",
        "TOOLTIPS_KEY": "tool-tips-key"
    },

    "PANEL": {
        "PANEL_CONFIG_ENABLE": "panel-config-enable"
    },

    "UI": {
        "JQUERY_UI_BUTTON_CLASSES": "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only",
        "JQUERY_UI_INPUT_CLASSES": "ui-state-default ui-corner-all",
        "PANEL_TABLE_CLASS": "panel-table",
        "RIGHT_RANGE_LABEL_CLASS": "range-label",
        "LEFT_RANGE_LABEL_CLASS": "range-label-left",
        "TEXT_LABEL_CLASS": "ui-text-label",
        "SCREEN_PPI": 96
    },

    "MULTIMEDIA": {
        "AUDIO_STATES": {
            "OPENED": "opened",
            "STOPPED": "stopped",
            "PAUSED": "paused",
            "PLAYING": "playing",
            "COMPLETED": "completed"
        }
    },

    "LANG": {
        "ISO6392_LIST": ["abk", "ace", "ach", "ada", "ady", "aar", "afh", "afr", "afa", "ain", "aka", "akk", "alb/sqi", "gsw", "ale", "alg", "tut", "amh", "anp", "apa", "ara", "arg", "arp", "arw", "arm/hye", "rup", "art", "asm", "ast", "ath", "aus", "map", "ava", "ave", "awa", "aym", "aze", "ban", "bat", "bal", "bam", "bai", "bad", "bnt", "bas", "bak", "baq/eus", "btk", "bej", "bel", "bem", "ben", "ber", "bho", "bih", "bik", "byn", "bin", "bis", "zbl", "nob", "bos", "bra", "bre", "bug", "bul", "bua", "bur/mya", "cad", "spa", "cat", "cau", "ceb", "cel", "cai", "khm", "chg", "cmc", "cha", "che", "chr", "nya", "chy", "chb", "chi/zho", "chn", "chp", "cho", "zha", "chu", "chk", "chv", "nwc", "syc", "rar", "cop", "cor", "cos", "cre", "mus", "crp", "cpe", "cpf", "cpp", "crh", "hrv", "cus", "cze/ces", "dak", "dan", "dar", "del", "div", "zza", "din", "doi", "dgr", "dra", "dua", "dut/nld", "dum", "dyu", "dzo", "frs", "efi", "egy", "eka", "elx", "eng", "enm", "ang", "myv", "epo", "est", "ewe", "ewo", "fan", "fat", "fao", "fij", "fil", "fin", "fiu", "fon", "fre/fra", "frm", "fro", "fur", "ful", "gaa", "gla", "car", "glg", "lug", "gay", "gba", "gez", "geo/kat", "ger/deu", "nds", "gmh", "goh", "gem", "kik", "gil", "gon", "gor", "got", "grb", "grc", "gre/ell", "kal", "grn", "guj", "gwi", "hai", "hat", "hau", "haw", "heb", "her", "hil", "him", "hin", "hmo", "hit", "hmn", "hun", "hup", "iba", "ice/isl", "ido", "ibo", "ijo", "ilo", "arc", "smn", "inc", "ine", "ind", "inh", "ina", "ile", "iku", "ipk", "ira", "gle", "mga", "sga", "iro", "ita", "jpn", "jav", "kac", "jrb", "jpr", "kbd", "kab", "xal", "kam", "kan", "kau", "pam", "kaa", "krc", "krl", "kar", "kas", "csb", "kaw", "kaz", "kha", "khi", "kho", "kmb", "kin", "kir", "tlh", "kom", "kon", "kok", "kor", "kos", "kpe", "kro", "kua", "kum", "kur", "kru", "kut", "lad", "lah", "lam", "day", "lao", "lat", "lav", "ltz", "lez", "lim", "lin", "lit", "jbo", "dsb", "loz", "lub", "lua", "lui", "smj", "lun", "luo", "lus", "mac/mkd", "mad", "mag", "mai", "mak", "mlg", "may/msa", "mal", "mlt", "mnc", "mdr", "man", "mni", "mno", "glv", "mao/mri", "arn", "mar", "chm", "mah", "mwr", "mas", "myn", "men", "mic", "min", "mwl", "moh", "mdf", "rum/ron", "mkh", "lol", "mon", "mos", "mul", "mun", "nqo", "nah", "nau", "nav", "nde", "nbl", "ndo", "nap", "new", "nep", "nia", "nic", "ssa", "niu", "zxx", "nog", "non", "nai", "frr", "sme", "nso", "nor", "nno", "nub", "iii", "nym", "nyn", "nyo", "nzi", "oci", "pro", "oji", "ori", "orm", "osa", "oss", "oto", "pal", "pau", "pli", "pag", "pan", "pap", "paa", "pus", "per/fas", "peo", "phi", "phn", "pon", "pol", "por", "pra", "que", "raj", "rap", "qaa-qtz", "roa", "roh", "rom", "run", "rus", "sal", "sam", "smi", "smo", "sad", "sag", "san", "sat", "srd", "sas", "sco", "sel", "sem", "srp", "srr", "shn", "sna", "scn", "sid", "sgn", "bla", "snd", "sin", "sit", "sio", "sms", "den", "sla", "slo/slk", "slv", "sog", "som", "son", "snk", "wen", "sot", "sai", "alt", "sma", "srn", "suk", "sux", "sun", "sus", "swa", "ssw", "swe", "syr", "tgl", "tah", "tai", "tgk", "tmh", "tam", "tat", "tel", "ter", "tet", "tha", "tib/bod", "tig", "tir", "tem", "tiv", "tli", "tpi", "tkl", "tog", "ton", "tsi", "tso", "tsn", "tum", "tup", "tur", "ota", "tuk", "tvl", "tyv", "twi", "udm", "uga", "uig", "ukr", "umb", "mis", "und", "hsb", "urd", "uzb", "vai", "ven", "vie", "vol", "vot", "wak", "wln", "war", "was", "wel/cym", "fry", "wal", "wol", "xho", "sah", "yao", "yap", "yid", "yor", "ypk", "znd", "zap", "zen", "zul", "zun"]
    },

    "XHR": {
        "PROXY_DISABLED_BUTTON": "settings-xhrproxy-disabled"
    },

    "PLATFORMS": {
        "WAC": {
            "APPLICATIONS": [
                "ALARM",
                "BROWSER",
                "CALCULATOR",
                "CALENDAR",
                "CAMERA",
                "CONTACTS",
                "FILES",
                "GAMES",
                "MAIL",
                "MEDIAPLAYER",
                "MESSAGING",
                "PHONECALL",
                "PICTURES",
                "PROG_MANAGER",
                "SETTINGS",
                "TASKS",
                "WIDGET_MANAGER"
            ],
            "DEVICE": {
                "WIDGET_ENGINE_NAME": "Generic",
                "WIDGET_ENGINE_PROVIDER": "tinyHippos",
                "WIDGET_ENGINE_VERSION": "x.x"
            }
        }
    },

    "POWER_RESOURCE": {
        "SCREEN": {
            "NAME": "SCREEN",
            "STATE": {
                "SCREEN_OFF": {
                    "NAME": "SCREEN_OFF",
                    "MIN": 0,
                    "MAX": 0,
                    "VALUE": 0
                },
                "SCREEN_DIM": {
                    "NAME": "SCREEN_DIM",
                    "MIN": 0,
                    "MAX": 0.2,
                    "VALUE": 0.15
                },
                "SCREEN_NORMAL": {
                    "NAME": "SCREEN_NORMAL",
                    "MIN": 0.2,
                    "MAX": 1,
                    "VALUE": 0.8
                },
                "SCREEN_BRIGHT": {
                    "NAME": "SCREEN_BRIGHT",
                    "MIN": 1,
                    "MAX": 1,
                    "VALUE": 1
                }
            }
        },
        "CPU": {
            "NAME": "CPU",
            "STATE": {
                "CPU_AWAKE": {
                    "NAME": "CPU_AWAKE",
                    "DEFAULT_VALUE" : 0.5
                }
            }
        }
    }
};

});
define('ripple/db', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    _db,
    utils = require('ripple/utils'),
    constants = require('ripple/constants'),
    event = require('ripple/event'),
    _cache = {};

function _validateAndSetPrefix(prefix) {
    if (prefix) {
        utils.validateArgumentType(prefix, "string");
    }

    return prefix || constants.COMMON.PREFIX;
}

function _createKey(key, prefix) {
    return _validateAndSetPrefix(prefix) + key;
}

function _createItem(key, value, prefix) {
    return {
        id: _createKey(key, prefix),
        key: key,
        value: value,
        prefix: _validateAndSetPrefix(prefix)
    };
}

function _save(key, value, prefix, callback) {
    var item = _createItem(key, value, prefix);
    _cache[item.id] = item;

    _db.transaction(function (tx) {
        tx.executeSql('REPLACE INTO persistence (id, key, value, prefix) VALUES (?, ?, ?, ?)', [item.id, item.key, item.value, item.prefix], function () {
            return callback && callback();
        });
    });
}

function _retrieve(key, prefix) {
    var item = _cache[_createKey(key, prefix)];
    return item ? item.value : undefined;
}

function _retrieveAll(prefix, callback) {
    var result = {};

    if (prefix) {
        utils.forEach(_cache, function (value, key) {
            if (value.prefix === prefix) {
                result[value.key] = value.value;
            }
        });
    }

    callback.apply(null, [result]);
}

function _remove(key, prefix, callback) {
    delete _cache[_createKey(key, prefix)];

    _db.transaction(function (tx) {
        tx.executeSql('DELETE FROM persistence WHERE key = ? AND prefix = ?', [key, _validateAndSetPrefix(prefix)], function () {
            return callback && callback();
        });
    });
}

function _removeAll(prefix, callback) {
    utils.forEach(_cache, function (value, key) {
        if (!prefix || key.indexOf(prefix) === 0) {
            delete _cache[key];
        }
    });

    _db.transaction(function (tx) {
        if (prefix) {
            tx.executeSql('DELETE FROM persistence WHERE prefix = ?', [prefix], function () {
                return callback && callback();
            });
        } else {
            tx.executeSql('DELETE FROM persistence', [], function () {
                return callback && callback();
            });
        }
    });
}

_self = {
    save: function (key, value, prefix, callback) {
        _save(key, value, prefix, callback);
        event.trigger("StorageUpdatedEvent");
    },

    saveObject: function (key, obj, prefix, callback) {
        _save(key, JSON.stringify(obj), prefix, callback);
        event.trigger("StorageUpdatedEvent");
    },

    retrieve: function (key, prefix) {
        return _retrieve(key, prefix);
    },

    retrieveObject: function (key, prefix) {
        var retrievedValue = _retrieve(key, prefix);
        return retrievedValue ? JSON.parse(retrievedValue) : retrievedValue;
    },

    retrieveAll: function (prefix, callback) {
        return _retrieveAll(prefix, callback);
    },

    remove: function (key, prefix, callback) {
        event.trigger("StorageUpdatedEvent");
        _remove(key, prefix, callback);
    },

    removeAll: function (prefix, callback) {
        _removeAll(prefix, callback);
        event.trigger("StorageUpdatedEvent");
    },

    initialize: function (previous, baton) {
        baton.take();

        _db = openDatabase('tinyHippos', '1.0', 'tiny Hippos persistence', 2 * 1024 * 1024);
        _db.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS persistence (id unique, key, value, prefix)');

            tx.executeSql('SELECT id, key, value, prefix FROM persistence', [], function (tx, results) {
                var len = results.rows.length, i, item;

                for (i = 0; i < len; i++) {
                    item = results.rows.item(i);
                    _cache[item.id] = item;
                }

                baton.pass();
            });
        });
    }
};

module.exports = _self;

});
define('ripple/dbfs', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    _cache = {},
    _self;

function _get(path) {
    return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
        return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
    }, _cache);
}

function _getInfo(path) {
    var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
        name = parent.splice(parent.length - 1, 1).join(""),
        ext = name.split(".");

    return {
        name: name,
        extension: ext.length > 1 ? ext[ext.length - 1] : "",
        hidden: (name.length > 0 && name[0] === ".") || false,
        parent: parent.join("/") || "/"
    };
}

function _set(path, obj) {
    var parent = _cache,
        tokens = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
        child = tokens.splice(tokens.length - 1, 1).join("");

    tokens.forEach(function (token) {
        parent = parent.children[token];
    });

    parent.children = parent.children || {};
    obj.properties = obj.properties || {};
    parent.children[child] = obj;
}

function _delete(path) {
    var parent = _cache,
        tokens = path.replace(/^\//, '').split("/"),
        child = tokens.splice(tokens.length - 1, 1).join("");

    tokens.forEach(function (token) {
        parent = parent.children[token];
    });

    delete parent.children[child];
}

function _save() {
    db.saveObject("db-filesystem", _cache);
}

_self = {

    initialize: function (prev, baton) {
        _cache = db.retrieveObject("db-filesystem") || {};
        event.trigger("FileSystemInitialized", null, true);
    },

    ls: function (path, success, error) {
        try {
            var dir = _get(path),
                items = [];

            if (dir) {
                utils.forEach(dir.children, function (item) {
                    if (!item.isDirectory) {
                        item.file = function (callback) {
                            callback({});
                        };
                    }
                    items.push(item);
                });
            }
            else {
                items = {};
            }

            success(utils.copy(items));
        }
        catch (e) {
            e.code = 1;
            error(e);
        }
    },

    rm: function (path, success, error, options) {
        _delete(path);
        _save();
        success();
    },

    rmdir: function (path, success, error, options) {
        _delete(path);
        _save();
        success();
    },

    mkdir: function (path, success, error) {
        var entry = _get(path),
            info = _getInfo(path);

        if (!entry) {
            _set(path, {
                name: info.name,
                isDirectory: true,
                fullPath: path
            });
            entry = _get(path);
        }
        
        _save();
        if (entry) {
            success(utils.copy(entry));
        }
        else {
            error({code: 1});
        }
    },

    mv: function (from, to, success, error) {
        try {
            var fromEntry = _get(from),
                toInfo = _getInfo(to);

            fromEntry.fullPath = to;
            fromEntry.name = toInfo.name;

            _set(to, fromEntry);
            _delete(from);
            _save();
            success(utils.copy(_get(to)));
        }
        catch (e) {
            e.code = 1;
            error(e);
        }
    },

    touch: function (path, success, error) {
        if (!_get(path)) {
            _set(path, {
                fullPath: path
            });
        }
        _save();
        success(utils.copy(_get(path)));
    },

    cp: function (from, to, success, error) {
        try {
            var fromEntry = _get(from);
            fromEntry.fullPath = to;
            _set(to, fromEntry);
            _save();
            success(utils.copy(_get(to)));
        }
        catch (e) {
            e.code = 1;
            error(e);
        }
    },

    stat: function (path, success, error) {
        var entry = _get(path);
        success(utils.copy(entry));
    },

    write: function (path, contents, success, error, options) {
        var info = _getInfo(path);

        _set(path, {
            lastModifiedDate: new Date(),
            name: info.name,
            fullPath: path,
            isDirectory: false,
            properties: {
                type: "",
                size: contents.size
            },
            data: contents,
            file: function (callback) {
                callback({});
            }
        });

        success(utils.copy(_get(path)));
    },

    read: function (path, success, error) {
        var entry = _get(path);

        if (entry) {
            success(utils.copy(entry.data));
        }
        else {
            error({code: 1});
        }
    }
};

module.exports = _self;

});
define('ripple/deviceMotionEmulator', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    platform = require('ripple/platform'),
    INTERVAL = 60000,
    _self;

function _bind(name, win) {
    var callback = null;

    win.__defineGetter__(name, function () {
        return callback;
    });

    win.__defineSetter__(name, function (cb) {
        callback = cb;
    });

    return {
        get: function () {
            return callback;
        },
        set: function (value) {
            callback = value;
        },
        exec: function (arg) {
            return callback && callback(arg);
        },
        unbind: function (cb) {
            callback = cb === callback ? null : callback;
        }
    };
}

_self = {
    init: function (win, doc) {
        var widgetWindow = win,
            _motion,
            _orientation,
            _calibration,
            add = widgetWindow.addEventListener,
            remove = widgetWindow.removeEventListener;

        //Hang events off window (these are used to check for API existence by developer)
        widgetWindow.DeviceMotionEvent = function DeviceMotionEvent() {};
        widgetWindow.DeviceOrientationEvent = function DeviceOrientationEvent() {};

        _motion = _bind("ondevicemotion", widgetWindow);
        _orientation = _bind("ondeviceorientation", widgetWindow);
        _calibration = _bind("oncompassneedscalibration", widgetWindow);

        widgetWindow.addEventListener = function (e, callback, useCapture) {
            switch (e) {
            case "deviceorientation":
                _orientation.set(callback);
                event.trigger("DeviceOrientationEventAddedEvent");
                break;
            case "devicemotion":
                _motion.set(callback);
                event.trigger("DeviceMotionEventAddedEvent");
                break;
            case "compassneedscalibration":
                _calibration.set(callback);
                break;

            default:
                add.apply(widgetWindow, arguments);
                break;
            }
        };

        widgetWindow.removeEventListener = function (event, callback) {
            _motion.unbind(callback);
            _orientation.unbind(callback);
            _calibration.unbind(callback);
            remove.apply(widgetWindow, arguments);
        };

        event.on("DeviceMotionEvent", function (motion) {
            var _motionEvent, DeviceMotionEvent;

            if (platform.current().DeviceMotionEvent) {
                DeviceMotionEvent = platform.current().DeviceMotionEvent;
                if (typeof DeviceMotionEvent !== "function")
                    return;

                _motionEvent = new DeviceMotionEvent();
                _motionEvent.initAccelerometerEvent("devicemotion", true, false, motion.acceleration, motion.accelerationIncludingGravity, 
                                                    motion.rotationRate, INTERVAL);    
            }
            else {
                _motionEvent = {
                    acceleration: motion.acceleration,
                    accelerationIncludingGravity: motion.accelerationIncludingGravity,
                    rotationRate: motion.rotationRate
                };
            }

            _motion.exec(_motionEvent);
        });

        event.on("DeviceOrientationEvent", function (motion) {
            var _orientationEvent, DeviceOrientationEvent;

            if (platform.current().DeviceOrientationEvent) {
                DeviceOrientationEvent = platform.current().DeviceOrientationEvent;
                if (typeof DeviceOrientationEvent !== "function")
                    return;

                _orientationEvent = new DeviceOrientationEvent();        
                _orientationEvent.initDeviceOrientationEvent("deviceorientation", true, false, motion.orientation.alpha, 
                                                              motion.orientation.beta, motion.orientation.gamma, true);
            }
            else {
                _orientationEvent = motion.orientation;
            }

            _orientation.exec(_orientationEvent);
        });
    }
};

module.exports = _self;

});
define('ripple/deviceSettings', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
/* DeviceSettings
 *  A per object store for a platform's settings.
 *  For example, RadioInfo object in WAC has isRadioEnabled that can be true/false
 *  setting => {key: {key1: "test"}}
 */
var _PERSISTENCE_KEY = "devicesettings",
    db = require('ripple/db'),
    platform = require('ripple/platform'),
    _currentDeviceSettings = {},
    _self;

function _default(key) {
    var keys = key.split("."),
        defaults = platform.current().device;
    if (keys.length === 1)
        return defaults[key];
    return keys.length === 2 &&
           defaults[keys[0]] &&
           defaults[keys[0]][keys[1]] &&
           defaults[keys[0]][keys[1]].control ?
           defaults[keys[0]][keys[1]].control.value : undefined;
}

_self = {
    initialize: function () {
        // TODO: remove deprecated DeviceSettings from persisted ones.
        _currentDeviceSettings = db.retrieveObject(_PERSISTENCE_KEY) || {};
    },
    register: function (key, obj) {
        _currentDeviceSettings[key] = obj;
    },

    persist: function (key, obj) {
        if (key) {
            _currentDeviceSettings[key] = obj;
        }
        db.saveObject(_PERSISTENCE_KEY, _currentDeviceSettings);
    },

    retrieve: function (key) {
        return _currentDeviceSettings.hasOwnProperty(key) ?
               _currentDeviceSettings[key] : _default(key);
    },

    retrieveAsInt: function (key) {
        return parseInt(_self.retrieve(key), 10);
    },

    retrieveAsBoolean: function (key) {
        return !!_self.retrieve(key);
    }
};

module.exports = _self;

});
define('ripple/devices/Bold9700', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Bold9700",
    "name": "BlackBerry Bold 9700",
    "model": "9700",
    "osName": "BlackBerry OS",
    "uuid": "42",
    "osVersion": "6",
    "manufacturer": "Research In Motion",

    "skin": "Bold9700",

    "capabilities": [
        "location.gps",
        "location.maps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "storage.memorycard",
        "network.bluetooth",
        "network.wlan",
        "network.3gpp"
    ],

    "screen": {
        "width": 480,
        "height": 360
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 360,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 245.00,
    "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9700; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1",
    "platforms": ["web", "phonegap", "webworks.handset", "cordova"]
};

});
define('ripple/devices/Bold9900', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Bold9900",
    "name": "BlackBerry Bold 9900",
    "model": "9900",
    "osName": "BlackBerry OS",
    "uuid": "42",
    "osVersion": "7",
    "manufacturer": "Research In Motion",

    "skin": "Bold9900",

    "capabilities": [
        "input.touch",
        "location.gps",
        "location.maps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "storage.memorycard",
        "network.bluetooth",
        "network.wlan",
        "network.3gpp"
    ],

    "screen": {
        "width": 640,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 640,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 287.00,
    "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.141 Mobile Safari/534.1",
    "platforms": ["web", "phonegap", "webworks.handset", "cordova"]
};

});
define('ripple/devices/Colt', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Colt",
    "name": "BlackBerry 10 Dev Alpha",
    "model": "Colt",
    "osName": "BlackBerry",
    "uuid": "42",
    "osVersion": "10.0.6.99",
    "manufacturer": "Research In Motion",
    "hardwareId": "0x8500240a",

    "skin": "Colt",

    "capabilities": [
        "input.touch",
        "location.gps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "network.bluetooth",
        "network.wlan"
    ],

    "screen": {
        "width": 768,
        "height": 1280
    },
    "viewPort": {
        "portrait": {
            "width": 768,
            "height": 1280,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 1280,
            "height": 768,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "defaultOrientation": "portrait",

    "ppi": 355,
    "userAgent": "Mozilla/5.0 (BlackBerry) AppleWebKit/536.2+ (KHTML, like Gecko) Version/10.0.4.182 Mobile Safari/536.2+",
    "platforms": ["web", "webworks.bb10", "cordova"]
};

});
define('ripple/devices/Curve9300', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Curve9300",
    "name": "BlackBerry Curve 9300",
    "model": "9300",
    "osName": "BlackBerry OS",
    "uuid": "42",
    "osVersion": "6",
    "manufacturer": "Research In Motion",

    "skin": "Curve9300",

    "capabilities": [
        "location.gps",
        "location.maps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "storage.memorycard",
        "network.bluetooth",
        "network.wlan",
        "network.3gpp"
    ],

    "screen": {
        "width": 320,
        "height": 240
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 240,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 163,
    "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9300; en) AppleWebKit/534.3+ (KHTML, like Gecko) Version/6.0.0.286 Mobile Safari/534.3+",
    "platforms": ["web", "phonegap", "webworks.handset"]
};

});
define('ripple/devices/Curve9350-9360-9370', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Curve9350-9360-9370",
    "name": "BlackBerry Curve 9350/9360/9370",
    "model": "9350-9360-9370",
    "osName": "BlackBerry OS",
    "uuid": "42",
    "osVersion": "7",
    "manufacturer": "Research In Motion",

    "skin": "Curve9350-9360-9370",

    "capabilities": [
        "location.gps",
        "location.maps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "storage.memorycard",
        "network.bluetooth",
        "network.wlan",
        "network.3gpp"
    ],

    "screen": {
        "width": 480,
        "height": 360
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 360,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 246.00,
    "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9350; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.0 Mobile Safari/534.1",
    "platforms": ["web", "phonegap", "webworks.handset"]
};

});
define('ripple/devices/FWVGA', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "group": "Generic Devices",

    "id": "FWVGA",
    "name": "Generic - FWVGA (480x854)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Generic",
    "model": "Generic",
    "uuid": "42",

    "screen": {
        "width": 480,
        "height": 854
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 854,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 854,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 96,
    "platforms": ["web", "phonegap", "cordova"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/G1', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "G1",
    "name": "HTC G1",
    "model": "G1",
    "osName": "Android",
    "osVersion": "1.6",
    "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",
    "manufacturer": "HTC",

    "screen": {
        "width": 320,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 180.28,
    "platforms": ["web", "phonegap"],
    "userAgent": "Mozilla/5.0 (Linux; U; Android 1.0; en-us; dream) AppleWebKit/525.10+ (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2",

    "notes": {
        "1": "<a href=\"http://www.htc.com/www/product/g1/specification.html\" target=\"_blank\">Specs</a>"
    }
};

});
define('ripple/devices/HD', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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.
 */

module.exports = {
    "id": "HD",
    "name": "HD (720x1280)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Generic",
    "model": "Generic",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 720,
        "height": 1280
    },
    "viewPort": {
        "portrait": {
            "width": 720,
            "height": 1280,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 1280,
            "height": 720,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "browser": ["Generic"],
    "platforms": ["wac", "web", "phonegap", "tizen", "cordova"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/HPPre3', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "HPPre3",
    "name": "HP Pre 3",
    "manufacturer": "HP",
    "model": "Pre",
    "osName": "WebOS",
    "osVersion": "2.x",

    "screen": {
        "width": 480,
        "height": 800
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 800,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 800,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 260,
    // TODO :: not exactly the correct userAgent webkit version is probably different
    "userAgent": "Mozilla/5.0 (webOS/2.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/2.0",
    "platforms": ["web", "phonegap"],

    "notes": {
        "1": "<a href=\"http://www.palm.com/us/products/phones/pre3/index.html\" target=\"_blank\">Specs</a>"
    }
};

});
define('ripple/devices/HPVeer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "HPVeer",
    "name": "HP Veer",
    "manufacturer": "HP",
    "model": "Veer",
    "osName": "WebOS",
    "osVersion": "2.x",

    "screen": {
        "width": 320,
        "height": 400
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 400,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 400,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 197,
    // TODO :: not exactly the correct userAgent webkit version is probably different
    "userAgent": "Mozilla/5.0 (webOS/2.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/2.0",
    "platforms": ["web", "phonegap"],

    "notes": {
        "1": "<a href=\"http://www.palm.com/us/products/phones/veer/index.html\" target=\"_blank\">Specs</a>"
    }
};

});
define('ripple/devices/HVGA', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "group": "Generic Devices",

    "id": "HVGA",
    "name": "HVGA (320x480)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Generic",
    "model": "Generic",
    "uuid": "42",

    "screen": {
        "width": 320,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "platforms": ["wac", "web", "phonegap", "tizen", "cordova"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/IVI-HD', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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.
 */

module.exports = {
    "id": "IVI-HD",
    "name": "IVI HD (800x480)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Tizen",
    "model": "Generic",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 800,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 1024,
            "height": 640,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 640,
            "height": 1024,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "browser": ["Generic"],
    "platforms": ["ivi"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/Legend', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "Legend",
    "name": "HTC Legend",
    "osName": "Android",
    "osVersion": "1.6",
    "manufacturer": "HTC",
    "model": "Legend",
    "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",

    "screen": {
        "width": 320,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 180.3,
    "userAgent": "Mozilla/5.0 (Linux; U; Android 2.1; fr-fr; HTC Legend 1.32.163.1 Build/ERD79) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17",
    "platforms": ["web", "phonegap"]
};

});
define('ripple/devices/Nexus', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "Nexus",
    "name": "Nexus One",
    "manufacturer": "HTC",
    "model": "Nexux One",
    "osName": "Android",
    "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",
    "osVersion": "2.x.x",

    "screen": {
        "width": 480,
        "height": 800
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 800,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 800,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 252.15,
    "userAgent": "Mozilla/5.0 (Linux; U; Android 2.1; en-us; Nexus One Build/ERD62) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17",
    "platforms": ["web", "phonegap"],

    "notes": {
        "1": "<a href=\"http://www.google.com/phone/static/en_US-nexusone_tech_specs.html\" target=\"_blank\">Specs</a>"
    }
};

});
define('ripple/devices/Nexus7', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id" : "Nexus7",
    "name": "Nexus 7 (Tablet)",
    "manufacturer": "Asus",
    "model": "Nexus 7 8/16 GB",
    "osName": "Android",
    "uuid" : "903802EA-1786-4175-B0F1-1FDF87813CAA",
    "osVersion": "4.x.x",

    "screen": {
        "width": 800,
        "height": 1280
    },
    "viewPort": {
        "portrait": {
            "width": 800,
            "height": 1280,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 1280,
            "height": 800,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 215,
    "userAgent": "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19",
    "platforms": ["web", "phonegap", "cordova"],

    "notes": {
        "1": "<a href=\"http://www.google.com/nexus/#/7/specs\" target=\"_blank\">Specs</a>"
    }

};

});
define('ripple/devices/NexusGalaxy', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id" : "NexusGalaxy",
    "name": "Nexus (Galaxy)",
    "manufacturer": "Samsung",
    "model": "Galaxy Nexus (generic)",
    "osName": "Android",
    "uuid" : "3D0AD03B-8B46-431A-BEF5-FF01B96BA990",
    "osVersion": "4.x.x",

    "screen": {
        "width": 720,
        "height": 1280
    },
    "viewPort": {
        "portrait": {
            "width": 720,
            "height": 1280,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 1280,
            "height": 720,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 315,
    "userAgent": "Mozilla/5.0 (Linux; Android 4.0.1; Galaxy Nexus Build/ITL41F) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
    "platforms": ["web", "phonegap", "cordova"],

    "notes": {
        "1": "<a href=\"http://www.google.com/nexus/#/tech-specs\" target=\"_blank\">Specs</a>"
    }

};

});
define('ripple/devices/NexusS', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id" : "NexusS",
    "name": "Nexus S",
    "manufacturer": "Samsung",
    "model": "Nexux S",
    "osName": "Android",
    "uuid" : "F54E13F1-C1B7-4212-BFA8-AB3C9C3F088F",
    "osVersion": "2.3.x",

    "screen": {
        "width": 480,
        "height": 800
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 800,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 800,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 235,
    "userAgent": "Mozilla/5.0 (Linux; U; Android 2.3.2; en-us; Nexus S Build/GRH78C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
    "platforms": ["web", "phonegap", "cordova"],

    "notes": {
        "1": "<a href=\"http://www.google.com/nexus/#/tech-specs\" target=\"_blank\">Specs</a>"
    }

};

});
define('ripple/devices/NokiaN8', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "NokiaN8",
    "name": "Nokia N8",
    "model": "N8",
    "osName": "SymbianOS",
    "uuid": "42",
    "osVersion": "3",
    "manufacturer": "Nokia",

    "screen": {
        "width": 360,
        "height": 640
    },
    "viewPort": {
        "portrait": {
            "width": 360,
            "height": 640,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 640,
            "height": 360,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 209.8,
    "userAgent": "(Symbian/3; S60/5.2 Mozilla/5.0; NokiaN8-00/10.0.000; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.2",
    "platforms": ["web", "phonegap"],

    "notes": {
        "1": "<a href=\"http://www.forum.nokia.com/Devices/Device_specifications/N8-00/\" target=\"_blank\">Specs</a>"
    }
};

});
define('ripple/devices/NokiaN97', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "NokiaN97",
    "name": "Nokia N97/5800 (touch)",
    "manufacturer": "Nokia",
    "model": "N97",
    "osName": "S60",
    "osVersion": "v5",
    "uuid": "42",

    "screen": {
        "width": 360,
        "height": 640
    },
    "viewPort": {
        "portrait": {
            "width": 360,
            "height": 640,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 640,
            "height": 360,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 232,
    "userAgent": "?",
    "platforms": ["web", "phonegap"]
};

});
define('ripple/devices/PalmPre', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "PalmPre",
    "name": "Palm Pre",
    "manufacturer": "Palm",
    "model": "Pre",
    "osName": "WebOS",
    "osVersion": "1.x",

    "screen": {
        "width": 320,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 186.09,
    "userAgent": "Mozilla/5.0 (webOS/1.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/1.0",
    "platforms": ["web", "phonegap"],

    "notes": {
        "1": "<a href=\"http://www.palm.com/us/products/phones/pre/#tab2\" target=\"_blank\">Specs</a>"
    }
};

});
define('ripple/devices/PalmPre2', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "PalmPre2",
    "name": "Palm Pre 2",
    "manufacturer": "Palm",
    "model": "Pre",
    "osName": "WebOS",
    "osVersion": "2.x",

    "screen": {
        "width": 320,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 186.09,
    // TODO :: not exactly the correct userAgent webkit version is probably different
    "userAgent": "Mozilla/5.0 (webOS/2.0; U; en-US) AppleWebKit/525.27.1 (KHTML, like Gecko) Version/1.0 Safari/525.27.1 Pre/2.0",
    "platforms": ["web", "phonegap"],

    "notes": {
        "1": "<a href=\"http://www.palm.com/us/products/phones/pre2/#tab2\" target=\"_blank\">Specs</a>"
    }
};

});
define('ripple/devices/Pearl9100', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Pearl9100",
    "name": "BlackBerry Pearl 9100",
    "model": "9100",
    "osName": "BlackBerry OS",
    "uuid": "42",
    "osVersion": "6",
    "manufacturer": "Research In Motion",

    "skin": "Pearl9100",

    "capabilities": [
        "input.keyboard.issuretype",
        "location.gps",
        "location.maps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "storage.memorycard",
        "network.bluetooth",
        "network.wlan",
        "network.3gpp"
    ],

    "screen": {
        "width": 360,
        "height": 400
    },
    "viewPort": {
        "portrait": {
            "width": 360,
            "height": 400,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 239,
    "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9100; en) AppleWebKit/534.3+ (KHTML, like Gecko) Version/6.0.0.286 Mobile Safari/534.3+",
    "platforms": ["web", "phonegap", "webworks.handset"]
};

});
define('ripple/devices/Playbook', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Playbook",
    "name": "BlackBerry Playbook",
    "model": "100669958",
    "osName": "BlackBerry PlayBook OS",
    "uuid": "42",
    "osVersion": "BlackBerry PlayBook OS",
    "manufacturer": "Research In Motion",

    "skin": "Playbook",

    "capabilities": [
        "input.touch",
        "location.gps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "network.bluetooth",
        "network.wlan"
    ],

    "screen": {
        "width": 1024,
        "height": 600
    },
    "viewPort": {
        "portrait": {
            "width": 1024,
            "height": 600,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 600,
            "height": 1024,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "defaultOrientation": "landscape",

    "ppi": 169.55,
    "userAgent": "Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML, like Gecko) Version/7.2.1.0 Safari/536.2+",
    "platforms": ["web", "webworks.tablet", "phonegap", "cordova"]
};

});
define('ripple/devices/QVGA', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "QVGA",
    "name": "Generic - QVGA (240X320)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Generic",
    "model": "Generic",
    "uuid": "42",

    "screen": {
        "width": 240,
        "height": 320
    },
    "viewPort": {
        "portrait": {
            "width": 240,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 320,
            "height": 240,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 96,
    "platforms": ["web", "phonegap", "cordova", "tizen"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/Style9670', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Style9670",
    "name": "BlackBerry Style 9670",
    "model": "9670",
    "osName": "BlackBerry OS",
    "uuid": "42",
    "osVersion": "6",
    "manufacturer": "Research In Motion",

    "skin": "Style9670",

    "capabilities": [
        "location.gps",
        "location.maps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "storage.memorycard",
        "network.bluetooth",
        "network.wlan",
        "network.3gpp"
    ],

    "screen": {
        "width": 360,
        "height": 400
    },
    "viewPort": {
        "portrait": {
            "width": 360,
            "height": 400,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 200,
    "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9670; en) AppleWebKit/534.3+ (KHTML, like Gecko) Version/6.0.0.286 Mobile Safari/534.3+",
    "platforms": ["web", "phonegap", "webworks.handset"]
};

});
define('ripple/devices/TV-HD', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation
 *
 * 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 requWEBAPIS-HD.jsired 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.
 */

module.exports = {
    "id": "TV-HD",
    "name": "TV HD (1280x720)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Tizen",
    "model": "Generic",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 1280,
        "height": 720
    },
    "viewPort": {
        "portrait": {
            "width": 1280,
            "height": 720,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 1280,
            "height": 720,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "browser": ["Generic"],
    "platforms": ["tv"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/Tattoo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "Tattoo",
    "name": "HTC Tattoo",
    "manufacturer": "HTC",
    "model": "Tattoo",
    "osVersion": "1.6",
    "uuid": "6F196F23-FD0D-4F62-B27B-730147FCC5A3",
    "osName": "Android",

    "screen": {
        "width": 240,
        "height": 320
    },
    "viewPort": {
        "portrait": {
            "width": 240,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 142.9,
    "userAgent": "Mozilla/5.0 (Linux; U; Android 1.6; en-us; HTC_TATTOO_A3288 Build/DRC79) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1",
    "platforms": ["web", "phonegap"]
};

});
define('ripple/devices/Torch9800', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Torch9800",
    "name": "BlackBerry Torch 9800",
    "model": "9800",
    "osName": "BlackBerry OS",
    "uuid": "42",
    "osVersion": "6",
    "manufacturer": "Research In Motion",

    "skin": "Torch9800",

    "capabilities": [
        "input.touch",
        "location.gps",
        "location.maps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "storage.memorycard",
        "network.bluetooth",
        "network.wlan",
        "network.3gpp"
    ],

    "screen": {
        "width": 360,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 360,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 360,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 188.68,
    "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/6.0.0.141 Mobile Safari/534.1",
    "platforms": ["web", "phonegap", "webworks.handset"]
};

});
define('ripple/devices/Torch9810', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Torch9810",
    "name": "BlackBerry Torch 9810",
    "model": "9810",
    "osName": "BlackBerry OS",
    "uuid": "42",
    "osVersion": "7",
    "manufacturer": "Research In Motion",

    "skin": "Torch9810",

    "capabilities": [
        "input.touch",
        "location.gps",
        "location.maps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "storage.memorycard",
        "network.bluetooth",
        "network.wlan",
        "network.3gpp"
    ],

    "screen": {
        "width": 480,
        "height": 640
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 640,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 640,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 253,
    "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9810; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.0 Mobile Safari/534.1",
    "platforms": ["web", "phonegap", "webworks.handset"]
};

});
define('ripple/devices/Torch9860-9850', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "Torch9860-9850",
    "name": "BlackBerry Torch 9860/9850",
    "model": "9860-9850",
    "osName": "BlackBerry OS",
    "uuid": "42",
    "osVersion": "7",
    "manufacturer": "Research In Motion",

    "skin": "Torch9860-9850",

    "capabilities": [
        "input.touch",
        "location.gps",
        "location.maps",
        "media.audio.capture",
        "media.video.capture",
        "media.recording",
        "storage.memorycard",
        "network.bluetooth",
        "network.wlan",
        "network.3gpp"
    ],

    "screen": {
        "width": 480,
        "height": 800
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 800,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 800,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 253,
    "userAgent": "Mozilla/5.0 (BlackBerry; U; BlackBerry 9860; en) AppleWebKit/534.1+ (KHTML, Like Gecko) Version/7.0.0.0 Mobile Safari/534.1",
    "platforms": ["web", "phonegap", "webworks.handset"]
};

});
define('ripple/devices/WQVGA', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "WQVGA",
    "name": "Generic - WQVGA (240x480)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Generic",
    "model": "Generic",
    "uuid": "42",

    "screen": {
        "width": 240,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 240,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 240,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 96,
    "browser": ["Generic"],
    "platforms": ["web", "phonegap", "tizen"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/WSVGA', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "WSVGA",
    "name": "WSVGA (600x1024)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Generic",
    "model": "Generic",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 600,
        "height": 1024
    },
    "viewPort": {
        "portrait": {
            "width": 600,
            "height": 1024,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 1024,
            "height": 600,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "browser": ["Generic"],
    "platforms": ["wac", "web", "phonegap", "tizen", "cordova"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/WVGA', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "WVGA",
    "name": "WVGA (480x800)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Generic",
    "model": "Generic",
    "uuid": "42",

    "screen": {
        "width": 480,
        "height": 800
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 800,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 800,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "browser": ["Generic"],
    "platforms": ["web", "phonegap", "tizen", "cordova"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/Wave', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "Wave",
    "name": "Samsung Wave",
    "manufacturer": "Samsung",
    "model": "Wave",
    "osName": "Bada",
    "osVersion": "n/a",

    "screen": {
        "width": 480,
        "height": 800
    },
    "viewPort": {
        "portrait": {
            "width": 480,
            "height": 800,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 800,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 283,
    "userAgent": "?",
    "platforms": ["web"]
};

});
define('ripple/devices/Wearable-HD', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation
 *
 * 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.
 */

module.exports = {
    "id": "Wearable-HD",
    "name": "Wearable (320X320)",
    "osName": "Tizen",
    "osVersion": "2.2.1",
    "manufacturer": "Samsung",
    "model": "SM-R380",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 320,
        "height": 320
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 320,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "browser": ["Generic"],
    "platforms": ["wearable"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/Wearable-S', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation
 *
 * 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.
 */

module.exports = {
    "id": "Wearable-S",
    "name": "Wearable (360X480)",
    "osName": "Tizen",
    "osVersion": "2.2.1",
    "manufacturer": "Samsung",
    "model": "SM-R710",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 360,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 360,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 360,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 300,
    "browser": ["Generic"],
    "platforms": ["wearable"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/Wearable-O', function (require, exports, module) {
/*
 *  Copyright 2015 Samsung Electronics Corporation
 *
 * 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.
 */

module.exports = {
    "id": "Wearable-O",
    "name": "Wearable (360X360)",
    "osName": "Tizen",
    "osVersion": "2.3",
    "manufacturer": "Samsung",
    "model": "SM-R720",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 360,
        "height": 360
    },
    "viewPort": {
        "portrait": {
            "width": 360,
            "height": 360,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 360,
            "height": 360,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 300,
    "browser": ["Generic"],
    "platforms": ["wearable"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/custom', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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.
 */

module.exports = {
    "id": "CUSTOM",
    "name": "Custom",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Generic",
    "model": "Generic",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 600,
        "height": 800
    },
    "viewPort": {
        "portrait": {
            "width": 600,
            "height": 800,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 600,
            "height": 800,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "browser": ["Generic"],
    "platforms": [],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices/iPad', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "iPad",
    "name": "iPad",
    "model": "iPad",
    "osName": "iOS",
    "uuid": "e0101010d38bde8e6740011221af335301010333",
    "osVersion": "1.6",
    "manufacturer": "Apple",

    "screen": {
        "width": 768,
        "height": 1024
    },
    "viewPort": {
        "portrait": {
            "width": 768,
            "height": 1024,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 1024,
            "height": 768,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 132,
    "userAgent": "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B367 Safari/531.21.10",
    "platforms": ["web", "phonegap", "cordova"],

    "notes": {
        "1": "<a href=\"http://www.apple.com/ipad/specs/\" target=\"_blank\">Specs</a>"
    }
};

});
define('ripple/devices/iPhone3', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    "id": "iPhone3",
    "name": "iPhone 3G/3Gs/4/4s",
    "model": "3G",
    "osName": "iPhone",
    "osVersion": "3",
    "uuid": "e0101010d38bde8e6740011221af335301010333",
    "manufacturer": "Apple",

    "screen": {
        "width": 320,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 164.8,
    "userAgent": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3",
    "platforms": ["web", "phonegap", "cordova"]
};

});
define('ripple/devices/tizen-HD', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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.
 */

module.exports = {
    "id": "tizen-HD",
    "name": "Tizen HD (720x1280)",
    "osName": "Tizen",
    "osVersion": "2.3",
    "manufacturer": "Samsung",
    "model": "SM-Z910F",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 720,
        "height": 1280
    },
    "viewPort": {
        "portrait": {
            "width": 360,
            "height": 640,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 640,
            "height": 360,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "browser": ["Generic"],
    "platforms": ["wac", "web", "phonegap", "tizen", "cordova"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});

define('ripple/devices/tizen-HVGA', function (require, exports, module) {
/*
 *  Copyright 2014 Samsung Corporation
 *
 * 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.
 */

module.exports = {
    "id": "tizen-HVGA",
    "name": "Tizen HVGA (320x480)",
    "osName": "Generic",
    "osVersion": "Generic",
    "manufacturer": "Tizen",
    "model": "Generic",
    "uuid": "42",
    "firmware": "Generic",

    "screen": {
        "width": 320,
        "height": 480
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 480,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 480,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 96,
    "browser": ["Generic"],
    "platforms": ["wac", "web", "phonegap", "tizen", "cordova"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});

define('ripple/devices/tizen-WVGA', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    "id": "tizen-WVGA",
    "name": "Tizen WVGA (480x800)",
    "osName": "Tizen",
    "osVersion": "2.3",
    "manufacturer": "Samsung",
    "model": "SM-Z130H",
    "uuid": "42",

    "screen": {
        "width": 480,
        "height": 800
    },
    "viewPort": {
        "portrait": {
            "width": 320,
            "height": 534,
            "paddingTop": 0,
            "paddingLeft": 0
        },
        "landscape": {
            "width": 534,
            "height": 320,
            "paddingTop": 0,
            "paddingLeft": 0
        }
    },

    "ppi": 316,
    "browser": ["Generic"],
    "platforms": ["web", "phonegap", "tizen", "cordova"],
    "userAgent": "Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.7 Safari/533.2"
};

});
define('ripple/devices', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    db = require('ripple/db'),
    utils = require('ripple/utils'),
    platform = require('ripple/platform'),
    event = require('ripple/event'),
    _devices = {};

event.on("HardwareKeyDefault", function (key) {
    if (key === 0 || key === "0") { //back button key
        require('ripple/emulatorBridge').window().history.back();
    }
});

_self = module.exports = {
    initialize: function () {
        _devices = [
/* 
           "Bold9700",
            "Bold9900",
            "Colt",
            "Curve9300",
            "Curve9350-9360-9370",
            "FWVGA",
            "G1",
            "IVI-HD",
            "TV-HD",
            "tizen-WVGA",
            "HPPre3",
            "HPVeer",
            "HVGA",
            "iPad",
            "iPhone3",
            "Legend",
            "Nexus",
            "NexusS",
            "NexusGalaxy",
            "Nexus7",
            "NokiaN8",
            "NokiaN97",
            "PalmPre",
            "PalmPre2",
            "Pearl9100",
            "Playbook",
            "QVGA",
            "Style9670",
            "Tattoo",
            "Torch9800",
            "Torch9810",
            "Torch9860-9850",
            "Wave",
            "WQVGA",
            "WSVGA",
            "WVGA",
            "HD",
            "tizen-HVGA"
*/          "tizen-WVGA",
	    "tizen-HD",
	    "Wearable-HD",
	    "Wearable-S",
	    "Wearable-O",
            "custom"
        ].reduce(function (hash, deviceID) {
            hash[deviceID] = require('ripple/devices/' + deviceID);
            return hash;
        }, {});

        var current = this.getCurrentDevice();
        require('ripple/bus').send('userAgent', current.userAgent);
    },

    getCurrentDevice: function () {
        var deviceId = db.retrieve("device-key"),
            device = this.getDevice(deviceId),
            platformId = platform.current().id,
            does = function (device) {
                return {
                    include: function (platformId) {
                        return device.platforms.some(function (id) {
                            return platformId === id;
                        });
                    }
                };
            };

        if (deviceId !== "custom" && (!device || !does(device).include(platformId))) {
            deviceId = utils.reduce(_devices, function (current, device, id) {
                return does(device).include(platformId) ? id : current;
            });
            device = this.getDevice(deviceId);
        }

        return device;
    },

    getDevice: function (deviceId) {
        var device, width, height, viewportWidth, viewportHeight, layout, viewportTag, ratio;

        device = _devices[deviceId] ? utils.copy(_devices[deviceId]) : null;
        width = db.retrieve("custom_width") || 600;
        height = db.retrieve("custom_height") || 800;
        viewportTag = db.retrieveObject("viewportTag");
        layout = db.retrieve("layout") || "portrait" ;

        if (deviceId === undefined)
            return null;
        width =  parseInt(width, 10);
        height =  parseInt(height, 10);

        if (viewportTag !== undefined) {
            if (viewportTag['width'] !== undefined) {
                if (viewportTag['width'] === "device-width") {
                    viewportWidth = device.viewPort[layout].width;
                } else if (viewportTag['width'] === "device-height") {
                    viewportWidth = device.viewPort[layout].height;
                }
                else {
                    viewportWidth = parseInt(viewportTag['width'], 10);
                    if (isNaN(viewportWidth)) {
                        viewportWidth = device.viewPort[layout].width;
                    }
                }
                db.saveObject("viewport_width", viewportWidth);

                if (layout === "portrait") {
                    if (deviceId !== "custom") {
                        ratio = device.screen.height / device.screen.width;
                    } else {
                        ratio = height / width;
                    }
                    viewportHeight = viewportWidth * ratio;
                    db.saveObject("viewport_height", viewportHeight);
                } else {
                    if (deviceId !== "custom") {
                        ratio = device.screen.width / device.screen.height;
                    } else {
                        ratio = width / height;
                    }
                    viewportHeight = viewportWidth * ratio;
                    db.saveObject("viewport_height", viewportHeight);
                }
            } else if(viewportTag['height'] !== undefined) {
                if (viewportTag['height'] === "device-height") {
                    viewportHeight = device.viewPort[layout].height;
                } else if (viewportTag['height'] === "device-width") {
                    viewportHeight = device.viewPort[layout].width;
                }
                else {
                    viewportHeight = parseInt(viewportTag['height'], 10);
                    if (isNaN(viewportHeight)) {
                        viewportHeight = device.viewPort[layout].height;
                    }
                }
                db.saveObject("viewport_height", viewportHeight);

                if (layout === "portrait") {
                    if (deviceId !== "custom") {
                        ratio = device.screen.height / device.screen.width;
                    } else {
                        ratio = height / width;
                    }
                    viewportWidth = viewportHeight / ratio;
                    db.saveObject("viewport_width", viewportWidth);
                } else {
                    if (deviceId !== "custom") {
                        ratio = device.screen.width / device.screen.height;
                    } else {
                        ratio = width / height;
                    }
                    viewportWidth = viewportHeight / ratio;
                    db.saveObject("viewport_width", viewportWidth);
                }
            }
        }

        if (viewportWidth === undefined) {
            if (deviceId === "custom") {
                viewportWidth = width;
            } else {
                viewportWidth = device.viewPort[layout].width;
            }
        }

        if (viewportHeight === undefined) {
            if (deviceId === "custom") {
                viewportHeight = height;
            } else {
                viewportHeight = device.viewPort[layout].height;
            }
        }

        $('#resolution-custom-width').val(width);
        $('#resolution-custom-height').val(height);

        if (deviceId === "custom") {
            device.screen.width = width;
            device.screen.height = height;
            $('input:radio[name="resolution-type"][value="custom"]').click();
        }

        if (layout === "portrait") {
            device.viewPort.portrait.width = viewportWidth;
            device.viewPort.portrait.height = viewportHeight;
            device.viewPort.landscape.width = viewportHeight;
            device.viewPort.landscape.height = viewportWidth;
        } else {
            device.viewPort.portrait.width = viewportHeight;
            device.viewPort.portrait.height = viewportWidth;
            device.viewPort.landscape.width = viewportWidth;
            device.viewPort.landscape.height = viewportHeight;
        }
        return device;
    },

    getDevicesForPlatform: function (platformId) {
        return utils.filter(_devices, function (device) {
            return device.platforms.indexOf(platformId) > -1;
        });
    }
};

});
define('ripple/documentEventListener', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    constants = require('ripple/constants'),
    deviceSettings = require('ripple/deviceSettings'),
    ui = require('ripple/ui'),
    _self,
    _ComWinShow = false;

function _bind(name, win) {
    var _listeners = [];

    return {
        add: function (callback, useCapture) {
            // ignore non-function
            if (typeof callback === "function") {
                // ignore useCapture as we could not handle it
                if (!useCapture) {
                    if (!_listeners.some(function (listener) {
                        return (listener === callback);
                    })) {
                        _listeners.push(callback);
                    }
                }
            }
        },
        exec: function (arg) {
            _listeners.forEach(function (listener) {
                listener.apply(win, arg);
            });
        },
        remove: function (callback, useCapture) {
            // ignore non-function
            if (typeof callback === "function") {
                // ignore useCapture as we do not add them into _listeners
                if (!useCapture) {
                    _listeners = _listeners.filter(function (listener) {
                        return (listener !== callback);
                    });
                }
            }
        }
    };
}

function _isComWinSHow() {
    return _ComWinShow;
}

_self = {
    mask: function (frame, doc) {
        /* 
         * The current issue is that "document.addEventListener(visibilitychange, function(){...})" 
         * does not work if it is invoked in the document.DOMContentLoaded listeners, for example, at 
         * JQuery(document).ready function.

         * The reason is that window.DOMContentLoaded is fired after the document.DOMContentLoaded. 
         * Currently we have not found a proper event to override the document.addEventListener. 
         * The beforeload is fine for window.addEventListener, while does not work for document.addEventListener 
         * because the contentDocument will be reset after loading. 
         */
        frame.addEventListener("DOMContentLoaded", function () {
            var widgetDocument = doc,
                _pageVisibility,
                add = widgetDocument.addEventListener,
                remove = widgetDocument.removeEventListener;

            widgetDocument.PAGE_HIDDEN  = "hidden";
            widgetDocument.PAGE_VISIBLE = "visible";
            widgetDocument.PAGE_PREVIEW = "preview";

            function _lockScreen(on) {
                var hidden = on;

                if (on) {
                    ui.showOverlay("lock-screen-window", function (background) {});
                } else {
                    ui.hideOverlay("lock-screen-window", function (background) {});
                }

                event.trigger("visibilitychange", [hidden]);
            }

            function _isLockScreenOn() {
                return deviceSettings.retrieve("Config.lockScreen");
            }

            _lockScreen(_isLockScreenOn());

            _pageVisibility = _bind("visibilitychange", frame.contentWindow);

            widgetDocument.addEventListener = function (event, callback, useCapture) {
                switch (event) {
                case "visibilitychange":
                    _pageVisibility.add(callback, useCapture);
                    break;

                default:
                    add.apply(widgetDocument, arguments);
                    break;
                }
            };

            widgetDocument.removeEventListener = function (event, callback, useCapture) {
                _pageVisibility.remove(callback, useCapture);
                remove.apply(widgetDocument, arguments);
            };

            event.on("LockScreenChanged", function (on) {
                if (_isComWinSHow() === false) {
                    _lockScreen(on);
                }
                else {
                    if (on === true) {
                        ui.hideOverlay("communication-window");
                        _lockScreen(on);
                    }
                    else {
                        _lockScreen(on);
                        ui.showOverlay("communication-window");
                    }
                }
            });

            event.on("CommWinShow", function (status) {
                _ComWinShow = status;
                if (_isLockScreenOn() === true) {
                    if (status === false) {
                        _lockScreen(true);
                    }
                    else {
                        jQuery("#lock-screen-window").hide();
                    }
                }
            });

            event.on("visibilitychange", function (hidden) {
                widgetDocument.hidden = hidden;
                widgetDocument.visibilityState = hidden ? widgetDocument.PAGE_HIDDEN : widgetDocument.PAGE_VISIBLE;
                _pageVisibility.exec();
            });
        });
    }
};

module.exports = _self;

});
define('ripple/emulatorBridge', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 platform = require('ripple/platform'),
    builder = require('ripple/platform/builder'),
    utils = require('ripple/utils'),
    _xhr, _win, _doc;

function _getEmulatedViewportStyle(attr) {
    var vp = document.getElementById("viewport-container");
    return vp["client" + attr];
}

function _getEmulatedDeviceStyle(attr) {
    var vp = document.getElementById("device-container"), value;
    value = vp.style[attr].replace(/\s/g, '');
    value = value.split("px")[0] - 4;
    return (value);
}

function _screenAvailWidth() {
    return _getEmulatedDeviceStyle("width");
}

function _screenAvailHeight() {
    return _getEmulatedDeviceStyle("height");
}

function _screenWidth() {
    return _getEmulatedDeviceStyle("width");
}

function _screenHeight() {
    return _getEmulatedDeviceStyle("height");
}

function _window_innerWidth() {
    return _getEmulatedViewportStyle("Width");
}

function _window_innerHeight() {
    return _getEmulatedViewportStyle("Height");
}

function _marshalScreen(win) {
    utils.forEach({
        "availWidth": _screenAvailWidth,
        "availHeight": _screenAvailHeight,
        "width": _screenWidth,
        "height": _screenHeight
    }, function (mappedFunc, prop) {
        win.screen.__defineGetter__(prop, mappedFunc);
    });

    utils.forEach({
        "innerWidth": _window_innerWidth,
        "innerHeight": _window_innerHeight
    }, function (mappedFunc, prop) {
        win.__defineGetter__(prop, mappedFunc);
    });
}

module.exports = {
    link: function  (win, doc) {
        // Only cache the device window and route onmessage to it
        if (win.parent.parent === win.parent &&
                win.frameElement.getAttribute('id') === 'document') {
            _win = win;
            _doc = doc;
            _xhr = win.XMLHttpRequest;

            window.onmessage = function (e) {
                if (typeof win.onmessage === 'function') {
                    win.onmessage(e);
                }
            };
        }

        require('ripple/widgetConfig').initialize();

        var marshal = function (obj, key) {
                window[key] = win[key] = obj;
            },
            currentPlatform = platform.current(),
            sandbox = {};

        marshal(window.tinyHippos, "tinyHippos");
        marshal(window.XMLHttpRequest, "XMLHttpRequest");
        marshal(window.Date, "Date");

        if (currentPlatform.initialize) {
            currentPlatform.initialize(win);
        }

        builder.build(platform.current().objects).into(sandbox);
        utils.forEach(sandbox, marshal);

        _marshalScreen(win);
        _marshalScreen(window);
    },

    document: function () {
        return _doc;
    },

    window: function () {
        return _win;
    },

    xhr: function () {
        return _xhr;
    }
};

});
define('ripple/event', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    _listeners = {};

function _on(eventType, listener, scope, once) {
    if (!eventType) {
        throw "eventType must be truthy";
    }
    _listeners[eventType] = _listeners[eventType] || [];
    _listeners[eventType].push({
        func: listener,
        scope: scope,
        once: !!once
    });
}

function _deleteEventHandler(eventType, listenerFunc, scope) {
    var i, listeners;

    if (!eventType) {
        throw "eventType must be truthy";
    }

    listeners = _listeners[eventType];

    // only delete once
    for (i = 0; i < listeners.length; i++) {
        if (listeners[i].func === listenerFunc) {
            listeners.splice(i, 1);
            break;
        }
    }
}

function _trigger(listener, args, sync) {
    try {
        if (sync) {
            listener.func.apply(listener.scope, args);
        }
        else {
            setTimeout(function () {
                listener.func.apply(listener.scope, args);
            }, 1);
        }
    }
    catch (e) {
        exception.handle(e);
    }
}

module.exports = {
    on: function (eventType, listener, scope) {
        _on(eventType, listener, scope, false);
    },

    once: function (eventType, listener, scope) {
        _on(eventType, listener, scope, true);
    },

    trigger: function (eventType, args, sync) {
        args = args || [];
        sync = sync || false;

        var listeners = _listeners[eventType];

        if (listeners) {
            listeners.forEach(function (listener) {
                _trigger(listener, args, sync);
            });

            _listeners[eventType] = listeners.filter(function (listener) {
                return !listener.once;
            });
        }
    },

    eventHasSubscriber: function (eventType) {
        return !!_listeners[eventType];
    },

    getEventSubscribers: function (eventType) {
        return utils.copy(_listeners[eventType]) || [];
    },

    clear: function (eventType) {
        if (eventType) {
            delete _listeners[eventType];
        }
    },

    deleteEventHandler: function (eventType, listener, scope) {
        _deleteEventHandler(eventType, listener, scope);
    }
};

});
define('ripple/exception', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _console = require('ripple/console');

function _getStack(depth) {
    var caller,
        stack = "",
        count = 0;

    try {
        caller = arguments.callee.caller.arguments.callee.caller;

        while (count <= depth && caller) {
            stack += "function: " + caller.toString().match(/function\s?(.*)\{/)[1] + "\n";
            caller = caller.arguments.callee.caller;
            count++;
        }
    } catch (e) {
        stack = "failed to determine stack trace (" + (e.name || e.type) + " :: " + e.message + ")";
    }

    return stack;
}

module.exports = {

    types: {
        Application: "Application",
        ArgumentLength: "ArgumentLength",
        ArgumentType: "ArgumentType",
        Argument: "Argument",
        NotificationType: "NotificationType",
        NotificationStateType: "NotificationStateType",
        DomObjectNotFound: "DomObjectNotFound",
        LayoutType: "LayoutType",
        OrientationType: "OrientationType",
        DeviceNotFound: "DeviceNotFound",
        tinyHipposMaskedException: "tinyHipposMaskedException",
        Geo: "Geo",
        Accelerometer: "Accelerometer",
        MethodNotImplemented: "MethodNotImplemented",
        InvalidState: "InvalidState",
        ApplicationState: "ApplicationState"
    },

    handle: function handle(exception, reThrow) {
        reThrow = reThrow || false;

        var eMsg = exception.message || "exception caught!",
        msg = eMsg + "\n\n" + (exception.stack || "*no stack provided*") + "\n\n";

        _console.error(msg);

        if (reThrow) {
            throw exception;
        }
    },

    raise: function raise(exceptionType, message, customExceptionObject) {
        var obj = customExceptionObject || {
                type: "",
                message: "",

                toString: function () {
                    var result = this.name + ': "' + this.message + '"';

                    if (this.stack) {
                        result += "\n" + this.stack;
                    }
                    return result;
                }
            };

        message = message || "";

        obj.name = exceptionType;
        obj.type = exceptionType;
        // TODO: include the exception objects original message if exists
        obj.message = message;
        obj.stack = _getStack(5);

        throw obj;
    },

    throwMaskedException: function throwMaskedException(exceptionType, message, customExceptionObject) {
        try {
            this.raise.apply(this, arguments);
        } catch (e) {
            this.handle(e);
        }
        this.raise(this.types.tinyHipposMaskedException, "tinyhippos terminated your script due to exception");
    }

};

});
define('ripple/fileSystem', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    db = require('ripple/db'),
    exception = require('ripple/exception'),
    event = require('ripple/event'),
    _console = require('ripple/console'),
    utils = require('ripple/utils'),
    _fileSystemPaths = {
        "photos": { "uri": "" },
        "videos": { "uri": "" },
        "music": { "uri": "" },
        "downloads": { "uri": "" },
        "widgethome": { "uri": "" }
    },
    _fileSystemRegex = {
        "photos": { "virtualPathRegex": /^\/virtual\/photos\//i },
        "videos": { "virtualPathRegex": /^\/virtual\/videos\//i },
        "music": { "virtualPathRegex": /^\/virtual\/music\//i },
        "downloads": { "virtualPathRegex": /^\/virtual\/downloads\//i },
        "widgethome": { "virtualPathRegex": /^\/virtual\/widgethome\//i }
    },
    _overrides = {};

module.exports = {
    initialize: function () {
        _fileSystemPaths = db.retrieveObject(constants.FILESYSTEM.PERSISTENCE_KEY) || _fileSystemPaths;
        _fileSystemPaths.widgethome.uri = window.location.protocol + "//" + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/') + 1);
    },

    getURI: function getURI(origURI) {
        var newURI = origURI,
            found = false;

        if (_overrides[origURI]) {
            return _overrides[origURI];
        }

        utils.forEach(_fileSystemPaths, function (value, key) {
            if (found) {
                return;
            }

            var uri = value.uri.replace(/\/$/, "");
            if (origURI.match(_fileSystemRegex[key].virtualPathRegex)) {
                newURI = origURI.replace(_fileSystemRegex[key].virtualPathRegex, uri + "/");
                found = true;
            }
        });

        return newURI;
    },

    exists: function (path) {
        try {
            var scrubbedUri = this.getURI(path),
                xhr = new XMLHttpRequest();

            xhr.open("GET", scrubbedUri, false);
            xhr.send();

            //HACK: this should return maybe for 403
            return xhr.status !== 404;
        }
        catch (e) {
            exception.handle(e);
            _console.log("failed to check if [" + path + "] exists");
            return false;
        }
    },


    getFileSystemPaths: function getFileSystemPaths() {
        return utils.copy(_fileSystemPaths);
    },

    updateFileSystemPaths: function updateFileSystemPaths(filePathsObject) {
        _fileSystemPaths = utils.copy(filePathsObject);
        _fileSystemPaths.widgethome.uri = window.location.protocol + "//" + window.location.host + window.location.pathname;
        db.saveObject(constants.FILESYSTEM.PERSISTENCE_KEY, filePathsObject);
    },

    override : function (from, to) {
        _overrides[from] = to;
    }
};

});
define('ripple/fs', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    constants = require('ripple/constants'),
    event = require('ripple/event'),
    _console = require('ripple/console'),
    _self, _fs;

function _map(array, callback) {
    var map = [], i;
    for (i = 0; i < array.length; i++) {
        map[i] = callback(array[i], i);
    }
    return map;
}

function _resolveLocalFileSystemURL(path, success, error) {
    return (window.resolveLocalFileSystemURL || window.webkitResolveLocalFileSystemURL)(path, success, error);
}

function _blobBuilder() {
    var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder;
    return new BlobBuilder();
}

function _error(e) {
    var msg = '';

    switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
        msg = 'QUOTA_EXCEEDED_ERR';
        break;
    case FileError.NOT_FOUND_ERR:
        msg = 'NOT_FOUND_ERR';
        break;
    case FileError.SECURITY_ERR:
        msg = 'SECURITY_ERR';
        break;
    case FileError.INVALID_MODIFICATION_ERR:
        msg = 'INVALID_MODIFICATION_ERR';
        break;
    case FileError.INVALID_STATE_ERR:
        msg = 'INVALID_STATE_ERR';
        break;
    default:
        msg = 'Unknown Error';
        break;
    }

    _console.log('FileSystem error: ' + msg);
}

_self = {
    initialize: function (prev, baton) {
        try {
            var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

            if (requestFileSystem) {
                baton.take();
            }

            requestFileSystem(window.TEMPORARY, constants.FS_SIZE, function (fs) {
                _fs = fs;
                event.trigger("FileSystemInitialized", null, true);
                baton.pass();
            }, _error);
        }
        catch (e) {
            console.log("File System Not Available");
        }
    },

    ls: function (path, success, error) {
        path = path || "/";

        _fs.root.getDirectory(path, {}, function (dirEntry) {
            var dirReader = dirEntry.createReader();
            dirReader.readEntries(function (entries) {
                success(_map(entries, function (entry, index) {
                    return entry;
                }));
            }, error);
        }, error);
    },

    rm: function (path, success, error, options) {
        options = options || {};

        _fs.root[options.recursive ? "getDirectory" : "getFile"](path, {create: false}, function (entry) {
            entry[options.recursive ? "removeRecursively" : "remove"](function () {
                success();
            }, error);
        }, error);
    },

    rmdir: function (path, success, error, options) {
        options = options || {};

        _fs.root.getDirectory(path, {create: false}, function (entry) {
            entry.remove(function () {
                success();
            }, error);
        }, error);
    },

    mkdir: function (path, success, error) {
        _fs.root.getDirectory(path, {create: true}, function (dirEntry) {
            success(dirEntry);
        }, error);
    },

    mv: function (from, to, success, error) {
        var path = to.replace(/^\//, "").split("/"),
            fileName = path.splice(path.length - 1, 1).toString();

        _self.stat(from, function (entry) {
            _self.stat(path.length > 0 ? path.join("/") : "/", function (dest) {
                entry.moveTo(dest, fileName, function (finalDestination) {
                    success(finalDestination);
                }, error);
            }, error);
        }, error);
    },

    touch: function (path, success, error) {
        _fs.root.getFile(path, {create: true}, function (fileEntry) {
            success(fileEntry);
        }, error);
    },

    cp: function (from, to, success, error) {
        var path = to.replace(/^\//, "").split("/"),
            fileName = path.splice(path.length - 1, 1).toString();

        _self.stat(from, function (entry) {
            _self.stat(path.length > 0 ? path.join("/") : "/", function (dest) {
                entry.copyTo(dest, fileName, function (finalDestination) {
                    success(finalDestination);
                }, error);
            }, error);
        }, error);
    },

    stat: function (path, success, error) {
        var url = "filesystem:" + utils.location().origin + "/temporary/" + path;
        _resolveLocalFileSystemURL(url, function (entry) {
            success(entry);
        }, error);
    },

    write: function (path, contents, success, error, options) {
        options = options || {};

        function write(entry) {
            entry.createWriter(function (fileWriter) {
                var bb = _blobBuilder();

                fileWriter.onwriteend = function (progressEvent) {
                    success(entry);
                };
                fileWriter.onerror = error;

                if (options.mode === "append") {
                    fileWriter.seek(fileWriter.length);
                }

                bb.append(contents);
                fileWriter.write(bb.getBlob('text/plain'));
            }, error);
        }

        _self.stat(path, function (entry) {
            if (options.mode === "append") {
                write(entry);
            } else {
                _self.rm(path, function () {
                    _self.touch(path, write, error);
                }, error);
            }
        }, function (e) {
            if (e.code === FileError.NOT_FOUND_ERR) {
                _self.touch(path, write, error);
            } else {
                error(e);
            }
        });
    },

    read: function (path, success, error) {
        _self.stat(path, function (entry) {
            entry.file(function (file) {
                var reader = new FileReader();

                reader.onloadend = function (progressEvent) {
                    success(progressEvent.target.result);
                };
                reader.onerror = error;

                reader.readAsText(file);
            }, error);
        }, error);
    }
};

module.exports = _self;

});
define('ripple/geo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    exception = require('ripple/exception'),
    event = require('ripple/event'),
    utils = require('ripple/utils'),
    _positionInfo = {
        "latitude": 39.968362,
        "longitude": 116.410186,
        "altitude": 50,
        "accuracy": 150,
        "altitudeAccuracy": 80,
        "heading": 0,
        "speed": 0,
        "cellID": 1130433
    },
    self;

function _serialize(settings) {
    var tempSettings = utils.copy(settings);
    tempSettings.position.timeStamp = "new Date(" + tempSettings.position.timeStamp.getTime() + ")";
    return tempSettings;
}

function _validatePositionInfo(pInfo) {
    return (pInfo &&
        !(isNaN(pInfo.latitude) ||
        isNaN(pInfo.longitude) ||
        isNaN(pInfo.altitude) ||
        isNaN(pInfo.accuracy) ||
        isNaN(pInfo.altitudeAccuracy) ||
        isNaN(pInfo.heading) ||
        isNaN(pInfo.speed) ||
        isNaN(pInfo.cellID))) ? true : false;
}

self = module.exports = {
    initialize: function () {
        var settings = db.retrieveObject("geosettings");
        if (settings) {
            utils.forEach(_positionInfo, function (value, key) {
                _positionInfo[key] = parseFloat(settings.position[key] || value);
            });

            self.timeout = settings.timeout;
            self.delay = settings.delay || 0;

        }
    },

    getPositionInfo: function () {
        var pi = utils.copy(_positionInfo);
        pi.timeStamp = new Date();

        return pi;
    },

    updatePositionInfo: function (newPositionInfo, delay, timeout) {
        if (!_validatePositionInfo(newPositionInfo)) {
            exception.raise(exception.types.Geo, "invalid positionInfo object");
        }

        _positionInfo = utils.copy(newPositionInfo);
        _positionInfo.timeStamp = new Date();

        self.delay = delay || 0;
        self.timeout = timeout;

        db.saveObject("geosettings", _serialize({
            position: _positionInfo,
            delay: self.delay,
            timeout: self.timeout
        }));

        event.trigger("PositionInfoUpdatedEvent", [_positionInfo]);
    },

    timeout: false,
    delay: 0,
    map: {}
};

});
define('ripple/honeypot', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 noop = function () {};

module.exports = {
    monitor: function (context, target) {

        var setup = function (get, set) {
            set = set || noop;

            context.__defineGetter__(target, noop);
            context.__defineSetter__(target, function (value) {
                context.__defineGetter__(target, get);
                set(value);
            });
        };

        return {
            andReturn: function (value) {
                setup(function () {
                    return value;
                });
            },
            andRun: function (get, set) {
                setup(get, set);
            }
        };
    }
};

});
define('ripple/hwKeyEmulator', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
   _self;

function _HWKeyEvent(keyName) {
    var doc = document.getElementById('document').contentDocument,
    event;

    event = doc.createEvent('Event');
    event.initEvent("tizenhwkey", true, false);
    event.__defineGetter__("keyName", function () {
        return keyName;
    });
    doc.dispatchEvent(event);
}


_self = {
    init: function (win, doc) {
        event.clear("tizenhwkeyEvent");
        event.on("tizenhwkeyEvent", function (keyName) {
            _HWKeyEvent(keyName);
        });
    }
};

module.exports = _self;

});
define('ripple/notifications', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    exception = require('ripple/exception'),
    utils = require('ripple/utils'),
    event = require('ripple/event');

function _validateAndInitNType(nType) {
    nType = nType || "normal";

    if (nType !== "normal" && nType !== "error") {
        exception.raise(exception.types.NotificationType, "Unknown Notification Type == " + nType + ",when dealing with Console notification.");
    }

    return nType;
}

function _processNotification(nType, stateType, message) {
    nType = _validateAndInitNType(nType);
    message = message || "";

    var display,
        displayText,
        className,
        notificationIcon,
        box = document.getElementById(constants.NOTIFICATIONS.MAIN_CONTAINER_CLASS),
        msgBox = document.getElementById(constants.NOTIFICATIONS.MESSAGE_TEXT_CONTAINER_CLASS);

    className = "ui-widget";

    switch (stateType) {

    case constants.NOTIFICATIONS.STATE_TYPES.CLOSE:
        display = "display: none;"; //need to do this better.
        displayText = "";
        break;

    case constants.NOTIFICATIONS.STATE_TYPES.OPEN:
        display = "display: block;"; //need to do this better.
        displayText = message;
        if (nType === "error") {
            displayText = "Oh Snap!\n\n" + displayText;
            className += " ui-state-error ui-corner-all";
            notificationIcon = '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>';
        }
        else {
            className += " ui-state-highlight ui-corner-all";
            notificationIcon = '<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>';
        }
        break;

    default:
        exception.raise(exception.types.NotificationStateType, "Unknown StateType == " + stateType.toString());
    }

    msgBox.innerHTML = notificationIcon + displayText;
    box.setAttribute("class", className);
    box.setAttribute("style", display);

}

module.exports = {
    openNotification: function (nType, msg) {
        _processNotification(nType, constants.NOTIFICATIONS.STATE_TYPES.OPEN, msg);
    },

    closeNotification: function (nType) {
        _processNotification(nType, constants.NOTIFICATIONS.STATE_TYPES.CLOSE);
    }
};

});
define('ripple/omgwtf', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    db = require('ripple/db'),
    _loaded = false,
    _self;

function _delay(action) {
    window.setTimeout(function () {
        if (!_loaded) {
            if (jQuery(".first-run-window").is(":visible")) {
                _delay(action);
            } else {
                action();
            }
        }
    }, 10000);
}

function _hide() {
    jQuery(".error-window").css({display: 'none'});
    jQuery(".error-dialog").css({display: 'none'});
}

function _show() {
    jQuery(".error-window").css({display: 'block'});

    jQuery(".error-dialog").css({
        display: 'block',
        left: (jQuery(document).width() / 2) - 277 + "px"
    });

    jQuery("#error-wait").click(function () {
        _hide();
        _delay(_show);
    });

    jQuery("#error-panic").click(function () {
        db.removeAll(null, function () {
            window.tinyHipposReload = true;
            localStorage.clear();
            location.reload();
        });
    });
}

_delay(_show);

_self = {
    initialize: function (previous, baton) {
        event.on("TinyHipposLoaded", function () {
            _loaded = true;
        });
    },
    show: _show,
    hide: _hide
};

module.exports = _self;

});
define('ripple/platform/builder', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    app = require('ripple/app');

function _objectFactory(context, objects/*, allowed*/) {
    utils.forEach(objects, function (obj, key) {
        var result = {}, objFeatures = {}, rst, f, widgetFeatures;

//        if (allowed(obj)) {
        result = obj.path ? require('ripple/platform/' + obj.path) : {};
        if (typeof result === "function" && obj.handleSubfeatures && obj.handleSubfeatures === true) {
            rst = new result();
            if (obj.feature) {
                objFeatures = obj.feature.split('|');
                if (rst.handleSubFeatures) {
                    widgetFeatures = app.getInfo().features; // features in config.xml
                    f = {};
                    utils.forEach(objFeatures, function (o) {
                        if (widgetFeatures && !!widgetFeatures[o]) {
                            f[widgetFeatures[o].id] = widgetFeatures[o];
                        }
                    });
                    rst.handleSubFeatures(f);
                    delete rst.handleSubFeatures;
                }
            }
            result = rst;
        }
//        }

        if (obj.children) {
            _objectFactory(result, obj.children/*, allowed*/);
        }

        context.__defineGetter__(key, function () {
            return result;
        });
        // inject into the context if it is allowed or it has children that were allowed
//        if (allowed(obj) || utils.count(result)) {
//        context[key] = result;
//        }
//        else {
//            if (context.hasOwnProperty(key))
//                console.log("delete " + key);
//            delete context[key];
//        }
    });
}

module.exports = {
    build: function (objects) {
        return {
            into: function (sandbox) {
/*                var features = utils.copy(app.getInfo().features);
                    allowed = function (obj) {
                        var contains = function (requirements) {
                            return requirements.split('|').some(function (feature) {
                                return !!features[feature];
                            });
                        };
                        //object is allowed if:
                        // 1. it has no feature requirement
                        // 2. the config file doesn't exist (features collection is null)
                        // 3. the feature exists in the defined features
                        return !obj.feature || !features || (features && contains(obj.feature));
                    };
*/

                _objectFactory(sandbox, objects/*, allowed*/);
            }
        };
    }
};

});
define('ripple/platform/cordova/2.0.0/JavaPluginManager', function (require, exports, module) {
module.exports = {
    exec: function () {
        throw "this really shouldn't be called. like ever!";
    },
    resume: function () {
        throw "this shouldn't be called";
    },
    pause: function () {
        throw "this shouldn't be called";
    },
    destroy: function () {
        throw "this shouldn't be called";
    }
};

});
define('ripple/platform/cordova/2.0.0/MediaError', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 MediaError = function (code, msg) {
    this.code = (code !== undefined ? code : null);
    this.message = msg || "";
};

MediaError.MEDIA_ERR_NONE_ACTIVE    = 0;
MediaError.MEDIA_ERR_ABORTED        = 1;
MediaError.MEDIA_ERR_NETWORK        = 2;
MediaError.MEDIA_ERR_DECODE         = 3;
MediaError.MEDIA_ERR_NONE_SUPPORTED = 4;

module.exports = MediaError;

});
define('ripple/platform/cordova/2.0.0/bridge/accelerometer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    _success,
    _error,
    _current = {x: 0, y: 0, z: 0, timestamp: (new Date()).getTime()},
    _interval;

event.on("AccelerometerInfoChangedEvent", function (accelerometerInfo) {
    _current.x = accelerometerInfo.accelerationIncludingGravity.x;
    _current.y = accelerometerInfo.accelerationIncludingGravity.y;
    _current.z = accelerometerInfo.accelerationIncludingGravity.z;
    _current.timestamp = (new Date()).getTime();
});

module.exports = {
    start: function (success, error, args) {
        _success = success;
        _error = error;
        // Possible HACK? update the timestamp of the last data to something current
        _interval = window.setInterval(function () {
            _current.timestamp = (new Date()).getTime();
            _success(_current);
        }, 50);
    },

    stop: function () {
        _success = null;
        _error = null;
        window.clearInterval(_interval);
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/app', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 camera = require('ripple/ui/plugins/camera'),
    event = require('ripple/event');

module.exports = {
    show: function (success, error, args) {
        return success && success();
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/camera', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 camera = require('ripple/ui/plugins/camera'),
    event = require('ripple/event');

module.exports = {
    takePicture: function (success, error, args) {
        event.once("captured-image", function (uri, file) {
            success(uri);
        });
        camera.show();
    },
    cleanup: function (success, error, args) {
        success();
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/capture', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 camera = require('ripple/ui/plugins/camera'),
    event = require('ripple/event');

module.exports = {
    captureImage: function (success, error, args) {
        event.once("captured-image", function (uri, file) {
            file.fullPath = uri;
            success([file]);
        });
        camera.show();
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/compass', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 geo = require('ripple/geo');

module.exports = {
    getHeading: function (success, error, args) {
        // TODO: build facility to trigger onError() from emulator
        // see pivotal item: https://www.pivotaltracker.com/story/show/7040343
        success({
            magneticHeading: geo.getPositionInfo().heading, 
            trueHeading: geo.getPositionInfo().heading, 
            headingAccuracy: 100, 
            timestamp: new Date().getSeconds()
        });
    },

    stopHeading: function () { 
        //do nothing
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/console', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */

module.exports = {
    log: function (win, fail, args) {
        console.log(args[0]);
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/contacts', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    _self;

function _default() {
    return [{
        "name": {formatted: "Brent Lintner"},
        "displayName": "Brent Lintner",
        "emails": [{type: "work", value: "brent@tinyhippos.com", pref: false}]
    }, {
        "name": {formatted: "PJ Lowe"},
        "displayName": "PJ Lowe",
        "emails": [{type: "work", value: "pj@tinyhippos.com", pref: false}]
    }, {
        "name": {formatted: "Dan Silivestru"},
        "displayName": "Dan Silivestru",
        "emails": [{type: "work", value: "dan@tinyhippos.com", pref: false}]
    }, {
        "name": {formatted: "Gord Tanner"},
        "displayName": "Gord Tanner",
        "emails": [{type: "work", value: "gord@tinyhippos.com", pref: true}]
    }, {
        "name": {formatted: "Mark McArdle"},
        "displayName": "Mark McArdle",
        "emails": [{type: "work", value: "mark@tinyhippos.com", pref: false}]
    }].map(function (obj) {
        obj.id = Math.uuid(undefined, 16);
        return navigator.contacts.create(obj);
    });
}

function _get() {
    return db.retrieveObject("cordova-contacts") || _default();
}

function _save(contacts) {
    db.saveObject("cordova-contacts", contacts);
}

function _filtered(compare, options) {
    // this could be done a lot better..
    var found = false;
    if (!options.filter || options.filter === "") {
        found = true;
    } else if (typeof compare === "string" &&
              compare.match(new RegExp(".*" + options.filter + ".*", "i"))) {
        found = true;
    } else if (typeof compare === "object" || compare instanceof Array) {
        utils.forEach(compare, function (value) {
            if (!found) {
                found = _filtered(value, options);
            }
        });
    }
    return found;
}

_self = {
    search: function (success, error, args) {
        var fields = args[0],
            options = args[1],
            foundContacts = [],
            tempContact = navigator.contacts.create(),
            contacts = _get();

        options = options || {};

        // handle special case of ["*"] to return all fields
        if (fields.length === 1 && fields[0] === "*") {
            fields = utils.map(tempContact, function (v, k) {
                return k;
            });
        }

        if (fields.length > 0) {
            contacts.forEach(function (contact, index) {
                var newContact = navigator.contacts.create(contact);

                if (options && (!_filtered(contact, options))) {
                    return;
                }

                utils.forEach(newContact, function (value, prop) {
                    if (typeof newContact[prop] !== "function" && prop !== "id" &&
                        !fields.some(function (field) {
                            return field === prop;
                        })) {
                        delete newContact[prop];
                    }
                });

                foundContacts.push(newContact);
            });
        }

        // TODO: don't loop over entire db just to slice the array
        if (options.multiple === false) {
            foundContacts = foundContacts.splice(0, 1);
        }
        success(foundContacts);
    },

    save: function (success, error, args) {
        var contacts = _get(),
            contact = args[0],
            index;

        if (!contact.id) {
            contact.id = Math.uuid(undefined, 16);
            contacts.push(contact);
        } else {
            index = contacts.reduce(function (result, value, index) {
                return value.id === contact.id ? index : result;
            }, -1);

            if (index >= 0) {
                utils.mixin(contact, contacts[index]);
                contact = contacts[index];
            } else {
                contact = null;
            }
        }

        _save(contacts);
        if (success) {
            success(contact);
        }
    },

    remove: function (success, error, args) {
        var contacts = _get(),
            id = args[0],
            toDelete = contacts.reduce(function (result, current, index) {
                return current.id === id ? index : result;
            }, -1);

        if (toDelete >= 0) {
            contacts.splice(toDelete, 1);
            _save(contacts);
            if (success) {
                success();
            }
        } else {
            error({code: 3, message: "could not find contact with id (" + id + ")"}); // PENDING_OPERATION_ERROR
        }
    }
};

module.exports = _self;

});
define('ripple/platform/cordova/2.0.0/bridge/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 devices = require('ripple/devices');

module.exports = {
    getDeviceInfo: function (success, fail, args) {
        var device = devices.getCurrentDevice();

        success({
            available: true,
            platform: device.osName,
            version: device.osVersion,
            name: device.name,
            uuid: device.uuid,
            cordova: "2.0.0"
        });
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/file', function (require, exports, module) {
// HACK: fs keeps a reference to the last-used FileSystem requested via requestFileSystem
// this is a hack because if you keep switching between TEMPORARY vs. PERSISTENT file systems requested,
// and run Cordova File API methods, no parameter is passed into exec specifying the underlying File System.
// This should be fixed in Cordova!
var fs, 
    topCordova = require('ripple/platform/cordova/2.0.0/spec'),
    rlfsu;

function cleanPath(path) {
    while (path[0] && path[0] === '/') {
        path = path.substr(1);
    }
    return path;
}

module.exports = {
    requestFileSystem: function (win, fail, args) {
        // HACK: may not be webkit
        var rfs = window.webkitRequestFileSystem,
            type = args[0],
            size = args[1];

        // HACK: assume any FS requested over a gig in size will throw an error
        if (size > (1024 * 1024 * 1024 /* gigabyte */)) {
            if (fail) fail(FileError.QUOTA_EXCEEDED_ERR);
        } else {
            return rfs(type, size, function (effes) {
                fs = effes;
                win(effes);
            }, fail);
        }
    },
    resolveLocalFileSystemURI: function (win, fail, args) {
        var uri = args[0],
            fulluri = fs.root.toURL();

        // HACK: iOS-specific bs right here. See lib/ios/plugin/ios/Entry.js in cordova.js for details
        // Cordova badly needs a unified File System abstraction.
        if (uri.indexOf("file://localhost") === 0) {
            uri = uri.substr(16);
        }
        uri = cleanPath(uri);

        fulluri += uri;

        return window.webkitResolveLocalFileSystemURL(fulluri, function (entry) {
            if (win) win(entry);
        }, function (error) {
            if (fail) fail(error.code);
        });
    },
    getFile: function (win, fail, args) {
        var path = args[0],
            filename = args[1],
            options = args[2],
            file = '';

        path = cleanPath(path);
        filename = cleanPath(filename);

        if (path) {
            file = path + '/';
        }
        file += filename;

        fs.root.getFile(file, options, function (entry) {
            if (win) win(entry);
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    remove: function (win, fail, args) {
        var file = args[0];
        window.webkitResolveLocalFileSystemURL(fs.root.toURL() + file, function (entry) {
            entry.remove(function () {
                if (win) win();
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, fail);
    },
    readEntries: function (win, fail, args) {
        var root = fs.root.toURL(),
            path = args[0],
            reader;

        path = cleanPath(path);
        path = root + path;

        window.webkitResolveLocalFileSystemURL(path, function (entry) {
            reader = entry.createReader();
            reader.readEntries(function (entries) {
                if (win) win(entries);
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    getDirectory: function (win, fail, args) {
        var path = args[0],
            filename = args[1],
            options = args[2],
            file = '';

        path = cleanPath(path);
        filename = cleanPath(filename);

        if (path) {
            file = path + '/';
        }
        file += filename;

        fs.root.getDirectory(file, options, function (entry) {
            if (win) win(entry);
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    removeRecursively: function (win, fail, args) {
        var root = fs.root.toURL(),
            path = args[0];

        path = cleanPath(path);

        window.webkitResolveLocalFileSystemURL(root + path, function (dirEntry) {
            dirEntry.removeRecursively(function () {
                if (win) win();
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    getFileMetadata: function (win, fail, args) {
        var path = args[0],
            root = fs.root.toURL();

        path = cleanPath(path);

        window.webkitResolveLocalFileSystemURL(root + path, function (entry) {
            entry.file(function (file) {
                if (win) win(file);
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    getMetadata: function (win, fail, args) {
        var path = args[0],
            root = fs.root.toURL();

        path = cleanPath(path);
        
        window.webkitResolveLocalFileSystemURL(root + path, function (entry) {
            entry.getMetadata(function (data) {
                if (win) win(data);
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    getParent: function (win, fail, args) {
        var path = args[0],
            root = fs.root.toURL();

        path = cleanPath(path);

        window.webkitResolveLocalFileSystemURL(root + path, function (entry) {
            entry.getParent(function (dirEntry) {
                if (win) win(dirEntry);
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    copyTo: function (win, fail, args) {
        var src = args[0],
            parent = args[1],
            name = args[2],
            root = fs.root.toURL();

        parent = cleanPath(parent);
        src = cleanPath(src);

        rlfsu = window.webkitResolveLocalFileSystemURL;
        // get the directoryentry that we will copy TO
        rlfsu(root + parent, function (parentDirToCopyTo) {
            rlfsu(root + src, function (sourceDir) {
                sourceDir.copyTo(parentDirToCopyTo, name, function (newEntry) {
                    if (win) win(newEntry);
                }, function (err) {
                    if (fail) fail(err.code);
                });
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    moveTo: function (win, fail, args) {
        var src = args[0],
            parent = args[1],
            name = args[2],
            root = fs.root.toURL();

        parent = cleanPath(parent);
        src = cleanPath(src);

        rlfsu = window.webkitResolveLocalFileSystemURL;
        // get the directoryentry that we will move TO
        rlfsu(root + parent, function (parentDirToMoveTo) {
            rlfsu(root + src, function (sourceDir) {
                sourceDir.moveTo(parentDirToMoveTo, name, function (newEntry) {
                    if (win) win(newEntry);
                }, function (err) {
                    if (fail) fail(err.code);
                });
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    write: function (win, fail, args) {
        var file = args[0],
            text = args[1],
            position = args[2],
            sourcepath,
            BB = window.BlobBuilder || window.WebKitBlobBuilder,
            bb = new BB();

        // Format source path
        sourcepath = (file.fullPath ? file.fullPath : '') + file.name;
        sourcepath = cleanPath(sourcepath);

        // Create a blob for the text to be written
        bb.append(text);

        // Get the FileEntry, create if necessary
        fs.root.getFile(sourcepath, {create: true}, function (entry) {
            // Create a FileWriter for this entry
            entry.createWriter(function (writer) {
                writer.onwriteend = function (progressEvt) {
                    if (win) win(progressEvt.total);
                };
                writer.onerror = function (err) {
                    if (fail) fail(err.code);
                };

                if (position && position > 0) {
                    writer.seek(position);
                }
                writer.write(bb.getBlob('text/plain'));
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    readAsText: function (win, fail, args) {
        var path = args[0],
            encoding = args[1],
            FileReader = topCordova.nativeMethods.FileReader,
            fr = new window.FileReader();

        // Set up FileReader events
        fr.onerror = function (err) {
            if (fail) fail(err.code);
        };
        fr.onload = function (evt) {
            if (win) win(evt.target.result);
        };

        path = cleanPath(path);

        fs.root.getFile(path, {create: false}, function (entry) {
            entry.file(function (blob) {
                fr.readAsText(blob, encoding);
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    readAsDataURL: function (win, fail, args) {
        var path = args[0],
            FileReader = topCordova.nativeMethods.FileReader,
            fr = new window.FileReader();

        // Set up FileReader events
        fr.onerror = function (err) {
            if (fail) fail(err.code);
        };
        fr.onload = function (evt) {
            if (win) win(evt.target.result);
        };

        path = cleanPath(path);

        fs.root.getFile(path, {create: false}, function (entry) {
            entry.file(function (blob) {
                fr.readAsDataURL(blob);
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    },
    truncate: function (win, fail, args) {
        var file = args[0],
            position = args[1],
            sourcepath;

        // Format source path
        sourcepath = (file.fullPath ? file.fullPath : '') + file.name;
        sourcepath = cleanPath(sourcepath);

        // Get the FileEntry, create if necessary
        fs.root.getFile(sourcepath, {create: false}, function (entry) {
            // Create a FileWriter for this entry
            entry.createWriter(function (writer) {
                writer.onwriteend = function (progressEvt) {
                    if (win) win(progressEvt.target.length);
                };
                writer.onerror = function (err) {
                    if (fail) fail(err.code);
                };

                writer.truncate(position);
            }, function (err) {
                if (fail) fail(err.code);
            });
        }, function (err) {
            if (fail) fail(err.code);
        });
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/geolocation', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    geo = require('ripple/geo'),
    utils = require('ripple/utils'),
    PositionError = require('ripple/platform/w3c/1.0/PositionError'),
    _watches = {},
    _current = {
        "latitude": 43.465187,
        "longitude": -80.522372,
        "altitude": 100,
        "accuracy": 150,
        "altitudeAccuracy": 80,
        "heading": 0,
        "velocity": 0,
    },
    _error;

function _getCurrentPosition(win, fail) {
    if (geo.timeout) {
        if (fail) {
            var positionError = new PositionError();

            positionError.code = PositionError.TIMEOUT;
            positionError.message = "postion timed out";
            fail(positionError);
        }
    }
    else {
        win(geo.getPositionInfo());
    }
}

event.on("PositionInfoUpdatedEvent", function (pi) {
    _current.latitude = pi.latitude;
    _current.longitude = pi.longitude;
    _current.altitude = pi.altitude;
    _current.accuracy = pi.accuracy;
    _current.altitudeAccuracy = pi.altitudeAccuracy;
    _current.heading = pi.heading;
    _current.velocity = pi.speed;

    utils.forEach(_watches, function (watch) {
        try {
            _getCurrentPosition(watch.win, watch.fail);
        } catch (e) {
            console.log(e);
        }
    });
});

module.exports = {
    getLocation: function (success, error, args) {
        _getCurrentPosition(success, error);
    },

    addWatch: function (success, error, args) {
        _watches[args[0]] = {
            win: success,
            fail: error
        };
        _getCurrentPosition(success, error);
    },

    clearWatch: function (id) {
        delete _watches[id];
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/media', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 audioObjects = {},
    noop = function () {};

function createAudio(id, src, error) {
    var a = new Audio();
    a.addEventListener("error", function (e) {
        error(new window.MediaError(1, e.toString()));
    });
    a.addEventListener("durationchange", function () {
        //HACK: I don't like this but best way for us to update the duration
        cordova.require("cordova/plugin/Media").onStatus(id, 2, this.duration);
    });
    a.src = src;

    return a;
}

module.exports = {
    create: function (success, error, args) {
        if (!args.length) {
            error("Media Object id was not sent in arguments");
            return;
        }

        var id = args[0],
            src = args[1];

        error = error || noop;
        success = success || noop;

        audioObjects[id] = createAudio(id, src, error);
        success();
    },
    startPlayingAudio: function (success, error, args) {
        error = error || noop;
        success = success || noop;
        if (!args.length) {
            error("Media Object id was not sent in arguments");
            return;
        }

        var id = args[0],
            audio = audioObjects[id];

        if (args.length === 1) {
            error("Media source argument not found");
            return;
        }

        if (audio) {
            audio.pause();
            audioObjects[id] = undefined;
        }

        audio = audioObjects[id] = createAudio(id, args[1], error);
        audio.play();

        success();
    },
    stopPlayingAudio: function (success, error, args) {
        error = error || noop;
        success = success || noop;
        if (!args.length) {
            error("Media Object id was not sent in arguments");
            return;
        }

        var id = args[0],
            audio = audioObjects[id];

        if (!audio) {
            error("Audio Object has not been initialized");
            return;
        }

        audio.pause();
        audioObjects[id] = undefined;

        success();
    },
    seekToAudio: function (success, error, args) {
        error = error || noop;
        success = success || noop;
        if (!args.length) {
            error("Media Object id was not sent in arguments");
            return;
        }

        var id = args[0],
            audio = audioObjects[id];

        if (!audio) {
            error("Audio Object has not been initialized");
            return;
        } else if (args.length === 1) {
            error("Media seek time argument not found");
            return;
        } else {
            try {
                audio.currentTime = args[1];
            } catch (e) {
                error("Error seeking audio: " + e);
            }
        }

        success();
    },
    pausePlayingAudio: function (success, error, args) {
        error = error || noop;
        success = success || noop;
        if (!args.length) {
            error("Media Object id was not sent in arguments");
            return;
        }

        var id = args[0],
            audio = audioObjects[id];

        if (!audio) {
            error("Audio Object has not been initialized");
            return;
        }

        audio.pause();
        success();
    },
    getCurrentPositionAudio: function (success, error, args) {
        error = error || noop;
        success = success || noop;
        if (!args.length) {
            error("Media Object id was not sent in arguments");
            return;
        }

        var id = args[0],
            audio = audioObjects[id];

        if (!audio) {
            error("Audio Object has not been initialized");
            return;
        }

        success(audio.currentTime);
    },
    getDuration: function (success, error, args) {
        error = error || noop;
        success = success || noop;
        if (!args.length) {
            error("Media Object id was not sent in arguments");
            return;
        }

        var id = args[0],
            audio = audioObjects[id];

        if (!audio) {
            error("Audio Object has not been initialized");
            return;
        }

        success(audio.duration);
    },
    startRecordingAudio: function (success, error, args) {
        error = error || noop;
        error("Not supported");
    },
    stopRecordingAudio: function (success, error, args) {
        error = error || noop;
        error("Not supported");
    },
    release: function (success, error, args) {
        error = error || noop;
        success = success || noop;
        if (!args.length) {
            error("Media Object id was not sent in arguments");
            return;
        }

        var id = args[0],
            audio = audioObjects[id];

        if (audio) {
            audioObjects[id] = undefined;
            audio.src = undefined;
            //delete audio;
        }

        success();
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/network', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 deviceSettings = require('ripple/deviceSettings'),
    event = require('ripple/event'),
    _success;

event.on("ConnectionChanged", function () {
    return _success && _success(deviceSettings.retrieve("NetworkStatus.connectionType"));
});

module.exports = {
    getConnectionInfo: function (success, fail, args) {
        _success = success;
        success(deviceSettings.retrieve("NetworkStatus.connectionType"));
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge/notification', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 notifications = require('ripple/notifications'),
    _console = require('ripple/console'),
    goodVibrations = require('ripple/ui/plugins/goodVibrations');

module.exports = {
    alert: function (success, error, args) {
        notifications.openNotification("normal", args[0]);
        return success && success();
    },

    confirm: function (success, error, args) {
        throw "Not Implemented";
    },

    activityStart: function (success, error, args) {
    },

    activityStop: function (success, error, args) { 
    },

    progressStart: function (success, error, args) {
    },

    vibrate: function (success, error, args) {
        var ms = args[0] || 500;
        goodVibrations.vibrateDevice(ms);
    },

    beep: function (success, error, args) {
        for (var i = args[0]; i > 0; i--) {
            _console.log("beep!");
        }
        notifications.openNotification("normal", "BEEP x " + args[0]);
    }
};

});
define('ripple/platform/cordova/2.0.0/bridge', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _prompt = require('ripple/ui/plugins/exec-dialog');

module.exports = {
    exec: function (success, fail, service, action, args) {
        var emulator = {
            "App": require('ripple/platform/cordova/2.0.0/bridge/app'),
            "Accelerometer": require('ripple/platform/cordova/2.0.0/bridge/accelerometer'),
            "Compass": require('ripple/platform/cordova/2.0.0/bridge/compass'),
            "Camera": require('ripple/platform/cordova/2.0.0/bridge/camera'),
            "Capture": require('ripple/platform/cordova/2.0.0/bridge/capture'),
            "Contacts": require('ripple/platform/cordova/2.0.0/bridge/contacts'),
            "Debug Console": require('ripple/platform/cordova/2.0.0/bridge/console'),
            "Device": require('ripple/platform/cordova/2.0.0/bridge/device'),
            "File": require('ripple/platform/cordova/2.0.0/bridge/file'),
            "Geolocation": require('ripple/platform/cordova/2.0.0/bridge/geolocation'),
            "Media": require('ripple/platform/cordova/2.0.0/bridge/media'),
            "Network Status": require('ripple/platform/cordova/2.0.0/bridge/network'),
            "NetworkStatus": require('ripple/platform/cordova/2.0.0/bridge/network'),
            "Notification": require('ripple/platform/cordova/2.0.0/bridge/notification')
        };

        try {
            emulator[service][action](success, fail, args);
        }
        catch (e) {
            console.log("missing exec:" + service + "." + action);
            console.log(args);
            console.log(e);
            console.log(e.stack);
            //TODO: this should really not log the above lines, but they are very nice for development right now
            _prompt.show(service, action, success, fail);
        }
    }
};

});
define('ripple/platform/cordova/2.0.0/logger', function (require, exports, module) {
module.exports = {
    log: function (msg) {
        console.log(msg);
    }
};

});
define('ripple/platform/cordova/2.0.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (configValidationObject) {
        var valid = true;
        valid = !((!configValidationObject.widget.validationResult[0].attributes.xmlns.valid) ||
            (!configValidationObject.widget.validationResult[0].attributes["xmlns:gap"].valid));

        return valid;
    },
    extractInfo: function (configValidationObject) {
        if (!configValidationObject) {
            return null;
        }

        var widgetInfo = {};

        widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
        widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
        widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xmlns:gap": {
                    attributeName: "xmlns:gap",
                    required: true,
                    type: "list",
                    listValues: ["http://phonegap.com/ns/1.0"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                },
                dir: {
                    attributeName: "dir",
                    required: false,
                    type: "list",
                    listValues: ["ltr", "rtl", "lro", "rlo"]
                },
                id: {
                    attributeName: "id",
                    required: false,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    required: false,
                    type: "string"
                },
                height: {
                    attributeName: "height",
                    required: false,
                    type: "integer"
                },
                width: {
                    attributeName: "width",
                    required: false,
                    type: "integer"
                },
                viewmodes: {
                    attributeName: "viewmodes",
                    required: false,
                    type: "list",
                    listValues: ["floating", "fullscreen"]
                }
            },
            children: {
                name: {
                    nodeName: "name",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "short": {
                            attributeName: "short",
                            type: "string",
                            required: false
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 1,
                    type: "string",
                    attributes: {
                        email: {
                            attributeName: "email",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.EMAIL
                        },
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 1,
                    type: "string",
                    attributes: {
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        src: {
                            attributeName: "src",
                            type: "string",
                            required: true
                        },
                        height: {
                            attributeName: "height",
                            required: false,
                            type: "integer"
                        },
                        width: {
                            attributeName: "width",
                            required: false,
                            type: "integer"
                        }
                    }
                },
                content: {
                    nodeName: "content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        src: {
                            attributeName: "src",
                            type: "string",
                            required: true
                        },
                        encoding: {
                            attributeName: "encoding",
                            type: "string",
                            required: false
                        },
                        type: {
                            attributeName: "type",
                            type: "string",
                            required: false
                        }
                    }
                },
                feature: {
                    nodeName: "feature",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        name: {
                            attributeName: "name",
                            type: "list",
                            required: true,
                            listValues: ["http://api.phonegap.com/1.0/accelerometer", "http://api.phonegap.com/1.0/camera",
                                "http://api.phonegap.com/1.0/compass", "http://api.phonegap.com/1.0/contacts", "http://api.phonegap.com/1.0/device",
                                "http://api.phonegap.com/1.0/events", "http://api.phonegap.com/1.0/file", "http://api.phonegap.com/1.0/geolocation",
                                "http://api.phonegap.com/1.0/media", "http://api.phonegap.com/1.0/network", "http://api.phonegap.com/1.0/notification",
                                "http://api.phonegap.com/1.0/storage"]
                        },
                        required: {
                            attributeName: "required",
                            type: "boolean",
                            required: false
                        }
                    }
                },
                preference: {
                    nodeName: "preference",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        name: {
                            attributeName: "name",
                            type: "string",
                            required: true
                        },
                        value: {
                            type: "string",
                            attributeName: "value",
                            required: false
                        },
                        readonly: {
                            attributeName: "readonly",
                            type: "boolean",
                            required: false
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/cordova/2.0.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event');

module.exports = {
    "NetworkStatus": {
        "connectionType": {
            "name": "Connection Type",
            "control": {
                "type": "select",
                "value": "ethernet"
            },
            "options": {
                "unknown": "UNKNOWN",
                "ethernet": "ETHERNET",
                "wifi": "WIFI",
                "2g": "CELL_2G",
                "3g": "CELL_3G",
                "4g": "CELL_4G",
                "none": "none"
            },
            "callback": function (setting) {
                var connected = setting !== "none";
                require('ripple/bus').send("network", connected);
            }
        },
        "lag": {
            "name": "Lag the network",
            "control": {
                type: "checkbox",
                value: false
            },
            "callback": function (setting) {
                require('ripple/bus').send("lag", setting);
            }
        },
    }
};

});
define('ripple/platform/cordova/2.0.0/spec/events', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function _fires(name, data) {
    return function () {
        cordova.fireDocumentEvent(name, data);
    };
}

module.exports = {
    "deviceready": {
        callback: _fires("deviceready")
    },
    "backbutton": {
        callback: _fires("backbutton")
    },
    "menubutton": {
        callback: _fires("menubutton")
    },
    "pause": {
        callback: _fires("pause")
    },
    "resume": {
        callback: _fires("resume")
    },
    "searchbutton": {
        callback: _fires("searchbutton")
    },
    "online": {
        callback: _fires("online")
    },
    "offline": {
        callback: _fires("offline")
    }
};

});
define('ripple/platform/cordova/2.0.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "accelerometer",
        "deviceSettings",
        "geoView",
        "widgetConfig",
        "platformEvents"
    ]
};

});
define('ripple/platform/cordova/2.0.0/spec', function (require, exports, module) {
function loadWebworks(win, device) {
    var builder = require('ripple/platform/builder'),
        platform = device.id === "Playbook" || device.id === "Colt" ? "tablet" : "handset",
        webworks = require('ripple/platform/webworks.' + platform + '/2.0.0/spec');

    builder.build(webworks.objects).into(win);
    builder.build(webworks.objects).into(window);
}

module.exports = {
    id: "cordova",
    version: "2.0.0",
    name: "Apache Cordova",
    type: "platform",
    nativeMethods: {},

    config: require('ripple/platform/cordova/2.0.0/spec/config'),
    device: require('ripple/platform/cordova/2.0.0/spec/device'),
    ui: require('ripple/platform/cordova/2.0.0/spec/ui'),
    events: require('ripple/platform/cordova/2.0.0/spec/events'),

    initialize: function (win) {
        var honeypot = require('ripple/honeypot'),
            devices = require('ripple/devices'),
            device = devices.getCurrentDevice(),
            bridge = require('ripple/platform/cordova/2.0.0/bridge'),
            cordova,
            topCordova = window.top.require('ripple/platform/cordova/2.0.0/spec'),
            get = function () {
                return cordova;
            },
            set = function (orig) {
                if (cordova) {
                    return;
                }

                cordova = orig;

                cordova.define.remove("cordova/exec");
                cordova.define("cordova/exec", function (require, exports, module) {
                    module.exports = bridge.exec;
                });

                cordova.UsePolling = true;

                //do nothing here as we will just call the callbacks ourselves
                cordova.define.remove("cordova/plugin/android/polling");
                cordova.define("cordova/plugin/android/polling", function (require, exports, module) {
                    module.exports = function () {};
                });

                var builder = cordova.require('cordova/builder'),
                    allTheThings = window,
                    base = cordova.require('cordova/common'),
                    iosPlugin;

                //HACK: Overwrite all the things, handles when cordova.js executes before we start booting
                builder.build(base.objects).intoAndClobber(allTheThings);
                cordova.require('cordova/channel').onNativeReady.fire();
                //  DIRTY HACK: once cordova is cleaned up, we do not
                //  need this.
                // reference issue: https://issues.apache.org/jira/browse/CB-1013
                try {
                    iosPlugin = cordova.require('cordova/plugin/ios/device');
                    bridge.exec(function (info) {
                        iosPlugin.setInfo(info);
                    }, null, 'Device', 'getDeviceInfo', []);
                } catch (e) {
                    cordova.require('cordova/channel').onCordovaInfoReady.fire();
                }
            };

        if (window.FileReader && !topCordova.nativeMethods.FileReader) {
            topCordova.nativeMethods.FileReader = window.FileReader;
        }

        if (device.manufacturer === "Research In Motion") {
            loadWebworks(win, device);
        }

        honeypot.monitor(win, "cordova").andRun(get, set);
    },

    objects: {
        MediaError: {
            path: "cordova/2.0.0/MediaError"
        },
        org: {
            children: {
                apache: {
                    children: {
                        cordova: {
                            children: {
                                Logger: {
                                    path: "cordova/2.0.0/logger"
                                },
                                JavaPluginManager: {
                                    path: "cordova/2.0.0/JavaPluginManager"
                                }
                            }
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/ivi/3.0/SpeechGrammar', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 SpeechGrammar = window.webkitSpeechGrammar;

module.exports = SpeechGrammar;

});
define('ripple/platform/ivi/3.0/SpeechGrammarList', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 SpeechGrammarList = window.webkitSpeechGrammarList;

module.exports = SpeechGrammarList;

});
define('ripple/platform/ivi/3.0/SpeechRecognition', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 SpeechRecognition = window.webkitSpeechRecognition;

module.exports = SpeechRecognition;

});
define('ripple/platform/ivi/3.0/VehiclePanelEngine', function (require, exports, module) {

/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    dbinit = require('ripple/platform/ivi/3.0/dbinit'),
    _vehicleMapStack = {},
    _databaseName = "ivi-vehicle-database",
    VehiclePanelEngine;

function _save (data) {
    db.saveObject(_databaseName, data);
}

function _get () {
    var database = db.retrieveObject(_databaseName);

    if (!database) {
        db.saveObject(_databaseName, dbinit.Vehicle);
        database = db.retrieveObject(_databaseName);
    }

    return database;
}

VehiclePanelEngine = function () {
    var _CONFIGURATION = "configuration", _AUTO = "auto",
        _database,
        _configuration, _currentConfiguration,
        _supported, _settings, _autoRunning;

    function _init () {
        _database = _get();

        _settings = _database.settingData;

        _configuration = _database.configurationData;
        _currentConfiguration = _database.currentConfiguration;

        _supported = _database.supported;

        _autoRunning = _database.autoRunningData;
    }

    this.saveData = function (supported, currentConfiguration, configuration, settings, autoRunning) {
        _database.supported = supported;
        _database.currentConfiguration = currentConfiguration;
        _database.settingData = settings;
        _database.configurationData[currentConfiguration] = configuration;
        _database.autoRunningData[0] = autoRunning;

        _save(_database);
    };

    function _formatVehicleDB (map, db) {
        var formatSettings = {},
            VehicleMap = map, vehicleData = db,
            property, name, item, i = 0;

        for (property in VehicleMap) {
            name = property.split("-")[0];
            item = property.split("-")[1];

            if (!formatSettings[name]) {
                formatSettings[name] = {};
            }

            formatSettings[name][item] = utils.copy(VehicleMap[property]);
            formatSettings[name][item].value = vehicleData[i];

            i++;
        }

        return formatSettings;
    }

    /**
     * get
     * @return {Object}
     */
    this.getConfiguration = function () {
        var configuration = {}, i, j, dataIndex, tempArray,
            configurationMap = _vehicleMapStack.vehicleConfigurationMap,
            configurationData = _configuration;

        for (j = 0; j < configurationData.length; j++) {
            dataIndex = _CONFIGURATION + j;
            configuration[dataIndex] = {};

            for (i = 0; i < configurationMap.length; i++) {
                tempArray = configurationMap[i].split("-");

                if (!configuration[dataIndex][tempArray[0]]) {
                    configuration[dataIndex][tempArray[0]] = {};
                }
                configuration[dataIndex][tempArray[0]][tempArray[1]] = configurationData[j][i];
            }
        }

        return configuration;
    };

    /**
     * get
     * @return {String}
     */
    this.getCurrentConfiguration = function () {
        return _CONFIGURATION + _currentConfiguration;
    };

    /**
     * get
     * @return {Array}
     */
    this.getProperties = function () {
        return _vehicleMapStack.vehicleProperties;
    };

    /**
     * get supported vehicle properties name.
     * @return {Array}
     */
    this.getSupported = function () {
        return _supported;
    };

    /**
     * get property unit.
     * @param property
     * @param item
     * @return {String}
     */
    this.getPropertyUnit = function (property, item) {
        var unitKey = property + "-" + item,
            propertyUnitMap = _vehicleMapStack.vehiclePropertyUnitsMap;

        return !propertyUnitMap[unitKey] ? "" : "(" + propertyUnitMap[unitKey] + ")";
    };

    this.getPropertyRange = function (property, item) {
        var rangeKey = property + "-" + item,
            propertyRangeMap = _vehicleMapStack.vehiclePropertyRangeMap;

        return !propertyRangeMap[rangeKey] ? false : propertyRangeMap[rangeKey];
    };

    /**
     * get
     * @param property
     * @param item
     * @return {*}
     */
    this.getPropertyConstant = function (property, item) {
        var propertyConstants = _vehicleMapStack.vehiclePropertyConstantsMap;

        return !propertyConstants[property] ? null : propertyConstants[property][item];
    };

    this.getSettings = function () {
        return _formatVehicleDB(_vehicleMapStack.vehicleSettingMap, _settings);
    };

    this.getAutoRunning = function () {
        var autoRunning = {}, i,
            autoRunningMap = _vehicleMapStack.vehicleAutoRunningMap,
            autoRunningData = _autoRunning;

        for (i = 0; i < _autoRunning.length; i++) {
            autoRunning[_AUTO + i] = _formatVehicleDB(autoRunningMap, autoRunningData[i]);
        }
        return autoRunning;
    };

    _init();
};

//can support all properties.
_vehicleMapStack.vehicleProperties = [
    "VehicleSpeed", "WheelSpeed", "EngineSpeed", "VehiclePowerModeType",
    "Acceleration", "Transmission", "CruiseControlStatus", "LightStatus",
    "InteriorLightStatus", "Horn", "Fuel", "EngineOil", "Temperature",
    "RainSensor", "ClimateControl", "Sunroof", "ConvertibleRoof",
     "Identification", "SizeConfiguration", "FuelConfiguration",
    "TransmissionConfiguration", "Odometer", "BatteryStatus", "ParkingBrake",
    "AntilockBrakingSystem", "TractionControlSystem", "AirbagStatus",
    "NightMode", "DrivingMode", "ButtonEvent", "SteeringWheel",
    "ThrottlePosition", "EngineCoolant"
];

//Vehicle Configuration
_vehicleMapStack.vehicleConfigurationMap = [
    "Identification-WMI", "Identification-VIN", "SizeConfiguration-width",
    "SizeConfiguration-height", "SizeConfiguration-length",
    "FuelConfiguration-fuelType", "FuelConfiguration-refuelPosition",
    "TransmissionConfiguration-transmissionGearType"
];

//all ranged attributes' min. max and step.
_vehicleMapStack.vehiclePropertyRangeMap = {
    "VehicleSpeed-speed": [0, 400, 1],
    "WheelSpeed-speed": [0, 400, 1],
    "EngineSpeed-speed": [0, 10000, 20],
    "Acceleration-x": [0, 200, 1],
    "Acceleration-y": [0, 200, 1],
    "Acceleration-z": [0, 200, 1],
    "Fuel-level": [0, 100, 1],
    "Fuel-range": [0, 1000, 1],
    "Fuel-instantConsumption": [0, 100, 1],
    "Fuel-fuelConsumedSinceRestart": [0, 100, 1],
    "Fuel-vehicleTimeSinceRestart": [0, 100, 1],
    "EngineOil-remaining": [0, 100, 1],
    "EngineOil-temperature": [0, 100, 1],
    "EngineOil-pressure": [0, 1000, 1],
    "Temperature-interiorTemperature": [-5, 35, 1],
    "Temperature-exteriorTemperature": [-40, 60, 1],
    "Odometer-distanceTotal": [0, 10000, 10],
    "CruiseControlStatus-speed": [1, 100, 1],
    "ClimateControl-targetTemperature": [0, 35, 7],
    "Sunroof-openness": [0, 100, 1],
    "Sunroof-tilt": [0, 100, 1],
    "BatteryStatus-voltage": [0, 12, 1],
    "BatteryStatus-current": [0, 200, 1],
    "ButtonEvent-buttonEvent": [0, 100, 1],
    "SteeringWheel-angle": [-90, 90, 1],
    "ThrottlePosition-value": [0, 100, 1],
    "EngineCoolant-level": [0, 100, 1],
    "EngineCoolant-temperature": [0, 100, 1],
};

//simulate car running attributes' controller-types.
_vehicleMapStack.vehicleAutoRunningMap = {
    "VehicleSpeed-speed": {
        "type": "range"
    },
    "WheelSpeed-speed": {
        "type": "range"
    },
    "EngineSpeed-speed": {
        "type": "range"
    },
    "VehiclePowerModeType-value": {
        "type": "select",
        "options": [{"OFF": "off"},{"ACCESSORY1": "accessory1"},
            {"ACCESSORY2": "accessory2"},{"RUNNING": "running"}]
    },
    "Acceleration-x": {
        "type": "range"
    },
    "Acceleration-y": {
        "type": "range"
    },
    "Acceleration-z": {
        "type": "range"
    },
    "Fuel-level": {
        "type": "range"
    },
    "Fuel-range": {
        "type": "range"
    },
    "Fuel-instantConsumption": {
        "type": "range"
    },
    "Fuel-vehicleTimeSinceRestart": {
        "type": "range"
    },
    "Fuel-fuelConsumedSinceRestart": {
        "type": "range"
    },
    "EngineOil-remaining": {
        "type": "range"
    },
    "EngineOil-temperature": {
        "type": "range"
    },
    "EngineOil-pressure": {
        "type": "range"
    },
    "Temperature-interiorTemperature": {
        "type": "range"
    },
    "Temperature-exteriorTemperature": {
        "type": "range"
    },
    "RainSensor-rain": {
        "type": "select",
        "options": [{"No Rain": 0},{"Rain 1": 1},{"Rain 2": 2},{"Rain 3": 3},
            {"Rain 4": 4},{"Rain 5": 5},{"Rain 6": 6},{"Rain 7": 7},
            {"Rain 8": 8},{"Rain 9": 9},{"Heaviest": 10}]
    },
    "Odometer-distanceTotal": {
        "type": "range"
    },
    "ButtonEvent-buttonEvent": {
        "type": "range"
    },
    "SteeringWheel-angle": {
        "type": "range"
    },
    "ThrottlePosition-value": {
        "type": "range"
    },
    "EngineCoolant-level": {
        "type": "range"
    },
    "EngineCoolant-temperature": {
        "type": "range"
    }
};

//Vehicle Setting attributes' controller-types.
_vehicleMapStack.vehicleSettingMap = {
    "Transmission-gear": {
        "type": "select",
        "options": [{"NEUTRAL": 0},{"FIRST": 1},{"SECOND": 2},{"THIRD": 3},
            {"FORTH": 4},{"FIFTH": 5},{"SIXTH": 6},{"SEVENTH": 7},
            {"EIGHTH": 8},{"NINTH": 9},{"TENTH": 10},{"CVT": 64},
            {"REVERSE": 128},{"PARK": 255}]
    },
    "Transmission-mode": {
        "type": "select",
        "options": [{"NORMAL": 0},{"SPORT": 1},{"ECONOMY": 2},
            {"OEMCUSTOM1": 3},{"OEMCUSTOM2": 4}]
    },
    "CruiseControlStatus-status": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "CruiseControlStatus-speed": {
        "type": "range"
    },
    "LightStatus-head": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "LightStatus-rightTurn": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "LightStatus-leftTurn": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "LightStatus-brake": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "LightStatus-fog": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "LightStatus-hazard": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "LightStatus-parking": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "LightStatus-highBeam": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "InteriorLightStatus-passenger": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "InteriorLightStatus-driver": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "InteriorLightStatus-center": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "Horn-status": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "ClimateControl-airflowDirection": {
        "type": "select",
        "options": [{"FRONTPANEL": 0},{"FLOORDUCT": 1},{"FRONT": 0x02},
            {"DEFROSTER": 0x04}]
    },
    "ClimateControl-fanSpeedLevel": {
        "type": "select",
        "options": [{"0": 0},{"1": 1},{"2": 2},{"3": 3},{"4": 4},{"5": 5},
            {"6": 6},{"7": 7}]
    },
    "ClimateControl-targetTemperature": {
        "type": "range"
    },
    "ClimateControl-airConditioning": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "ClimateControl-airRecirculation": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "ClimateControl-heater": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "ClimateControl-steeringWheelHeater": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "ClimateControl-seatHeater": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "ClimateControl-seatCooler": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "Sunroof-openness": {
        "type": "range"
    },
    "Sunroof-tilt": {
        "type": "range"
    },
    "ConvertibleRoof-status": {
        "type": "select",
        "options": [{"CLOSED": "closed"},{"CLOSING": "closing"},
            {"OPENING": "opening"},{"OPENED": "opened"}]
    },
    "ParkingBrake-status": {
        "type": "select",
        "options": [{"INACTIVE": "inactive"},{"ACTIVE": "active"},
            {"ERROR": "error"}]
    },
    "AntilockBrakingSystem-engaged": {
        "type": "radio",
        "options":[{"Engaged": true}, {"Idle": false}]
    },
    "TractionControlSystem-enabled": {
        "type": "radio",
        "options": [{"On": true}, {"Off": false}]
    },
    "AirbagStatus-activated": {
        "type": "radio",
        "options": [{"INACTIVE": false}, {"ACTIVE": true}]
    },
    "NightMode-mode": {
        "type": "radio",
        "options": [{"Night": true}, {"Day": false}]
    },
    "DrivingMode-mode": {
        "type": "radio",
        "options": [{"Driving": true}, {"No Driving": false}]
    },
    "BatteryStatus-voltage": {
        "type": "range"
    },
    "BatteryStatus-current": {
        "type": "range"
    }
};

//attributes units
_vehicleMapStack.vehiclePropertyUnitsMap = {
    "VehicleSpeed-speed": "kph",
    "WheelSpeed-speed": "m/h",
    "EngineSpeed-speed": "rpm",
    "CruiseControlStatus-speed": "kph",
    "Fuel-level": "%",
    "Fuel-instantConsumption": "ml/s",
    "Fuel-vehicleTimeSinceRestart": "km/l",
    "Fuel-fuelConsumedSinceRestart": "km/l",
    "EngineOil-remaining": "%",
    "EngineOil-temperature": "C",
    "EngineOil-pressure": "kpa",
    "Temperature-interiorTemperature": "C",
    "Temperature-exteriorTemperature": "C",
    "ClimateControl-targetTemperature": "C",
    "Sunroof-openness": "%",
    "Sunroof-tilt": "%",
    "SizeConfiguration-width": "mm",
    "SizeConfiguration-height": "mm",
    "SizeConfiguration-length": "mm",
    "Odometer-distanceTotal": "km",
    "BatteryStatus-voltage": "V",
    "BatteryStatus-current": "A",
    "SteeringWheel-angle": "deg",
    "ThrottlePosition-value": "%",
    "EngineCoolant-level": "%",
    "EngineCoolant-temperature": "C"
};

//key and value of select types in attributes
_vehicleMapStack.vehiclePropertyConstantsMap = {
    "FuelConfiguration": {
        "fuelType": {
            "val0": "GASOLINE",
            "val1": "HIGH_OCTANE",
            "val2": "DIESEL",
            "val3": "ELECTRIC",
            "val4": "HYDROGEN"
        },
        "refuelPosition": {
            "val0": "LEFT",
            "val1": "RIGHT",
            "val2": "FRONT",
            "val3": "REAR"
        }
    },
    "TransmissionConfiguration": {
        "transmissionGearType": {
            "val0": "AUTO",
            "val1": "MANUAL",
            "val2": "CV"
        }
    },
    "VehiclePowerModeType": {
        "value": {
            "val0": "off",
            "val1": "accessory1",
            "val2": "accessory2",
            "val3": "running"
        }
    }
};

exports.VehiclePanelEngine = new VehiclePanelEngine();

});
define('ripple/platform/ivi/3.0/WebAPIError', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/ivi/3.0/errorcode');

var msg = {
    1: "Permission denied.",
    2: "Unsupported property.",
    3: "Timeout.",
    10: "Unknown."
},
    errType = {
    1: "PermissionDeniedError",
    2: "PropertyUnavailableError",
    3: "TimeoutError",
    10: "UnknownError"
};

module.exports = function (code, message, name) {
    var _code, _message, _name;

    if (typeof code !== 'number') {
        _code = errorcode.UNKNOWN;
        _message = msg[_code];
        _name = errType[_code];
    } else {
        _code = code;
        if (typeof message === 'string') {
            _message = message;
        } else {
            _message = msg[_code];
        }
        if (typeof name === 'string') {
            _name = name;
        } else {
            _name = errType[_code];
        }
    }

    this.__defineGetter__("code", function () {
        return _code;
    });
    this.__defineGetter__("message", function () {
        return _message;
    });
    this.__defineGetter__("name", function () {
        return _name;
    });
};

});
define('ripple/platform/ivi/3.0/WebAPIException', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/ivi/3.0/errorcode');

var msg = {
        1: "Permission denied.",
        2: "Unsupported property.",
        3: "Timeout.",
        10: "Unknown."
    },
    errType = {
        1: "PermissionDeniedError",
        2: "PropertyUnavailableError",
        3: "TimeoutError",
        10: "UnknownError"
    };

module.exports = function (code, message, name) {
    var g, c, _code, _message, _name;

    for (c in errorcode) {
        g = errorcode.__lookupGetter__(c);
        if (g) {
            this.__defineGetter__(c, g);
        }
    }

    if (typeof code !== 'number') {
        _code = errorcode.UNKNOWN;
        _message = msg[_code];
        _name = errType[_code];
    } else {
        _code = code;
        if (typeof message === 'string') {
            _message = message;
        } else {
            _message = msg[_code];
        }
        if (typeof name === 'string') {
            _name = name;
        } else {
            _name = errType[_code];
        }
    }

    this.__defineGetter__("code", function () {
        return _code;
    });
    this.__defineGetter__("message", function () {
        return _message;
    });
    this.__defineGetter__("name", function () {
        return _name;
    });
};

});
define('ripple/platform/ivi/3.0/Zone', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation
 *
 * 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.
 */
module.exports = function (pro) {
    var zn = {};

    pro = pro ? pro : {};
    zn.value = pro.value || [];
    zn.driver = pro.driver || {};

    this.__defineGetter__("value", function () {
        return zn.value;
    });

    this.__defineSetter__("value", function (val) {
        try {
            zn.value = t.DOMString(val, "[]");
        }
        catch (err) {
        }
    });

    this.__defineGetter__("driver", function () {
        return zn.driver;
    });

    this.contains = function (zone) {
        var i;

        for (i = 0; i < zone.value.length; i++) {
            if (this.value.indexOf(zone.value[i]) > -1) {
                return true;
            }
        }
        return false;
    };

    this.equals = function (zone) {
        var i;

        if (zone.value.length !== this.value.length) {
            return false;
        }

        for (i = 0; i < zone.value.length; i++) {
            if (this.value.indexOf(zone.value[i]) === -1) {
                return false;
            }
        }
        return true;
    };
};

});
define('ripple/platform/ivi/3.0/dbinit', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 exception = require('ripple/exception'),
    DBBuilder,
    _data = {
        dbBuilder: null
    },
    _self = {};

function _initialize() {
    _data.dbBuilder = new DBBuilder();

    _data.dbBuilder.register("Vehicle", "dbvehicle.json");
    _data.dbBuilder.register("MediaServer", "dbmediaserver.json");
}

DBBuilder = function () {
    var self;

    // private
    function formatString(str) {
        return str.replace(/^\s+|[\t\n\r\v]+|\s+$/g, "").replace(/\s+/g, "");
    }

    // private
    function formatHex(str) {
        return str.replace(/,(0x[0-9a-fA-F]+?),/g, ',"$1",');
    }

    // public
    function register(type, dbFile, Extension) {
        _data[type] = Extension ? new Extension() : {};

        if (!dbFile)
            return;

        _self.__defineGetter__(type, function () {
            var fnInit;

            if (!_data[type].db) {
                fnInit = _data[type].initdb || initdb;
                _data[type].db = fnInit(dbFile);
            }

            return _data[type].db;
        });
    }

    function initdb(dbFile) {
        var xmlHttp, res;

        try {
            xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", "dbsamples/" + dbFile, false);
            xmlHttp.send();
        } catch (e) {
            exception.handle(e);
        }

        if (!xmlHttp.responseText) {
            return null;
        }

        res = formatHex(formatString(xmlHttp.responseText));

        return JSON.parse(res);
    }

    self = {
        register: register,
        initdb:   initdb
    };

    return self;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/ivi/3.0/errorcode', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 _self = {};

_self.__defineGetter__("PERMISSION_DENIED", function () {
    return 1;
});

_self.__defineGetter__("PROPERTY_UNAVAILABLE", function () {
    return 2;
});

_self.__defineGetter__("TIMEOUT", function () {
    return 3;
});

_self.__defineGetter__("UNKNOWN", function () {
    return 10;
});

module.exports = _self;

});
define('ripple/platform/ivi/3.0/ivi_utils', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 self,
    utils = require('ripple/utils'),
    errorcode = require('ripple/platform/ivi/3.0/errorcode'),
    WebAPIException = require('ripple/platform/ivi/3.0/WebAPIException');

self = module.exports = {
    _wac2_regexSanitize: function (regexString) {
        var escapePattern = /([^\\]|^)(%)/g, percentPattern = /\\%/g;
        return regexString.replace("^", "\\^")
                .replace("$", "\\$")
                .replace("(", "\\(")
                .replace(")", "\\)")
                .replace("<", "\\<")
                .replace("[", "\\[")
                .replace("{", "\\{")
                .replace(/\\([^%])/, "\\\\$1")    /* don't replace \\% */
                .replace("|", "\\|")
                .replace(">", "\\>")
                .replace(".", "\\.")
                .replace("*", "\\*")
                .replace("+", "\\+")
                .replace("?", "\\?")
                .replace(escapePattern, "$1.*")  /* replace % with .* */
                .replace(percentPattern, "%");   /* strip excape of % */
    },

    isValidDate: function (d) {
        if (Object.prototype.toString.call(d) !== "[object Date]")
            return false;
        return !isNaN(d.getTime());
    },
    isValidTZDate: function (d) {
        if (d &&  (d instanceof tizen.TZDate)) {
            return true;
        }
        return false;
    },
    isValidArray: function (a) {
        return (Object.prototype.toString.call(a) === "[object Array]");
    },

    matchOptionArrayString: function (src, attr, pattern) {
        /* src.obj[attr] is a StringArray */
        var _pattern, re, _stringMatch;
        _pattern = this._wac2_regexSanitize(pattern);
        re = new RegExp("^" + _pattern + "$", "i");

        _stringMatch = function (obj, index) {
            if (pattern.search(/^%*$/i) === 0)
                return true;
            if (obj[attr] === undefined || obj[attr] === null)
                return false;
            return obj[attr].some(function (f) {
                return f.search(re) !== -1;
            });
        };
        return utils.filter(src, _stringMatch);
    },

    matchAttributeBooleanFilter: function (src, attr, value) {
        // only support EXACTLY matchFlag
        var _booleanMatch, atr = attr.split(".");

        if (atr.length === 2) {
            _booleanMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                return (obj[atr[0]][atr[1]] === value);
            };
        } else {
            _booleanMatch = function (obj, index) {
                return (obj[attr] === value);
            };
        }

        return utils.filter(src, _booleanMatch);
    },

    matchAttributeArrayFilter: function (src, attr, matchFlag, value) {
        var _re, _arrayMatch, atr = attr.split("."), _existMatch;

        if (atr.length === 2) {
            _existMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                return (obj[atr[0]][atr[1]] !== undefined);
            };
        } else {
            _existMatch = function (obj, index) {
                return (obj[attr] !== undefined);
            };
        }

        if (value === undefined || value === null) {
            return utils.filter(src, _existMatch);
        }

        switch (matchFlag)
        {
        case "EXACTLY":
            _re = new RegExp("^" + value + "$");
            break;
        case "FULLSTRING":
            _re = new RegExp("^" + value + "$", "i");
            break;
        case "CONTAINS":
            _re = new RegExp(value, "i");
            break;
        case "STARTSWITH":
            _re = new RegExp("^" + value, "i");
            break;
        case "ENDSWITH":
            _re = new RegExp(value + "$", "i");
            break;
        case "EXISTS":
            return utils.filter(src, _existMatch);
        default:
            return [];
        }

        if (atr.length === 2) {
            _arrayMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                return (obj[atr[0]][atr[1]] && obj[atr[0]][atr[1]].some(function (o) {
                    return (o.search(_re) !== -1);
                }));
            };
        } else {
            _arrayMatch = function (obj, index) {
                return (obj[attr] && obj[attr].some(function (o) {
                    return (o.search(_re) !== -1);
                }));
            };
        }

        return utils.filter(src, _arrayMatch);
    },

    matchAttributeRangeFilter: function (src, attr, low, high) {
        var _rangeMatch, atr = attr.split(".");

        if (atr.length === 2) {
            _rangeMatch = function (obj, index) {
                var matched = true;

                if (!obj[atr[0]])
                    return false;

                if (low !== null && low !== undefined) {
                    matched = (obj[atr[0]][atr[1]] >= low);
                }
                if (matched && (high !== null && high !== undefined)) {
                    matched = (obj[atr[0]][atr[1]] <= high);
                }
                return matched;
            };
        } else {
            _rangeMatch = function (obj, index) {
                var matched = true;

                if (low !== null && low !== undefined) {
                    matched = (obj[attr] >= low);
                }
                if (matched && (high !== null && high !== undefined)) {
                    matched = (obj[attr] <= high);
                }
                return matched;
            };
        }
        return utils.filter(src, _rangeMatch);
    },

    matchAttributeFilter: function (src, attr, matchFlag, value) {
        var _re, _stringMatch, atr = attr.split("."),
            _existMatch;

        if (atr.length === 2) {
            _existMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                return (obj[atr[0]][atr[1]] !== undefined);
            };
        } else {
            _existMatch = function (obj, index) {
                return (obj[attr] !== undefined);
            };
        }

        if (value === undefined || value === null) {
            return utils.filter(src, _existMatch);
        }

        switch (matchFlag)
        {
        case "EXACTLY":
            _re = new RegExp("^" + value + "$");
            break;
        case "FULLSTRING":
            _re = new RegExp("^" + value + "$", "i");
            break;
        case "CONTAINS":
            _re = new RegExp(value, "i");
            break;
        case "STARTSWITH":
            _re = new RegExp("^" + value, "i");
            break;
        case "ENDSWITH":
            _re = new RegExp(value + "$", "i");
            break;
        case "EXISTS":
            return utils.filter(src, _existMatch);
        default:
            return [];
        }
        if (atr.length === 2) {
            _stringMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                if (matchFlag === "EXACTLY") {
                    return (obj[atr[0]][atr[1]] === value);
                } else if (typeof obj[atr[0]][atr[1]] !== 'string') {
                    return false;
                }

                return (obj[atr[0]][atr[1]].search(_re) !== -1);
            };
        } else {
            _stringMatch = function (obj, index) {
                if (matchFlag === "EXACTLY") {
                    return (obj[attr] === value);
                } else if (typeof obj[attr] !== 'string') {
                    return false;
                }

                return (obj[attr].search(_re) !== -1);
            };
        }
        return utils.filter(src, _stringMatch);
    },

    matchOptionString: function (src, attr, pattern) {
        /* src.obj[attr] is a string */
        var _stringMatch, _pattern, _re;
        _pattern = this._wac2_regexSanitize(pattern);
        _re = new RegExp("^" + _pattern + "$", "mi");

        _stringMatch = function (obj, index) {
            return (obj[attr].search(_re) !== -1);
        };
        return utils.filter(src, _stringMatch);
    },

    matchOptionDate: function (src, attr, filterStart, filterEnd) {
        var _dateMatch;
        _dateMatch = function (obj, index) {
            var matched = true, valueDate = obj[attr];

            if (filterStart !== undefined && filterStart !== null) {
                matched = (valueDate.getTime() >= filterStart.getTime());
            }
            if (matched && (filterEnd !== undefined && filterEnd !== null)) {
                matched = (valueDate.getTime() <= filterEnd.getTime());
            }
            return matched;
        };
        return utils.filter(src, _dateMatch);
    },

    matchOptionShortArray: function (src, attr, filterArray) {
        /* src.obj[attr] is a short, filterArray is an array
           i.e. find status is [CONFRIMED or TENTATIVE] */
        var arraySome = function (obj, index) {
            return filterArray.some(function (f) {
                return f === obj[attr];
            });
        };
        return utils.filter(src, arraySome);
    },

    validateArgumentType: function (arg, argType, errorObj) {
        var invalidArg = false;

        switch (argType) {
        case "array":
            if (!arg instanceof Array) {
                invalidArg = true;
            }
            break;
        case "date":
            if (!arg instanceof Date) {
                invalidArg = true;
            }
            break;
        case "integer":
            if (typeof Number(arg) !== "number" || Number(arg) !== Math.floor(arg)) {
                invalidArg = true;
            }
            break;
        default:
            if (typeof arg !== argType) {
                invalidArg = true;
            }
            break;
        }

        if (invalidArg) {
            throw errorObj;
        }
    },

    validateCallbackType: function (successCallback, errorCallback) {
        if (successCallback) {
            this.validateArgumentType(successCallback, "function",
                new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
        }
        if (errorCallback) {
            this.validateArgumentType(errorCallback, "function",
                new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
        }
    },

    validateEqualArrays: function (arrayOne, arrayTwo) {
        var isEqual = false, i;

        if (Object.prototype.toString.call(arrayTwo) === "[object Array]" &&
            Object.prototype.toString.call(arrayTwo) === "[object Array]" &&
            arrayOne.length === arrayTwo.length) {
            isEqual = true;
            for (i in arrayOne) {
                if (arrayOne[i] !== arrayTwo[i]) {
                    isEqual = false;
                    break;
                }
            }
        }
        return isEqual;
    },

    validateTypeMismatch: function (onSuccess, onError, name, callback) {

        if (onSuccess === undefined || onSuccess === null) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        this.validateArgumentType(onSuccess, "function",
                                  new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
        if (onError !== null && onError !== undefined) {
            this.validateArgumentType(onError, "function",
                                      new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
        }

        return callback && callback();
    },

    isEmptyObject: function (obj) {
        var prop;

        for (prop in obj) {
            return false;
        }
        return true;
    },

    arrayComposite: function (mode, arrayA, arrayB) {
        var combinedArray = arrayA.concat(arrayB),
            intersectionArray = arrayA.filter(function (value) {
                if (utils.arrayContains(arrayB, value)) {
                    return true;
                }

                return false;
            });

        switch (mode) {
        case "AND":
        case "INTERSECTION":
            return intersectionArray;
        case "OR":
        case "UNION":
            return intersectionArray.concat(combinedArray.filter(function (value) {
                if (utils.arrayContains(intersectionArray, value)) {
                    return false;
                }

                return true;
            }));
        default:
            return undefined;
        }
    },

    isEqual: function (srcObj, aimObj) {
        var i;

        if (typeof srcObj !== typeof aimObj) {
            return false;
        }

        if (srcObj === null || srcObj === undefined || typeof srcObj === 'number' ||
            typeof srcObj === 'string' || typeof srcObj === 'boolean') {
            return srcObj === aimObj;
        }

        for (i in srcObj) {
            if (!aimObj.hasOwnProperty(i) || !self.isEqual(srcObj[i], aimObj[i])) {
                return false;
            }
        }

        return true;
    },

    query: function (objects, filter, sortMode, count, offset) {
        function isCompositeFilter(filter) {
            return (filter.type) ? true : false;
        }

        function isAttributeFilter(filter) {
            return (filter.matchFlag) ? true : false;
        }

        function getValue(obj, key) {
            var keys = key.split("."),
                value = obj[keys[0]],
                i;

            for (i = 1; i < keys.length; i++) {
                if (value[keys[i]]) {
                    value = value[keys[i]];
                }
            }

            return value;
        }

        function _filter(objects, filter) {
            var i, results, eachResult, filterFunc;

            if (isCompositeFilter(filter)) {
                for (i in filter.filters) {
                    eachResult = _filter(objects, filter.filters[i]);
                    results = (results === undefined) ? eachResult : self.arrayComposite(filter.type, results, eachResult);
                }
                return results;
            }

            if (isAttributeFilter(filter)) {
                for (i in objects) {
                    if (filter.attributeName in objects[i])
                        break;
                }
                filterFunc = self.isValidArray(objects[i][filter.attributeName]) ? self.matchAttributeArrayFilter : self.matchAttributeFilter;
                results = filterFunc(objects, filter.attributeName, filter.matchFlag, filter.matchValue);
            } else {
                results = self.matchAttributeRangeFilter(objects, filter.attributeName, filter.initialValue, filter.endValue);
            }

            return results;
        }

        function _sort(objects, sortMode) {
            objects.sort(function (a, b) {
                return (sortMode.order === "ASC") ?
                    (getValue(a, sortMode.attributeName) < getValue(b, sortMode.attributeName) ? -1 : 1):
                    (getValue(a, sortMode.attributeName) > getValue(b, sortMode.attributeName) ? -1 : 1);
            });

            return objects;
        }

        var res = objects;

        if (filter) {
            res = _filter(res, filter);
        }

        if (sortMode) {
            _sort(res, sortMode);
        }

        if (offset || count) {
            offset = (offset > 0) ? offset : 0;
            res = (count > 0) ? res.slice(offset, offset + count) : res.slice(offset);
        }

        return res;
    },

    copyString: function (str) {
        var newStr, charConvert = [], i;

        if (typeof str !== 'string') {
            return str;
        }
        for (i = 0; i < str.length; i++) {
            charConvert[i] = str.charAt(i);
        }
        newStr = charConvert.join("");

        return newStr;
    },

    copy: function (obj) {
        var i,
            newObj = jQuery.isArray(obj) ? [] : {};

        if (typeof obj === 'number' ||
            typeof obj === 'string' ||
            typeof obj === 'boolean' ||
            obj === null ||
            obj === undefined) {
            return obj;
        }

        if (obj instanceof Date) {
            return new Date(obj);
        }

        if (obj instanceof RegExp) {
            return new RegExp(obj);
        }

        for (i in obj) {
            if (obj.hasOwnProperty(i)) {
                if (obj.__lookupGetter__(i)) {
                    newObj.__defineGetter__(i, (function (key) {
                        return function () {
                            return self.copy(obj[key]);
                        };
                    }(i)));
                }
                else {
                    newObj[i] = self.copy(obj[i]);
                }
            }
        }

        return newObj;
    }
};

});
define('ripple/platform/ivi/3.0/locale', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    t = require('ripple/platform/ivi/3.0/typecast'),
    errorcode = require('ripple/platform/ivi/3.0/errorcode'),
    WebAPIException = require('ripple/platform/ivi/3.0/WebAPIException'),
    _security = {
        "http://tizen.org/privilege/vehicle": []
    },
    _data = {
        DEFAULT: {lang: "eng"},
        listener: null,
        locale: null,
        language: [],
        dbStorage: "ivi-locale"
    },
    _self;

function _save(data) {
    db.saveObject(_data.dbStorage, data);
}

function _get() {
    var database = db.retrieveObject(_data.dbStorage);

    if (!database) {
        db.saveObject(_data.dbStorage, _data.DEFAULT);
        database = db.retrieveObject(_data.dbStorage);
    }

    return database;
}

function _initialize() {
    _data.locale = _get();

    // ISO 639-2 Language Codes
    _data.language = ["abk", "ace", "ach", "ada", "ady", "ady", "aar", "afh",
        "afr", "afa", "ain", "aka", "akk", "alb", "sqi", "gsw", "ale", "alg",
        "gsw", "tut", "amh", "anp", "apa", "ara", "arg", "arp", "arw", "arm",
        "hye", "rup", "art", "rup", "asm", "ast", "ast", "ath", "aus", "map",
        "ava", "ave", "awa", "aym", "aze", "ast", "ban", "bat", "bal", "bam",
        "bai", "bad", "bnt", "bas", "bak", "baq", "eus", "btk", "bej", "bej",
        "bel", "bem", "ben", "ber", "bho", "bih", "bik", "byn", "bin", "bis",
        "byn", "zbl", "zbl", "zbl", "nob", "bos", "bra", "bre", "bug", "bul",
        "bua", "bur", "mya", "cad", "spa", "cat", "cau", "ceb", "cel", "cai",
        "khm", "chg", "cmc", "cha", "che", "chr", "nya", "chy", "chb", "nya",
        "chi", "zho", "chn", "chp", "cho", "zha", "chu", "chu", "chk", "chv",
        "nwc", "nwc", "syc", "rar", "cop", "cor", "cos", "cre", "mus", "crp",
        "cpe", "cpf", "cpp", "crh", "crh", "hrv", "cus", "cze", "ces", "dak",
        "dan", "dar", "del", "chp", "div", "zza", "zza", "din", "div", "doi",
        "dgr", "dra", "dua", "dut", "nld", "dum", "dyu", "dzo", "frs", "bin",
        "efi", "egy", "eka", "elx", "eng", "enm", "ang", "myv", "epo", "est",
        "ewe", "ewo", "fan", "fat", "fao", "fij", "fil", "fin", "fiu", "dut",
        "nld", "fon", "fre", "fra", "frm", "fro", "fur", "ful", "gaa", "gla",
        "car", "glg", "lug", "gay", "gba", "gez", "geo", "kat", "ger", "deu",
        "nds", "gmh", "goh", "gem", "kik", "gil", "gon", "gor", "got", "grb",
        "grc", "gre", "ell", "kal", "grn", "guj", "gwi", "hai", "hat", "hat",
        "hau", "haw", "heb", "her", "hil", "him", "hin", "hmo", "hit", "hmn",
        "hun", "hup", "iba", "ice", "isl", "ido", "ibo", "ijo", "ilo", "arc",
        "smn", "inc", "ine", "ind", "inh", "ina", "ile", "iku", "ipk", "ira",
        "gle", "mga", "sga", "iro", "ita", "jpn", "jav", "kac", "jrb", "jpr",
        "kbd", "kab", "kac", "kal", "xal", "kam", "kan", "kau", "pam", "kaa",
        "krc", "krl", "kar", "kas", "csb", "kaw", "kaz", "kha", "khi", "kho",
        "kik", "kmb", "kin", "zza", "kir", "zza", "tlh", "kom", "kon", "kok",
        "kor", "kos", "kpe", "kro", "kua", "kum", "kur", "kru", "kut", "kua",
        "kir", "lad", "lah", "lam", "day", "lao", "lat", "lav", "ast", "ltz",
        "lez", "lim", "lim", "lim", "lin", "lit", "jbo", "nds", "nds", "dsb",
        "loz", "lub", "lua", "lui", "smj", "lun", "luo", "lus", "ltz", "rup",
        "mac", "mkd", "mad", "mag", "mai", "mak", "mlg", "may", "msa", "mal",
        "div", "mlt", "mnc", "mdr", "man", "mni", "mno", "glv", "mao", "mri",
        "arn", "arn", "mar", "chm", "mah", "mwr", "mas", "myn", "men", "mic",
        "mic", "min", "mwl", "moh", "mdf", "rum", "ron", "rum", "ron", "mkh",
        "hmn", "lol", "mon", "mos", "mul", "mun", "nqo", "nah", "nau", "nav",
        "nav", "nde", "nbl", "ndo", "nap", "new", "nep", "new", "nia", "nic",
        "ssa", "niu", "zxx", "nog", "non", "nai", "nde", "frr", "sme", "nso",
        "nor", "nob", "nno", "zxx", "nub", "iii", "nym", "nya", "nyn", "nno",
        "nyo", "nzi", "ile", "oci", "pro", "arc", "xal", "oji", "chu", "chu",
        "nwc", "chu", "ori", "orm", "osa", "oss", "oss", "oto", "pal", "pau",
        "pli", "pam", "pag", "pan", "pap", "paa", "pus", "nso", "per", "fas",
        "peo", "phi", "phn", "fil", "pon", "pol", "por", "pra", "pro", "pan",
        "pus", "que", "raj", "rap", "rar", "qaa-qtz", "roa", "rum", "ron",
        "roh", "rom", "run", "rus", "kho", "sal", "sam", "smi", "smo", "sad",
        "sag", "san", "sat", "srd", "sas", "nds", "sco", "gla", "sel", "sem",
        "nso", "srp", "srr", "shn", "sna", "iii", "scn", "sid", "sgn", "bla",
        "snd", "sin", "sin", "sit", "sio", "sms", "den", "sla", "slo", "slk",
        "slv", "sog", "som", "son", "snk", "wen", "nso", "sot", "sai", "nbl",
        "alt", "sma", "spa", "srn", "zgh", "suk", "sux", "sun", "sus", "swa",
        "ssw", "swe", "gsw", "syr", "tgl", "tah", "tai", "tgk", "tmh", "tam",
        "tat", "tel", "ter", "tet", "tha", "tib", "bod", "tig", "tir", "tem",
        "tiv", "tlh", "tli", "tpi", "tkl", "tog", "ton", "tsi", "tso", "tsn",
        "tum", "tup", "tur", "ota", "tuk", "tvl", "tyv", "twi", "udm", "uga",
        "uig", "ukr", "umb", "mis", "und", "hsb", "urd", "uig", "uzb", "vai",
        "cat", "ven", "vie", "vol", "vot", "wak", "wln", "war", "was", "wel",
        "cym", "fry", "him", "wal", "wal", "wol", "xho", "sah", "yao", "yap",
        "yid", "yor", "ypk", "znd", "zap", "zza", "zza", "zen", "zha", "zul",
        "zun"];
}

_self = function () {
    var locale;

    function getLocale() {
        return _data.locale.lang;
    }

    function setLocale(newLocale) {
        t.Locale("setLocale", arguments);

        if (_data.language.indexOf(newLocale) === -1) {
            throw new WebAPIException(errorcode.UNKNOWN);
        }

        if (_data.locale.lang === newLocale)
            return;

        _data.locale.lang = newLocale;
        _save(_data.locale);

        window.setTimeout(function () {
            if (_data.listener) {
                _data.listener(newLocale);
            }
        }, 1);
    }

    function localeChanged(callback) {
        t.Locale("localeChanged", arguments);

        _data.listener = callback;
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    locale = {
        getLocale:         getLocale,
        setLocale:         setLocale,
        localeChanged:     localeChanged,
        handleSubFeatures: handleSubFeatures
    };

    return locale;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/ivi/3.0/mediaserver', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 dbinit = require('ripple/platform/ivi/3.0/dbinit'),
    ivi_utils = require('ripple/platform/ivi/3.0/ivi_utils'),
    t = require('ripple/platform/ivi/3.0/typecast'),
    errorcode = require('ripple/platform/ivi/3.0/errorcode'),
    WebAPIError = require('ripple/platform/ivi/3.0/WebAPIError'),
    WebAPIException = require('ripple/platform/ivi/3.0/WebAPIException'),
    MediaFactory,
    MediaObject,
    MediaContainer,
    MediaItem,
    MediaVideo,
    MediaAudio,
    MediaImage,
    MediaServer,
    _security = {
        "http://tizen.org/privilege/mediaserver": []
    },
    _data = {
        root: "",
        mediaServer: {}
    },
    _self;

function _initialize() {
    var db = dbinit.MediaServer,
        server = db.server,
        containers = db.containers,
        items = db.items,
        i;

    for (i = 0; i < containers.length; i++) {
        if (containers[i].Path === "/") {
            server.root = new MediaContainer(containers[i]);
            break;
        }
    }

    _data.root = _setRoot();

    for (i = 0; i < items.length; i++) {
        items[i].URLs = [_data.root + items[i].Path];
        items[i].ThumbnailURIs = _data.root + items[i].Path;
    }

    _data.mediaServer.server = server;
    _data.mediaServer.containers = containers;
    _data.mediaServer.items = items;
}

function _setRoot() {
    return location.pathname.replace("ripple.html", "resources/media");
}

function _formatSortMode(sortMode) {
    var order, attributeName,
        attributes = ["Type", "Path", "DisplayName", "URLs", "ThumbnailURIs",
                "MIMEType", "Rating", "Size", "Duration", "Album", "Genre",
                "Artists", "Width", "Height", "SampleRate"];

    order = sortMode.match(/[+|-]/g);
    if (order.length > 1) {
        return null;
    }

    attributeName = sortMode.match(/[A-Za-z]+/)[0];
    if (attributes.indexOf(attributeName) === -1) {
        return null;
    }

    return {
        order: (order[0] === "-") ? "DESC" : "ASC",
        attributeName: attributeName
    };
}

function _replacedQuoteSpace(filter) {
    var match = filter.match(/\"([a-z0-9A-Z]+)(\s+)([a-z0-9A-Z]+)\"/g);

    for (var i = 0; match && i < match.length; i++) {
        filter = filter.replace(match[i], match[i].replace(/\s+/g, "__"));
    }

    return filter.replace(/\"/g, "");
}

function _goFiltering(filter, items) {
    var str = _replacedQuoteSpace(filter),
        keyArray, tempArray, tempItems = [], results = [],
        cells = [], conditions = [], property, condition, value, i, p;

    keyArray = str.split(/\s+/);

    if ((keyArray.length + 1) % 4 !== 0) {
        return null;
    }

    while (keyArray.length > 0) {
        property = keyArray.shift();
        condition = keyArray.shift();
        value = keyArray.shift().replace("__", "");
        tempArray = [property, condition, value];

        if ((keyArray.indexOf("and") === 0) ||
                (keyArray.indexOf("or") === 0)) {
            conditions.push(keyArray.shift());
        }

        switch (condition) {
        case "contains":
            for (i = 0; i < items.length; i++) {
                if (items[i][property].indexOf(value) > -1) {
                    tempItems.push(items[i].Path);
                }
            }
            break;

        case "doesNotContain":
            for (i = 0; i < items.length; i++) {
                if (items[i][property].indexOf(value) === -1) {
                    tempItems.push(items[i].Path);
                }
            }
            break;

        case "exists":
            for (i = 0; i < items.length; i++) {
                if ((tempArray[2] === "true") ||
                    (tempArray[2] === true)) {
                    if (items[i][tempArray[0]]) {
                        tempItems.push(items[i].Path);
                    }
                } else if ((tempArray[2] === "false") ||
                    (tempArray[2] === false)) {
                    if (!items[i][tempArray[0]]) {
                        tempItems.push(items[i].Path);
                    }
                }
            }
            break;

        case "=":
            for (i = 0; i < items.length; i++) {
                if (items[i][property] === value) {
                    tempItems.push(items[i].Path);
                }
            }
            break;

        case "!=":
            for (i = 0; i < items.length; i++) {
                if (items[i][property] !== value) {
                    tempItems.push(items[i].Path);
                }
            }
            break;

        case "<":
            for (i = 0; i < items.length; i++) {
                if (items[i][property] < value) {
                    tempItems.push(items[i].Path);
                }
            }
            break;

        case "<=":
            for (i = 0; i < items.length; i++) {
                if (items[i][property] <= value) {
                    tempItems.push(items[i].Path);
                }
            }
            break;

        case ">":
            for (i = 0; i < items.length; i++) {
                if (items[i][property] > value) {
                    tempItems.push(items[i].Path);
                }
            }
            break;

        case ">=":
            for (i = 0; i < items.length; i++) {
                if (items[i][property] >= value) {
                    tempItems.push(items[i].Path);
                }
            }
            break;

        default:
            return null;
        }

        cells.push(ivi_utils.copy(tempItems));
        tempArray.length = 0;
        tempItems.length = 0;
    }

    while (true) {
        p = conditions.indexOf("and");
        if (p === -1)
            break;
        for (i = 0; i < cells[p + 1].length; i++) {
            if (cells[p].indexOf(cells[p + 1][i]) > -1) {
                results.push(cells[p + 1][i]);
            }
        }

        conditions.shift();
        cells.shift();
        cells.splice(0, 1, ivi_utils.copy(results));
        results.length = 0;
    }

    while (true) {
        p = conditions.indexOf("or");
        if (p === -1)
            break;
        results = [].concat(cells[p]);
        for (i = 0; i < cells[p + 1].length; i++) {
            if (cells[p].indexOf(cells[p + 1][i]) === -1) {
                results.push(cells[p + 1][i]);
            }
        }

        conditions.shift();
        cells.shift();
        cells.splice(0, 1, ivi_utils.copy(results));
        results.length = 0;
    }

    return cells[0];
}

function _filter(searchFilter, items) {
    var pp = [], index = 0, lpIndex, rpIndex, temp, i, results = [];

    searchFilter = searchFilter.trim();
    if (searchFilter === "*") {
        return items;
    }

    lpIndex = searchFilter.indexOf("(", index);
    if (lpIndex > -1) {
        pp.push(lpIndex);
        index = lpIndex;

        while (++index < searchFilter.length) {
            lpIndex = searchFilter.indexOf("(", index);
            rpIndex = searchFilter.indexOf(")", index);
            if ((lpIndex < rpIndex) && (lpIndex > -1)) {
                pp.push(lpIndex);
                index = lpIndex + 1;
            } else if ((lpIndex < rpIndex) && (lpIndex === -1)) {
                lpIndex = pp.pop();
                index = rpIndex + 1;
                temp = searchFilter.substring(lpIndex + 1, rpIndex);
                results = results.concat(_goFiltering(temp, items));
                break;
            } else if (lpIndex > rpIndex) {
                lpIndex = pp.pop();
                index = rpIndex + 1;
                temp = searchFilter.substring(lpIndex + 1, rpIndex);
                results = results.concat(_goFiltering(temp, items));
            } else {
                break;
            }
        }
    } else {
        temp = searchFilter;
        results = _goFiltering(temp, items);
    }

    if (results === null) return null;
    if (results.length === 0) return [];

    for (i = 0; i < items.length; i++) {
        if (results.indexOf(items[i].Path) === -1) {
            items.splice(i, 1);
            i--;
        }
    }

    return items;
}

_self = function () {
    var mediaserver;

    function scanNetwork(successCallback, errorCallback) {
        t.MediaServerManager("scanNetwork", arguments);

        window.setTimeout(function () {
            if (!_data.mediaServer.server) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.UNKNOWN));
                }
                return;
            }

            successCallback(new MediaServer(_data.mediaServer.server));
        }, 1);
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    mediaserver = {
        scanNetwork: scanNetwork,
        handleSubFeatures: handleSubFeatures
    };

    return mediaserver;
};

MediaServer = function (obj) {
    var mediaServer = {};

    mediaServer.id = obj.id || "";
    mediaServer.friendlyName = obj.friendlyName || "";
    mediaServer.manufacturer = obj.manufacturer || "";
    mediaServer.manufacturerURL = obj.manufacturerURL || "";
    mediaServer.modelDescription = obj.modelDescription || "";
    mediaServer.modelName = obj.modelName || "";
    mediaServer.modelNumber = obj.modelNumber || "";
    mediaServer.serialNumber = obj.serialNumber || "";
    mediaServer.UDN = obj.UDN || "";
    mediaServer.presentationURL = obj.presentationURL || "";
    mediaServer.iconURL = obj.iconURL || "";
    mediaServer.deviceType = obj.deviceType || "";
    mediaServer.root = obj.root || null;
    mediaServer.canCreateContainer = obj.canCreateContainer || false;
    mediaServer.canUpload = obj.canUpload || false;
    mediaServer.searchAttrs = obj.searchAttrs || [];
    mediaServer.sortAttrs = obj.sortAttrs || [];

    this.__defineGetter__("id", function () {
        return mediaServer.id;
    });

    this.__defineGetter__("friendlyName", function () {
        return mediaServer.friendlyName;
    });

    this.__defineGetter__("manufacturer", function () {
        return mediaServer.manufacturer;
    });

    this.__defineGetter__("manufacturerURL", function () {
        return mediaServer.manufacturerURL;
    });

    this.__defineGetter__("modelDescription", function () {
        return mediaServer.modelDescription;
    });

    this.__defineGetter__("modelName", function () {
        return mediaServer.modelName;
    });

    this.__defineGetter__("modelNumber", function () {
        return mediaServer.modelNumber;
    });

    this.__defineGetter__("serialNumber", function () {
        return mediaServer.serialNumber;
    });

    this.__defineGetter__("UDN", function () {
        return mediaServer.UDN;
    });

    this.__defineGetter__("presentationURL", function () {
        return mediaServer.presentationURL;
    });

    this.__defineGetter__("iconURL", function () {
        return mediaServer.iconURL;
    });

    this.__defineGetter__("deviceType", function () {
        return mediaServer.deviceType;
    });

    this.__defineGetter__("root", function () {
        return mediaServer.root;
    });

    this.__defineGetter__("canCreateContainer", function () {
        return mediaServer.canCreateContainer;
    });

    this.__defineGetter__("canUpload", function () {
        return mediaServer.canUpload;
    });

    this.__defineGetter__("searchAttrs", function () {
        return mediaServer.searchAttrs;
    });

    this.__defineGetter__("sortAttrs", function () {
        return mediaServer.sortAttrs;
    });

    this.upload = function (path) {
        if (!this.canUpload) {
            throw new WebAPIException(errorcode.PERMISSION_DENIED);
        }

        t.MediaServer("upload", arguments);

        // upload
    };

    this.createFolder = function (title) {
        if (!this.canCreateContainer) {
            throw new WebAPIException(errorcode.PERMISSION_DENIED);
        }

        t.MediaServer("createFolder", arguments);

        // createFolder
    };

    this.cancel = function () {
        // cancel
    };

    this.browse = function (containerId, sortMode, count, offset,
            successCallback, errorCallback) {
        t.MediaServer("browse", arguments);

        window.setTimeout(function () {
            var i, j, results, container = "", mediaFiles = [],
                paths = _data.mediaServer.containers,
                medias = _data.mediaServer.items,
                sort = _formatSortMode(sortMode);

            if (!containerId) {
                if (errorCallback)
                    errorCallback(new WebAPIError(errorcode.UNKNOWN));
                return;
            }

            for (i = 0; i < paths.length; i++) {
                if (paths[i].id === containerId) {
                    container = paths[i].Path;
                    continue;
                }

                if ((paths[i].Path.indexOf(containerId) === 0) &&
                        (paths[i].Path !== containerId)) {
                    mediaFiles.push(new MediaFactory(paths[i].Type,
                        paths[i]));
                }
            }

            if (!container) {
                if (errorCallback)
                    errorCallback(new WebAPIError(errorcode.UNKNOWN));
                return;
            }

            for (i = 0; i < paths.length; i++) {
                if ((paths[i].Path.indexOf(container) === 0) &&
                        (paths[i].Path !== container)) {
                    mediaFiles.push(new MediaFactory(paths[i].Type,
                        paths[i]));
                }
            }

            for (j = 0; j < medias.length; j++) {
                if (medias[j].Path.indexOf(container) === 0) {
                    mediaFiles.push(new MediaFactory(medias[j].Type,
                            medias[j]));
                }
            }

            results = ivi_utils.query(mediaFiles, false, sort, count, offset);
            successCallback(results);
        }, 1);
    };

    this.find = function (containerId, searchFilter, sortMode, count,
            offset, successCallback, errorCallback) {
        t.MediaServer("find", arguments);

        window.setTimeout(function () {
            var i, j, results, container = "", mediaFiles = [],
                paths = _data.mediaServer.containers,
                medias = _data.mediaServer.items,
                sort = _formatSortMode(sortMode);

            if (!containerId) {
                if (errorCallback)
                    errorCallback(new WebAPIError(errorcode.UNKNOWN));
                return;
            }

            for (i = 0; i < paths.length; i++) {
                if (paths[i].id === containerId) {
                    container = paths[i].Path;
                    continue;
                }

                if ((paths[i].Path.indexOf(containerId) === 0) &&
                        (paths[i].Path !== containerId)) {
                    mediaFiles.push(new MediaFactory(paths[i].Type,
                            paths[i]));
                }
            }

            if (!container) {
                if (errorCallback)
                    errorCallback(new WebAPIError(errorcode.UNKNOWN));
                return;
            }

            for (i = 0; i < paths.length; i++) {
                if ((paths[i].Path.indexOf(container) === 0) &&
                        (paths[i].Path !== container)) {
                    mediaFiles.push(new MediaFactory(paths[i].Type,
                            paths[i]));
                }
            }

            for (j = 0; j < medias.length; j++) {
                if (medias[j].Path.indexOf(container) === 0) {
                    mediaFiles.push(new MediaFactory(medias[j].Type,
                            medias[j]));
                }
            }

            mediaFiles = _filter(searchFilter, mediaFiles);
            if (mediaFiles === null) {
                if (errorCallback)
                    errorCallback(new WebAPIError(errorcode.UNKNOWN));
                return;
            }

            results = ivi_utils.query(_filter(searchFilter, mediaFiles), false,
                    sort, count, offset);
            successCallback(results);
        }, 1);
    };
};

MediaFactory = function (type, property) {
    var MediaType;

    switch (type) {
        case "image":
            MediaType = MediaImage;
            break;
        case "video":
            MediaType = MediaVideo;
            break;
        case "music":
        case "audio":
            MediaType = MediaAudio;
            break;
        case "container":
            MediaType = MediaObject;
            break;
    }

    return new MediaType(property);
};

MediaObject = function (property) {
    var mediaObject = {};

    mediaObject.id = property.id || "";
    mediaObject.Path = property.Path || "";
    mediaObject.DisplayName = property.DisplayName || "";
    mediaObject.Type = property.Type || "";

    this.__defineGetter__("Path", function () {
        return mediaObject.Path;
    });

    this.__defineGetter__("DisplayName", function () {
        return mediaObject.DisplayName;
    });

    this.__defineGetter__("Type", function () {
        return mediaObject.Type;
    });

    this.__defineGetter__("id", function () {
        return mediaObject.id;
    });
};

MediaContainer = function (property) {
    var mediaContainer = {};

    MediaObject.call(this, property);

    mediaContainer.childCount = property.childCount || 0;
    mediaContainer.canCreateContainer = property.canCreateContainer || false;
    mediaContainer.canDelete = property.canDelete || false;
    mediaContainer.canUpload = property.canUpload || false;
    mediaContainer.canRename = property.canRename || false;

    this.__defineGetter__("childCount", function () {
        return mediaContainer.childCount;
    });

    this.__defineGetter__("canCreateContainer", function () {
        return mediaContainer.canCreateContainer;
    });

    this.__defineGetter__("canDelete", function () {
        return mediaContainer.canDelete;
    });

    this.__defineGetter__("canUpload", function () {
        return mediaContainer.canUpload;
    });

    this.__defineGetter__("canRename", function () {
        return mediaContainer.canRename;
    });

    this.upload = function (title, path) {
        if (!this.canUpload) {
            throw new WebAPIException(errorcode.PERMISSION_DENIED);
        }

        t.MediaContainer("upload", arguments);

        // upload
    };

    this.createFolder = function (title) {
        if (!this.canCreateContainer) {
            throw new WebAPIException(errorcode.PERMISSION_DENIED);
        }

        t.MediaContainer("createFolder", arguments);

        // createFolder
    };
};

MediaItem = function (property) {
    var mediaItem = {};

    MediaObject.call(this, property);

    mediaItem.MIMEType = property.MIMEType || "";
    mediaItem.URLs = property.URLs || [];
    mediaItem.Size = property.Size || 0;

    this.__defineGetter__("MIMEType", function () {
        return mediaItem.MIMEType;
    });

    this.__defineGetter__("URLs", function () {
        return mediaItem.URLs;
    });

    this.__defineGetter__("Size", function () {
        return mediaItem.Size;
    });
};

MediaVideo = function (property) {
    var mediaVideo = {};

    MediaItem.call(this, property);

    mediaVideo.Album = property.Album || "";
    mediaVideo.Artist = property.Artist || [];
    mediaVideo.Duration = property.Duration || 0;
    mediaVideo.Width = property.Width || 0;
    mediaVideo.Height = property.Height || 0;

    this.__defineGetter__("Album", function () {
        return mediaVideo.Album;
    });

    this.__defineGetter__("Artist", function () {
        return mediaVideo.Artist;
    });

    this.__defineGetter__("Duration", function () {
        return mediaVideo.Duration;
    });

    this.__defineGetter__("Width", function () {
        return mediaVideo.Width;
    });

    this.__defineGetter__("Height", function () {
        return mediaVideo.Height;
    });
};

MediaAudio = function (property) {
    var mediaAudio = {};

    MediaItem.call(this, property);

    mediaAudio.Album = property.Album || "";
    mediaAudio.Artist = property.Artist || [];
    mediaAudio.Genre = property.Genre || [];
    mediaAudio.SampleRate = property.SampleRate || 0;
    mediaAudio.Duration = property.Duration || 0;

    this.__defineGetter__("Album", function () {
        return mediaAudio.Album;
    });

    this.__defineGetter__("Artist", function () {
        return mediaAudio.Artist;
    });

    this.__defineGetter__("Genre", function () {
        return mediaAudio.Genre;
    });

    this.__defineGetter__("SampleRate", function () {
        return mediaAudio.SampleRate;
    });

    this.__defineGetter__("Duration", function () {
        return mediaAudio.Duration;
    });
};

MediaImage = function (property) {
    var mediaImage = {};

    MediaItem.call(this, property);

    mediaImage.Width = property.Width || 0;
    mediaImage.Height = property.Height || 0;

    this.__defineGetter__("Width", function () {
        return mediaImage.Width;
    });

    this.__defineGetter__("Height", function () {
        return mediaImage.Height;
    });
};

_initialize();

module.exports = _self;

});
define('ripple/platform/ivi/3.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    constants = require('ripple/constants');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (configValidationObject) {
        var valid = true;
        // no xmlns:JIL in wac 2.0 spec
        valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;

        return valid;
    },
    extractInfo: function (configValidationObject) {
        if (!configValidationObject) {
            return null;
        }

        var widgetInfo = {},
            configFeatures,
            configPreferences,
            preferenceName,
            platform, rst, i, j,
            settingRst = {
                'screen-orientation': 'portrait',
                'context-menu': 'enable',
                'background-support': 'disable',
                encryption: 'disable',
                'install-location': 'auto',
                'hwkey-event': 'enable'
            };

        widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
        widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
        widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
        if (configValidationObject.widget.children.application.validationResult[0].valid) {
            widgetInfo.tizenAppId = configValidationObject.widget.children.application.validationResult[0].attributes.id.value;
            widgetInfo.tizenPackageId = configValidationObject.widget.children.application.validationResult[0].attributes.package.value;
        }

        widgetInfo.features = {};

        if (configValidationObject.widget.children.setting.hasOwnProperty('validationResult') === true) {
            rst = configValidationObject.widget.children.setting.validationResult;
            // the first one has higher priority per platform implementation
            for (i = rst.length -1 ; i >= 0; i--) {
                if (rst[i].valid === true) {
                    for (j in rst[i].attributes) {
                        if (rst[i].attributes[j].value !== undefined) {
                            settingRst[j] = rst[i].attributes[j].value;
                        }
                    }
                }
            }
            db.save("layout", settingRst["screen-orientation"]);
        }

        configFeatures = configValidationObject.widget.children.feature.validationResult;
        utils.forEach(configFeatures, function (f) {
            if (f.valid === true) {
                var feature = {id: f.attributes.name.value,
                         required: f.attributes.required.valid};
                widgetInfo.features[feature.id] = feature;
            }
        });

        widgetInfo.preferences = {};

        configPreferences = configValidationObject.widget.children.preference.validationResult;

        platform = require('ripple/platform');
        utils.forEach(configPreferences, function (preference) {
            preferenceName = preference.attributes.name.value;
            if (preferenceName) {
                widgetInfo.preferences[preferenceName] = {
                    "key": preferenceName,
                    "value": preference.attributes.value.value || "",
                    "readonly": preference.attributes.readonly.value === "true"
                };

                db.save(preferenceName,
                        widgetInfo.preferences[preferenceName].value,
                        platform.getPersistencePrefix(widgetInfo.id));
            }
        });

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in the configuration document and may have the following child elments: name,description,icon,author,license,content,feature and preference.The \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xmlns:tizen": {
                    attributeName: "xmlns:tizen",
                    required: false,
                    type: "list",
                    listValues: ["http://tizen.org/ns/widgets"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                },
                dir: {
                    attributeName: "dir",
                    required: false,
                    type: "list",
                    listValues: ["ltr", "rtl", "lro", "rlo"]
                },
                id: {
                    attributeName: "id",
                    required: false,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    required: false,
                    type: "string"
                },
                height: {
                    attributeName: "height",
                    required: false,
                    type: "integer"
                },
                width: {
                    attributeName: "width",
                    required: false,
                    type: "integer"
                },
                viewmodes: {
                    attributeName: "viewmodes",
                    required: false,
                    type: "list",
                    listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
                },
                defaultlocale: {
                    attributeName: "defaultlocale",
                    required: false,
                    type: "iso-language"
                }
            },
            children: {
                name: {
                    nodeName: "name",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        "short": {
                            attributeName: "short",
                            required: false,
                            type: "string"
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.URL
                        },
                        email: {
                            attributeName: "email",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.EMAIL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        width: {
                            attributeName: "width",
                            required: false,
                            type: "integer"
                        },
                        height: {
                            attributeName: "height",
                            required: false,
                            type: "integer"
                        }
                    }
                },
                content: {
                    nodeName: "content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        encoding: {
                            attributeName: "encoding",
                            required: false,
                            type: "string"
                        },
                        type: {
                            attributeName: "type",
                            required: false,
                            type: "string"
                        }
                    }
                },
                setting: {
                    nodeName: "tizen:setting",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        'screen-orientation': {
                            attributeName: "screen-orientation",
                            required: false,
                            type: "list",
                            listValues: ['portrait', 'landscape', 'auto']
                        },
                        'context-menu': {
                            attributeName: "context-menu",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'background-support': {
                            attributeName: "background-support",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'encryption': {
                            attributeName: "encryption",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'install-location': {
                            attributeName: "install-location",
                            required: false,
                            type: "list",
                            listValues: ['auto', 'internal-only', 'perfer-external']
                        },
                        'hwkey-event': {
                            attributeName: "hwkey-event",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        }
                    }
                },
                application: {
                    nodeName: "tizen:application",
                    required: true,
                    occurrence: 1,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            type: "string"
                        },
                        required_version: {
                            attributeName: "required_version",
                            required: true,
                            type: "list",
                            listValues: ['1.0', '2.0', '2.1', '2.2']
                        },
                        package: {
                            attributeName: "package",
                            required: false,
                            type: "string"
                        }
                    }
                },
                "tizen:content": {
                    nodeName: "tizen:content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        }
                    }
                },
                control: {
                    nodeName: "tizen:app-control",
                    required: false,
                    occurrence: 0,
                    children: {
                        src: {
                            nodeName: "tizen:src",
                            required: true,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        operation: {
                            nodeName: "tizen:operation",
                            required: true,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        uri: {
                            nodeName: "tizen:uri",
                            required: false,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        mime: {
                            nodeName: "tizen:mime",
                            required: false,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                "app-widget": {
                    nodeName: "tizen:app-widget",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            type: "string"
                        },
                        primary: {
                            attributeName: "primary",
                            required: true,
                            type: "list",
                            listValues: ['true', 'false']
                        },
                        "auto-launch": {
                            attributeName: "auto-launch",
                            required: false,
                            type: "list",
                            listValues: ['true', 'false']
                        },
                        "update-period": {
                            attributeName: "update-period",
                            required: false,
                            type: "integer"
                        }
                    },
                    children: {
                        "box-label": {
                            nodeName: "tizen:box-label",
                            required: true,
                            occurence: 1
                        },
                        "box-icon": {
                            nodeName: "tizen:box-icon",
                            required: true,
                            occurence: 1,
                            attributes: {
                                src: {
                                    attributeName: "src",
                                    required: true,
                                    type: "string"
                                }
                            }
                        },
                        "box-content": {
                            nodeName: "tizen:box-content",
                            required: true,
                            occurence: 1,
                            attributes: {
                                src: {
                                    attributeName: "src",
                                    required: true,
                                    type: "string"
                                },
                                "mouse-event": {
                                    attributeName: "mouse-event",
                                    required: false,
                                    type: "string"
                                },
                                "touch-event": {
                                    attributeName: "touch-event",
                                    required: false,
                                    type: "string"
                                }
                            },
                            children: {
                                "box-size": {
                                    nodeName: "tizen:box-size",
                                    required: false,
                                    occurence: 1,
                                    attributes: {
                                        "preview": {
                                            attributeName: "preview",
                                            required: false,
                                            type: "string"
                                        }
                                    }
                                },
                                pd: {
                                    nodeName: "tizen:pd",
                                    required: false,
                                    occurence: 1,
                                    attributes: {
                                        "src": {
                                            attributeName: "src",
                                            required: true,
                                            type: "string"
                                        },
                                        "width": {
                                            attributeName: "width",
                                            required: true,
                                            type: "integer"
                                        },
                                        "height": {
                                            attributeName: "height",
                                            required: true,
                                            type: "integer"
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                account: {
                    nodeName: "tizen:account",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "multiple-account-support": {
                            attributeName: "multiple-account-support",
                            required: true,
                            type: "list",
                            listValues: ['true', 'false']
                        }
                    },
                    children: {
                        icon: {
                            nodeName: "tizen:icon",
                            required: false,
                            occurence: 1,
                            attributes: {
                                section: {
                                    attributeName: "section",
                                    required: true,
                                    type: "string"
                                }
                            }
                        },
                        "display-name": {
                            nodeName: "tizen:display-name",
                            required: false,
                            occurence: 1,
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        capability: {
                            nodeName: "capability",
                            required: false,
                            occurence: 1
                        }
                    }
                },
                feature: {
                    nodeName: "tizen:privilege",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "list",
                            listValues: ["http://www.w3.org/TR/battery-status/",
                                         "http://www.w3.org/TR/geolocation-API/",
                                         "http://www.w3.org/TR/touch-events/",
                                         "http://www.w3.org/TR/vibration/",
                                         "http://tizen.org/privilege/tizen",
                                         "http://tizen.org/privilege/alarm",
                                         "http://tizen.org/privilege/application.launch",
                                         "http://tizen.org/privilege/appmanager.kill", "http://tizen.org/privilege/appmanager.certificate",
                                         "http://tizen.org/privilege/bluetoothmanager", "http://tizen.org/privilege/bluetooth.admin",
                                         "http://tizen.org/privilege/bluetooth.gap", "http://tizen.org/privilege/bluetooth.spp",
                                         "http://tizen.org/privilege/bookmark.read", "http://tizen.org/privilege/bookmark.write",
                                         "http://tizen.org/privilege/calendar.read", "http://tizen.org/privilege/calendar.write",
                                         "http://tizen.org/privilege/callhistory.read", "http://tizen.org/privilege/callhistory.write",
                                         "http://tizen.org/privilege/contact.read", "http://tizen.org/privilege/contact.write",
                                         "http://tizen.org/privilege/content.read", "http://tizen.org/privilege/content.write",
                                         "http://tizen.org/privilege/datacontrol.consumer",
                                         "http://tizen.org/privilege/datasync",
                                         "http://tizen.org/privilege/download",
                                         "http://tizen.org/privilege/filesystem.read", "http://tizen.org/privilege/filesystem.write",
                                         "http://tizen.org/privilege/mediaserver",
                                         "http://tizen.org/privilege/messaging.read", "http://tizen.org/privilege/messaging.write",
                                         "http://tizen.org/privilege/networkbearerselection",
                                         "http://tizen.org/privilege/nfc.common", "http://tizen.org/privilege/nfc.admin",
                                         "http://tizen.org/privilege/nfc.tag", "http://tizen.org/privilege/nfc.p2p",
                                         "http://tizen.org/privilege/notification",
                                         "http://tizen.org/privilege/packagemanager.install", "http://tizen.org/privilege/package.info",
                                         "http://tizen.org/privilege/power",
                                         "http://tizen.org/privilege/push",
                                         "http://tizen.org/privilege/secureelement",
                                         "http://tizen.org/privilege/setting",
                                         "http://tizen.org/privilege/speech",
                                         "http://tizen.org/privilege/system", "http://tizen.org/privilege/systemmanager",
                                         "http://tizen.org/privilege/time",
                                         "http://tizen.org/privilege/vehicle",
                                         "http://tizen.org/privilege/websetting"]
                        },
                        required: {
                            attributeName: "required",
                            type: "boolean",
                            required: false
                        }
                    },
                    children: {
                        param: {
                            nodeName: "param",
                            required: false,
                            occurrence: 0,
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language"
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                },
                                name: {
                                    attributeName: "name",
                                    required: true,
                                    type: "string"
                                },
                                value: {
                                    attributeName: "value",
                                    required: true,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                preference: {
                    nodeName: "preference",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "string"
                        },
                        value: {
                            type: "string",
                            required: false,
                            attributeName: "value"
                        },
                        readonly: {
                            attributeName: "readonly",
                            type: "boolean",
                            required: false
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/ivi/3.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    StorageTypeTable = {
        "UNKNOWN": "UNKNOWN",
        "INTERNAL": "INTERNAL",
        "MMC": "MMC",
        "USB_HOST": "USB_HOST"
    },
    NetworkTypeTable = {
        "NONE": "NONE",
        "2G": "2G",
        "2.5G": "2.5G",
        "3G": "3G",
        "4G": "4G",
        "WIFI": "WIFI",
        "ETHERNET": "ETHERNET",
        "UNKNOWN": "UNKNOWN"
    },
    LocaleTable = {
        "eng_USA": "eng_USA",
        "eng_CAN": "eng_CAN",
        "deu_DEU": "deu_DEU",
        "jpn_JPN": "jpn_JPN",
        "zho_CHN": "zho_CHN",
        "UNKNOWN": "UNKNOWN"
    },
    SimStateTable = {
        "ABSENT": "ABSENT",
        "INITIALIZING": "INITIALIZING",
        "READY": "READY",
        "PIN_REQUIRED": "PIN_REQUIRED",
        "PUK_REQUIRED":"PUK_REQUIRED",
        "NETWORK_LOCKED": "NETWORK_LOCKED",
        "SIM_LOCKED": "SIM_LOCKED",
        "UNKNOWN": "UNKNOWN"
    };

function deviceStatusEventTrigger(setting) {
    event.trigger("DeviceStatusChanged", [setting]);
}

module.exports = {
    "Config": {
        "vibratingMode": {
            "name": "Vibrator",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("VibratingModeChanged", [setting]);
            }
        },
        "lockScreen": {
            "name": "Lock Screen",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "callback": function (setting) {
                event.trigger("LockScreenChanged", [setting]);
            }
        }
    },
    "DEVICE_ORIENTATION": {
        "status": {
            "name": "Status",
            "control": {
                "type": "label",
                "innertext": "PORTRAIT_PRIMARY",
                "value": "PORTRAIT_PRIMARY"
            },
            "event": "LayoutChanged"
        },
        "isAutoRotation": {
            "name": "Is Auto Rotation",
            "control": {
                "type": "label",
                "value": false
            }
        }
    },
    "CPU": {
        "load": {
            "name": "Load",
            "control": {
                "type": "number",
                "value": 0.1
            },
            "event": "CpuLoadChanged",
            "callback": function (setting) {
                if (setting > 1) setting = 1;
                if (setting < 0) setting = 0;
                event.trigger("CpuLoadChanged", [setting]);
            }
        }
    },
    "STORAGE": {
        "type": {
            "name": "Type",
            "control": {
                "type": "select",
                "value": StorageTypeTable["INTERNAL"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(StorageTypeTable, function (key, value) {
                    optionList[key] = StorageTypeTable[value];
                });

                return optionList;
            }())
        },
        "capacity": {
            "name": "Capacity(bytes)",
            "control": {
                "type": "label",
                "value": 16000000000
            }
        },
        "availableCapacity": {
            "name": "AvailableCapacity(bytes)",
            "control": {
                "type": "number",
                "value": 12000000000
            },
            "callback": function (setting) {
                event.trigger("AvailCapacityChanged", [setting]);
            }
        },
        "isRemovable": {
            "name": "IsRemovable",
            "control": {
                "type": "checkbox",
                "value": true
            }
        }
    },
    "BUILD": {
        "model": {
            "name": "Model",
            "control": {
                "type": "label",
                "innertext": "tizen-2.2 build",
                "value": "tizen-2.2 build"
            }
        },
        "manufacturer": {
            "name": "Manufacturer",
            "control": {
                "type": "label",
                "innertext": "Tizen",
                "value": "Tizen"
            }
        },
        "buildVersion": {
            "name": "Build Version",
            "control": {
                "type": "label",
                "innertext": "TIZEN_WEB_SIMULATOR_000001",
                "value": "TIZEN_WEB_SIMULATOR_000001"
            }
        }
    },
    "LOCALE": {
        "language": {
            "name": "Language",
            "control": {
                "type": "select",
                "value": LocaleTable["eng_USA"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(LocaleTable, function (key, value) {
                    optionList[key] = LocaleTable[value];
                });

                return optionList;
            }())
        },
        "country": {
            "name": "Country",
            "control": {
                "type": "select",
                "value": LocaleTable["eng_USA"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(LocaleTable, function (key, value) {
                    optionList[key] = LocaleTable[value];
                });

                return optionList;
            }())
        }
    },
    "DISPLAY": {
        "resolutionWidth": {
            "name": "Resolution Width(pixels)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "resolutionHeight": {
            "name": "Resolution Height(pixels)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "dotsPerInchWidth": {
            "name": "DPI-X",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "dotsPerInchHeight": {
            "name": "DPI-Y",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "physicalWidth": {
            "name": "Physical Width(millimeters)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "physicalHeight": {
            "name": "Physical Height(millimeters)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "brightness": {
            "name": "Brightness",
            "control": {
                "type": "number",
                "value": 1
            },
            "event": "DisplayBrightnessChanged",
            "callback": function (setting) {
                if (setting > 1) setting = 1;
                if (setting < 0) setting = 0;
                event.trigger("DisplayBrightnessChanged", [setting]);
            }
        }
    },
    "NETWORK": {
        "networkType": {
            "name": "Network Type",
            "control" : {
                "type": "select",
                "value": NetworkTypeTable["NONE"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(NetworkTypeTable, function (key, value) {
                    optionList[key] = NetworkTypeTable[value];
                });

                return optionList;
            }())
        }
    },
    "WIFI_NETWORK": {
        "status": {
            "name": "Status",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "event": "WiFiNetworkStatusChanged",
            "callback": function (setting) {
                event.trigger("WiFiNetworkStatusChanged", [setting]);
            }
        },
        "ssid": {
            "name": "SSID",
            "control": {
                "type": "text",
                "value": "Tizen WiFi"
            }
        },
        "ipAddress": {
            "name": "IP Address",
            "control": {
                "type": "text",
                "value": "192.168.0.1"
            }
        },
        "ipv6Address": {
            "name": "IPv6 Address",
            "control": {
                "type": "text",
                "value": "2001:db8:85a3:0:0:0:70:7334"
            }
        },
        "signalStrength": {
            "name": "Signal Strength",
            "control": {
                "type": "select",
                "value": 0
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 10; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }())
        }
    },
    "CELLULAR_NETWORK": {
        "status": {
            "name": "Status",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "event": "CellularNetworkStatusChanged",
            "callback": function (setting) {
                event.trigger("CellularNetworkStatusChanged", [setting]);
            }
        },
        "apn": {
            "name": "APN",
            "control": {
                "type": "text",
                "value": "Tizen"
            }
        },
        "ipAddress": {
            "name": "IP Address",
            "control": {
                "type": "text",
                "value": "10.0.2.16"
            }
        },
        "ipv6Address": {
            "name": "IPv6 Address",
            "control": {
                "type": "text",
                "value": "2001:db8:85a3:0:0:0:70:7334"
            }
        },
        "mcc": {
            "name": "MCC",
            "control": {
                "type": "number",
                "value": 460
            }
        },
        "mnc": {
            "name": "MNC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "cellId": {
            "name": "Cell ID",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "lac": {
            "name": "LAC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "isRoaming": {
            "name": "Roaming",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "isFlightMode": {
            "name": "Flight Mode",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "callback": function (setting) {
                event.trigger("FlightModeChanged", [setting]);
            }
        },
        "imei": {
            "name": "IMEI",
            "control": {
                "type": "text",
                "value": "012417005203000"
            }
        }
    },
    "SIM": {
        "state": {
            "name": "State",
            "control": {
                "type": "select",
                "value": SimStateTable["READY"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(SimStateTable, function (key, value) {
                    optionList[key] = SimStateTable[value];
                });

                return optionList;
            }())
        },
        "operatorName": {
            "name": "Operator Name",
            "control": {
                "type": "text",
                "value": "Tizen"
            }
        },
        "msisdn": {
            "name": "MSISDN",
            "control": {
                "type": "text",
                "value": "088123456789"
            }
        },
        "iccid": {
            "name": "ICCID",
            "control": {
                "type": "text",
                "value": "123000MFSSYYGXXXXXXP"
            }
        },
        "mcc": {
            "name": "MCC",
            "control": {
                "type": "number",
                "value": 460
            }
        },
        "mnc": {
            "name": "MNC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "msin": {
            "name": "MSIN",
            "control": {
                "type": "text",
                "value": "H1 H2 H3 S 12345"
            }
        },
        "spn": {
            "name": "SPN",
            "control": {
                "type": "text",
                "value": "TizenSPN"
            }
        }
    },
    "PERIPHERAL": {
        "isVideoOutputOn": {
            "name": "Video Output",
            "control": {
                "type": "checkbox",
                "value": false
            }
        }
    }
};

});
define('ripple/platform/ivi/3.0/spec/sensor', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event');

function sensorStatusEventTrigger(setting) {
    event.trigger("SensorStatusChanged", [setting]);
}

module.exports = {
    "Accelerometer": {
        "resolution": 0.039239998906850815,
        "minDelay": 20,
        "range": 20.051639556884766,
        "name": "Accelerometer",
        "type": "Accelerometer"
    },
    "MagneticField": {
        "x": {
            "name": "X",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-xChanged", [setting]);
            }
        },

        "y": {
            "name": "Y",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-yChanged", [setting]);
            }
        },

        "z": {
            "name": "Z",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-zChanged", [setting]);
            }
        },

        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "MagneticField",
        "type": "MagneticField"
    },
    "Rotation": {
        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "Rotation",
        "type": "Rotation"
    },
    "Orientation": {
        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "Orientation",
        "type": "Orientation"
    }
};

});
define('ripple/platform/ivi/3.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "vehicle",
        "sensors",
        "communication",
        "geoView",
        "widgetConfig",
        "deviceSettings",
        "application",
        "network",
        "power",
        "download",
        "notifications",
        "package",
        "messagePort",
        "secureElement"
    ]
};

});
define('ripple/platform/ivi/3.0/spec', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = {

    id: "ivi",
    version: "3.0",
    name: "IVI",

    persistencePrefix: "ivi3-",

    config: require('ripple/platform/ivi/3.0/spec/config'),
    ui: require('ripple/platform/ivi/3.0/spec/ui'),
    device: require('ripple/platform/ivi/3.0/spec/device'),
    sensor: require('ripple/platform/ivi/3.0/spec/sensor'),
    DeviceMotionEvent: require('ripple/platform/tizen/2.0/DeviceMotionEvent'),
    DeviceOrientationEvent: require('ripple/platform/tizen/2.0/DeviceOrientationEvent'),

    objects: {
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        SensorConnection: {
            path: "w3c/1.0/SensorConnection"
        },
        SpeechRecognition: {
            path: "ivi/3.0/SpeechRecognition"
        },
        SpeechGrammarList: {
            path: "ivi/3.0/SpeechGrammarList"
        },
        SpeechGrammar: {
            path: "ivi/3.0/SpeechGrammar"
        },
        Zone: {
            path: "ivi/3.0/Zone"
        },
        navigator: {
            path: "tizen/2.0/navigator",
            children: {
                geolocation: {
                    path: "wac/2.0/geolocation"
                },
                battery: {
                    path: "tizen/2.0/battery"
                }
            }
        },
        tizen: {
            feature: "http://tizen.org/privilege/tizen",
            children: {
                AlarmAbsolute: {
                    path: "tizen/2.0/AlarmAbsolute"
                },
                AlarmRelative: {
                    path: "tizen/2.0/AlarmRelative"
                },
                ApplicationControl: {
                    path: "tizen/2.0/ApplicationControl"
                },
                ApplicationControlData: {
                    path: "tizen/2.0/ApplicationControlData"
                },
                AttributeFilter: {
                    path: "tizen/2.0/AttributeFilter"
                },
                AttributeRangeFilter: {
                    path: "tizen/2.0/AttributeRangeFilter"
                },
                BookmarkFolder: {
                    path: "tizen/2.0/BookmarkFolder"
                },
                BookmarkItem: {
                    path: "tizen/2.0/BookmarkItem"
                },
                CalendarAlarm: {
                    path: "tizen/2.0/CalendarAlarm"
                },
                CalendarAttendee: {
                    path: "tizen/2.0/CalendarAttendee"
                },
                CalendarEvent: {
                    path: "tizen/2.0/CalendarEvent"
                },
                CalendarEventId: {
                    path: "tizen/2.0/CalendarEventId"
                },
                CalendarRecurrenceRule: {
                    path: "tizen/2.0/CalendarRecurrenceRule"
                },
                CalendarTask: {
                    path: "tizen/2.0/CalendarTask"
                },
                CompositeFilter: {
                    path: "tizen/2.0/CompositeFilter"
                },
                Contact: {
                    path: "tizen/2.0/ContactBase"
                },
                ContactAddress: {
                    path: "tizen/2.0/ContactAddress"
                },
                ContactAnniversary: {
                    path: "tizen/2.0/ContactAnniversary"
                },
                ContactEmailAddress: {
                    path: "tizen/2.0/ContactEmailAddress"
                },
                ContactGroup: {
                    path: "tizen/2.0/ContactGroup"
                },
                ContactName: {
                    path: "tizen/2.0/ContactName"
                },
                ContactOrganization: {
                    path: "tizen/2.0/ContactOrganization"
                },
                ContactPhoneNumber: {
                    path: "tizen/2.0/ContactPhoneNumber"
                },
                ContactRef: {
                    path: "tizen/2.0/ContactRef"
                },
                ContactWebSite: {
                    path: "tizen/2.0/ContactWebSite"
                },
                DownloadRequest: {
                    path: "tizen/2.0/DownloadRequest"
                },
                Message: {
                    path: "tizen/2.0/Message"
                },
                NDEFMessage: {
                    path: "tizen/2.0/NDEFMessage"
                },
                NDEFRecord: {
                    path: "tizen/2.0/NDEFRecord"
                },
                NDEFRecordMedia: {
                    path: "tizen/2.0/NDEFRecordMedia"
                },
                NDEFRecordText: {
                    path: "tizen/2.0/NDEFRecordText"
                },
                NDEFRecordURI: {
                    path: "tizen/2.0/NDEFRecordURI"
                },
                NotificationDetailInfo: {
                    path: "tizen/2.0/NotificationDetailInfo"
                },
                SimpleCoordinates: {
                    path: "tizen/2.0/SimpleCoordinates"
                },
                SortMode: {
                    path: "tizen/2.0/SortMode"
                },
                StatusNotification: {
                    path: "tizen/2.0/StatusNotification"
                },
                SyncInfo: {
                    path: "tizen/2.0/SyncInfo"
                },
                SyncServiceInfo: {
                    path: "tizen/2.0/SyncServiceInfo"
                },
                SyncProfileInfo: {
                    path: "tizen/2.0/SyncProfileInfo"
                },
                TZDate: {
                    path: "tizen/2.0/TZDate"
                },
                TimeDuration: {
                    path: "tizen/2.0/TimeDuration"
                },
                alarm: {
                    path: "tizen/2.0/alarm",
                    feature: "http://tizen.org/privilege/alarm",
                    handleSubfeatures: true
                },
                application: {
                    path: "tizen/2.0/application",
                    feature: "http://tizen.org/privilege/application.launch|http://tizen.org/privilege/appmanager.kill|http://tizen.org/privilege/appmanager.certificate",
                    handleSubfeatures: true
                },
                bluetooth: {
                    path: "tizen/2.0/bluetooth",
                    feature: "http://tizen.org/privilege/bluetoothmanager|http://tizen.org/privilege/bluetooth.admin|http://tizen.org/privilege/bluetooth.gap|http://tizen.org/privilege/bluetooth.spp",
                    handleSubfeatures: true
                },
                bookmark: {
                    path: "tizen/2.0/bookmark",
                    feature: "http://tizen.org/privilege/bookmark.read|http://tizen.org/privilege/bookmark.write",
                    handleSubfeatures: true
                },
                callhistory: {
                    path: "tizen/2.0/callHistory",
                    feature: "http://tizen.org/privilege/callhistory|http://tizen.org/privilege/callhistory.read|http://tizen.org/privilege/callhistory.write",
                    handleSubfeatures: true
                },
                calendar: {
                    path: "tizen/2.0/calendar",
                    feature: "http://tizen.org/privilege/calendar.read|http://tizen.org/privilege/calendar.write",
                    handleSubfeatures: true
                },
                contact: {
                    path: "tizen/2.0/contact",
                    feature: "http://tizen.org/privilege/contact.read|http://tizen.org/privilege/contact.write",
                    handleSubfeatures: true
                },
                content: {
                    path: "tizen/2.0/content",
                    feature: "http://tizen.org/privilege/content.read|http://tizen.org/privilege/content.write",
                    handleSubfeatures: true
                },
                datacontrol: {
                    path: "tizen/2.0/datacontrol",
                    feature: "http://tizen.org/privilege/datacontrol.consumer",
                    handleSubfeatures: true
                },
                datasync: {
                    path: "tizen/2.0/datasync",
                    feature: "http://tizen.org/privilege/datasync",
                    handleSubfeatures: true
                },
                download: {
                    path: "tizen/2.0/download",
                    feature: "http://tizen.org/privilege/download",
                    handleSubfeatures: true
                },
                filesystem: {
                    path: "tizen/2.0/filesystem",
                    feature: "http://tizen.org/privilege/filesystem.read|http://tizen.org/privilege/filesystem.write"
                },
                messageport: {
                    path: "tizen/2.0/messageport"
                },
                messaging: {
                    path: "tizen/2.0/messaging",
                    feature: "http://tizen.org/privilege/messaging.send|http://tizen.org/privilege/messaging.read|http://tizen.org/privilege/messaging.write",
                    handleSubfeatures: true
                },
                networkbearerselection: {
                    path: "tizen/2.0/networkbearerselection",
                    feature: "http://tizen.org/privilege/networkbearerselection",
                    handleSubfeatures: true
                },
                nfc: {
                    path: "tizen/2.0/nfc",
                    feature: "http://tizen.org/privilege/nfc.common|http://tizen.org/privilege/nfc.admin|http://tizen.org/privilege/nfc.tag|http://tizen.org/privilege/nfc.p2p",
                    handleSubfeatures: true
                },
                notification: {
                    path: "tizen/2.0/notification",
                    feature: "http://tizen.org/privilege/notification",
                    handleSubfeatures: true
                },
                package: {
                    path: "tizen/2.0/package",
                    feature: "http://tizen.org/privilege/packagemanager.install|http://tizen.org/privilege/package.info",
                    handleSubfeatures: true
                },
                power: {
                    path: "tizen/2.0/power",
                    feature: "http://tizen.org/privilege/power",
                    handleSubfeatures: true
                },
                push: {
                    path: "tizen/2.0/push",
                    feature: "http://tizen.org/privilege/push",
                    handleSubfeatures: true
                },
                seService: {
                    path: "tizen/2.0/secureelement",
                    feature: "http://tizen.org/privilege/secureelement",
                    handleSubfeatures: true
                },
                systeminfo: {
                    path: "tizen/2.0/systeminfo",
                    feature: "http://tizen.org/privilege/system|http://tizen.org/privilege/systemmanager",
                    handleSubfeatures: true
                },
                systemsetting: {
                    path: "tizen/2.0/systemsetting",
                    feature: "http://tizen.org/privilege/setting",
                    handleSubfeatures: true
                },
                time: {
                    path: "tizen/2.0/time",
                    feature: "http://tizen.org/privilege/time",
                    handleSubfeatures: true
                },
                websetting: {
                    path: "tizen/2.0/websetting",
                    feature: "http://tizen.org/privilege/websetting",
                    handleSubfeatures: true
                },
                locale: {
                    path: "ivi/3.0/locale",
                    feature: "http://tizen.org/privilege/vehicle",
                    handleSubfeatures: true
                },
                mediaserver: {
                    path: "ivi/3.0/mediaserver",
                    feature: "http://tizen.org/privilege/mediaserver",
                    handleSubfeatures: true
                },
                speech: {
                    path: "ivi/3.0/speech",
                    feature: "http://tizen.org/privilege/speech",
                    handleSubfeatures: true
                },
                vehicle: {
                    path: "ivi/3.0/vehicle",
                    feature: "http://tizen.org/privilege/vehicle",
                    handleSubfeatures: true
                }
            }
        }
    }
};

});
define('ripple/platform/ivi/3.0/speech', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 t = require('ripple/platform/ivi/3.0/typecast'),
    _security = {
        "http://tizen.org/privilege/speech": []
    },
    _self;

function _initialize () {
}

_self = function () {
    var speech;

    function vocalizeString (speakString) {
        t.SpeechManager("vocalizeString", arguments);

        meSpeak.speak(speakString);
    }

    function handleSubFeatures (subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    speech = {
        vocalizeString: vocalizeString,
        handleSubFeatures: handleSubFeatures
    };

    return speech;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/ivi/3.0/typecast', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 typedef = require('ripple/platform/ivi/3.0/typedef'),
    errorcode = require('ripple/platform/ivi/3.0/errorcode'),
    WebAPIException = require('ripple/platform/ivi/3.0/WebAPIException'),
    TypeCoerce = require('ripple/platform/ivi/3.0/typecoerce'),
    _self = {};

function _cast(pattern, obj, isDuplicate) {
    var tc, tcFunc;

    if (pattern === null)
        return;

    tc = new TypeCoerce(pattern);
    tcFunc = isDuplicate ? tc.copy : tc.cast;

    if ((obj = tcFunc(obj)) === null) {
        throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
    }

    return obj;
}

function _castType(pattern) {
    /*
     * Type cast for each known type. The function name is the exact name of the
     * corresponding type.
     *
     * obj
     *    Variable to be casted
     *
     * aux
     *    Auxiliary descriptor of obj. It can be any one or combination of below
     *    strings, or ignored in most cases.
     *
     *    "?"     Nullable types
     *    "[]"    Array
     *    "+"     Deep copy
     *
     * Return
     *    Casted or duplicated object.
     */

    return function (obj, aux) {
        var type, isNullable, isDuplicate;

        aux = aux ? String(aux) : "";
        type = (aux.indexOf("[]") !== -1) ? [pattern] : pattern;
        isNullable = (aux.indexOf("?") !== -1);
        isDuplicate = (aux.indexOf("+") !== -1);

        if (isNullable && ((obj === null) || (obj === undefined))) {
            return obj;
        }

        return _cast(type, obj, isDuplicate);
    };
}

function _castConstructor(name) {
    var constructors, hook, vtc, isOverloaded, castConstructor;

    /*
     * Type cast for constructor. The function name is the exact name of the
     * object type.
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     */

    function castUnique(argv) {
        _cast(constructors, argv, false);
    }

    /*
     * Type cast for overloaded constructors. The function name is the exact
     * name of the object type.
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     *
     * scope
     *    'this' of the original constructor.
     *
     * voc
     *    Array of overloaded constructors callback
     */

    function castOverload(argv, scope, voc) {
        var iOverload;

        if (!vtc) {
            vtc = [];
            constructors.forEach(function (c) {
                vtc.push((c === null) ? null : new TypeCoerce(c));
            });
        }

        vtc.some(function (tc, index) {
            if (tc && (tc.cast(argv) === null))
                return false;

            iOverload = index;
            return true;
        });

        if (iOverload === undefined) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }

        return (voc && voc[iOverload].apply(scope, argv));
    }

    constructors = typedef.constructor[name];

    if (name in _self) {
        hook = _self[name];
    }

    isOverloaded = (Object.prototype.toString.call(constructors) ===
            "[object Array]");
    castConstructor = isOverloaded ? castOverload : castUnique;

    return function (argv, scope) {
        if (Object.prototype.toString.call(argv) !== "[object Arguments]") {
            return (hook && hook.apply(this, arguments));
        }

        if (!(scope instanceof argv.callee)) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR, null, "TypeError");
        }

        castConstructor.apply(this, arguments);
    };
}

function _castInterface(name) {
    var interface, hook;

    interface = typedef.interface[name];

    if (name in _self) {
        hook = _self[name];
    }

    /*
     * Type cast for each known method of interface. The function name is the
     * exact name of the corresponding interface.
     *
     * method
     *    String of method name
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     *
     * isDuplicate
     *    A boolean value to indicate whether arguments will be copied or not.
     */

    return function (method, argv, isDuplicate) {
        if ((typeof method !== "string") || (typeof argv !== "object")) {
            return (hook && hook.apply(this, arguments));
        }

        _cast(interface[method], argv, isDuplicate);
    };
}

(function () {
    var i;

    for (i in typedef) {
        _self[i] = _castType(typedef[i]);
    }

    for (i in typedef.constructor) {
        _self[i] = _castConstructor(i);
        typedef[i]._constructor = i;
    }

    for (i in typedef.interface) {
        _self[i] = _castInterface(i);
    }
}());

module.exports = _self;

});
define('ripple/platform/ivi/3.0/typecoerce', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/ivi/3.0/typedef'),
    _MAX_INT_BITS = 53,
    _MAX_INT = Math.pow(2, _MAX_INT_BITS) - 1,
    _self;

_self = function (pattern) {
    var typeCoerce, typeOfPattern;

    // private
    function getExtendedType(val) {
        var type = Object.prototype.toString.call(val), attr;

        switch (type) {
        case "[object Array]":
            if ((typeof val[0] === "string") && (val[0].length > 0)) {
                type = "enum";
            } else {
                type = "Union";
            }
            return type;

        case "[object Object]":
            if ("_dictionary" in val) {
                return "dictionary";
            }

            type = "Object";

            for (attr in val) {
                if (attr === "0") {
                    type = "Arguments";
                } else if (val[attr] === "Callback") {
                    type = "Callback";
                }
                break;
            }

            return type;
        }

        switch (val) {
        case "Callback":
            type = "Function";
            break;

        case "TZDate":
        case "any":
        case "byte":
        case "float":
        case "long":
        case "long long":
        case "octet":
        case "short":
        case "unsigned long":
        case "unsigned long long":
        case "unsigned short":
            type = val;
            break;

        case "double":
            type = "float";
            break;

        default:    // Derivative type name: e.g., "AbstractFilter"
            type = "";
            break;
        }

        return type;
    }

    function getType(val, isPattern) {
        var type = Object.prototype.toString.call(val);

        switch (type) {
        case "[object Array]":
            type = (isPattern && (val.length > 1)) ? getExtendedType(val) :
                    "Array";
            break;

        case "[object Arguments]":
            type = "Arguments";
            break;

        case "[object Boolean]":
            type = "boolean";
            break;

        case "[object Date]":
            type = "Date";
            break;

        case "[object Function]":
            type = "Function";
            break;

        case "[object Number]":
            type = "Number";
            break;

        case "[object Object]":
            type = isPattern ? getExtendedType(val) : "Object";
            break;

        case "[object String]":
            type = (isPattern && !!val) ? getExtendedType(val) : "DOMString";
            break;
        }

        return type;
    }

    function isConstructed(obj) {
        if (!("_constructor" in pattern))
            return true;

        if (obj instanceof window.tizen[pattern._constructor])
            return true;

        if ("_derived" in pattern)
            return true;

        return false;
    }

    function toInteger(x) {
        return (x < 0) ? Math.ceil(x) : Math.floor(x);
    }

    function isBitsOverflowed(bits) {
        return (bits >= _MAX_INT_BITS);
    }

    function toJsInt(x, isUnsigned) {
        var min, max;

        min = isUnsigned ? 0 : -_MAX_INT;
        max = _MAX_INT;

        if ((x < min) || (x > max))
            return null;

        return toInteger(x);
    }

    function modulo(a, b) {
        return (a - Math.floor(a / b) * b);
    }

    function toInt(x, bits) {
        var p;

        x = Number(x);

        if (isNaN(x) || !isFinite(x))
            return null;

        if (isBitsOverflowed(bits))
            return toJsInt(x, false);

        p = Math.pow(2, bits);
        x = modulo(toInteger(x), p);

        return (x >= Math.pow(2, bits - 1)) ? (x - p) : x;
    }

    function toUInt(x, bits) {
        x = Number(x);

        if (isNaN(x) || !isFinite(x))
            return null;

        if (isBitsOverflowed(bits))
            return toJsInt(x, true);

        return modulo(toInteger(x), Math.pow(2, bits));
    }

    function toInt8(x) {
        return toInt(x, 8);
    }

    function toInt16(x) {
        return toInt(x, 16);
    }

    function toInt32(x) {
        return toInt(x, 32);
    }

    function toInt64(x) {
        return toInt(x, 64);
    }

    function toUInt8(x) {
        return toUInt(x, 8);
    }

    function toUInt16(x) {
        return toUInt(x, 16);
    }

    function toUInt32(x) {
        return toUInt(x, 32);
    }

    function toUInt64(x) {
        return toUInt(x, 64);
    }

    // public
    function cast(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Arguments": function () {
                var i, isNullable, ret;

                for (i in pattern) {
                    if (i === "_optional")
                        continue;

                    isNullable = !!(pattern._optional && pattern._optional[i]);

                    if (i > obj.length - 1) {
                        if (!isNullable) {
                            return null;
                        }
                        break;
                    }

                    if (!isNullable || (obj[i] !== null)) {
                        ret = _self(pattern[i]).cast(obj[i]);
                        if (ret === null) {
                            return null;
                        }
                        obj[i] = ret;
                    }
                }

                return obj;
            },

            "Array": function () {
                var elementType, i, ret;

                if (typeOfObj !== typeOfPattern) {
                    return null;
                }

                elementType = _self(pattern[0]);
                for (i in obj) {
                    ret = elementType.cast(obj[i]);
                    if (ret === null) {
                        return null;
                    }
                    obj[i] = ret;
                }

                return obj;
            },

            "Callback": function () {
                var attr;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        obj[attr] = _self(pattern[attr]).cast(obj[attr]);
                        if (obj[attr] === null) {
                            return null;
                        }
                    }
                }

                return obj;
            },

            "DOMString": function () {
                switch (typeOfObj) {
                case "DOMString":
                case "Date":
                case "Number":
                case "boolean":
                    obj = String(obj);
                    break;

                default:
                    if ((obj === null) || (obj === undefined)) {
                        obj = String(obj);
                    } else {
                        obj = null;
                    }
                    break;
                }

                return obj;
            },

            "Date": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "Function": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "Object": function () {
                var ret, attr, i;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return null;
                    }
                    if (!("_derived" in pattern)) {
                        return null;
                    }
                }

                if (!isConstructed(obj)) {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            ret = _self(pattern._derived[i]).cast(obj);
                            if (ret !== null)
                                break;
                        }
                        if (ret === null) {
                            if ("_constructor" in pattern)
                                break;

                            return null;
                        }
                        break;

                    default:
                        if (!pattern._optional || !pattern._optional[attr] ||
                                (obj[attr] !== undefined) &&
                                (obj[attr] !== null)) {
                            ret = _self(pattern[attr]).cast(obj[attr]);
                            if (ret === null) {
                                return null;
                            }
                            obj[attr] = ret;
                        }
                        break;
                    }
                }

                return obj;
            },

            "TZDate": function () {
                if (typeOfObj !== "Object") {
                    return null;
                }
                return (obj instanceof window.tizen.TZDate) ? obj : null;
            },

            "Union": function () {
                var ret, i;

                for (i in pattern) {
                    ret = _self(pattern[i]).cast(obj);
                    if (ret !== null)
                        break;
                }

                return ret;
            },

            "any": function () {
                return obj;
            },

            "boolean": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "byte": function () {
                return toInt8(obj);
            },

            "dictionary": function () {
                var attr, ret;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            ret = _self(pattern._dictionary).cast(obj);
                            if (ret === null) {
                                return null;
                            }
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            ret = _self(pattern[attr]).cast(obj[attr]);
                            if (ret === null) {
                                return null;
                            }
                            obj[attr] = ret;
                        }
                        break;
                    }
                }

                return obj;
            },

            "enum": function () {
                var i;

                obj = String(obj).trim();
                for (i in pattern) {
                    if (obj === pattern[i]) {
                        return obj;
                    }
                }

                return null;
            },

            "float": function () {
                var f = parseFloat(obj, 10);

                return (isNaN(f) ? null : f);
            },

            "long": function () {
                return toInt32(obj);
            },

            "long long": function () {
                return toInt64(obj);
            },

            "octet": function () {
                return toUInt8(obj);
            },

            "short": function () {
                return toInt16(obj);
            },

            "unsigned long": function () {
                return toUInt32(obj);
            },

            "unsigned long long": function () {
                return toUInt64(obj);
            },

            "unsigned short": function () {
                return toUInt16(obj);
            },

            "": function () {
                return _self(t[pattern]).cast(obj);
            }
        };

        return typeMap[typeOfPattern]();
    }

    function copy(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Arguments": function () {
                var i, isNullable, ret = [];

                for (i in pattern) {
                    if (i === "_optional")
                        continue;

                    isNullable = !!(pattern._optional && pattern._optional[i]);

                    if (i > obj.length - 1) {
                        if (!isNullable) {
                            return null;
                        }
                        break;
                    }

                    if (!isNullable || (obj[i] !== null)) {
                        ret[i] = _self(pattern[i]).copy(obj[i]);
                        if (ret[i] === null) {
                            return null;
                        }
                    }
                }

                for (i in ret) {
                    obj[i] = ret[i];
                }

                return obj;
            },

            "Array": function () {
                var arr = [], elementType, i;

                if (typeOfObj !== typeOfPattern) {
                    return null;
                }

                elementType = _self(pattern[0]);
                for (i in obj) {
                    if (obj[i] !== undefined) {
                        arr[i] = elementType.copy(obj[i]);
                        if (arr[i] === null)
                            return null;
                    }
                }

                return arr;
            },

            "Callback": function () {
                var ret = {}, attr;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                        if (ret[attr] === null) {
                            return null;
                        }
                    }
                }

                return ret;
            },

            "Object": function () {
                var ret = {}, attr, i, derived;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return null;
                    }
                    if (!("_derived" in pattern)) {
                        return null;
                    }
                }

                if (!isConstructed(obj)) {
                    return null;
                }
                if ("_constructor" in pattern) {
                    ret.__proto__ = window.tizen[pattern._constructor].prototype;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            derived = _self(pattern._derived[i]).copy(obj);
                            if (derived !== null)
                                break;
                        }
                        if (derived === null) {
                            if ("_constructor" in pattern)
                                break;

                            return null;
                        }
                        for (attr in derived) {
                            ret[attr] = derived[attr];
                        }
                        break;

                    default:
                        if (!pattern._optional || !pattern._optional[attr] ||
                                (obj[attr] !== undefined) &&
                                (obj[attr] !== null)) {
                            ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                            if (ret[attr] === null) {
                                return null;
                            }
                        }
                        break;
                    }
                }

                return ret;
            },

            "Union": function () {
                var ret, i;

                for (i in pattern) {
                    ret = _self(pattern[i]).copy(obj);
                    if (ret !== null)
                        break;
                }

                return ret;
            },

            "dictionary": function () {
                var ret = {}, attr, base, i;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            base = _self(pattern._dictionary).copy(obj);
                            if (base === null) {
                                return null;
                            }
                            for (i in base) {
                                ret[i] = base[i];
                            }
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                            if (ret[attr] === null) {
                                return null;
                            }
                        }
                        break;
                    }
                }

                return ret;
            },

            "": function () {
                return _self(t[pattern]).copy(obj);
            }
        };

        return (typeOfPattern in typeMap) ? typeMap[typeOfPattern]() :
                cast(obj);
    }

    function match(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Array": function () {
                var elementType, i;

                if (typeOfObj !== typeOfPattern)
                    return false;

                elementType = _self(pattern[0]);
                for (i in obj) {
                    if (!elementType.match(obj[i])) {
                        return false;
                    }
                }

                return true;
            },

            "Callback": function () {
                var attr, isMatched = true;

                if (typeOfObj !== "Object") {
                    return false;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        isMatched = _self(pattern[attr]).match(obj[attr]);
                        if (!isMatched) {
                            break;
                        }
                    }
                }

                return isMatched;
            },

            "DOMString": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Date": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Function": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Object": function () {
                var attr, isMatched = false, i;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return false;
                    }
                    if (!("_derived" in pattern)) {
                        return false;
                    }
                    return false;
                }

                if (!isConstructed(obj)) {
                    return false;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            isMatched = _self(pattern._derived[i]).match(obj);
                            if (isMatched)
                                break;
                        }
                        break;

                    default:
                        if (pattern._optional && pattern._optional[attr]) {
                            isMatched = ((obj[attr] === null) ||
                                    (obj[attr] === undefined) ||
                                    _self(pattern[attr]).match(obj[attr]));
                        } else {
                            isMatched = (obj[attr] !== undefined) &&
                                    _self(pattern[attr]).match(obj[attr]);
                        }
                        break;
                    }

                    if (!isMatched)
                        break;
                }

                /*// Check if verbose attributes are present
                if (isMatched) {
                    for (attr in obj) {
                        if (pattern[attr] === undefined) {
                            isMatched = false;
                            break;
                        }
                    }
                }*/

                return isMatched;
            },

            "Union": function () {
                var isMatched, i;

                for (i in pattern) {
                    isMatched = _self(pattern[i]).match(obj);
                    if (isMatched)
                        break;
                }

                return isMatched;
            },

            "any": function () {
                return true;
            },

            "boolean": function () {
                return (typeOfObj === typeOfPattern);
            },

            "byte": function () {
                return (obj === toInt8(obj));
            },

            "dictionary": function () {
                var attr, isMatched = true;

                if (typeOfObj !== "Object") {
                    return false;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            isMatched = _self(pattern._dictionary).match(obj);
                            if (!isMatched)
                                break;
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            isMatched = _self(pattern[attr]).match(obj[attr]);
                            if (!isMatched)
                                break;
                        }
                        break;
                    }
                }

                return isMatched;
            },

            "enum": function () {
                for (var i in pattern) {
                    if (obj === pattern[i]) {
                        return true;
                    }
                }

                return false;
            },

            "float": function () {
                return (typeOfObj === "Number");
            },

            "long": function () {
                return (obj === toInt32(obj));
            },

            "long long": function () {
                return (obj === toInt64(obj));
            },

            "octet": function () {
                return (obj === toUInt8(obj));
            },

            "short": function () {
                return (obj === toInt16(obj));
            },

            "unsigned long": function () {
                return (obj === toUInt32(obj));
            },

            "unsigned long long": function () {
                return (obj === toUInt64(obj));
            },

            "unsigned short": function () {
                return (obj === toUInt16(obj));
            },

            "Arguments": function () {
                return true;
            },

            "": function () {
                return _self(t[pattern]).match(obj);
            }
        };

        return typeMap[typeOfPattern]();
    }

    typeOfPattern = getType(pattern, true);

    typeCoerce = {
        cast:  cast,
        copy:  copy,
        match: match
    };

    return typeCoerce;
};

module.exports = _self;

});
define('ripple/platform/ivi/3.0/typedef', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 _t, _c, _i;

/*
 * Primitive type definition
 */

_t = {
    // Basic
    Callback:                           "Callback",
    DOMString:                          "",
    Date:                               new Date(),
    Function:                           function () {},
    TZDate:                             "TZDate",
    any:                                "any",
    boolean:                            false,
    byte:                               "byte",
    double:                             "double",
    float:                              "float",
    long:                               "long",
    octet:                              "octet",
    short:                              "short",
    long_long:                          "long long",
    unsigned_long:                      "unsigned long",
    unsigned_long_long:                 "unsigned long long",
    unsigned_short:                     "unsigned short",

    // Vehicle
    TransmissionMode:                   ["park", "reverse", "neutral", "low",
                                        "drive", "overdrive"],
    DoorOpenStatus:                     ["open", "ajar", "closed"],
    AirflowDirection:                   ["frontpanel", "floorduct", "bilevel",
                                        "defrostfloor"],
    VehicleTypeEnum:                    [ "passengerCarMini",
                                        "passengerCarLight",
                                        "passengerCarCompact",
                                        "passengerCarMedium",
                                        "passengerCarHeavy",
                                        "sportUtilityVehicle", "pickupTruck",
                                        "van"],
    TransmissionGearTypeEnum:           ["auto", "manual"],
    FuelTypeEnum:                       ["gasoline", "methanol", "ethanol",
                                        "diesel", "lpg", "cng", "electric"],
    VehiclePowerMode:                   ["off", "accessory1", "accessory2",
                                        "running"],
    ConvertibleRoofStatus:              ["closed", "closing", "opening",
                                        "opened"],
    ParkingBrakeStatus:                 ["inactive", "active", "error"]
};

/*
 * Derivative type definition
 */

/*
 * Object attributes
 *     Contruct a prototype of an object. Specify a primitive type for each attribute.
 *
 * _optional
 *     Optional attributes table, which consists of two types of attributes,
 *
 *     nullable
 *         Nullable attributes, marked as '?' in IDL.
 *
 *     undefined
 *         Array type attributes, that not definitely specified to be
 *         initialized as an empty array, i.e., undefined-initialized array.
 *
 * _derived
 *     Derived types, which used in two cases of definition,
 *
 *     Subtype list
 *         An array consists of derived subtypes. It exists in the definition of
 *         a base type.
 *
 *     Union types
 *         An array consists of member types. It exists in the definition of
 *         a union type.
 *
 * _dictionary
 *     Dictionary type, which indicates that the object is a dictionary type.
 */

/*
 * Locale
 */

_t.LocaleChangedCallback = _t.Function;

/*
 * Media Server
 */
_t.MediaServerFoundServerCallback = _t.Function;
_t.MediaServerBrowseFindCallback = _t.Function;
_t.MediaServerErrorCallback = _t.Function;

/*
 * Vehicle
 */
_t.SupportedPropertiesSuccessCallback = _t.Function;

_t.VehiclePropertyErrorCallback = _t.Function;

_t.VehiclePropertyCallback = _t.Function;

_t.VehiclePropertyListCallback = _t.Function;

/*
 * VehicleSpeed
 */
_t.VehicleSpeed = {
    speed: _t.unsigned_short
};

/*
 * WheelSpeed
 */
_t.WheelSpeed = {
    speed: _t.unsigned_short
};

/*
 * EngineSpeed
 */
_t.EngineSpeed = {
    speed: _t.unsigned_long
};

/*
 * VehiclePowerModeType
 */
_t.VehiclePowerModeType = {
    value: _t.VehiclePowerMode
};

/*
 * Acceleration
 */
_t.Acceleration = {
    x: _t.unsigned_long,
    y: _t.unsigned_long,
    z: _t.unsigned_long
};

/*
 * Transmission
 */
_t.Transmission = {
    gear: _t.octet,
    mode: _t.TransmissionMode
};

/*
 * CruiseControlStatus
 */
_t.CruiseControlStatus = {
    activated: _t.boolean,
    speed:     _t.unsigned_short
};

/*
 * LightStatus
 */
_t.LightStatus = {
    head:                _t.boolean,
    rightTurn:           _t.boolean,
    leftTurn:            _t.boolean,
    brake:               _t.boolean,
    fog:                 _t.boolean,
    hazard:              _t.boolean,
    parking:             _t.boolean,
    highBeam:            _t.boolean,
    automaticHeadlights: _t.boolean,
    dynamicHighBeam:     _t.boolean,
    zone:                _t.unsigned_short
};

/*
 * InteriorLightStatus
 */
_t.InteriorLightStatus = {
    passenger: _t.boolean,
    driver:    _t.boolean,
    center:    _t.boolean
};

/*
 * Horn
 */
_t.Horn = {
    status: _t.boolean
};

/*
 * Fuel
 */
_t.Fuel = {
    level:                    _t.unsigned_short,
    range:                    _t.unsigned_long,
    instantConsumption:       _t.unsigned_long,
    averageConsumption:       _t.unsigned_long,
    fuelConsumedSinceRestart: _t.unsigned_long,
    vehicleTimeSinceRestart:  _t.unsigned_long
};

/*
 * EngineOil
 */
_t.EngineOil = {
    remaining:   _t.unsigned_short,
    temperature: _t.long,
    pressure:    _t.unsigned_short
};

/*
 * Temperature
 */
_t.Temperature = {
    interiorTemperature: _t.float,
    exteriorTemperature: _t.float
};

/*
 * RainSensor
 */
_t.RainSensor = {
    rain: _t.byte,
    zone: _t.unsigned_short
};

/*
 * Sunroof
 */
_t.Sunroof = {
    openness: _t.byte,
    tilt:     _t.byte
};

/*
 * ConvertibleRoof
 */
_t.ConvertibleRoof = {
    status: _t.ConvertibleRoofStatus
};

/*
 * Identification
 */
_t.Identification = {
    WMI:         _t.DOMString,
    VIN:         _t.DOMString,
    brand:       _t.DOMString,
    model:       _t.DOMString,
    year:        _t.DOMString,
    vehicleType: _t.VehicleTypeEnum
};

/*
 * SizeConfiguration
 */
_t.SizeConfiguration = {
    width:      _t.unsigned_short,
    height:     _t.unsigned_short,
    length:     _t.unsigned_short,
    doorsCount: [_t.unsigned_short],
    totalDoors: _t.unsigned_short
};

/*
 * FuelConfiguration
 */
_t.FuelConfiguration = {
    fuelType:       _t.FuelTypeEnum,
    refuelPosition: _t.unsigned_short
};

/*
 * TransmissionConfiguration
 */
_t.TransmissionConfiguration = {
    transmissionGearType: _t.TransmissionGearTypeEnum
};

/*
 * Odometer
 */
_t.Odometer = {
    distanceSinceStart: _t.unsigned_long,
    distanceTotal:      _t.unsigned_long
};

/*
 * ParkingBrake
 */
_t.ParkingBrake = {
    status: _t.ParkingBrakeStatus
};

/*
 * AntilockBrakingSystem
 */
_t.AntilockBrakingSystem = {
    enabled: _t.boolean,
    engaged: _t.boolean
};

/*
 * TractionControlSystem
 */
_t.TractionControlSystem = {
    enabled: _t.boolean,
    engaged: _t.boolean
};

/*
 * AirbagStatus
 */
_t.AirbagStatus = {
    activated: _t.boolean,
    deployed:  _t.boolean,
    zone:      _t.unsigned_short
};

/*
 * NightMode
 */
_t.NightMode = {
    mode: _t.boolean
};

/*
 * DrivingMode
 */
_t.DrivingMode = {
    mode: _t.boolean
};

/*
 * ButtonEvent
 */
_t.ButtonEvent = {
    buttonEvent: _t.unsigned_short
};

/*
 * SteeringWheel
 */
_t.SteeringWheel = {
    angle: _t.short
};

/*
 * ThrottlePosition
 */
_t.ThrottlePosition = {
    value: _t.unsigned_short
};

/*
 * EngineCoolant
 */
_t.EngineCoolant = {
    level:       _t.unsigned_short,
    temperature: _t.unsigned_short
};

/*
 * BrakeOperation
 */
_t.BrakeOperation = {
    brakePedalDepressed: _t.boolean
};

/*
 * Tire
 */
_t.Tire = {
    pressureLow: _t.boolean,
    pressure:    _t.unsigned_short,
    temperature: _t.short,
    zone:        _t.unsigned_short
};

/*
 * Door
 */
_t.Door = {
    status: _t.DoorOpenStatus,
    lock:   _t.boolean,
    zone:   _t.unsigned_short
};

/*
 * Defrost
 */
_t.Defrost = {
    defrostWindow:  _t.boolean,
    defrostMirrors: _t.boolean,
    zone:           _t.unsigned_short
};

/*
 * ClimateControl
 */
_t.ClimateControl = {
    airflowDirection:    _t.AirflowDirection,
    fanSpeedLevel:       _t.byte,
    targetTemperature:   _t.byte,
    airConditioning:     _t.boolean,
    heater:              _t.boolean,
    seatHeater:          _t.byte,
    seatCooler:          _t.byte,
    airRecirculation:    _t.boolean,
    steeringWheelHeater: _t.byte,
    zone:                _t.unsigned_short
};

/*
 * BatteryStatus
 */
_t.BatteryStatus = {
    chargeLevel: _t.unsigned_short,
    voltage:     _t.unsigned_short,
    current:     _t.unsigned_short,
    zone:        _t.unsigned_short
};

/*
 * VehicleCommonDataType
 */
_t.VehicleCommonDataType = {
    timeStamp: _t.unsigned_long_long,

    _derived: [_t.VehicleSpeed, _t.WheelSpeed, _t.EngineSpeed,
        _t.VehiclePowerModeType, _t.Acceleration, _t.Transmission,
        _t.CruiseControlStatus, _t.LightStatus, _t.InteriorLightStatus, _t.Horn,
        _t.Fuel, _t.EngineOil, _t.Temperature, _t.RainSensor, _t.Sunroof,
        _t.ConvertibleRoof, _t.Identification, _t.SizeConfiguration,
        _t.FuelConfiguration, _t.TransmissionConfiguration, _t.Odometer,
        _t.ParkingBrake, _t.AntilockBrakingSystem, _t.TractionControlSystem,
        _t.AirbagStatus, _t.NightMode, _t.ButtonEvent, _t.SteeringWheel,
        _t.ThrottlePosition, _t.EngineCoolant, _t.BrakeOperation, _t.Tire,
        _t.Door, _t.Defrost, _t.ClimateControl, _t.BatteryStatus]
};

/*
 * Constructor list definition
 */

/*
 * Generic constructor
 *     Construct a prototype of constructor. A fake array of arguments type is
 *     specified for constructor.
 *
 * Overloaded constructors
 *     Construct an array of prototype of constructor. Each array element is
 *     specified for one of constructors. The constructor with extra arguments
 *     are recommended to be defined ahead of the one with fewer same arguments
 *     for exact match.
 */

_c = {};

/*
 * Interface prototype definition
 */

_i = {
    // Locale
    Locale:             {},

    // Media Server
    MediaServerManager: {},
    MediaServer:        {},
    MediaContainer:     {},

    // Speech
    SpeechManager:      {},

    // Vehicle
    Vehicle:            {}
};

// Locale
_i.Locale.setLocale = {
    0: _t.DOMString
};

_i.Locale.getLocale = null;

_i.Locale.localeChanged = {
    0: _t.LocaleChangedCallback
};

// Media Server
_i.MediaServerManager.scanNetwork = {
    0: _t.MediaServerFoundServerCallback,
    1: _t.MediaServerErrorCallback,

    _optional: {
        // nullable
        1: true
    }
};

_i.MediaServer.upload = {
    0: _t.DOMString
};

_i.MediaServer.createFolder = {
    0: _t.DOMString
};

_i.MediaServer.browse = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.unsigned_long,
    3: _t.unsigned_long,
    4: _t.MediaServerBrowseFindCallback,
    5: _t.MediaServerErrorCallback,

    _optional: {
        // nullable
        5: true
    }
};

_i.MediaServer.find = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.DOMString,
    3: _t.unsigned_long,
    4: _t.unsigned_long,
    5: _t.MediaServerBrowseFindCallback,
    6: _t.MediaServerErrorCallback,

    _optional: {
        // nullable
        6: true
    }
};

_i.MediaContainer.upload = {
    0: _t.DOMString,
    1: _t.DOMString
};

_i.MediaContainer.createFolder = {
    0: _t.DOMString
};

// Speech
_i.SpeechManager.vocalizeString = {
    0: _t.DOMString
};

// Vehicle
_i.Vehicle.get = {
    0: _t.short,

    _optional: {
        // nullable
        1: true
    }
};

_i.Vehicle.subscribe = {
    0: _t.VehiclePropertyCallback,
    1: _t.short,

    _optional: {
        // nullable
        1: true
    }
};

_i.Vehicle.unsubscribe = {
    0: _t.unsigned_short,
};

_i.Vehicle.set = {
    0: _t.VehicleCommonDataType,
    1: _t.short,

    _optional: {
        // nullable
        1: true
    }
};

_i.Vehicle.getHistory = {
    0: _t.Date,
    1: _t.Date,
    2: _t.short,

    _optional: {
        // nullable
        2: true
    }
};

// Exports
_t.constructor = _c;
_t.interface   = _i;

module.exports = _t;

});
define('ripple/platform/ivi/3.0/vehicle', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    event = require('ripple/event'),
    t = require('ripple/platform/ivi/3.0/typecast'),
    errorcode = require('ripple/platform/ivi/3.0/errorcode'),
    WebAPIError = require('ripple/platform/ivi/3.0/WebAPIError'),
    VehicleCommonDataType,
    //Configuration and Identification Interfaces
    Identification,
    SizeConfiguration,
    FuelConfiguration,
    TransmissionConfiguration,
    WheelConfiguration,
    SteeringWheelConfiguration,
    //Running Status Interfaces
    VehicleSpeed,
    WheelSpeed,
    EngineSpeed,
    VehiclePowerModeType,
    PowerTrainTorque,
    AcceleratorPedalPosition,
    ThrottlePosition,
    //TripMeters   ------no work
    Diagnostic,
    Transmission,
    CruiseControlStatus,
    LightStatus,
    InteriorLightStatus,
    Horn,
    Chime,
    Fuel,
    EngineOil,
    Acceleration,
    EngineCoolant,
    SteeringWheel,
    IgnitionTime,
    YawRate,
    BrakeOperation,
    WheelTick,
    ButtonEvent,
    DrivingMode,
    NightMode,
    //Maintenance Interfaces
    Odometer,
    BatteryStatus,
    Tire,
    //DrivingSafety Interfaces
    AntilockBrakingSystem,
    TractionControlSystem,
    AirbagStatus,
    Door,
    //Climate Interfaces
    Temperature,
    RainSensor,
    Defrost,
    ClimateControl,
    Sunroof,
    ConvertibleRoof,
    //Vision and Parking Interfaces
    ParkingBrake,
    //
    VehicleFactory,
    _data = {
        nHandle: 0,          //subscribe listener flag
        supported: null,     //current supported properties
        history: null,         //all properties data
        cache: null,         //current all properties data
        properties: {}       //properties name
    },
    _security = {
        "http://tizen.org/privilege/vehicle": []
    },
    _self;

function _initialize () {
    _data.properties.common = ["diagnostic"];
    _data.properties.conf = [
        "identification", "sizeConfiguration", "fuelConfiguration",
        "transmissionConfiguration", "wheelConfiguration",
        "steeringWheelConfiguration"
    ];
    _data.properties.signal = [
        "vehicleSpeed", "wheelSpeed", "engineSpeed", "powerTrainTorque",
        "acceleratorPedalPosition", "throttlePosition", "tripMeters",
        "diagnostic", "transmission", "cruiseControlStatus", "lightStatus",
        "interiorLightStatus", "chime", "fuel", "engineOil", "acceleration",
        "engineCoolant", "steeringWheel", "ignitionTime", "yawRate",
        "brakeOperation", "wheelTick", "buttonEvent", "drivingMode",
        "nightMode", "odometer", "transmissionOil", "transmissionClutch",
        "brakeMaintenance", "washerFluid", "malfunctionIndicator",
        "batteryStatus", "tire", "driverIdentification",
        "languageConfiguration", "unitsOfMeasure", "mirror", "steeringWheel",
        "driveMode", "seatAdjustment", "dashboardIllumination", "vehicleSound",
        "antilockBrakingSystem", "tractionControlSystem",
        "electronicStabilityControl", "topSpeedLimit", "airbagStatus", "door",
        "childSafetyLock", "seat", "temperature", "rainSensor", "wiperStatus",
        "wiperSetting", "defrost", "sunroof", "convertibleRoof", "sideWindow",
        "climateControl", "atmosphericPressure", "laneDepartureStatus", "alarm",
        "parkingBrake", "parkingLights"
    ];

    event.on("vehicle-cache-refresh", function (supported, data) {
        _data.supported = supported;
        _data.cache = data;
    });

    event.trigger("vehicle-cache-request", [_data]);
}

event.on("vehicle-subscribe-response", function(propertyObj) {
    var property = propertyObj.type, success, handle, value;

    if (_data[property]) {
        for (handle in _data[property]) {
            success = _data[property][handle];
            value = new VehicleFactory(property, propertyObj.val);

            success(value);
        }
    }
});

event.on("vehicle-history-response", function(history) {
    _data.history = history;
});

function VehicleInterface (property) {
    function _supported() {
        t.Vehicle("supported", arguments);

        if (_data.supported.indexOf(property) === -1) {
            return false;
        }

        return true;
    }

    function _getFrom() {
        var history = _data.history;

        for (var i = 0; i < history.length; i++) {
            if (history[i][property]) {
                return history[i][property].timeStamp;
            }
        }
        return null;
    }

    function _getTo() {
        var history = _data.history;

        for (var i = history.length - 1; i >= 0; i--) {
            if (history[i][property]) {
                return history[i][property].timeStamp;
            }
        }
        return null;
    }

    this.__defineGetter__("supported", function () {
        return _supported(property);
    });

    this.__defineGetter__("zones", function () {
        return null;
    });

    this.__defineGetter__("isLogged", function () {
        return true;
    });

    this.__defineGetter__("from", function () {
        return new Date(_getFrom());
    });

    this.__defineGetter__("to", function () {
        return new Date(_getTo());
    });

    this.get = function (zone) {
        zone = zone ? zone : 0;
        t.Vehicle("get", arguments);

        return {
            then: function (resolve, reject) {
                var data;

                if (_data.supported.indexOf(property) === -1) {
                    reject(new WebAPIError(errorcode.PROPERTY_UNAVAILABLE));
                    return;
                }

                data = new VehicleFactory(property, _data.cache[property]);
                resolve(data);
            }
        };
    };

    this.getHistory = function (begin, end, zone) {
        zone = zone ? zone : 0;
        t.Vehicle("getHistory", arguments);

        return {
            then: function (resolve) {
                var history = _data.history,
                    data = [],
                    i, val, timeStamp;

                if (!begin || !end) {
                    resolve(data);
                    return;
                }
                begin = begin.getTime();
                end = end.getTime();

                for ( i = 0; i < history.length; i++) {
                    val = history[i][property];

                    if (val) {
                        timeStamp = val.timeStamp;
                        if (timeStamp < begin || timeStamp > end) {
                            continue;
                        }

                        data.push(new VehicleFactory(property, val));
                    }
                }

                resolve(data);
            }
        };
    };

    this.availableForRetrieval = function (attr) {
        if (_data.supported.indexOf(property) === -1) {
            return "not_supported";
        }
        return "available";
    };

    this.availabilityChangedListener = function (callback) {
        return 0;
    };

    this.removeAvailabilityChangedListener = function (handle) {
        return;
    };
}

function VehicleConfigurationInterface (property) {
    VehicleInterface.call(this, property);
}

function VehicleSignalInterface (property) {
    VehicleInterface.call(this, property);

    this.set = function (value, zone) {
        zone = zone ? zone : 0;
        t.Vehicle("set", arguments);

        return {
            then: function (resolve, reject) {
                var val = utils.copy(value);

                if (_data.supported.indexOf(property) === -1) {
                    reject(new WebAPIError(errorcode.PROPERTY_UNAVAILABLE));
                    return;
                }
                resolve();
                event.trigger("vehicle-set-request", [property, val]);
            }
        };
    };

    this.subscribe = function (success, zone) {
        var handle = ++_data.nHandle,
            key = "subscribe" + handle;

        zone = zone ? zone : 0;
        t.Vehicle("subscribe", arguments);

        if (!_data[property]) {
            _data[property] = {};
        }

        _data[property][key] = success;

        event.trigger("vehicle-subscribe-request", [property, true, zone]);

        return handle;
    };

    this.unsubscribe = function (handle) {
        var key = "subscribe" + handle;

        t.Vehicle("unsubscribe", arguments);

        if (_data[property] && _data[property][key])
            delete _data[property][key];

        return;
    };

    this.availableForSubscription = function (attr) {
        if (_data.supported.indexOf(property) === -1) {
            return "not_supported";
        }
        return "available";
    };

    this.availableForSetting = function (attr) {
        if (_data.supported.indexOf(property) === -1) {
            return "not_supported";
        }
        return "available";
    };
}

_self = function () {
    var vehicle;

    function _defineInterfaces() {
        var i, propertyName, propertyKey;

        for (i = 0; i < _data.properties.common.length; i++) {
            propertyKey = _data.properties.common[i];
            propertyName = propertyKey.substring(0, 1).toUpperCase() +
                    propertyKey.substring(1);

            vehicle[propertyKey] = {};
            (function(property){
                vehicle[propertyKey] = new VehicleInterface(property);
            })(propertyName);
        }

        for (i = 0; i < _data.properties.conf.length; i++) {
            propertyKey = _data.properties.conf[i];
            propertyName = propertyKey.substring(0, 1).toUpperCase() +
                    propertyKey.substring(1);

            vehicle[propertyKey] = {};
            (function(property){
                vehicle[propertyKey] = new VehicleConfigurationInterface(property);
            })(propertyName);
        }

        for (i = 0; i < _data.properties.signal.length; i++) {
            propertyKey = _data.properties.signal[i];
            propertyName = propertyKey.substring(0, 1).toUpperCase() +
                    propertyKey.substring(1);

            vehicle[propertyKey] = {};
            (function(property){
                vehicle[propertyKey] = new VehicleSignalInterface(property);
            })(propertyName);
        }
    }

    function handleSubFeatures (subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    vehicle = {
        handleSubFeatures: handleSubFeatures
    };
    _defineInterfaces();

    return vehicle;
};

VehicleFactory = function (vehicleType, value) {
    var instanceType;

    switch (vehicleType) {
    //configuration
    case "Identification":
        instanceType = new Identification(value);
        break;
    case "SizeConfiguration":
        instanceType = new SizeConfiguration(value);
        break;
    case "FuelConfiguration":
        instanceType = new FuelConfiguration(value);
        break;
    case "TransmissionConfiguration":
        instanceType = new TransmissionConfiguration(value);
        break;
    case "WheelConfiguration":
        instanceType = new WheelConfiguration(value);
        break;
    case "SteeringWheelConfiguration":
        instanceType = new SteeringWheelConfiguration(value);
        break;
    //signal
    case "VehicleSpeed":
        instanceType = new VehicleSpeed(value);
        break;
    case "WheelSpeed":
        instanceType = new WheelSpeed(value);
        break;
    case "EngineSpeed":
        instanceType = new EngineSpeed(value);
        break;
    case "VehiclePowerModeType":
        instanceType = new VehiclePowerModeType(value);
        break;
    case "PowerTrainTorque":
        instanceType = new PowerTrainTorque(value);
        break;
    case "AcceleratorPedalPosition":
        instanceType = new AcceleratorPedalPosition(value);
        break;
    case "ThrottlePosition":
        instanceType = new ThrottlePosition(value);
        break;
    case "Diagnostic":
        instanceType = new Diagnostic(value);
        break;
    case "Transmission":
        instanceType = new Transmission(value);
        break;
    case "CruiseControlStatus":
        instanceType = new CruiseControlStatus(value);
        break;
    case "LightStatus":
        instanceType = new LightStatus(value);
        break;
    case "InteriorLightStatus":
        instanceType = new InteriorLightStatus(value);
        break;
    case "Horn":
        instanceType = new Horn(value);
        break;
    case "Chime":
        instanceType = new Chime(value);
        break;
    case "Fuel":
        instanceType = new Fuel(value);
        break;
    case "EngineOil":
        instanceType = new EngineOil(value);
        break;
    case "Acceleration":
        instanceType = new Acceleration(value);
        break;
    case "EngineCoolant":
        instanceType = new EngineCoolant(value);
        break;
    case "SteeringWheel":
        instanceType = new SteeringWheel(value);
        break;
    case "IgnitionTime":
        instanceType = new IgnitionTime(value);
        break;
    case "YawRate":
        instanceType = new YawRate(value);
        break;
    case "BrakeOperation":
        instanceType = new BrakeOperation(value);
        break;
    case "WheelTick":
        instanceType = new WheelTick(value);
        break;
    case "ButtonEvent":
        instanceType = new ButtonEvent(value);
        break;
    case "DrivingMode":
        instanceType = new DrivingMode(value);
        break;
    case "NightMode":
        instanceType = new NightMode(value);
        break;
    //
    case "Odometer":
        instanceType = new Odometer(value);
        break;
    case "BatteryStatus":
        instanceType = new BatteryStatus(value);
        break;
    case "Tire":
        instanceType = new Tire(value);
        break;
    //
    case "AntilockBrakingSystem":
        instanceType = new AntilockBrakingSystem(value);
        break;
    case "TractionControlSystem":
        instanceType = new TractionControlSystem(value);
        break;
    case "AirbagStatus":
        instanceType = new AirbagStatus(value);
        break;
    case "Door":
        instanceType = new Door(value);
        break;
    //
    case "Temperature":
        instanceType = new Temperature(value);
        break;
    case "RainSensor":
        instanceType = new RainSensor(value);
        break;
    case "Defrost":
        instanceType = new Defrost(value);
        break;
    case "ClimateControl":
        instanceType = new ClimateControl(value);
        break;
    case "Sunroof":
        instanceType = new Sunroof(value);
        break;
    case "ConvertibleRoof":
        instanceType = new ConvertibleRoof(value);
        break;
    //
    case "ParkingBrake":
        instanceType = new ParkingBrake(value);
        break;
    }

    function _construct () {
        var val;

        for (val in value) {
            instanceType[val] = value[val];
        }
        return instanceType;
    }

    return _construct();
};

VehicleCommonDataType = function (propertyTypes) {
    var commonData = {};

    commonData.timeStamp = propertyTypes.timeStamp || null;

    this.__defineGetter__("timeStamp", function () {
        return commonData.timeStamp;
    });
};

VehiclePowerModeType = function (propertyTypes) {
    var vehiclePowerMode = {};

    VehicleCommonDataType.call(this, propertyTypes);

    vehiclePowerMode.value = propertyTypes.value || "off";

    this.__defineGetter__("value", function () {
        return vehiclePowerMode.value;
    });
};

Horn = function (propertyTypes) {
    var horn = {};

    VehicleCommonDataType.call(this, propertyTypes);

    horn.status = propertyTypes.status || false;

    this.__defineGetter__("status", function () {
        return horn.status;
    });

    this.__defineSetter__("status", function (val) {
        try {
            horn.status = t.boolean(val);
        } catch (err) {
        }
    });
};

RainSensor = function (propertyTypes) {
    var rainSensor = {};

    VehicleCommonDataType.call(this, propertyTypes);

    rainSensor.rain = propertyTypes.rain || 0;
    rainSensor.zone = propertyTypes.zone || 0;

    this.__defineGetter__("rain", function () {
        return rainSensor.rain;
    });

    this.__defineSetter__("rain", function (val) {
        try {
            val = t.byte(val);
            if (val >= 0 && val <= 10) {
                rainSensor.rain = val;
            }
        } catch (err) {
        }
    });

    this.__defineGetter__("zone", function () {
        return rainSensor.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            rainSensor.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

Sunroof = function (propertyTypes) {
    var sunroof = {};

    VehicleCommonDataType.call(this, propertyTypes);

    sunroof.openness = propertyTypes.openness || 0;
    sunroof.tilt = propertyTypes.tilt || 0;
    sunroof.zone = propertyTypes.zone || 0;

    this.__defineGetter__("openness", function () {
        return sunroof.openness;
    });

    this.__defineSetter__("openness", function (val) {
        try {
            val = t.byte(val);
            if (val >= 0 && val <= 100) {
                sunroof.openness = val;
            }
        } catch (err) {
        }
    });

    this.__defineGetter__("tilt", function () {
        return sunroof.tilt;
    });

    this.__defineSetter__("tilt", function (val) {
        try {
            val = t.byte(val);
            if (val >= 0 && val <= 100) {
                sunroof.tilt = val;
            }
        } catch (err) {
        }
    });

    this.__defineGetter__("zone", function () {
        return sunroof.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            sunroof.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

ConvertibleRoof = function (propertyTypes) {
    var convertibleRoof = {};

    VehicleCommonDataType.call(this, propertyTypes);

    convertibleRoof.status = propertyTypes.status || "closed";

    this.__defineGetter__("status", function () {
        return convertibleRoof.status;
    });

    this.__defineSetter__("status", function (val) {
        try {
            convertibleRoof.status = t.ConvertibleRoofStatus(val);
        } catch (err) {
        }
    });
};

Identification = function (propertyTypes) {
    var identification = {};

    VehicleCommonDataType.call(this, propertyTypes);

    identification.VIN = propertyTypes.VIN || null;
    identification.WMI = propertyTypes.WMI || null;
    identification.brand = propertyTypes.brand || null;
    identification.model = propertyTypes.model || null;
    identification.year = propertyTypes.year || null;
    identification.vehicleType = propertyTypes.vehicleType || null;

    this.__defineGetter__("VIN", function () {
        return identification.VIN;
    });

    this.__defineGetter__("WMI", function () {
        return identification.WMI;
    });

    this.__defineGetter__("brand", function () {
        return identification.brand;
    });

    this.__defineGetter__("model", function () {
        return identification.model;
    });

    this.__defineGetter__("year", function () {
        return identification.year;
    });

    this.__defineGetter__("vehicleType", function () {
        return identification.vehicleType;
    });
};

SizeConfiguration = function (propertyTypes) {
    var sizeConfiguration = {};

    VehicleCommonDataType.call(this, propertyTypes);

    sizeConfiguration.doorsCount = propertyTypes.doorsCount || null;
    sizeConfiguration.height = propertyTypes.height || null;
    sizeConfiguration.length = propertyTypes.length || null;
    sizeConfiguration.totalDoors = propertyTypes.totalDoors || null;
    sizeConfiguration.width = propertyTypes.width || null;

    this.__defineGetter__("doorsCount", function () {
        return sizeConfiguration.doorsCount;
    });

    this.__defineGetter__("height", function () {
        return sizeConfiguration.height;
    });

    this.__defineGetter__("length", function () {
        return sizeConfiguration.length;
    });

    this.__defineGetter__("totalDoors", function () {
        return sizeConfiguration.totalDoors;
    });

    this.__defineGetter__("width", function () {
        return sizeConfiguration.width;
    });
};

FuelConfiguration = function (propertyTypes) {
    var fuelConfiguration = {};

    VehicleCommonDataType.call(this, propertyTypes);

    fuelConfiguration.fuelType = propertyTypes.fuelType || null;
    fuelConfiguration.refuelPosition = propertyTypes.refuelPosition || null;

    this.__defineGetter__("fuelType", function () {
        return fuelConfiguration.fuelType;
    });

    this.__defineGetter__("refuelPosition", function () {
        return fuelConfiguration.refuelPosition;
    });
};

TransmissionConfiguration = function (propertyTypes) {
    var transmissionConfiguration = {};

    VehicleCommonDataType.call(this, propertyTypes);

    transmissionConfiguration.transmissionGearType =
        propertyTypes.transmissionGearType || null;

    this.__defineGetter__("transmissionGearType", function () {
        return transmissionConfiguration.transmissionGearType;
    });
};

WheelConfiguration = function (propertyTypes) {
    var wheelConfiguration = {};

    VehicleCommonDataType.call(this, propertyTypes);

    wheelConfiguration.wheelRadius = propertyTypes.wheelRadius || null;
    wheelConfiguration.zone = propertyTypes.zone || 0;

    this.__defineGetter__("wheelRadius", function () {
        return wheelConfiguration.wheelRadius;
    });

    this.__defineGetter__("zone", function () {
        return wheelConfiguration.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            wheelConfiguration.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

SteeringWheelConfiguration = function (propertyTypes) {
    var steeringWheelConfiguration = {};

    VehicleCommonDataType.call(this, propertyTypes);

    steeringWheelConfiguration.steeringWheelLeft =
        propertyTypes.steeringWheelLeft || null;

    this.__defineGetter__("steeringWheelLeft", function () {
        return steeringWheelConfiguration.steeringWheelLeft;
    });
};

VehicleSpeed = function (propertyTypes) {
    var vehicleSpeed = {};

    VehicleCommonDataType.call(this, propertyTypes);

    vehicleSpeed.speed = propertyTypes.speed || 0;

    this.__defineGetter__("speed", function () {
        return vehicleSpeed.speed;
    });
};

WheelSpeed = function (propertyTypes) {
    var wheelSpeed = {};

    VehicleCommonDataType.call(this, propertyTypes);

    wheelSpeed.speed = propertyTypes.speed || 0;
    wheelSpeed.zone = propertyTypes.zone || 0;

    this.__defineGetter__("speed", function () {
        return wheelSpeed.speed;
    });

    this.__defineGetter__("zone", function () {
        return wheelSpeed.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            wheelSpeed.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

EngineSpeed = function (propertyTypes) {
    var engineSpeed = {};

    VehicleCommonDataType.call(this, propertyTypes);

    engineSpeed.speed = propertyTypes.speed || 0;

    this.__defineGetter__("speed", function () {
        return engineSpeed.speed;
    });
};

PowerTrainTorque = function (propertyTypes) {
    var powerTrainTorque = {};

    VehicleCommonDataType.call(this, propertyTypes);

    powerTrainTorque.value = propertyTypes.value || 0;

    this.__defineGetter__("value", function () {
        return powerTrainTorque.value;
    });
};

AcceleratorPedalPosition = function (propertyTypes) {
    var acceleratorPedalPosition = {};

    VehicleCommonDataType.call(this, propertyTypes);

    acceleratorPedalPosition.value = propertyTypes.value || 0;

    this.__defineGetter__("value", function () {
        return acceleratorPedalPosition.value;
    });
};

ThrottlePosition = function (propertyTypes) {
    var throttlePosition = {};

    VehicleCommonDataType.call(this, propertyTypes);

    throttlePosition.value = propertyTypes.value || 0;

    this.__defineGetter__("value", function () {
        return throttlePosition.value;
    });
};

Diagnostic = function (propertyTypes) {
    var diagnostic = {};

    VehicleCommonDataType.call(this, propertyTypes);

    diagnostic.accumulatedEngineRuntime =
        propertyTypes.accumulatedEngineRuntime || 0;
    diagnostic.distanceWithMILOn = propertyTypes.distanceWithMILOn || 0;
    diagnostic.distanceSinceCodeCleared =
        propertyTypes.distanceSinceCodeCleared || 0;
    diagnostic.timeRunMILOn = propertyTypes.timeRunMILOn || 0;
    diagnostic.timeTroubleCodeClear = propertyTypes.timeTroubleCodeClear || 0;

    this.__defineGetter__("accumulatedEngineRuntime", function () {
        return diagnostic.accumulatedEngineRuntime;
    });

    this.__defineGetter__("distanceWithMILOn", function () {
        return diagnostic.distanceWithMILOn;
    });

    this.__defineGetter__("distanceSinceCodeCleared", function () {
        return diagnostic.distanceSinceCodeCleared;
    });

    this.__defineGetter__("timeRunMILOn", function () {
        return diagnostic.timeRunMILOn;
    });

    this.__defineGetter__("timeTroubleCodeClear", function () {
        return diagnostic.timeTroubleCodeClear;
    });
};

Transmission = function (propertyTypes) {
    var transmission = {};

    VehicleCommonDataType.call(this, propertyTypes);

    transmission.gear = propertyTypes.gear || null;
    transmission.mode = propertyTypes.mode || null;

    this.__defineGetter__("gear", function () {
        return transmission.gear;
    });

    this.__defineGetter__("mode", function () {
        return transmission.mode;
    });
};

CruiseControlStatus = function (propertyTypes) {
    var cruiseControlStatus = {};

    VehicleCommonDataType.call(this, propertyTypes);

    cruiseControlStatus.status = propertyTypes.status || false;
    cruiseControlStatus.speed = propertyTypes.speed || 0;

    this.__defineGetter__("status", function () {
        return cruiseControlStatus.status;
    });

    this.__defineGetter__("speed", function () {
        return cruiseControlStatus.speed;
    });
};

LightStatus = function (propertyTypes) {
    var lightStatus = {};

    VehicleCommonDataType.call(this, propertyTypes);

    lightStatus.head = propertyTypes.head || false;
    lightStatus.rightTurn = propertyTypes.rightTurn || false;
    lightStatus.leftTurn = propertyTypes.leftTurn || false;
    lightStatus.brake = propertyTypes.brake || false;
    lightStatus.fog = propertyTypes.fog || null;
    lightStatus.hazard = propertyTypes.hazard || false;
    lightStatus.parking = propertyTypes.parking || false;
    lightStatus.highBeam = propertyTypes.highBeam || false;
    lightStatus.automaticHeadlights = propertyTypes.automaticHeadlights || null;
    lightStatus.dynamicHighBeam = propertyTypes.dynamicHighBeam || null;
    lightStatus.zone = propertyTypes.zone || 0;

    this.__defineGetter__("head", function () {
        return lightStatus.head;
    });

    this.__defineSetter__("head", function (val) {
        try {
            lightStatus.head = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("rightTurn", function () {
        return lightStatus.rightTurn;
    });

    this.__defineSetter__("rightTurn", function (val) {
        try {
            lightStatus.rightTurn = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("leftTurn", function () {
        return lightStatus.leftTurn;
    });

    this.__defineSetter__("leftTurn", function (val) {
        try {
            lightStatus.leftTurn = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("brake", function () {
        return lightStatus.brake;
    });

    this.__defineSetter__("brake", function (val) {
        try {
            lightStatus.brake = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("fog", function () {
        return lightStatus.fog;
    });

    this.__defineSetter__("fog", function (val) {
        try {
            lightStatus.fog = t.boolean(val, "?");
        } catch (err) {
        }
    });

    this.__defineGetter__("hazard", function () {
        return lightStatus.hazard;
    });

    this.__defineSetter__("hazard", function (val) {
        try {
            lightStatus.hazard = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("parking", function () {
        return lightStatus.parking;
    });

    this.__defineSetter__("parking", function (val) {
        try {
            lightStatus.parking = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("highBeam", function () {
        return lightStatus.highBeam;
    });

    this.__defineSetter__("highBeam", function (val) {
        try {
            lightStatus.highBeam = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("automaticHeadlights", function () {
        return lightStatus.automaticHeadlights;
    });

    this.__defineSetter__("automaticHeadlights", function (val) {
        try {
            lightStatus.automaticHeadlights = t.boolean(val, "?");
        } catch (err) {
        }
    });

    this.__defineGetter__("dynamicHighBeam", function () {
        return lightStatus.dynamicHighBeam;
    });

    this.__defineSetter__("dynamicHighBeam", function (val) {
        try {
            lightStatus.dynamicHighBeam = t.boolean(val, "?");
        } catch (err) {
        }
    });

    this.__defineGetter__("zone", function () {
        return lightStatus.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            lightStatus.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

InteriorLightStatus = function (propertyTypes) {
    var interiorLightStatus = {};

    VehicleCommonDataType.call(this, propertyTypes);

    interiorLightStatus.passenger = propertyTypes.passenger || false;
    interiorLightStatus.driver = propertyTypes.driver || false;
    interiorLightStatus.center = propertyTypes.center || false;

    this.__defineGetter__("passenger", function () {
        return interiorLightStatus.passenger;
    });

    this.__defineSetter__("passenger", function (val) {
        try {
            interiorLightStatus.passenger = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("driver", function () {
        return interiorLightStatus.driver;
    });

    this.__defineSetter__("driver", function (val) {
        try {
            interiorLightStatus.driver = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("center", function () {
        return interiorLightStatus.center;
    });

    this.__defineSetter__("center", function (val) {
        try {
            interiorLightStatus.center = t.boolean(val);
        } catch (err) {
        }
    });
};

Chime = function (propertyTypes) {
    var chime = {};

    VehicleCommonDataType.call(this, propertyTypes);

    chime.status = chime.status || false;

    this.__defineGetter__("status", function () {
        return chime.status;
    });
};

Fuel = function (propertyTypes) {
    var fuel = {};

    VehicleCommonDataType.call(this, propertyTypes);

    fuel.level = propertyTypes.level || 0;
    fuel.range = propertyTypes.range || 0;
    fuel.instantConsumption = propertyTypes.instantConsumption || 0;
    fuel.averageConsumption = propertyTypes.averageConsumption || 0;
    fuel.fuelConsumedSinceRestart = propertyTypes.fuelConsumedSinceRestart || 0;
    fuel.vehicleTimeSinceRestart = propertyTypes.vehicleTimeSinceRestart || 0;

    this.__defineGetter__("level", function () {
        return fuel.level;
    });

    this.__defineGetter__("range", function () {
        return fuel.range;
    });

    this.__defineGetter__("instantConsumption", function () {
        return fuel.instantConsumption;
    });

    this.__defineGetter__("averageConsumption", function () {
        return fuel.averageConsumption;
    });

    this.__defineGetter__("fuelConsumedSinceRestart", function () {
        return fuel.fuelConsumedSinceRestart;
    });

    this.__defineGetter__("vehicleTimeSinceRestart", function () {
        return fuel.vehicleTimeSinceRestart;
    });
};

EngineOil = function (propertyTypes) {
    var engineOil = {};

    VehicleCommonDataType.call(this, propertyTypes);

    engineOil.remaining = propertyTypes.remaining || 0;
    engineOil.temperature = propertyTypes.temperature || 0;
    engineOil.pressure = propertyTypes.Pressure || 0;

    this.__defineGetter__("remaining", function () {
        return engineOil.remaining;
    });

    this.__defineSetter__("remaining", function (val) {
        try {
            engineOil.remaining = t.unsigned_short(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("temperature", function () {
        return engineOil.temperature;
    });

    this.__defineSetter__("temperature", function (val) {
        try {
            engineOil.temperature = t.long(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("pressure", function () {
        return engineOil.pressure;
    });

    this.__defineSetter__("pressure", function (val) {
        try {
            engineOil.pressure = t.unsigned_short(val);
        } catch (err) {
        }
    });
};

Acceleration = function (propertyTypes) {
    var acceleration = {};

    VehicleCommonDataType.call(this, propertyTypes);

    acceleration.x = propertyTypes.x || 0;
    acceleration.y = propertyTypes.y || 0;
    acceleration.z = propertyTypes.z || 0;

    this.__defineGetter__("x", function () {
        return acceleration.x;
    });

    this.__defineGetter__("y", function () {
        return acceleration.y;
    });

    this.__defineGetter__("z", function () {
        return acceleration.z;
    });
};

EngineCoolant = function (propertyTypes) {
    var engineCoolant = {};

    VehicleCommonDataType.call(this, propertyTypes);

    engineCoolant.level = propertyTypes.level || 0;
    engineCoolant.temperature = propertyTypes.temperature || 0;

    this.__defineGetter__("level", function () {
        return engineCoolant.level;
    });

    this.__defineGetter__("temperature", function () {
        return engineCoolant.temperature;
    });
};

SteeringWheel = function (propertyTypes) {
    var steeringWheel = {};

    VehicleCommonDataType.call(this, propertyTypes);

    steeringWheel.angle = propertyTypes.angle || 0;

    this.__defineGetter__("angle", function () {
        return steeringWheel.angle;
    });
};

IgnitionTime = function (propertyTypes) {
    var ignitionTime = {};

    VehicleCommonDataType.call(this, propertyTypes);

    ignitionTime.ignitionOnTime = propertyTypes.ignitionOnTime || 0;
    ignitionTime.ignitionOffTime = propertyTypes.ignitionOffTime || 0;

    this.__defineGetter__("ignitionOnTime", function () {
        return ignitionTime.ignitionOnTime;
    });

    this.__defineGetter__("ignitionOffTime", function () {
        return ignitionTime.ignitionOffTime;
    });
};

YawRate = function (propertyTypes) {
    var yawRate = {};

    VehicleCommonDataType.call(this, propertyTypes);

    yawRate.value = propertyTypes.value || 0;

    this.__defineGetter__("value", function () {
        return yawRate.value;
    });
};

BrakeOperation = function (propertyTypes) {
    var brakeOperation = {};

    VehicleCommonDataType.call(this, propertyTypes);

    brakeOperation.brakePedalDepressed = propertyTypes.brakePedalDepressed ||
        false;

    this.__defineGetter__("brakePedalDepressed", function () {
        return brakeOperation.brakePedalDepressed;
    });
};

WheelTick = function (propertyTypes) {
    var wheelTick = {};

    VehicleCommonDataType.call(this, propertyTypes);

    wheelTick.value = propertyTypes.value || 0;
    wheelTick.zone = propertyTypes.zone || 0;

    this.__defineGetter__("value", function () {
        return wheelTick.value;
    });

    this.__defineGetter__("zone", function () {
        return wheelTick.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            wheelTick.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

ButtonEvent = function (propertyTypes) {
    var buttonEvent = {};

    VehicleCommonDataType.call(this, propertyTypes);

    buttonEvent.buttonEvent = propertyTypes.buttonEvent || 0;

    this.__defineGetter__("buttonEvent", function () {
        return buttonEvent.buttonEvent;
    });

    this.__defineSetter__("buttonEvent", function (val) {
        try {
            buttonEvent.buttonEvent = t.unsigned_short(val);
        } catch (err) {
        }
    });
};

DrivingMode = function (propertyTypes) {
    var drivingMode = {};

    VehicleCommonDataType.call(this, propertyTypes);

    drivingMode.mode = propertyTypes.mode || false;

    this.__defineGetter__("drivingMode", function () {
        return drivingMode.drivingMode;
    });
};

NightMode = function (propertyTypes) {
    var nightMode = {};

    VehicleCommonDataType.call(this, propertyTypes);

    nightMode.mode = propertyTypes.mode || false;

    this.__defineGetter__("mode", function () {
        return nightMode.mode;
    });

    this.__defineSetter__("mode", function (val) {
        try {
            nightMode.mode = t.boolean(val);
        } catch (err) {
        }
    });
};

Odometer = function (propertyTypes) {
    var odm = {};

    VehicleCommonDataType.call(this, propertyTypes);

    odm.distanceSinceStart = propertyTypes.distanceSinceStart || null;
    odm.distanceTotal = propertyTypes.distanceTotal || 0;

    this.__defineGetter__("distanceSinceStart", function () {
        return odm.distanceSinceStart;
    });

    this.__defineGetter__("distanceTotal", function () {
        return odm.distanceTotal;
    });
};

BatteryStatus = function (propertyTypes) {
    var batteryStatus = {};

    VehicleCommonDataType.call(this, propertyTypes);

    batteryStatus.chargeLevel = propertyTypes.chargeLevel || null;
    batteryStatus.voltage = propertyTypes.voltage || null;
    batteryStatus.current = propertyTypes.current || null;
    batteryStatus.zone = propertyTypes.zone || 0;

    this.__defineGetter__("chargeLevel", function () {
        return batteryStatus.chargeLevel;
    });

    this.__defineGetter__("voltage", function () {
        return batteryStatus.voltage;
    });

    this.__defineGetter__("current", function () {
        return batteryStatus.current;
    });

    this.__defineGetter__("zone", function () {
        return batteryStatus.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            batteryStatus.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

Tire = function (propertyTypes) {
    var tire = {};

    VehicleCommonDataType.call(this, propertyTypes);

    tire.pressureLow = propertyTypes.pressureLow || null;
    tire.pressure = propertyTypes.pressure || null;
    tire.temperature = propertyTypes.temperature || null;
    tire.zone = propertyTypes.zone || 0;

    this.__defineGetter__("pressureLow", function () {
        return tire.pressureLow;
    });

    this.__defineGetter__("pressure", function () {
        return tire.pressure;
    });

    this.__defineGetter__("zone", function () {
        return tire.zone;
    });

    this.__defineGetter__("temperature", function () {
        return tire.temperature;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            tire.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

AntilockBrakingSystem = function (propertyTypes) {
    var abs = {};

    VehicleCommonDataType.call(this, propertyTypes);

    abs.enabled = propertyTypes.enabled || false;
    abs.engaged = propertyTypes.engaged || false;

    this.__defineGetter__("enabled", function () {
        return abs.enabled;
    });

    this.__defineGetter__("engaged", function () {
        return abs.engaged;
    });
};

TractionControlSystem = function (propertyTypes) {
    var tcs = {};

    VehicleCommonDataType.call(this, propertyTypes);

    tcs.enabled = propertyTypes.enabled || false;
    tcs.engaged = propertyTypes.engaged || false;

    this.__defineGetter__("enabled", function () {
        return tcs.enabled;
    });

    this.__defineGetter__("engaged", function () {
        return tcs.engaged;
    });
};

AirbagStatus = function (propertyTypes) {
    var airbagStatus = {};

    VehicleCommonDataType.call(this, propertyTypes);

    airbagStatus.activated = propertyTypes.activated || false;
    airbagStatus.deployed = propertyTypes.deployed || false;
    airbagStatus.zone = propertyTypes.zone || 0;

    this.__defineGetter__("activated", function () {
        return airbagStatus.activated;
    });

    this.__defineGetter__("deployed", function () {
        return airbagStatus.deployed;
    });

    this.__defineGetter__("zone", function () {
        return airbagStatus.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            airbagStatus.zone = t.unsigned_short(val);
        } catch (err) {
        }
    });
};

Door = function (propertyTypes) {
    var door = {};

    VehicleCommonDataType.call(this, propertyTypes);

    door.status = propertyTypes.status || "closed";
    door.lock = propertyTypes.lock || false;
    door.zone = propertyTypes.zone || 0;

    this.__defineGetter__("status", function () {
        return door.status;
    });

    this.__defineGetter__("lock", function () {
        return door.lock;
    });

    this.__defineSetter__("lock", function (val) {
        try {
            door.lock = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("zone", function () {
        return door.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            door.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

Temperature = function (propertyTypes) {
    var temperature = {};

    VehicleCommonDataType.call(this, propertyTypes);

    temperature.interiorTemperature = propertyTypes.interiorTemperature || 0;
    temperature.exteriorTemperature = propertyTypes.exteriorTemperature || 0;

    this.__defineGetter__("interiorTemperature", function () {
        return temperature.interiorTemperature;
    });

    this.__defineGetter__("exteriorTemperature", function () {
        return temperature.exteriorTemperature;
    });
};

Defrost = function (propertyTypes) {
    var defrost = {};

    VehicleCommonDataType.call(this, propertyTypes);

    defrost.defrostWindow = propertyTypes.defrostWindow || null;
    defrost.defrostMirrors = propertyTypes.defrostMirrors || null;
    defrost.zone = propertyTypes.zone || 0;

    this.__defineGetter__("defrostWindow", function () {
        return defrost.defrostWindow;
    });

    this.__defineSetter__("defrostWindow", function (val) {
        try {
            defrost.defrostWindow = t.boolean(val, "?");
        } catch (err) {
        }
    });

    this.__defineGetter__("defrostMirrors", function () {
        return defrost.defrostMirrors;
    });

    this.__defineSetter__("defrostMirrors", function (val) {
        try {
            defrost.defrostMirrors = t.boolean(val, "?");
        } catch (err) {
        }
    });

    this.__defineGetter__("zone", function () {
        return defrost.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            defrost.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

ClimateControl = function (propertyTypes) {
    var climateControl = {};

    VehicleCommonDataType.call(this, propertyTypes);

    climateControl.airflowDirection = propertyTypes.airflowDirection ||
        "frontpanel";
    climateControl.fanSpeedLevel = propertyTypes.fanSpeedLevel || 0;
    climateControl.targetTemperature = propertyTypes.targetTemperature || null;
    climateControl.airConditioning = propertyTypes.airConditioning || false;
    climateControl.heater = propertyTypes.heater || false;
    climateControl.seatHeater = propertyTypes.seatHeater || null;
    climateControl.seatCooler = propertyTypes.seatCooler || null;
    climateControl.airRecirculation = propertyTypes.airRecirculation || false;
    climateControl.steeringWheelHeater = propertyTypes.steeringWheelHeater ||
        null;
    climateControl.zone = propertyTypes.zone || 0;

    this.__defineGetter__("airflowDirection", function () {
        return climateControl.airflowDirection;
    });

    this.__defineSetter__("airflowDirection", function (val) {
        try {
            climateControl.airflowDirection = t.AirflowDirection(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("fanSpeedLevel", function () {
        return climateControl.fanSpeedLevel;
    });

    this.__defineSetter__("fanSpeedLevel", function (val) {
        try {
            climateControl.fanSpeedLevel = t.byte(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("targetTemperature", function () {
        return climateControl.targetTemperature;
    });

    this.__defineSetter__("targetTemperature", function (val) {
        try {
            climateControl.targetTemperature = t.byte(val, "?");
        } catch (err) {
        }
    });

    this.__defineGetter__("airConditioning", function () {
        return climateControl.airConditioning;
    });

    this.__defineSetter__("airConditioning", function (val) {
        try {
            climateControl.airConditioning = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("heater", function () {
        return climateControl.heater;
    });

    this.__defineSetter__("heater", function (val) {
        try {
            climateControl.heater = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("seatHeater", function () {
        return climateControl.seatHeater;
    });

    this.__defineSetter__("seatHeater", function (val) {
        try {
            climateControl.seatHeater = t.byte(val, "?");
        } catch (err) {
        }
    });

    this.__defineGetter__("seatCooler", function () {
        return climateControl.seatCooler;
    });

    this.__defineSetter__("seatCooler", function (val) {
        try {
            climateControl.seatCooler = t.byte(val, "?");
        } catch (err) {
        }
    });

    this.__defineGetter__("airRecirculation", function () {
        return climateControl.airRecirculation;
    });

    this.__defineSetter__("airRecirculation", function (val) {
        try {
            climateControl.airRecirculation = t.boolean(val);
        } catch (err) {
        }
    });

    this.__defineGetter__("steeringWheelHeater", function () {
        return climateControl.steeringWheelHeater;
    });

    this.__defineSetter__("steeringWheelHeater", function (val) {
        try {
            climateControl.steeringWheelHeater = t.byte(val, "?");
        } catch (err) {
        }
    });

    this.__defineGetter__("zone", function () {
        return climateControl.zone;
    });

    this.__defineSetter__("zone", function (val) {
        try {
            climateControl.zone = t.unsigned_short(val, "?");
        } catch (err) {
        }
    });
};

ParkingBrake = function (propertyTypes) {
    var parkingBrake = {};

    VehicleCommonDataType.call(this, propertyTypes);

    parkingBrake.status = propertyTypes.status || "inactive";

    this.__defineGetter__("status", function () {
        return parkingBrake.status;
    });

    this.__defineSetter__("status", function (val) {
        try {
            parkingBrake.status = t.ParkingBrakeStatus(val);
        } catch (err) {
        }
    });
};

_initialize();

module.exports = _self;

});
define('ripple/platform/phonegap/1.0.0/AVCodecsAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, audioCodecs, videoCodecs) {
    return {
        info: info,
        id: id,
        audioCodecs: audioCodecs,
        videoCodecs: videoCodecs
    };
};

});
define('ripple/platform/phonegap/1.0.0/Acceleration', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (x, y, z) {
    return {
        x: x || 0,
        y: y || 0,
        z: z || 0,
        timestamp: new Date().getTime()
    };
};

});
define('ripple/platform/phonegap/1.0.0/AudioCodecAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, compFormats, encode, decode) {
    return {
        info: info,
        id: id,
        compFormats: compFormats,
        encode: encode,
        decode: decode
    };
};

});
define('ripple/platform/phonegap/1.0.0/AudioDeviceAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (type, freqRangeLow, freqRangeHigh, volumeLevel, info) {
    return {
        type: type,
        freqRangeLow: freqRangeLow,
        freqRangeHigh: freqRangeHigh,
        volumeLevel: volumeLevel,
        info: info
    };

};

});
define('ripple/platform/phonegap/1.0.0/BrailleDeviceAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (nbCells, info) {
    return {
        nbCells: nbCells,
        info: info
    };

};

});
define('ripple/platform/phonegap/1.0.0/CPUAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, usage) {
    return {
        info: info,
        id: id,
        usage: usage
    };
};

});
define('ripple/platform/phonegap/1.0.0/CameraAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (supportsVideo, hasFlash, sensorPixels, maxZoomFactor) {
    return {
        supportsVideo: supportsVideo,
        hasFlash: hasFlash,
        sensorPixels: sensorPixels,
        maxZoomFactor: maxZoomFactor
    };

};

});
define('ripple/platform/phonegap/1.0.0/Connection', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    UNKNOWN: "unknown",
    ETHERNET: "ethernet",
    WIFI: "wifi",
    CELL_2G: "2g",
    CELL_3G: "3g",
    CELL_4G: "4g",
    NONE: "none"
};

});
define('ripple/platform/phonegap/1.0.0/ConnectionAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, type, currentOrientation, currentUploadBandwidth, maxDownloadBandwidth, maxUploadBandwidth, currentSignalStrength, roaming) {
    return {
        info: info,
        id: id,
        type: type,
        currentDownloadBandwidth: currentOrientation,
        currentUploadBandwidth: currentUploadBandwidth,
        maxDownloadBandwidth: maxDownloadBandwidth,
        maxUploadBandwidth: maxUploadBandwidth,
        currentSignalStrength: currentSignalStrength,
        roaming: roaming
    };
};

});
define('ripple/platform/phonegap/1.0.0/Contact', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    event = require('ripple/event');

function _properties(obj) {
    var prop, newObj = {};
    for (prop in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, prop)) {
            if (typeof obj[prop] !== "function") {
                newObj[prop] = utils.copy(obj[prop]);
            }
        }
    }
    return newObj;
}

module.exports = function (
        id,
        displayName,
        name,
        nickname,
        phoneNumbers,
        emails,
        addresses,
        ims,
        organizations,
        birthday,
        note,
        photos,
        categories,
        urls
) {

    return {
        id: id || Math.uuid(undefined, 16),
        displayName: displayName || null,
        name: name || null,
        nickname: nickname || null,
        phoneNumbers: phoneNumbers || null,
        emails: emails || null,
        addresses: addresses || null,
        ims: ims || null,
        organizations: organizations || null,
        birthday: birthday || null,
        note: note || null,
        photos: photos || null,
        categories: categories || null,
        urls: urls || null,
        save: function (success, error) {
            var _self = this,
                lastUpdated = this.updated; // hackish

            this.updated = new Date();

            if (!this.id) {
                this.id = Math.uuid(undefined, 16);
            }

            event.trigger("phonegap-contact-save", [_properties(this), success, function (e) {
                _self.updated = lastUpdated;
                error(e);
            }]);
        },
        remove: function (success, error) {
            event.trigger("phonegap-contact-remove", [this.id, success, error]);
        },
        clone: function () {
            var copy = utils.copy(this);
            copy.id = null;
            return copy;
        }
    };
};

});
define('ripple/platform/phonegap/1.0.0/ContactAccount', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (domain, username, userid) {
    return {
        domain: domain,
        username: username,
        userid: userid
    };
};

});
define('ripple/platform/phonegap/1.0.0/ContactAddress', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (pref, type, formatted, streetAddress, locality, region, postalCode, country, id) {
    return {
        pref: pref || null,
        type: type || null,
        formatted: formatted || null,
        streetAddress: streetAddress || null,
        locality: locality || null,
        region: region || null,
        postalCode: postalCode || null,
        country: country || null,
        id: id || null
    };
};

});
define('ripple/platform/phonegap/1.0.0/ContactError', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function ContactError(code) {
    this.code = code || null;
}

ContactError.UNKNOWN_ERROR = 0;
ContactError.INVALID_ARGUMENT_ERROR = 1;
ContactError.NOT_FOUND_ERROR = 2;
ContactError.TIMEOUT_ERROR = 3;
ContactError.PENDING_OPERATION_ERROR = 4;
ContactError.IO_ERROR = 5;
ContactError.NOT_SUPPORTED_ERROR = 6;
ContactError.PERMISSION_DENIED_ERROR = 20;

module.exports = ContactError;

});
define('ripple/platform/phonegap/1.0.0/ContactField', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (type, value, pref) {
    return {
        type: type,
        value: value,
        pref: pref || false
    };
};

});
define('ripple/platform/phonegap/1.0.0/ContactFindOptions', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (filter, multiple, updatedSince) {
    return {
        filter: filter || "",
        multiple: multiple || false,
        updatedSince: updatedSince || ""
    };
};

});
define('ripple/platform/phonegap/1.0.0/ContactName', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (formatted, familyName, givenName, middleName, honorificPrefix, honorificSuffix) {
    return {
        formatted: formatted,
        familyName: familyName,
        givenName: givenName,
        middleName: middleName,
        honorificPrefix: honorificPrefix,
        honorificSuffix: honorificSuffix
    };
};

});
define('ripple/platform/phonegap/1.0.0/ContactOrganization', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (pref, type, name, dept, title) {
    return {
        pref: pref || null,
        type: type || null,
        name: name || null,
        department: dept || null,
        title: title || null
    };
};

});
define('ripple/platform/phonegap/1.0.0/DisplayDeviceAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (orientation, brightness, contrast, blanked, dotsPerInchW, dotsPerInchH, physicalWidth, physicalHeight, info) {
    return {
        orientation: orientation,
        brightness: brightness,
        contrast: contrast,
        blanked: blanked,
        dotsPerInchW: dotsPerInchW,
        dotsPerInchH: dotsPerInchH,
        physicalWidth: physicalWidth,
        physicalHeight: physicalHeight,
        info: info
    };
};

});
define('ripple/platform/phonegap/1.0.0/InputDevicesAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, pointingDevices, activePointingDevices, keyboards, activeKeyboards, cameras, activeCameras, microphones, activeMicrophones) {
    return {
        info: info,
        id: id,
        pointingDevices: pointingDevices,
        activePointingDevices: activePointingDevices,
        keyboards: keyboards,
        activeKeyboards: activeKeyboards,
        cameras: cameras,
        activeCameras: activeCameras,
        microphones: microphones,
        activeMicrophones: activeMicrophones
    };

};

});
define('ripple/platform/phonegap/1.0.0/KeyboardAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (type, isHardware, info) {
    return {
        type: type,
        isHardware: isHardware,
        info: info
    };
};

});
define('ripple/platform/phonegap/1.0.0/MicrophoneAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (type, freqRangeLow, freqRangeHigh, info, name, types) {
    return {
        type: type,
        freqRangeLow: freqRangeLow,
        freqRangeHigh: freqRangeHigh,
        info: info,
        name: name,
        types: types
    };
};

});
define('ripple/platform/phonegap/1.0.0/NetworkAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, activeConnections) {
    return {
        info: info,
        id: id,
        activeConnections: activeConnections || []
    };
};

});
define('ripple/platform/phonegap/1.0.0/NetworkStatus', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    NOT_REACHABLE: 0,
    REACHABLE_VIA_CARRIER_DATA_NETWORK: 1,
    REACHABLE_VIA_WIFI_NETWORK: 2
};

});
define('ripple/platform/phonegap/1.0.0/OutputDevicesAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, displayDevices, activeDisplayDevices, printingDevices, activePrintingDevice, brailleDevices, activeBrailleDevice, audioDevices, activeAudioDevices) {
    return {
        info: info,
        id: id,
        displayDevices: displayDevices,
        activeDisplayDevices: activeDisplayDevices,
        printingDevices: printingDevices,
        activePrintingDevice: activePrintingDevice,
        brailleDevices: brailleDevices,
        activeBrailleDevice: activeBrailleDevice,
        audioDevices: audioDevices,
        activeAudioDevices: activeAudioDevices
    };
};

});
define('ripple/platform/phonegap/1.0.0/PhoneGap', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    available: true
};

});
define('ripple/platform/phonegap/1.0.0/PointerAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (type, supportsMultiTouch, info) {
    return {
        type: type,
        supportsMultiTouch: supportsMultiTouch,
        info: info
    };
};

});
define('ripple/platform/phonegap/1.0.0/PowerAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, level, timeRemaining, isBattery, isCharging) {
    return {
        info: info,
        id: id,
        level: level,
        timeRemaining: timeRemaining,
        isBattery: isBattery,
        isCharging: isCharging
    };
};

});
define('ripple/platform/phonegap/1.0.0/PrintingDeviceAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (type, resolution, color, info) {
    return {
        type: type,
        resolution: resolution,
        color: color,
        info: info
    };
};

});
define('ripple/platform/phonegap/1.0.0/SensorAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (value, min, max, normalizedValue) {
    return {
        value: value,
        min: min,
        max: max,
        normalizedValue: normalizedValue
    };
};

});
define('ripple/platform/phonegap/1.0.0/StorageUnitAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, type, isWritable, capacity, availableCapacity, isRemoveable) {
    return {
        info: info,
        id: id,
        type: type,
        isWritable: isWritable,
        capacity: capacity,
        availableCapacity: availableCapacity,
        isRemoveable: isRemoveable
    };
};

});
define('ripple/platform/phonegap/1.0.0/SystemInfoOptions', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (highThreshold, lowThreshold, thresholdTarget, timeout, id) {
    return {
        highThreshold: highThreshold,
        lowThreshold: lowThreshold,
        thresholdTarget: thresholdTarget,
        timeout: timeout,
        id: id
    };
};

});
define('ripple/platform/phonegap/1.0.0/ThermalAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, state) {
    return {
        info: info,
        id: id,
        state: state
    };
};

});
define('ripple/platform/phonegap/1.0.0/VideoCodecAttributes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (info, id, compFormats, containerFormats, hwAccel, profiles, frameTypes, rateTypes) {
    return {
        info: info,
        id: id,
        compFormats: compFormats,
        containerFormats: containerFormats,
        hwAccel: hwAccel,
        profiles: profiles,
        frameTypes: frameTypes,
        rateTypes: rateTypes
    };
};

});
define('ripple/platform/phonegap/1.0.0/accelerometer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 Acceleration = require('ripple/platform/phonegap/1.0.0/Acceleration'),
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    _accelerometerInfo = new Acceleration(),
    _watches = {},
    self;

module.exports = self = {
    getCurrentAcceleration: function (onSuccess, onError) {
        // TODO: implement error call if accelerometer is not available, to be driven by behaviours?

        if (typeof onSuccess === "function") {
            setTimeout(function () {
                // TODO: build facility to trigger onError() from emulator
                // see pivotal item: https://www.pivotaltracker.com/story/show/7040343
                onSuccess(utils.copy(_accelerometerInfo));
            }, 1);
        }

    },

    watchAcceleration: function (accelerometerSuccess, accelerometerError, accelerometerOptions) {
        var watchId = (new Date()).getTime().toString(),
            watchObj = {};


        if (accelerometerOptions &&
                accelerometerOptions.frequency && typeof
                accelerometerOptions.frequency === "number" &&
                accelerometerOptions.frequency === Math.floor(accelerometerOptions.frequency)) {

            watchObj = {
                onSuccess: accelerometerSuccess,
                onError: accelerometerError,
                interval: accelerometerOptions.frequency
            };

            _watches[watchId] = watchObj;

            _watches[watchId].intervalId = setInterval(function () {
                self.getCurrentAcceleration(_watches[watchId].onSuccess, _watches[watchId].onError);
            }, accelerometerOptions.frequency);

        }
        else {
            if (typeof accelerometerError === "function") {
                setTimeout(function () {
                    accelerometerError();
                }, 1);
            }
        }

        return watchId;
    },

    clearWatch: function (watchId) {
        clearInterval(_watches[watchId].intervalId);
    }
};

event.on("AccelerometerInfoChangedEvent", function (accelerometerInfo) {
    _accelerometerInfo.x = accelerometerInfo.accelerationIncludingGravity.x / 9.8;
    _accelerometerInfo.y = accelerometerInfo.accelerationIncludingGravity.y / 9.8;
    _accelerometerInfo.z = accelerometerInfo.accelerationIncludingGravity.z / 9.8;
    _accelerometerInfo.timestamp = (new Date()).getTime();
});

});
define('ripple/platform/phonegap/1.0.0/camera', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    getPicture: function (cameraSuccess, cameraError, cameraOptions) {
        if (cameraError) {
            cameraError.apply(null, ["not implemented"]);
        }
        else {
            throw "not implemented";
        }
    }
};

});
define('ripple/platform/phonegap/1.0.0/compass', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 geo = require('ripple/geo');

function _getHeading() {
    return geo.getPositionInfo().heading;
}

module.exports = {
    getCurrentHeading: function (compassSuccess, compassError, compassOptions) {
        setTimeout(function () {
            compassSuccess(_getHeading());
        }, 1);
    },
    watchHeading: function (compassSuccess, compassError, compassOptions) {
        compassOptions = compassOptions || {};
        return setInterval(function () {
            compassSuccess(_getHeading());
        }, compassOptions.frequency || 100);
    },
    clearWatch: function (watchId) {
        clearInterval(watchId);
    }
};

});
define('ripple/platform/phonegap/1.0.0/contacts', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 Contact = require('./Contact'),
    ContactName = require('./ContactName'),
    ContactError = require('./ContactError'),
    ContactField = require('./ContactField'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    event = require('ripple/event'),
    _defaultContacts = 
    [{
        "id": Math.uuid(undefined, 16),
        "name": new ContactName("Brent Lintner"),
        "displayName": "Brent Lintner",
        "emails": [new ContactField("work", "brent@tinyhippos.com", false)]
    }, {
        "id": Math.uuid(undefined, 16),
        "name": new ContactName("PJ Lowe"),
        "displayName": "PJ Lowe",
        "emails": [new ContactField("work", "pj@tinyhippos.com", false)]
    }, {
        "id": Math.uuid(undefined, 16),
        "name": new ContactName("Dan Silivestru"),
        "displayName": "Dan Silivestru",
        "emails": [new ContactField("work", "dan@tinyhippos.com", false)]
    }, {
        "id": Math.uuid(undefined, 16),
        "name": new ContactName("Gord Tanner"),
        "displayName": "Gord Tanner",
        "emails": [new ContactField("work", "gord@tinyhippos.com", true)]
    }, {
        "id": Math.uuid(undefined, 16),
        "name": new ContactName("Mark McArdle"),
        "displayName": "Mark McArdle",
        "emails": [new ContactField("work", "mark@tinyhippos.com", false)]
    }],
    self;

function _error(callback, code, msg) {
    var e = new ContactError();
    e.code = code;
    e.message = msg;
    window.setTimeout(function () {
        callback(e);
    }, 1);
}


function _getContacts() {
    return db.retrieveObject("phonegap-contacts") || 
        _defaultContacts.map(function (person) {
            var contact = new Contact();
            contact.updated = new Date();
            utils.forEach(person, function (value, prop) {
                contact[prop] = value;
            });

            return contact;
        });
}

function _saveContacts(contacts) {
    db.saveObject("phonegap-contacts", contacts);
}

function _filtered(compare, options) {
    // this could be done a lot better..
    var found = false;
    if (!options.filter || options.filter === "") {
        found = true;
    } else if (typeof compare === "string" &&
              compare.match(new RegExp(".*" + options.filter + ".*", "i"))) {
        found = true;
    } else if (typeof compare === "object" || compare instanceof Array) {
        utils.forEach(compare, function (value) {
            if (!found) {
                found = _filtered(value, options);
            }
        });
    }
    return found;
}

event.on("phonegap-contact-save", function (contactProperties, success, error) {
    var contacts = _getContacts(),
        existsIndex = contacts.reduce(function (result, value, index) {
            return value.id === contactProperties.id ? index : result;
        }, -1),
        contact = existsIndex >= 0 ? contacts[existsIndex] : new Contact();

    utils.mixin(contactProperties, contact);
    if (existsIndex < 0) {
        contacts.push(contact);
    }
    _saveContacts(contacts);
    success(contact);
});

event.on("phonegap-contact-remove", function (id, success, error) {
    if (!id) {
        _error(error, ContactError.NOT_FOUND_ERROR, "id is falsy (" + id + ")");
    } else {
        var contacts = _getContacts(),
            toDelete = contacts.reduce(function (result, current, index) {
                return current.id === id ? index : result;
            }, -1);

        if (toDelete >= 0) {
            contacts.splice(toDelete, 1);
            _saveContacts(contacts);
            success();
        } else {
            _error(error, ContactError.NOT_FOUND_ERROR, "could not find contact with id (" + id + ")");
        }
    }
});

self = module.exports = {
    create: function (properties) {
        var contact = new Contact();
        utils.forEach(properties, function (value, key) {
            contact[key] = value;
        });
        return contact;
    },
    find: function (fields, success, error, options) {
        var foundContacts = [],
            tempContact = self.create(),
            contacts = _getContacts(),
            errorFlag = false;

        options = options || {};

        // not a fan of error handling at the moment
        if (!fields || !("forEach" in fields)) {
            errorFlag = true;
            _error(error, ContactError.INVALID_ARGUMENT_ERROR, "missing contact fields array");
            return;
        }

        // handle special case of ["*"] to return all fields
        if (fields.length === 1 && fields[0] === "*") {
            fields = utils.map(tempContact, function (v, k) {
                return k;
            });
        }

        fields.forEach(function (prop) {
            if (!(tempContact.hasOwnProperty(prop))) {
                errorFlag = true;
                _error(error, ContactError.INVALID_ARGUMENT_ERROR, "invalid contact field (" + prop + ")");
            }
        });

        if (typeof success !== "function" && !errorFlag) {
            errorFlag = true;
            _error(error, ContactError.INVALID_ARGUMENT_ERROR, "missing success callback");
        }

        if (errorFlag) {
            return;
        }

        if (fields.length > 0) {
            contacts.forEach(function (contact, index) {
                var newContact = utils.copy(contact);

                if (options && (!_filtered(contact, options) ||
                        options.updatedSince && contact.updated && contact.updated.getTime() < options.updatedSince.getTime())) {
                    return;
                }

                utils.forEach(newContact, function (value, prop) {
                    if (typeof newContact[prop] !== "function" && prop !== "id" &&
                        !fields.some(function (field) {
                            return field === prop;
                        })) {
                        delete newContact[prop];
                    }
                });

                foundContacts.push(newContact);
            });
        }

        window.setTimeout(function () {
            // TODO: don't loop over entire db just to slice the array
            if (options.multiple === false) {
                foundContacts = foundContacts.splice(0, 1);
            }
            success(foundContacts);
        }, 1);
    }
};

});
define('ripple/platform/phonegap/1.0.0/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self = {},
    event = require('ripple/event'),
    devices = require('ripple/devices');


event.on("HardwareKey", function (key) {
    event.trigger("HardwareKeyDefault", [key]);
});

_self.__defineGetter__("name", function () {
    return devices.getCurrentDevice().name;
});

_self.__defineGetter__("platform", function () {
    return devices.getCurrentDevice().osName;
});

_self.__defineGetter__("uuid", function () {
    return devices.getCurrentDevice().uuid;
});

_self.__defineGetter__("version", function () {
    return devices.getCurrentDevice().osVersion;
});

_self.phonegap = "placeholder string";

module.exports = _self;

});
define('ripple/platform/phonegap/1.0.0/map', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    show: function () {
        throw "not implemented";
    }
};

});
define('ripple/platform/phonegap/1.0.0/navigator', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 nav = require('ripple/platform/w3c/1.0/navigator'),
    event = require('ripple/event'),
    _console = require('ripple/console'),
    utils = require('ripple/utils'),
    emulatorBridge = require('ripple/emulatorBridge'),
    _self = {};

event.on("TinyHipposLoaded", function () {
    var doc = emulatorBridge.document(),
        evt = doc.createEvent("Events");
    evt.initEvent("deviceready", true, true);
    doc.dispatchEvent(evt);
    _console.log("fired deviceready event!");
});

utils.mixin(nav, _self);

module.exports = _self;

});
define('ripple/platform/phonegap/1.0.0/network', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 deviceSettings = require('ripple/deviceSettings'),
    _self = {
        connection: {
        }
    };

_self.connection.__defineGetter__("type", function () {
    return deviceSettings.retrieve("NetworkStatus.connectionType");
});

module.exports = _self;

});
define('ripple/platform/phonegap/1.0.0/notification', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 notifications = require('ripple/notifications'),
    constants = require('ripple/constants'),
    _console = require('ripple/console'),
    ui = require('ripple/ui'),
    goodVibrations = require('ripple/ui/plugins/goodVibrations');

module.exports = {
    alert: function (message, title, buttonName) {
        notifications.openNotification("normal", message);
    },

    beep: function (times) {
        for (var i = times; i > 0; i--) {
            _console.log("beep!");
        }
        notifications.openNotification("normal", "BEEP x " + times);
    },

    vibrate: function (milliseconds) {
        milliseconds = milliseconds || 500;
        goodVibrations.vibrateDevice(milliseconds);
    }
};

});
define('ripple/platform/phonegap/1.0.0/orientation', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    currentOrientation: null,
    getCurrentOrientation: function (onSuccess, onFail) {
        throw "not implemented";
    },
    watchOrientation: function () {
        throw "not implemented";
    }
};

});
define('ripple/platform/phonegap/1.0.0/service', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
// for form, but could probably just delete
module.exports = {};

});
define('ripple/platform/phonegap/1.0.0/sms', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    send: function () {
        throw "not implemented";
    }
};

});
define('ripple/platform/phonegap/1.0.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (configValidationObject) {
        var valid = true;
        valid = !((!configValidationObject.widget.validationResult[0].attributes.xmlns.valid) ||
            (!configValidationObject.widget.validationResult[0].attributes["xmlns:gap"].valid));

        return valid;
    },
    extractInfo: function (configValidationObject) {
        if (!configValidationObject) {
            return null;
        }

        var widgetInfo = {};

        widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
        widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
        widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xmlns:gap": {
                    attributeName: "xmlns:gap",
                    required: true,
                    type: "list",
                    listValues: ["http://phonegap.com/ns/1.0"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                },
                dir: {
                    attributeName: "dir",
                    required: false,
                    type: "list",
                    listValues: ["ltr", "rtl", "lro", "rlo"]
                },
                id: {
                    attributeName: "id",
                    required: false,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    required: false,
                    type: "string"
                },
                height: {
                    attributeName: "height",
                    required: false,
                    type: "integer"
                },
                width: {
                    attributeName: "width",
                    required: false,
                    type: "integer"
                },
                viewmodes: {
                    attributeName: "viewmodes",
                    required: false,
                    type: "list",
                    listValues: ["floating", "fullscreen"]
                }
            },
            children: {
                name: {
                    nodeName: "name",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "short": {
                            attributeName: "short",
                            type: "string",
                            required: false
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 1,
                    type: "string",
                    attributes: {
                        email: {
                            attributeName: "email",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.EMAIL
                        },
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 1,
                    type: "string",
                    attributes: {
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        src: {
                            attributeName: "src",
                            type: "string",
                            required: true
                        },
                        height: {
                            attributeName: "height",
                            required: false,
                            type: "integer"
                        },
                        width: {
                            attributeName: "width",
                            required: false,
                            type: "integer"
                        }
                    }
                },
                content: {
                    nodeName: "content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        src: {
                            attributeName: "src",
                            type: "string",
                            required: true
                        },
                        encoding: {
                            attributeName: "encoding",
                            type: "string",
                            required: false
                        },
                        type: {
                            attributeName: "type",
                            type: "string",
                            required: false
                        }
                    }
                },
                feature: {
                    nodeName: "feature",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        name: {
                            attributeName: "name",
                            type: "list",
                            required: true,
                            listValues: ["http://api.phonegap.com/1.0/accelerometer", "http://api.phonegap.com/1.0/camera",
                                "http://api.phonegap.com/1.0/compass", "http://api.phonegap.com/1.0/contacts", "http://api.phonegap.com/1.0/device",
                                "http://api.phonegap.com/1.0/events", "http://api.phonegap.com/1.0/file", "http://api.phonegap.com/1.0/geolocation",
                                "http://api.phonegap.com/1.0/media", "http://api.phonegap.com/1.0/network", "http://api.phonegap.com/1.0/notification",
                                "http://api.phonegap.com/1.0/storage"]
                        },
                        required: {
                            attributeName: "required",
                            type: "boolean",
                            required: false
                        }
                    }
                },
                preference: {
                    nodeName: "preference",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        name: {
                            attributeName: "name",
                            type: "string",
                            required: true
                        },
                        value: {
                            type: "string",
                            attributeName: "value",
                            required: false
                        },
                        readonly: {
                            attributeName: "readonly",
                            type: "boolean",
                            required: false
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/phonegap/1.0.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event');

module.exports = {
    "NetworkStatus": {
        "connectionType": {
            "name": "Connection Type",
            "control": {
                "type": "select",
                "value": "ethernet"
            },
            "options": {
                "unknown": "UNKNOWN",
                "ethernet": "ETHERNET",
                "wifi": "WIFI",
                "2g": "CELL_2G",
                "3g": "CELL_3G",
                "4g": "CELL_4G",
                "none": "none"
            },
            "callback": function (setting) {
                var connected = setting !== "none";
                require('ripple/bus').send("network", connected);
            }
        },
        "lag": {
            "name": "Lag the network",
            "control": {
                type: "checkbox",
                value: false
            },
            "callback": function (setting) {
                require('ripple/bus').send("lag", setting);
            }
        },
    }
};

});
define('ripple/platform/phonegap/1.0.0/spec/events', function (require, exports, module) {
function _fires(name, data) {
    return function () {
        var doc = require("ripple/emulatorBridge").document(),
            evt = doc.createEvent("Events");

        evt.initEvent(name, true, false);
        doc.dispatchEvent(evt);
    };
}

module.exports = {
    "deviceready": {
        callback: _fires("deviceready")
    },
    "backbutton": {
        callback: _fires("backbutton")
    },
    "menubutton": {
        callback: _fires("menubutton")
    },
    "pause": {
        callback: _fires("pause")
    },
    "resume": {
        callback: _fires("resume")
    },
    "searchbutton": {
        callback: _fires("searchbutton")
    },
    "online": {
        callback: _fires("online")
    },
    "offline": {
        callback: _fires("offline")
    }
};

});
define('ripple/platform/phonegap/1.0.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "accelerometer",
        "deviceSettings",
        "geoView",
        "widgetConfig",
        "platformEvents"
    ]
};

});
define('ripple/platform/phonegap/1.0.0/spec', function (require, exports, module) {
module.exports = {
    id: "phonegap",
    version: "1.0.0",
    name: "PhoneGap",
    type: "platform",

    persistencePrefix: "phonegap-",

    config: require('ripple/platform/phonegap/1.0.0/spec/config'),
    device: require('ripple/platform/phonegap/1.0.0/spec/device'),
    ui: require('ripple/platform/phonegap/1.0.0/spec/ui'),
    events: require('ripple/platform/phonegap/1.0.0/spec/events'),

    initialize: function () { },

    objects: {
        PhoneGap: {
            path: "phonegap/1.0.0/PhoneGap"
        },
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        Acceleration: {
            path: "phonegap/1.0.0/Acceleration"
        },
        navigator: {
            path: "phonegap/1.0.0/navigator",
            children: {
                accelerometer: {
                    path: "phonegap/1.0.0/accelerometer"
                },
                geolocation: {
                    path: "w3c/1.0/geolocation"
                },
                notification: {
                    path: "phonegap/1.0.0/notification"
                },
                contacts: {
                    path: "phonegap/1.0.0/contacts"
                },
                network: {
                    path: "phonegap/1.0.0/network"
                },
                camera: {
                    path: "phonegap/1.0.0/camera"
                },
                sms: {
                    path: "phonegap/1.0.0/sms"
                },
                telephony: {
                    path: "phonegap/1.0.0/telephony"
                },
                map: {
                    path: "phonegap/1.0.0/map"
                },
                orientation: {
                    path: "phonegap/1.0.0/orientation"
                },
                system: {
                    path: "phonegap/1.0.0/system"
                },
                compass: {
                    path: "phonegap/1.0.0/compass"
                }
            }
        },
        ContactError: {
            path: "phonegap/1.0.0/ContactError"
        },
        Contact: {
            path: "phonegap/1.0.0/Contact"
        },
        ContactName: {
            path: "phonegap/1.0.0/ContactName"
        },
        ContactAccount: {
            path: "phonegap/1.0.0/ContactAccount"
        },
        ContactAddress: {
            path: "phonegap/1.0.0/ContactAddress"
        },
        ContactOrganization: {
            path: "phonegap/1.0.0/ContactOrganization"
        },
        ContactFindOptions: {
            path: "phonegap/1.0.0/ContactFindOptions"
        },
        ContactField: {
            path: "phonegap/1.0.0/ContactField"
        },
        NetworkStatus: {
            path: "phonegap/1.0.0/NetworkStatus"
        },
        device: {
            path: "phonegap/1.0.0/device"
        },
        SystemInfoOptions: {
            path: "phonegap/1.0.0/SystemInfoOptions"
        },
        PowerAttributes: {
            path: "phonegap/1.0.0/PowerAttributes"
        },
        CPUAttributes: {
            path: "phonegap/1.0.0/CPUAttributes"
        },
        ThermalAttributes: {
            path: "phonegap/1.0.0/ThermalAttributes"
        },
        NetworkAttributes: {
            path: "phonegap/1.0.0/NetworkAttributes"
        },
        Connection: {
            path: "phonegap/1.0.0/Connection"
        },
        ConnectionAttributes: {
            path: "phonegap/1.0.0/ConnectionAttributes"
        },
        SensorAttributes: {
            path: "phonegap/1.0.0/SensorAttributes"
        },
        AVCodecsAttributes: {
            path: "phonegap/1.0.0/AVCodecsAttributes"
        },
        AudioCodecAttributes: {
            path: "phonegap/1.0.0/AudioCodecAttributes"
        },
        VideoCodecAttributes: {
            path: "phonegap/1.0.0/VideoCodecAttributes"
        },
        StorageUnitAttributes: {
            path: "phonegap/1.0.0/StorageUnitAttributes"
        },
        InputDevicesAttributes: {
            path: "phonegap/1.0.0/InputDevicesAttributes"
        },
        OutputDevicesAttributes: {
            path: "phonegap/1.0.0/OutputDevicesAttributes"
        },
        DisplayDeviceAttributes: {
            path: "phonegap/1.0.0/DisplayDeviceAttributes"
        },
        AudioDeviceAttributes: {
            path: "phonegap/1.0.0/AudioDeviceAttributes"
        },
        PrintingDeviceAttributes: {
            path: "phonegap/1.0.0/PrintingDeviceAttributes"
        },
        BrailleDeviceAttributes: {
            path: "phonegap/1.0.0/BrailleDeviceAttributes"
        },
        PointerAttributes: {
            path: "phonegap/1.0.0/PointerAttributes"
        },
        KeyboardAttributes: {
            path: "phonegap/1.0.0/KeyboardAttributes"
        },
        CameraAttributes: {
            path: "phonegap/1.0.0/CameraAttributes"
        },
        MicrophoneAttributes: {
            path: "phonegap/1.0.0/MicrophoneAttributes"
        }
    }

};

});
define('ripple/platform/phonegap/1.0.0/system', function (require, exports, module) {
module.exports = {
    get: function () {
        throw "not implemented";
    },
    has: function () {
        throw "not implemented";
    },
    monitor: function () {
        throw "not implemented";
    }
};

});
define('ripple/platform/phonegap/1.0.0/telephony', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    send: function () {
        throw "not implemented";
    }
};

});
define('ripple/platform/spec', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    //"phonegap": {"1.0.0": require('ripple/platform/phonegap/1.0.0/spec')},
    "tizen": {"2.0": require('ripple/platform/tizen/2.0/spec')},
    //"ivi": {"3.0": require('ripple/platform/ivi/3.0/spec')},
    "wearable": {"2.0": require('ripple/platform/wearable/2.0/spec')},
    //"tv": {"1.0": require('ripple/platform/tv/1.0/spec')},
    //"cordova": {"2.0.0": require('ripple/platform/cordova/2.0.0/spec')},
    //"webworks.bb10": {"1.0.0": require('ripple/platform/webworks.bb10/1.0.0/spec')},
    //"webworks.handset": {"2.0.0": require('ripple/platform/webworks.handset/2.0.0/spec')},
    //"webworks.tablet": {"2.0.0": require('ripple/platform/webworks.tablet/2.0.0/spec')},
    //"web": {"default": require('ripple/platform/web/default/spec')},

    "get": function (name, version) {
        var platform = module.exports[name] || {};
        return (platform[version] || platform[Object.keys(platform)[0]]);
    }
};

});
define('ripple/platform/tizen/2.0/AccountBase', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (appId, userName, displayName, service) {
    var _self,
        _id = Math.uuid(null, 16);

    _self = {
        appId : appId || "",
        userName : userName || "",
        displayName : displayName || "",
        service : service || {}
    };

    _self.__defineGetter__("id", function () {
        return _id;
    });

    return _self;
};

});
define('ripple/platform/tizen/2.0/AccountService', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (serviceName, serviceType, tag, displayName, icon, settings) {
    var _self,
        _id = Math.uuid(null, 16);

    _self = {
        serviceName : serviceName || "",
        serviceType : serviceType || "",
        displayName : displayName || null,
        icon : icon || null,
        settings : settings || null,
        tag : tag || []
    };

    _self.__defineGetter__("id", function () {
        return _id;
    });

    return _self;
};

});
define('ripple/platform/tizen/2.0/AlarmAbsolute', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 AlarmBase = require('ripple/platform/tizen/2.0/AlarmBase'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    _byDayValue = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"],
    PERIOD_WEEK = (7 * 24 * 60 * 60), MILLI_SECOND = 1000,
    AlarmAbsolute;

AlarmAbsolute = function () {
    var alarm, period = null, daysOfTheWeek = [], ascDays = [], voc, date;

    function getScheduleDateByPeriod(current, date, period) {
        var diff = period * MILLI_SECOND,
            triggerDate = new Date(date);

        while (current > (triggerDate - MILLI_SECOND)) { // In advance 1s - MILLI_SECOND
            triggerDate.setTime(triggerDate.getTime() + diff);
        }
        return triggerDate;
    }

    function getSchedulteDateByDay(current, triggerTime, startDay, endDay) {
        startDay = (7 + (endDay - startDay)) % 7;
        current.setHours(triggerTime.getHours());
        current.setMinutes(triggerTime.getMinutes());
        current.setSeconds(triggerTime.getSeconds());
        current.setMilliseconds(triggerTime.getMilliseconds());
        current.setDate(current.getDate() + startDay);
        return current;
    }

    function getAscDays() { // Get asc order array
        for (var i in daysOfTheWeek) {
            ascDays.push(_byDayValue.lastIndexOf(daysOfTheWeek[i]));
        }
        return ascDays.sort();
    }

    /*
     * Return
     *     true:  A is bigger than B
     *     false: otherwise
     */
    function compareTime(current, triggerTime) {
        var diff = current.getHours() - triggerTime.getHours();
        if (diff !== 0)
            return (diff > 0);

        diff = current.getMinutes() - triggerTime.getMinutes();
        if (diff !== 0)
            return (diff > 0);

        diff = current.getSeconds() - triggerTime.getSeconds();
        if (diff < -1) // Delay 1s
            return false;

        return true;
    }

    alarm = new AlarmBase(this);

    voc = [
        function (_date, _daysOfTheWeek) {
            date = _date;
            daysOfTheWeek = _daysOfTheWeek;
            period = PERIOD_WEEK;
        },
        function (_date, _period) {
            date = _date;
            period = _period;
        },
        function (_date) {
            date = _date;
        }
    ];

    t.AlarmAbsolute(arguments, this, voc);

    this.getNextScheduledDate = function () {
        var current = new Date(),
            diff, isPass, today, total, i, nextDate;

        diff = current - date;
        if (diff < -1000) // Advance 1s
            return date; // Before first trigger, return date

        if (period === null)
            return null;

        if (period !== PERIOD_WEEK)
            return getScheduleDateByPeriod(current, date, period); // Repeat by period

        today = current.getDay(); // 0~6
        ascDays = getAscDays();
        total = ascDays.length;

        if ((ascDays[0] <= today) && (today <= ascDays[total - 1])) { // Today out of ascDays
            for (i in ascDays) { // Today in ascDays
                if (ascDays[i] < today) {
                    continue;
                } else if (ascDays[i] > today) {
                    nextDate = ascDays[i];
                    break;
                } else {
                    isPass = compareTime(current, date); // Is triggerTime pass
                    if (isPass) {
                        nextDate = ascDays[(i < total - 1) ? (parseInt(i, 10) + 1) : 0];
                    } else {
                        nextDate = today;
                    }
                    break;
                }
            }
        } else {
            nextDate = ascDays[0];
        }

        return getSchedulteDateByDay(current, date, today, nextDate);
    };

    this.__defineGetter__("date", function () {
        return new Date(date);
    });

    this.__defineGetter__("period", function () {
        return period;
    });

    this.__defineGetter__("daysOfTheWeek", function () {
        return daysOfTheWeek;
    });
};

module.exports = AlarmAbsolute;

});
define('ripple/platform/tizen/2.0/AlarmBase', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (self) {
    self = self || this;

    self.__defineGetter__("id", function () {
        return null;
    });
};

});
define('ripple/platform/tizen/2.0/AlarmRelative', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 AlarmBase = require('ripple/platform/tizen/2.0/AlarmBase'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    AlarmRelative;

AlarmRelative = function (delay, period) {
    var alarm, date;

    t.AlarmRelative(arguments, this);

    alarm  = new AlarmBase(this);
    period = period || null;
    date   = new Date(); // Alarm settime

    this.getRemainingSeconds = function () {
        var current, diff, triggerDate, MILLI_SECOND = 1000;
        current     = new Date();
        triggerDate = new Date(delay * MILLI_SECOND + date.getTime()); // First triggerDate
        diff        = Math.round((triggerDate - current) / MILLI_SECOND);

        if (diff > 0) // Before first trigger
            return diff;

        if (period === null)
            return null; // Alarm is expired

        while (current - triggerDate >= 0) { // Trigger repeatly
            triggerDate = new Date(period * MILLI_SECOND + triggerDate.getTime());
        }
        diff = Math.round(((triggerDate - current) / MILLI_SECOND));
        return diff;
    };

    this.__defineGetter__("delay", function () {
        return delay;
    });

    this.__defineGetter__("period", function () {
        return period;
    });
};

module.exports = AlarmRelative;

});
define('ripple/platform/tizen/2.0/ApplicationControl', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ApplicationControlData = require('ripple/platform/tizen/2.0/ApplicationControlData');

var ApplicationControl = function (operation, uri, mime, category, data) {
    var applicationControl = {}, i;

    t.ApplicationControl(arguments, this);

    applicationControl.operation = operation;
    applicationControl.uri       = uri || null;
    applicationControl.mime      = mime || null;
    applicationControl.category  = category || null;
    applicationControl.data      = [];

    if (data) {
        for (i in data) {
            applicationControl.data[i] = new ApplicationControlData(data[i].key,
                    data[i].value);
        }
    }

    this.__defineGetter__("operation", function () {
        return applicationControl.operation;
    });
    this.__defineSetter__("operation", function (val) {
        try {
            applicationControl.operation = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("uri", function () {
        return applicationControl.uri;
    });
    this.__defineSetter__("uri", function (val) {
        try {
            applicationControl.uri = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("mime", function () {
        return applicationControl.mime;
    });
    this.__defineSetter__("mime", function (val) {
        try {
            applicationControl.mime = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("category", function () {
        return applicationControl.category;
    });
    this.__defineSetter__("category", function (val) {
        try {
            applicationControl.category = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("data", function () {
        return applicationControl.data;
    });
    this.__defineSetter__("data", function (val) {
        var i;

        try {
            t.ApplicationControlData(val, "[]");
            for (i in val) {
                applicationControl.data[i] = new ApplicationControlData(
                        val[i].key, val[i].value);
            }
        } catch (e) {
        }
    });
};

module.exports = ApplicationControl;

});
define('ripple/platform/tizen/2.0/ApplicationControlData', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ApplicationControlData;

ApplicationControlData = function (key, value) {
    var applicationControlData = {};

    t.ApplicationControlData(arguments, this);

    applicationControlData.key   = key;
    applicationControlData.value = value;

    this.__defineGetter__("key", function () {
        return applicationControlData.key;
    });
    this.__defineSetter__("key", function (val) {
        try {
            applicationControlData.key = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("value", function () {
        return applicationControlData.value;
    });
    this.__defineSetter__("value", function (val) {
        try {
            applicationControlData.value = t.DOMString(val, '[]');
        } catch (e) {
        }
    });
};

module.exports = ApplicationControlData;

});
define('ripple/platform/tizen/2.0/AttributeFilter', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    AttributeFilter;

AttributeFilter = function (attributeName, matchFlag, matchValue) {
    var attributeFilter = {};

    t.AttributeFilter(arguments, this);

    attributeFilter.attributeName = attributeName;
    attributeFilter.matchFlag     = matchFlag || "EXACTLY";
    attributeFilter.matchValue    = (matchFlag === "EXISTS") ? null :
            matchValue || null;

    this.__defineGetter__("attributeName", function () {
        return attributeFilter.attributeName;
    });
    this.__defineSetter__("attributeName", function (val) {
        try {
            attributeFilter.attributeName = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("matchFlag", function () {
        return attributeFilter.matchFlag;
    });
    this.__defineSetter__("matchFlag", function (val) {
        try {
            attributeFilter.matchFlag = t.FilterMatchFlag(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("matchValue", function () {
        return attributeFilter.matchValue;
    });
    this.__defineSetter__("matchValue", function (val) {
        try {
            if (attributeFilter.matchFlag === "EXISTS") {
                return;
            }
            attributeFilter.matchValue = t.any(val, "?");
        } catch (e) {
        }
    });
};

module.exports = AttributeFilter;

});
define('ripple/platform/tizen/2.0/AttributeRangeFilter', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    AttributeRangeFilter;

AttributeRangeFilter = function (attributeName, initialValue, endValue) {
    var attributeRangeFilter = {};

    t.AttributeRangeFilter(arguments, this);

    this.__defineGetter__("attributeName", function () {
        return attributeRangeFilter.attributeName;
    });
    this.__defineSetter__("attributeName", function (val) {
        try {
            attributeRangeFilter.attributeName = t.DOMString(val);
        } catch (e) {
        }
    });

    attributeRangeFilter.attributeName = attributeName;

    this.initialValue = initialValue || null;
    this.endValue     = endValue || null;
};

module.exports = AttributeRangeFilter;

});
define('ripple/platform/tizen/2.0/BluetoothClass', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    BluetoothClass,
    _security;

BluetoothClass = function (prop, metaData) {
    var bluetoothClass = {};

    _security = metaData;

    bluetoothClass.major    = prop.major || 0;
    bluetoothClass.minor    = prop.minor || 0;
    bluetoothClass.services = prop.services || [];

    this.__defineGetter__("major", function () {
        return bluetoothClass.major;
    });

    this.__defineGetter__("minor", function () {
        return bluetoothClass.minor;
    });

    this.__defineGetter__("services", function () {
        return bluetoothClass.services;
    });

    bluetoothClass.services.forEach(function (service, i) {
        bluetoothClass.services.__defineGetter__(i, function () {
            return service;
        });
    });

    this.hasService = function (service) {
        if (!_security.hasService) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothClass("hasService", arguments);

        return (bluetoothClass.services.join(",").indexOf(service) !== -1);
    };
};

module.exports = BluetoothClass;

});
define('ripple/platform/tizen/2.0/BluetoothClassDeviceMajor', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 BluetoothClassDeviceMajor = function () {
    this.__defineGetter__("MISC", function () {
        return 0x00;
    });

    this.__defineGetter__("COMPUTER", function () {
        return 0x01;
    });

    this.__defineGetter__("PHONE", function () {
        return 0x02;
    });

    this.__defineGetter__("NETWORK", function () {
        return 0x03;
    });

    this.__defineGetter__("AUDIO_VIDEO", function () {
        return 0x04;
    });

    this.__defineGetter__("PERIPHERAL", function () {
        return 0x05;
    });

    this.__defineGetter__("IMAGING", function () {
        return 0x06;
    });

    this.__defineGetter__("WEARABLE", function () {
        return 0x07;
    });

    this.__defineGetter__("TOY", function () {
        return 0x08;
    });

    this.__defineGetter__("HEALTH", function () {
        return 0x09;
    });

    this.__defineGetter__("UNCATEGORIZED", function () {
        return 0x1F;
    });
};

module.exports = BluetoothClassDeviceMajor;

});
define('ripple/platform/tizen/2.0/BluetoothClassDeviceMinor', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 BluetoothClassDeviceMinor = function () {
    // COMPUTER
    this.__defineGetter__("COMPUTER_UNCATEGORIZED", function () {
        return 0x00;
    });

    this.__defineGetter__("COMPUTER_DESKTOP", function () {
        return 0x01;
    });

    this.__defineGetter__("COMPUTER_SERVER", function () {
        return 0x02;
    });

    this.__defineGetter__("COMPUTER_LAPTOP", function () {
        return 0x03;
    });

    this.__defineGetter__("COMPUTER_HANDHELD_PC_OR_PDA", function () {
        return 0x04;
    });

    this.__defineGetter__("COMPUTER_PALM_PC_OR_PDA", function () {
        return 0x05;
    });

    this.__defineGetter__("COMPUTER_WEARABLE", function () {
        return 0x06;
    });

    // PHONE
    this.__defineGetter__("PHONE_UNCATEGORIZED", function () {
        return 0x00;
    });

    this.__defineGetter__("PHONE_CELLULAR", function () {
        return 0x01;
    });

    this.__defineGetter__("PHONE_CORDLESS", function () {
        return 0x02;
    });

    this.__defineGetter__("PHONE_SMARTPHONE", function () {
        return 0x03;
    });

    this.__defineGetter__("PHONE_MODEM_OR_GATEWAY", function () {
        return 0x04;
    });

    this.__defineGetter__("PHONE_ISDN", function () {
        return 0x05;
    });

    // AUDIO_VIDEO
    this.__defineGetter__("AV_UNRECOGNIZED", function () {
        return 0x00;
    });

    this.__defineGetter__("AV_WEARABLE_HEADSET", function () {
        return 0x01;
    });

    this.__defineGetter__("AV_HANDSFREE", function () {
        return 0x02;
    });

    this.__defineGetter__("AV_MICROPHONE", function () {
        return 0x04;
    });

    this.__defineGetter__("AV_LOUDSPEAKER", function () {
        return 0x05;
    });

    this.__defineGetter__("AV_HEADPHONES", function () {
        return 0x06;
    });

    this.__defineGetter__("AV_PORTABLE_AUDIO", function () {
        return 0x07;
    });

    this.__defineGetter__("AV_CAR_AUDIO", function () {
        return 0x08;
    });

    this.__defineGetter__("AV_SETTOP_BOX", function () {
        return 0x09;
    });

    this.__defineGetter__("AV_HIFI", function () {
        return 0x0a;
    });

    this.__defineGetter__("AV_VCR", function () {
        return 0x0b;
    });

    this.__defineGetter__("AV_VIDEO_CAMERA", function () {
        return 0x0c;
    });

    this.__defineGetter__("AV_CAMCORDER", function () {
        return 0x0d;
    });

    this.__defineGetter__("AV_MONITOR", function () {
        return 0x0e;
    });

    this.__defineGetter__("AV_DISPLAY_AND_LOUDSPEAKER", function () {
        return 0x0f;
    });

    this.__defineGetter__("AV_VIDEO_CONFERENCING", function () {
        return 0x10;
    });

    this.__defineGetter__("AV_GAMING_TOY", function () {
        return 0x12;
    });

    // PERIPHERAL
    this.__defineGetter__("PERIPHERAL_UNCATEGORIZED", function () {
        return 0;
    });

    this.__defineGetter__("PERIPHERAL_KEYBOARD", function () {
        return 0x10;
    });

    this.__defineGetter__("PERIPHERAL_POINTING_DEVICE", function () {
        return 0x20;
    });

    this.__defineGetter__("PERIPHERAL_KEYBOARD_AND_POINTING_DEVICE", function () {
        return 0x30;
    });

    this.__defineGetter__("PERIPHERAL_JOYSTICK", function () {
        return 0x01;
    });

    this.__defineGetter__("PERIPHERAL_GAMEPAD", function () {
        return 0x02;
    });

    this.__defineGetter__("PERIPHERAL_REMOTE_CONTROL", function () {
        return 0x03;
    });

    this.__defineGetter__("PERIPHERAL_SENSING_DEVICE", function () {
        return 0x04;
    });

    this.__defineGetter__("PERIPHERAL_DEGITIZER_TABLET", function () {
        return 0x05;
    });

    this.__defineGetter__("PERIPHERAL_CARD_READER", function () {
        return 0x06;
    });

    this.__defineGetter__("PERIPHERAL_DIGITAL_PEN", function () {
        return 0x07;
    });

    this.__defineGetter__("PERIPHERAL_HANDHELD_SCANNER", function () {
        return 0x08;
    });

    this.__defineGetter__("PERIPHERAL_HANDHELD_INPUT_DEVICE", function () {
        return 0x09;
    });

    // IMAGING
    this.__defineGetter__("IMAGING_UNCATEGORIZED", function () {
        return 0x00;
    });

    this.__defineGetter__("IMAGING_DISPLAY", function () {
        return 0x04;
    });

    this.__defineGetter__("IMAGING_CAMERA", function () {
        return 0x08;
    });

    this.__defineGetter__("IMAGING_SCANNER", function () {
        return 0x10;
    });

    this.__defineGetter__("IMAGING_PRINTER", function () {
        return 0x20;
    });

    // WEARABLE
    this.__defineGetter__("WEARABLE_WRITST_WATCH", function () {
        return 0x01;
    });

    this.__defineGetter__("WEARABLE_PAGER", function () {
        return 0x02;
    });

    this.__defineGetter__("WEARABLE_JACKET", function () {
        return 0x03;
    });

    this.__defineGetter__("WEARABLE_HELMET", function () {
        return 0x04;
    });

    this.__defineGetter__("WEARABLE_GLASSES", function () {
        return 0x05;
    });

    // TOY
    this.__defineGetter__("TOY_ROBOT", function () {
        return 0x01;
    });

    this.__defineGetter__("TOY_VEHICLE", function () {
        return 0x02;
    });

    this.__defineGetter__("TOY_DOLL", function () {
        return 0x03;
    });

    this.__defineGetter__("TOY_CONTROLLER", function () {
        return 0x04;
    });

    this.__defineGetter__("TOY_GAME", function () {
        return 0x05;
    });

    // HEALTH
    this.__defineGetter__("HEALTH_UNDEFINED", function () {
        return 0x00;
    });

    this.__defineGetter__("HEALTH_BLOOD_PRESSURE_MONITOR", function () {
        return 0x01;
    });

    this.__defineGetter__("HEALTH_THERMOMETER", function () {
        return 0x02;
    });

    this.__defineGetter__("HEALTH_WEIGHING_SCALE", function () {
        return 0x03;
    });

    this.__defineGetter__("HEALTH_GLUCOSE_METER", function () {
        return 0x04;
    });

    this.__defineGetter__("HEALTH_PULSE_OXIMETER", function () {
        return 0x05;
    });

    this.__defineGetter__("HEALTH_PULSE_RATE_MONITOR", function () {
        return 0x06;
    });

    this.__defineGetter__("HEALTH_DATA_DISPLAY", function () {
        return 0x07;
    });

    this.__defineGetter__("HEALTH_STEP_COUNTER", function () {
        return 0x08;
    });

    this.__defineGetter__("HEALTH_BODY_COMPOSITION_ANALYZER", function () {
        return 0x09;
    });

    this.__defineGetter__("HEALTH_PEAK_FLOW_MONITOR", function () {
        return 0x0a;
    });

    this.__defineGetter__("HEALTH_MEDICATION_MONITOR", function () {
        return 0x0b;
    });

    this.__defineGetter__("HEALTH_KNEE_PROSTHESIS", function () {
        return 0x0c;
    });

    this.__defineGetter__("HEALTH_ANKLE_PROSTHESIS", function () {
        return 0x0d;
    });
};

module.exports = BluetoothClassDeviceMinor;

});
define('ripple/platform/tizen/2.0/BluetoothClassDeviceService', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 BluetoothClassDeviceService = function () {
    this.__defineGetter__("LIMITED_DISCOVERABILITY", function () {
        return 0x0001;
    });

    this.__defineGetter__("POSITIONING", function () {
        return 0x0008;
    });

    this.__defineGetter__("NETWORKING", function () {
        return 0x0010;
    });

    this.__defineGetter__("RENDERING", function () {
        return 0x0020;
    });

    this.__defineGetter__("CAPTURING", function () {
        return 0x0040;
    });

    this.__defineGetter__("OBJECT_TRANSFER", function () {
        return 0x0080;
    });

    this.__defineGetter__("AUDIO", function () {
        return 0x0100;
    });

    this.__defineGetter__("TELEPHONY", function () {
        return 0x0200;
    });

    this.__defineGetter__("INFORMATION", function () {
        return 0x0400;
    });
};

module.exports = BluetoothClassDeviceService;

});
define('ripple/platform/tizen/2.0/BluetoothDevice', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    BluetoothClass = require('ripple/platform/tizen/2.0/BluetoothClass'),
    BluetoothSocket = require('ripple/platform/tizen/2.0/BluetoothSocket'),
    BluetoothDevice,
    _security;

BluetoothDevice = function (prop) {
    var bluetoothDevice = {}, sockets = {}, self;

    bluetoothDevice.name        = prop.name || "";
    bluetoothDevice.address     = prop.address || "";
    bluetoothDevice.deviceClass = new BluetoothClass(prop.deviceClass,
            prop.metaData) || {};
    bluetoothDevice.isBonded    = prop.isBonded || false;
    bluetoothDevice.isTrusted   = prop.isTrusted || false;
    bluetoothDevice.isConnected = prop.isConnected || false;
    bluetoothDevice.services    = prop.services;
    bluetoothDevice.uuids       = [];

    this.__defineGetter__("name", function () {
        return bluetoothDevice.name;
    });

    this.__defineGetter__("address", function () {
        return bluetoothDevice.address;
    });

    this.__defineGetter__("deviceClass", function () {
        return bluetoothDevice.deviceClass;
    });

    this.__defineGetter__("isBonded", function () {
        return bluetoothDevice.isBonded;
    });

    this.__defineGetter__("isTrusted", function () {
        return bluetoothDevice.isTrusted;
    });

    this.__defineGetter__("isConnected", function () {
        return bluetoothDevice.isConnected;
    });

    this.__defineGetter__("uuids", function () {
        return bluetoothDevice.uuids;
    });

    this.connectToServiceByUUID = function (uuid, successCallback,
            errorCallback) {
        if (!_security.all && !_security.connectToServiceByUUID) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothDevice("connectToServiceByUUID", arguments);

        window.setTimeout(function () {
            if (bluetoothDevice.uuids.join(",").indexOf(uuid) === -1) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                }
                return;
            }

            bluetoothDevice.isConnected = true;
            event.trigger("bt-device-connected-changed", [bluetoothDevice.address,
                    true]);
            event.trigger("bt-service-state-changed", [bluetoothDevice.address,
                    uuid, true]);

            window.setTimeout(function () {
                successCallback(sockets[uuid]);
            }, 1);
        }, 1);
    };

    event.on("bt-device-connected-update", function (addr, isConnected) {
        if (addr !== bluetoothDevice.address)
            return;

        bluetoothDevice.isConnected = isConnected;
        event.trigger("bt-device-connected-changed",
                [bluetoothDevice.address, bluetoothDevice.isConnected]);
    });

    event.on("bt-device-bonded-changed", function (addr, isBonded) {
        if (addr !== bluetoothDevice.address)
            return;

        bluetoothDevice.isBonded = isBonded;
    });

    _security = prop.metaData;
    self = this;

    utils.forEach(bluetoothDevice.services, function (service) {
        bluetoothDevice.uuids.push(service.uuid);
        sockets[service.uuid] = new BluetoothSocket({
            uuid: service.uuid,
            protocol: service.protocol,
            state: "CLOSED",
            peer: self,
            metaData: _security
        });
    });
};

module.exports = BluetoothDevice;

});
define('ripple/platform/tizen/2.0/BluetoothServiceHandler', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    BluetoothServiceHandler,
    _security;

BluetoothServiceHandler = function (prop) {
    var bluetoothServiceHandler = {};

    _security = prop.metaData;

    bluetoothServiceHandler.uuid        = prop.uuid || "";
    bluetoothServiceHandler.name        = prop.name || "";
    bluetoothServiceHandler.isConnected = prop.isConnected || false;
    bluetoothServiceHandler.onconnect   = null;

    this.__defineGetter__("uuid", function () {
        return bluetoothServiceHandler.uuid;
    });

    this.__defineGetter__("name", function () {
        return bluetoothServiceHandler.name;
    });

    this.__defineGetter__("isConnected", function () {
        return bluetoothServiceHandler.isConnected;
    });

    this.__defineGetter__("onconnect", function () {
        return bluetoothServiceHandler.onconnect;
    });
    this.__defineSetter__("onconnect", function (val) {
        try {
            bluetoothServiceHandler.onconnect =
                    t.BluetoothSocketSuccessCallback(val, "?");
        } catch (e) {
        }
    });

    this.unregister = function (successCallback, errorCallback) {
        if (!_security.unregister) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothServiceHandler("unregister", arguments);

        event.trigger("bt-unregister-service", [bluetoothServiceHandler.uuid,
                successCallback, errorCallback]);
    };
};

module.exports = BluetoothServiceHandler;

});
define('ripple/platform/tizen/2.0/BluetoothSocket', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    BluetoothSocket,
    _security;

BluetoothSocket = function (prop) {
    var bluetoothSocket = {}, buffer = [], that = this;

    _security = prop.metaData;

    bluetoothSocket.uuid      = prop.uuid;
    bluetoothSocket.state     = prop.state;
    bluetoothSocket.peer      = prop.peer;
    bluetoothSocket.onmessage = null;
    bluetoothSocket.onclose   = null;

    this.__defineGetter__("uuid", function () {
        return bluetoothSocket.uuid;
    });

    this.__defineGetter__("state", function () {
        return bluetoothSocket.state;
    });

    this.__defineGetter__("peer", function () {
        return bluetoothSocket.peer;
    });

    this.__defineGetter__("onmessage", function () {
        return bluetoothSocket.onmessage;
    });
    this.__defineSetter__("onmessage", function (val) {
        try {
            bluetoothSocket.onmessage = t.SuccessCallback(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("onclose", function () {
        return bluetoothSocket.onclose;
    });
    this.__defineSetter__("onclose", function (val) {
        try {
            bluetoothSocket.onclose = t.SuccessCallback(val, "?");
        } catch (e) {
        }
    });

    this.writeData = function (data) {
        if (!_security.writeData) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothSocket("writeData", arguments);

        if (this.state === "CLOSED") {
            return;
        }

        event.trigger("bt-service-write-msg", [bluetoothSocket.peer.address,
                bluetoothSocket.uuid, data]);

        return data.length;
    };

    this.readData = function () {
        var data;

        if (!_security.readData) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        if (this.state === "CLOSED") {
            return;
        }

        data = utils.copy(buffer);
        buffer = [];

        return data;
    };

    this.close = function () {
        if (!_security.close) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        bluetoothSocket.state = "CLOSED";

        event.trigger("bt-service-state-changed", [bluetoothSocket.peer.address,
                bluetoothSocket.uuid, false]);
        event.trigger("bt-device-connected-update",
                [bluetoothSocket.peer.address, false]);

        if (bluetoothSocket.onclose) {
            bluetoothSocket.onclose();
        }
    };

    event.on("bt-service-state-update", function (addr, state) {
        var stateStr = "CLOSED";

        if (addr !== bluetoothSocket.peer.address) {
            return;
        }
        if (state) {
            stateStr = "OPEN";
        }

        bluetoothSocket.state = stateStr;

        event.trigger("bt-service-state-changed",
                [bluetoothSocket.peer.address, bluetoothSocket.uuid,
                state]);
        event.trigger("bt-device-connected-update",
                [bluetoothSocket.peer.address, state]);
    });

    event.on("bt-service-rawdata-received", function (addr, uuid, msg) {
        var i;

        if ((addr !== bluetoothSocket.peer.address) ||
                (uuid !== bluetoothSocket.uuid)) {
            return;
        }
        buffer = [];
        for (i = 0; i < msg.length; i++) {
            buffer.push(msg.charCodeAt(i));
        }
        if (bluetoothSocket.onmessage) {
            bluetoothSocket.onmessage();
        }
    });

    event.on("bt-device-connected-changed", function (addr, isConnected) {
        bluetoothSocket.state = isConnected ? "OPEN" : "CLOSED";
    });
};

module.exports = BluetoothSocket;

});
define('ripple/platform/tizen/2.0/BookmarkFolder', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    BookmarkFolder;

BookmarkFolder = function (title) {
    t.BookmarkFolder(arguments, this);

    this.__defineGetter__("parent", function () {
        return undefined;
    });

    this.__defineGetter__("title", function () {
        return title;
    });
};

module.exports = BookmarkFolder;

});
define('ripple/platform/tizen/2.0/BookmarkItem', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    BookmarkItem;

BookmarkItem = function (title, url) {
    t.BookmarkItem(arguments, this);

    this.__defineGetter__("parent", function () {
        return undefined;
    });
    this.__defineGetter__("title", function () {
        return title;
    });
    this.__defineGetter__("url", function () {
        return url;
    });
};

module.exports = BookmarkItem;

});
define('ripple/platform/tizen/2.0/CalendarAlarm', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    CalendarAlarm;

CalendarAlarm = function () {
    var voc, calendarAlarm = {};

    // private
    function construct() {
        this.__defineGetter__("absoluteDate", function () {
            return calendarAlarm.absoluteDate;
        });
        this.__defineSetter__("absoluteDate", function (val) {
            try {
                calendarAlarm.absoluteDate = t.TZDate(val, "?");
            } catch (e) {
            }
        });

        this.__defineGetter__("before", function () {
            return calendarAlarm.before;
        });
        this.__defineSetter__("before", function (val) {
            try {
                calendarAlarm.before = t.TimeDuration(val, "?");
            } catch (e) {
            }
        });

        this.__defineGetter__("method", function () {
            return calendarAlarm.method;
        });
        this.__defineSetter__("method", function (val) {
            try {
                calendarAlarm.method = t.AlarmMethod(val);
            } catch (e) {
            }
        });

        this.__defineGetter__("description", function () {
            return calendarAlarm.description;
        });
        this.__defineSetter__("description", function (val) {
            try {
                calendarAlarm.description = t.DOMString(val, "?");
            } catch (e) {
            }
        });
    }

    // Constructor
    function CalendarAlarm_TZDate_AlarmMethod_DOMString(absoluteDate, method,
            description) {
        construct.call(this);

        calendarAlarm.absoluteDate = absoluteDate;
        calendarAlarm.before       = null;
        calendarAlarm.method       = method;
        calendarAlarm.description  = description || "";
    }

    function CalendarAlarm_TimeDuration_AlarmMethod_DOMString(before, method,
            description) {
        construct.call(this);

        calendarAlarm.absoluteDate = null;
        calendarAlarm.before       = before;
        calendarAlarm.method       = method;
        calendarAlarm.description  = description || "";
    }

    voc = [CalendarAlarm_TZDate_AlarmMethod_DOMString,
           CalendarAlarm_TimeDuration_AlarmMethod_DOMString];
    t.CalendarAlarm(arguments, this, voc);
};

module.exports = CalendarAlarm;

});
define('ripple/platform/tizen/2.0/CalendarAttendee', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    CalendarAttendee;

CalendarAttendee = function (uri, attendeeInitDict) {
    var calendarAttendee = {}, attr;

    t.CalendarAttendee(arguments, this);

    calendarAttendee.uri          = uri;
    calendarAttendee.name         = undefined;
    calendarAttendee.role         = "REQ_PARTICIPANT";
    calendarAttendee.status       = "PENDING";
    calendarAttendee.RSVP         = false;
    calendarAttendee.type         = "INDIVIDUAL";
    calendarAttendee.group        = undefined;
    calendarAttendee.delegatorURI = undefined;
    calendarAttendee.delegateURI  = undefined;
    calendarAttendee.contactRef   = null;

    if (attendeeInitDict) {
        for (attr in attendeeInitDict) {
            calendarAttendee[attr] = attendeeInitDict[attr];
        }
    }

    this.__defineGetter__("uri", function () {
        return calendarAttendee.uri;
    });
    this.__defineSetter__("uri", function (val) {
        try {
            calendarAttendee.uri = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("name", function () {
        return calendarAttendee.name;
    });
    this.__defineSetter__("name", function (val) {
        try {
            calendarAttendee.name = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("role", function () {
        return calendarAttendee.role;
    });
    this.__defineSetter__("role", function (val) {
        try {
            calendarAttendee.role = t.AttendeeRole(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("status", function () {
        return calendarAttendee.status;
    });
    this.__defineSetter__("status", function (val) {
        try {
            calendarAttendee.status = t.AttendeeStatus(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("RSVP", function () {
        return calendarAttendee.RSVP;
    });
    this.__defineSetter__("RSVP", function (val) {
        try {
            calendarAttendee.RSVP = t.boolean(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("type", function () {
        return calendarAttendee.type;
    });
    this.__defineSetter__("type", function (val) {
        try {
            calendarAttendee.type = t.AttendeeType(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("group", function () {
        return calendarAttendee.group;
    });
    this.__defineSetter__("group", function (val) {
        try {
            calendarAttendee.group = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("delegatorURI", function () {
        return calendarAttendee.delegatorURI;
    });
    this.__defineSetter__("delegatorURI", function (val) {
        try {
            calendarAttendee.delegatorURI = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("delegateURI", function () {
        return calendarAttendee.delegateURI;
    });
    this.__defineSetter__("delegateURI", function (val) {
        try {
            calendarAttendee.delegateURI = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("contactRef", function () {
        return calendarAttendee.contactRef;
    });
    this.__defineSetter__("contactRef", function (val) {
        try {
            calendarAttendee.contactRef = t.ContactRef(val, "?");
        } catch (e) {
        }
    });
};

module.exports = CalendarAttendee;

});
define('ripple/platform/tizen/2.0/CalendarEvent', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    typedef = require('ripple/platform/tizen/2.0/typedef'),
    CalendarItem = require('ripple/platform/tizen/2.0/CalendarItem'),
    CalendarEvent;

CalendarEvent = function () {
    var voc, calendarEvent = {};

    // private
    function construct(eventInitDict) {
        CalendarItem.call(this, eventInitDict);

        this.status = "CONFIRMED";

        calendarEvent.convertToString  = this.convertToString;
        calendarEvent.isDetached       = false;
        calendarEvent.endDate          = null;
        calendarEvent.availability     = "BUSY";
        calendarEvent.recurrenceRule   = null;

        this.__defineGetter__("isDetached", function () {
            return calendarEvent.isDetached;
        });

        this.__defineGetter__("endDate", function () {
            return calendarEvent.endDate;
        });
        this.__defineSetter__("endDate", function (val) {
            try {
                calendarEvent.endDate = t.TZDate(val, "?");
            } catch (e) {
            }
        });

        this.__defineGetter__("availability", function () {
            return calendarEvent.availability;
        });
        this.__defineSetter__("availability", function (val) {
            try {
                calendarEvent.availability = t.EventAvailability(val);
            } catch (e) {
            }
        });

        this.__defineGetter__("recurrenceRule", function () {
            return calendarEvent.recurrenceRule;
        });
        this.__defineSetter__("recurrenceRule", function (val) {
            try {
                calendarEvent.recurrenceRule = t.CalendarRecurrenceRule(val,
                        "?");
            } catch (e) {
            }
        });

        this.convertToString  = convertToString;
        this.clone            = clone(this);
        this.expandRecurrence = expandRecurrence;
    }

    function clone(self) {
        return function () {
            return new CalendarEvent(self);
        };
    }

    // public
    function convertToString(format) {
        var str;

        str = calendarEvent.convertToString.call(this, format);
        str = str.replace(/#TYPE#/g, "VEVENT");

        // TODO: endDate is not supported
        // TODO: recurrenceRule is not supported
        str = str.replace(/#AVAILABILITY#/g, "FREEBUSY;FBTYPE=" +
                calendarEvent.availability);

        str = str.replace(/#[^#]*#/g, "");

        return str;
    }

    function expandRecurrence(startDate, endDate, successCallback,
            errorCallback) {
    }

    // Constructor
    function CalendarEvent_CalendarEventInit(eventInitDict) {
        var attr;

        construct.call(this, eventInitDict);

        if (eventInitDict) {
            for (attr in eventInitDict) {
                if (attr in typedef.CalendarEventInit) {
                    calendarEvent[attr] = eventInitDict[attr];
                }
            }
        }
    }

    function CalendarEvent_DOMString_CalendarTextFormat(stringRepresentation,
            format) {
    }

    voc = [CalendarEvent_CalendarEventInit,
           CalendarEvent_DOMString_CalendarTextFormat];
    t.CalendarEvent(arguments, this, voc);
};

module.exports = CalendarEvent;

});
define('ripple/platform/tizen/2.0/CalendarEventId', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    CalendarEventId;

CalendarEventId = function (uid, rid) {
    var calendarEventId = {};

    t.CalendarEventId(arguments, this);

    calendarEventId.uid = uid;
    calendarEventId.rid = rid || null;

    this.__defineGetter__("uid", function () {
        return calendarEventId.uid;
    });
    this.__defineSetter__("uid", function (val) {
        try {
            calendarEventId.uid = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("rid", function () {
        return calendarEventId.rid;
    });
    this.__defineSetter__("rid", function (val) {
        try {
            calendarEventId.rid = t.DOMString(val, "?");
        } catch (e) {
        }
    });
};

module.exports = CalendarEventId;

});
define('ripple/platform/tizen/2.0/CalendarItem', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    typedef = require('ripple/platform/tizen/2.0/typedef'),
    CalendarItem;

CalendarItem = function (itemInitDict) {
    var calendarItem = {}, attr;

    // private
    function toDigit(number) {
        return ((number >= 10) ? "" : "0") + number;
    }

    // public
    function convertToString(format) {
        var header = "BEGIN:VCALENDAR\r\nPRODID:-//Tizen.org//Tizen Calendar//EN\r\nVERSION:2.0\r\n",
            end = "END:VCALENDAR\r\n", str = "", pri, i, date, before, y, m, d,
            hh, mm, ss, dateStart = "", dateEnd = "";

        t.CalendarItem("convertToString", arguments);

        //TODO: vcalendar 1.0 doesn't support yet
        if (format === "VCALENDAR_10") {
            return;
        }

        str = header + "BEGIN:#TYPE#\r\n";

        if (this.isAllDay) {
            if (this.startDate) {
                date = this.startDate;
                y = date.getFullYear();
                m = toDigit(date.getMonth() + 1);
                d = toDigit(date.getDate());
                str += "DTSTART;VALUE=DATE:" + y + m + d + "\r\n";
                dateStart = "" + y + m + d + "T000000Z";
                if (this.duration) {
                    date = date.addDuration(this.duration);
                    y = date.getFullYear();
                    m = toDigit(date.getMonth() + 1);
                    d = toDigit(date.getDate());
                    str += "DTEND;VALUE=DATE:" + y + m + d + "\r\n";
                    dateEnd = "" + y + m + d + "T000000Z";
                }
            }
        } else {
            if (this.startDate) {
                date = this.startDate;
                y = date.getFullYear();
                m = toDigit(date.getMonth() + 1);
                d = toDigit(date.getDate());
                hh = toDigit(date.getHours());
                mm = toDigit(date.getMinutes());
                ss = toDigit(date.getSeconds());
                str += "DTSTART:" + y + m + d + "T" + hh + mm + ss + "Z" + "\r\n";
                dateStart = "" + y + m + d + "T" + hh + mm + ss + "Z";
                if (this.duration && this.duration.length && this.duration.unit) {
                    date = date.addDuration(this.duration);
                    y = date.getFullYear();
                    m = toDigit(date.getMonth() + 1);
                    d = toDigit(date.getDate());
                    hh = toDigit(date.getHours());
                    mm = toDigit(date.getMinutes());
                    ss = toDigit(date.getSeconds());
                    str += "DTEND:" + y + m + d + "T" + hh + mm + ss + "Z" + "\r\n";
                    dateEnd = "" + y + m + d + "T" + hh + mm + ss + "Z";
                }
            }
        }

        if (this.description) {
            str += "DESCRIPTION:" + this.description + "\r\n";
        }
        if (this.summary) {
            str += "SUMMARY:" + this.summary + "\r\n";
        }
        if (this.location) {
            str += "LOCATION:" + this.location + "\r\n";
        }
        if (this.geolocation) {
            // Don't need to check latitude and longitude due to they are mandatory attributes
            str += "GEO:" + this.geolocation.latitude + "," + this.geolocation.longitude + "\r\n";
        }
        if (this.organizer) {
            str += "ORGANIZER:" + this.organizer + "\r\n";
        }
        if (this.visibility) {
            str += "CLASS:" + this.visibility + "\r\n";
        }
        if (this.status) {
            str += "STATUS:" + this.status + "\r\n";
        }
        if (this.priority) {
            switch (this.priority) {
            case "HIGH":
                pri = 2;
                break;
            case "MEDIUM":
                pri = 5;
                break;
            case "LOW":
                pri = 7;
                break;
            }
            str += "PRIORITY:" + pri + "\r\n";
        }
        if (tizen1_utils.isValidArray(this.alarms)) {
            for (i = 0; i < this.alarms.length; i++) {
                str += "BEGIN:VALARM\r\n";
                // Don't need to check this.alarms[i].method due to it is a mandatory attribute
                str += "ACTION:" + this.alarms[i].method + "\r\n";
                if (this.alarms[i].description) {
                    str += "DESCRIPTION:" + this.alarms[i].description + "\r\n";
                } else {
                    // description property MUST included if action is DISPLAY (RFC5545 3.6.6)
                    str += "DESCRIPTION:This is a reminder\r\n";
                }
                if (this.alarms[i].absoluteDate) {
                    date = this.alarms[i].absoluteDate;
                    y = date.getFullYear();
                    m = toDigit(date.getMonth() + 1);
                    d = toDigit(date.getDate());
                    hh = toDigit(date.getHours());
                    mm = toDigit(date.getMinutes());
                    ss = toDigit(date.getSeconds());
                    str += "TRIGGER;VALUE=DATE-TIME:" + y + m + d + "T" + hh + mm + ss + "Z" + "\r\n";
                } else {
                    //it must be included before attribute
                    before = this.alarms[i].before;
                    switch (before.unit) {
                    case "DAYS":
                        str += "TRIGGER:-P" + before.length + "D" + "\r\n";
                        break;
                    case "HOURS":
                        str += "TRIGGER:-P0DT" + before.length + "H0M0S" + "\r\n";
                        break;
                    case "MINS":
                        str += "TRIGGER:-P0DT0H" + before.length + "M0S" + "\r\n";
                        break;
                    case "SECS":
                        str += "TRIGGER:-P0DT0H0M" + before.length + "S" + "\r\n";
                        break;
                    }
                }
                str += "END:VALARM\r\n";
            }
        }
        if (tizen1_utils.isValidArray(this.categories)) {
            str += "CATEGORIES:";
            for (i = 0; i < this.categories.length; i++) {
                str += this.categories[i] + ",";
            }
            str = str.slice(0, -1);
            str += "\r\n";
        }
        if (tizen1_utils.isValidArray(this.attendees)) {
            for (i = 0; i < this.attendees.length; i++) {
                //TODO: basic implementation
                str += "ATTENDEE:mailto:" + this.attendees[i].uri + "\r\n";
            }
        }

        if ((dateStart !== "") && (dateEnd !== "")) {
            str += "#AVAILABILITY#:" + dateStart + "/" + dateEnd + "\r\n";
        }

        str += "#ENDDATE##RECURRENCERULE#";
        str += "#DUEDATE##COMPLETEDDATE##PROGRESS#";
        str += "END:#TYPE#\r\n" + end;

        return str;
    }

    calendarItem.description = "";
    calendarItem.summary     = "";
    calendarItem.isAllDay    = false;
    calendarItem.startDate   = null;
    calendarItem.duration    = null;
    calendarItem.location    = "";
    calendarItem.geolocation = null;
    calendarItem.organizer   = "";
    calendarItem.visibility  = "PUBLIC";
    calendarItem.status      = "TENTATIVE";
    calendarItem.priority    = "LOW";
    calendarItem.alarms      = [];
    calendarItem.categories  = [];
    calendarItem.attendees   = [];

    if (itemInitDict) {
        for (attr in itemInitDict) {
            if (!(attr in typedef.CalendarItemInit))
                continue;

            switch (attr) {
            case "alarms":
                calendarItem.alarms = t.CalendarAlarm(itemInitDict.alarms,
                        "[]+");
                break;

            case "categories":
                calendarItem.categories = t.DOMString(itemInitDict.categories,
                        "[]+");
                break;

            case "attendees":
                calendarItem.attendees = t.CalendarAttendee(
                        itemInitDict.attendees, "[]+");
                break;

            default:
                calendarItem[attr] = itemInitDict[attr];
                break;
            }
        }
    }

    this.__defineGetter__("id", function () {
        return null;
    });

    this.__defineGetter__("calendarId", function () {
        return null;
    });

    this.__defineGetter__("lastModificationDate", function () {
        return null;
    });

    this.__defineGetter__("description", function () {
        return calendarItem.description;
    });
    this.__defineSetter__("description", function (val) {
        try {
            calendarItem.description = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("summary", function () {
        return calendarItem.summary;
    });
    this.__defineSetter__("summary", function (val) {
        try {
            calendarItem.summary = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("isAllDay", function () {
        return calendarItem.isAllDay;
    });
    this.__defineSetter__("isAllDay", function (val) {
        try {
            calendarItem.isAllDay = t.boolean(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("startDate", function () {
        return calendarItem.startDate;
    });
    this.__defineSetter__("startDate", function (val) {
        try {
            calendarItem.startDate = t.TZDate(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("duration", function () {
        return calendarItem.duration;
    });
    this.__defineSetter__("duration", function (val) {
        try {
            calendarItem.duration = t.TimeDuration(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("location", function () {
        return calendarItem.location;
    });
    this.__defineSetter__("location", function (val) {
        try {
            calendarItem.location = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("geolocation", function () {
        return calendarItem.geolocation;
    });
    this.__defineSetter__("geolocation", function (val) {
        try {
            calendarItem.geolocation = t.SimpleCoordinates(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("organizer", function () {
        return calendarItem.organizer;
    });
    this.__defineSetter__("organizer", function (val) {
        try {
            calendarItem.organizer = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("visibility", function () {
        return calendarItem.visibility;
    });
    this.__defineSetter__("visibility", function (val) {
        try {
            calendarItem.visibility = t.CalendarItemVisibility(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("status", function () {
        return calendarItem.status;
    });
    this.__defineSetter__("status", function (val) {
        try {
            calendarItem.status = t.CalendarItemStatus(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("priority", function () {
        return calendarItem.priority;
    });
    this.__defineSetter__("priority", function (val) {
        try {
            calendarItem.priority = t.CalendarItemPriority(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("alarms", function () {
        return calendarItem.alarms;
    });
    this.__defineSetter__("alarms", function (val) {
        try {
            calendarItem.alarms = t.CalendarAlarm(val, "[]");
        } catch (e) {
        }
    });

    this.__defineGetter__("categories", function () {
        return calendarItem.categories;
    });
    this.__defineSetter__("categories", function (val) {
        try {
            calendarItem.categories = t.DOMString(val, "[]");
        } catch (e) {
        }
    });

    this.__defineGetter__("attendees", function () {
        return calendarItem.attendees;
    });
    this.__defineSetter__("attendees", function (val) {
        try {
            calendarItem.attendees = t.CalendarAttendee(val, "[]");
        } catch (e) {
        }
    });

    this.convertToString = convertToString;
};

module.exports = CalendarItem;

});
define('ripple/platform/tizen/2.0/CalendarRecurrenceRule', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    CalendarRecurrenceRule;

CalendarRecurrenceRule = function (frequency, ruleInitDict) {
    var calendarRecurrenceRule = {}, attr;

    t.CalendarRecurrenceRule(arguments, this);

    calendarRecurrenceRule.frequency       = frequency;
    calendarRecurrenceRule.interval        = 1;
    calendarRecurrenceRule.untilDate       = null;
    calendarRecurrenceRule.occurrenceCount = -1;
    calendarRecurrenceRule.daysOfTheWeek   = [];
    calendarRecurrenceRule.setPositions    = [];
    calendarRecurrenceRule.exceptions      = [];

    if (ruleInitDict) {
        for (attr in ruleInitDict) {
            switch (attr) {
            case "daysOfTheWeek":
                calendarRecurrenceRule.daysOfTheWeek = t.ByDayValue(
                        ruleInitDict.daysOfTheWeek, "[]+");
                break;

            case "setPositions":
                calendarRecurrenceRule.setPositions = t.short(
                        ruleInitDict.setPositions, "[]+");
                break;

            case "exceptions":
                calendarRecurrenceRule.exceptions = t.TZDate(
                        ruleInitDict.exceptions, "[]+");
                break;

            default:
                calendarRecurrenceRule[attr] = ruleInitDict[attr];
                break;
            }
        }
    }

    this.__defineGetter__("frequency", function () {
        return calendarRecurrenceRule.frequency;
    });
    this.__defineSetter__("frequency", function (val) {
        try {
            calendarRecurrenceRule.frequency = t.RecurrenceRuleFrequency(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("interval", function () {
        return calendarRecurrenceRule.interval;
    });
    this.__defineSetter__("interval", function (val) {
        try {
            calendarRecurrenceRule.interval = t.unsigned_short(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("untilDate", function () {
        return calendarRecurrenceRule.untilDate;
    });
    this.__defineSetter__("untilDate", function (val) {
        try {
            calendarRecurrenceRule.untilDate = t.TZDate(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("occurrenceCount", function () {
        return calendarRecurrenceRule.occurrenceCount;
    });
    this.__defineSetter__("occurrenceCount", function (val) {
        try {
            calendarRecurrenceRule.occurrenceCount = t.long(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("daysOfTheWeek", function () {
        return calendarRecurrenceRule.daysOfTheWeek;
    });
    this.__defineSetter__("daysOfTheWeek", function (val) {
        try {
            calendarRecurrenceRule.daysOfTheWeek = t.ByDayValue(val, "[]");
        } catch (e) {
        }
    });

    this.__defineGetter__("setPositions", function () {
        return calendarRecurrenceRule.setPositions;
    });
    this.__defineSetter__("setPositions", function (val) {
        try {
            calendarRecurrenceRule.setPositions = t.short(val, "[]");
        } catch (e) {
        }
    });

    this.__defineGetter__("exceptions", function () {
        return calendarRecurrenceRule.exceptions;
    });
    this.__defineSetter__("exceptions", function (val) {
        try {
            calendarRecurrenceRule.exceptions = t.TZDate(val, "[]");
        } catch (e) {
        }
    });
};

module.exports = CalendarRecurrenceRule;

});
define('ripple/platform/tizen/2.0/CalendarTask', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    typedef = require('ripple/platform/tizen/2.0/typedef'),
    CalendarItem = require('ripple/platform/tizen/2.0/CalendarItem'),
    CalendarTask;

CalendarTask = function () {
    var voc, calendarTask = {};

    // private
    function construct(taskInitDict) {
        CalendarItem.call(this, taskInitDict);

        this.status = "NEEDS_ACTION";

        calendarTask.convertToString = this.convertToString;
        calendarTask.dueDate         = null;
        calendarTask.completedDate   = null;
        calendarTask.progress        = 0;

        this.__defineGetter__("dueDate", function () {
            return calendarTask.dueDate;
        });
        this.__defineSetter__("dueDate", function (val) {
            try {
                calendarTask.dueDate = t.TZDate(val, "?");
            } catch (e) {
            }
        });

        this.__defineGetter__("completedDate", function () {
            return calendarTask.completedDate;
        });
        this.__defineSetter__("completedDate", function (val) {
            try {
                calendarTask.completedDate = t.TZDate(val, "?");
            } catch (e) {
            }
        });

        this.__defineGetter__("progress", function () {
            return calendarTask.progress;
        });
        this.__defineSetter__("progress", function (val) {
            try {
                calendarTask.progress = t.unsigned_short(val);
            } catch (e) {
            }
        });

        this.convertToString = convertToString;
        this.clone           = clone(this);
    }

    function clone(self) {
        return function () {
            return new CalendarTask(self);
        };
    }

    // public
    function convertToString(format) {
        var str;

        str = calendarTask.convertToString.call(this, format);
        str = str.replace(/#TYPE#/g, "VTASK");

        // TODO: dueDate is not supported
        // TODO: completedDate is not supported
        if (this.progress) {
            str = str.replace(/#PROGRESS#/g, "PERCENT-COMPLETE:" +
                    this.progress + "\r\n");
        }

        str = str.replace(/#AVAILABILITY#.*\r\n/g, "");
        str = str.replace(/#[^#]*#/g, "");

        return str;
    }

    // Constructor
    function CalendarTask_CalendarTaskInit(taskInitDict) {
        var attr;

        construct.call(this, taskInitDict);

        if (taskInitDict) {
            for (attr in taskInitDict) {
                if (attr in typedef.CalendarTaskInit) {
                    calendarTask[attr] = taskInitDict[attr];
                }
            }
        }
    }

    function CalendarTask_DOMString_CalendarTextFormat(stringRepresentation,
            format) {
    }

    voc = [CalendarTask_CalendarTaskInit,
           CalendarTask_DOMString_CalendarTextFormat];
    t.CalendarTask(arguments, this, voc);
};

module.exports = CalendarTask;

});
define('ripple/platform/tizen/2.0/CompositeFilter', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    CompositeFilter;

CompositeFilter = function (type, filters) {
    var compositeFilter = {};

    t.CompositeFilter(arguments, this);

    this.__defineGetter__("type", function () {
        return compositeFilter.type;
    });
    this.__defineSetter__("type", function (val) {
        try {
            compositeFilter.type = t.CompositeFilterType(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("filters", function () {
        return compositeFilter.filters;
    });
    this.__defineSetter__("filters", function (val) {
        try {
            compositeFilter.filters = t.AbstractFilter(val, "[]");
        } catch (e) {
        }
    });

    compositeFilter.type    = type;
    compositeFilter.filters = filters || [];
};

module.exports = CompositeFilter;

});
define('ripple/platform/tizen/2.0/ContactAddress', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactAddress;

ContactAddress = function (addressInitDict) {
    var contactAddress = {}, attr, arr, i;

    t.ContactAddress(arguments, this);

    contactAddress.country               = null;
    contactAddress.region                = null;
    contactAddress.city                  = null;
    contactAddress.streetAddress         = null;
    contactAddress.additionalInformation = null;
    contactAddress.postalCode            = null;
    contactAddress.isDefault             = false;
    contactAddress.types                 = ["HOME"];

    this.__defineGetter__("country", function () {
        return contactAddress.country;
    });
    this.__defineSetter__("country", function (val) {
        try {
            contactAddress.country = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("region", function () {
        return contactAddress.region;
    });
    this.__defineSetter__("region", function (val) {
        try {
            contactAddress.region = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("city", function () {
        return contactAddress.city;
    });
    this.__defineSetter__("city", function (val) {
        try {
            contactAddress.city = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("streetAddress", function () {
        return contactAddress.streetAddress;
    });
    this.__defineSetter__("streetAddress", function (val) {
        try {
            contactAddress.streetAddress = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("additionalInformation", function () {
        return contactAddress.additionalInformation;
    });
    this.__defineSetter__("additionalInformation", function (val) {
        try {
            contactAddress.additionalInformation = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("postalCode", function () {
        return contactAddress.postalCode;
    });
    this.__defineSetter__("postalCode", function (val) {
        try {
            contactAddress.postalCode = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("isDefault", function () {
        return contactAddress.isDefault;
    });
    this.__defineSetter__("isDefault", function (val) {
        try {
            contactAddress.isDefault = t.boolean(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("types", function () {
        return contactAddress.types;
    });
    this.__defineSetter__("types", function (val) {
        try {
            contactAddress.types = t.DOMString(val, "[]");
        } catch (e) {
        }
    });

    if (addressInitDict) {
        for (attr in addressInitDict) {
            switch (attr) {
            case "types":
                arr = addressInitDict[attr];
                if (arr) {
                    for (i in arr) {
                        contactAddress[attr][i] = arr[i];
                    }
                }
                break;

            default:
                contactAddress[attr] = addressInitDict[attr];
                break;
            }
        }
    }
};

module.exports = ContactAddress;

});
define('ripple/platform/tizen/2.0/ContactAnniversary', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactAnniversary;

ContactAnniversary = function (date, label) {
    var contactAnniversary = {};

    t.ContactAnniversary(arguments, this);

    contactAnniversary.date  = date;
    contactAnniversary.label = label || null;

    this.__defineGetter__("date", function () {
        return contactAnniversary.date;
    });
    this.__defineSetter__("date", function (val) {
        try {
            contactAnniversary.date = t.Date(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("label", function () {
        return contactAnniversary.label;
    });
    this.__defineSetter__("label", function (val) {
        try {
            contactAnniversary.label = t.DOMString(val, "?");
        } catch (e) {
        }
    });
};

module.exports = ContactAnniversary;

});
define('ripple/platform/tizen/2.0/ContactBase', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 decorator = require('ripple/platform/tizen/2.0/decorator'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    ContactName = require('ripple/platform/tizen/2.0/ContactName'),
    ContactAddress = require('ripple/platform/tizen/2.0/ContactAddress'),
    ContactPhoneNumber = require('ripple/platform/tizen/2.0/ContactPhoneNumber'),
    ContactEmailAddress = require('ripple/platform/tizen/2.0/ContactEmailAddress'),
    ContactAnniversary = require('ripple/platform/tizen/2.0/ContactAnniversary'),
    ContactOrganization = require('ripple/platform/tizen/2.0/ContactOrganization'),
    ContactWebSite = require('ripple/platform/tizen/2.0/ContactWebSite'),
    Contact;

Contact = function () {
    var voc;

    // private
    function construct() {
        this.name          = null;
        this.addresses     = [];
        this.photoURI      = null;
        this.phoneNumbers  = [];
        this.emails        = [];
        this.birthday      = null;
        this.anniversaries = [];
        this.organizations = [];
        this.notes         = [];
        this.urls          = [];
        this.ringtoneURI   = null;
        this.groupIds      = [];
    }

    // Constructor
    function Contact_ContactInit(contactInitDict) {
        var i, attr, arr;

        construct.apply(this);

        for (attr in contactInitDict) {
            switch (attr) {
            case "name":
                this[attr] = new ContactName(contactInitDict[attr]);
                break;

            case "addresses":
                arr = contactInitDict[attr];
                if (arr) {
                    for (i in arr) {
                        this[attr][i] = new ContactAddress(arr[i]);
                    }
                }
                break;

            case "phoneNumbers":
                arr = contactInitDict[attr];
                if (arr) {
                    for (i in arr) {
                        this[attr][i] = new ContactPhoneNumber(arr[i].number,
                                arr[i].types || null, arr[i].isDefault || null);
                    }
                }
                break;

            case "emails":
                arr = contactInitDict[attr];
                if (arr) {
                    for (i in arr) {
                        this[attr][i] = new ContactEmailAddress(arr[i].email,
                                arr[i].types || null, arr[i].isDefault || null);
                    }
                }
                break;

            case "birthday":
                this[attr] = new Date(contactInitDict[attr]);
                break;

            case "anniversaries":
                arr = contactInitDict[attr];
                if (arr) {
                    for (i in arr) {
                        this[attr][i] = new ContactAnniversary(arr[i].date,
                                arr[i].label || null);
                    }
                }
                break;

            case "organizations":
                arr = contactInitDict[attr];
                if (arr) {
                    for (i in arr) {
                        this[attr][i] = new ContactOrganization(arr[i]);
                    }
                }
                break;

            case "notes":
            case "groupIds":
                arr = contactInitDict[attr];
                if (arr) {
                    for (i in arr) {
                        this[attr][i] = arr[i];
                    }
                }
                break;

            case "urls":
                arr = contactInitDict[attr];
                if (arr) {
                    for (i in arr) {
                        this[attr][i] = new ContactWebSite(arr[i].url,
                                arr[i].type || null);
                    }
                }
                break;

            default:
                this[attr] = contactInitDict[attr];
                break;
            }
        }

        decorator.Contact(this);
    }

    function Contact_DOMString(stringRepresentation) {
    }

    voc = [Contact_ContactInit, Contact_DOMString];
    t.Contact(arguments, this, voc);
};

module.exports = Contact;

});
define('ripple/platform/tizen/2.0/ContactEmailAddress', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactEmailAddress;

ContactEmailAddress = function (email, types, isDefault) {
    var contactEmailAddress = {};

    t.ContactEmailAddress(arguments, this);

    contactEmailAddress.email     = email;
    contactEmailAddress.isDefault = isDefault || false;
    contactEmailAddress.types     = (types && types[0]) ? types : ["WORK"];

    this.__defineGetter__("email", function () {
        return contactEmailAddress.email;
    });
    this.__defineSetter__("email", function (val) {
        try {
            contactEmailAddress.email = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("isDefault", function () {
        return contactEmailAddress.isDefault;
    });
    this.__defineSetter__("isDefault", function (val) {
        try {
            contactEmailAddress.isDefault = t.boolean(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("types", function () {
        return contactEmailAddress.types;
    });
    this.__defineSetter__("types", function (val) {
        try {
            contactEmailAddress.types = t.DOMString(val, "[]");
        } catch (e) {
        }
    });
};

module.exports = ContactEmailAddress;

});
define('ripple/platform/tizen/2.0/ContactGroup', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactGroup;

ContactGroup = function (name, ringtoneURI, photoURI) {
    var contactGroup = {};

    t.ContactGroup(arguments, this);

    contactGroup.name        = name;
    contactGroup.ringtoneURI = ringtoneURI || null;
    contactGroup.photoURI    = photoURI || null;

    this.__defineGetter__("id", function () {
        return null;
    });

    this.__defineGetter__("addressBookId", function () {
        return null;
    });

    this.__defineGetter__("name", function () {
        return contactGroup.name;
    });
    this.__defineSetter__("name", function (val) {
        try {
            contactGroup.name = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("ringtoneURI", function () {
        return contactGroup.ringtoneURI;
    });
    this.__defineSetter__("ringtoneURI", function (val) {
        try {
            contactGroup.ringtoneURI = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("photoURI", function () {
        return contactGroup.photoURI;
    });
    this.__defineSetter__("photoURI", function (val) {
        try {
            contactGroup.photoURI = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("readOnly", function () {
        return false;
    });
};

module.exports = ContactGroup;

});
define('ripple/platform/tizen/2.0/ContactName', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactName;

ContactName = function (nameInitDict) {
    var contactName = {}, attr;

    t.ContactName(arguments, this);

    contactName.prefix            = null;
    contactName.suffix            = null;
    contactName.firstName         = null;
    contactName.middleName        = null;
    contactName.lastName          = null;
    contactName.nicknames         = [];
    contactName.phoneticFirstName = null;
    contactName.phoneticLastName  = null;

    this.__defineGetter__("prefix", function () {
        return contactName.prefix;
    });
    this.__defineSetter__("prefix", function (val) {
        try {
            contactName.prefix = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("suffix", function () {
        return contactName.suffix;
    });
    this.__defineSetter__("suffix", function (val) {
        try {
            contactName.suffix = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("firstName", function () {
        return contactName.firstName;
    });
    this.__defineSetter__("firstName", function (val) {
        try {
            contactName.firstName = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("middleName", function () {
        return contactName.middleName;
    });
    this.__defineSetter__("middleName", function (val) {
        try {
            contactName.middleName = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("lastName", function () {
        return contactName.lastName;
    });
    this.__defineSetter__("lastName", function (val) {
        try {
            contactName.lastName = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("nicknames", function () {
        return contactName.nicknames;
    });
    this.__defineSetter__("nicknames", function (val) {
        try {
            contactName.nicknames = t.DOMString(val, "[]");
        } catch (e) {
        }
    });

    this.__defineGetter__("phoneticFirstName", function () {
        return contactName.phoneticFirstName;
    });
    this.__defineSetter__("phoneticFirstName", function (val) {
        try {
            contactName.phoneticFirstName = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("phoneticLastName", function () {
        return contactName.phoneticLastName;
    });
    this.__defineSetter__("phoneticLastName", function (val) {
        try {
            contactName.phoneticLastName = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("displayName", function () {
        return null;
    });

    if (nameInitDict) {
        for (attr in nameInitDict) {
            contactName[attr] = nameInitDict[attr];
        }
    }
};

module.exports = ContactName;

});
define('ripple/platform/tizen/2.0/ContactOrganization', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactOrganization;

ContactOrganization = function (orgInitDict) {
    var contactOrganization = {}, attr;

    t.ContactOrganization(arguments, this);

    contactOrganization.name       = null;
    contactOrganization.department = null;
    contactOrganization.title      = null;
    contactOrganization.role       = null;
    contactOrganization.logoURI    = null;

    this.__defineGetter__("name", function () {
        return contactOrganization.name;
    });
    this.__defineSetter__("name", function (val) {
        try {
            contactOrganization.name = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("department", function () {
        return contactOrganization.department;
    });
    this.__defineSetter__("department", function (val) {
        try {
            contactOrganization.department = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("title", function () {
        return contactOrganization.title;
    });
    this.__defineSetter__("title", function (val) {
        try {
            contactOrganization.title = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("role", function () {
        return contactOrganization.role;
    });
    this.__defineSetter__("role", function (val) {
        try {
            contactOrganization.role = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("logoURI", function () {
        return contactOrganization.logoURI;
    });
    this.__defineSetter__("logoURI", function (val) {
        try {
            contactOrganization.logoURI = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    if (orgInitDict) {
        for (attr in orgInitDict) {
            contactOrganization[attr] = orgInitDict[attr];
        }
    }
};

module.exports = ContactOrganization;

});
define('ripple/platform/tizen/2.0/ContactPhoneNumber', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactPhoneNumber;

ContactPhoneNumber = function (number, types, isDefault) {
    var contactPhoneNumber = {};

    t.ContactPhoneNumber(arguments, this);

    contactPhoneNumber.number    = number;
    contactPhoneNumber.isDefault = isDefault || false;
    contactPhoneNumber.types     = (types && types[0]) ? types : ["VOICE"];

    this.__defineGetter__("number", function () {
        return contactPhoneNumber.number;
    });
    this.__defineSetter__("number", function (val) {
        try {
            contactPhoneNumber.number = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("isDefault", function () {
        return contactPhoneNumber.isDefault;
    });
    this.__defineSetter__("isDefault", function (val) {
        try {
            contactPhoneNumber.isDefault = t.boolean(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("types", function () {
        return contactPhoneNumber.types;
    });
    this.__defineSetter__("types", function (val) {
        try {
            contactPhoneNumber.types = t.DOMString(val, "[]");
        } catch (e) {
        }
    });
};

module.exports = ContactPhoneNumber;

});
define('ripple/platform/tizen/2.0/ContactRef', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactRef;

ContactRef = function (addressBookId, contactId) {
    var contactRef = {};

    t.ContactRef(arguments, this);

    contactRef.addressBookId = addressBookId;
    contactRef.contactId     = contactId;

    this.__defineGetter__("addressBookId", function () {
        return contactRef.addressBookId;
    });
    this.__defineSetter__("addressBookId", function (val) {
        try {
            contactRef.addressBookId = t.AddressBookId(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("contactId", function () {
        return contactRef.contactId;
    });
    this.__defineSetter__("contactId", function (val) {
        try {
            contactRef.contactId = t.ContactId(val);
        } catch (e) {
        }
    });
};

module.exports = ContactRef;

});
define('ripple/platform/tizen/2.0/ContactWebSite', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactWebSite;

ContactWebSite = function (url, type) {
    var contactWebSite = {};

    t.ContactWebSite(arguments, this);

    contactWebSite.url  = url;
    contactWebSite.type = type || "HOMEPAGE";

    this.__defineGetter__("url", function () {
        return contactWebSite.url;
    });
    this.__defineSetter__("url", function (val) {
        try {
            contactWebSite.url = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("type", function () {
        return contactWebSite.type;
    });
    this.__defineSetter__("type", function (val) {
        try {
            contactWebSite.type = t.DOMString(val);
        } catch (e) {
        }
    });
};

module.exports = ContactWebSite;

});
define('ripple/platform/tizen/2.0/Conversation', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 utils = require('ripple/utils');

module.exports = function (opt) {
    var conv = {}, priv = utils.copy(opt);

    conv.__defineGetter__("id", function () {
        return priv.id;
    });
    conv.__defineGetter__("type", function () {
        return priv.type;
    });
    conv.__defineGetter__("timestamp", function () {
        return priv.timestamp;
    });
    conv.__defineGetter__("messageCount", function () {
        return priv.messageCount;
    });
    conv.__defineGetter__("unreadMessages", function () {
        return priv.unreadMessages;
    });
    conv.__defineGetter__("preview", function () {
        return priv.preview;
    });
    conv.__defineGetter__("subject", function () {
        return priv.subject;
    });
    conv.__defineGetter__("isRead", function () {
        return priv.isRead;
    });
    conv.__defineGetter__("from", function () {
        return priv.from;
    });
    conv.__defineGetter__("to", function () {
        return priv.to;
    });
    conv.__defineGetter__("cc", function () {
        return priv.cc;
    });
    conv.__defineGetter__("bcc", function () {
        return priv.bcc;
    });
    conv.__defineGetter__("lastMessageId", function () {
        return priv.lastMessageId;
    });
    return conv;
};

});
define('ripple/platform/tizen/2.0/DeviceMotionEvent', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    Event = require('ripple/platform/tizen/2.0/EventBase');

module.exports = function () {
    var _self = {
            acceleration: {
                x: null,
                y: null,
                z: null
            },
            accelerationIncludingGravity: {
                x: null,
                y: null,
                z: null
            },
            rotationRate: {
                alpha: null,
                beta: null,
                gamma: null
            },
            interval: 0
        };

    Event.call(this);

    this.__defineGetter__("acceleration", function () {
        return _self.acceleration;
    });

    this.__defineGetter__("accelerationIncludingGravity", function () {
        return _self.accelerationIncludingGravity;
    });

    this.__defineGetter__("rotationRate", function () {
        return _self.rotationRate;
    });

    this.__defineGetter__("interval", function () {
        return _self.interval;
    });

    this.initAccelerometerEvent = function (accelerometerType, accelerometerBubbles, accelerometerCancelable,
                                            accelerationData, accelerationGData, rotationRateData, intervalValue) {
        this.initEvent(accelerometerType, accelerometerBubbles, accelerometerCancelable);

        _self.acceleration = utils.copy(accelerationData);
        _self.accelerationIncludingGravity = utils.copy(accelerationGData);
	//sensor value sync with tizen target 
	_self.accelerationIncludingGravity.x = -_self.accelerationIncludingGravity.x;
	_self.accelerationIncludingGravity.y = -_self.accelerationIncludingGravity.y;
        _self.rotationRate = utils.copy(rotationRateData);
        _self.interval = intervalValue;
    };
};


});
define('ripple/platform/tizen/2.0/DeviceOrientationEvent', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 Event = require('ripple/platform/tizen/2.0/EventBase');

module.exports = function () {
    var _self = {
            alpha: null,
            beta: null,
            gamma: null,
            absolute: false,
        };

    Event.call(this);

    this.__defineGetter__("alpha", function () {
        return _self.alpha;
    });

    this.__defineGetter__("beta", function () {
        return _self.beta;
    });

    this.__defineGetter__("gamma", function () {
        return _self.gamma;
    });

    this.__defineGetter__("absolute", function () {
        return _self.absolute;
    });

    this.initDeviceOrientationEvent = function (orientationType, orientationBubbles, orientationCancelable,
                                               alphaData, betaData, gammaData, isAbsolute) {
        this.initEvent(orientationType, orientationBubbles, orientationCancelable);

        _self.alpha    = alphaData;
        _self.beta     = betaData;
        _self.gamma    = gammaData;
        _self.absolute = isAbsolute;
    };
};


});
define('ripple/platform/tizen/2.0/DownloadRequest', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    DownloadRequest;

DownloadRequest = function (url, destination, fileName, networkType,
        httpHeader) {
    var downloadRequest = {};

    t.DownloadRequest(arguments, this);

    this.__defineGetter__("url", function () {
        return downloadRequest.url;
    });
    this.__defineSetter__("url", function (val) {
        try {
            downloadRequest.url = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("networkType", function () {
        return downloadRequest.networkType;
    });
    this.__defineSetter__("networkType", function (val) {
        try {
            downloadRequest.networkType = t.DownloadNetworkType(val, "?");
        } catch (e) {
        }
    });

    this.destination            = destination || "";
    this.fileName               = fileName || "";
    this.httpHeader             = httpHeader || {};

    downloadRequest.url         = url;
    downloadRequest.networkType = networkType || "ALL";
};

module.exports = DownloadRequest;

});
define('ripple/platform/tizen/2.0/EventBase', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function () {
    var _self = {
        CAPTURING_PHASE: 1,
        AT_TARGET:  2,
        BUBBLING_PHASE: 3,

        type: '',
        target: null, //new EventTarget(),
        currentTarget: null, //new EventTarget(),
        eventPhase: 0,
        bubbles: false,
        cancelable: false,
        timeStamp: 0
    };

    this.__defineGetter__("type", function () {
        return _self.type;
    });

    this.__defineGetter__("target", function () {
        return _self.target;
    });

    this.__defineGetter__("currentTarget", function () {
        return _self.currentTarget;
    });

    this.__defineGetter__("eventPhase", function () {
        return _self.eventPhase;
    });

    this.__defineGetter__("bubbles", function () {
        return _self.bubbles;
    });

    this.__defineGetter__("cancelable", function () {
        return _self.cancelable;
    });

    this.__defineGetter__("timeStamp", function () {
        return _self.timeStamp;
    });

    this.stopPropagation = function () {};

    this.preventDefault = function () {};

    this.initEvent = function (eventTypeArg, canBubbleArg, cancelableArg) {
        _self.type = eventTypeArg;
        _self.bubbles = canBubbleArg;
        _self.cancelable = cancelableArg;

        _self.timeStamp = (new Date()).getTime();
    };

    return _self;
};


});
define('ripple/platform/tizen/2.0/GeoCircleBounds', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (_center, _radius) {
    var center, radius;
    center = _center || null;
    radius = _radius || 0;

    this.__defineGetter__("center", function () {
        return center;
    });

    this.__defineGetter__("radius", function () {
        return radius;
    });
};

});
define('ripple/platform/tizen/2.0/GeoPolyBounds', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (_points) {
    var points = _points || [];

    this.__defineGetter__("points", function () {
        return points;
    });
};

});
define('ripple/platform/tizen/2.0/GeoRectBounds', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (_southWest, _northEast) {
    var southWest, northEast;
    southWest = _southWest || null;
    northEast = _northEast || null;

    this.__defineGetter__("southWest", function () {
        return southWest;
    });

    this.__defineGetter__("northEast", function () {
        return northEast;
    });
};

});
define('ripple/platform/tizen/2.0/GeocodeOptions', function (require, exports, module) {
/*      
 *  Copyright 2012 Intel Corporation.
 *  
 * 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 errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    SortMode = require('ripple/platform/tizen/2.0/SortMode');

module.exports = function (_sortMode, _maxResults) {
    var _self;
    if (_sortMode !== null && _sortMode !== undefined) {
        if (typeof _sortMode !== "object") {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
        try {
            new SortMode(_sortMode.attributeName, _sortMode.order);
        } catch (e) {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
    }
    if (_maxResults !== null && _maxResults !== undefined) {
        if (typeof _maxResults !== "number") {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
    }

    _self = {
        sortMode : _sortMode,
        maxResults : _maxResults || 0
    };

    return _self;
};


});
define('ripple/platform/tizen/2.0/GeocodeResult', function (require, exports, module) {
/*      
 *  Copyright 2012 Intel Corporation.
 *  
 * 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 SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates');

module.exports = function (lat, lon) {
    var _self, _coordinates, jsonStr, jsonObj;

    _coordinates = new SimpleCoordinates(lat, lon);

    jsonObj = {
        "type" : "Point",
        "coordinates" : [lat, lon]
    };

    jsonStr = JSON.stringify(jsonObj);

    _self = {
        coordinates : _coordinates,
        toGeoJSON : function () {
            return jsonStr;
        }
    };
    return _self;
};


});
define('ripple/platform/tizen/2.0/GeometryFilter', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (criteria, geometry) {
    var _self;

    _self = {
        criteria: criteria,
        geometry: geometry
    };

    return _self;
};

});
define('ripple/platform/tizen/2.0/Message', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 msg_utils = require('ripple/platform/tizen/2.0/msg_utils'),
    MessageBody = require('ripple/platform/tizen/2.0/MessageBody'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException');

module.exports = function (type, messageInit) {
    var _id = null, _serviceId = null, _conversationId = null,
        _folderId = null, _type = type, _timestamp = null,
        _from = null, _hasAttachment = false, _messageStatus = null,
        msg = {};

    if (messageInit !== undefined && messageInit !== null) {
        if (msg_utils.setMsg(messageInit, msg) === false) {
            throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
        }
        if (messageInit.priv !== undefined) {
            /* secret constructor for PrivateMessage */
            _id = messageInit.priv.id;
            _serviceId = messageInit.priv.serviceId;
            _conversationId = messageInit.priv.conversationId;
            _folderId = messageInit.priv.folderId;
            _type = messageInit.priv.type;
            _timestamp = new Date(messageInit.priv.timestamp);
            _from = messageInit.priv.from;
            _hasAttachment = messageInit.priv.hasAttachment;
            _messageStatus = messageInit.priv.messageStatus;
        }
        msg.body = new MessageBody(_id, msg.body.loaded, msg.body.plainBody, msg.body.htmlBody, []);
    }

    msg.__defineGetter__("id", function () {
        return _id;
    });
    msg.__defineGetter__("conversationId", function () {
        return _conversationId;
    });
    msg.__defineGetter__("folderId", function () {
        return _folderId;
    });
    msg.__defineGetter__("type", function () {
        return _type;
    });
    msg.__defineGetter__("timestamp", function () {
        return _timestamp;
    });
    msg.__defineGetter__("from", function () {
        return _from;
    });
    msg.__defineGetter__("hasAttachment", function () {
        return _hasAttachment;
    });
    msg.__defineGetter__("messageStatus", function () {
        return _messageStatus;
    });
    return msg;
};

});
define('ripple/platform/tizen/2.0/MessageBody', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (id, isloaded, _plainbody, _htmlbody, inlineattachments) {
    var msgbody, _id = id, _loaded = isloaded;
    msgbody = {
        plainBody: _plainbody,
        htmlBody: _htmlbody,
        inlineAttachments: [] // TODO: not support attachment yet
    };
    msgbody.__defineGetter__("messageId", function () {
        return _id;
    });
    msgbody.__defineGetter__("loaded", function () {
        return _loaded;
    });
    return msgbody;
};

});
define('ripple/platform/tizen/2.0/MessageFolder', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (opt) {
    var folder = {}, _id = opt.id, _parentId = null, _serviceId = opt.serviceId,
        _contentType = opt.contentType, _name = opt.id, _path = opt.path,
        _type = opt.type, _synchronizable = opt.synchronizable;

    folder.name = _name;
    folder.synchronizable = _synchronizable;
    
    folder.__defineGetter__("id", function () {
        return _id;
    });
    folder.__defineGetter__("parentId", function () {
        return _parentId;
    });
    folder.__defineGetter__("serviceId", function () {
        return _serviceId;
    });
    folder.__defineGetter__("contentType", function () {
        return _contentType;
    });
    folder.__defineGetter__("path", function () {
        return _path;
    });
    folder.__defineGetter__("type", function () {
        return _type;
    });
    return folder;
};

});
define('ripple/platform/tizen/2.0/MessageStorage', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 _self,
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    Message = require('ripple/platform/tizen/2.0/Message'),
    Conversation = require('ripple/platform/tizen/2.0/Conversation'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    PrivMessage = require('ripple/platform/tizen/2.0/PrivMessage'),
    MessageFolder = require('ripple/platform/tizen/2.0/MessageFolder'),
    msg_utils = require('ripple/platform/tizen/2.0/msg_utils'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    t = require('ripple/platform/tizen/2.0/typedef'),
    TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
    TIZEN_DEFAULT_MSG_FROM = {"messaging.sms": "13572468",
                              "messaging.mms": "13572468",
                              "messaging.email": "tizen.simulator@tizen.org"};

_self = function (messages, security_check) {
    var message_storage = {},
        _findMessage, _findConversation,
        _processMessageChange, _processConversationChange,
        _folders = {}, folderOpt = {},
        _msgListeners = {},
        _convListeners = {},
        _folderListeners = {},
        _security_check = security_check,
        _messages = messages;

    // init folders
    folderOpt = {id: "INBOX", serviceId: _messages.id, contentType: _messages.type,
                 path: "inbox", type: "INBOX", synchronizable: true};
    _folders.INBOX = new MessageFolder(folderOpt);
    folderOpt = {id: "OUTBOX", serviceId: _messages.id, contentType: _messages.type,
                 path: "outbox", type: "OUTBOX", synchronizable: false};
    _folders.OUTBOX = new MessageFolder(folderOpt);
    folderOpt = {id: "DRAFT", serviceId: _messages.id, contentType: _messages.type,
                 path: "draft", type: "DRAFTS", synchronizable: false};
    _folders.DRAFT = new MessageFolder(folderOpt);
    folderOpt = {id: "SENTBOX", serviceId: _messages.id, contentType: _messages.type,
                 path: "sentbox", type: "SENTBOX", synchronizable: false};
    _folders.SENTBOX = new MessageFolder(folderOpt);

    event.on("MsgRecv", function (msg) {
        // msg sent from panel to module
        if (msg.priv.type !== _messages.type ||
            msg.priv.serviceId !== _messages.id) {
            return;
        }
        // trigger Message add
        _processMessageChange([msg], "add");
        _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);

        if (_messages.conv[msg.priv.conversationId].messageCount === 1) {
            _processConversationChange([_messages.conv[msg.priv.conversationId]], "add");
        } else {
            _processConversationChange([_messages.conv[msg.priv.conversationId]], "update");
        }
    });

    event.on("OutsideMessageReceived", function (msg) {
        // msg sent from module to panel
        if (msg.msg.priv.type !== _messages.type ||
            msg.msg.priv.serviceId !== _messages.id) {
            return;
        }
        // trigger conversation/Message add
        _processMessageChange([msg.msg], "add");
        _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);

        if (_messages.conv[msg.msg.priv.conversationId].messageCount === 1) {
            _processConversationChange([_messages.conv[msg.msg.priv.conversationId]], "add");
        } else {
            _processConversationChange([_messages.conv[msg.msg.priv.conversationId]], "update");
        }
    });

    event.on("MsgSentRst", function (rst) {
        // ACK from panel when module sent a msg to panel
        if (rst.priv.type !== _messages.type ||
            rst.priv.serviceId !== _messages.id) {
            return;
        }
        // trigger conversation/Message Update
        _processMessageChange([rst], "update");
        _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
        _processConversationChange([_messages.conv[rst.priv.conversationId]], "update");
    });

    _findMessage = function (src, filter) {
        var ret, foo = {};
        switch (filter.attributeName) {
        case "type":
            foo[filter.attributeName] = _messages.type;
            ret = tizen1_utils.matchAttributeFilter([foo],
                      filter.attributeName, filter.matchFlag, filter.matchValue);
            if (ret.length === 0) {
                ret = [];
            } else {
                // make an array
                ret = utils.filter(src, function () { return true; });
            }
            break;
        case "id":
        case "conversationId":
        case "folderId":
        case "from":
        case "messageStatus":
            ret = tizen1_utils.matchAttributeFilter(src,
                      "priv." + filter.attributeName,
                      filter.matchFlag, filter.matchValue);
            break;
        case "hasAttachment":
            if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
                throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
                              "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
            }
            ret = tizen1_utils.matchAttributeBooleanFilter(src,
                      "priv." + filter.attributeName, filter.matchValue);
            break;
        case "to":
        case "cc":
        case "bcc":
            ret = tizen1_utils.matchAttributeArrayFilter(src,
                      filter.attributeName, filter.matchFlag, filter.matchValue);
            break;
        case "body":
            ret = tizen1_utils.matchAttributeFilter(src,
                      filter.attributeName + ".plainBody",
                      filter.matchFlag, filter.matchValue);
            break;
        case "subject":
        case "inResponseTo":
            ret = tizen1_utils.matchAttributeFilter(src, filter.attributeName,
                      filter.matchFlag, filter.matchValue);
            break;
        case "isRead":
        case "isHighPriority":
            if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
                throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
                              "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
            }
            ret = tizen1_utils.matchAttributeBooleanFilter(src,
                      filter.attributeName, filter.matchValue);
            break;
        case "timestamp":
            ret = tizen1_utils.matchAttributeRangeFilter(src,
                      "priv." + filter.attributeName,
                      filter.initialValue, filter.endValue);
            break;

        case "attachments":
            throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR,
                                  "not support find by " + filter.attributeName));
        default:
            throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
                                   "invalid attributeName"));
        }
        return ret;
    };

    _processMessageChange = function (messages, type) {
        var i, j, ret = [], tmp,
            operation = {"add": "messagesadded",
                         "remove": "messagesremoved",
                         "update": "messagesupdated"};

        for (i in _msgListeners) {
            ret = [];
            if (_msgListeners[i].filter !== null) {
                tmp = _findMessage(messages, _msgListeners[i].filter);
            } else {
                tmp = messages;
            }
            if (tmp.length !== 0) {
                for (j = 0; j < tmp.length; j++) {
                    ret.push(new Message(tmp[j].priv.type, tmp[j]));
                }
                _msgListeners[i].callback[operation[type]](ret);
            }
        }
    };

    _findConversation = function (src, filter) {
        var ret, foo = {};
        switch (filter.attributeName) {
        case "type":
            foo[filter.attributeName] = _messages.type;
            ret = tizen1_utils.matchAttributeFilter([foo], filter.attributeName, filter.matchFlag, filter.matchValue);
            if (ret.length === 0) {
                ret = [];
            } else {
                // make an array
                ret = utils.filter(_messages.conv, function () { return true; });
            }
            break;
        case "id":
        case "preview":
        case "subject":
        case "from":
        case "lastMessageId":
            ret = tizen1_utils.matchAttributeFilter(src, filter.attributeName, filter.matchFlag, filter.matchValue);
            break;
        case "to":
        case "cc":
        case "bcc":
            ret = tizen1_utils.matchAttributeArrayFilter(src,
                      filter.attributeName, filter.matchFlag, filter.matchValue);
            break;
        case "isRead":
            if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
                throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
                              "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
            }
            ret = tizen1_utils.matchAttributeBooleanFilter(src,
                      filter.attributeName, filter.matchValue);
            break;
        case "timestamp":
        case "messageCount":
        case "unreadMessages":
            ret = tizen1_utils.matchAttributeRangeFilter(src,
                      filter.attributeName,
                      filter.initialValue, filter.endValue);
            break;
        default:
            throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
                                   "invalid attributeName"));
        }
        return ret;
    };

    _processConversationChange = function (conversations, type) {
        var i, j, ret = [], tmp,
            operation = {"add": "conversationsadded",
                         "remove": "conversationsremoved",
                         "update": "conversationsupdated"};

        for (i in _convListeners) {
            ret = [];
            if (_convListeners[i].filter !== null) {
                tmp = _findConversation(conversations, _convListeners[i].filter);
            } else {
                tmp = conversations;
            }
            if (tmp.length !== 0) {
                for (j = 0; j < tmp.length; j++) {
                    ret.push(new Conversation(tmp[j]));
                }
                _convListeners[i].callback[operation[type]](ret);
            }
        }
    };

    message_storage = {
        addDraftMessage: function (_msg, onSuccess, onError) {
            var m, msg = {}, opt = {};

            if (_security_check.write === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (msg_utils.setMsg(_msg, msg) === false) {
                throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
            }
            if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            opt.id = Math.uuid(8, 16);
            opt.serviceId = _messages.id;
            if ((msg.inResponseTo !== null) &&
                (_messages.msg[msg.inResponseTo] !== undefined)) {
                opt.conversationId = _messages.msg[msg.inResponseTo].conversationId;
            } else {
                opt.conversationId = opt.id;
            }
            opt.folderId = "DRAFTS";
            opt.type = _messages.type;
            opt.timestamp = new Date();
            opt.from = TIZEN_DEFAULT_MSG_FROM[_messages.type];
            if (msg.attachments.length === 0) {
                opt.hasAttachment = false;
            } else {
                opt.hasAttachment = true;
            }
            opt.messageStatus = "DRAFT";

            m = new PrivMessage(msg, opt);
            _messages.msg[m.priv.id] = m;  // local
            msg_utils.saveMsg(_messages.msg[m.priv.id]);  // remote
            // trigger message add
            _processMessageChange([m], "add");
            if (onSuccess) {
                setTimeout(function () {
                    onSuccess(new Message(m.priv.type, m));
                }, 1);
            }
        },

        removeMessages: function (messages, onSuccess, onError) {
            var i, c, na_msg = "", msgToDel = [], convToDel = {}, delConv = [], updateConv = [];

            if (_security_check.write === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (tizen1_utils.isValidArray(messages) === false) {
                throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
            }
            if (messages.length === 0) {
                throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
            }
            if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }

            _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
            for (i = 0; i < messages.length; i++) {
                if (_messages.msg[messages[i].id] === undefined) {
                    na_msg += messages[i].id + ", ";
                } else {
                    msgToDel.push(utils.copy(_messages.msg[messages[i].id]));
                }
                if (_messages.conv[messages[i].conversationId] !== undefined) {
                    convToDel[messages[i].conversationId] = _messages.conv[messages[i].conversationId];
                }
            }
            if (na_msg === "") {
                for (i = 0; i < messages.length; i++) {
                    // conversation updated at remote when msg is deleted
                    msg_utils.delMsg(_messages.msg[messages[i].id]); // remote
                    delete _messages.msg[messages[i].id]; // local
                }
                // update conversation
                _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
                for (c in convToDel) {
                    if (_messages.conv[c] === undefined) {
                        delConv.push(convToDel[c]);
                    } else {
                        updateConv.push(convToDel[c]);
                    }
                }
                if (onSuccess) {
                    setTimeout(function () {
                        onSuccess();
                    }, 1);
                }
                // trigger messages remove
                _processMessageChange(msgToDel, "remove");
                if (delConv.length > 0) {
                    _processConversationChange(delConv, "remove");
                }
                if (updateConv.length > 0) {
                    _processConversationChange(updateConv, "update");
                }
            } else {
                if (onError) {
                    setTimeout(function () {
                        onError(new WebAPIError(errorcode.NOT_FOUND_ERR,
                                na_msg + "not found !!"));
                    }, 1);
                }
            }
        },

        updateMessages: function (messages, onSuccess, onError) {
            var i, m, updateConv = {}, updateMsg = [], tmp,
                na_msg = "", invalid_msg = "";

            if (_security_check.write === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (tizen1_utils.isValidArray(messages) === false) {
                throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
            }
            if (messages.length === 0) {
                throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
            }
            // update conversation
            _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
            for (i = 0; i < messages.length; i++) {
                m = _messages.msg[messages[i].id];
                if (m === undefined) {
                    // msg not found
                    na_msg += messages[i].id + ", ";
                } else {
                    if (m.priv.messageStatus === "DRAFT") {
                        tmp = {};
                        // allow update all writeable attr in draft
                        if (msg_utils.setMsg(messages[i], tmp) === false) {
                            invalid_msg += messages[i].id + ", ";
                        }
                    }
                }
            }
            if (invalid_msg !== "") {
                if (onError) {
                    setTimeout(function () {
                        onError(new WebAPIError(errorcode.INVALID_VALUES_ERR,
                                invalid_msg + "invalid values"));
                    }, 1);
                }
                return;
            }
            if (na_msg !== "") {
                if (onError) {
                    setTimeout(function () {
                        onError(new WebAPIError(errorcode.NOT_FOUND_ERR,
                                na_msg + "not found !!"));
                    }, 1);
                }
                return;
            }

            for (i = 0; i < messages.length; i++) {
                m = _messages.msg[messages[i].id];
                if (m.priv.messageStatus === "DRAFT") {
                    msg_utils.setMsg(messages[i], m);
                    updateMsg.push(m);
                } else {
                    // only allow update isRead in other folders
                    if (typeof messages[i].isRead === 'boolean') {
                        m.isRead = messages[i].isRead;
                        updateMsg.push(m);
                        updateConv[m.priv.conversationId] = _messages.conv[m.priv.conversationId];
                    }
                }
                msg_utils.saveMsg(m);
            }
            if (onSuccess) {
                setTimeout(function () {
                    onSuccess();
                }, 1);
            }

            // trigger Message update
            _processMessageChange(updateMsg, "update");

            _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);
            // trigger conversation update
            _processConversationChange(updateConv, "update");
        },

        findMessages: function (filter, onSuccess, onError, sort, _limit, _offset) {
            var i, tmp, offset, limit, ret = [];

            if (_security_check.read === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (!(new TypeCoerce(t.MessageArraySuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (sort && !(new TypeCoerce(t.SortMode)).match(sort)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (_limit && !(new TypeCoerce(t.long)).match(_limit)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (_offset && !(new TypeCoerce(t.long)).match(_offset)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            tmp = _findMessage(_messages.msg, filter);

            if (_offset) {
                offset = _offset;
            } else {
                offset = 0;
            }
            if (_limit) {
                limit = Math.min(_limit + offset, tmp.length);
            } else {
                limit = tmp.length;
            }
            for (i = offset; i < limit; i++) {
                ret.push(new Message(tmp[i].priv.type, tmp[i]));
            }
            setTimeout(function () {
                onSuccess(ret);
            }, 1);
        },

        findConversations: function (filter, onSuccess, onError, sort, _limit, _offset) {
            var i, tmp, offset, limit, ret = [];

            if (_security_check.read === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (!(new TypeCoerce(t.MessageConversationArraySuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (sort && !(new TypeCoerce(t.SortMode)).match(sort)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (_limit && !(new TypeCoerce(t.long)).match(_limit)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (_offset && !(new TypeCoerce(t.long)).match(_offset)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            // download conversation
            _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);

            tmp = _findConversation(_messages.conv, filter);

            if (_offset) {
                offset = _offset;
            } else {
                offset = 0;
            }
            if (_limit) {
                limit = Math.min(_limit + offset, tmp.length);
            } else {
                limit = tmp.length;
            }
            for (i = offset; i < limit; i++) {
                ret.push(new Conversation(tmp[i]));
            }
            setTimeout(function () {
                onSuccess(ret);
            }, 1);
        },

        removeConversations: function (conversations, onSuccess, onError) {
            var i, m, na_msg = "", retConv = [], removeMsg = [];

            if (_security_check.write === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (onSuccess && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            // download conversation
            _messages.conv = msg_utils.loadConv(_messages.type, _messages.id);

            if (tizen1_utils.isValidArray(conversations) === false) {
                throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
            }
            if (conversations.length === 0) {
                throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
            }
            if ((onSuccess && typeof onSuccess !== "function") ||
                (onError && typeof onError !== "function")) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }

            for (i = 0; i < conversations.length; i++) {
                if (_messages.conv[conversations[i].id] === undefined) {
                    na_msg += conversations[i].id + ", ";
                } else {
                    retConv.push(_messages.conv[conversations[i].id]);
                    for (m in _messages.msg) {
                        if (_messages.msg[m].priv.conversationId === conversations[i].id) {
                            removeMsg.push(_messages.msg[m]);
                        }
                    }
                }
            }
            if (na_msg === "") {
                for (i = 0; i < removeMsg.length; i++) {
                    // conversation updated at remote
                    msg_utils.delMsg(removeMsg[i]);  // remote
                    delete _messages.msg[removeMsg[i].priv.id]; // local
                }
                // trigger msg(retMsg)/conv(retConv) delete update
                _processMessageChange(removeMsg, "remove");
                _processConversationChange(retConv, "remove");
                if (onSuccess) {
                    setTimeout(function () {
                        onSuccess();
                    }, 1);
                }
            } else {
                if (onError) {
                    setTimeout(function () {
                        onError(new WebAPIError(errorcode.NOT_FOUND_ERR,
                                na_msg + "not found !!"));
                    }, 1);
                }
            }
        },

        findFolders: function (filter, onSuccess, onError) {
            var ret = [], tmp, i;

            if (_security_check.read === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (!(new TypeCoerce(t.MessageFolderArraySuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            switch (filter.attributeName) {
            case "id":
            case "serviceId":
            case "contentType":
            case "name":
            case "path":
            case "type":
                tmp = tizen1_utils.matchAttributeFilter(_folders,
                          filter.attributeName, filter.matchFlag,
                          filter.matchValue);
                break;
            case "synchronizable":
                if (filter.matchFlag !== "EXACTLY" ||
                    typeof filter.matchValue !== "boolean") {
                    throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
                                  "Support only matchFlag === 'EXACTLY' and typeof matchValue === 'boolean'"));
                }
                tmp = tizen1_utils.matchAttributeBooleanFilter(_folders,
                          filter.attributeName, filter.matchValue);
                break;
            case "parentId":
                if (filter.matchValue === null) {
                    tmp = utils.filter(_folders, function (o) { return o.parentId === null; });
                } else {
                    tmp = tizen1_utils.matchAttributeFilter(_folders,
                              filter.attributeName, filter.matchValue);
                }
                break;
            default:
                throw (new WebAPIException(errorcode.INVALID_VALUES_ERR,
                                       "invalid attributeName"));
            }
            for (i = 0; i < tmp.length; i++) {
                ret.push(new MessageFolder(tmp[i]));
            }
            setTimeout(function () {
                onSuccess(ret);
            }, 1);
        },

        addMessagesChangeListener: function (msgCallback, filter) {
            var watchId, msgListener = {};

            if (_security_check.read === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (!(new TypeCoerce(t.MessagesChangeCallback)).match(msgCallback)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (filter && !(new TypeCoerce(t.AbstractFilter)).match(filter)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }

            watchId = Number(Math.uuid(8, 10));
            msgListener.callback = msgCallback;
            msgListener.filter = filter || null;
            _msgListeners[watchId] = msgListener;
            return watchId;
        },

        addConversationsChangeListener: function (convCallback, filter) {
            var watchId, convListener = {};

            if (_security_check.read === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (!(new TypeCoerce(t.MessageConversationsChangeCallback)).match(convCallback)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (filter && !(new TypeCoerce(t.AbstractFilter)).match(filter)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }

            watchId = Number(Math.uuid(8, 10));
            convListener.callback = convCallback;
            convListener.filter = filter || null;
            _convListeners[watchId] = convListener;
            return watchId;
        },

        addFoldersChangeListener: function (callback, filter) {
            var watchId, folderListener = {};

            if (_security_check.read === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (!(new TypeCoerce(t.MessageFoldersChangeCallback)).match(callback)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (filter && !(new TypeCoerce(t.AbstractFilter)).match(filter)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }

            watchId = Number(Math.uuid(8, 10));
            folderListener.callback = callback;
            folderListener.filter = filter || null;
            _folderListeners[watchId] = folderListener;
            return watchId;
        },

        removeChangeListener: function (watchid) {
            if (_security_check.read === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (_msgListeners[watchid] !== undefined) {
                delete _msgListeners[watchid];
                return;
            }
            if (_convListeners[watchid] !== undefined) {
                delete _convListeners[watchid];
                return;
            }
            if (_folderListeners[watchid] !== undefined) {
                delete _folderListeners[watchid];
                return;
            }
        }

    };
    return message_storage;
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/MessagingService', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    deviceSettings = require('ripple/deviceSettings'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    PrivMessage = require('ripple/platform/tizen/2.0/PrivMessage'),
    MessageStorage = require('ripple/platform/tizen/2.0/MessageStorage'),
    msg_utils = require('ripple/platform/tizen/2.0/msg_utils'),
    t = require('ripple/platform/tizen/2.0/typedef'),
    TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
    _self,
    TIZEN_DEFAULT_MSG_FROM = {"messaging.sms": "13572468",
                              "messaging.mms": "13572468",
                              "messaging.email": "tizen.simulator@tizen.org"},
    INCOMING_TYPE = {"messaging.sms": "sms",
                     "messaging.mms": "mms",
                     "messaging.email": "email"};

_self = function (id, type, security_check) {
    var msg_service = {},
        pendingOperations = {},
        _msgSending = {},
        _receivedEmails = [],
        _id = id,
        _type = type,
        _security_check = security_check,
        _from = TIZEN_DEFAULT_MSG_FROM[_type],
        _incomingType = INCOMING_TYPE[_type],
        _messages = msg_utils.loadMsg(_type, _id),
        _messageStorage = new MessageStorage(_messages, _security_check);

    event.on("MessageSent", function (rst) {
        var i, rsp_ok = [], rsp_fail = [];
        // rst.msg is the real msg in module
        if (rst.msg.priv.type !== _type ||
            rst.msg.priv.serviceId !== _id) {
            // not my msg
            return;
        }
        if (_msgSending[rst.id] !== undefined) {
            for (i in rst) {
                if ((i !== "id") && (i !== "msg")) {
                    if (rst[i] === true) {
                        rsp_ok.push(i);
                    } else {
                        rsp_fail.push(i);
                    }
                }
            }
            rst.msg.priv.folderId = "SENTBOX";
            if (rsp_fail.length === 0) {
                rst.msg.priv.messageStatus = "SENT";
                _msgSending[rst.id].onsuccess(rsp_ok);
            } else {
                rst.msg.priv.messageStatus = "FAILED";
                _msgSending[rst.id].onerror(rsp_fail);
            }
            msg_utils.saveMsg(rst.msg);  // sync to remote
            event.trigger("MsgSentRst", [rst.msg]);
            delete _msgSending[rst.id];
        }
    });

    event.on("MessageReceived", function (rst) {
        var m, opt = {}, msgInit = {}, msg = {};

        if (rst.type !== _incomingType) {
            // not my msg
            return;
        }
        msgInit.plainBody = rst.body;
        msgInit.to = [_from];
        // TODO: handle attachment
        if (msg_utils.setMsg(msgInit, msg) === false) {
            throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR, "received message error"));
        }
        opt.id = Math.uuid(8, 16);
        opt.serviceId = _id;
        opt.conversationId = opt.id;
        opt.folderId = "INBOX";
        opt.type = _type;
        opt.timestamp = new Date();
        opt.from = rst.from;
        if (msg.attachments.length === 0) {
            opt.hasAttachment = false;
        } else {
            opt.hasAttachment = true;
        }
        opt.messageStatus = "RECEIVED";
        m = new PrivMessage(msg, opt);
        msg_utils.saveMsg(m);   // save in server
        if (_type !== "messaging.email") {
            _messages.msg[m.priv.id] = m;  // sync to local
            event.trigger("MsgRecv", [m]);
        } else {
            _receivedEmails.push(m);  // don't sync to local yet
        }
    });

    msg_service = {
        sendMessage: function (_msg, onSuccess, onError) {
            var m, msg = {}, opt = {}, shortMsg = {}, rst = {};
            if (_security_check.write === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (_msg === null || _msg === undefined || _msg.id === undefined) {
                throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
            }

            if (msg_utils.setMsg(_msg, msg) === false) {
                throw (new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
            }
            if ((arguments.length > 1) && onSuccess !== null && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === false &&
                (_incomingType === 'sms' || _incomingType === 'mms')) {
                if (onError) {
                    setTimeout(function () {
                        onError(new WebAPIError(errorcode.NETWORK_ERR));
                    }, 1);
                }
                return;
            }
            if (deviceSettings.retrieve("WIFI_NETWORK.status") === false &&
                _incomingType === 'email') {
                if (onError) {
                    setTimeout(function () {
                        onError(new WebAPIError(errorcode.NETWORK_ERR));
                    }, 1);
                }
                return;
            }
            if (typeof _msg.id === 'string') {
                if (_messages.msg[_msg.id] === undefined) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return;
                }
                if (_messages.msg[_msg.id].priv.messageStatus === "DRAFT") {
                    msg_utils.delMsg(_messages.msg[_msg.id]);
                    delete _messages.msg[_msg.id];
                } else {
                    // if msg found in storage, it can only be a draft.
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.UNKNOWN_ERR));
                        }, 1);
                    }
                    return;
                }
            }
            opt.id = Math.uuid(8, 16);
            opt.serviceId = _id;
            if ((msg.inResponseTo !== null) &&
                (_messages.msg[msg.inResponseTo] !== undefined) &&
                (_messages.msg[msg.inResponseTo].priv.messageStatus !== "DRAFT")) {
                opt.conversationId = _messages.msg[msg.inResponseTo].priv.conversationId;
            } else {
                opt.conversationId = opt.id;
            }
            opt.folderId = "OUTBOX";
            opt.type = _type;
            opt.timestamp = new Date();
            opt.from = _from;
            if (msg.attachments.length === 0) {
                opt.hasAttachment = false;
            } else {
                opt.hasAttachment = true;
            }
            opt.messageStatus = "SENDING";

            m = new PrivMessage(msg, opt);
            _messages.msg[m.priv.id] = m;
            msg_utils.saveMsg(m);  // sync to remote
            shortMsg.msg = m;   // pass by ref
            shortMsg.id = m.priv.id;
            shortMsg.body = m.body.plainBody;
            shortMsg.to = m.to.slice(0);
            shortMsg.cc = m.cc.slice(0);
            shortMsg.bcc = m.bcc.slice(0);
            event.trigger("OutsideMessageReceived", [shortMsg]);
            rst.onsuccess = onSuccess;
            rst.onerror = onError;
            _msgSending[m.priv.id] = rst;
        },

        loadMessageBody: function (msg, onSuccess, onError) {
            var pendingID;
            if (_security_check.write === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (_messages.msg[msg.id] === undefined) {
                throw (new WebAPIException(errorcode.NOT_FOUND_ERR));
            }
            if (!(new TypeCoerce(t.MessageBodySuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            pendingID = setTimeout(function () {
                if (pendingOperations.hasOwnProperty(pendingID) === false) {
                    // has been cancelled/expired
                    return;
                }
                delete pendingOperations[pendingID];
                onSuccess(_messages.msg[msg.id].body);
            }, 1);
            pendingOperations[pendingID] = onError;
            return pendingID;
        },
        loadMessageAttachment: function (msg, onSuccess, onError) {
            var pendingID;

            if (_security_check.write === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (_messages.msg[msg.id] === undefined) {
                throw (new WebAPIException(errorcode.NOT_FOUND_ERR));
            }
            if (!(new TypeCoerce(t.MessageAttachmentSuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            pendingID = setTimeout(function () {
                if (pendingOperations.hasOwnProperty(pendingID) === false) {
                    // has been cancelled/expired
                    return;
                }
                delete pendingOperations[pendingID];
                onSuccess(_messages.msg[msg.id].attachments);
            }, 1);
            pendingOperations[pendingID] = onError;
            return pendingID;
        },
        sync: function (successCallback, errorCallback, limit) {
            var i, m, pendingID;

            if (_security_check.write === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if ((arguments.length > 0) && successCallback !== null && !(new TypeCoerce(t.SuccessCallback)).match(successCallback)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if ((arguments.length > 1) && errorCallback !== null && !(new TypeCoerce(t.ErrorCallback)).match(errorCallback)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if ((arguments.length > 2) && limit !== null && !(new TypeCoerce(t.long)).match(limit)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            pendingID = setTimeout(function () {
                if (pendingOperations.hasOwnProperty(pendingID) === false) {
                    // has been cancelled/expired
                    return;
                }
                delete pendingOperations[pendingID];
                for (i = 0; i < _receivedEmails.length; i++) {
                    m = _receivedEmails[i];
                    _messages.msg[m.priv.id] = m;  // sync to local
                    event.trigger("MsgRecv", [m]);
                }
                _receivedEmails = [];
                if (successCallback) {
                    successCallback();
                }
            }, 1);
            pendingOperations[pendingID] = errorCallback;
            return pendingID;
        },

        syncFolder: function (folder, onSuccess, onError, limit) {
            var i, m, pendingID;

            if (_security_check.write === false) {
                throw (new WebAPIException(errorcode.SECURITY_ERR));
            }
            if (!(new TypeCoerce(t.MessageFolder)).match(folder)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if ((arguments.length > 1) && onSuccess !== null && !(new TypeCoerce(t.SuccessCallback)).match(onSuccess)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if ((arguments.length > 2) && onError !== null && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if ((arguments.length > 3) && limit !== null && !(new TypeCoerce(t.long)).match(limit)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            pendingID = setTimeout(function () {
                if (pendingOperations.hasOwnProperty(pendingID) === false) {
                    // has been cancelled/expired
                    return;
                }
                delete pendingOperations[pendingID];
                if (folder.id === "INBOX") {
                    for (i = 0; i < _receivedEmails.length; i++) {
                        m = _receivedEmails[i];
                        _messages.msg[m.priv.id] = m;  // sync to local
                        event.trigger("MsgRecv", [m]);
                    }
                    _receivedEmails = [];
                }
                onSuccess();
            }, 1);
            pendingOperations[pendingID] = onError;
            return pendingID;
        },

        stopSync: function (pendingID) {
            if (!(new TypeCoerce(t.long)).match(pendingID)) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (pendingOperations[pendingID] !== undefined) {
                clearTimeout(pendingID);
                pendingOperations[pendingID](new WebAPIError(errorcode.ABORT_ERR));
            }
            delete pendingOperations[pendingID];
        }
    };
    msg_service.__defineGetter__("type", function () {
        return _type;
    });
    msg_service.__defineGetter__("messageStorage", function () {
        return _messageStorage;
    });
    return msg_service;
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/NDEFMessage', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    NDEFRecord = require('ripple/platform/tizen/2.0/NDEFRecord'),
    NDEFRecordText = require('ripple/platform/tizen/2.0/NDEFRecordText'),
    NDEFRecordURI = require('ripple/platform/tizen/2.0/NDEFRecordURI'),
    NDEFRecordMedia = require('ripple/platform/tizen/2.0/NDEFRecordMedia'),
    NDEFRecordFactory,
    NDEFMessage;

NDEFRecordFactory = function (ndefRecord) {
    var record;

    if (ndefRecord instanceof NDEFRecordText) {
        record = new NDEFRecordText(ndefRecord.text, ndefRecord.languageCode,
                ndefRecord.encoding || null);
    } else if (ndefRecord instanceof NDEFRecordURI) {
        record = new NDEFRecordURI(ndefRecord.url);
    } else if (ndefRecord instanceof NDEFRecordMedia) {
        record = new NDEFRecordMedia(ndefRecord.mimeType, ndefRecord.payload);
    } else {
        record = new NDEFRecord(ndefRecord.tnf, ndefRecord.type,
                ndefRecord.payload, ndefRecord.id || null);
    }

    return record;
};

NDEFMessage = function () {
    var voc, records = [];

    // private
    function construct() {
        this.__defineGetter__("recordCount", function () {
            return this.records.length;
        });

        this.__defineGetter__("records", function () {
            return records;
        });

        this.__defineSetter__("records", function (val) {
            try {
                t.NDEFRecord(val, "[]");
                records = val;
            } catch (e) {
            }
        });

        this.toByte = function () {
            var result = [], i, j, space = " ".charCodeAt(0);

            for (i in this.records) {
                for (j = 0; j < this.records[i].payload.length; j++) {
                    result.push(this.records[i].payload.charCodeAt(j));
                }
                if (i < this.records.length - 1) {
                    result.push(space);
                }
            }

            return result;
        };
    }

    // constructor
    function NDEFMessage_NDEFRecords(ndefRecords) {
        var i;

        construct.apply(this);

        for (i = 0; i < ndefRecords.length; i++) {
            records[i] = new NDEFRecordFactory(ndefRecords[i]);
        }
    }

    function NDEFMessage_bytes(rawData) {
        //TODO: NDEFMessage doesn't support rawData constructor
        construct.apply(this);
    }

    function NDEFMessage_void() {
        construct.apply(this);
    }

    voc = [NDEFMessage_NDEFRecords, NDEFMessage_bytes, NDEFMessage_void];
    t.NDEFMessage(arguments, this, voc);
};

module.exports = NDEFMessage;

});
define('ripple/platform/tizen/2.0/NDEFRecord', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
    NDEFRecord;

NDEFRecord = function () {
    var voc = [
        function (tnf, type, payload, id) {
            NDEFRecordInternal.call(this, tnf, type, payload, id || []);
        },
        function (raw_data) {
            NDEFRecordInternal.call(this, 0, [], [], []);
        }
    ];

    t.NDEFRecord(arguments, this, voc);
};

module.exports = NDEFRecord;

});
define('ripple/platform/tizen/2.0/NDEFRecordInternal', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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.
 */

module.exports = function (tnf, type, payload, id) {
    this.__defineGetter__("tnf", function () {
        return tnf;
    });

    this.__defineGetter__("type", function () {
        return type;
    });

    this.__defineGetter__("id", function () {
        return id;
    });

    this.__defineGetter__("payload", function () {
        return payload;
    });
};

});
define('ripple/platform/tizen/2.0/NDEFRecordMedia', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
    NDEFRecordMedia;

NDEFRecordMedia = function (mimeType, data) {
    var i, type = [], payload;

    t.NDEFRecordMedia(arguments, this);

    for (i = 0; i < mimeType.length; i++) {
        type[i] = mimeType.charCodeAt(i);
    }
    payload = t.byte(data, "[]");

    // Normally, we can use prototype to inherit a class, for example:
    //     NDEFRecordMedia.prototype = new NDEFRecord(2, [...], [...], [...]);
    // But the test case thinks that all the inherited property should be
    // the object's own property. So, we can only change the "this" point
    // of NDEFRecord constructor here.
    NDEFRecordInternal.call(this, tizen.nfc.NFC_RECORD_TNF_MIME_MEDIA, type,
            payload, []);

    this.__defineGetter__("mimeType", function () {
        return mimeType;
    });
};

module.exports = NDEFRecordMedia;

});
define('ripple/platform/tizen/2.0/NDEFRecordText', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
    NDEFRecordText;

NDEFRecordText = function (text, languageCode, encoding) {
    var payload = [], i;

    t.NDEFRecordText(arguments, this);

    encoding = encoding || "UTF8";

    // Store languageCode in payload
    payload.push(languageCode.length);
    for (i = 0; i < languageCode.length; i++) {
        payload.push(languageCode.charCodeAt(i));
    }

    // Store text in payload
    for (i = 0; i < text.length; i++) {
        payload.push(text.charCodeAt(i));
    }

    NDEFRecordInternal.call(this, tizen.nfc.NFC_RECORD_TNF_WELL_KNOWN,
            ["T".charCodeAt(0)], payload, []);

    this.__defineGetter__("text", function () {
        return text;
    });

    this.__defineGetter__("languageCode", function () {
        return languageCode;
    });

    this.__defineGetter__("encoding", function () {
        return encoding;
    });
};

module.exports = NDEFRecordText;

});
define('ripple/platform/tizen/2.0/NDEFRecordURI', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    NDEFRecordInternal = require('ripple/platform/tizen/2.0/NDEFRecordInternal'),
    NDEFRecordURI;

NDEFRecordURI = function (uri) {
    var payload = [], i;

    t.NDEFRecordURI(arguments, this);

    // Store uri in payload
    payload.push(0);
    for (i = 0; i < uri.length; i++) {
        payload.push(uri.charCodeAt(i));
    }

    NDEFRecordInternal.call(this, tizen.nfc.NFC_RECORD_TNF_WELL_KNOWN,
            ["U".charCodeAt(0)], payload, []);

    this.__defineGetter__("uri", function () {
        return uri;
    });
};

module.exports = NDEFRecordURI;

});
define('ripple/platform/tizen/2.0/NotificationBase', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    Notification;

Notification = function (title, content) {
    var notification = {};

    notification.title = title;
    notification.content = content || null;

    this.__defineGetter__("id", function () {
        return undefined;
    });

    this.__defineGetter__("type", function () {
        return "STATUS";
    });

    this.__defineGetter__("postedTime", function () {
        return undefined;
    });

    this.__defineGetter__("title", function () {
        return notification.title;
    });
    this.__defineSetter__("title", function (val) {
        try {
            notification.title = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("content", function () {
        return notification.content;
    });
    this.__defineSetter__("content", function (val) {
        try {
            notification.content = t.DOMString(val, "?");
        } catch (e) {
        }
    });
};

module.exports = Notification;

});
define('ripple/platform/tizen/2.0/NotificationDetailInfo', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    NotificationDetailInfo;

NotificationDetailInfo = function (mainText, subText) {
    var notificationDetailInfo = {};

    t.NotificationDetailInfo(arguments, this);

    notificationDetailInfo.mainText = mainText;
    notificationDetailInfo.subText  = subText || null;

    this.__defineGetter__("mainText", function () {
        return notificationDetailInfo.mainText;
    });
    this.__defineSetter__("mainText", function (val) {
        try {
            notificationDetailInfo.mainText = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("subText", function () {
        return notificationDetailInfo.subText;
    });
    this.__defineSetter__("subText", function (val) {
        try {
            notificationDetailInfo.subText = t.DOMString(val, "?");
        } catch (e) {
        }
    });
};

module.exports = NotificationDetailInfo;

});
define('ripple/platform/tizen/2.0/POIBase', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    POIGeometry = require('ripple/platform/tizen/2.0/POIGeometry'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError');


module.exports = function (prop) {
    var _self, i, copy, attr;
    _self = {
        name : null,
        categories : [],
        address : null,
        phoneNumbers : [],
        geometry : null,
        urls : [],
        rating : null,
        tags : null,
        toGeoJSON : function () {
            throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
        }
    };

    _self.__defineGetter__("id", function () {
        return null;
    });

    _self.__defineGetter__("providerName", function () {
        return null;
    });

    if (prop) {
        if (prop.name) {
            _self.name = String(prop.name);
        }
        if (tizen1_utils.isValidArray(prop.categories)) {
            _self.categories = [];
            for (i in prop.categories) {
                _self.categories.push(String(prop.categories[i]));
            }
        }
        if (prop.address) {
            if (typeof prop.address === "string") {
                _self.address = String(prop.address);
            } else if (Object.prototype.toString.call(prop.address) === "[object Object]") {
                copy = prop.address.constructor();
                for (attr in prop.address) {
                    if (prop.address.hasOwnProperty(attr)) {
                        copy[attr] = prop.address[attr];
                    }
                }
                _self.address = copy;
            }
        }
        if (tizen1_utils.isValidArray(prop.phoneNumbers)) {
            _self.phoneNumbers = [];
            for (i in prop.phoneNumbers) {
                _self.phoneNumbers.push(String(prop.phoneNumbers[i]));
            }
        }
        if (prop.geometry) {
            _self.geometry = new POIGeometry(prop.geometry.position, prop.geometry.viewport, prop.geometry.wkt);
        }
        if (tizen1_utils.isValidArray(prop.urls)) {
            _self.urls = [];
            for (i in prop.urls) {
                _self.urls.push(String(prop.urls[i]));
            }
        }
        if (typeof prop.rating === "number") {
            _self.rating = prop.rating;
        }
        if (Object.prototype.toString.call(prop.tags) === "[object Object]") {
            copy = prop.tags.constructor();
            for (attr in prop.tags) {
                if (prop.tags.hasOwnProperty(attr)) {
                    copy[attr] = prop.tags[attr];
                }
            }
            _self.tags = copy;
        }
    }

    return _self;
};

});
define('ripple/platform/tizen/2.0/POIFilter', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = function (attributeName, value) {
    var _self;

    _self = {
        attributeName: attributeName,
        value: value
    };

    return _self;
};

});
define('ripple/platform/tizen/2.0/POIGeometry', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
    GeoRectBounds = require('ripple/platform/tizen/2.0/GeoRectBounds');

module.exports = function (position, viewport, wkt) {
    var _self, _position = null, _viewport = null, _wkt = "";

    if (position) {
        _position = new SimpleCoordinates(position.latitude, position.longitude);
    }

    if (viewport) {
        _viewport = new GeoRectBounds(viewport.southWest, viewport.northEast);
    }

    if (wkt) {
        _wkt = String(wkt);
    }

    _self = {
        position : _position,
        viewport: _viewport,
        wkt: _wkt
    };

    return _self;
};

});
define('ripple/platform/tizen/2.0/PackageInformation', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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.
 */
module.exports = function (id, name, iconPath, version, totalSize,
        dataSize, lastModified, author, description, appIds) {
    var packageInformation = {}, _date = new Date(lastModified);

    packageInformation.__defineGetter__("id", function () {
        return id;
    });
    packageInformation.__defineGetter__("name", function () {
        return name;
    });
    packageInformation.__defineGetter__("iconPath", function () {
        return iconPath;
    });
    packageInformation.__defineGetter__("version", function () {
        return version;
    });
    packageInformation.__defineGetter__("totalSize", function () {
        return totalSize;
    });
    packageInformation.__defineGetter__("dataSize", function () {
        return dataSize;
    });
    packageInformation.__defineGetter__("lastModified", function () {
        return _date;
    });
    packageInformation.__defineGetter__("author", function () {
        return author;
    });
    packageInformation.__defineGetter__("description", function () {
        return description;
    });
    packageInformation.__defineGetter__("appIds", function () {
        return appIds;
    });

    return packageInformation;
};

});
define('ripple/platform/tizen/2.0/PrivMessage', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 utils = require('ripple/utils');

module.exports = function (m, opt) {
    return {
// readonly begin
        priv: {id: opt.id,
               serviceId: opt.serviceId,
               conversationId: opt.conversationId,
               folderId: opt.folderId,
               type: opt.type,
               timestamp: new Date(opt.timestamp),
               from: opt.from,
               hasAttachment: opt.hasAttachment,
               messageStatus: opt.messageStatus
        },
// readonly end
        to: m.to.slice(0),
        cc: m.cc.slice(0),
        bcc: m.bcc.slice(0),
        body: utils.copy(m.body),
        isRead: m.isRead,
        isHighPriority: m.isHighPriority,
        subject: m.subject,
        inResponseTo: m.inResponseTo,
        attachments: utils.copy(m.attachments)
    };
};

});
define('ripple/platform/tizen/2.0/ReverseGeocodeOptions', function (require, exports, module) {
/*      
 *  Copyright 2012 Intel Corporation.
 *  
 * 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 errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    SortMode = require('ripple/platform/tizen/2.0/SortMode');

module.exports = function (_sortMode, _resultType, _maxResults) {
    var _self;
    if (_sortMode !== null && _sortMode !== undefined) {
        if (typeof _sortMode !== "object") {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
        try {
            new SortMode(_sortMode.attributeName, _sortMode.order);
        } catch (e) {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
    }
    if (_resultType !== null && _resultType !== undefined) {
        if (_resultType !== "FORMATTED" && _resultType !== "STRUCTURED") {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
    }
    if (_maxResults !== null && _maxResults !== undefined) {
        if (typeof _maxResults !== "number") {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
    }
    _self = {
        sortMode : _sortMode,
        resultType : _resultType || "FORMATTED",
        maxResults : _maxResults || 0
    };

    return _self;
};


});
define('ripple/platform/tizen/2.0/SimpleCoordinates', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    SimpleCoordinates;

SimpleCoordinates = function (latitude, longitude) {
    var simpleCoordinates = {};

    t.SimpleCoordinates(arguments, this);

    this.__defineGetter__("latitude", function () {
        return simpleCoordinates.latitude;
    });
    this.__defineSetter__("latitude", function (val) {
        try {
            simpleCoordinates.latitude = t.double(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("longitude", function () {
        return simpleCoordinates.longitude;
    });
    this.__defineSetter__("longitude", function (val) {
        try {
            simpleCoordinates.longitude = t.double(val);
        } catch (e) {
        }
    });

    simpleCoordinates.latitude  = latitude;
    simpleCoordinates.longitude = longitude;
};

module.exports = SimpleCoordinates;

});
define('ripple/platform/tizen/2.0/SortMode', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    SortMode;

SortMode = function (attributeName, order) {
    var sortMode = {};

    t.SortMode(arguments, this);

    this.__defineGetter__("attributeName", function () {
        return sortMode.attributeName;
    });
    this.__defineSetter__("attributeName", function (val) {
        try {
            sortMode.attributeName = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("order", function () {
        return sortMode.order;
    });
    this.__defineSetter__("order", function (val) {
        try {
            sortMode.order = t.SortModeOrder(val);
        } catch (e) {
        }
    });

    sortMode.attributeName = attributeName;
    sortMode.order         = order || "ASC";
};

module.exports = SortMode;

});
define('ripple/platform/tizen/2.0/StatusNotification', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ApplicationControl = require('ripple/platform/tizen/2.0/ApplicationControl'),
    Notification = require('ripple/platform/tizen/2.0/NotificationBase'),
    NotificationDetailInfo = require('ripple/platform/tizen/2.0/NotificationDetailInfo'),
    StatusNotification;

StatusNotification = function (statusType, title, notificationInitDict) {
    var statusNotification = {}, attr, i, info;

    t.StatusNotification(arguments, this);

    Notification.call(this, title, notificationInitDict ?
            notificationInitDict.content : null);

    statusNotification.statusType          = statusType;
    statusNotification.iconPath            = null;
    statusNotification.subIconPath         = null;
    statusNotification.number              = null;
    statusNotification.detailInfo          = [];
    statusNotification.ledColor            = null;
    statusNotification.ledOnPeriod         = 0;
    statusNotification.ledOffPeriod        = 0;
    statusNotification.backgroundImagePath = null;
    statusNotification.thumbnails          = [];
    statusNotification.soundPath           = null;
    statusNotification.vibration           = false;
    statusNotification.appControl          = null;
    statusNotification.appId               = null;
    statusNotification.progressType        = "PERCENTAGE";
    statusNotification.progressValue       = null;

    for (attr in notificationInitDict) {
        switch (attr) {
        case "appControl":
            statusNotification.appControl = new ApplicationControl(
                    notificationInitDict.appControl.operation,
                    notificationInitDict.appControl.uri || null,
                    notificationInitDict.appControl.mime || null,
                    notificationInitDict.appControl.category || null,
                    notificationInitDict.appControl.data || null);
            break;

        case "detailInfo":
            for (i in notificationInitDict.detailInfo) {
                info = notificationInitDict.detailInfo[i];
                info = new NotificationDetailInfo(info.mainText,
                        info.subText);

                statusNotification.detailInfo.push(info);
            }
            break;

        default:
            statusNotification[attr] = notificationInitDict[attr];
            break;
        }
    }

    this.__defineGetter__("statusType", function () {
        return statusNotification.statusType;
    });

    this.__defineGetter__("iconPath", function () {
        return statusNotification.iconPath;
    });
    this.__defineSetter__("iconPath", function (val) {
        try {
            statusNotification.iconPath = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("subIconPath", function () {
        return statusNotification.subIconPath;
    });
    this.__defineSetter__("subIconPath", function (val) {
        try {
            statusNotification.subIconPath = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("number", function () {
        return statusNotification.number;
    });
    this.__defineSetter__("number", function (val) {
        try {
            statusNotification.number = t.long(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("detailInfo", function () {
        return statusNotification.detailInfo;
    });
    this.__defineSetter__("detailInfo", function (val) {
        try {
            statusNotification.detailInfo = t.NotificationDetailInfo(val, "[]?");
        } catch (e) {
        }
    });

    this.__defineGetter__("ledColor", function () {
        return statusNotification.ledColor;
    });
    this.__defineSetter__("ledColor", function (val) {
        try {
            statusNotification.ledColor = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("ledOnPeriod", function () {
        return statusNotification.ledOnPeriod;
    });
    this.__defineSetter__("ledOnPeriod", function (val) {
        try {
            statusNotification.ledOnPeriod = t.unsigned_long(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("ledOffPeriod", function () {
        return statusNotification.ledOffPeriod;
    });
    this.__defineSetter__("ledOffPeriod", function (val) {
        try {
            statusNotification.ledOffPeriod = t.unsigned_long(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("backgroundImagePath", function () {
        return statusNotification.backgroundImagePath;
    });
    this.__defineSetter__("backgroundImagePath", function (val) {
        try {
            statusNotification.backgroundImagePath = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("thumbnails", function () {
        return statusNotification.thumbnails;
    });
    this.__defineSetter__("thumbnails", function (val) {
        try {
            statusNotification.thumbnails = t.DOMString(val, "[]?");
        } catch (e) {
        }
    });

    this.__defineGetter__("soundPath", function () {
        return statusNotification.soundPath;
    });
    this.__defineSetter__("soundPath", function (val) {
        try {
            statusNotification.soundPath = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("vibration", function () {
        return statusNotification.vibration;
    });
    this.__defineSetter__("vibration", function (val) {
        try {
            statusNotification.vibration = t.boolean(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("appControl", function () {
        return statusNotification.appControl;
    });
    this.__defineSetter__("appControl", function (val) {
        try {
            statusNotification.appControl = t.ApplicationControl(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("appId", function () {
        return statusNotification.appId;
    });
    this.__defineSetter__("appId", function (val) {
        try {
            statusNotification.appId = t.ApplicationId(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("progressType", function () {
        return statusNotification.progressType;
    });
    this.__defineSetter__("progressType", function (val) {
        try {
            statusNotification.progressType = t.NotificationProgressType(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("progressValue", function () {
        return statusNotification.progressValue;
    });
    this.__defineSetter__("progressValue", function (val) {
        try {
            val = t.unsigned_long(val, '?');

            if ((statusNotification.progressType === "PERCENTAGE") &&
                    (val > 100))
                return;

            statusNotification.progressValue = val;
        } catch (e) {
        }
    });
};

module.exports = StatusNotification;

});
define('ripple/platform/tizen/2.0/SyncInfo', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    SyncInfo,
    _accounts = {},
    _counter = 0;

SyncInfo = function () {
    var voc, syncInfo = {}, index;

    function save() {
        _accounts[index] = {
            id:       syncInfo.id,
            password: syncInfo.password
        };
        db.saveObject("save-syncinfo", _accounts);
    }

    function construct(url, id, password, mode) {
        syncInfo.url      = url;
        syncInfo.id       = id;
        syncInfo.password = password;
        syncInfo.mode     = mode;
        syncInfo.type     = null;
        syncInfo.interval = null;

        this.__defineGetter__("url", function () {
            return syncInfo.url;
        });
        this.__defineSetter__("url", function (url) {
            try {
                syncInfo.url = t.DOMString(url);
            } catch (e) {
            }
        });

        this.__defineGetter__("id", function () {
            return null;
        });
        this.__defineSetter__("id", function (id) {
            try {
                syncInfo.id = t.DOMString(id);
                save();
            } catch (e) {
            }
        });

        this.__defineGetter__("password", function () {
            return null;
        });
        this.__defineSetter__("password", function (password) {
            try {
                syncInfo.password = t.DOMString(password);
                save();
            } catch (e) {
            }
        });

        this.__defineGetter__("mode", function () {
            return syncInfo.mode;
        });
        this.__defineSetter__("mode", function (mode) {
            try {
                syncInfo.mode = t.SyncMode(mode);
            } catch (e) {
            }
        });

        this.__defineGetter__("type", function () {
            return syncInfo.type;
        });
        this.__defineSetter__("type", function (type) {
            if (mode !== "MANUAL") {
                return;
            }
            try {
                syncInfo.type = t.SyncType(type);
            } catch (e) {
            }
        });

        this.__defineGetter__("interval", function () {
            return syncInfo.interval;
        });
        this.__defineSetter__("interval", function (interval) {
            if (mode !== "PERIODIC") {
                return;
            }
            try {
                syncInfo.interval = t.SyncInterval(interval);
            } catch (e) {
            }
        });
    }

    voc = [
        function (url, id, password, mode, type) {
            construct.apply(this, arguments);

            if (mode === "MANUAL") {
                syncInfo.type = type;
            }
        },
        function (url, id, password, mode, interval) {
            construct.apply(this, arguments);

            if (mode === "PERIODIC") {
                syncInfo.interval = interval;
            }
        },
        function (url, id, password, mode) {
            construct.apply(this, arguments);
        }
    ];

    t.SyncInfo(arguments, this, voc);

    index = _counter++;
    Object.defineProperty(this, "__syncInfoID__", {
        "configurable": false,
        "enumerable":   false,
        "get": (function (_id_) {
            return function () { return _id_; };
        })(index)
    });
    save();
};

module.exports = SyncInfo;

});
define('ripple/platform/tizen/2.0/SyncProfileInfo', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    SyncProfileInfo;

SyncProfileInfo = function (profileName, syncInfo, serviceInfo) {
    var syncProfileInfo = {};

    t.SyncProfileInfo(arguments, this);

    syncProfileInfo.profileName = profileName;
    syncProfileInfo.syncInfo    = syncInfo;
    syncProfileInfo.serviceInfo = serviceInfo;

    this.__defineGetter__("profileId", function () {
        return null;
    });

    this.__defineGetter__("profileName", function () {
        return syncProfileInfo.profileName;
    });
    this.__defineSetter__("profileName", function (profileName) {
        try {
            syncProfileInfo.profileName = t.DOMString(profileName);
        } catch (e) {
        }
    });

    this.__defineGetter__("syncInfo", function () {
        return syncProfileInfo.syncInfo;
    });
    this.__defineSetter__("syncInfo", function (syncInfo) {
        try {
            t.SyncInfo(syncInfo);
            syncProfileInfo.syncInfo = syncInfo;
        } catch (e) {
        }
    });

    this.__defineGetter__("serviceInfo", function () {
        return syncProfileInfo.serviceInfo;
    });
    this.__defineSetter__("serviceInfo", function (serviceInfo) {
        try {
            t.SyncServiceInfo(serviceInfo, "[]?");
            syncProfileInfo.serviceInfo = serviceInfo;
        } catch (e) {
        }
    });
};

module.exports = SyncProfileInfo;

});
define('ripple/platform/tizen/2.0/SyncServiceInfo', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    SyncServiceInfo,
    _accounts = {},
    _counter = 0;

SyncServiceInfo = function (enable, serviceType, serverDatabaseUri, id,
        password) {
    var syncServiceInfo = {}, index;

    function save() {
        _accounts[index] = {
            id: syncServiceInfo.id,
            password: syncServiceInfo.password
        };
        db.saveObject("save-syncserviceinfo", _accounts);
    }

    t.SyncServiceInfo(arguments, this);

    syncServiceInfo.enable            = enable;
    syncServiceInfo.serviceType       = serviceType;
    syncServiceInfo.serverDatabaseUri = serverDatabaseUri;
    syncServiceInfo.id                = id || null;
    syncServiceInfo.password          = password || null;

    this.__defineGetter__("enable", function () {
        return syncServiceInfo.enable;
    });
    this.__defineSetter__("enable", function (enable) {
        try {
            syncServiceInfo.enable = t.boolean(enable);
        } catch (e) {
        }
    });

    this.__defineGetter__("serviceType", function () {
        return syncServiceInfo.serviceType;
    });
    this.__defineSetter__("serviceType", function (serviceType) {
        try {
            syncServiceInfo.serviceType = t.SyncServiceType(serviceType);
        } catch (e) {
        }
    });

    this.__defineGetter__("serverDatabaseUri", function () {
        return syncServiceInfo.serverDatabaseUri;
    });
    this.__defineSetter__("serverDatabaseUri", function (serverDatabaseUri) {
        try {
            syncServiceInfo.serverDatabaseUri = t.DOMString(serverDatabaseUri);
        } catch (e) {
        }
    });

    this.__defineGetter__("id", function () {
        return null;
    });
    this.__defineSetter__("id", function (id) {
        try {
            syncServiceInfo.id = t.DOMString(id);
            save();
        } catch (e) {
        }
    });

    this.__defineGetter__("password", function () {
        return null;
    });
    this.__defineSetter__("password", function (password) {
        try {
            syncServiceInfo.password = t.DOMString(password);
            save();
        } catch (e) {
        }
    });

    index = _counter++;
    Object.defineProperty(this, "__syncServiceInfoID__", {
        "configurable": false,
        "enumerable":   false,
        "get": (function (_id_) {
            return function () { return _id_; };
        })(index)
    });
    save();
};

module.exports = SyncServiceInfo;

});
define('ripple/platform/tizen/2.0/SyncStatistics', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 SyncStatistics = function (syncStatus, serviceType, lastSyncTime,
        serverToClientTotal, serverToClientAdded, serverToClientUpdated,
        serverToClientRemoved, clientToServerTotal, clientToServerAdded,
        clientToServerUpdated, clientToServerRemoved) {
    this.__defineGetter__("syncStatus", function () {
        return syncStatus;
    });

    this.__defineGetter__("serviceType", function () {
        return serviceType;
    });

    this.__defineGetter__("lastSyncTime", function () {
        return lastSyncTime;
    });

    this.__defineGetter__("serverToClientTotal", function () {
        return serverToClientTotal;
    });

    this.__defineGetter__("serverToClientAdded", function () {
        return serverToClientAdded;
    });

    this.__defineGetter__("serverToClientUpdated", function () {
        return serverToClientUpdated;
    });

    this.__defineGetter__("serverToClientRemoved", function () {
        return serverToClientRemoved;
    });

    this.__defineGetter__("clientToServerTotal", function () {
        return clientToServerTotal;
    });

    this.__defineGetter__("clientToServerAdded", function () {
        return clientToServerAdded;
    });

    this.__defineGetter__("clientToServerUpdated", function () {
        return clientToServerUpdated;
    });

    this.__defineGetter__("clientToServerRemoved", function () {
        return clientToServerRemoved;
    });
};

module.exports = SyncStatistics;

});
define('ripple/platform/tizen/2.0/TZDate', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    tz = require('ripple/platform/tizen/2.0/timezone_info'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    _Month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
    _Day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

function TZDate (dt) {
    var d, UTCd, UTC_diff, tzid = "", target_diff, temp_date, localeTime_fmt = 'h:m:s', localeDate_fmt = 'D, d M y',
    time = require('ripple/platform/tizen/2.0/time'),
        hour = arguments[3] || 0, min = arguments[4] || 0,
        sec = arguments[5] || 0, msec = arguments[6] || 0,

    _checkTZDate = function (dat) {
        var Tzdate = require('ripple/platform/tizen/2.0/TZDate'),
            i, tzd;
        if (typeof dat !== 'object' || dat === undefined || dat === null) {
            return false;
        }
        tzd = new Tzdate();
        for (i in tzd) {
            if (dat.hasOwnProperty(i) === false) {
                return false;
            }
        }
        return true;
    },
    _d2UTCd_sync = function () {
        UTCd = new Date(d.valueOf() - (UTC_diff * 1000 * 60 * 60));
    },
    _UTCd2d_sync = function () {
        d = new Date(UTCd.valueOf() + (UTC_diff * 1000 * 60 * 60));
    },
    _getValue = function (o) {
        var other;
        other = new Date(o.getUTCFullYear(), o.getUTCMonth(), o.getUTCDate(),
                    o.getUTCHours(), o.getUTCMinutes(), o.getUTCSeconds(), o.getUTCMilliseconds());
        return other.valueOf();
    },
    _formatDateString = function (fmt) {
        var i, ret = '';
        for (i = 0; i < fmt.length; i++) {
            switch (fmt.charAt(i)) {
            case 'd':
                ret = ret + d.getDate();
                break;
            case 'y':
                ret = ret + d.getFullYear();
                break;
            case 'm':
                ret = ret + (d.getMonth() + 1);
                break;
            case 'M':
                ret = ret + _Month[d.getMonth()];
                break;
            case 'D':
                ret = ret + _Day[d.getDay()];
                break;
            default:
                ret = ret + fmt.charAt(i);
            }
        }
        return ret;
    },
    _formatTimeString = function (fmt) {
        var i, hh, mm, ss, AP, ret = "";
        if (fmt.search(/ap/) === -1) {
            AP = false;
        } else {
            AP = true;
            if (d.getHours() > 11) {
                fmt = fmt.replace("ap", "PM");
            } else {
                fmt = fmt.replace("ap", "AM");
            }
        }
        for (i = 0; i < fmt.length; i++) {
            switch (fmt.charAt(i)) {
            case 'h':
                hh = d.getHours();
                if (AP) {
                    hh = (hh > 12) ? hh - 12 : hh;
                }
                ret = ret + hh;
                break;
            case 'm':
                mm = d.getMinutes();
                mm = (mm < 10 ? "0" : "") + mm;
                ret = ret + mm;
                break;
            case 's':
                ss = d.getSeconds();
                ss = (ss < 10 ? "0" : "") + ss;
                ret = ret + ss;
                break;
            default:
                ret = ret + fmt.charAt(i);
            }
        }
        return ret;
    };

    if (arguments[7] !== undefined) {
        tzid = arguments[7];
    }

    if (dt === null || dt === undefined) {
        temp_date = new Date();
        if (arguments[1] !== undefined) {
            if (typeof arguments[1] !== 'string') {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            if (tz.isValidTimezone(arguments[1]) === false) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }
            tzid = arguments[1];
        } else {
            tzid = time.getLocalTimezone();
        }
        target_diff = tz.getTimezoneDiff(tzid);
        d = new Date(temp_date.valueOf() + (target_diff + temp_date.getTimezoneOffset() / 60) * 1000 * 60 * 60);
    } else {
        if (tizen1_utils.isValidDate(dt)) {
            d = new Date(dt);
            if (arguments[1] !== undefined) {
                tzid = arguments[1];
            } else {
                tzid = time.getLocalTimezone();
            }
        } else {
            if (arguments.length === 1) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            } else {
                d = new Date(arguments[0], arguments[1], arguments[2], hour, min, sec, msec);
                if (arguments[7] !== undefined) {
                    tzid = arguments[7];
                } else {
                    tzid = time.getLocalTimezone();
                }
            }
        }
    }

    if (tz.isValidTimezone(tzid) === false) {
        tzid = 'UTC';
    }
    UTC_diff = tz.getTimezoneDiff(tzid);
    _d2UTCd_sync();

    this.getDate = function () {
        return d.getDate();
    };
    this.setDate = function (dt) {
        d.setDate(dt);
        _d2UTCd_sync();
    };
    this.getDay = function () {
        return d.getDay();
    };
    this.getFullYear = function () {
        return d.getFullYear();
    };
    this.setFullYear = function (yr) {
        d.setFullYear(yr);
        _d2UTCd_sync();
    };
    this.getHours = function () {
        return d.getHours();
    };
    this.setHours = function (hr) {
        d.setHours(hr);
        _d2UTCd_sync();
    };
    this.getMilliseconds = function () {
        return d.getMilliseconds();
    };
    this.setMilliseconds = function (msec) {
        d.setMilliseconds(msec);
        _d2UTCd_sync();
    };
    this.getMinutes = function () {
        return d.getMinutes();
    };
    this.setMinutes = function (min) {
        d.setMinutes(min);
        _d2UTCd_sync();
    };
    this.getMonth = function () {
        return d.getMonth();
    };
    this.setMonth = function (m) {
        d.setMonth(m);
        _d2UTCd_sync();
    };
    this.getSeconds = function () {
        return d.getSeconds();
    };
    this.setSeconds = function (s) {
        d.setSeconds(s);
        _d2UTCd_sync();
    };
    this.getUTCDate = function () {
        return UTCd.getDate();
    };
    this.setUTCDate = function (dt) {
        UTCd.setDate(dt);
        _UTCd2d_sync();
    };
    this.getUTCDay = function () {
        return UTCd.getDay();
    };
    this.getUTCFullYear = function () {
        return UTCd.getFullYear();
    };
    this.setUTCFullYear = function (yr) {
        UTCd.setFullYear(yr);
        _UTCd2d_sync();
    };
    this.getUTCHours = function () {
        return UTCd.getHours();
    };
    this.setUTCHours = function (hr) {
        UTCd.setHours(hr);
        _UTCd2d_sync();
    };
    this.getUTCMilliseconds = function () {
        return UTCd.getMilliseconds();
    };
    this.setUTCMilliseconds = function (msec) {
        UTCd.setMilliseconds(msec);
        _UTCd2d_sync();
    };
    this.getUTCMinutes = function () {
        return UTCd.getMinutes();
    };
    this.setUTCMinutes = function (min) {
        UTCd.setMinutes(min);
        _UTCd2d_sync();
    };
    this.getUTCMonth = function () {
        return UTCd.getMonth();
    };
    this.setUTCMonth = function (m) {
        UTCd.setMonth(m);
        _UTCd2d_sync();
    };
    this.getUTCSeconds = function () {
        return UTCd.getSeconds();
    };
    this.setUTCSeconds = function (s) {
        UTCd.setSeconds(s);
        _UTCd2d_sync();
    };
    this.getTimezone = function () {
        return tzid;
    };
    this.toTimezone = function (new_tzid) {
        var diff,
            Tzdate = require('ripple/platform/tizen/2.0/TZDate');
        if (tz.isValidTimezone(String(new_tzid)) === true) {
            diff = tz.getTimezoneDiff(new_tzid) - UTC_diff;
            return new Tzdate(new Date(d.valueOf() + (diff * 1000 * 60 * 60)), new_tzid);
        } else {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
    };
    this.toLocalTimezone = function () {
        var diff,
            localTzid,
            Tzdate = require('ripple/platform/tizen/2.0/TZDate');
        localTzid = time.getLocalTimezone();

        diff = tz.getTimezoneDiff(localTzid) - UTC_diff;
        return new Tzdate(new Date(d.valueOf() + (diff * 1000 * 60 * 60)), localTzid);
    };
    this.toUTC = function () {
        var Tzdate = require('ripple/platform/tizen/2.0/TZDate');
        return new Tzdate(UTCd, "UTC");
    };
    this.difference = function (other) {
        var diff,
            TDur = require('ripple/platform/tizen/2.0/TimeDuration');
        if (_checkTZDate(other) === false) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        diff = (UTCd.valueOf() - _getValue(other));
        if (diff % 86400000 === 0) {
            return new TDur(diff/86400000, 'DAYS');
        } else {
            return new TDur(diff);
        }
    };
    this.equalsTo = function (other) {
        if (_checkTZDate(other) === false) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        return (UTCd.valueOf() === _getValue(other));
    };
    this.earlierThan = function (other) {
        if (_checkTZDate(other) === false) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        return (UTCd.valueOf() < _getValue(other));
    };
    this.laterThan = function (other) {
        if (_checkTZDate(other) === false) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        return (UTCd.valueOf() > _getValue(other));
    };
    this.addDuration = function (dur) {
        var Tzdate = require('ripple/platform/tizen/2.0/TZDate'),
            Tunit = {"MSECS": 1,
                "SECS": 1000,
                "MINS": 60 * 1000,
                "HOURS": 60 * 60 * 1000,
                "DAYS": 24 * 60 * 60 * 1000
            };
        if (typeof dur !== 'object' || dur === undefined || dur === null) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        if (dur.length === undefined || dur.length === null ||
                dur.unit === undefined || dur.unit === null) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        if ((typeof dur.length) !== 'number') {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        if (Tunit[dur.unit] === undefined) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        return new Tzdate(new Date(d.valueOf() + (parseInt(dur.length, 10) * Tunit[dur.unit])), tzid);
    };
    this.toLocaleDateString = function () {
        if (d.toString() === "Invalid Date") {
            return d.toString();
        } else {
            return _formatDateString(localeDate_fmt);
        }
    };
    this.toLocaleTimeString = function () {
        if (d.toString() === "Invalid Date") {
            return d.toString();
        } else {
            return _formatTimeString(localeTime_fmt);
        }
    };
    this.toLocaleString = function () {
        if (d.toString() === "Invalid Date") {
            return d.toString();
        } else {
            return (this.toLocaleDateString() + " " + this.toLocaleTimeString());
        }
    };
    this.toDateString = function () {
        var ret = "", fmt = time.getDateFormat();
        if (d.toString() === "Invalid Date") {
            return d.toString();
        }
        ret = _formatDateString(fmt);
        return ret;
    };
    this.toTimeString = function () {
        var ret, fmt = time.getTimeFormat();

        if (d.toString() === "Invalid Date") {
            return d.toString();
        }

        ret = _formatTimeString(fmt);
        if (tz.getTimezoneDesc(tzid) !== null) {
            return ret + " " + tz.getTimezoneDesc(tzid);
        } else {
            return ret + " " + tz.getTimezoneAbbr(tzid);
        }
        return ret;
    };
    this.toString = function () {
        if (d.toString() === "Invalid Date") {
            return d.toString();
        } else {
            return (this.toDateString() + " " + this.toTimeString());
        }
    };
    this.getTimezoneAbbreviation = function () {
        return tz.getTimezoneAbbr(tzid);
    };
    this.secondsFromUTC = function () {
        return (-1 * UTC_diff * 60 * 60);
    };
    this.isDST = function () {
        throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR));
    };
    this.getPreviousDSTTransition = function () {
        throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR));
    };
    this.getNextDSTTransition = function () {
        throw (new WebAPIException(errorcode.NOT_SUPPORTED_ERR));
    };
    return this;
}

module.exports = TZDate;

});
define('ripple/platform/tizen/2.0/TimeDuration', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    TimeDuration;

TimeDuration = function (_length, _unit) {
    var timeDuration = {},
        TimeDurationUnit = {"MSECS": 1,
                            "SECS": 1000,
                            "MINS": 60 * 1000,
                            "HOURS": 60 * 60 * 1000,
                            "DAYS": 24 * 60 * 60 * 1000
                           },
        _simplifyDuration = function (ms) {
            var TDur = require('ripple/platform/tizen/2.0/TimeDuration'),
                uni = "MSECS";
            if ((ms % 1000) === 0) {
                ms = ms / 1000;
                uni = "SECS";
                if ((ms % 60) === 0) {
                    ms = ms / 60;
                    uni = "MINS";
                    if ((ms % 60) === 0) {
                        ms = ms / 60;
                        uni = "HOURS";
                        if ((ms % 24) === 0) {
                            ms = ms / 24;
                            uni = "DAYS";
                        }
                    }
                }
            }
            return (new TDur(ms, uni));
        },
        _toMSECS = function (unit) {
            if (TimeDurationUnit[unit] === undefined) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            } else {
                return TimeDurationUnit[unit];
            }
        };

    t.TimeDuration(arguments, this);

    this.__defineGetter__("length", function () {
        return timeDuration.length;
    });
    this.__defineSetter__("length", function (val) {
        try {
            timeDuration.length = t.double(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("unit", function () {
        return timeDuration.unit;
    });
    this.__defineSetter__("unit", function (val) {
        try {
            timeDuration.unit = t.TimeDurationUnit(val);
        } catch (e) {
        }
    });

    timeDuration.length = _length;
    timeDuration.unit = _unit || "MSECS";

    this.difference = function (o) {

        t.TimeDuration("difference", arguments);

        var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
            otherMS = o.length * _toMSECS(o.unit);
        return _simplifyDuration(thisMS - otherMS);
    };
    this.equalsTo = function (o) {

        t.TimeDuration("equalsTo", arguments);

        var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
            otherMS = o.length * _toMSECS(o.unit);
        return (thisMS === otherMS);
    };
    this.lessThan = function (o) {

        t.TimeDuration("lessThan", arguments);

        var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
            otherMS = o.length * _toMSECS(o.unit);
        return (thisMS < otherMS);
    };
    this.greaterThan = function (o) {

        t.TimeDuration("greaterThan", arguments);

        var thisMS = timeDuration.length * _toMSECS(timeDuration.unit),
            otherMS = o.length * _toMSECS(o.unit);
        return (thisMS > otherMS);
    };
};

module.exports = TimeDuration;

});
define('ripple/platform/tizen/2.0/WebAPIError', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/tizen/2.0/errorcode');

var msg = {
    0: "Generic Error",
    1: "Index or size is negative, or greater than the allowed value.",
    2: "Specified range of text does not fit into a DOMString.",
    3: "Node is inserted somewhere it doesn't belong.",
    4: "Node is used in a different document than the one that created it (that doesn't support it).",
    5: "An invalid or illegal character is specified.",
    6: "Data is specified for a Node which does not support data.",
    7: "An attempt is made to modify an object where modifications are not allowed.",
    8: "An attempt is made to reference a Node in a context where it does not exist.",
    9: "The implementation does not support the requested type of object or operation.",
    10: "An attempt is made to add an attribute that is already in use elsewhere.",
    11: "An attempt is made to use an object that is not, or is no longer, usable.",
    12: "An invalid or illegal string is specified.",
    13: "An attempt is made to modify the type of the underlying object.",
    14: "An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.",
    15: "A parameter or an operation is not supported by the underlying object.",
    16: "A call to a method such as insertBefore or removeChild would make the Node invalid with respect to \"partial validity\", this exception would be raised and the operation would not be done.",
    17: "The type of an object is incompatible with the expected type of the parameter associated to the object.",
    18: "An attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.",
    19: "A network error occurs in synchronous requests.",
    20: "The abort error occurs in asynchronous requests by user prompt.",
    21: "The operation could not be completed because the URL does not match.",
    22: "The quota has been exceeded.",
    23: "The operation timed out.",
    24: "The supplied node is incorrect or has an incorrect ancestor for this operation.",
    25: "The object can not be cloned.",
    99: "The content of an object does not include valid values.",
    100: "Error occurred in communication with the underlying implementation that meant the requested method could not complete.",
    111: "Requested service is not available."
},
    errType = {
    0: "UnknownError",
    1: "IndexSizeError",
    2: "DOMStringSizeError",
    3: "HierarchyRequestError",
    4: "WrongDocumentError",
    5: "InvalidCharacterError",
    6: "NoDataAllowedError",
    7: "NoModificationAllowedError",
    8: "NotFoundError",
    9: "NotSupportedError",
    10: "InuseAttributeError",
    11: "InvalidStateError",
    12: "SyntaxError",
    13: "InvalidModificationError",
    14: "NamespaceError",
    15: "InvalidAccessError",
    16: "ValidationError",
    17: "TypeMismatchError",
    18: "SecurityError",
    19: "NetworkError",
    20: "AbortError",
    21: "URLMismatchError",
    22: "QuotaExceededError",
    23: "TimeoutError",
    24: "InvalidNodeTypeError",
    25: "DataCloneError",
    99: "InvalidValuesError",
    100: "IOError",
    111: "ServiceNotAvailableError"
};

/*
  support 3 types of error:
  - WebAPIError()
      code = errorcode.UNKNOWN_ERR
      message = errorcode.message[UNKNOWN_ERR]
  - WebAPIError(errorcode."TYPE_MISMATCH_ERR")
      code = 17
      message = errorcode.message[17]
  - WebAPIError(my_own_error_code, "This is my error message.")
      code = my_own_error_code(number)
      message = "This is my error message."
*/

module.exports = function (code, message, name) {
    var _code, _message, _name;

    if (typeof code !== 'number') {
        _code = errorcode.UNKNOWN_ERR;
        _message = msg[_code];
        _name = errType[_code];
    } else {
        _code = code;
        if (typeof message === 'string') {
            _message = message;
        } else {
            _message = msg[_code];
        }
        if (typeof name === 'string') {
            _name = name;
        } else {
            _name = errType[_code];
        }
    }

    this.__defineGetter__("code", function () {
        return _code;
    });
    this.__defineGetter__("message", function () {
        return _message;
    });
    this.__defineGetter__("name", function () {
        return _name;
    });
};

});
define('ripple/platform/tizen/2.0/WebAPIException', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/tizen/2.0/errorcode');

var msg = {
    0: "Generic Error",
    1: "Index or size is negative, or greater than the allowed value.",
    2: "Specified range of text does not fit into a DOMString.",
    3: "Node is inserted somewhere it doesn't belong.",
    4: "Node is used in a different document than the one that created it (that doesn't support it).",
    5: "An invalid or illegal character is specified.",
    6: "Data is specified for a Node which does not support data.",
    7: "An attempt is made to modify an object where modifications are not allowed.",
    8: "An attempt is made to reference a Node in a context where it does not exist.",
    9: "The implementation does not support the requested type of object or operation.",
    10: "An attempt is made to add an attribute that is already in use elsewhere.",
    11: "An attempt is made to use an object that is not, or is no longer, usable.",
    12: "An invalid or illegal string is specified.",
    13: "An attempt is made to modify the type of the underlying object.",
    14: "An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.",
    15: "A parameter or an operation is not supported by the underlying object.",
    16: "A call to a method such as insertBefore or removeChild would make the Node invalid with respect to \"partial validity\", this exception would be raised and the operation would not be done.",
    17: "The type of an object is incompatible with the expected type of the parameter associated to the object.",
    18: "An attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.",
    19: "A network error occurs in synchronous requests.",
    20: "The abort error occurs in asynchronous requests by user prompt.",
    21: "The operation could not be completed because the URL does not match.",
    22: "The quota has been exceeded.",
    23: "The operation timed out.",
    24: "The supplied node is incorrect or has an incorrect ancestor for this operation.",
    25: "The object can not be cloned.",
    99: "The content of an object does not include valid values.",
    100: "Error occurred in communication with the underlying implementation that meant the requested method could not complete.",
    111: "Requested service is not available."
},
    errType = {
    0: "UnknownError",
    1: "IndexSizeError",
    2: "DOMStringSizeError",
    3: "HierarchyRequestError",
    4: "WrongDocumentError",
    5: "InvalidCharacterError",
    6: "NoDataAllowedError",
    7: "NoModificationAllowedError",
    8: "NotFoundError",
    9: "NotSupportedError",
    10: "InuseAttributeError",
    11: "InvalidStateError",
    12: "SyntaxError",
    13: "InvalidModificationError",
    14: "NamespaceError",
    15: "InvalidAccessError",
    16: "ValidationError",
    17: "TypeMismatchError",
    18: "SecurityError",
    19: "NetworkError",
    20: "AbortError",
    21: "URLMismatchError",
    22: "QuotaExceededError",
    23: "TimeoutError",
    24: "InvalidNodeTypeError",
    25: "DataCloneError",
    99: "InvalidValuesError",
    100: "IOError",
    111: "ServiceNotAvailableError"
};

/*
  support 3 types of error:
  - WebAPIError()
      code = errorcode.UNKNOWN_ERR
      message = errorcode.message[UNKNOWN_ERR]
  - WebAPIError(errorcode."TYPE_MISMATCH_ERR")
      code = 17
      message = errorcode.message[17]
  - WebAPIError(my_own_error_code, "This is my error message.")
      code = my_own_error_code(number)
      message = "This is my error message."
*/

module.exports = function (code, message, name) {
    var g, c, _code, _message, _name;

    for (c in errorcode) {
        g = errorcode.__lookupGetter__(c);
        if (g) {
            this.__defineGetter__(c, g);
        }
    }

    if (typeof code !== 'number') {
        _code = errorcode.UNKNOWN_ERR;
        _message = msg[_code];
        _name = errType[_code];
    } else {
        _code = code;
        if (typeof message === 'string') {
            _message = message;
        } else {
            _message = msg[_code];
        }
        if (typeof name === 'string') {
            _name = name;
        } else {
            _name = errType[_code];
        }
    }

    this.__defineGetter__("code", function () {
        return _code;
    });
    this.__defineGetter__("message", function () {
        return _message;
    });
    this.__defineGetter__("name", function () {
        return _name;
    });
};

});
define('ripple/platform/tizen/2.0/account', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    _data = {
        DB_ACCOUNT_KEY : "tizen1-db-accounts",
        accounts : {}
    },
    _self;

function _checkAccount(account) {
    if (typeof account !== "object" ||
        typeof account.id !== "string" ||
        typeof account.appid !== "string" ||
        typeof account.userName !== "string" ||
        typeof account.displayName !== "string" ||
        typeof account.service !== "object") {
        return false;
    }

    return true;
}

function _checkCallback(successCallback, errorCallback) {
    tizen1_utils.validateArgumentType(successCallback, "function",
                                        new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
    if (errorCallback) {
        tizen1_utils.validateArgumentType(errorCallback, "function",
                                            new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
    }
}

_self = {
    getAccounts : function () {
        var results = [];
        utils.forEach(_data.accounts, function (account) {
            results.push(utils.copy(account));
        });

        return results;
    },

    getAccountById : function (id) {
        var acccount = null;

        if (typeof id !== "string") {
            throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
        }

        if (_data.accounts[id]) {
            account = utils.copy(_data.accounts[id]);
        }

        return account;
    },

    getAccountByUserName : function (userName) {
        var result = null;

        if (typeof userName !== "string") {
            throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
        }

        utils.forEach(_data.accounts, function (account) {
            if (userName === account.userName) {
                result = utils.copy(account);
            }
        });

        return result;
    },

    getAccountByappId : function (appId) {
        var result = null;

        if (typeof appId !== "string") {
            throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
        }

        utils.forEach(_data.accounts, function (account) {
            if (appId === account.appId) {
                result = utils.copy(account);
            }
        });

        return result;
    },

    getAccountByServiceId : function (serviceId) {
        var result = null;

        if (typeof serviceId !== "string") {
            throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
        }

        utils.forEach(_data.accounts, function (account) {
            if (serviceId === account.service.id) {
                result = utils.copy(account);
            }
        });

        return result;
    },

    getAccountByTag : function (tag) {
        var results = [], i;

        if (typeof tag !== "string") {
            throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
        }

        utils.forEach(_data.accounts, function (account) {
            for (i in account.service.tag) {
                if (tag === account.service.tag[i]) {
                    results.push(utils.copy(account));
                    break;
                }
            }
        });

        return results;
    },

    add : function (account, successCallback, errorCallback) {
        if (!_checkAccount(account)) {
            throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
        }

        _checkCallback(successCallback, errorCallback);

        if (!_data.accounts[account.id]) {
            _data.accounts[account.id] = utils.copy(account);
        }

        successCallback();
    },

    update : function (account, successCallback, errorCallback) {
        if (!_checkAccount(account)) {
            throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
        }

        _checkCallback(successCallback, errorCallback);

        if (!_data.accounts[account.id]) {
            errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
            return;
        }

        _data.accounts[account.id] = utils.copy(account);
        successCallback();
    },

    remove : function (id, successCallback, errorCallback) {
        if (typeof id !== "string") {
            throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
        }

        _checkCallback(successCallback, errorCallback);

        if (!_data.accounts[id]) {
            errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
            return;
        }

        delete _data.accounts[id];
        successCallback();
    },

    getAccountApplications : function () {
        var results = [];
        /* FIXME: wait for API update */
        return results;
    }
};

function _initialize() {
    _data.accounts = db.retrieveObject(_data.DB_ACCOUNT_KEY) || {};
}

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/alarm', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    event = require('ripple/event'),
    utils = require('ripple/utils'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    AlarmRelative = require('ripple/platform/tizen/2.0/AlarmRelative'),
    AlarmAbsolute = require('ripple/platform/tizen/2.0/AlarmAbsolute'),
    AlarmStore,
    _DB_ALARMS_KEY = "tizen1.0-db-alarms",
    PERIOD_MINUTE = 60,
    PERIOD_HOUR   = 60 * PERIOD_MINUTE,
    PERIOD_DAY    = 24 * PERIOD_HOUR,
    PERIOD_WEEK   = 7 * PERIOD_DAY,
    _alarms = {}, _alarmStack = [],
    _security = {
        "http://tizen.org/privilege/alarm": ["add", "remove", "removeAll"]
    },
    _isInitialized = false, _self;

function _initialize() {
    _alarms = db.retrieveObject(_DB_ALARMS_KEY);
    utils.forEach(_alarms, function (alarmStore) {
        alarmStore.date = new Date(alarmStore.date);
        _alarmStack.push(alarmStore);
    });
    _isInitialized = true;
}

function _get() {
    if (!_isInitialized) {
        _initialize();
    }
}

function _save() {
    db.saveObject(_DB_ALARMS_KEY, _alarmStack);
}

function _updateDB(alarmStore) {
    _alarmStack.push(alarmStore);
    _save();
}

function _getCurrentAppId() {
    return db.retrieve("current-url");
}

function _checkTriggerAlarm(alarm) {
    var remainingTime, nextTriggerDate;

    if (alarm.delay !== undefined) { // Alarm is relative
        if (alarm.period !== null)
            return false;

        remainingTime = alarm.getRemainingSeconds();
        if (remainingTime === null)
            return true; // This alarm is triggered, remove it
    } else if (alarm.period !== undefined) { // Alarm is absolute,no repeat
        nextTriggerDate = alarm.getNextScheduledDate();
        if (nextTriggerDate === null)
            return true; // Already triggered
    }

    return false; // Alarm is repeat, not expired
}

function _convertToAlarm(alarmStore) {
    var alarm, frequency;

    if (alarmStore.delay !== null) { // AlarmRelative
        alarm = new AlarmRelative(alarmStore.delay, alarmStore.period);
        alarm.date = alarmStore.date;
    } else { // AlarmAbsolute
        if (alarmStore.period !== null && alarmStore.period !== PERIOD_WEEK) {
            frequency = alarmStore.period;
        } else if (alarmStore.period === PERIOD_WEEK) {
            frequency = alarmStore.daysOfTheWeek;
        }
        alarm = new AlarmAbsolute(alarmStore.date, frequency);
    }

    alarm.__defineGetter__("id", function () {
        return alarmStore.id;
    });

    return alarm;
}

function _eventCheckAlarm(id) {
    var alarm, diff;

    _get();
    utils.forEach(_alarmStack, function (alarmStore) {
        if (alarmStore.id !== id)
            return;

        alarm = _convertToAlarm(alarmStore);
        if (alarm.delay !== undefined) {
            diff = alarm.getRemainingSeconds();
            if (0 < diff && diff < 2) {
                event.trigger("SendTriggerAppId", [alarmStore.applicationId]);
            }
        } else {
            diff = (new Date()) - alarm.getNextScheduledDate();
            if (-2000 < diff && diff < 2000) {
                event.trigger("SendTriggerAppId", [alarmStore.applicationId]);
            }
        }
    });
}


_self = function () {
    var currentAppId, alarm;

    alarm = {
        add: function (alarm, applicationId, appControl) {
            var id, alarmStore;

            if (!_security.add) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            t.AlarmManager("add", arguments);

            alarm.__defineGetter__("id", function () {
                return id;
            });

            id = Math.uuid(null, 16);
            currentAppId = _getCurrentAppId(); // Update The Current URL.
            alarmStore = new AlarmStore(alarm, applicationId, currentAppId, appControl);
            _updateDB(alarmStore);
        },

        remove: function (id) {
            var isFound = false, i;

            if (!_security.remove) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            t.AlarmManager("remove", arguments);

            for (i in _alarmStack) {
                if (_alarmStack[i].id !== id)
                    continue;

                _alarmStack.splice(i, 1);
                _save();
                isFound = true;
            }

            if (!isFound) {
                throw new WebAPIException(errorcode.NOT_FOUND_ERR);
            }
        },

        removeAll: function () {
            var availableStack = [], i;

            if (!_security.removeAll)
                throw new WebAPIException(errorcode.SECURITY_ERR);

            t.AlarmManager("removeAll", arguments);

            for (i in _alarmStack) {
                if (_alarmStack[i].currentAppId === currentAppId)
                    continue;

                availableStack.push(_alarmStack[i]);
            }
            _alarmStack = availableStack;
            _save();
        },

        get: function (id) {
            var isFound = false, item, isExpired, alarm;

            t.AlarmManager("get", arguments);

            for (item in _alarmStack) {
                if (_alarmStack[item].id === id) {
                    alarm = _convertToAlarm(_alarmStack[item]);
                    isExpired = _checkTriggerAlarm(alarm);
                    if (isExpired) {
                        _alarmStack.splice(item, 1);
                        _save();
                    } else {
                        isFound = true;
                    }
                    break;
                }
            }
            if (!isFound) {
                throw new WebAPIException(errorcode.NOT_FOUND_ERR);
            }

            return alarm;
        },

        getAll: function () {
            var availableStack = [], backAlarms = [], isExpired, alarm, i;

            t.AlarmManager("getAll", arguments);

            for (i in _alarmStack) {
                alarm = _convertToAlarm(_alarmStack[i]); // alarmStore --> alarm
                isExpired = _checkTriggerAlarm(alarm); // Check if the alarm is expired
                if (isExpired)
                    continue;

                availableStack.push(_alarmStack[i]);
                if (_alarmStack[i].currentAppId === currentAppId)
                    backAlarms.push(alarm);
            }
            _alarmStack = availableStack;
            _save();
            return backAlarms;
        },

        handleSubFeatures: function (subFeatures) {
            var i, subFeature;

            for (subFeature in subFeatures) {
                for (i in _security[subFeature]) {
                    _security[_security[subFeature][i]] = true;
                }
            }
        }
    };

    currentAppId = _getCurrentAppId();
    _get();

    alarm.__defineGetter__("PERIOD_MINUTE", function () {
        return PERIOD_MINUTE;
    });

    alarm.__defineGetter__("PERIOD_HOUR", function () {
        return PERIOD_HOUR;
    });

    alarm.__defineGetter__("PERIOD_DAY", function () {
        return PERIOD_DAY;
    });

    alarm.__defineGetter__("PERIOD_WEEK", function () {
        return PERIOD_WEEK;
    });

    return alarm;
};

AlarmStore = function (alarmObject, applicationId, currentAppId, appControl) {
    var _self;
    _self = {
        id: alarmObject.id,
        delay: alarmObject.delay || null,
        date: alarmObject.date || null,
        period: alarmObject.period || null,
        daysOfTheWeek: alarmObject.daysOfTheWeek || null,
        applicationId: applicationId,
        currentAppId: currentAppId,
        appControl: appControl || null
    };
    return _self;
};

event.on("CheckAlarm", function (id) {
    _eventCheckAlarm(id);
});

module.exports = _self;

});
define('ripple/platform/tizen/2.0/application', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    event = require('ripple/event'),
    app = require('ripple/app'),
    db = require('ripple/db'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    ApplicationControl = require('ripple/platform/tizen/2.0/ApplicationControl'),
    Application,
    ApplicationInformation,
    ApplicationContext,
    ApplicationCertificate,
    RequestedApplicationControl,
    _DB_APPLICATION_KEY = "tizen1-db-application",
    PSEUDO_PACKAGE_ID = "pseudopack00",
    PSEUDO_APP_ID = "pseudoapp00",
    _security = {
        "http://tizen.org/privilege/application.launch": ["launch", "launchAppControl"],
        "http://tizen.org/privilege/appmanager.kill": ["kill"],
        "http://tizen.org/privilege/appmanager.certificate": ["getAppCerts"]
    },
    _data = {
        applications : {},
        applicationContexts : {},
        activeApp : null,
        listeners : {}
    },
    _appDialogTemplate = jQuery("#app-dialog-template").html(),
    _appDialogTemplate_short = jQuery("#app-dialog2-template").html(),
    _appDialogTemplate_exit_hide = jQuery("#app-dialog3-template").html(),
    reasonable_mimetype = {
        "application"   : true,
        "text"          : true,
        "video"         : true,
        "audio"         : true,
        "image"         : true
    },
    _self;

function _setupCurrentApp() {
    var info, contextId, packageId, appId;
    info = app.getInfo();
    packageId = info.tizenPackageId || PSEUDO_PACKAGE_ID;
    appId = info.tizenAppId || PSEUDO_APP_ID;
    contextId = Math.uuid(null, 16);
    _data.applications[appId] = {
        id: appId,
        name: info.name,
        iconPath: info.icon,
        version: info.version,
        show: true,
        categories: [],
        installDate: new Date(),
        size: 1024,
        packageId: packageId,
        sharedURI: "/usr/local/share/",
        operation: "",
        appControl: {
            uri: "",
            mime: "",
            category: "",
            data: []
        },
        type: "AUTHOR_ROOT",
        value: ""
    };
    event.trigger("install-current-app", [_data.applications[appId]]);
    _data.applicationContexts[contextId] = {id: contextId, appId: appId};
    _data.activeApp = _data.applicationContexts[contextId];
}

function _translate(apps) {
    // translate string to Date after retrieving from DB,
    // it is a temporary sulusion
    var i;
    for (i in apps) {
        if (typeof apps[i].installDate === 'string') {
            apps[i].installDate = new Date(apps[i].installDate);
        }
    }
    return apps;
}

function _initialize() {
    _data = {
        applications : {},
        applicationContexts : {},
        activeApp : null,
        listeners : {}
    };

    if (!db.retrieveObject(_DB_APPLICATION_KEY))
        return;

    _data.applications = _translate(db.retrieveObject(_DB_APPLICATION_KEY).installedAppList);
    _setupCurrentApp();
    $("#app-dialog").dialog({
        resizable: false,
        draggable: false,
        modal: true,
        autoOpen: false,
        position: 'center',
        minWidth: '500',
        minHeight: '262',
        open: function () { $(".ui-dialog-titlebar-close", $(this).parent()).hide(); }
    });
}

_self = function () {
    // private
    function getHandle() {
        var handle;
        do {
            handle = Math.uuid(8, 10);
        } while (handle.toString().indexOf('0') === 0);

        return parseInt(handle, 10);
    }

    // public
    function getCurrentApplication() {
        var application, innerApp;

        t.ApplicationManager("getCurrentApplication", arguments);

        /* activeApp update (by WidgetInformationUpdate event) sometime will late after user calling getCurrentApplication()
           for example: load other application by omnibar */
        if (app.getInfo().id !== _data.activeApp.appId) {
            _data.applications = db.retrieveObject(_DB_APPLICATION_KEY).installedAppList;
            utils.forEach(_data.applications, function(item) {
                item.installDate = new Date(item.installDate);
            });
            _setupCurrentApp();
        }
        innerApp = _data.applications[_data.activeApp.appId];
        application = new Application(
                new ApplicationInformation(
                    innerApp.id,
                    innerApp.name,
                    innerApp.iconPath,
                    innerApp.version,
                    innerApp.show,
                    innerApp.categories,
                    innerApp.installDate,
                    innerApp.size,
                    innerApp.packageId),
                _data.activeApp.id, innerApp);
        return application;
    }

    function kill(contextId, successCallback, errorCallback) {
        if (!_security.kill) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ApplicationManager("kill", arguments);

        window.setTimeout(function () {
            if (!_data.applicationContexts[contextId]) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                }
                return;
            }

            if (_data.activeApp && (_data.activeApp.id === contextId)) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                }
                return;
            }

            delete _data.applicationContexts[contextId];
            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    function launch(id, successCallback, errorCallback) {
        if (!_security.launch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ApplicationManager("launch", arguments);

        window.setTimeout(function () {
            var htmlContent;

            if (!_data.applications[id]) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                }
                return;
            }

            htmlContent = _appDialogTemplate_short.replace(/#application-name/, _data.applications[id].name)
                .replace(/#application-id/, id);
            jQuery("#app-dialog-box").html(htmlContent);
            $("#app-dialog").dialog("open");

            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    function launchAppControl(appControl, id, successCallback, errorCallback, replyCallback) {
        if (!_security.launchAppControl) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ApplicationManager("launchAppControl", arguments, true);

        window.setTimeout(function () {
            var isFound = false, appId, htmlContent;

            if (id) {
                if (!_data.applications[id]) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }
                htmlContent = _appDialogTemplate.replace(/#application-name/, _data.applications[appId].name)
                    .replace(/#appControl-operation/, _data.applications[appId].operation)
                    .replace(/#appControl-uri/, _data.applications[appId].appControl.uri)
                    .replace(/#appControl-mime/, _data.applications[appId].appControl.mime)
                    .replace(/#appControl-category/, _data.applications[appId].appControl.category)
                    .replace(/#appControl-data/, JSON.stringify(_data.applications[appId].appControl.data));
                jQuery("#app-dialog-box").html(htmlContent);
                $("#app-dialog").dialog("open");

                _data.activeApp.replyCallback = replyCallback;

                if (successCallback) {
                    successCallback();
                }
            } else {
                utils.forEach(_data.applications, function (application) {
                    if (application.operation === appControl.operation) {
                        if (appControl.mime && (typeof appControl.mime === "string")) {
                            if (!reasonable_mimetype[appControl.mime.split("/")[0]]) {
                                return;
                            }
                        }
                        appId = application.id;
                        isFound = true;
                    }
                });

                if (!isFound) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }

                htmlContent = _appDialogTemplate.replace(/#application-name/,
                        _data.applications[appId].name)
                    .replace(/#appControl-operation/, _data.applications[appId].operation)
                    .replace(/#appControl-uri/, _data.applications[appId].appControl.uri)
                    .replace(/#appControl-mime/, _data.applications[appId].appControl.mime)
                    .replace(/#appControl-category/, _data.applications[appId].appControl.category)
                    .replace(/#appControl-data/, JSON.stringify(_data.applications[appId].appControl.data));
                jQuery("#app-dialog-box").html(htmlContent);
                $("#app-dialog").dialog("open");

                _data.activeApp.replyCallback = replyCallback;

                if (successCallback) {
                    successCallback();
                }
            }
        }, 1);
    }

    function findAppControl(appControl, successCallback, errorCallback) {
        var appControlExternal = appControl;

        t.ApplicationManager("findAppControl", arguments, true);

        window.setTimeout(function () {
            var informationArray = [];

            utils.forEach(_data.applications, function (application) {
                if (application.operation === appControl.operation) {
                    informationArray.push(new ApplicationInformation(
                            application.id,
                            application.name,
                            application.iconPath,
                            application.version,
                            application.show,
                            application.categories,
                            application.installDate,
                            application.size,
                            application.packageId));
                }
            });

            successCallback(informationArray, appControlExternal);
        }, 1);
    }

    function getAppsContext(successCallback, errorCallback) {
        t.ApplicationManager("getAppsContext", arguments);

        window.setTimeout(function () {
            var contexts = [];

            utils.forEach(_data.applicationContexts, function (context) {
                contexts.push(new ApplicationContext(context.id, context.appId));
            });

            successCallback(contexts);
        }, 1);
    }

    function getAppContext(contextId) {
        var appContext;

        if (contextId === null || contextId === undefined) {
            appContext = new ApplicationContext(_data.activeApp.id, _data.activeApp.appId);
            return (appContext);
        }

        t.ApplicationManager("getAppContext", arguments);

        if (_data.applicationContexts[contextId]) {
            appContext = new ApplicationContext(contextId, _data.applicationContexts[contextId].appId);
            return (appContext);
        }
        throw new WebAPIException(errorcode.NOT_FOUND_ERR);
    }

    function getAppsInfo(successCallback, errorCallback) {
        t.ApplicationManager("getAppsInfo", arguments);

        window.setTimeout(function () {
            var applications = [];

            utils.forEach(_data.applications, function (application) {
                applications.push(new ApplicationInformation(
                        application.id,
                        application.name,
                        application.iconPath,
                        application.version,
                        application.show,
                        application.categories,
                        application.installDate,
                        application.size,
                        application.packageId));
            });

            successCallback(applications);
        }, 1);
    }

    function getAppInfo(id) {
        var appId, appInfo, theApp;

        t.ApplicationManager("getAppInfo", arguments);

        if (arguments.length === 0) {
            appId = _data.activeApp.appId;
            theApp = _data.applications[appId];

            appInfo = new ApplicationInformation(
                    theApp.id,
                    theApp.name,
                    theApp.iconPath,
                    theApp.version,
                    theApp.show,
                    theApp.categories,
                    theApp.installDate,
                    theApp.size,
                    theApp.packageId);
            return appInfo;
        }

        if (!_data.applications[id]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        theApp = _data.applications[id];
        appInfo = new ApplicationInformation(
                    theApp.id,
                    theApp.name,
                    theApp.iconPath,
                    theApp.version,
                    theApp.show,
                    theApp.categories,
                    theApp.installDate,
                    theApp.size,
                    theApp.packageId);
        return appInfo;
    }

    function getAppCerts(id) {
        var certs = [];

        if (!_security.getAppCerts) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ApplicationManager("getAppCerts", arguments);

        if (arguments.length === 0) {
            id = _data.activeApp.appId;
            certs.push(new ApplicationCertificate(_data.applications[id].type, _data.applications[id].value));
            return certs;
        }

        if (!_data.applications[id]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        certs.push(new ApplicationCertificate(_data.applications[id].type, _data.applications[id].value));
        return certs;
    }

    function getAppSharedURI(id) {
        var appId;

        t.ApplicationManager("getAppSharedURI", arguments);

        if (id === null || id === undefined) {
            appId = _data.activeApp.appId;
            return _data.applications[appId].sharedURI;
        }

        if (!_data.applications[id]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        return _data.applications[id].sharedURI;
    }

    function addAppInfoEventListener(eventCallback) {
        var handle;

        t.ApplicationManager("addAppInfoEventListener", arguments);

        handle = getHandle();
        _data.listeners[handle] = eventCallback;

        return handle;
    }

    function removeAppInfoEventListener(listenerID) {
        if (!_data.listeners[listenerID])
            return;

        delete _data.listeners[listenerID];
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    var application = {
        getCurrentApplication : getCurrentApplication,
        kill : kill,
        launch : launch,
        launchAppControl : launchAppControl,
        findAppControl : findAppControl,
        getAppsContext : getAppsContext,
        getAppContext : getAppContext,
        getAppsInfo : getAppsInfo,
        getAppInfo : getAppInfo,
        getAppCerts : getAppCerts,
        getAppSharedURI: getAppSharedURI,
        addAppInfoEventListener : addAppInfoEventListener,
        removeAppInfoEventListener : removeAppInfoEventListener,
        handleSubFeatures : handleSubFeatures
    };

    return application;
};

Application = function (appInfo, contextId, metaData) {
    var application = {}, requestedAppControl;

    application.appInfo   = appInfo;
    application.contextId = contextId;

    requestedAppControl = new RequestedApplicationControl(
            new ApplicationControl(metaData.operation, metaData.appControl.uri,
                    metaData.appControl.mime, metaData.appControl.category,
                    metaData.appControl.data), application.appInfo.id);

    this.__defineGetter__("appInfo", function () {
        return application.appInfo;
    });

    this.__defineGetter__("contextId", function () {
        return application.contextId;
    });

    this.exit = function () {
        event.trigger("tizen-application-exit", [contextId]);
    };

    this.hide = function () {
        event.trigger("tizen-application-hide", [contextId]);
    };

    this.getRequestedAppControl = function () {
        return requestedAppControl;
    };
};

ApplicationInformation = function (id, name, iconPath, version, show,
        categories, installDate, size, packageId) {
    this.__defineGetter__("id", function () {
        return id;
    });

    this.__defineGetter__("name", function () {
        return name;
    });

    this.__defineGetter__("iconPath", function () {
        return iconPath;
    });

    this.__defineGetter__("version", function () {
        return version;
    });

    this.__defineGetter__("show", function () {
        return show;
    });

    this.__defineGetter__("categories", function () {
        return categories;
    });

    this.__defineGetter__("installDate", function () {
        return installDate;
    });

    this.__defineGetter__("size", function () {
        return size;
    });

    this.__defineGetter__("packageId", function () {
        return packageId;
    });
};

ApplicationContext = function (id, appId) {
    this.__defineGetter__("id", function () {
        return id;
    });

    this.__defineGetter__("appId", function () {
        return appId;
    });
};

RequestedApplicationControl = function (appControl, callerAppId) {
    this.__defineGetter__("appControl", function () {
        return appControl;
    });

    this.__defineGetter__("callerAppId", function () {
        return callerAppId;
    });

    this.replyResult = function (data) {
        t.RequestedApplicationControl("replyResult", arguments);

        event.trigger("appServiceReplied", "Result: " + data);
    };

    this.replyFailure = function () {
        event.trigger("appServiceReplied", "Failure");
    };
};

ApplicationCertificate = function (type, value) {
    this.__defineGetter__("type", function () {
        return type;
    });

    this.__defineGetter__("value", function () {
        return value;
    });
};

jQuery("#app-dialog-return-btn").live("click", function () {
    $("#app-dialog").dialog("close");
});

jQuery("#app-dialog-reload-btn").live("click", function () {
    $("#app-dialog").dialog("close");
    window.tinyHipposReload = true;
    location.reload();
});

jQuery("#app-dialog-generate-reply").live("click", function () {
    var type, data, ret = [];
    type = jQuery('input:radio[name="app-dialog-reply-type"]:checked').val();
    data = jQuery("#app-dialog-reply-json").val();
    $("#app-dialog").dialog("close");
    if (_data.activeApp.replyCallback) {
        switch (type) {
        case "replyResult":
            if (_data.activeApp.replyCallback.onsuccess) {
                if (data === "") {
                    _data.activeApp.replyCallback.onsuccess();
                } else {
                    try {
                        ret = JSON.parse(data);
                        _data.activeApp.replyCallback.onsuccess(ret);
                    } catch (e) {
                        console.log("replyResult: JSON parsing error: " + e.message);
                        _data.activeApp.replyCallback.onsuccess();
                    }
                }
            }
            break;
        case "replyFailure":
            if (_data.activeApp.replyCallback.onfailure) {
                _data.activeApp.replyCallback.onfailure();
            }
            break;
        }
    }
});

event.on("ApplicationLoad", function () {
    _initialize();
});

event.on("tizen-application-exit", function () {
    var htmlContent;
    htmlContent = _appDialogTemplate_exit_hide.replace(/#application-name/, _data.applications[_data.activeApp.appId].name)
        .replace(/#application-id/, _data.applications[_data.activeApp.appId].id)
        .replace(/#application-operation/g, "exit")
        .replace(/#application-verb/, "launch")
        .replace(/#next-command/g, "Launch")
        .replace(/#application-btn/, "app-dialog-reload-btn");
    jQuery("#app-dialog-box").html(htmlContent);
    $("#app-dialog").dialog("open");
});

event.on("tizen-application-hide", function () {
    var htmlContent;
    htmlContent = _appDialogTemplate_exit_hide.replace(/#application-name/, _data.applications[_data.activeApp.appId].name)
        .replace(/#application-id/, _data.applications[_data.activeApp.appId].id)
        .replace(/#application-operation/g, "hide")
        .replace(/#application-verb/, "show")
        .replace(/#next-command/g, "Show")
        .replace(/#application-btn/, "app-dialog-return-btn");
    jQuery("#app-dialog-box").html(htmlContent);
    $("#app-dialog").dialog("open");
});

event.on("programChanged", function (status, id) {
    var callback, data, innerApp;
    _data.applications = db.retrieveObject(_DB_APPLICATION_KEY).installedAppList;
    utils.forEach(_data.applications, function(item) {
        item.installDate = new Date(item.installDate);
    });
    _setupCurrentApp();
    switch (status) {
    case "installed":
    case "updated":
        innerApp = _data.applications[id];
        data = new ApplicationInformation(
                        innerApp.id,
                        innerApp.name,
                        innerApp.iconPath,
                        innerApp.version,
                        innerApp.show,
                        innerApp.categories,
                        innerApp.installDate,
                        innerApp.size,
                        innerApp.packageId);
        break;
    case "uninstalled":
        data = id;
        break;

    default:
        return;
    }
    callback = "on" + status;
    utils.forEach(_data.listeners, function (listener) {
        listener[callback](data);
    });
});

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/battery', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    _data = {
        charging: true,
        chargingTime: 0,
        level: 1.0,
        dischargingTime: Infinity,
        chargingchange: {},
        chargingtimechange: {},
        levelchange: {},
        dischargingtimechange: {}
    },
    _self;

_self = {
    addEventListener: function (event, callback, capture) {
        if (typeof callback !== "function" || event === undefined) {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
        switch (event) {
        case "chargingchange":
        case "chargingtimechange":
        case "levelchange":
        case "dischargingtimechange":
            var isExist = false, item;
            for (item in _data[event]) {
                if (callback === item) {
                    isExist = true;
                    break;
                }
            }
            if (!isExist) {
                _data[event].add(callback);
            }
            break;

        default:
            break;
        }
    },

    removeEventListener: function (event, callback, capture) {
        if (typeof callback !== "function" || event === undefined) {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
        _data[event].unbind(callback);
    },

    dispatchEvent: function (event) {
        if (event === undefined) {
            throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }
        return _data[event].exec(event);
    }
};

_self.__defineGetter__("charging", function () {
    return _data.charging;
});

_self.__defineGetter__("chargingTime", function () {
    return _data.chargingTime;
});

_self.__defineGetter__("level", function () {
    return _data.level;
});

_self.__defineGetter__("dischargingTime", function () {
    return _data.dischargingTime;
});

function _initialize() {
    var callback = [];

    function bind(name) {
        _self.__defineGetter__(name, function () {
            return callback;
        });

        _self.__defineSetter__(name, function (cb) {
            callback = cb;
        });

        return {
            get: function () {
                return callback;
            },

            set: function (value) {
                callback = value;
            },

            add: function (value) {
                callback.push(value);
            },

            exec: function (arg) {
                callback.forEach(function (callback) {
                    return !callback || callback(arg);
                });
            },

            unbind: function (value) {
                if (value === undefined) {
                    callback = [];
                } else {
                    utils.forEach(callback, function (callback, index) {
                        if (callback === value) {
                            callback.splice(index, 1);
                        }
                    });
                }
            }
        };
    }

    _data.chargingchange        = bind("onchargingchange");
    _data.chargingtimechange    = bind("onchargingtimechange");
    _data.levelchange           = bind("onlevelchange");
    _data.dischargingtimechange = bind("ondischargingtimechange");

    event.on("BatteryEvent", function (status) {
        for (var ev in status) {
            if ((status[ev] !== undefined) && (status[ev] !== _data[ev])) {
                _data[ev] = status[ev];
            }
        }
        _data[status.type].exec();
    });
}

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/bluetooth', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    BluetoothDevice = require('ripple/platform/tizen/2.0/BluetoothDevice'),
    BluetoothClassDeviceMajor = require('ripple/platform/tizen/2.0/BluetoothClassDeviceMajor'),
    BluetoothClassDeviceMinor = require('ripple/platform/tizen/2.0/BluetoothClassDeviceMinor'),
    BluetoothClassDeviceService = require('ripple/platform/tizen/2.0/BluetoothClassDeviceService'),
    BluetoothServiceHandler = require('ripple/platform/tizen/2.0/BluetoothServiceHandler'),
    BluetoothAdapter,
    _data = {
        DB_BLUETOOTH_KEY: "tizen1-db-bluetooth_adapter-name",
        DEFAULT_ADAPTER_NAME: "Tizen BT Adapter",
        DEFAULT_ADAPTER_ADDRESS: "12:34:56:78:90:AB",
        availableDevsChanging: false,
        DEFAULT_VISIBLE_TIME: 180000,
        DISCOVER_TIME: 10000,
        DISCOVER_INTERVAL: 1000,
        bluetoothClassDeviceMajor: {},
        bluetoothClassDeviceMinor: {},
        bluetoothClassDeviceService: {},
        adapter: {},
        historyDevs: {},
        availableDevs: {},
        localServices: {}
    },
    _security = {
        "http://tizen.org/privilege/bluetoothmanager": ["setVisible"],
        "http://tizen.org/privilege/bluetooth.admin": ["setName", "setPowered"],
        "http://tizen.org/privilege/bluetooth.gap": ["getDefaultAdapter",
                "discoverDevices", "stopDiscovery", "getKnownDevices",
                "getDevice", "createBonding", "destroyBonding", "hasService"],
        "http://tizen.org/privilege/bluetooth.spp":
                ["registerRFCOMMServiceByUUID", "connectToServiceByUUID",
                "writeData", "readData", "close", "unregister"]
    },
    _self;

function _initialize() {
    var adapterName, devs;

    _data.bluetoothClassDeviceMajor = new BluetoothClassDeviceMajor();
    _data.bluetoothClassDeviceMinor = new BluetoothClassDeviceMinor();
    _data.bluetoothClassDeviceService = new BluetoothClassDeviceService();
    adapterName = db.retrieveObject(_data.DB_BLUETOOTH_KEY) ||
            _data.DEFAULT_ADAPTER_NAME;
    _data.adapter = new BluetoothAdapter(adapterName,
            _data.DEFAULT_ADAPTER_ADDRESS);

    // get defalt nearby devices
    devs = db.retrieveObject("bt-simulated-devices");
    utils.forEach(devs, function (item) {
        if (!_data.availableDevs[item.address]) {
            _data.availableDevs[item.address] = new BluetoothDevice({
                name: item.name,
                address: item.address,
                deviceClass: item.deviceClass,
                isBonded: false,
                isTrusted: item.isTrusted,
                isConnected: false,
                services: item.services,
                metaData: _security
            });
        }
    });
}

BluetoothAdapter = function (devName, devAddress) {
    var adapter,
        timeoutVar,
        _devName = devName,
        _devAddress = devAddress,
        _devPowered = false,
        _devVisible = false,
        _isDiscovering = false,
        discoverInterval;

    // private
    function updateVisibleStatus(status, time) {
        if (!_devPowered)
            return;

        _devVisible = status;
        event.trigger("bt-adapter-visible-changed", [_devVisible]);
        if (_devVisible) {
            if (time > 0) {
                timeoutVar = window.setTimeout(function () {
                    _devVisible = false;
                    event.trigger("bt-adapter-visible-changed", [_devVisible]);
                }, time);
            }
        } else {
            window.clearTimeout(timeoutVar);
        }
    }

    function updatePowerStatus(status) {
        if (_devPowered === status) {
            return;
        }
        if (!status) {
            updateVisibleStatus(false);
            utils.forEach(_data.historyDevs, function (dev) {
                event.trigger("bt-service-state-update", [dev.address, false]);
                event.trigger("bt-device-bonded-changed", [dev.address, false]);
                jQuery("#service-transfer-textarea-" + dev.address.replace(/:/g, "")).val("");
                jQuery("#service-receive-textarea-" + dev.address.replace(/:/g, "")).html("");
            });
        }
        _devPowered = status;
        event.trigger("bt-adapter-power-changed", [_devPowered]);
    }

    // public
    function setName(name, successCallback, errorCallback) {
        if (!_security.setName) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("setName", arguments);

        window.setTimeout(function () {
            if (!_devPowered) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(
                            errorcode.SERVICE_NOT_AVAILABLE_ERR));
                }
                return;
            }

            _devName = name;
            db.saveObject(_data.DB_BLUETOOTH_KEY, _devName);
            event.trigger("bt-adapter-name-changed", [_devName]);
            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    function setPowered(state, successCallback, errorCallback) {
        if (!_security.setPowered) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("setPowered", arguments);

        window.setTimeout(function () {
            updatePowerStatus(state);
            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    function setVisible(mode, successCallback, errorCallback, timeout) {
        if (!_security.setVisible) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("setVisible", arguments);

        window.setTimeout(function () {
            var time;

            if (!_devPowered) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(
                            errorcode.SERVICE_NOT_AVAILABLE_ERR));
                }
                return;
            }

            if (typeof timeout === "number") {
                if (timeout < 0) {
                    time = _data.DEFAULT_VISIBLE_TIME;
                } else {
                    time = timeout * 1000;
                }
            } else {
                time = _data.DEFAULT_VISIBLE_TIME;
            }
            updateVisibleStatus(mode, time);

            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    function discoverDevices(successCallback, errorCallback) {
        if (!_security.discoverDevices) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("discoverDevices", arguments);

        window.setTimeout(function () {
            var interval;

            if (!_devPowered) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(
                            errorcode.SERVICE_NOT_AVAILABLE_ERR));
                }
                return;
            }

            // already discovering
            if (_isDiscovering) {
                return;
            }

            _isDiscovering = true;
            _data.historyDevs = {};

            successCallback.onstarted();

            _data.availableDevsChanging = false;
            utils.forEach(_data.availableDevs, function (item) {
                _data.historyDevs[item.address] = item;
                successCallback.ondevicefound(item);
            });

            discoverInterval = window.setTimeout(function () {
                var devs = [];

                window.clearInterval(interval);
                utils.forEach(_data.historyDevs, function (item) {
                    devs.push(item);
                });
                successCallback.onfinished(devs);
                _isDiscovering = false;
            }, _data.DISCOVER_TIME);

            interval = window.setInterval(function () {
                var removeList = [], i;

                if (!_isDiscovering) {
                    window.clearInterval(interval);
                    return;
                }

                if (_data.availableDevsChanging) {
                    _data.availableDevsChanging = false;
                    utils.forEach(_data.historyDevs, function (item) {
                        if (!_data.availableDevs[item.address]) {
                            removeList.push(item.address);
                        }
                    });
                    for (i in removeList) {
                        successCallback.ondevicedisappeared(removeList[i]);
                        delete _data.historyDevs[removeList[i]];
                    }
                    utils.forEach(_data.availableDevs, function (item) {
                        if (!_data.historyDevs[item.address]) {
                            _data.historyDevs[item.address] = item;
                            successCallback.ondevicefound(item);
                        }
                    });
                }
            }, _data.DISCOVER_INTERVAL);
        }, 1);
    }

    function stopDiscovery(successCallback, errorCallback) {
        if (!_security.stopDiscovery) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("stopDiscovery", arguments);

        window.setTimeout(function () {
            if (!_devPowered) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(
                            errorcode.SERVICE_NOT_AVAILABLE_ERR));
                }
                return;
            }

            if (_isDiscovering) {
                window.clearTimeout(discoverInterval);
            }
            _isDiscovering = false;
            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    function getKnownDevices(successCallback, errorCallback) {
        if (!_security.getKnownDevices) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("getKnownDevices", arguments);

        window.setTimeout(function () {
            var devs = [];

            if (!_devPowered) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(
                            errorcode.SERVICE_NOT_AVAILABLE_ERR));
                }
                return;
            }
            utils.forEach(_data.historyDevs, function (item) {
                devs.push(new BluetoothDevice({
                    name: item.name,
                    address: item.address,
                    deviceClass: item.deviceClass,
                    isBonded: false,
                    isTrusted: item.isTrusted,
                    isConnected: false,
                    services: item.services,
                    metaData: _security
                }));
            });
            successCallback(devs);
        }, 1);
    }

    function getDevice(address, successCallback, errorCallback) {
        if (!_security.getDevice) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("getDevice", arguments);

        window.setTimeout(function () {
            if (!_devPowered) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(
                            errorcode.SERVICE_NOT_AVAILABLE_ERR));
                }
                return;
            }

            if (!_data.historyDevs[address]) {
                if (!_data.availableDevs[address]) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }

                _data.historyDevs[address] = _data.availableDevs[address];
            }

            successCallback(_data.historyDevs[address]);
        }, 1);
    }

    function createBonding(address, successCallback, errorCallback) {
        if (!_security.createBonding) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("createBonding", arguments);

        window.setTimeout(function () {
            if (!_devPowered) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(
                            errorcode.SERVICE_NOT_AVAILABLE_ERR));
                }
                return;
            }

            if (!_data.historyDevs[address]) {
                if (!_data.availableDevs[address]) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }

                _data.historyDevs[address] = _data.availableDevs[address];
            }

            event.trigger("bt-device-bonded-changed", [address, true]);
            successCallback(_data.historyDevs[address]);
        }, 1);
    }

    function destroyBonding(address, successCallback, errorCallback) {
        if (!_security.destroyBonding) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("destroyBonding", arguments);

        window.setTimeout(function () {
            if (!_devPowered) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(
                            errorcode.SERVICE_NOT_AVAILABLE_ERR));
                }
                return;
            }

            if (!_data.historyDevs[address]) {
                if (!_data.availableDevs[address]) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }

                _data.historyDevs[address] = _data.availableDevs[address];
            }

            event.trigger("bt-service-state-update", [address, false]);
            event.trigger("bt-device-bonded-changed", [address, false]);
            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    function registerRFCOMMServiceByUUID(uuid, name, successCallback,
            errorCallback, securityLevel) {
        if (!_security.registerRFCOMMServiceByUUID) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BluetoothAdapter("registerRFCOMMServiceByUUID", arguments);

        window.setTimeout(function () {
            if (!_devPowered) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(
                            errorcode.SERVICE_NOT_AVAILABLE_ERR));
                }
                return;
            }

            _data.localServices[uuid] = new BluetoothServiceHandler({
                uuid: uuid,
                name: name,
                isConnected: false,
                metaData: _security
            });
            successCallback(_data.localServices[uuid]);
        }, 1);
    }

    event.on("bt-simulated-devices-changed", function () {
        var devs = db.retrieveObject("bt-simulated-devices");
        utils.forEach(_data.availableDevs, function (item) {
            if (!devs[item.address]) {
                delete _data.availableDevs[item.address];
            }
        });
        utils.forEach(devs, function (item) {
            if (!_data.availableDevs[item.address]) {
                _data.availableDevs[item.address] = new BluetoothDevice({
                    name: item.name,
                    address: item.address,
                    deviceClass: item.deviceClass,
                    isBonded: false,
                    isTrusted: item.isTrusted,
                    isConnected: false,
                    services: item.services,
                    metaData: _security
                });
            }
        });
        _data.availableDevsChanging = true;
    });

    event.on("bt-unregister-service", function (uuid, successCallback, errorCallback) {
        if (!_data.localServices[uuid]) {
            if (errorCallback) {
                errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
            }
            return;
        }
        delete _data.localServices[uuid];
        if (successCallback) {
            successCallback();
        }
    });

    event.on("bt-power-setting", function (status) {
        updatePowerStatus(status);
    });

    adapter = {
        setName:                     setName,
        setPowered:                  setPowered,
        setVisible:                  setVisible,
        discoverDevices:             discoverDevices,
        stopDiscovery:               stopDiscovery,
        getKnownDevices:             getKnownDevices,
        getDevice:                   getDevice,
        createBonding:               createBonding,
        destroyBonding:              destroyBonding,
        registerRFCOMMServiceByUUID: registerRFCOMMServiceByUUID
    };

    adapter.__defineGetter__("name", function () {
        return _devName;
    });

    adapter.__defineGetter__("address", function () {
        return _devAddress;
    });

    adapter.__defineGetter__("powered", function () {
        return _devPowered;
    });

    adapter.__defineGetter__("visible", function () {
        return _devVisible;
    });

    return adapter;
};

_self = function () {
    var bluetooth;

    function getDefaultAdapter() {
        if (!_security.getDefaultAdapter) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        if (!_data.adapter) {
            throw new WebAPIException(errorcode.UNKNOWN_ERR);
        }

        return _data.adapter;
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    bluetooth = {
        getDefaultAdapter: getDefaultAdapter,
        handleSubFeatures: handleSubFeatures
    };

    bluetooth.__defineGetter__("deviceMajor", function () {
        return _data.bluetoothClassDeviceMajor;
    });

    bluetooth.__defineGetter__("deviceMinor", function () {
        return _data.bluetoothClassDeviceMinor;
    });

    bluetooth.__defineGetter__("deviceService", function () {
        return _data.bluetoothClassDeviceService;
    });

    return bluetooth;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/bookmark', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    BookmarkFolder = require('ripple/platform/tizen/2.0/BookmarkFolder'),
    BookmarkItem = require('ripple/platform/tizen/2.0/BookmarkItem'),
    BookmarkExternal,
    BookmarkInternal,
    BookmarkStorage,
    _data = {
        DB_BOOKMARK_KEY: "tizen1-bookmark",
        bookmarks:       [],
        dbStorage:       []
    },
    _security = {
        "http://tizen.org/privilege/bookmark.read": ["get"],
        "http://tizen.org/privilege/bookmark.write": ["add", "remove"]
    },
    _self;

function _get() {
    _data.dbStorage = db.retrieveObject(_data.DB_BOOKMARK_KEY) || [];
}

function _save() {
    db.saveObject(_data.DB_BOOKMARK_KEY, _data.dbStorage);
}

function _initialize() {
    _get();

    utils.forEach(_data.dbStorage, function (bookmark) {
        _data.bookmarks.push(new BookmarkInternal(bookmark, null));
    });
}

function _persist() {
    _data.dbStorage = [];

    utils.forEach(_data.bookmarks, function (bookmark) {
        _data.dbStorage.push(new BookmarkStorage(bookmark));
    });

    _save();
}

function _isFolder(bookmark) {
    return !bookmark.url;
}

function _isExternal(bookmark) {
    return !("children" in bookmark);
}

function _getChildren(bookmark, BookmarkType, parent) {
    var i, children = [];

    if (!_isExternal(bookmark)) {
        for (i in bookmark.children) {
            children.push(new BookmarkType(bookmark.children[i], parent));
        }
    }

    return children;
}

_self = function () {
    var bookmark;

    // private
    /*
     * map
     *    Map the external bookmark to the internal one in the tree
     *
     * bookmarkExternal
     *    External bookmark Object
     *
     * callback
     *    callback(index, peers). Optional.
     *
     *          Root    Bookmark        Not Found
     * ------------------------------------------
     *  index   0       index           -1
     *  peers   null    peers           null
     *
     * Return   null    peers[index]    undefined
     */

    function map(bookmarkExternal, callback) {
        var trace = [], it, i, peers = null;

        if (!bookmarkExternal) {
            if (callback) {
                callback(0, null);
            }
            return null;
        }

        for (it = bookmarkExternal; it; it = it.parent) {
            trace.push(it);
        }

        for (it = _data.bookmarks; trace.length !== 0; it = it[i].children) {
            bookmarkExternal = trace.pop();
            peers = null;

            if (it.length === 0)
                break;

            for (i in it) {
                if (it[i].external === bookmarkExternal) {
                    peers = it;
                    break;
                }
            }
        }

        if (callback) {
            return callback((peers !== null) ? i : -1, peers);
        }

        return (peers !== null) ? peers[i] : undefined;
    }

    function traverse(bookmarks, trace, level) {
        for (var i in bookmarks) {
            trace.push(bookmarks[i].external);
            if ((level !== 0) && bookmarks[i].children) {
                traverse(bookmarks[i].children, trace, --level);
            }
        }
    }

    function findUrl(bookmarks, url) {
        var i, isFound = false;

        for (i in bookmarks) {
            if (_isFolder(bookmarks[i])) {
                isFound = findUrl(bookmarks[i].children, url);
            } else {
                isFound = (bookmarks[i].url === url);
            }

            if (isFound)
                break;
        }

        return isFound;
    }

    function isExisting(bookmark, peers) {
        var i;

        if (!_isFolder(bookmark)) {
            return findUrl(_data.bookmarks, bookmark.url);
        }

        for (i in peers) {
            if (_isFolder(peers[i]) && (peers[i].title === bookmark.title)) {
                return true;
            }
        }

        return false;
    }

    // public
    function get(parentFolder, recursive) {
        var bookmarks = [], parent, peers;

        if (!_security.get) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BookmarkManager("get", arguments);

        parent = map(parentFolder);
        if ((parent === undefined) || (parent && !_isFolder(parent))) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        peers = parent ? parent.children : _data.bookmarks;
        traverse(peers, bookmarks, recursive ? -1 : 0);

        return bookmarks;
    }

    function add(bookmark, parentFolder) {
        var parent, peers;

        if (!_security.add) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BookmarkManager("add", arguments);

        parent = map(parentFolder);
        if ((parent === undefined) || (parent && !_isFolder(parent))) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        peers = parent ? parent.children : _data.bookmarks;
        if (isExisting(bookmark, peers)) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }

        peers.push(new BookmarkInternal(bookmark));

        _persist();

        bookmark.__defineGetter__("parent", function () {
            return parent ? parent.external : null;
        });
    }

    function remove(bookmark) {
        if (!_security.remove) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.BookmarkManager("remove", arguments);

        if (!bookmark) {
            _data.bookmarks = [];
        } else {
            map(bookmark, function (index, peers) {
                if (index === -1) {
                    throw new WebAPIException(errorcode.NOT_FOUND_ERR);
                }
                peers.splice(index, 1);
            });

            bookmark.__defineGetter__("parent", function () {
                return undefined;
            });
        }

        _persist();
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    bookmark = {
        get:               get,
        add:               add,
        remove:            remove,
        handleSubFeatures: handleSubFeatures
    };

    return bookmark;
};

/*
 * BookmarkInternal     BookmarkStorage     BookmarkExternal
 * ---------------------------------------------------------
 * title                title               title
 * url                  url                 url/-
 * children             children            -
 * external             -                   -
 * -                    -                   parent
 */

BookmarkInternal = function (bookmark, parent) {
    this.title    = bookmark.title;
    this.url      = _isFolder(bookmark) ? null : bookmark.url;
    this.children = _isFolder(bookmark) ?
        _getChildren(bookmark, BookmarkInternal, this) : null;
    this.external = _isExternal(bookmark) ? bookmark :
        new BookmarkExternal(bookmark, parent);
};

BookmarkStorage = function (bookmark) {
    this.title    = bookmark.title;
    this.url      = _isFolder(bookmark) ? null : bookmark.url;
    this.children = _isFolder(bookmark) ?
        _getChildren(bookmark, BookmarkStorage) : null;
};

BookmarkExternal = function (bookmark, parent) {
    var self;

    if (_isFolder(bookmark)) {
        self = new BookmarkFolder(bookmark.title);
    } else {
        self = new BookmarkItem(bookmark.title, bookmark.url);
    }

    self.__defineGetter__("parent", function () {
        return parent ? parent.external : null;
    });

    return self;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/calendar', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    TZDate = require('ripple/platform/tizen/2.0/TZDate'),
    TDur = require('ripple/platform/tizen/2.0/TimeDuration'),
    CalendarItem = require('ripple/platform/tizen/2.0/CalendarItem'),
    CalendarEvent = require('ripple/platform/tizen/2.0/CalendarEvent'),
    CalendarEventId = require('ripple/platform/tizen/2.0/CalendarEventId'),
    CalendarTask = require('ripple/platform/tizen/2.0/CalendarTask'),
    Calendar,
    CalendarStorage,
    CalendarItemsStorage,
    _DB_CALENDARS_KEY = "tizen1-db-calendars",
    _watchers = [],
    _calendars = {
        EVENT: {},
        TASK: {}
    },
    _calendarsStorage,
    _security = {
        "http://tizen.org/privilege/calendar.read": ["getCalendars",
                "getUnifiedCalendar", "getDefaultCalendar", "getCalendar",
                "get", "find", "addChangeListener", "removeChangeListener",
                "expandRecurrence", "convertToString", "clone"],
        "http://tizen.org/privilege/calendar.write": ["add", "addBatch",
                "update", "updateBatch", "remove", "removeBatch"]
    },
    _self;

function _isValidId(id) {
    return (/[a-z]|[A-Z]|[0-9]|[\-]/).test(id);
}

function retrieveCalendars() {
    _calendarsStorage = db.retrieveObject(_DB_CALENDARS_KEY) || {EVENT: {}, TASK: {}};
}

function saveCalendars() {
    db.saveObject(_DB_CALENDARS_KEY, _calendarsStorage);
}

_self = function () {
    var calendarManager;

    // private
    function loadCalendars(type) {
        var calsStorage, defCalendar, id, i, item;

        retrieveCalendars();
        calsStorage = _calendarsStorage[type];

        if (tizen1_utils.isEmptyObject(calsStorage)) {
            defCalendar = new Calendar(type, "Default " + type.toLowerCase() + " calendar");

            _calendars[type][defCalendar.id] = defCalendar;
            calsStorage[defCalendar.id] = new CalendarStorage(defCalendar);
        } else {
            for (id in calsStorage) {
                for (i in calsStorage[id].items) {
                    item = calsStorage[id].items[i];
                }
                _calendars[type][id] = new Calendar(type, calsStorage[id].name,
                        calsStorage[id].items, id);
            }
        }
    }

    // public
    function getCalendars(type, successCallback, errorCallback) {
        if (!_security.getCalendars) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.CalendarManager("getCalendars", arguments);

        window.setTimeout(function () {
            var i, result = [];

            if (tizen1_utils.isEmptyObject(_calendars[type])) {
                loadCalendars(type);
            }

            if (_calendars.length !== 0) {
                for (i in _calendars[type]) {
                    result.push(_calendars[type][i]);
                }
                successCallback(result);
            } else if (errorCallback) {
                errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
            }
        }, 1);
    }

    function getUnifiedCalendar(type) {
        var id, calendar;

        if (!_security.getUnifiedCalendar) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.CalendarManager("getUnifiedCalendar", arguments);

        if (tizen1_utils.isEmptyObject(_calendars[type])) {
            loadCalendars(type);
        }

        for (id in _calendars[type]) {
            calendar = _calendars[type][id];
            break;
        }

        if (calendar === undefined)
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);

        return calendar;
    }

    function getDefaultCalendar(type) {
        var id, calendar;

        if (!_security.getDefaultCalendar) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.CalendarManager("getDefaultCalendar", arguments);

        if (tizen1_utils.isEmptyObject(_calendars[type])) {
            loadCalendars(type);
        }

        for (id in _calendars[type]) {
            calendar = _calendars[type][id];
            break;
        }

        if (calendar === undefined)
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);

        return calendar;
    }

    function getCalendar(type, id) {
        var calendar;

        if (!_security.getCalendar) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.CalendarManager("getCalendar", arguments);

        if (tizen1_utils.isEmptyObject(_calendars[type])) {
            loadCalendars(type);
        }

        calendar = _calendars[type][id];
        if (calendar === undefined)
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);

        return calendar;
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    calendarManager = {
        getCalendars:       getCalendars,
        getUnifiedCalendar: getUnifiedCalendar,
        getDefaultCalendar: getDefaultCalendar,
        getCalendar:        getCalendar,
        handleSubFeatures:  handleSubFeatures
    };

    return calendarManager;
};

Calendar = function (type, name, storageItems, calendarId) {
    var privateItems = {},
        defaultWatchId = 0;
    calendarId = calendarId || Math.uuid(null, 16);

    // private
    function createCalendarItem() {
        var calendarItem = null;

        switch (type) {
        case "EVENT":
            calendarItem = new CalendarEvent();
            break;

        case "TASK":
            calendarItem = new CalendarTask();
            break;

        default:
            break;
        }

        return calendarItem;
    }

    function isValidCalendarItemId(itemId) {
        var i;

        if (!_isValidId(itemId))
            return false;

        for (i in privateItems) {
            if (i === itemId)
                return true;
        }

        return false;
    }

    function loadCalendarItemInit(calendarItem, storageItem) {
        calendarItem.description    = utils.copy(storageItem.description);
        calendarItem.summary        = utils.copy(storageItem.summary);
        calendarItem.isAllDay       = utils.copy(storageItem.isAllDay);
        calendarItem.startDate      = storageItem.startDate;
        if (storageItem.startDate instanceof TZDate) {
            calendarItem.startDate      = storageItem.startDate.addDuration(new TDur(0, 'MSECS'));
        }
        if (typeof storageItem.startDate === 'string') {
            calendarItem.startDate      = new TZDate(new Date(storageItem.startDate));
        }

        calendarItem.duration       = utils.copy(storageItem.duration);
        calendarItem.location       = utils.copy(storageItem.location);
        calendarItem.geolocation    = utils.copy(storageItem.geolocation);
        calendarItem.organizer      = utils.copy(storageItem.organizer);
        calendarItem.visibility     = utils.copy(storageItem.visibility);
        calendarItem.status         = utils.copy(storageItem.status);
        calendarItem.priority       = utils.copy(storageItem.priority);
        calendarItem.alarms         = utils.copy(storageItem.alarms);
        calendarItem.categories     = utils.copy(storageItem.categories);
        calendarItem.attendees      = utils.copy(storageItem.attendees);
    }

    function loadCalendarEventInit(calendarItem, storageItem) {
        loadCalendarItemInit(calendarItem, storageItem);

        calendarItem.endDate = storageItem.endDate;
        if (storageItem.endDate instanceof TZDate) {
            calendarItem.endDate = storageItem.endDate.addDuration(new TDur(0, 'MSECS'));
        }
        if (typeof storageItem.endDate === 'string') {
            calendarItem.endDate = new TZDate(new Date(storageItem.endDate));
        }
        calendarItem.availability = utils.copy(storageItem.availability);
        calendarItem.recurrenceRule = utils.copy(storageItem.recurrenceRule);
        calendarItem.expandRecurrence = function (startDate, endDate, successCallback, errorCallback) {
            if (!_security.expandRecurrence) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            calendarItem.startDate = startDate;
            calendarItem.endDate   = endDate;

            if (errorCallback) {
                window.setTimeout(function () {
                    errorCallback(new WebAPIError(errorcode.NOT_SUPPORTED_ERR));
                }, 1);
            }
        };
        calendarItem.frequency       = utils.copy(storageItem.frequency);
        calendarItem.interval        = utils.copy(storageItem.interval);
        calendarItem.untilDate = storageItem.untilDate;
        if (storageItem.untilDate instanceof TZDate) {
            calendarItem.untilDate = storageItem.untilDate.addDuration(new TDur(0, 'MSECS'));
        }
        if (typeof storageItem.untilDate === 'string') {
            calendarItem.untilDate = new TZDate(new Date(storageItem.untilDate));
        }
        calendarItem.occurrenceCount = utils.copy(storageItem.occurrenceCount);
        calendarItem.daysOfTheWeek   = utils.copy(storageItem.daysOfTheWeek);
        calendarItem.setPositions    = utils.copy(storageItem.setPositions);
        calendarItem.exceptions      = utils.copy(storageItem.exceptions);
    }

    function loadCalendarTaskInit(calendarItem, storageItem) {
        loadCalendarItemInit(calendarItem, storageItem);

        calendarItem.dueDate = storageItem.dueDate;
        if (storageItem.dueDate instanceof TZDate) {
            calendarItem.dueDate = storageItem.dueDate.addDuration(new TDur(0, 'MSECS'));
        }
        if (typeof storageItem.dueDate === 'string') {
            calendarItem.dueDate = new TZDate(new Date(storageItem.dueDate));
        }
        calendarItem.completeDate = storageItem.completeDate;
        if (storageItem.completeDate instanceof TZDate) {
            calendarItem.completeDate = storageItem.completeDate.addDuration(new TDur(0, 'MSECS'));
        }
        if (typeof storageItem.completeDate === 'string') {
            calendarItem.completeDate = new TZDate(new Date(storageItem.completeDate));
        }
        calendarItem.progress      = utils.copy(storageItem.progress);
    }

    function loadCalendarItems() {
        var i, calendarItem;

        if (storageItems === undefined)
            return;

        for (i in storageItems) {
            calendarItem = new CalendarItem(type, i, storageItems[i].lastModificationDate? new TZDate(new Date(storageItems[i].lastModificationDate)) : null, _security);

            if (type === "EVENT") {
                loadCalendarEventInit(calendarItem, storageItems[i]);
            } else {
                loadCalendarTaskInit(calendarItem, storageItems[i]);
            }

            privateItems[i] = calendarItem;
        }
    }

    function saveCalendarItems() {
        _calendarsStorage[type][calendarId] ||  (_calendarsStorage[type][calendarId] = {});
        _calendarsStorage[type][calendarId].items = new CalendarItemsStorage(privateItems);
        saveCalendars();
    }

    // public
    function get(id) {
        var item, uid, CalendarItemType, external = {};

        if (!_security.get) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Calendar("get", arguments);

        if (type === "EVENT") {
            t.CalendarEventId(id);
            uid = id.uid;
            CalendarItemType = CalendarEvent;
        } else {
            t.CalendarTaskId(id);
            uid = id;
            CalendarItemType = CalendarTask;
        }

        if (!isValidCalendarItemId(uid))
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);

        item = new CalendarItemType(privateItems[uid]);
        external.id                   = privateItems[uid].id;
        external.lastModificationDate = privateItems[uid].lastModificationDate;

        item.__defineGetter__("calendarId", function () {
            return calendarId;
        });

        item.__defineGetter__("id", function () {
            return external.id;
        });

        item.__defineGetter__("lastModificationDate", function () {
            return external.lastModificationDate;
        });

        return item;
    }

    function add(item) {
        var uid, external = {};

        if (!_security.add) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Calendar("add", arguments);

        uid = Math.uuid(null, 16);
        privateItems[uid] = t.CalendarItem(item, "+");
        if (type === "EVENT") {
            privateItems[uid].id = new CalendarEventId(uid);
        } else {
            privateItems[uid].id = uid;
        }
        privateItems[uid].lastModificationDate = new TZDate();

        external.id = privateItems[uid].id;
        external.lastModificationDate = privateItems[uid].lastModificationDate;

        saveCalendarItems();

        // set the calendarId of the item
        item.__defineGetter__("calendarId", function () {
            return calendarId;
        });

        item.__defineGetter__("id", function () {
            return external.id;
        });

        item.__defineGetter__("lastModificationDate", function () {
            return external.lastModificationDate;
        });

        window.setTimeout(function () {
            for (var i in _watchers) {
                _watchers[i].onitemsadded([item]);
            }
        }, 1);
    }

    function addBatch(items, successCallback, errorCallback) {
        if (!_security.addBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Calendar("addBatch", arguments, true);

        window.setTimeout(function () {
            var i, j, uid, external = [];

            for (i in items) {
                uid = Math.uuid(null, 16);
                privateItems[uid] = utils.copy(items[i]);

                if (type === "EVENT") {
                    privateItems[uid].id = new CalendarEventId(uid);
                } else {
                    privateItems[uid].id = uid;
                }

                external[i] = {};
                external[i].id = privateItems[uid].id;
                external[i].lastModificationDate = new TZDate();

                items[i].__defineGetter__("calendarId", function () {
                    return calendarId;
                });

                items[i].__defineGetter__("id", function () {
                    return external[i].id;
                });

                items[i].__defineGetter__("lastModificationDate", function () {
                    return external[i].lastModificationDate;
                });
            }

            saveCalendarItems();

            if (successCallback) {
                successCallback(items);
            }
            for (j in _watchers) {
                _watchers[j].onitemsadded(items);
            }
        }, 1);
    }

    function update(item, updateAllInstances) {
        var calendarItem, attr, uid;

        if (!_security.update) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Calendar("update", arguments);

        uid = (type === "EVENT") ? item.id.uid : item.id;
        if (!isValidCalendarItemId(uid))
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);

        if (updateAllInstances === undefined || updateAllInstances === null) {
            updateAllInstances = true;
        }

        if ((type === "EVENT") && !updateAllInstances) {
            calendarItem = createCalendarItem();

            for (attr in privateItems[uid]) {
                if (attr !== "id" && attr !== "lastModificationDate") {
                    if (item[attr] !== undefined)
                        calendarItem[attr] = utils.copy(item[attr]);
                    else
                        calendarItem[attr] = utils.copy(privateItems[uid][attr]);
                }
            }

            add(calendarItem);
        } else {
            for (attr in privateItems[uid]) {
                if ((attr !== "id") && (attr !== "lastModificationDate") && (item[attr] !== undefined))
                    privateItems[uid][attr] = utils.copy(item[attr]);
            }
            window.setTimeout(function () {
                var i;

                for (i in _watchers) {
                    _watchers[i].onitemsupdated([utils.copy(privateItems[uid])]);
                }
            }, 1);
        }
        saveCalendarItems();
    }

    function updateBatch(items, successCallback, errorCallback,
            updateAllInstances) {
        if (!_security.updateBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Calendar("updateBatch", arguments, true);

        window.setTimeout(function () {
            var i, j, attr, calendarItem, updatedItems = [], uid;

            for (i in items) {
                uid = (type === "EVENT") ? items[i].id.uid : items[i].id;
                if (!uid || !privateItems[uid]) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }
            }

            if (updateAllInstances) {
                for (i in privateItems) {
                    for (j in items) {
                        uid = (type === "EVENT") ? items[j].id.uid : items[j].id;
                        if (i === uid) {
                            for (attr in privateItems[i]) {
                                if (attr !== "id" && attr !== "lastModificationDate" && items[j][attr] !== undefined)
                                    privateItems[i][attr] = utils.copy(items[j][attr]);
                            }
                            saveCalendarItems();
                            updatedItems.push(utils.copy(privateItems[i]));
                        }
                    }
                }
            } else {
                for (i in items) {
                    calendarItem = createCalendarItem();

                    uid = (type === "EVENT") ? items[i].id.uid : items[i].id;
                    for (attr in privateItems[uid]) {
                        if (attr !== "id" && attr !== "lastModificationDate") {
                            if (items[i][attr] !== undefined)
                                calendarItem[attr] = utils.copy(items[i][attr]);
                            else
                                calendarItem[attr] = utils.copy(privateItems[uid][attr]);
                        }
                    }

                    add(calendarItem);
                    updatedItems.push(utils.copy(calendarItem));
                }
            }

            saveCalendarItems();
            if (successCallback) {
                successCallback();
            }
            for (i in _watchers) {
                _watchers[i].onitemsupdated(utils.copy(updatedItems));
            }
        }, 1);
    }

    function remove(id) {
        var isFound = false, i, uid;

        if (!_security.remove) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Calendar("remove", arguments);

        if (type === "EVENT") {
            t.CalendarEventId(id);
            uid = id.uid;
        } else {
            t.CalendarTaskId(id);
            uid = id;
        }

        for (i in privateItems) {
            if (i === uid) {
                delete privateItems[i];
                isFound = true;
                break;
            }
        }

        if (!isFound)
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);

        saveCalendarItems();

        window.setTimeout(function () {
            var i;

            for (i in _watchers) {
                _watchers[i].onitemsremoved([id]);
            }
        }, 1);
    }

    function removeBatch(ids, successCallback, errorCallback) {
        if (!_security.removeBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Calendar("removeBatch", arguments, true);

        window.setTimeout(function () {
            var i, uid;

            for (i in ids) {
                uid = (type === "EVENT") ? ids[i].uid : ids[i];

                if (!privateItems[uid]) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }
            }

            for (i in ids) {
                uid = (type === "EVENT") ? ids[i].uid : ids[i];
                delete privateItems[uid];
            }
            saveCalendarItems();
            if (successCallback) {
                successCallback();
            }

            for (i in _watchers) {
                _watchers[i].onitemsremoved(utils.copy(ids));
            }
        }, 1);
    }

    function find(successCallback, errorCallback, filter, sortMode) {
        if (!_security.find) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Calendar("find", arguments, true);

        window.setTimeout(function () {
            var i, calendarItems = [], result = [];

            for (i in privateItems) {
                calendarItems.push(privateItems[i]);
            }
            if (calendarItems.length > 0) {
                result = tizen1_utils.query(calendarItems, filter, sortMode);
            }
            successCallback(result);
        }, 1);
    }

    function addChangeListener(successCallback) {
        var watchId;

        if (!_security.addChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Calendar("addChangeListener", arguments);

        watchId = ++defaultWatchId;
        _watchers[watchId] = successCallback;

        return watchId;
    }

    function removeChangeListener(watchId) {
        if (!_security.removeChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        if (!_watchers[watchId])
            return;

        delete _watchers[watchId];
    }

    loadCalendarItems(type, privateItems, storageItems);

    this.__defineGetter__("id", function () {
        return calendarId;
    });
    this.__defineGetter__("name", function () {
        return name;
    });

    this.get                  = get;
    this.add                  = add;
    this.addBatch             = addBatch;
    this.update               = update;
    this.updateBatch          = updateBatch;
    this.remove               = remove;
    this.removeBatch          = removeBatch;
    this.find                 = find;
    this.addChangeListener    = addChangeListener;
    this.removeChangeListener = removeChangeListener;
};

CalendarStorage = function (calendar) {
    this.id   = calendar.id;
    this.name = calendar.name;
};

CalendarItemsStorage = function (privateItems) {
    var itemsStorage = {}, i, attr;

    for (i in privateItems) {
        itemsStorage[i] = {};
        for (attr in privateItems[i]) {
            //TODO: should be
            //      if (privateItems[i][attr] instanceof TZDate) {
            //But, we used "utils.copy" before store the item to privateItems list.
            //So the constructor information all lost
            if ((attr === "startDate" || attr === "endDate" || attr === "dueDate" || attr === "completedDate" || attr === "lastModificationDate") &&
                (privateItems[i][attr])) {

                itemsStorage[i][attr] = privateItems[i][attr].toString();
            } else if (typeof privateItems[i] !== "function") {
                itemsStorage[i][attr] = privateItems[i][attr];
            }
        }
    }

    return itemsStorage;
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/callHistory', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    _DB_CALL_KEY = "tizen1-db-callhistory",
    _data = {
        observers: {},
        callHistory: []
    },
    _security = {
        "http://tizen.org/privilege/callhistory.read": ["find", "addChangeListener", "removeChangeListener"],
        "http://tizen.org/privilege/callhistory.write": ["remove", "removeBatch", "removeAll"]
    },
    _self;

function _getValue(inputValue, key) {
    var keys = key.split("."),
        value = inputValue[keys[0]],
        index;

    for (index = 1; index < keys.length; index++) {
        if (value[keys[index]]) {
            value = value[keys[index]];
        }
    }

    return value;
}

function _filter(inputArray, filter) {
    var index, filterResults = [], compositeResultArray;

    if (filter === null || filter === undefined) {
        return inputArray;
    }

    if (filter.type && filter.filters) {
        filterResults = _filter(inputArray, filter.filters[0]);
        for (index = 1; index < filter.filters.length; index++) {
            compositeResultArray = _filter(inputArray, filter.filters[index]);

            filterResults = tizen1_utils.arrayComposite(filter.type, filterResults, compositeResultArray);
        }
        return filterResults;
    }

    if (filter.attributeName === null || filter.attributeName === undefined) {
        throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
    }

    if (filter.matchFlag) {
        if (filter.attributeName === 'features') {
            filterResults = tizen1_utils.matchAttributeArrayFilter(inputArray, filter.attributeName, filter.matchFlag, filter.matchValue);
        } else {
            filterResults = tizen1_utils.matchAttributeFilter(inputArray, filter.attributeName, filter.matchFlag, filter.matchValue);
        }
    }
    else if (filter.initialValue || filter.endValue) {
        filterResults = tizen1_utils.matchAttributeRangeFilter(inputArray, filter.attributeName, filter.initialValue, filter.endValue);
    }

    return filterResults;
}

function _sort(inputArray, sortMode) {
    if (sortMode.attributeName === null || sortMode.attributeName === undefined) {
        throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
    }

    inputArray.sort(function (a, b) {
        return sortMode.order === "ASC" ? _getValue(a, sortMode.attributeName) - _getValue(b, sortMode.attributeName) :
               _getValue(b, sortMode.attributeName) - _getValue(a, sortMode.attributeName);
    });

    return inputArray;
}

function _save() {
    db.saveObject(_DB_CALL_KEY, _data.callHistory);
}

function _retrieve() {
    var index;

    _data.callHistory = db.retrieveObject(_DB_CALL_KEY) || [];

    for (index = 0; index < _data.callHistory.length; index++) {
        _data.callHistory[index].startTime = new Date(_data.callHistory[index].startTime);
    }
}

function _isValidCallHistoryEntry(arg) {
    return arg && arg.hasOwnProperty("uid") && arg.hasOwnProperty("type") &&
           arg.hasOwnProperty("features") && arg.hasOwnProperty("remoteParties") &&
           arg.hasOwnProperty("startTime") && arg.hasOwnProperty("duration") &&
           arg.hasOwnProperty("direction");
}

function _rtnRmtPty(pty) {
    var _remoteParty = pty.remoteParty,
        _personId = pty.personId,
        _self = {};
    _self.__defineGetter__("remoteParty", function () {
        return _remoteParty;
    });
    _self.__defineGetter__("personId", function () {
        return _personId;
    });
    return _self;
}

function _rtnEntry(entry) {
    var _uid = entry.uid,
        _type = entry.type,
        _features = tizen1_utils.copy(entry.features),
        _remoteParties = [],
        _startTime = new Date(entry.startTime),
        _duration = entry.duration,
        _direction = entry.direction,
        _self = {}, i;

    for (i = 0; i < entry.remoteParties.length; i++) {
        _remoteParties.push(_rtnRmtPty(entry.remoteParties[i]));
    }
    _self.__defineGetter__("uid", function () {
        return _uid;
    });
    _self.__defineGetter__("type", function () {
        return _type;
    });
    _self.__defineGetter__("features", function () {
        return _features;
    });
    _self.__defineGetter__("remoteParties", function () {
        return _remoteParties;
    });
    _self.__defineGetter__("startTime", function () {
        return _startTime;
    });
    _self.__defineGetter__("duration", function () {
        return _duration;
    });
    _self.direction = _direction;

    return _self;
}

function _initialize() {
    _retrieve();

    event.on("CallInProgress", function () {
    });

    event.on("CallRecorded", function (record) {
        var historyEntry = tizen1_utils.copy(record);
        historyEntry.uid = Math.uuid(8, 16);

        _data.callHistory.push(historyEntry);
        _save();

        utils.forEach(_data.observers, function (observer) {
            observer.onadded([historyEntry]);
        });
    });
}

_self = function () {
    this.find = function (successCallback, errorCallback, filter, sortMode, limit, offset) {
        var i, rtn = [],
            filterResults,
            limitValue = limit | 0,
            offsetValue = offset | 0;

        if (!_security.find) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.CallHistory("find", arguments);

        filterResults = tizen1_utils.copy(_data.callHistory);
        if (filter !== null && filter !== undefined) {
            filterResults = _filter(filterResults, filter);
        }

        if (sortMode !== null && sortMode !== undefined) {
            _sort(filterResults, sortMode);
        }

        setTimeout(function () {
            if (limitValue > 0) {
                offsetValue = offsetValue > 0 ? offsetValue : 0;
                filterResults = filterResults.slice(offsetValue, limitValue);
            }

            for (i = 0; i < filterResults.length; i++) {
                rtn.push(_rtnEntry(filterResults[i]));
            }
            successCallback(rtn);
        }, 1);
    };
    this.remove = function (entry) {
        var isFound = false, rtn = [];

        if (!_security.remove) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.CallHistory("remove", arguments);

        _data.callHistory = _data.callHistory.filter(function (element) {
            return utils.some(element, function (value, key) {
                if (tizen1_utils.isEqual(entry[key], value)) {
                    isFound = true;
                    return false;
                }
                return true;
            });
        });

        if (!isFound) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        _save();
        rtn.push(_rtnEntry(entry));
        utils.forEach(_data.observers, function (observer) {
            observer.onchanged(rtn);
        });

    };
    this.removeBatch = function (entries, successCallback, errorCallback) {
        var isFound = false, i, rtn = [];

        if (!_security.removeBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.CallHistory("removeBatch", arguments);

        setTimeout(function () {
            isFound = entries.every(function (element) {
                return _data.callHistory.some(function (callHistory) {
                    return element.uid === callHistory.uid;
                });
            });

            if (!isFound) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                }
                return;
            }

            _data.callHistory = _data.callHistory.filter(function (element) {
                return !entries.some(function (entryValue, entryIndex) {
                    return tizen1_utils.isEqual(element, entryValue);
                });
            });

            _save();

            if (successCallback) {
                successCallback();
            }
            for (i = 0; i < entries.length; i++) {
                rtn.push(_rtnEntry(entries[i]));
            }
            utils.forEach(_data.observers, function (observer) {
                observer.onchanged(rtn);
            });
        }, 1);
    };
    this.removeAll = function (successCallback, errorCallback) {
        var i, rtn = [];

        if (!_security.removeAll) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.CallHistory("removeAll", arguments);

        for (i = 0; i < _data.callHistory.length; i++) {
            rtn.push(_rtnEntry(_data.callHistory[i]));
        }

        _data.callHistory = [];
        _save();

        utils.forEach(_data.observers, function (observer) {
            observer.onchanged(rtn);
        });

        if (successCallback) {
            setTimeout(function () {
                successCallback();
            }, 1);
        }

    };
    this.addChangeListener = function (observerObj) {
        var handle = Number(Math.uuid(8, 10));

        if (!_security.addChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.CallHistory("addChangeListener", arguments);

        _data.observers[handle] = observerObj;

        return handle;
    };
    this.removeChangeListener = function (handle) {
        if (!_security.removeChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        if (!_data.observers[handle])
            return;

        delete _data.observers[handle];
    };
    this.handleSubFeatures = function (subFeatures) {
        function setSecurity(method) {
            _security[method] = true;
        }

        for (var subFeature in subFeatures) {
            utils.forEach(_security[subFeature], setSecurity);
        }
    };
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/contact', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    decorator = require('ripple/platform/tizen/2.0/decorator'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    utils = require('ripple/utils'),
    ContactName = require('ripple/platform/tizen/2.0/ContactName'),
    ContactAddress = require('ripple/platform/tizen/2.0/ContactAddress'),
    ContactPhoneNumber = require('ripple/platform/tizen/2.0/ContactPhoneNumber'),
    ContactEmailAddress = require('ripple/platform/tizen/2.0/ContactEmailAddress'),
    ContactAnniversary = require('ripple/platform/tizen/2.0/ContactAnniversary'),
    ContactOrganization = require('ripple/platform/tizen/2.0/ContactOrganization'),
    ContactWebSite = require('ripple/platform/tizen/2.0/ContactWebSite'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    AddressBook,
    AddressBookData,
    AddressBookStorage,
    Contact,
    ContactData,
    ContactInternal,
    ContactGroup,
    Person,
    PersonBuilder,
    _data = {
        DB_CONTACT_KEY: "tizen1-contact",
        addressBooks:   [],
        contacts:       {},
        persons:        {},
        contactData:    {},
        dbStorage:      {}
    },
    _security = {
        "http://tizen.org/privilege/contact.read": ["getAddressBooks",
                "getUnifiedAddressBook", "getDefaultAddressBook",
                "getAddressBook", "get", "find", "addChangeListener",
                "removeChangeListener", "getGroup", "getGroups", "clone"],
        "http://tizen.org/privilege/contact.write": ["add", "addBatch",
                "update", "updateBatch", "remove", "removeBatch", "addGroup",
                "updateGroup", "removeGroup", "link", "unlink"]
    },
    _self;

function _get() {
    _data.dbStorage = db.retrieveObject(_data.DB_CONTACT_KEY) ||
            {addressBooks: [], persons: {}};
}

function _save() {
    db.saveObject(_data.DB_CONTACT_KEY, _data.dbStorage);
}

function _serialize(obj) {
    var i, dbObj = {};

    for (i in obj) {
        if (typeof obj[i] !== "function")
            dbObj[i] = utils.copy(obj[i]);
    }

    return dbObj;
}

/* check filter type (it's a recursive function)
   0: It is not a filter
   1: CompositeFilter
   2: AttributeFilter
   3: AttributeRangeFilter
 */
function _filterType(filter) {
    var i = 0, ret;

    if (Object.prototype.toString.call(filter) !== "[object Object]") {
        return 0; // 0: it is not a filter
    }

    /* check if it is CompositFilter or not */
    if (filter.type !== null && filter.type !== undefined) {
        /* attribute 'type' of CompositeFilter must be "UNION" or "INTERSECTION" */
        if (filter.type === "UNION" || filter.type === "INTERSECTION") {
            /*attribute 'filters' of CompositeFilter must be AbstractFilter array */
            if (tizen1_utils.isValidArray(filter.filters)) {
                for (i = 0; i < filter.filters.length; i++) {
                    /* recursive call */
                    if (_filterType(filter.filters[i]) === 0) {
                        return 0; // 0: it is not a filter
                    }
                }
            } else {
                return 0; // 0: it is not a filter
            }
        } else {
            return 0; // 0: it is not a filter
        }
        return 1; // CompositeFilter
    }

    /* AttributeFilter or AttributeRangeFilter must have attributeName */
    if (filter.attributeName === null || filter.attributeName === undefined) {
        return 0; // 0: it is not a filter
    } else {
        ret = 2; // assume it is an AttributeFilter
        if ((filter.initialValue !== null && filter.initialValue !== undefined) ||
            (filter.endValue !== null && filter.endValue !== undefined)) {
            ret = 3; // AttributeRangeFilter
        }
        return ret;
    }
}

function _sort(objects, sortMode) {
    function getValue(obj, key) {
        var keys = key.split("."),
            value = obj[keys[0]],
            i;

        for (i = 1; i < keys.length; i++) {
            if (value[keys[i]]) {
                value = value[keys[i]];
            }
        }

        return value;
    }

    objects.sort(function (a, b) {
        return (sortMode.order === "ASC") ?
            (getValue(a, sortMode.attributeName) < getValue(b, sortMode.attributeName) ? -1 : 1):
            (getValue(a, sortMode.attributeName) > getValue(b, sortMode.attributeName) ? -1 : 1);
    });

    return objects;
}

function _replacePerson(oldId, newId) {
    var contact, dbAddressBook, idab, idc, i;

    for (idab in _data.contacts) {
        for (idc in _data.contacts[idab]) {
            contact = _data.contacts[idab][idc];
            if (contact.personId === oldId) {
                if (newId === null) {
                    delete _data.contacts[idab][idc];
                } else {
                    contact.personId = newId;
                }
            }
        }
    }

    if (_data.persons[oldId]) {
        delete _data.persons[oldId];
    }

    for (i in _data.dbStorage.addressBooks) {
        dbAddressBook = _data.dbStorage.addressBooks[i];
        for (idc in dbAddressBook.contacts) {
            contact = dbAddressBook.contacts[idc];
            if (contact.personId === oldId) {
                if (newId === null) {
                    delete dbAddressBook.contacts[idc];
                } else {
                    contact.personId = newId;
                }
            }
        }
    }

    if (_data.dbStorage.persons[oldId]) {
        delete _data.dbStorage.persons[oldId];
    }
}

_self = function () {
    var contact;

    // private
    function loadAddressBooks() {
        var i;

        _get();

        if (_data.dbStorage.addressBooks.length === 0) {
            // Initialize default address books if database is empty
            _data.dbStorage.addressBooks = [
                new AddressBookStorage(Math.uuid(null, 16), "Phone address book", false, {}, []),
                new AddressBookStorage(Math.uuid(null, 16), "SIM address book", false, {}, [])
            ];
        }

        utils.forEach(_data.dbStorage.addressBooks, function (addressBook) {
            _data.addressBooks.push(new AddressBook(addressBook.id, addressBook.name,
                addressBook.readOnly, addressBook.contacts, addressBook.groups));
        });

        for (i in _data.dbStorage.persons) {
            _data.persons[i] = new Person(_data.dbStorage.persons[i]);
        }
    }

    // public
    // Address Book Methods
    function getAddressBooks(successCallback, errorCallback) {
        if (!_security.getAddressBooks) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContactManager("getAddressBooks", arguments);

        window.setTimeout(function () {
            if (_data.addressBooks.length === 0) {
                loadAddressBooks();
            }
            successCallback(_data.addressBooks);
        }, 1);
    }

    function getUnifiedAddressBook() {
        if (!_security.getUnifiedAddressBook) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        if (_data.addressBooks.length === 0) {
            loadAddressBooks();
        }
        return _data.addressBooks[0];
    }

    function getDefaultAddressBook() {
        if (!_security.getDefaultAddressBook) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        if (_data.addressBooks.length === 0) {
            loadAddressBooks();
        }
        return _data.addressBooks[0];
    }

    function getAddressBook(addressBookId) {
        var i;

        if (!_security.getAddressBook) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContactManager("getAddressBook", arguments);

        if (_data.addressBooks.length === 0) {
            loadAddressBooks();
        }
        for (i in _data.addressBooks) {
            if (_data.addressBooks[i].id === addressBookId) {
                return _data.addressBooks[i];
            }
        }

        /* Cannot found */
        throw new WebAPIException(errorcode.NOT_FOUND_ERR);
    }

    // Person Methods
    function get(personId) {
        if (!_security.get) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContactManager("get", arguments);

        if (_data.persons[personId] === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        return new Person(_data.persons[personId]);
    }

    function update(person) {
        var updated;

        if (!_security.update) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContactManager("update", arguments);

        if (!person.id) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
        if (_data.persons[person.id] === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        updated = new Person(person);

        _data.persons[updated.id] = updated;
        _data.dbStorage.persons[updated.id] = _serialize(updated);
        _save();

        window.setTimeout(function () {
            utils.forEach(_data.contactData.listeners, function (listener) {
                listener.onpersonsupdated([new Person(updated)]);
            });
        }, 1);
    }

    function updateBatch(persons, successCallback, errorCallback) {
        if (!_security.updateBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContactManager("updateBatch", arguments, true);

        window.setTimeout(function () {
            var i, updated;

            if (persons.length === 0) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                }
                return;
            }

            for (i in persons) {
                if (!persons[i].id) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                    }
                    return;
                }
                if (_data.persons[persons[i].id] === undefined) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }
            }
            for (i in persons) {
                updated = new Person(persons[i]);

                _data.persons[updated.id] = updated;
                _data.dbStorage.persons[updated.id] = _serialize(updated);
            }
            _save();
            if (successCallback) {
                successCallback();
            }

            utils.forEach(_data.contactData.listeners, function (listener) {
                var i, watched = [];

                for (i in persons) {
                    watched.push(new Person(_data.persons[persons[i].id]));
                }
                listener.onpersonsupdated(watched);
            });
        }, 1);
    }

    function remove(personId) {
        if (!_security.remove) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContactManager("remove", arguments);

        if (_data.persons[personId] === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        _replacePerson(personId, null);
        _save();

        window.setTimeout(function () {
            utils.forEach(_data.contactData.listeners, function (listener) {
                listener.onpersonsremoved([personId]);
            });
        }, 1);
    }

    function removeBatch(personIds, successCallback, errorCallback) {
        if (!_security.removeBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContactManager("removeBatch", arguments, true);

        window.setTimeout(function () {
            var i;

            if (personIds.length === 0) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                }
                return;
            }

            for (i in personIds) {
                if (!personIds[i]) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                    }
                    return;
                }
                if (_data.persons[personIds[i]] === undefined) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }
            }
            for (i in personIds) {
                _replacePerson(personIds[i], null);
            }
            _save();
            if (successCallback) {
                successCallback();
            }

            utils.forEach(_data.contactData.listeners, function (listener) {
                listener.onpersonsremoved(utils.copy(personIds));
            });
        }, 1);
    }

    function find(successCallback, errorCallback, filter, sortMode) {
        if (!_security.find) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContactManager("find", arguments, true);

        window.setTimeout(function () {
            var i, matched = [], result = [];

            if (filter) {
                switch (_filterType(filter)) {
                case 0:
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                    }
                    return;

                case 1:
                    //TODO:
                    //"compositeFilter doesn't support"
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_SUPPORTED_ERR));
                    }
                    return;

                case 2:
                case 3:
                    break;
                }
            }

            if (filter === null || filter === undefined) {
                utils.forEach(_data.persons, function (person) {
                    matched.push(person);
                });
            } else {
                switch (filter.attributeName) {
                case "id":
                case "displayName":
                case "photoURI":
                case "ringtoneURI":
                case "displayContactId":
                    matched = tizen1_utils.matchAttributeFilter(_data.persons,
                            filter.attributeName, filter.matchFlag, filter.matchValue);
                    break;

                case "contactCount":
                    if ((filter.matchFlag !== "EXACTLY") ||
                            (typeof filter.matchValue !== "number")) {
                        if (errorCallback) {
                            errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                        }
                        return;
                    }
                    matched = tizen1_utils.matchAttributeFilter(_data.persons,
                            filter.attributeName, filter.matchFlag, filter.matchValue);
                    break;

                case "hasPhoneNumber":
                case "hasEmail":
                case "isFavorite":
                    if ((filter.matchFlag !== "EXACTLY") ||
                            (typeof filter.matchValue !== "boolean")) {
                        if (errorCallback) {
                            errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                        }
                        return;
                    }
                    matched = tizen1_utils.matchAttributeBooleanFilter(_data.persons,
                            filter.attributeName, filter.matchValue);
                    break;

                default:
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                    }
                    return;
                }
            }

            if (sortMode) {
                _sort(matched, sortMode);
            }

            for (i in matched) {
                result.push(new Person(matched[i]));
            }

            successCallback(result);
        }, 1);
    }

    function addChangeListener(successCallback) {
        var id;

        if (!_security.addChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContactManager("addChangeListener", arguments);

        id = ++_data.contactData.nListener;
        _data.contactData.listeners[id] = successCallback;

        return id;
    }

    function removeChangeListener(watchId) {
        if (!_security.removeChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        if (!_data.contactData.listeners[watchId])
            return;

        delete _data.contactData.listeners[watchId];
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    _data.contactData = new ContactData();

    contact = {
        getAddressBooks:       getAddressBooks,
        getUnifiedAddressBook: getUnifiedAddressBook,
        getDefaultAddressBook: getDefaultAddressBook,
        getAddressBook:        getAddressBook,

        get:                   get,
        update:                update,
        updateBatch:           updateBatch,
        remove:                remove,
        removeBatch:           removeBatch,
        find:                  find,
        addChangeListener:     addChangeListener,
        removeChangeListener:  removeChangeListener,
        handleSubFeatures:     handleSubFeatures
    };

    return contact;
};

AddressBook = function (id, name, readOnly, dbContacts, dbGroups) {
    var addressBook,
        privateData = new AddressBookData(dbContacts, dbGroups);

    // private
    function addNewContact(contact, external) {
        var added, person;

        added = new ContactInternal(contact);
        privateData.contacts[added.id] = added;

        person = new PersonBuilder(added);
        _data.persons[person.id] = person;

        added.personId = person.id;
        added.addressBookId = id;

        dbContacts[added.id] = _serialize(added);
        _data.dbStorage.persons[person.id] = _serialize(_data.persons[person.id]);

        decorator.Contact(external, added);
    }

    // public
    function get(id) {
        if (!_security.get) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("get", arguments);

        if (privateData.contacts[id] === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        return new Contact(privateData.contacts[id]);
    }

    function add(contact) {
        var external = contact;

        if (!_security.add) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        if (addressBook.readOnly) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("add", arguments, true);

        addNewContact(contact, external);
        _save();

        window.setTimeout(function () {
            utils.forEach(privateData.listeners, function (listener) {
                listener.oncontactsadded([new Contact(external)]);
            });
            utils.forEach(_data.contactData.listeners, function (listener) {
                listener.onpersonsadded([new Person(_data.persons[external.personId])]);
            });
        }, 1);
    }

    function addBatch(contacts, successCallback, errorCallback) {
        var external = contacts;
        if (!_security.addBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        if (addressBook.readOnly) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("addBatch", arguments, true);

        window.setTimeout(function () {
            var i, personIds = [];

            if (contacts.length === 0) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                }
                return;
            }

            for (i in contacts) {
                addNewContact(contacts[i], external[i]);
                personIds.push(external[i].personId);
            }
            _save();
            if (successCallback) {
                successCallback(external);
            }

            utils.forEach(privateData.listeners, function (listener) {
                var i, watched = [];

                for (i in contacts) {
                    watched.push(new Contact(external[i]));
                }
                listener.oncontactsadded(watched);
            });
            utils.forEach(_data.contactData.listeners, function (listener) {
                var i, watched = [];

                for (i in personIds) {
                    watched.push(new Person(_data.persons[personIds[i]]));
                }
                listener.onpersonsadded(watched);
            });
        }, 1);
    }

    function update(contact) {
        var updated;

        if (!_security.update) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        if (addressBook.readOnly) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("update", arguments);

        if (!contact.id) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
        if (privateData.contacts[contact.id] === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        updated = new ContactInternal(contact);

        privateData.contacts[updated.id] = updated;
        dbContacts[updated.id] = _serialize(updated);
        _save();

        window.setTimeout(function () {
            utils.forEach(privateData.listeners, function (listener) {
                listener.oncontactsupdated([new Contact(updated)]);
            });
        }, 1);
    }

    function updateBatch(contacts, successCallback, errorCallback) {
        if (!_security.updateBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        if (addressBook.readOnly) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("updateBatch", arguments, true);

        window.setTimeout(function () {
            var i, updated;

            if (contacts.length === 0) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                }
                return;
            }

            for (i in contacts) {
                if (!contacts[i].id) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                    }
                    return;
                }
                if (privateData.contacts[contacts[i].id] === undefined) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }
            }
            for (i in contacts) {
                updated = new ContactInternal(contacts[i]);

                privateData.contacts[updated.id] = updated;
                dbContacts[updated.id] = _serialize(updated);
            }
            _save();
            if (successCallback) {
                successCallback();
            }

            utils.forEach(privateData.listeners, function (listener) {
                var i, watched = [];

                for (i in contacts) {
                    watched.push(new Contact(
                        privateData.contacts[contacts[i].id]));
                }
                listener.oncontactsupdated(watched);
            });
        }, 1);
    }

    function remove(id) {
        if (!_security.remove) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        if (addressBook.readOnly) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("remove", arguments);

        if (privateData.contacts[id] === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        delete privateData.contacts[id];
        if (dbContacts[id]) {
            delete dbContacts[id];
        }
        _save();

        window.setTimeout(function () {
            utils.forEach(privateData.listeners, function (listener) {
                listener.oncontactsremoved([id]);
            });
        }, 1);
    }

    function removeBatch(ids, successCallback, errorCallback) {
        if (!_security.removeBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        if (addressBook.readOnly) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("removeBatch", arguments, true);

        window.setTimeout(function () {
            var i;

            if (ids.length === 0) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                }
                return;
            }

            for (i in ids) {
                if (!ids[i]) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                    }
                    return;
                }
                if (privateData.contacts[ids[i]] === undefined) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                    }
                    return;
                }
            }
            for (i in ids) {
                delete privateData.contacts[ids[i]];
                if (dbContacts[ids[i]]) {
                    delete dbContacts[ids[i]];
                }
            }
            _save();
            if (successCallback) {
                successCallback();
            }

            utils.forEach(privateData.listeners, function (listener) {
                listener.oncontactsremoved(utils.copy(ids));
            });
        }, 1);
    }

    function find(successCallback, errorCallback, filter, sortMode) {
        if (!_security.find) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("find", arguments, true);

        window.setTimeout(function () {
            var result = [], begin, end, i, atr, _re, errFlag = false,
                _rangeMatch, low, high, matched, _existMatch, _arrayMatch;

            if (filter) {
                switch (_filterType(filter)) {
                case 0:
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                    }
                    return;

                case 1:
                    //TODO:
                    //"compositeFilter doesn't support"
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.NOT_SUPPORTED_ERR));
                    }
                    return;

                case 2:
                case 3:
                    break;
                }
            }

            /* return all contacts if no filter argument */
            if (filter === null || filter === undefined) {
                utils.forEach(privateData.contacts, function (contact) {
                    result.push(new Contact(contact));
                });

                successCallback(result);
                return;
            }

            /* check composition of filter.attributeName */
            switch (filter.attributeName) {
            case "id" :
            case "personId" :
            case "addressBookId" :
            case "name.prefix" :
            case "name.suffix" :
            case "name.firstName" :
            case "name.middleName" :
            case "name.lastName" :
            case "name.phoneticFirstName" :
            case "name.phoneticLastName" :
            case "name.displayName" :
            case "account.accountServiceId" :
            case "account.contactURI" :
            case "photoURI" :
            case "ringtoneURI" :
                matched = tizen1_utils.matchAttributeFilter(privateData.contacts,
                        filter.attributeName, filter.matchFlag, filter.matchValue);
                break;

            case "name.nicknames" :
            case "notes" :
            case "groupIds" :
                matched = tizen1_utils.matchAttributeArrayFilter(privateData.contacts,
                        filter.attributeName, filter.matchFlag, filter.matchValue);
                break;

            case "addresses.country" :
            case "addresses.region" :
            case "addresses.city" :
            case "addresses.streetAddress" :
            case "addresses.additionalInformation" :
            case "addresses.postalCode" :
            case "phoneNumbers.number" :
            case "emails.email" :
            case "anniversaries.label" :
            case "organizations.name" :
            case "organizations.department" :
            case "organizations.title" :
            case "organizations.role" :
            case "organizations.logoURI" :
            case "urls.url" :
            case "urls.type" :
                atr = filter.attributeName.split(".");
                _existMatch = function (obj) {
                    return (obj[atr[0]] !== undefined);
                };

                if (filter.matchValue === undefined || filter.matchFlag === "EXISTS") {
                    matched = utils.filter(privateData.contacts, _existMatch);
                    break;
                }

                errFlag = false;

                switch (filter.matchFlag)
                {
                case "EXACTLY":
                    _re = new RegExp("^" + filter.matchValue + "$");
                    break;
                case "FULLSTRING":
                    _re = new RegExp("^" + filter.matchValue + "$", "i");
                    break;
                case "CONTAINS":
                    _re = new RegExp(filter.matchValue, "i");
                    break;
                case "STARTSWITH":
                    _re = new RegExp("^" + filter.matchValue, "i");
                    break;
                case "ENDSWITH":
                    _re = new RegExp(filter.matchValue + "$", "i");
                    break;
                default:
                    errFlag = true;
                }

                if (errFlag) {
                    matched = [];
                    break;
                }

                _arrayMatch = function (obj) {
                    return (obj[atr[0]].some(function (o) {
                        if (typeof o[atr[1]] !== "string") {
                            return false;
                        } else {
                            return (o[atr[1]].search(_re) !== -1);
                        }
                    }));
                };

                matched = utils.filter(privateData.contacts, _arrayMatch);
                break;

            case "addresses.types" :
            case "phoneNumbers.types" :
            case "emails.types" :
                atr = filter.attributeName.split(".");
                _existMatch = function (obj) {
                    return (obj[atr[0]].some(function (o) {
                        return (o[atr[1]] !== undefined);
                    }));
                };

                if (filter.matchValue === undefined || filter.matchFlag === "EXISTS") {
                    matched = utils.filter(privateData.contacts, _existMatch);
                    break;
                }

                errFlag = false;

                switch (filter.matchFlag) {
                case "EXACTLY":
                    _re = new RegExp("^" + filter.matchValue + "$");
                    break;
                case "FULLSTRING":
                    _re = new RegExp("^" + filter.matchValue + "$", "i");
                    break;
                case "CONTAINS":
                    _re = new RegExp(filter.matchValue, "i");
                    break;
                case "STARTSWITH":
                    _re = new RegExp("^" + filter.matchValue, "i");
                    break;
                case "ENDSWITH":
                    _re = new RegExp(filter.matchValue + "$", "i");
                    break;
                default:
                    errFlag = true;
                }

                if (errFlag) {
                    matched = [];
                    break;
                }

                _arrayMatch = function (obj) {
                    return (obj[atr[0]].some(function (o) {
                        if (!tizen1_utils.isValidArray(o[atr[1]])) {
                            return false;
                        } else {
                            return (o[atr[1]].some(function (t) {
                                return (t.search(_re) !== -1);
                            }));
                        }
                    }));
                };

                matched = utils.filter(privateData.contacts, _arrayMatch);
                break;

            case "anniversaries.date" :
                low = filter.initialValue;
                high = filter.endValue;
                atr = filter.attributeName.split(".");

                _rangeMatch = function (obj) {
                    var isMatched = true;
                    if (low !== null && low !== undefined) {
                        if (!tizen1_utils.isValidArray(obj[atr[0]])) {
                            isMatched = false;
                        } else {
                            isMatched = (obj[atr[0]].some(function (o) {
                                return (o[atr[1]] >= low);
                            }));
                        }
                    }
                    if (isMatched && (high !== null && high !== undefined)) {
                        if (!tizen1_utils.isValidArray(obj[atr[0]])) {
                            isMatched = false;
                        } else {
                            isMatched = (obj[atr[0]].some(function (o) {
                                return (o[atr[1]] <= high);
                            }));
                        }
                    }
                    return isMatched;
                };

                matched = utils.filter(privateData.contacts, _rangeMatch);
                break;

            case "addresses.isDefault" :
            case "phoneNumbers.isDefault" :
            case "emails.isDefault" :
                break;

            case "isFavorite" :
                if (filter.matchFlag !== "EXACTLY" || typeof filter.matchValue !== "boolean") {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                    }
                    return;
                } else {
                    matched = tizen1_utils.matchAttributeBooleanFilter(privateData.contacts,
                            filter.attributeName, filter.matchValue);
                }
                break;

            case "birthday" :
                begin = filter.initialValue;
                end = filter.endValue;

                matched = tizen1_utils.matchAttributeRangeFilter(privateData.contacts,
                        filter.attributeName, begin, end);
                break;

            default:
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                }
                return;
            }

            if (sortMode) {
                _sort(matched, sortMode);
            }

            for (i in matched) {
                result.push(new Contact(matched[i]));
            }

            successCallback(result);
        }, 1);
    }

    function addChangeListener(successCallback, errorCallback) {
        var id;

        if (!_security.addChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("addChangeListener", arguments);

        id = ++privateData.nListener;
        privateData.listeners[id] = successCallback;

        return id;
    }

    function removeChangeListener(watchId) {
        if (!_security.removeChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        if (!privateData.listeners[watchId])
            return;

        delete privateData.listeners[watchId];
    }

    function getGroup(groupId) {
        var i;

        if (!_security.getGroup) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("getGroup", arguments);

        for (i in privateData.groups) {
            if (privateData.groups[i].id === groupId)
                break;
        }
        if (privateData.groups[i] === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        return new ContactGroup(privateData.groups[i]);
    }

    function addGroup(group) {
        var external = group;

        if (!_security.addGroup) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("addGroup", arguments, true);

        group.id            = Math.uuid(null, 16);
        group.addressBookId = id;

        external.__defineGetter__("id", function () {
            return group.id;
        });

        external.__defineGetter__("addressBookId", function () {
            return group.addressBookId;
        });

        privateData.groups.push(group);
        _save();
    }

    function updateGroup(group) {
        var i;

        if (!_security.updateGroup) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("updateGroup", arguments);

        if (!group.id) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
        for (i in privateData.groups) {
            if (privateData.groups[i].id === group.id)
                break;
        }
        if (privateData.groups[i].id === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        if (privateData.groups[i].readOnly) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        privateData.groups[i] = utils.copy(group);
        _save();
    }

    function removeGroup(groupId) {
        var i;

        if (!_security.removeGroup) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.AddressBook("removeGroup", arguments);

        for (i in privateData.groups) {
            if (privateData.groups[i].id === groupId)
                break;
        }
        if (privateData.groups[i].id === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        if (privateData.groups[i].readOnly) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        privateData.groups.splice(i, 1);
        _save();
    }

    function getGroups() {
        var groups = [], i;

        if (!_security.getGroups) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        for (i in privateData.groups) {
            groups.push(new ContactGroup(privateData.groups[i]));
        }
        return groups;
    }

    privateData.load();
    // Make private contacts accessible for Person methods
    _data.contacts[id] = privateData.contacts;

    addressBook = {
        get:                  get,
        add:                  add,
        addBatch:             addBatch,
        update:               update,
        updateBatch:          updateBatch,
        remove:               remove,
        removeBatch:          removeBatch,
        find:                 find,
        addChangeListener:    addChangeListener,
        removeChangeListener: removeChangeListener,

        getGroup:             getGroup,
        addGroup:             addGroup,
        updateGroup:          updateGroup,
        removeGroup:          removeGroup,
        getGroups:            getGroups
    };

    addressBook.__defineGetter__("id", function () {
        return id;
    });

    addressBook.__defineGetter__("name", function () {
        return name;
    });

    addressBook.__defineGetter__("readOnly", function () {
        return readOnly;
    });

    return addressBook;
};

AddressBookData = function (contacts, groups) {
    var addressBookData;

    // private
    function loadContacts() {
        for (var i in contacts) {
            addressBookData.contacts[i] = new ContactInternal(contacts[i]);
        }
    }

    function loadGroups() {
        addressBookData.groups = groups;
    }

    // public
    function load() {
        loadContacts();
        loadGroups();
    }

    addressBookData = {
        contacts:  {},
        groups:    [],
        listeners: {},
        nListener: 0,
        load:      load
    };

    return addressBookData;
};

AddressBookStorage = function (id, name, readOnly, contacts, groups) {
    this.id       = id;
    this.name     = name;
    this.readOnly = readOnly;
    this.contacts = contacts;
    this.groups   = groups;
};

Contact = function (contact) {
    var i, attr, arr;

    this.name          = null;
    this.addresses     = [];
    this.photoURI      = null;
    this.phoneNumbers  = [];
    this.emails        = [];
    this.birthday      = null;
    this.anniversaries = [];
    this.organizations = [];
    this.notes         = [];
    this.urls          = [];
    this.ringtoneURI   = null;
    this.groupIds      = [];

    for (attr in contact) {
        switch (attr) {
        case "name":
            this[attr] = new ContactName(contact[attr]);
            break;

        case "addresses":
            arr = contact[attr];
            if (arr) {
                for (i in arr) {
                    this[attr][i] = new ContactAddress(arr[i]);
                }
            }
            break;

        case "phoneNumbers":
            arr = contact[attr];
            if (arr) {
                for (i in arr) {
                    this[attr][i] = new ContactPhoneNumber(arr[i].number,
                            arr[i].types || null, arr[i].isDefault || null);
                }
            }
            break;

        case "emails":
            arr = contact[attr];
            if (arr) {
                for (i in arr) {
                    this[attr][i] = new ContactEmailAddress(arr[i].email,
                            arr[i].types || null, arr[i].isDefault || null);
                }
            }
            break;

        case "birthday":
            this[attr] = new Date(contact[attr]);
            break;

        case "anniversaries":
            arr = contact[attr];
            if (arr) {
                for (i in arr) {
                    if (!tizen1_utils.isValidDate(arr[i].date)) {
                        arr[i].date = new Date(arr[i].date);
                    }
                    this[attr][i] = new ContactAnniversary(arr[i].date,
                            arr[i].label || null);
                }
            }
            break;

        case "organizations":
            arr = contact[attr];
            if (arr) {
                for (i in arr) {
                    this[attr][i] = new ContactOrganization(arr[i]);
                }
            }
            break;

        case "notes":
        case "groupIds":
            arr = contact[attr];
            if (arr) {
                for (i in arr) {
                    this[attr][i] = arr[i];
                }
            }
            break;

        case "urls":
            arr = contact[attr];
            if (arr) {
                for (i in arr) {
                    this[attr][i] = new ContactWebSite(arr[i].url,
                            arr[i].type || null);
                }
            }
            break;

        default:
            this[attr] = contact[attr];
            break;
        }
    }

    decorator.Contact(this, contact);
    this.__proto__ = tizen.Contact.prototype;
};

ContactInternal = function (contact) {
    var attr;

    for (attr in contact) {
        this[attr] = contact[attr];
    }

    if (!contact.id) {
        this.id = Math.uuid(null, 16);
        this.lastUpdated = new Date();
    } else {
        this.lastUpdated = new Date(contact.lastUpdated);
    }

    if (this.name) {
        this.name.__defineGetter__("displayName", function () {
            var displayName = "";

            if (!this)
                return "";

            if ((this.firstName !== null) &&
                (this.lastName !== null)) {
                displayName = [this.firstName, this.middleName, this.lastName];
                displayName = displayName.join(" ").replace(/ +/g, " ").trim();
            } else if (this.nicknames.length !== 0) {
                this.nicknames.some(function (nickname) {
                    displayName = nickname;
                    return displayName;
                });
            }

            return displayName;
        });
    }
};

ContactData = function () {
    this.listeners = {};
    this.nListener = 0;
};

ContactGroup = function (groupInitDict) {
    var id, addressBookId, readOnly;

    this.__defineGetter__("id", function () {
        return id;
    });

    this.__defineGetter__("addressBookId", function () {
        return addressBookId;
    });

    this.__defineGetter__("readOnly", function () {
        return readOnly;
    });

    id               = groupInitDict.id || null;
    addressBookId    = groupInitDict.addressBookId || null;
    readOnly         = groupInitDict.readOnly || false;

    this.name        = groupInitDict.name || "";
    this.ringtoneURI = groupInitDict.ringtoneURI || null;
    this.photoURI    = groupInitDict.photoURI || null;

    this.__proto__ = tizen.ContactGroup.prototype;
};

Person = function (personInitDict) {
    var person = {};

    function hasContactMethod(method) {
        var idab, idc, contact, count = 0;

        for (idab in _data.contacts) {
            for (idc in _data.contacts[idab]) {
                contact = _data.contacts[idab][idc];
                if (contact.personId === person.id) {
                    count += contact[method].length;
                }
            }
        }

        return (count !== 0);
    }

    person.id               = personInitDict.id || Math.uuid(null, 16);
    person.isFavorite       = personInitDict.isFavorite || false;
    person.photoURI         = personInitDict.photoURI || null;
    person.ringtoneURI      = personInitDict.ringtoneURI || null;
    person.displayContactId = personInitDict.displayContactId;

    this.__defineGetter__("id", function () {
        return person.id;
    });

    this.__defineGetter__("displayName", function () {
        var idab, contact, displayName = "";

        for (idab in _data.contacts) {
            contact = _data.contacts[idab][this.displayContactId];

            if (contact !== undefined) {
                if (contact.name && contact.name.displayName) {
                    displayName = contact.name.displayName;
                }
                break;
            }
        }

        return displayName;
    });

    this.__defineGetter__("contactCount", function () {
        var idab, idc, contactCount = 0;

        for (idab in _data.contacts) {
            for (idc in _data.contacts[idab]) {
                if (_data.contacts[idab][idc].personId === person.id) {
                    ++contactCount;
                }
            }
        }

        return contactCount;
    });

    this.__defineGetter__("hasPhoneNumber", function () {
        return hasContactMethod("phoneNumbers");
    });

    this.__defineGetter__("hasEmail", function () {
        return hasContactMethod("emails");
    });

    this.__defineGetter__("isFavorite", function () {
        return person.isFavorite;
    });
    this.__defineSetter__("isFavorite", function (val) {
        try {
            person.isFavorite = t.boolean(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("photoURI", function () {
        return person.photoURI;
    });
    this.__defineSetter__("photoURI", function (val) {
        try {
            person.photoURI = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("ringtoneURI", function () {
        return person.ringtoneURI;
    });
    this.__defineSetter__("ringtoneURI", function (val) {
        try {
            person.ringtoneURI = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("displayContactId", function () {
        return person.displayContactId;
    });
    this.__defineSetter__("displayContactId", function (val) {
        try {
            person.displayContactId = t.ContactId(val);
        } catch (e) {
        }
    });

    this.link = function (personId) {
        if (!_security.link) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Person("link", arguments);

        if (_data.persons[personId] === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        _replacePerson(personId, person.id);
        _save();
    };

    this.unlink = function (contactId) {
        var idab, contact, separated, i, dbAddressBook;

        if (!_security.unlink) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.Person("unlink", arguments);

        for (idab in _data.contacts) {
            if (_data.contacts[idab][contactId] !== undefined) {
                contact = _data.contacts[idab][contactId];
                break;
            }
        }

        if (contact === undefined) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        if (contact.personId !== person.id) {
            throw new WebAPIException(errorcode.UNKNOWN_ERR);
        }

        separated = new PersonBuilder(contact);
        _data.persons[separated.id] = separated;
        contact.personId = separated.id;

        _data.dbStorage.persons[separated.id] = _serialize(separated);
        for (i in _data.dbStorage.addressBooks) {
            dbAddressBook = _data.dbStorage.addressBooks[i];
            if (dbAddressBook.id === idab) {
                dbAddressBook.contacts[contact.id].personId = separated.id;
                break;
            }
        }
        _save();

        return separated;
    };
};

PersonBuilder = function (contact) {
    var person, personInitDict = {};

    personInitDict.displayContactId = contact.id;
    person = new Person(personInitDict);

    return person;
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/content', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    dbfs = require('ripple/platform/tizen/2.0/dbfs'),
    dbinit = require('ripple/platform/tizen/2.0/dbinit'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    Content,
    ContentDirectory,
    ContentFactory,
    ContentStorage,
    AudioContent,
    ImageContent,
    VideoContent,
    ContentInternal,
    ContentDirectoryInternal,
    AudioContentInternal,
    ImageContentInternal,
    VideoContentInternal,
    AudioContentLyrics,
    _data = {
        DB_CONTENT_KEY: "tizen1-db-content",
        content:        {},
        listener:       null,
        dbStorage:      null
    },
    _security = {
        "http://tizen.org/privilege/content.read": ["find",
            "setChangeListener", "unsetChangeListener"],
        "http://tizen.org/privilege/content.write": ["update", "updateBatch",
            "scanFile"]
    },
    _self;

function _get() {
    _data.dbStorage = db.retrieveObject(_data.DB_CONTENT_KEY) || dbinit.Content;
}

function _save() {
    db.saveObject(_data.DB_CONTENT_KEY, _data.dbStorage);
}

function _initialize() {
    _get();

    if (!_data.dbStorage)
        return;

    utils.forEach(_data.dbStorage, function (content) {
        _data.content[content.directoryURI] = new ContentStorage(content);
    });

    _data.dbStorage = _data.content;
    _save();
}

_self = function () {
    var content;

    // private
    function getType(file) {
        var extName, type;

        extName = file.substr(file.lastIndexOf(".") + 1).toLowerCase();

        switch (extName) {
        case "bmp":
        case "gif":
        case "jpeg":
        case "jpg":
        case "png":
            type = "IMAGE";
            break;

        case "avi":
        case "mpeg":
        case "mpg":
        case "wmv":
        case "mp4":
            type = "VIDEO";
            break;

        case "wav":
        case "mp3":
            type = "AUDIO";
            break;

        default:
            type = "OTHER";
            break;
        }

        return type;
    }

    function getMimeType(file) {
        var mimeTypeTab = {
            IMAGE: "image/x-msimage",
            VIDEO: "video/x-msvideo",
            AUDIO: "audio/x-msaudio",
            OTHER: "other/unknown"
        };

        return mimeTypeTab[getType(file)];
    }

    function getTitle(file) {
        var title;

        title = file.substr(0, file.lastIndexOf("."));
        title = title.charAt(0).toUpperCase() + title.substr(1).toLowerCase();

        return title;
    }

    function getDirectoryURI(contentURI) {
        return contentURI.slice(0, contentURI.lastIndexOf("/") + 1)
                .replace(/file:\/\//, "");
    }

    function extractProperties(entry) {
        var contentInitDict = {};

        contentInitDict.editableAttributes = ["name", "title", "description",
                "rating"];
        contentInitDict.name               = entry.name;
        contentInitDict.type               = getType(entry.name);
        contentInitDict.mimeType           = getMimeType(entry.name);
        contentInitDict.title              = getTitle(entry.name);
        contentInitDict.contentURI         = entry.fullPath ?
                "file://" + entry.fullPath : entry.fullPath;
        contentInitDict.thumbnailURIs      = [entry.fullPath];
        contentInitDict.releaseDate        = entry.lastModifiedDate;
        contentInitDict.modifiedDate       = entry.lastModifiedDate;
        contentInitDict.size               = 1048576;

        return contentInitDict;
    }

    function updateContents(contents, successCallback, errorCallback) {
        var i, isFound = false, dir, matched = [];

        for (i in contents) {
            dir = getDirectoryURI(contents[i].contentURI);

            isFound = ((dir in _data.content) && (contents[i].contentURI in
                    _data.content[dir].contents));

            if (!isFound)
                break;

            matched.push(dir);
        }

        if (!isFound) {
            if (errorCallback) {
                errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
            }
            return;
        }

        for (i in matched) {
            _data.content[matched[i]].contents[contents[i].contentURI] =
                    new ContentFactory(contents[i], true);
        }

        _save();

        if (successCallback) {
            successCallback();
        }

        if (_data.listener !== null) {
            for (i in matched) {
                _data.listener.oncontentupdated(new ContentFactory(_data
                        .content[matched[i]].contents[contents[i].contentURI],
                        false));
            }
        }
    }

    // public
    function update(content) {
        if (!_security.update) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContentManager("update", arguments);

        updateContents([content]);
    }

    function updateBatch(contents, successCallback, errorCallback) {
        if (!_security.updateBatch) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContentManager("updateBatch", arguments, true);

        window.setTimeout(function () {
            updateContents(contents, successCallback, errorCallback);
        }, 1);
    }

    function getDirectories(successCallback, errorCallback) {
        t.ContentManager("getDirectories", arguments);

        window.setTimeout(function () {
            var i, directories = [];

            for (i in _data.content) {
                directories.push(new ContentDirectory(_data.content[i]));
            }

            if (directories.length === 0) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                }
                return;
            }

            successCallback(directories);
        }, 1);
    }

    function find(successCallback, errorCallback, directoryId, filter, sortMode,
            count, offset) {
        if (!_security.find) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContentManager("find", arguments, true);

        window.setTimeout(function () {
            var i, dir, contents = [], results = [], matchedDir;

            if (!directoryId) {
                for (dir in _data.content) {
                    for (i in _data.content[dir].contents) {
                        contents.push(_data.content[dir].contents[i]);
                    }
                }
            } else {
                for (dir in _data.content) {
                    if (_data.content[dir].id === directoryId) {
                        matchedDir = dir;
                        break;
                    }
                }

                if (!matchedDir) {
                    if (errorCallback) {
                        errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
                    }
                    return;
                }

                for (i in _data.content[matchedDir].contents) {
                    contents.push(_data.content[matchedDir].contents[i]);
                }
            }

            if (contents.length === 0) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
                }
                return;
            }

            contents = tizen1_utils.query(contents, filter, sortMode, count,
                    offset);

            contents.forEach(function (content) {
                results.push(new ContentFactory(content, false));
            });

            successCallback(results);
        }, 1);
    }

    function scanFile(contentURI, successCallback, errorCallback) {
        var dir, isFound;

        function onStatSuccess(entry) {
            var contentInitDict, content;

            if (isFound) {
                content = new ContentFactory(_data.content[dir]
                        .contents[contentURI], true);
            } else {
                contentInitDict = extractProperties(entry);
                content = new ContentFactory(contentInitDict, true);
                _data.content[dir].contents[contentURI] = content;
            }

            _save();

            if (successCallback) {
                successCallback(contentURI);
            }

            if (_data.listener !== null) {
                if (isFound) {
                    _data.listener.oncontentupdated(
                            new ContentFactory(content, false));
                } else {
                    _data.listener.oncontentadded(
                            new ContentFactory(content, false));
                }
            }
        }

        function onStatError() {
            if (isFound) {
                delete _data.content[dir].contents[contentURI];
                _save();

                if (successCallback) {
                    successCallback(contentURI);
                }

                if (_data.listener !== null) {
                    _data.listener.oncontentremoved(_data.content[dir]
                            .contents[contentURI].id);
                }
            } else if (errorCallback) {
                errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
            }
        }

        if (!_security.scanFile) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContentManager("scanFile", arguments);

        window.setTimeout(function () {
            dir = getDirectoryURI(contentURI);

            isFound = ((dir in _data.content) &&
                    (contentURI in _data.content[dir].contents));

            dbfs.stat(contentURI.replace(/file:\/\//, ""), onStatSuccess,
                    onStatError);
        }, 1);
    }

    function setChangeListener(changeCallback) {
        if (!_security.setChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.ContentManager("setChangeListener", arguments);

        _data.listener = changeCallback;
    }

    function unsetChangeListener() {
        if (!_security.unsetChangeListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        _data.listener = null;
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    content = {
        update:              update,
        updateBatch:         updateBatch,
        getDirectories:      getDirectories,
        find:                find,
        scanFile:            scanFile,
        setChangeListener:   setChangeListener,
        unsetChangeListener: unsetChangeListener,
        handleSubFeatures:   handleSubFeatures
    };

    return content;
};

ContentDirectoryInternal = function (contentDirectoryInitDict) {
    this.id           = contentDirectoryInitDict.id || null;
    this.directoryURI = contentDirectoryInitDict.directoryURI || null;
    this.title        = contentDirectoryInitDict.title || "";
    this.storageType  = contentDirectoryInitDict.storageType || "INTERNAL";
    this.modifiedDate = contentDirectoryInitDict.modifiedDate ?
            new Date(contentDirectoryInitDict.modifiedDate) : null;
};

ContentDirectory = function (contentDirectoryInitDict) {
    var contentDirectory = {};

    contentDirectory.id           = contentDirectoryInitDict.id || null;
    contentDirectory.directoryURI = contentDirectoryInitDict.directoryURI || null;
    contentDirectory.title        = contentDirectoryInitDict.title || "";
    contentDirectory.storageType  = contentDirectoryInitDict.storageType || "INTERNAL";
    contentDirectory.modifiedDate = contentDirectoryInitDict.modifiedDate ?
            new Date(contentDirectoryInitDict.modifiedDate) : null;

    this.__defineGetter__("id", function () {
        return contentDirectory.id;
    });

    this.__defineGetter__("directoryURI", function () {
        return contentDirectory.directoryURI;
    });

    this.__defineGetter__("title", function () {
        return contentDirectory.title;
    });

    this.__defineGetter__("storageType", function () {
        return contentDirectory.storageType;
    });

    this.__defineGetter__("modifiedDate", function () {
        return contentDirectory.modifiedDate;
    });
};

ContentInternal = function (contentInitDict) {
    this.editableAttributes = contentInitDict.editableAttributes || [];
    this.id                 = contentInitDict.id || Math.uuid(null, 16);
    this.type               = contentInitDict.type || "IMAGE";
    this.mimeType           = contentInitDict.mimeType || "";
    this.title              = contentInitDict.title || "";
    this.contentURI         = contentInitDict.contentURI || "";
    this.thumbnailURIs      = contentInitDict.thumbnailURIs || null;
    this.releaseDate        = contentInitDict.releaseDate ?
            new Date(contentInitDict.releaseDate) : null;
    this.modifiedDate       = contentInitDict.modifiedDate ?
            new Date(contentInitDict.modifiedDate) : null;
    this.size               = contentInitDict.size || 0;
    this.name               = contentInitDict.name || "";
    this.description        = contentInitDict.description || null;
    this.rating             = contentInitDict.rating || 0;
};

Content = function (contentInitDict) {
    var content = {};

    content.editableAttributes = contentInitDict.editableAttributes || [];
    content.id                 = contentInitDict.id || Math.uuid(null, 16);
    content.name               = contentInitDict.name || "";
    content.type               = contentInitDict.type || "IMAGE";
    content.mimeType           = contentInitDict.mimeType || "";
    content.title              = contentInitDict.title || "";
    content.contentURI         = contentInitDict.contentURI || "";
    content.thumbnailURIs      = contentInitDict.thumbnailURIs || null;
    content.releaseDate        = contentInitDict.releaseDate ?
            new Date(contentInitDict.releaseDate) : null;
    content.modifiedDate       = contentInitDict.modifiedDate ?
            new Date(contentInitDict.modifiedDate) : null;
    content.size               = contentInitDict.size || 0;
    content.description        = contentInitDict.description || null;
    content.rating             = contentInitDict.rating || 0;

    this.__defineGetter__("editableAttributes", function () {
        return content.editableAttributes;
    });

    this.__defineGetter__("id", function () {
        return content.id;
    });

    this.__defineGetter__("name", function () {
        return content.name;
    });
    this.__defineSetter__("name", function (val) {
        try {
            content.name = t.DOMString(val);
        } catch (e) {
        }
    });

    this.__defineGetter__("type", function () {
        return content.type;
    });

    this.__defineGetter__("mimeType", function () {
        return content.mimeType;
    });

    this.__defineGetter__("title", function () {
        return content.title;
    });

    this.__defineGetter__("contentURI", function () {
        return content.contentURI;
    });

    this.__defineGetter__("thumbnailURIs", function () {
        return content.thumbnailURIs;
    });

    this.__defineGetter__("releaseDate", function () {
        return content.releaseDate;
    });

    this.__defineGetter__("modifiedDate", function () {
        return content.modifiedDate;
    });

    this.__defineGetter__("size", function () {
        return content.size;
    });

    this.__defineGetter__("description", function () {
        return content.description;
    });
    this.__defineSetter__("description", function (val) {
        try {
            content.description = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("rating", function () {
        return content.rating;
    });
    this.__defineSetter__("rating", function (val) {
        try {
            val = t.unsigned_long(val);
            if ((val < 0) || (val > 10))
                return;
            content.rating = val;
        } catch (e) {
        }
    });
};

VideoContentInternal = function (videoContentInitDict) {
    ContentInternal.call(this, videoContentInitDict);

    this.album       = videoContentInitDict.album || null;
    this.artists     = videoContentInitDict.artists || null;
    this.duration    = videoContentInitDict.duration || 0;
    this.width       = videoContentInitDict.width || 0;
    this.height      = videoContentInitDict.height || 0;
    this.geolocation = null;

    if (videoContentInitDict.geolocation) {
        this.geolocation = new SimpleCoordinates(
                videoContentInitDict.geolocation.latitude || null,
                videoContentInitDict.geolocation.longitude || null);
    }
};

VideoContent = function (videoContentInitDict) {
    var videoContent = {};

    Content.call(this, videoContentInitDict);

    videoContent.album       = videoContentInitDict.album || null;
    videoContent.artists     = videoContentInitDict.artists || null;
    videoContent.duration    = videoContentInitDict.duration || 0;
    videoContent.width       = videoContentInitDict.width || 0;
    videoContent.height      = videoContentInitDict.height || 0;
    videoContent.geolocation = null;

    if (videoContentInitDict.geolocation) {
        videoContent.geolocation = new SimpleCoordinates(
                videoContentInitDict.geolocation.latitude,
                videoContentInitDict.geolocation.longitude);
    }

    this.__defineGetter__("geolocation", function () {
        return videoContent.geolocation;
    });
    this.__defineSetter__("geolocation", function (val) {
        try {
            videoContent.geolocation = t.SimpleCoordinates(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("album", function () {
        return videoContent.album;
    });

    this.__defineGetter__("artists", function () {
        return videoContent.artists;
    });

    this.__defineGetter__("duration", function () {
        return videoContent.duration;
    });

    this.__defineGetter__("width", function () {
        return videoContent.width;
    });

    this.__defineGetter__("height", function () {
        return videoContent.height;
    });
};

AudioContentInternal = function (audioContentInitDict) {
    ContentInternal.call(this, audioContentInitDict);

    this.album       = audioContentInitDict.album || null;
    this.genres      = audioContentInitDict.genres || null;
    this.artists     = audioContentInitDict.artists || null;
    this.composers   = audioContentInitDict.composers || null;
    this.lyrics      = audioContentInitDict.lyrics ?
            new AudioContentLyrics(audioContentInitDict.lyrics) : null;
    this.copyright   = audioContentInitDict.copyright || null;
    this.bitrate     = audioContentInitDict.bitrate || 0;
    this.trackNumber = audioContentInitDict.trackNumber || null;
    this.duration    = audioContentInitDict.duration || 0;
};

AudioContentLyrics = function (lyrics) {
    var audioContentLyrics = {};

    audioContentLyrics.type       = lyrics.type;
    audioContentLyrics.texts      = lyrics.texts;
    audioContentLyrics.timestamps = (lyrics.type === "SYNCHRONIZED") ?
            lyrics.timestamps : undefined;

    this.__defineGetter__("type", function () {
        return audioContentLyrics.type;
    });

    this.__defineGetter__("texts", function () {
        return audioContentLyrics.texts;
    });

    this.__defineGetter__("timestamps", function () {
        return audioContentLyrics.timestamps;
    });
};

AudioContent = function (audioContentInitDict) {
    var audioContent = {};

    Content.call(this, audioContentInitDict);

    audioContent.album       = audioContentInitDict.album || null;
    audioContent.genres      = audioContentInitDict.genres || null;
    audioContent.artists     = audioContentInitDict.artists || null;
    audioContent.composers   = audioContentInitDict.composers || null;
    audioContent.lyrics      = audioContentInitDict.lyrics ?
            new AudioContentLyrics(audioContentInitDict.lyrics) : null;
    audioContent.copyright   = audioContentInitDict.copyright || null;
    audioContent.bitrate     = audioContentInitDict.bitrate || 0;
    audioContent.trackNumber = audioContentInitDict.trackNumber || null;
    audioContent.duration    = audioContentInitDict.duration || 0;

    this.__defineGetter__("album", function () {
        return audioContent.album;
    });

    this.__defineGetter__("genres", function () {
        return audioContent.genres;
    });

    this.__defineGetter__("artists", function () {
        return audioContent.artists;
    });

    this.__defineGetter__("composers", function () {
        return audioContent.composers;
    });

    this.__defineGetter__("lyrics", function () {
        return audioContent.lyrics;
    });

    this.__defineGetter__("copyright", function () {
        return audioContent.copyright;
    });

    this.__defineGetter__("bitrate", function () {
        return audioContent.bitrate;
    });

    this.__defineGetter__("trackNumber", function () {
        return audioContent.trackNumber;
    });

    this.__defineGetter__("duration", function () {
        return audioContent.duration;
    });
};

ImageContentInternal = function (imageContentInitDict) {
    ContentInternal.call(this, imageContentInitDict);

    this.geolocation = null;
    this.width       = imageContentInitDict.width || 0;
    this.height      = imageContentInitDict.height || 0;
    this.orientation = imageContentInitDict.orientation || "NORMAL";

    if (imageContentInitDict.geolocation) {
        this.geolocation = new SimpleCoordinates(
                imageContentInitDict.geolocation.latitude,
                imageContentInitDict.geolocation.longitude);
    }
};

ImageContent = function (imageContentInitDict) {
    var imageContent = {};

    Content.call(this, imageContentInitDict);

    imageContent.width       = imageContentInitDict.width || 0;
    imageContent.height      = imageContentInitDict.height || 0;
    imageContent.geolocation = null;
    imageContent.orientation = imageContentInitDict.orientation || "NORMAL";

    if (imageContentInitDict.geolocation) {
        imageContent.geolocation = new SimpleCoordinates(
                imageContentInitDict.geolocation.latitude,
                imageContentInitDict.geolocation.longitude);
    }

    this.__defineGetter__("geolocation", function () {
        return imageContent.geolocation;
    });
    this.__defineSetter__("geolocation", function (val) {
        try {
            imageContent.geolocation = t.SimpleCoordinates(val, "?");
        } catch (e) {
        }
    });

    this.__defineGetter__("width", function () {
        return imageContent.width;
    });

    this.__defineGetter__("height", function () {
        return imageContent.height;
    });

    this.__defineGetter__("orientation", function () {
        return imageContent.orientation;
    });
    this.__defineSetter__("orientation", function (val) {
        try {
            imageContent.orientation = t.ImageContentOrientation(val);
        } catch (e) {
        }
    });
};

ContentFactory = function (contentInitDict, isInternal) {
    var ContentType;

    switch (contentInitDict.type) {
    case "IMAGE":
        ContentType = isInternal ? ImageContentInternal : ImageContent;
        break;

    case "VIDEO":
        ContentType = isInternal ? VideoContentInternal : VideoContent;
        break;

    case "AUDIO":
        ContentType = isInternal ? AudioContentInternal : AudioContent;
        break;

    default:
        ContentType = isInternal ? ContentInternal : Content;
        break;
    }

    return new ContentType(contentInitDict);
};

ContentStorage = function (content) {
    var i;

    ContentDirectoryInternal.call(this, content);
    this.contents = {};

    for (i in content.contents) {
        this.contents[i] = new ContentFactory(content.contents[i], true);
    }
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/datacontrol', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    DataControlConsumerFactory,
    DataControlConsumerObject,
    SQLDataControlConsumer,
    MappedDataControlConsumer,
    SQLData,
    MappedData,
    _data = {
        DB_DATACONTROL_KEY: "tizen1-db-datacontrol",
        IDS_PROVIDER:       ["http://tizen.org/datacontrol/provider/DictionaryDataControlProvider"],
        IDS_DATA:           ["Dictionary"],
        PERSIST_DELAY:      1000,
        SQL:                null,
        MAP:                null,
        dbStorage:          null
    },
    _security = {
        "http://tizen.org/privilege/datacontrol.consumer":
            ["getDataControlConsumer", "insert", "update", "remove", "select",
            "addValue", "removeValue", "getValue", "updateValue"]
    },
    _self;

function _get() {
    _data.dbStorage = db.retrieveObject(_data.DB_DATACONTROL_KEY) || {};
}

function _save() {
    db.saveObject(_data.DB_DATACONTROL_KEY, _data.dbStorage);
}

function _load(type) {
    if (!_data.dbStorage[type])
        return;

    _data[type] = {};

    utils.forEach(_data.dbStorage[type], function (provider, id) {
        var dataId;

        _data[type][id] = {};

        for (dataId in provider) {
            _data[type][id][dataId] = new DataControlConsumerFactory(type,
                    id, dataId, provider[dataId]);
        }
    });
}

function _initialize() {
    _get();

    _load("SQL");
    _load("MAP");
}

_self = function () {
    var datacontrol;

    // private
    function initConsumer(type) {
        var providers;

        _data.dbStorage[type] = {};
        providers = _data.dbStorage[type];

        _data.IDS_PROVIDER.forEach(function (id) {
            providers[id] = {};

            _data.IDS_DATA.forEach(function (dataId) {
                providers[id][dataId] = {};
            });
        });

        _load(type);
    }

    // public
    function getDataControlConsumer(providerId, dataId, type) {
        if (!_security.getDataControlConsumer) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.DataControlManager("getDataControlConsumer", arguments);

        if (_data[type] === null) {
            initConsumer(type);
        }
        if (!_data[type][providerId] || !_data[type][providerId][dataId]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        return _data[type][providerId][dataId];
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    datacontrol = {
        getDataControlConsumer: getDataControlConsumer,
        handleSubFeatures:      handleSubFeatures
    };

    return datacontrol;
};

DataControlConsumerObject = function (type, providerId, dataId) {
    this.__defineGetter__("type", function () {
        return type;
    });

    this.__defineGetter__("providerId", function () {
        return providerId;
    });

    this.__defineGetter__("dataId", function () {
        return dataId;
    });
};

SQLDataControlConsumer = function (providerId, dataId, dc) {
    var self, privateData = new SQLData(dc);

    // public
    function insert(reqId, insertionData, successCallback, errorCallback) {
        if (!_security.insert) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.SQLDataControlConsumer("insert", arguments, true);

        privateData.insert(insertionData, function (rowId) {
            if (successCallback) {
                successCallback(reqId, rowId);
            }
        }, function (error) {
            if (errorCallback) {
                errorCallback(reqId, error);
            }
        });
    }

    function update(reqId, updateData, where, successCallback, errorCallback) {
        if (!_security.update) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.SQLDataControlConsumer("update", arguments, true);

        privateData.update(updateData, where, function () {
            if (successCallback) {
                successCallback(reqId);
            }
        }, function (error) {
            if (errorCallback) {
                errorCallback(reqId, error);
            }
        });
    }

    function remove(reqId, where, successCallback, errorCallback) {
        if (!_security.remove) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.SQLDataControlConsumer("remove", arguments, true);

        privateData.remove(where, function () {
            if (successCallback) {
                successCallback(reqId);
            }
        }, function (error) {
            if (errorCallback) {
                errorCallback(reqId, error);
            }
        });
    }

    function select(reqId, columns, where, successCallback, errorCallback, page,
            maxNumberPerPage) {
        if (!_security.select) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.SQLDataControlConsumer("select", arguments, true);

        privateData.select(columns, where, function (rows) {
            successCallback(rows, reqId);
        }, function (error) {
            if (errorCallback) {
                errorCallback(reqId, error);
            }
        }, page, maxNumberPerPage);
    }

    self = new DataControlConsumerObject("SQL", providerId, dataId);

    self.insert = insert;
    self.update = update;
    self.remove = remove;
    self.select = select;

    return self;
};

MappedDataControlConsumer = function (providerId, dataId, dc) {
    var self, privateData = new MappedData(dc);

    function addValue(reqId, key, value, successCallback, errorCallback) {
        if (!_security.addValue) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.MappedDataControlConsumer("addValue", arguments);

        window.setTimeout(function () {
            if (privateData.insert(key, value)) {
                if (successCallback) {
                    successCallback(reqId);
                }
            } else if (errorCallback) {
                errorCallback(reqId, new WebAPIError(errorcode.UNKNOWN_ERR));
            }
        }, 1);
    }

    function removeValue(reqId, key, value, successCallback, errorCallback) {
        if (!_security.removeValue) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.MappedDataControlConsumer("removeValue", arguments);

        window.setTimeout(function () {
            if (privateData.remove(key, value)) {
                successCallback(reqId);
            } else if (errorCallback) {
                errorCallback(reqId, new WebAPIError(errorcode.NOT_FOUND_ERR));
            }
        }, 1);
    }

    function getValue(reqId, key, successCallback, errorCallback) {
        if (!_security.getValue) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.MappedDataControlConsumer("getValue", arguments);

        window.setTimeout(function () {
            var values;

            values = privateData.search(key);

            if (values !== null) {
                successCallback(values, reqId);
            } else if (errorCallback) {
                errorCallback(reqId, new WebAPIError(errorcode.NOT_FOUND_ERR));
            }
        }, 1);
    }

    function updateValue(reqId, key, oldValue, newValue, successCallback,
            errorCallback) {
        if (!_security.updateValue) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.MappedDataControlConsumer("updateValue", arguments);

        window.setTimeout(function () {
            if (privateData.update(key, oldValue, newValue)) {
                successCallback(reqId);
            } else if (errorCallback) {
                errorCallback(reqId, new WebAPIError(errorcode.NOT_FOUND_ERR));
            }
        }, 1);
    }

    self = new DataControlConsumerObject("MAP", providerId, dataId);

    self.addValue    = addValue;
    self.removeValue = removeValue;
    self.getValue    = getValue;
    self.updateValue = updateValue;

    return self;
};

DataControlConsumerFactory = function (type, providerId, dataId, dc) {
    var self;

    switch (type) {
    case "SQL":
        self = new SQLDataControlConsumer(providerId, dataId, dc);
        break;

    case "MAP":
        self = new MappedDataControlConsumer(providerId, dataId, dc);
        break;
    }

    return self;
};

SQLData = function (dc) {
    var self, data, columnNames, SQLErr2WebAPIErr;

    // private
    function getDBTableName() {
        return "DC_" + Math.uuid(8, 16);
    }

    function getColumnNames(tx, results) {
        columnNames = results.rows.item(0).sql
                .replace(/^[^\(]+\(([^\)]+)\)/g, "$1")
                .replace(/(^|(,) )([^ ,]+)([^,]*|$)/g, "$2$3")
                .split(",");
    }

    function queryColumns(columns) {
        return columns.join("=?,") + "=?";
    }

    function queryValues(n) {
        return (new Array(n)).join("?,") + "?";
    }

    function shedQuotes(values) {
        return values.every(function (value, i, arr) {
            arr[i] = value.replace(/^('|")(.*)\1$/g, "$2");

            return (arr[i] !== value);
        });
    }

    function isNull(p) {
        return ((p === undefined) || (p === null));
    }

    function initialize() {
        SQLErr2WebAPIErr = [
            0,      // 0: UNKNOWN_ERR         0: UNKNOWN_ERR
            100,    // 1: DATABASE_ERR      100: IO_ERR
            100,    // 2: VERSION_ERR       100: IO_ERR
            100,    // 3: TOO_LARGE_ERR     100: IO_ERR
            22,     // 4: QUOTA_ERR          22: QUOTA_EXCEEDED_ERR
            12,     // 5: SYNTAX_ERR         12: SYNTAX_ERR
            100,    // 6: CONSTRAINT_ERR    100: IO_ERR
            23      // 7: TIMEOUT_ERR        23: TIMEOUT_ERR
        ];

        if (!("table" in dc)) {
            dc.table = getDBTableName();
            columnNames = ["id"];
            _save();
        }

        data = openDatabase('tinyHippos', '1.0', 'tiny Hippos persistence',
                2 * 1024 * 1024);

        data.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS ' + dc.table +
                    ' (id unique)');
            tx.executeSql('SELECT sql FROM sqlite_master WHERE type="table" AND name=?',
                    [dc.table], getColumnNames);
        });
    }

    // public
    function insert(rowData, onSuccess, onError) {
        if (rowData.columns.length > rowData.values.length) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
        if (!shedQuotes(rowData.values)) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }

        data.transaction(function (tx) {
            rowData.columns.forEach(function (column) {
                if (columnNames.indexOf(column) !== -1)
                    return;

                tx.executeSql('ALTER TABLE ' + dc.table + ' ADD ' + column +
                        ' TEXT', [], function () {
                            columnNames.push(column);
                        }, function (tx, error) {
                            onError(new WebAPIError(
                                    SQLErr2WebAPIErr[error.code],
                                    error.message));
                        });
            });

            tx.executeSql('INSERT INTO ' + dc.table + ' (' +
                    rowData.columns.join() + ') VALUES (' +
                    queryValues(rowData.values.length) + ')', rowData.values,
                    function (tx, results) {
                        onSuccess(results.insertId);
                    }, function (tx, error) {
                        onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
                                error.message));
                    });
        });
    }

    function update(rowData, where, onSuccess, onError) {
        if (rowData.columns.length > rowData.values.length) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
        if (!shedQuotes(rowData.values)) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }

        data.transaction(function (tx) {
            tx.executeSql('UPDATE ' + dc.table + ' SET ' +
                    queryColumns(rowData.columns) + ' WHERE ' + where,
                    rowData.values, onSuccess, function (tx, error) {
                        onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
                                error.message));
                    });
        });
    }

    function remove(where, onSuccess, onError) {
        data.transaction(function (tx) {
            tx.executeSql('DELETE FROM ' + dc.table + ' WHERE ' + where, [],
                    onSuccess, function (tx, error) {
                        onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
                                error.message));
                    });
        });
    }

    function select(columns, where, onSuccess, onError, page, maxNumberPerPage) {
        if (isNull(page)) {
            page = 1;
        } else {
            if (page <= 0) {
                throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
            }
            page = parseInt(page, 10);
        }

        if (isNull(maxNumberPerPage)) {
            if (page > 1) {
                throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
            }
        } else {
            if (maxNumberPerPage <= 0) {
                throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
            }
            maxNumberPerPage = parseInt(maxNumberPerPage, 10);
        }

        data.transaction(function (tx) {
            tx.executeSql('SELECT ' + columns.join() + ' FROM ' + dc.table +
                    ' WHERE ' + where, [], function (tx, results) {
                        var rows = [], rowStart, rowData, r, c;

                        rowStart = maxNumberPerPage ?
                            (page - 1) * maxNumberPerPage : 0;

                        for (r = rowStart; r < results.rows.length; ++r) {
                            rowData = {
                                columns: columns,
                                values: []
                            };
                            for (c in columns) {
                                rowData.values.push(results.rows
                                    .item(r)[columns[c]]);
                            }
                            rows.push(rowData);

                            if (maxNumberPerPage && (--maxNumberPerPage === 0))
                                break;
                        }

                        onSuccess(rows);
                    }, function (tx, error) {
                        onError(new WebAPIError(SQLErr2WebAPIErr[error.code],
                                error.message));
                    });
        });
    }

    initialize();

    self = {
        insert: insert,
        update: update,
        remove: remove,
        select: select
    };

    return self;
};

MappedData = function (dc) {
    var self, data = {}, ioStamp = 0;

    // private
    function addNode(tree, arr, i) {
        var key, value;

        if (typeof arr[i] === "string") {
            key = arr[i];
            value = 1;
        } else {
            key = arr[i][0];
            value = arr[i][1];
        }
        tree.insert(key, value);
    }

    function bisearch(tree, arr, queue) {
        var start, end, mid;

        if (queue.length === 0)
            return;

        start = queue.shift();
        end = queue.shift();

        if (start > end)
            return;

        mid = start + parseInt((end - start) / 2, 10);
        addNode(tree, arr, mid);
        queue.push(start, mid - 1);
        queue.push(mid + 1, end);
    }

    function build(arr) {
        var tree, mid, lTree = [], rTree = [];

        tree = redblack.tree();
        mid = parseInt(arr.length / 2, 10);
        addNode(tree, arr, mid);

        lTree.push(0, mid - 1);
        rTree.push(mid + 1, arr.length - 1);

        while ((lTree.length > 0) || (rTree.length > 0)) {
            bisearch(tree, arr, lTree);
            bisearch(tree, arr, rTree);
        }

        return tree;
    }

    function initialize() {
        for (var key in dc) {
            data[key] = build(dc[key]);
        }
    }

    function traverse(tree, key) {
        dc[key] = [];
        tree.forEach(function (count, value) {
            dc[key].push((count === 1) ? value : [value, count]);
        });
    }

    function persist() {
        if (ioStamp !== 0) {
            window.clearTimeout(ioStamp);
        }
        ioStamp = window.setTimeout(function () {
            var key;

            for (key in data) {
                traverse(data[key], key);
            }

            _save();

            ioStamp = 0;
        }, _data.PERSIST_DELAY);
    }

    // public
    function insert(key, value) {
        var tree, count;

        if (!(key in data)) {
            data[key] = redblack.tree();
        }

        tree = data[key];

        if (!tree)
            return false;

        count = tree.get(value);
        tree.insert(value, count ? (count + 1) : 1);
        persist();

        return true;
    }

    function remove(key, value) {
        var tree, count;

        if (!(key in data))
            return false;

        tree = data[key];
        count = tree.get(value);
        if (count === null)
            return false;

        tree.delete(value);

        if (tree.root === null) {
            delete data[key];
            if (key in dc) {
                delete dc[key];
            }
        }

        persist();

        return true;
    }

    function search(key) {
        var values = [], tree;

        if (!(key in data))
            return null;

        tree = data[key];
        tree.forEach(function (count, value) {
            while (count--) {
                values.push(value);
            }
        });

        return values;
    }

    function update(key, oldValue, newValue) {
        var tree, count, countNew;

        if (!(key in data))
            return false;

        tree = data[key];
        count = tree.get(oldValue);
        if (count === null)
            return false;

        countNew = tree.get(newValue);
        count += (countNew === null) ? 0 : countNew;
        tree.delete(oldValue);
        tree.insert(newValue, count);
        persist();

        return true;
    }

    initialize();

    self = {
        insert: insert,
        remove: remove,
        search: search,
        update: update
    };

    return self;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/datasync', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    SyncInfoMod = require('ripple/platform/tizen/2.0/SyncInfo'),
    SyncServiceInfoMod = require('ripple/platform/tizen/2.0/SyncServiceInfo'),
    SyncProfileInfoMod = require('ripple/platform/tizen/2.0/SyncProfileInfo'),
    SyncStatistics = require('ripple/platform/tizen/2.0/SyncStatistics'),
    _data = {
        DB_DATASYNC_ITEMS: "tizen1-db-datasync-items",
        DB_DATASYNC_COUNTER: "tizen1-db-datasync-counter",
        MAX_PROFILE_NUMBER: 5,
        profile_num: 0,
        profiles: {},
        sync_accounts: {},
        service_accounts: {},
        item_counter: 1000,
        type_table: {
            "TWO_WAY":             1,
            "SLOW":                2,
            "ONE_WAY_FROM_CLIENT": 3,
            "REFRESH_FROM_CLIENT": 4,
            "ONE_WAY_FROM_SERVER": 5,
            "REFRESH_FROM_SERVER": 6
        },
        mode_table: {
            "TWO_WAY":             200,
            "SLOW":                201,
            "ONE_WAY_FROM_CLIENT": 202,
            "REFRESH_FROM_CLIENT": 203,
            "ONE_WAY_FROM_SERVER": 204,
            "REFRESH_FROM_SERVER": 205
        },
        items: {}
    },
    _security = {
        "http://tizen.org/privilege/datasync":
            ["add", "update", "remove", "getMaxProfilesNum", "getProfilesNum",
             "get", "getAll", "startSync", "stopSync", "getLastSyncStatistics"]
    },
    _self,
    syncml = {
        adapter: require('ripple/platform/tizen/2.0/syncml-js-lib/adapter'),
        agent: require('ripple/platform/tizen/2.0/syncml-js-lib/agent'),
        base64: require('ripple/platform/tizen/2.0/syncml-js-lib/base64'),
        codec:  require('ripple/platform/tizen/2.0/syncml-js-lib/codec'),
        common: require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
        constant: require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
        context: require('ripple/platform/tizen/2.0/syncml-js-lib/context'),
        ctype: require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
        devinfo: require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
        item: require('ripple/platform/tizen/2.0/syncml-js-lib/item'),
        localadapter: require('ripple/platform/tizen/2.0/syncml-js-lib/localadapter'),
        matcher: require('ripple/platform/tizen/2.0/syncml-js-lib/matcher'),
        protocol: require('ripple/platform/tizen/2.0/syncml-js-lib/protocol'),
        remoteadapter: require('ripple/platform/tizen/2.0/syncml-js-lib/remoteadapter'),
        router: require('ripple/platform/tizen/2.0/syncml-js-lib/router'),
        state: require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
        storage: require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
        store: require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
        synchronizer: require('ripple/platform/tizen/2.0/syncml-js-lib/synchronizer'),
        useragent: require('ripple/platform/tizen/2.0/syncml-js-lib/useragent')
    },
    TizenAgent;

function _get() {
    _data.item_counter = db.retrieveObject(_data.DB_DATASYNC_COUNTER) || 1000;
    _data.items = db.retrieveObject(_data.DB_DATASYNC_ITEMS) || {};
}

function _save() {
    db.saveObject(_data.DB_DATASYNC_COUNTER, _data.item_counter);
    db.saveObject(_data.DB_DATASYNC_ITEMS, _data.items);
}

TizenAgent = syncml.agent.Agent.extend({
    constructor: function() {
    },
    getContentTypes: function() {
        return [
            new syncml.ctype.ContentTypeInfo('text/x-vcard', '2.1',{preferred: true})
        ];
    },
    dumpsItem: function(item, contentType, version, cb) {
        var cdata = new ET.CdataElement(item.item);
        cb(null, cdata);
    },
    loadsItem: function(data, contentType, version, cb) {
        return cb(null, {item: data._node.textContent});
    },
    getAllItems: function(cb) {
        var items = [];
        utils.forEach(_data.items, function(contact) {
            items.push(contact);
        });
        return cb(null, items);
    },
    addItem: function(item, cb) {
        _data.item_counter++;
        item.id = _data.item_counter.toString();
        _data.items[item.id] = item;
        _save();
        return cb(null, item);
    },
    getItem: function(itemID, cb) {
        return cb(null, _data.items[itemID]);
    },
    replaceItem: function(item, reportChanges, cb) {
        _data.items[item.id] = item;
        _save();
        return cb(null, null);
    },
    deleteItem: function(itemID, cb) {
        delete _data.items[itemID];
        _save();
        return cb(null);
    }
});

function _initialize() {
    _data.agent = new TizenAgent();
    _get();
}

_self = function () {
    var datasync;

    // private
    function createInternalProfile(profile) {
        var _profile, sync_account, service_accounts;

        sync_account = db.retrieveObject("save-syncinfo")[profile.syncInfo.__syncInfoID__];

        _profile = {
            profileName: profile.profileName,
            syncInfo: {
                url:        profile.syncInfo.url,
                id:         sync_account.id,
                password:   sync_account.password,
                mode:       profile.syncInfo.mode
            },
            serviceInfo: []
        };

        switch (_profile.syncInfo.mode) {
        case "MANUAL":
            _profile.syncInfo.type = profile.syncInfo.type || "TWO_WAY";
            break;
        case "PERIODIC":
            //TODO: set 1_HOUR as default value
            _profile.interval = profile.syncInfo.interval || "1_HOUR";
            _profile.syncInfo.type = "TWO_WAY";
            break;
        case "PUSH":
            _profile.syncInfo.type = "TWO_WAY";
            break;
        }

        if (profile.serviceInfo) {
            service_accounts = db.retrieveObject("save-syncserviceinfo");
            utils.forEach(profile.serviceInfo, function (service) {
                _profile.serviceInfo.push({
                    enable:             service.enable,
                    serviceType:        service.serviceType,
                    serverDatabaseUri:  service.serverDatabaseUri,
                    id:                 service_accounts[service.__syncServiceInfoID__].id,
                    password:           service_accounts[service.__syncServiceInfoID__].password
                });
            });
        }

        return _profile;
    }

    function createExternalProfile(profileId) {
        var profile, i, _syncinfo, _serviceinfo, p;

        p = _data.profiles[profileId];

        switch (p.syncInfo.mode) {
        case "MANUAL":
            _syncinfo = new SyncInfoMod(p.syncInfo.url, p.syncInfo.id, p.syncInfo.password, "MANUAL", p.syncInfo.type);
            _syncinfo.interval = null;
            break;
        case "PERIODIC":
            _syncinfo = new SyncInfoMod(p.syncInfo.url, p.syncInfo.id, p.syncInfo.password, "PERIODIC", p.syncInfo.interval);
            break;
        case "PUSH":
            _syncinfo = new SyncInfoMod(p.syncInfo.url, p.syncInfo.id, p.syncInfo.password, "PUSH");
            break;
        }

        if (p.serviceInfo) {
            _serviceinfo = [];
            for (i in p.serviceInfo) {
                var info;
                info = new SyncServiceInfoMod(p.serviceInfo[i].enable,
                        p.serviceInfo[i].serviceType, p.serviceInfo[i].serverDatabaseUri,
                        p.serviceInfo[i].id || null, p.serviceInfo[i].password || null);
                _serviceinfo.push(info);
            }
        }

        profile = new SyncProfileInfoMod(p.profileName, _syncinfo, _serviceinfo);
        Object.defineProperty(profile, "profileId", {value: p.profileId, writable: false});

        return profile;
    }

    // public
    function add(profile) {
        var _profile;

        if (!_security.add) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.DataSynchronizationManager("add", arguments);

        _profile = createInternalProfile(profile);

        if (_data.profile_num > _data.MAX_PROFILE_NUMBER) {
            throw new WebAPIException(errorcode.QUOTA_EXCEEDED_ERR);
        }

        _profile.profileId = Math.uuid(null, 16);
        _data.profiles[_profile.profileId] = _profile;
        _data.profile_num++;

        Object.defineProperty(profile, "profileId", {value: _profile.profileId, writable: false});
    }

    function update(profile) {
        var _profile;

        if (!_security.update) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.DataSynchronizationManager("update", arguments);

        _profile = createInternalProfile(profile);

        if (!profile.profileId || !_data.profiles[profile.profileId]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        _profile.profileId = profile.profileId;
        _data.profiles[_profile.profileId] = _profile;
    }

    function remove(profileId) {
        if (!_security.remove) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.DataSynchronizationManager("remove", arguments);

        if (!_data.profiles[profileId]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        delete _data.profiles[profileId];
        _data.profile_num--;
    }

    function getMaxProfilesNum() {
        if (!_security.getMaxProfilesNum) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        return _data.MAX_PROFILE_NUMBER;
    }

    function getProfilesNum() {
        if (!_security.getProfilesNum) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        return _data.profile_num;
    }

    function get(profileId) {
        var profile;

        if (!_security.get) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.DataSynchronizationManager("get", arguments);

        if (!_data.profiles[profileId]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        profile = createExternalProfile(profileId);

        return profile;
    }

    function getAll() {
        var profiles = [], i;

        if (!_security.getAll) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        for (i in _data.profiles) {
            profiles.push(createExternalProfile(_data.profiles[i].profileId));
        }

        return profiles;
    }

    function startSync(profileId, progressCallback) {
        var _profile, _stores, _routes, sync_peer;

        if (!_security.startSync) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.DataSynchronizationManager("startSync", arguments);

        if (!_data.profiles[profileId]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        _data.profiles[profileId].stop_flag = false;

        sync_peer = function(adapter, store, peer, type) {
            adapter.sync(peer, type, function(err, stats) {
                var p, name, hereTotal, peerTotal;
                p = _data.profiles[profileId];
                if (p.stop_flag === true) {
                    p.syncStatistics =[{
                        syncStatus: "STOP",
                        serviceType:            p.serviceInfo[0].serviceType,
                        lastSyncTime:           new Date(),
                        serverToClientTotal:    0,
                        serverToClientAdded:    0,
                        serverToClientUpdated:  0,
                        serverToClientRemoved:  0,
                        clientToServerTotal:    0,
                        clientToServerAdded:    0,
                        clientToServerUpdated:  0,
                        clientToServerRemoved:  0
                    }];
                    p.stop_flag = false;
                    return;
                }
                if (err) {
                    if (progressCallback) {
                        if (progressCallback.onfailed) {
                            progressCallback.onfailed(profileId, new WebAPIError(errorcode.UNKNOWN_ERR));
                        }
                    }
                    p.syncStatistics =[{
                        syncStatus: "FAIL",
                        serviceType:            p.serviceInfo[0].serviceType,
                        lastSyncTime:           new Date(),
                        serverToClientTotal:    0,
                        serverToClientAdded:    0,
                        serverToClientUpdated:  0,
                        serverToClientRemoved:  0,
                        clientToServerTotal:    0,
                        clientToServerAdded:    0,
                        clientToServerUpdated:  0,
                        clientToServerRemoved:  0
                    }];
                    p.stop_flag = false;
                    return;
                }
                name = p.profileName + "-" + p.serviceInfo[0].serviceType;
                hereTotal = stats[name].hereAdd + stats[name].hereDel + stats[name].hereMod;
                peerTotal = stats[name].peerAdd + stats[name].peerDel + stats[name].peerMod;
                p.syncStatistics =[{
                    syncStatus: "SUCCESS",
                    serviceType:            p.serviceInfo[0].serviceType,
                    lastSyncTime:           new Date(),
                    serverToClientTotal:    hereTotal,
                    serverToClientAdded:    stats[name].hereAdd,
                    serverToClientUpdated:  stats[name].hereMod,
                    serverToClientRemoved:  stats[name].hereDel,
                    clientToServerTotal:    peerTotal,
                    clientToServerAdded:    stats[name].peerAdd,
                    clientToServerUpdated:  stats[name].peerMod,
                    clientToServerRemoved:  stats[name].peerDel
                }];
                p.stop_flag = false;

                if (progressCallback) {
                    if (progressCallback.oncompleted) {
                        progressCallback.oncompleted(profileId);
                    }
                }
            });
        };
        _profile = _data.profiles[profileId];
        _profile.context = new syncml.context.Context({prefix: "tizen-"});
        _stores = [];
        _routes = [];
        utils.forEach(_profile.serviceInfo, function(service) {
            var name = _profile.profileName + "-" + service.serviceType;
            _stores.push({
                uri:            name,
                displayName:    name,
                maxGuidSize:    64,
                maxObjSize:     4000000,
                agent:          _data.agent
            });
            _routes.push([name, service.serverDatabaseUri]);
        });
        _profile.context.getEasyClientAdapter({
            displayName: "Tizen syncML adapter",
            devInfo: {
                devID: "tizen-syncml-03",
                devType: syncml.constant.DEVTYPE_WORKSTATION,
                manufacturerName: "Tizen",
                modelName: "tizen.syncml.client",
                hierarchicalSync: false
            },
            stores: _stores,
            peer: {
                url:        _profile.syncInfo.url,
                username:   _profile.syncInfo.id,
                password:   _profile.syncInfo.password
            },
            routes: _routes
        }, function(err, adapter, stores, peer) {
            if (err) {
                console.log("[datasync.syncml] getEasyClientAdapter fail:", err);
                return;
            }
            utils.forEach(stores, function(store) {
                var args = {
                    data:       _data.mode_table[_profile.syncInfo.type],
                    source:     store.uri,
                    target:     _profile.serviceInfo[0].serverDatabaseUri,
                    nextAnchor: syncml.common.ts()
                };
                if (args.data === _data.mode_table["SLOW"]) {
                    args.lastAnchor = null;
                } else if (peer.getStore(args.target)) {
                    args.lastAnchor = peer.getStore(args.target)._getBinding().localAnchor;
                }

                db.saveObject("syncml-alert-args", args);
                db.saveObject("syncml-first-flag", false);
                sync_peer(adapter, store, peer, _data.type_table[_profile.syncInfo.type]);
            });
        });

    }

    function stopSync(profileId) {
        if (!_security.stopSync) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.DataSynchronizationManager("stopSync", arguments);

        if (!_data.profiles[profileId]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        _data.profiles[profileId].stop_flag = true;
    }

    function getLastSyncStatistics(profileId) {
        var s, statistics = [], i;

        if (!_security.getLastSyncStatistics) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.DataSynchronizationManager("getLastSyncStatistics", arguments);

        if (!_data.profiles[profileId]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }

        s = _data.profiles[profileId].syncStatistics;

        for (i in s) {
            statistics.push(
                new SyncStatistics(s[i].syncStatus, s[i].serviceType, s[i].lastSyncTime,
                    s[i].serverToClientTotal, s[i].serverToClientAdded,
                    s[i].serverToClientUpdated, s[i].serverToClientRemoved,
                    s[i].clientToServerTotal, s[i].clientToServerAdded,
                    s[i].clientToServerUpdated, s[i].clientToServerRemoved)
            );
        }

        return statistics;
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    datasync = {
        add:                    add,
        update:                 update,
        remove:                 remove,
        getMaxProfilesNum:      getMaxProfilesNum,
        getProfilesNum:         getProfilesNum,
        get:                    get,
        getAll:                 getAll,
        startSync:              startSync,
        stopSync:               stopSync,
        getLastSyncStatistics:  getLastSyncStatistics,
        handleSubFeatures:      handleSubFeatures
    };

    return datasync;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/dbfs', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *  Copyright 2012 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    _console = require('ripple/console'),
    _cache = {},
    _self;

function _get(path) {
    return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
        return token === "" ? obj : ((obj && obj.children) ? obj.children[token] || null : null);
    }, _cache);
}

function _getInfo(path) {
    var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
        name = parent.splice(parent.length - 1, 1).join("");

    return {
        name: name,
        parent: parent.join("/") || "/"
    };
}

function _set(path, obj) {
    var parent = _cache,
        tokens = path.replace(/^\//, '').split("/"),
        child = tokens.splice(tokens.length - 1, 1).join("");

    tokens.forEach(function (token) {
        parent = parent.children[token];
    });

    parent.children = parent.children || {};
    parent.children[child] = obj;
}

function _delete(path) {
    var parent = _cache,
        tokens = path.replace(/^\//, '').split("/"),
        child = tokens.splice(tokens.length - 1, 1).join("");

    tokens.forEach(function (token) {
        parent = parent.children[token];
    });

    delete parent.children[child];
}

function _save() {
    db.saveObject("tizen1-db-filesystem", _cache);
}

function _walk(path, parent) {
    _self.ls(path, function (entries) {
        parent.children = parent.children || {};

        entries.forEach(function (entry) {
            parent.children[entry.name] = entry;

            if (entry.isDirectory) {
                _walk(entry.fullPath, entry);
            } else {
                /* after getting Date out of DB, Date will become
                   a string, so need to recast it back to Date */
                if (entry.lastModifiedDate !== null && entry.lastModifiedDate !== undefined)
                    entry.lastModifiedDate = new Date(entry.lastModifiedDate);
                if (entry.createdDate !== null && entry.createdDate !== undefined)
                    entry.createdDate = new Date(entry.createdDate);

                _self.read(entry.fullPath, function (data) {
                    parent.children[entry.name].data = data;
                }, function (e) {
                    _console.error(e);
                });
            }
        });
    }, function (e) {
        _console.error(e);
    });
}

function _createPath(path) {
    var parts = path.replace(/^\//, '').split("/"),
        workflow = jWorkflow.order();

    parts.forEach(function (part, index) {
        var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");

        workflow.andThen(function (prev, baton) {
            baton.take();
            _self.mkdir(dir, baton.pass, baton.pass);
        });
    });

    workflow.start();
}

_self = {
    // The order is consistent with _virtualRoots in filesystem.js
    roots: ["/opt/documents", "/opt/images", "/opt/music", "/opt/videos", "/opt/downloads", "/home/user/appdata/simulatedapp/wgt-package", "/home/user/appdata/simulatedapp/wgt-private", "/home/user/appdata/simulatedapp/wgt-private-tmp", "/SDCard", "/opt/attachments"],
    initialize: function () {
        // TODO: Initialize at bootstrap and emulatorBridge.link
        _cache = db.retrieveObject("tizen1-db-filesystem") || {};
        // create real root paths if empty
        _self.roots.every(function (root) {
            _createPath(root);
            return true;
        });
        // build the file system cache so that we could access information synchronously
        _walk("/", _cache);
    },
    ls: function (path, success, error) {
        try {
            var dir = _get(path),
                items = [];

            if (dir) {
                utils.forEach(dir.children, function (item) {
                    items.push(item);
                });
            }
            else {
                items = {};
            }

            success(items);
        }
        catch (e) {
            e.code = 1;
            error(e);
        }
    },
    rm: function (path, success, error, options) {
        _delete(path);
        _save();
        success();
    },
    rmdir: function (path, success, error, options) {
        _delete(path);
        _save();
        success();
    },
    mkdir: function (path, success, error) {
        var entry = _get(path),
            info = _getInfo(path);

        if (!entry) {
            _set(path, {
                lastModifiedDate: new Date(),
                createdDate: new Date(),
                name: info.name,
                isDirectory: true,
                fullPath: path
            });
            entry = _get(path);
            _save();
        }

        if (entry) {
            success(entry);
        }
        else {
            error({code: 1});
        }
    },
    mv: function (from, to, success, error) {
        try {
            var fromEntry = _get(from),
                toInfo = _getInfo(to);

            fromEntry.fullPath = to;
            fromEntry.name = toInfo.name;

            _set(to, fromEntry);
            _delete(from);
            _save();
            success();
        }
        catch (e) {
            e.code = 1;
            error(e);
        }
    },
    touch: function (path, success, error) {
        var entry = _get(path),
            info  = _getInfo(path);

        if (!entry) {
            _set(path, {
                lastModifiedDate: new Date(),
                createdDate: new Date(),
                name: info.name,
                isDirectory: false,
                fullPath: path,
                data: ""
            });
            entry = _get(path);
        }
        _save();
        success(entry);
    },
    cp: function (from, to, success, error) {
        try {
            var fromEntry = _get(from),
                copied = utils.copy(fromEntry);

            copied.name  = _getInfo(to).name;
            copied.fullPath = to;
            _set(to, copied);
            _save();
            success();
        }
        catch (e) {
            e.code = 1;
            error(e);
        }
    },
    stat: function (path, success, error) {
        var entry = _get(path);

        if (entry) {
            success(entry);
        } else {
            error({code: 1});
        }
    },
    write: function (path, contents, success, error, options) {
        var entry = _get(path);

        if (entry) {
            entry.lastModifiedDate = new Date();
            entry.data = contents;
            _save();
            success();
        } else {
            error({code: 1});
        }

    },
    read: function (path, success, error) {
        var entry = _get(path);

        if (entry) {
            success(utils.copy(entry.data));
        }
        else {
            error({code: 1});
        }
    }
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/dbinit', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    dbfs = require('ripple/platform/tizen/2.0/dbfs'),
    filesystem = require('ripple/platform/tizen/2.0/filesystem'),
    DBBuilder,
    Content,
    FileSystem,
    _data = {
        dbBuilder: null
    },
    _self = {};

function _initialize() {
    _data.dbBuilder = new DBBuilder();

    _data.dbBuilder.register("FileSystem", "", FileSystem);
    _data.dbBuilder.register("Content", "dbcontent.xml", Content);
    _data.dbBuilder.register("Package", "dbpackage.xml");
    _data.dbBuilder.register("Application", "dbapplication.xml");
    _data.dbBuilder.register("Bluetooth", "dbbluetooth.xml");
    _data.dbBuilder.register("MessagePort", "dbmessageport.json");

    _data.FileSystem.initdb();
}

DBBuilder = function () {
    var self;

    // private
    function formatString(str) {
        return str.replace(/^\s+|[\t\n\r\v]+|\s+$/g, "").replace(/\s+/g, " ");
    }

    function getType(node) {
        var type, reNum, reHexNum, reDate;

        if (node.childNodes) {
            return (node.childNodes[0].nodeName === "i") ? "Array" : "Object";
        }

        // Special case
        if (node.nodeName === "version") {
            return "DOMString";
        }

        reNum = /^(-?\d+)(\.\d+)?$/;
        reHexNum = /^0[Xx][0-9A-Fa-f]+$/;
        reDate = /^(\d{4})\-(\d{2})\-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$/;

        if (reNum.test(node.textContent)) {
            type = "Number";
        } else if (reHexNum.test(node.textContent)) {
            type = "Number";
        } else if (reDate.test(node.textContent)) {
            type = "Date";
        } else if (node.textContent === "true" || node.textContent === "false") {
            type = "Boolean";
        } else {
            type = "DOMString";
        }

        return type;
    }

    function build(node) {
        var i, value;

        switch (getType(node)) {
        case "Boolean":
            value = (formatString(node.textContent) === "true");
            break;

        case "Date":
            value = new Date(formatString(node.textContent));
            break;

        case "Number":
            value = Number(formatString(node.textContent));
            break;

        case "Object":
            value = {};
            for (i in node.childNodes) {
                value[node.childNodes[i].nodeName] = build(node.childNodes[i]);
            }
            break;

        case "Array":
            value = [];
            for (i in node.childNodes) {
                value.push(build(node.childNodes[i]));
            }
            break;

        default:  // "DOMString"
            value = formatString(node.textContent);
            break;
        }

        return value;
    }

    function parse(obj) {
        var i, res = {};

        res.nodeName = ("name" in obj.attributes) ?
                obj.attributes["name"].value : obj.nodeName;

        if (obj.childElementCount === 0) {
            res.textContent = obj.textContent;
        } else {
            res.childNodes = [];

            for (i in obj.childNodes) {
                if (obj.childNodes[i].attributes) {
                    res.childNodes.push(parse(obj.childNodes[i]));
                }
            }
        }

        return res;
    }

    // public
    function register(type, dbXml, Extension) {
        _data[type] = Extension ? new Extension() : {};

        if (!dbXml)
            return;

        _self.__defineGetter__(type, function () {
            var fnInit;

            if (!_data[type].db) {
                fnInit = _data[type].initdb || initdb;
                _data[type].db = fnInit(dbXml);
            }

            return _data[type].db;
        });
    }

    function initdb(dbXml) {
        var db = {}, xmlHttp, res;

        try {
            xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", "dbsamples/" + dbXml, false);
            xmlHttp.send();
        } catch (e) {
            exception.handle(e);
        }

        if (/^(.+)\.json$/.test(dbXml)) {
            if (!xmlHttp.responseText) {
                return null;
            }

            db = JSON.parse(formatString(xmlHttp.responseText));
        } else {
            if (!xmlHttp.responseXML) {
                return null;
            }

            res = parse(xmlHttp.responseXML.documentElement);
            res.childNodes.forEach(function (node) {
                db[node.nodeName] = build(node);
            });
        }

        return db;
    }

    self = {
        register: register,
        initdb:   initdb
    };

    return self;
};

/*
 * FileSystem
 */

FileSystem = function () {
    var self;

    // private
    function createPath(path) {
        var parts = path.replace(/^\//, "").split("/"),
            workflow = jWorkflow.order();

        parts.forEach(function (part, index) {
            var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");

            workflow.andThen(function (prev, baton) {
                baton.take();
                dbfs.mkdir(dir, baton.pass, baton.pass);
            });
        });

        workflow.start();
    }

    // public
    function initdb() {
        filesystem.resolve("images", function () {});
        filesystem.resolve("videos", function () {});
        filesystem.resolve("music", function () {});
    }

    function createFile(uri) {
        var directoryURI;

        directoryURI = uri.slice(0, uri.lastIndexOf("/") + 1)
                .replace(/file:\/\//, "");

        dbfs.stat(directoryURI, function () {}, function () {
            createPath(directoryURI);
        });

        uri = uri.replace(/file:\/\//, "");
        dbfs.touch(uri, function () {});
    }

    self = {
        initdb: initdb,
        createFile: createFile
    };

    return self;
};

/*
 * Content
 */

Content = function () {
    var self, ContentStorage;

    ContentStorage = function (contents, directories) {
        var i, parentURI;

        for (i in directories) {
            directories[i].contents = {};
            this[directories[i].directoryURI] = directories[i];
        }

        for (i in contents) {
            parentURI = contents[i].contentURI.slice(0,
                    contents[i].contentURI.lastIndexOf("/") + 1)
                    .replace(/file:\/\//, "");

            if (parentURI in this) {
                this[parentURI].contents[contents[i].contentURI] = contents[i];
            }
        }
    };

    // public
    function initdb(dbXml) {
        var i, db;

        db = _data.dbBuilder.initdb(dbXml);

        if (!db)
            return null;

        for (i in db.contents) {
            _data.FileSystem.createFile(db.contents[i].contentURI);
        }

        return new ContentStorage(db.contents, db.directories);
    }

    self = {
        initdb: initdb
    };

    return self;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/decorator', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    ContactDecorator,
    _self;

ContactDecorator = function (contact, overlap) {
    var raw = {};

    // private
    function clone(obj) {
        return function () {
            var Contact = require('ripple/platform/tizen/2.0/ContactBase'),
                duplicate;

            duplicate = new Contact(obj);

            duplicate.__defineGetter__("id", function () {
                return null;
            });

            duplicate.__defineGetter__("addressBookId", function () {
                return null;
            });

            return duplicate;
        };
    }

    // public
    function convertToString(format) {
        t.Contact("convertToString", arguments);

        // TODO: Convert contact according to VCard protocal
        return "";
    }

    raw.id            = overlap ? overlap.id : null;
    raw.personId      = overlap ? overlap.personId : null;
    raw.addressBookId = overlap ? overlap.addressBookId : null;
    raw.lastUpdated   = overlap ? overlap.lastUpdated : null;
    raw.isFavorite    = overlap ? overlap.isFavorite : false;
    raw.name          = contact.name;
    raw.addresses     = contact.addresses;
    raw.photoURI      = contact.photoURI;
    raw.phoneNumbers  = contact.phoneNumbers;
    raw.emails        = contact.emails;
    raw.birthday      = contact.birthday;
    raw.anniversaries = contact.anniversaries;
    raw.organizations = contact.organizations;
    raw.notes         = contact.notes;
    raw.urls          = contact.urls;
    raw.ringtoneURI   = contact.ringtoneURI;
    raw.groupIds      = contact.groupIds;

    contact.__defineGetter__("id", function () {
        return raw.id;
    });

    contact.__defineGetter__("personId", function () {
        return raw.personId;
    });

    contact.__defineGetter__("addressBookId", function () {
        return raw.addressBookId;
    });

    contact.__defineGetter__("lastUpdated", function () {
        return raw.lastUpdated;
    });

    contact.__defineGetter__("isFavorite", function () {
        return raw.isFavorite;
    });

    contact.__defineGetter__("name", function () {
        return raw.name;
    });
    contact.__defineSetter__("name", function (val) {
        try {
            raw.name = t.ContactName(val, "?");
        } catch (e) {
        }
    });

    contact.__defineGetter__("addresses", function () {
        return raw.addresses;
    });
    contact.__defineSetter__("addresses", function (val) {
        try {
            raw.addresses = t.ContactAddress(val, "[]");
        } catch (e) {
        }
    });

    contact.__defineGetter__("photoURI", function () {
        return raw.photoURI;
    });
    contact.__defineSetter__("photoURI", function (val) {
        try {
            raw.photoURI = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    contact.__defineGetter__("phoneNumbers", function () {
        return raw.phoneNumbers;
    });
    contact.__defineSetter__("phoneNumbers", function (val) {
        try {
            raw.phoneNumbers = t.ContactPhoneNumber(val, "[]");
        } catch (e) {
        }
    });

    contact.__defineGetter__("emails", function () {
        return raw.emails;
    });
    contact.__defineSetter__("emails", function (val) {
        try {
            raw.emails = t.ContactEmailAddress(val, "[]");
        } catch (e) {
        }
    });

    contact.__defineGetter__("birthday", function () {
        return raw.birthday;
    });
    contact.__defineSetter__("birthday", function (val) {
        try {
            raw.birthday = t.Date(val, "?");
        } catch (e) {
        }
    });

    contact.__defineGetter__("anniversaries", function () {
        return raw.anniversaries;
    });
    contact.__defineSetter__("anniversaries", function (val) {
        try {
            raw.anniversaries = t.ContactAnniversary(val, "[]");
        } catch (e) {
        }
    });

    contact.__defineGetter__("organizations", function () {
        return raw.organizations;
    });
    contact.__defineSetter__("organizations", function (val) {
        try {
            raw.organizations = t.ContactOrganization(val, "[]");
        } catch (e) {
        }
    });

    contact.__defineGetter__("notes", function () {
        return raw.notes;
    });
    contact.__defineSetter__("notes", function (val) {
        try {
            raw.notes = t.DOMString(val, "[]");
        } catch (e) {
        }
    });

    contact.__defineGetter__("urls", function () {
        return raw.urls;
    });
    contact.__defineSetter__("urls", function (val) {
        try {
            raw.urls = t.ContactWebSite(val, "[]");
        } catch (e) {
        }
    });

    contact.__defineGetter__("ringtoneURI", function () {
        return raw.ringtoneURI;
    });
    contact.__defineSetter__("ringtoneURI", function (val) {
        try {
            raw.ringtoneURI = t.DOMString(val, "?");
        } catch (e) {
        }
    });

    contact.__defineGetter__("groupIds", function () {
        return raw.groupIds;
    });
    contact.__defineSetter__("groupIds", function (val) {
        try {
            raw.groupIds = t.ContactGroupId(val, "[]");
        } catch (e) {
        }
    });

    if (contact.name) {
        contact.name.__defineGetter__("displayName", function () {
            return ((overlap && overlap.name) ? overlap.name.displayName :
                    null);
        });
    }

    contact.convertToString = convertToString;
    contact.clone           = clone(contact);
};

_self = {
    Contact: ContactDecorator
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/download', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    event = require('ripple/event'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    filesystem = require('ripple/platform/tizen/2.0/filesystem'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    DownloadRequest = require('ripple/platform/tizen/2.0/DownloadRequest'),
    DownloadState = {
        QUEUED: "QUEUED",
        DOWNLOADING: "DOWNLOADING",
        PAUSED: "PAUSED",
        CANCELED: "CANCELED",
        COMPLETED: "COMPLETED",
        FAILED: "FAILED"
    },
    _security = {
        "http://tizen.org/privilege/download": ["start"]
    },
    DB_DOWNLOAD_KEY = "tizen1-db-download",
    DownloadItem, _isInitialized = false, INTERVAL = 1000,
    _downloads = [], _resources = [], _self;

function _initDownloadItem(download) {
    var url, index, isExist = false;
    url = download.url;
    if (download.destination === null) {
        download.destination = "downloads";
    }
    if (download.fileName === null) {
        index = url.lastIndexOf('\/') + 1;
        download.fileName = url.substring(index);
    }
    if (!_isInitialized) {
        initializeResource();
    }
    _resources.some(function (value) {
        if (value.url === url) {
            download.size           = Number(value.size);
            download.speed          = Number(value.speed);
            download.estimatedTime = Math.round(value.estimatedTime * 100) / 100;
            download.MIMEType       = value.MIMEType;
            isExist =  true;
            return;
        }
    });
    if (!isExist) {
        download.state = DownloadState.FAILED;
        _exec(download.callback, 'onfailed', download.id, new WebAPIError(errorcode.NOT_FOUND_ERR));
        return;
    }
    return download;
}

function _exec(callback, name, downloadId, arg1, arg2) {
    if (callback === null) {
        return;
    }

    window.setTimeout(function () {
        switch (name) {
        case "onprogress":
            callback[name](downloadId, arg1, arg2);
            break;

        case "onpaused":
            callback[name](downloadId);
            break;

        case "oncanceled":
            callback[name](downloadId);
            break;

        case "oncompleted":
            callback[name](downloadId, arg1);
            break;

        case "onfailed":
            callback[name](downloadId, arg1);
            break;

        default:
            break;
        }
    }, 1);
}

function _getDownloadObjById(id) {
    var isFound = false, backObj;
    id = Number(id);
    _downloads.some(function (obj) {
        if (obj.id === id) {
            backObj = obj;
            isFound = true;
            return;
        }
    });
    if (!isFound) {
        throw new WebAPIException(errorcode.NOT_FOUND_ERR);
    }
    return backObj;
}

function initializeResource() {
    _resources = db.retrieveObject(DB_DOWNLOAD_KEY);
    _isInitialized = true;
}

function _saveFile(downloadObj, callback) {
    var name, path, content;

    name = downloadObj.fileName;
    path = downloadObj.destination;
    content = 'size|' + downloadObj.size + ',speed|' + downloadObj.speed + ',url|' + downloadObj.url + ',estimatedTime|' + downloadObj.estimatedTime;
    function onsuccess(fs) {
        fs.write(content);
        fs.close();
    }
    function onerror(e) {
        _exec(downloadObj.callback, 'onfailed', downloadObj.id, e);
    }
    function rename(name) { //index.html==>index_1.html
        var index, c;
        index = name.lastIndexOf('.');
        if (index < 0) {
            index = name.length;
        }
        c = name.substr(index - 2, 1);
        if (c === '_') {
            name = name.substr(0, index - 1) + (Number(name.substr(index - 1, 1)) + 1) + name.substring(index);
        } else {
            name = name.substr(0, index) + "_1" + name.substring(index);
        }
        return name;
    }

    filesystem.resolve(path, function (dir) {
        var file, isExist = true;
        while (isExist) {
            try {
                file = dir.resolve(name);
                name = rename(name);
            } catch (e) {
                isExist = false;
            }
        }
        file = dir.createFile(name);
        file.openStream('w', onsuccess, onerror, 'UTF-8');
        callback(name);
    }, onerror, "rw");
}

DownloadItem = function (download, callback) {
    var _self;
    _self = {
        id           : Number(Math.uuid(8, 10)),
        url          : download.url,
        state        : DownloadState.QUEUED,
        fileName     : download.fileName || null,
        destination  : download.destination || null,
        callback     : callback || null
    };
    return _self;
};

_self = function () {
    function start(downloadRequest, downloadCallback) {
        var downloadObj, fileSize, increment, receivedSize = 0, intervalId;

        if (!_security.start) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.DownloadManager("start", arguments);

        downloadObj = new DownloadItem(downloadRequest, downloadCallback);
        _downloads.push(downloadObj);
        downloadObj = _initDownloadItem(downloadObj);
        if (downloadObj === null || downloadObj === undefined) {
            return;
        }
        downloadObj.state = DownloadState.DOWNLOADING;

        fileSize = downloadObj.size;
        increment = downloadObj.speed;
        intervalId = setInterval(function () {
            if (receivedSize >= fileSize) {//Finish downloading
                receivedSize = fileSize;
                downloadObj.state = DownloadState.COMPLETED;
                _saveFile(downloadObj, function (fileName) {
                    _exec(downloadObj.callback, 'oncompleted', downloadObj.id, fileName);
                });
                clearInterval(intervalId);
            } else { // Continue downloading
                receivedSize += increment;
                downloadObj.receivedSize = receivedSize;
                _exec(downloadObj.callback, 'onprogress', downloadObj.id, receivedSize, fileSize);
            }
        }, INTERVAL);
        downloadObj.intervalId = intervalId;
        return downloadObj.id;
    }

    function cancel(downloadId) {
        var downloadObj;

        t.DownloadManager("cancel", arguments);

        downloadObj = _getDownloadObjById(downloadId);
        clearInterval(downloadObj.intervalId);
        if (downloadObj.state !== DownloadState.DOWNLOADING &&
            downloadObj.state !== DownloadState.PAUSED) {
            _exec(downloadObj.callback, 'onfailed', downloadObj.id, new WebAPIError(errorcode.INVALID_VALUES_ERR));
            return;
        }
        downloadObj.state = DownloadState.CANCELED;
        _exec(downloadObj.callback, 'oncanceled', downloadObj.id);
    }

    function pause(downloadId) {
        var downloadObj;

        t.DownloadManager("pause", arguments);

        downloadObj = _getDownloadObjById(downloadId);
        clearInterval(downloadObj.intervalId);
        if (downloadObj.state !== DownloadState.DOWNLOADING) {
            _exec(downloadObj.callback, 'onfailed', downloadObj.id, new WebAPIError(errorcode.INVALID_VALUES_ERR));
            return;
        }
        downloadObj.state = DownloadState.PAUSED;
        _exec(downloadObj.callback, 'onpaused', downloadObj.id);
    }

    function resume(downloadId) {
        var downloadObj, fileSize, receivedSize, increment, intervalId;

        t.DownloadManager("resume", arguments);

        downloadObj  = _getDownloadObjById(downloadId);
        fileSize     = downloadObj.size;
        receivedSize = downloadObj.receivedSize;
        increment    = downloadObj.speed;

        if (downloadObj.state !== DownloadState.PAUSED) {
            _exec(downloadObj.callback, 'onfailed', downloadObj.id, new WebAPIError(errorcode.INVALID_VALUES_ERR));
            return;
        }
        downloadObj.state = DownloadState.DOWNLOADING;
        intervalId = setInterval(function () {
            if (receivedSize >= fileSize) {//Finish downloading
                receivedSize = fileSize;
                downloadObj.state = DownloadState.COMPLETED;
                _saveFile(downloadObj, function (fileName) {
                    _exec(downloadObj.callback, 'oncompleted', downloadObj.id, fileName);
                });
                clearInterval(intervalId);
            } else {// Continue downloading
                receivedSize += increment;
                downloadObj.receivedSize = receivedSize;
                _exec(downloadObj.callback, 'onprogress', downloadObj.id, receivedSize, fileSize);
            }
        }, INTERVAL);
        downloadObj.intervalId = intervalId;
    }

    function getState(downloadId) {
        var downloadObj;

        t.DownloadManager("getState", arguments);

        downloadObj = _getDownloadObjById(downloadId);
        return downloadObj.state;
    }

    function getDownloadRequest(downloadId) {
        var req, downloadObj;

        t.DownloadManager("getDownloadRequest", arguments);

        downloadObj = _getDownloadObjById(downloadId);
        req = new DownloadRequest(downloadObj.url, downloadObj.destination, downloadObj.fileName);
        return req;
    }

    function getMIMEType(downloadId) {
        var downloadObj;

        t.DownloadManager("getMIMEType", arguments);

        downloadObj = _getDownloadObjById(downloadId);
        return downloadObj.MIMEType;
    }

    function setListener(downloadId, downloadCallback) {
        var downloadObj;

        t.DownloadManager("setListener", arguments);

        downloadObj = _getDownloadObjById(downloadId);
        if (downloadObj) {
            downloadObj.callback = downloadCallback;
        }
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    var download = {
        start: start,
        cancel: cancel,
        pause: pause,
        resume: resume,
        getState: getState,
        getDownloadRequest: getDownloadRequest,
        getMIMEType: getMIMEType,
        setListener: setListener,
        handleSubFeatures: handleSubFeatures
    };

    return download;
};

event.on('downloadResourceChanged', function () {
    _isInitialized = false;
});

module.exports = _self;

});
define('ripple/platform/tizen/2.0/errorcode', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 _self = {};

_self.__defineGetter__("UNKNOWN_ERR", function () {
    return 0;
});

_self.__defineGetter__("INDEX_SIZE_ERR", function () {
    return 1;
});

_self.__defineGetter__("DOMSTRING_SIZE_ERR", function () {
    return 2;
});

_self.__defineGetter__("HIERARCHY_REQUEST_ERR", function () {
    return 3;
});

_self.__defineGetter__("WRONG_DOCUMENT_ERR", function () {
    return 4;
});

_self.__defineGetter__("INVALID_CHARACTER_ERR", function () {
    return 5;
});

_self.__defineGetter__("NO_DATA_ALLOWED_ERR", function () {
    return 6;
});

_self.__defineGetter__("NO_MODIFICATION_ALLOWED_ERR", function () {
    return 7;
});

_self.__defineGetter__("NOT_FOUND_ERR", function () {
    return 8;
});

_self.__defineGetter__("NOT_SUPPORTED_ERR", function () {
    return 9;
});

_self.__defineGetter__("INUSE_ATTRIBUTE_ERR", function () {
    return 10;
});

_self.__defineGetter__("INVALID_STATE_ERR", function () {
    return 11;
});

_self.__defineGetter__("SYNTAX_ERR", function () {
    return 12;
});

_self.__defineGetter__("INVALID_MODIFICATION_ERR", function () {
    return 13;
});

_self.__defineGetter__("NAMESPACE_ERR", function () {
    return 14;
});

_self.__defineGetter__("INVALID_ACCESS_ERR", function () {
    return 15;
});

_self.__defineGetter__("VALIDATION_ERR", function () {
    return 16;
});

_self.__defineGetter__("TYPE_MISMATCH_ERR", function () {
    return 17;
});

_self.__defineGetter__("SECURITY_ERR", function () {
    return 18;
});

_self.__defineGetter__("NETWORK_ERR", function () {
    return 19;
});

_self.__defineGetter__("ABORT_ERR", function () {
    return 20;
});

_self.__defineGetter__("URL_MISMATCH_ERR", function () {
    return 21;
});

_self.__defineGetter__("QUOTA_EXCEEDED_ERR", function () {
    return 22;
});

_self.__defineGetter__("TIMEOUT_ERR", function () {
    return 23;
});

_self.__defineGetter__("INVALID_NODE_TYPE_ERR", function () {
    return 24;
});

_self.__defineGetter__("DATA_CLONE_ERR", function () {
    return 25;
});

_self.__defineGetter__("INVALID_VALUES_ERR", function () {
    return 99;
});

_self.__defineGetter__("IO_ERR", function () {
    return 100;
});

_self.__defineGetter__("SERVICE_NOT_AVAILABLE_ERR", function () {
    return 111;
});

module.exports = _self;


});
define('ripple/platform/tizen/2.0/filesystem', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    utils = require('ripple/utils'),
    dbfs  = require('ripple/platform/tizen/2.0/dbfs'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    _maxPathLength = 256,
    _virtualRoots = ["documents", "images", "music", "videos", "downloads", "wgt-package", "wgt-private", "wgt-private-tmp", "removable", "attachments"],
    _security = {
        "http://tizen.org/privilege/filesystem": [],
        "http://tizen.org/privilege/filesystem.read": ["copyTo", "moveTo", "createDirectory", "createFile", "deleteDirectory", "deleteFile", "openStreamR"],
        "http://tizen.org/privilege/filesystem.write": ["readAsText", "openStreamW"],
        all: true
    },
    _realRoots = dbfs.roots,
    _r2vmap = {},
    _v2rmap = {},
    _initialized = false,
    _readOnly  = false,
    _writeOnly = false,
    _defaultMode = "rw",
    _storages = [], // filesystem storages
    _observers = [],
    File,
    FileStream,
    FileFilter,
    FileSystemStorage;

function _isValidChar(c) {
    return  (c >= '0' && c <= '9') ||
        (c >= 'a' && c <= 'z') ||
        (c >= 'A' && c <= 'Z') ||
        (c === ' ') ||
        (c === '_') ||
        (c === '-') ||
        (c === '.');
}

function _isValidFileName(name) {
    var _valid = true,
        _c;

    if (name === '' || name === '.' || name === '..' || (name.length > _maxPathLength)) {
        _valid = false;
    } else {
        for (_c = 0; _c < name.length; _c++) {
            if (!_isValidChar(name[_c])) {
                _valid = false;
                break;
            }
        }
    }

    return _valid;
}

function _initialize() {
    var _i;

    _storages.push(FileSystemStorage("InternalFlash", "INTERNAL", "MOUNTED" ));
    _storages.push(FileSystemStorage("MMC", "EXTERNAL", "REMOVED"));
    dbfs.initialize();

    // set up the map between real path and virtual path
    for (_i = 0; _i < _virtualRoots.length; _i++) {
        _r2vmap[_realRoots[_i]] = _virtualRoots[_i];
    }

    utils.forEach(_r2vmap, function (value, key) {
        _v2rmap[value] = key;
    });
}

function _resolveSync(srcLocation, onSuccess, onError, accessMode) {
    var _parts = srcLocation.replace(/\/$/, '').split("/"),
        _header, _fullPath,
        _i;

    // TODO: Initialize at bootstrap and emulatorBridge.link
    if (!_initialized) {
        _initialize();
        _initialized = true;
    }

    for (_i = 0; _i < _parts.length; _i++) {
        if (!_isValidFileName(_parts[_i])) {
            if (onError) {
                onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
            }
            return;
        }
    }

    _header = _v2rmap[_parts[0]];
    if (_header === undefined) {
        if (onError) {
            onError(new WebAPIError(errorcode.NOT_FOUND_ERR));
        }
        return;
    }

    if (_parts.length === 1) {
        _fullPath = _header;
    } else {
        _fullPath = _header + "/" + _parts.splice(1, _parts.length - 1).join("/");
    }

    dbfs.stat(_fullPath,
            function (entry) {
                onSuccess(new File(entry, accessMode));
            },
            function () {
                if (onError) {
                    onError(new WebAPIError(errorcode.NOT_FOUND_ERR));
                }
            });
}

function _resolveAsync(onSuccess, onError, srcLocation, accessMode) {
    _resolveSync(srcLocation,
                function (file) {
                    setTimeout(function () {
                        onSuccess(file);
                    }, 1);
                },
                function (e) {
                    setTimeout(function () {
                        onError(e);
                    }, 1);
                },
                accessMode);
}

File = function (entry, mode) {
    var _entry = entry,
        _mode = mode,
        _parent,
        _self;

    function _r2v(rpath) {
        var i, v, r, regExp;

        for (i = 0; i < _virtualRoots.length; i++) {
            v = _virtualRoots[i];
            r = _v2rmap[v];
            if (rpath.match("^" + r)) {
                regExp = new RegExp("^" + r);
                return rpath.replace(regExp, v);
            }
        }

        return "";
    }

    function _v2r(vpath) {
        var i, v, r, regExp;

        for (i = 0; i < _virtualRoots.length; i++) {
            v = _virtualRoots[i];
            r = _v2rmap[v];
            if (vpath.match("^" + v)) {
                regExp = new RegExp("^" + v);
                return vpath.replace(regExp, r);
            }
        }

        return "";
    }

    function _copyMoveInternal(onSuccess, onError, src, dst, overwrite, func) {
        var _srcName = String(src),
            _dstName = String(dst),
            _src = null,
            _dst = null,
            _error = false,
            _dstParent = null,
            _dstParts  = _dstName.split("/"),
            _dstParentName = _dstParts.splice(0, _dstParts.length - 1).join("/");

        if (!_entry.isDirectory) {
            if (onError) {
                setTimeout(function () {
                    onError(new WebAPIError(errorcode.IO_ERR));
                }, 1);
            }
            return undefined;
        }

        _resolveSync(_srcName,
                function (file) {
                    _src = file;
                },
                function (e) {
                    setTimeout(function () {
                        onError(e);
                    }, 1);
                },
                _mode);

        if (_src) {
            if (_src.parent.fullPath === _self.fullPath) {
                if (!_readOnly && _mode !== "r") {
                    _resolveSync(_dstParentName,
                            function (file) {
                                _dstParent = file;
                            },
                            function (e) {
                                setTimeout(function () {
                                    onError(e);
                                }, 1);
                            },
                            _mode);

                    if (_dstParent === null) {
                        return undefined;
                    }

                    _resolveSync(_dstName,
                            function (file) {
                                _dst = file;
                            },
                            function (e) {
                                if (e.code !== errorcode.NOT_FOUND_ERR) {
                                    setTimeout(function () {
                                        onError(e);
                                    }, 1);
                                    _error = true;
                                }
                            },
                            _mode);

                    if (_error) {
                        return undefined;
                    }

                    if (_src.isFile) {
                        if (_dst === null) {
                            func(_v2r(_srcName), _v2r(_dstName),
                                    function () {
                                        setTimeout(function () {
                                            onSuccess();
                                        }, 1);
                                    },
                                    function () {});
                            return null;
                        } else {
                            if (_dst.isFile && Boolean(overwrite) && (_srcName !== _dstName)) {
                                func(_v2r(_srcName), _v2r(_dstName),
                                        function () {
                                            setTimeout(function () {
                                                onSuccess();
                                            }, 1);
                                        },
                                        function () {});
                                return null;
                            } else {
                                setTimeout(function () {
                                    onError(new WebAPIError(errorcode.IO_ERR));
                                }, 1);
                            }
                        }
                    } else {
                        if (_dst === null) {
                            func(_v2r(_srcName), _v2r(_dstName),
                                function () {
                                    setTimeout(function () {
                                        onSuccess();
                                    }, 1);
                                },
                                function () {});
                            return null;
                        } else {
                            setTimeout(function () {
                                onError(new WebAPIError(errorcode.IO_ERR));
                            }, 1);
                        }
                    }
                } else {
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                }
            } else {
                if (onError) {
                    setTimeout(function () {
                        onError(new WebAPIError(errorcode.IO_ERR));
                    }, 1);
                }
            }
        }

        return undefined;
    }

    _self = {
        toURI: function () {
            return "file://" + _entry.fullPath;
        },
        listFiles: function (onSuccess, onError, filter) {
            var _filter, _filterName, _startCreated, _endCreated, _startModified, _endModified;

            if (filter !== null && filter !== undefined) {

                if (typeof filter === 'number' || typeof filter === 'string') {
                    throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
                }
                _filter = filter;
                _filterName = _filter.name;
                _startModified = _filter.startModified;
                _endModified   = _filter.endModified;
                _startCreated = _filter.startCreated;
                _endCreated   = _filter.endCreated;

            }
            if ((_filterName !== undefined && typeof _filterName !== 'string') ||
                (_startModified !== undefined && !tizen1_utils.isValidDate(_startModified)) ||
                (_endModified !== undefined && !tizen1_utils.isValidDate(_endModified)) ||
                (_endCreated !== undefined && !tizen1_utils.isValidDate(_endCreated)) ||
                (_startCreated !== undefined && !tizen1_utils.isValidDate(_startCreated))) {
                throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
            }

            function _matchName(fileName) {
                var _matched = true,
                    _name1 = String(_filterName).toLowerCase(),
                    _name2 = fileName.toLowerCase(),
                    _pattern;

                if (_filterName !== undefined && _filterName !== null) {
                    if (!_name1.match("\\\\%")) {
                        if (_name1.match("%")) {
                            _pattern = new RegExp("^" + _name1.replace(/%/g, ".*") + "$");
                            _matched = _name2.match(_pattern) ? true : false;
                        } else {
                            _matched = (_name1 === _name2);
                        }
                    } else {
                        // % is not allowed as a part of file name
                        _matched = false;
                    }
                }

                return _matched;
            }

            function _matchDate(date) {
                var _matched = true;

                if (date === undefined) return true;

                if (_startModified !== undefined && _startModified !== null) {
                    _matched = (date.getTime() >= _startModified.getTime());
                }

                if (_matched && (_endModified !== undefined && _endModified !== null)) {
                    _matched = (date.getTime() <= _endModified.getTime());
                }

                return _matched;
            }

            function _matchFilter(entry) {
                return _matchName(entry.name) && _matchDate(entry.lastModifiedDate) && _matchDate(entry.createdDate);
            }

            function _listFiles() {
                var _files = [];

                if (!_entry.isDirectory) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.IO_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                utils.forEach(_entry.children, function (child) {
                    if (_matchFilter(child)) {
                        _files.push(new File(child, _mode));
                    }
                });

                setTimeout(function () {
                    onSuccess(_files);
                }, 1);

                return null;
            }

            return tizen1_utils.validateTypeMismatch(onSuccess, onError, "listFiles", _listFiles);
        },
        openStream: function (mode, onSuccess, onError, encoding) {
            function _openStream() {
                var  _openMode = String(mode),
                    _encoding = encoding ? String(encoding) : "UTF-8";

                if (_openMode !== "r" && _openMode !== "w" && _openMode !== "a") {
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                if (!_security.all && ((!_security.openStreamR && _openMode === "r") || (!_security.openStreamW && _openMode === "w"))) {
                    throw new WebAPIException(errorcode.SECURITY_ERR);
                }

                if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                if (((_readOnly || _mode === "r") && (_openMode === "w" || _openMode === "a")) ||
                    (_writeOnly && _openMode === "r")) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                setTimeout(function () {
                    onSuccess(new FileStream(_entry, _openMode, _encoding));
                }, 1);

                return null;
            }

            return tizen1_utils.validateTypeMismatch(onSuccess, onError, "openStream", _openStream);
        },
        readAsText: function (onSuccess, onError, encoding) {
            if (!_security.all && !_security.readAsText) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            function _readAsText() {
                var _encoding = encoding ? String(encoding) : "UTF-8";
                if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                if (_writeOnly) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                if (_self.isFile) {
                    dbfs.read(_entry.fullPath,
                            function (data) {
                                setTimeout(function () {
                                    onSuccess(data);
                                }, 1);
                            },
                            function () {});
                    return null;
                } else {
                    if (onError) {
                        setTimeout(function () {
                            onError(new WebAPIError(errorcode.IO_ERR));
                        }, 1);
                    }
                }

                return undefined;
            }

            return tizen1_utils.validateTypeMismatch(onSuccess, onError, "readAsText", _readAsText);
        },
        copyTo: function (src, dst, overwrite, onSuccess, onError) {
            if (!_security.all && !_security.copyTo) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            function _copyTo() {
                return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.cp);
            }

            return tizen1_utils.validateTypeMismatch(onSuccess, onError, "copyTo", _copyTo);
        },
        moveTo: function (src, dst, overwrite, onSuccess, onError) {
            if (!_security.all && !_security.moveTo) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            function _moveTo() {
                return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.mv);
            }

            return tizen1_utils.validateTypeMismatch(onSuccess, onError, "moveTo", _moveTo);
        },
        createDirectory: function (dirPath) {
            var _path  = String(dirPath),
                _parts = _path.replace(/\/$/, "").split("/"),
                _dir   = null,
                _exist = null,
                _current = _entry.fullPath,
                _i;

            if (!_security.all && !_security.createDirectory) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            function onSuccess(entry) {
                _dir = entry;
            }

            for (_i = 0; _i < _parts.length; _i++) {
                if (!_isValidFileName(_parts[_i])) {
                    throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
                }
            }

            if (!entry.isDirectory) {
                throw new WebAPIException(errorcode.IO_ERR);
            }

            _exist = _parts.reduce(function (obj, token) {
                return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
            }, _entry);

            if (_exist) {
                throw new WebAPIException(errorcode.IO_ERR);
            }

            if (_readOnly || _mode === "r") {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            for (_i = 0; _i < _parts.length; _i++) {
                _current = _current + "/" + _parts[_i];
                dbfs.mkdir(_current, onSuccess);
            }

            return new File(_dir, _mode);
        },
        createFile: function (filePath) {
            var _name = String(filePath),
                _file = null;

            if (!_security.all && !_security.createFile) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            if (!_isValidFileName(_name)) {
                throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
            }

            if (!entry.isDirectory || (_entry.children && _entry.children[_name])) {
                throw new WebAPIException(errorcode.IO_ERR);
            }

            if (_readOnly || _mode === "r") {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            dbfs.touch(_entry.fullPath + "/" + _name,
                        function (entry) {
                            _file = new File(entry, _mode);
                        },
                        function () {});

            return _file;
        },
        resolve: function (filePath) {
            var _fullPath = _self.fullPath + "/" + String(filePath),
                _file = null;

            if (!_entry.isDirectory) {
                throw new WebAPIException(errorcode.IO_ERR);
            }

            _resolveSync(_fullPath,
                    function (file) {
                        _file = file;
                    },
                    function (e) {
                        throw (e);
                    },
                    _mode);

            return _file;
        },
        deleteDirectory: function (directory, recursive, onSuccess, onError) {
            if (!_security.all && !_security.deleteDirectory) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            function _deleteDirectory() {
                var _dir = null,
                    _dirName = String(directory);
                _resolveSync(_dirName,
                        function (file) {
                            _dir = file;
                        },
                        function (e) {
                            setTimeout(function () {
                                onError(e);
                            }, 1);
                        },
                        _mode);

                if (_dir) {
                    if (_dir.isDirectory &&
                        _dir.parent.fullPath === _self.fullPath &&
                        (!recursive && _dir.length === 0)) {
                        if (!_readOnly && _mode !== "r") {
                            dbfs.rmdir(_v2r(_dirName),
                                    function () {
                                        setTimeout(function () {
                                            onSuccess();
                                        }, 1);
                                    },
                                    function () {});
                            return null;
                        } else {
                            if (onError) {
                                setTimeout(function () {
                                    onError(new WebAPIError(errorcode.SECURITY_ERR));
                                }, 1);
                            }
                        }
                    } else {
                        if (onError) {
                            setTimeout(function () {
                                onError(new WebAPIError(errorcode.IO_ERR));
                            }, 1);
                        }
                    }
                }

                return undefined;
            }

            return tizen1_utils.validateTypeMismatch(onSuccess, onError, "deleteDirectory", _deleteDirectory);
        },
        deleteFile: function (fileName, onSuccess, onError) {
            if (!_security.all && !_security.deleteFile) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }

            function _deleteFile() {
                var _file = null;
                _resolveSync(String(fileName),
                        function (file) {
                            _file = file;
                        },
                        function (e) {
                            if (onError) {
                                setTimeout(function () {
                                    onError(e);
                                }, 1);
                            }
                        },
                        _mode);

                if (_file) {
                    if (_file.isFile && _file.parent.fullPath === _self.fullPath) {
                        if (!_readOnly && _mode !== "r") {
                            dbfs.rm(_v2r(fileName),
                                    function () {
                                        setTimeout(function () {
                                            onSuccess();
                                        }, 1);
                                    },
                                    function () {});
                            return null;
                        } else {
                            if (onError) {
                                setTimeout(function () {
                                    onError(new WebAPIError(errorcode.SECURITY_ERR));
                                }, 1);
                            }
                        }
                    } else {
                        if (onError) {
                            setTimeout(function () {
                                onError(new WebAPIError(errorcode.IO_ERR));
                            }, 1);
                        }
                    }
                }

                return undefined;
            }

            return tizen1_utils.validateTypeMismatch(onSuccess, onError, "deleteFile", _deleteFile);
        }
    };

    _self.__defineGetter__("parent", function () {
        var _parts = _self.fullPath.split("/");

        if (_parent === undefined) {
            if (_parts.length === 1) {
                // virtual root's parent is null
                _parent = null;
            } else {
                _resolveSync(_parts.splice(0, _parts.length - 1).join("/"),
                        function (file) {
                            _parent = file;
                        },
                        function () {},
                        _mode);
            }
            return _parent;
        } else {
            return _parent;
        }
    });

    _self.__defineGetter__("readOnly", function () {
        return false;
    });

    _self.__defineGetter__("isFile", function () {
        return !_entry.isDirectory;
    });

    _self.__defineGetter__("isDirectory", function () {
        return _entry.isDirectory;
    });

    _self.__defineGetter__("created", function () {
        return _entry.createdDate;
    });

    _self.__defineGetter__("modified", function () {
        return _entry.lastModifiedDate;
    });

    _self.__defineGetter__("path", function () {
        var _parts = _self.fullPath.split("/");

        if (_parts.length === 1) {
            // virtual root
            return _parts.join("");
        } else {
            return _parts.splice(0, _parts.length - 1).join("/") + "/";
        }
    });

    _self.__defineGetter__("name", function () {
        return _entry.name;
    });

    _self.__defineGetter__("fullPath", function () {
        return _r2v(_entry.fullPath);
    });

    _self.__defineGetter__("fileSize", function () {
        if (_entry.isDirectory) {
            return undefined;
        } else {
            return _entry.data.length;
        }
    });

    _self.__defineGetter__("length", function () {
        var _l = 0;
        if (_entry.isDirectory) {
            utils.forEach(_entry.children, function () {
                _l++;
            });
            return _l;
        } else {
            return undefined;
        }
    });

    return _self;
};

FileStream = function (entry, mode, encoding) {
    var _entry = entry,
        _data = entry.data,
        _mode = mode,
        _position = (_mode === "a" ? _data.length : 0),
        _self;

    _self = {
        close: function () {
            var _element;
            if (mode === "a" || mode === "w") {
                dbfs.write(_entry.fullPath, _data, function () {}, function () {});
            }
            for (_element in _self) {
                delete _self[_element];
            }
        },
        read: function (charCount) {
            var _count  = charCount | 0,
                _substr = _data.substring(_position, _position + _count);

            if (_position + _count > _data.length) {
                _position = _data.length;
            } else {
                _position += _count;
            }

            return _substr;
        },
        readBytes: function (byteCount) {
            var _substr = _self.read(byteCount),
                _bytes = [],
                _i;

            for (_i = 0; _i < _substr.length; _i++) {
                _bytes.push(_substr.charCodeAt(_i));
            }

            return _bytes;
        },
        readBase64: function (byteCount) {
            var _substr = _self.read(byteCount);

            return window.atob(_substr);
        },
        write: function (stringData) {
            var _stringData = String(stringData),
                _substr = _data.substring(0, _position);

            _data = _substr.concat(_stringData);
            _position = _data.length;
        },
        writeBytes: function (byteData) {
            _self.write(String.fromCharCode.apply(String, byteData));
        },
        writeBase64: function (base64Data) {
            _self.write(window.btoa(String(base64Data)));
        }
    };

    _self.__defineGetter__("eof", function () {
        return _position === _data.length;
    });

    _self.__defineGetter__("position", function () {
        return _position;
    });

    _self.__defineSetter__("position", function (value) {
        var _value = value | 0;

        if (_value >= 0 && _value <= _data.length) {
            _position = _value;
        } else {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
    });

    _self.__defineGetter__("bytesAvailable", function () {
        return (_data.length - _position) || -1;
    });

    return _self;
};

FileFilter = function (name, startModified, endModified, startCreated, endCreated) {
    var _self = {
        name: name,
        startModified: utils.copy(startModified),
        endModified: utils.copy(endModified),
        endCreated: utils.copy(endCreated)
    };

    return _self;
};

FileSystemStorage = function (label, type, state) {
    var _self = {
        label: label,
        type: type,
        state: state
    };

    return _self;
};

module.exports = {
    maxPathLength: _maxPathLength,
    resolve: function (srcLocation, onSuccess, onError, accessMode) {
        function _resolve() {
            var _mode = accessMode ? String(accessMode) : _defaultMode;

            if (_mode === "r" || _mode === "rw") {
                _resolveAsync(onSuccess, onError, String(srcLocation), _mode);
                return null;
            } else {
                if (onError) {
                    setTimeout(function () {
                        onError(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                    }, 1);
                }
            }
            return undefined;
        }

        return tizen1_utils.validateTypeMismatch(onSuccess, onError, "resolve", _resolve);
    },

    getStorage: function (label, onSuccess, onError) {
        var storage = null, _label = String(label);

        _storages.some(function (value) {
            if (value.label === _label) {
                storage = utils.copy(value);
                setTimeout(function () {
                    onSuccess(storage);
                }, 1);
                return true;
            }
        });

        if (!storage) {
            if(onError) {
                setTimeout(function () {
                    onError(new WebAPIError(errorcode.NOT_FOUND_ERR));
                }, 1);

            } else {
                throw new WebAPIException(errorcode.NOT_FOUND_ERR);
            }
        }
    },

    listStorages: function (onSuccess, onError) {
        function _listStorages() {
            setTimeout(function () {
                onSuccess(utils.copy(_storages));
            }, 1);
        }

        return tizen1_utils.validateTypeMismatch(onSuccess, onError, "listStorages", _listStorages);
    },

    addStorageStateChangeListener: function(onSuccess, onError) {
        function _addStorageStateChangeListener() {
            var watchId = (new Date()).getTime() || 0;
                _observers[watchId] = function(storage) {//storage is which state is changed
                onSuccess(storage);
            };

            // This event should be triggered from outside
            event.on("StateChange", _observers[watchId]);
            return Number(watchId);
        }

        return tizen1_utils.validateTypeMismatch(onSuccess, onError, "addStorageStateChangeListener", _addStorageStateChangeListener);
    },

    removeStorageStateChangeListener: function (watchId) {
        if (!_observers[watchId])
            return;

        event.deleteEventHandler("StateChange", _observers[watchId]);
        delete _observers[watchId];
    },

    handleSubFeatures: function (subFeatures) {
        function setSecurity(_security) {
            return function (method) {
                _security[method] = true;
            };
        }

        for (var subFeature in subFeatures) {
            if (_security[subFeature].length === 0) {
                _security.all = true;
                return;
            }
            _security.all = false;
            utils.forEach(_security[subFeature], setSecurity);
        }
    }
};


});
define('ripple/platform/tizen/2.0/geoBackend_local', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    PendingObject = require('ripple/platform/tizen/2.0/pendingObject'),
    PendingOperation = require('ripple/platform/tizen/2.0/pendingoperation'),
    GeocodeResult = require('ripple/platform/tizen/2.0/GeocodeResult'),
    _GEO_OBJECTS = "tizen1.0-geocode-objects",
    _get, _save, _geoList_init, GeoEntry,
    _checkAddressType, _transAddressStr,
    _geocodeByString, _findCoordsByString, _geocodeByAddress,
    _reverseGeocodeBySimple, _reverseGeocodeByGeo, _checkCoordsType,
    _geoList = [],
    _PENDING_TIME = 10;

function _get() {
    var geoList = [],
        data = db.retrieveObject(_GEO_OBJECTS);

    utils.forEach(data, function (geo) {
        geoList.push(geo);
    });
    return geoList;
}

function _save() {
    db.saveObject(_GEO_OBJECTS, _geoList);
}

function _geoList_init() {
    var entry;
    _geoList = _get();

    /* Put some default data if database is empty */
    if (_geoList.length === 0) {
        entry = new GeoEntry(new lbs.StructuredAddress({
            country : "UK",
            region : "London",
            county : "Lambeth",
            city : "London",
            street : "Westminster Bridge Road",
            streetNumber : "1",
            premises : "Riverside Building",
            additionalInformation : "London Eye",
            postalCode : "SE1 7PB"
        }),
            new lbs.GeoCoordinates({
            latitude : 51.510452,
            longitude : -0.119820,
            altitude : 0,
            accuracy : 0,
            altitudeAccuracy : 0,
            heading : 0,
            speed : 0
        }));
        _geoList.push(entry);
        entry = new GeoEntry(new lbs.StructuredAddress({
            country : "UK",
            city : "London",
            street : "Baker Street",
            streetNumber : "221B",
            postalCode : "NW1 6XE"
        }),
            new lbs.GeoCoordinates({
            latitude : 51.524552,
            longitude : -0.158615,
            altitude : 0,
            accuracy : 0,
            altitudeAccuracy : 0,
            heading : 0,
            speed : 0
        }));
        _geoList.push(entry);
        entry = new GeoEntry(new lbs.StructuredAddress({
            country : "US",
            region : "OR",
            city : "Portland",
            street : "SE Water Ave",
            streetNumber : "1945",
            additionalInformation : "OMSI",
        }),
            new lbs.GeoCoordinates({
            latitude : 45.508490,
            longitude : -122.665953,
            altitude : 0,
            accuracy : 0,
            altitudeAccuracy : 0,
            heading : 0,
            speed : 0
        }));
        _geoList.push(entry);
        entry = new GeoEntry(new lbs.StructuredAddress({
            country : "US",
            region : "OR",
            city : "Portland",
            street : "NW Pittock Drive",
            streetNumber : "3229",
            additionalInformation : "Pittock Mansion",
        }),
            new lbs.GeoCoordinates({
            latitude : 45.531365,
            longitude : -122.716255,
            altitude : 0,
            accuracy : 0,
            altitudeAccuracy : 0,
            heading : 0,
            speed : 0
        }));
        _geoList.push(entry);
        entry = new GeoEntry(new lbs.StructuredAddress({
            region : "OR",
            city : "Hillsboro",
            street : "NE 25th St",
            streetNumber : "2111",
            postalCode : "97124"
        }),
            new lbs.GeoCoordinates({
            latitude : 45.543479,
            longitude : -122.9621601,
            altitude : 0,
            accuracy : 0,
            altitudeAccuracy : 0,
            heading : 0,
            speed : 0
        }));
        _geoList.push(entry);
        _save();
    }
}

function _pendingOperate(operate) {
    var pendingObj, pendingOperation, i, argumentVector = [];

    for (i = 0; i < arguments.length - 1; i++)
        argumentVector[i] = arguments[i + 1];

    pendingObj = new PendingObject();

    pendingObj.pendingID = window.setTimeout(function () {
        pendingObj.setCancelFlag(false);
        operate.apply(this, argumentVector);
    }, _PENDING_TIME);

    pendingOperation = new PendingOperation(pendingObj);

    return pendingOperation;
}

function GeoEntry(addr, coord) {
    var _self;
    _self = {
        address : addr || null,
        coordinate : coord || null
    };
    return _self;
}

function SortMode() {
    var _self;
    _self = {
        attributeName : "",
        order : "ASC"
    };
    return _self;
}

function _transAddressStr(addr) {
    var str = "";
    if (addr.additionalInformation !== null && addr.additionalInformation !== undefined)
        str = str + addr.additionalInformation + ", ";
    if (addr.premises !== null && addr.premises !== undefined)
        str = str + addr.premises + ", ";
    if (addr.streetNumber !== null && addr.streetNumber !== undefined)
        str = str + addr.streetNumber + " ";
    if (addr.street !== null && addr.street !== undefined)
        str = str + addr.street + ", ";
    if (addr.city !== null && addr.city !== undefined)
        str = str + addr.city + ", ";
    if (addr.county !== null && addr.county !== undefined)
        str = str + addr.county + ", ";
    if (addr.region !== null && addr.region !== undefined)
        str = str + addr.region + ", ";
    if (addr.country !== null && addr.country !== undefined)
        str = str + addr.country + ", ";
    if (addr.postalCode !== null && addr.postalCode !== undefined)
        str = str + addr.postalCode;

    if (str.lastIndexOf(", ") === str.length - 2)
        str = str.slice(0, -2);
    return str;
}

function _concatAddress(addr) {
    var str = "";
    if (addr.additionalInformation !== null && addr.additionalInformation !== undefined)
        str = str + addr.additionalInformation + " ";
    if (addr.premises !== null && addr.premises !== undefined)
        str = str + addr.premises + " ";
    if (addr.streetNumber !== null && addr.streetNumber !== undefined)
        str = str + addr.streetNumber + " ";
    if (addr.street !== null && addr.street !== undefined)
        str = str + addr.street + " ";
    if (addr.city !== null && addr.city !== undefined)
        str = str + addr.city + " ";
    if (addr.county !== null && addr.county !== undefined)
        str = str + addr.county + " ";
    if (addr.region !== null && addr.region !== undefined)
        str = str + addr.region + " ";
    if (addr.country !== null && addr.country !== undefined)
        str = str + addr.country + " ";
    if (addr.postalCode !== null && addr.postalCode !== undefined)
        str = str + addr.postalCode;

    return str;
}

function _findCoordsByString(address) {
    var array = [], reg, str, searchAddr, pieces, i;
    if (address.length === 0)
        return array;

    pieces = address.split(",");
    searchAddr = "";
    for (i = 0; i < pieces.length; i++) {
        searchAddr = searchAddr + pieces[i];
    }
    reg = new RegExp(searchAddr, "i");

    utils.forEach(_geoList, function (item) {
        str = _concatAddress(item.address);
        if (str.search(reg) !== -1)
            array.push(new GeocodeResult(item.coordinate.latitude, item.coordinate.longitude));
    });

    return array;
}

function _geocodeByString(address, successCB, errorCB, options) {
    var array;
    array = _findCoordsByString(address);
    successCB(array);
}

function _findCoordsByAddress(addr) {
    var array = [], select = false, i;
    for (i = 0; i < _geoList.length; i++) {
        select = false;
        if (addr.country !== null && addr.country !== undefined) {
            if (addr.country === _geoList[i].address.country)
                select = true;
            else
                continue;
        }

        if (addr.region !== null && addr.region !== undefined) {
            if (addr.region === _geoList[i].address.region)
                select = true;
            else
                continue;
        }

        if (addr.county !== null && addr.county !== undefined) {
            if (addr.county === _geoList[i].address.county)
                select = true;
            else
                continue;
        }

        if (addr.city !== null && addr.city !== undefined) {
            if (addr.city === _geoList[i].address.city)
                select = true;
            else
                continue;
        }

        if (addr.street !== null && addr.street !== undefined) {
            if (addr.street === _geoList[i].address.street)
                select = true;
            else
                continue;
        }

        if (addr.streetNumber !== null && addr.streetNumber !== undefined) {
            if (addr.streetNumber === _geoList[i].address.streetNumber)
                select = true;
            else
                continue;
        }

        if (addr.premises !== null && addr.premises !== undefined) {
            if (addr.premises === _geoList[i].address.premises)
                select = true;
            else
                continue;
        }

        if (addr.additionalInformation !== null &&
            addr.additionalInformation !== undefined) {
            if (addr.additionalInformation === _geoList[i].address.additionalInformation)
                select = true;
            else
                continue;
        }

        if (addr.postalCode !== null && addr.postalCode !== undefined) {
            if (addr.postalCode === _geoList[i].address.postalCode)
                select = true;
            else
                continue;
        }

        if (select === true) {
            array.push(new GeocodeResult(_geoList[i].coordinate.latitude, _geoList[i].coordinate.longitude));
        }
    }

    return array;
}

function _geocodeByAddress(address, successCB, errorCB, options) {
    var array;
    array = _findCoordsByAddress(address);
    successCB(array);
}

function _checkAddressType(address) {
    var str;
    if (typeof address === "string") {
        str = "string";
    } else if (typeof address === "object") {
        str = "StructuredAddress";
    } else {
        str = "typeMismatch";
    }
    return str;
}

function _checkCoordsType(coord) {
    var str;
    /* SimpleCoordinates is a subset of GeoCoordinates.
       SimpleCoordinates includes latitude, longitude as mandatory fields only.
       GeoCoordinates not only includes latitude, longitude as mandatory fields
       but also at least includes one more other optional fields */
    if (typeof coord !== "object") {
        str = "typeMismatch";
    } else if (typeof coord.latitude === "number" &&
                typeof coord.longitude === "number") {
        str = "simpleCoordinates";
        if (typeof coord.altitude === "number" ||
            typeof coord.accuracy === "number" ||
            typeof coord.altitudeAccuracy === "number" ||
            typeof coord.heading === "number" ||
            typeof coord.speed === "number") {
            str = "geoCoordinates";
        }
    } else {
        str = "typeMismatch";
    }

    return str;
}

function _findReverseGeocode(coords, options) {
    var array = [], _isStructured = false, i;
    if (options !== null && options !== undefined) {
        if (options.resultType === "STRUCTURED") {
            _isStructured = true;
        }
    }
    for (i = 0; i < _geoList.length; i++) {
        if (_geoList[i].coordinate.latitude === coords.latitude &&
            _geoList[i].coordinate.longitude === coords.longitude) {
            if (coords.altitude) {
                if (_geoList[i].coordinate.altitude !== coords.altitude)
                    continue;
            }
            if (coords.accuracy) {
                if (_geoList[i].coordinate.accuracy !== coords.accuracy)
                    continue;
            }
            if (coords.altitudeAccuracy) {
                if (_geoList[i].coordinate.altitudeAccuracy !== coords.altitudeAccuracy)
                    continue;
            }
            if (coords.heading) {
                if (_geoList[i].coordinate.heading !== coords.heading)
                    continue;
            }
            if (coords.speed) {
                if (_geoList[i].coordinate.speed !== coords.speed)
                    continue;
            }

            if (_isStructured === true) {
                array.push(new lbs.StructuredAddress(_geoList[i].address));
            } else {
                array.push(_transAddressStr(_geoList[i].address));
            }
        }
    }
    return array;
}

function _reverseGeocodeByGeo(coordinates, successCB, errorCB, options) {
    var array, coord;
    coord = new lbs.GeoCoordinates(coordinates);
    array = _findReverseGeocode(coord, options);
    return successCB(array);
}

function _reverseGeocodeBySimple(coordinates, successCB, errorCB, options) {
    var array, coord;
    coord = new lbs.GeoCoordinates({
            latitude : coordinates.latitude,
            longitude : coordinates.longitude
        });
    array = _findReverseGeocode(coord, options);
    return successCB(array);
}

module.exports = function (prop) {
    var _self = new lbs.LocationServiceProvider(prop);
    _geoList_init();

    _self.geocode = function (address, successCB, errorCB, options) {
        function _geocode() {
            var ret;

            ret = _pendingOperate(function () {
                /* address: its type is AbstractAddress.
                   It could be StructuredAddress or String */
                if (_checkAddressType(address) === "string") {
                    _geocodeByString(address, successCB, errorCB, options);
                } else if (_checkAddressType(address) === "StructuredAddress") {
                    _geocodeByAddress(address, successCB, errorCB, options);
                } else {
                    throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
                }
            });
        }

        tizen1_utils.validateTypeMismatch(successCB, errorCB, "geocode", _geocode);
    };

    _self.reverseGeocode = function (coordinates, successCB, errorCB, options) {
        function _reverseGeocode() {
            var ret;

            ret = _pendingOperate(function () {
                /* coordinates: Its type is AbstractCoordinates.
                   It could be SimpleCoordinates or GeoCoordinates */
                if (_checkCoordsType(coordinates) === "simpleCoordinates") {
                    _reverseGeocodeBySimple(coordinates, successCB, errorCB, options);
                } else if (_checkCoordsType(coordinates) === "geoCoordinates") {
                    _reverseGeocodeByGeo(coordinates, successCB, errorCB, options);
                } else {
                    throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
                }
            });
        }

        tizen1_utils.validateTypeMismatch(successCB, errorCB, "reverseGeocode", _reverseGeocode);
    };

    return _self;
};


});
define('ripple/platform/tizen/2.0/geoBackend_nominatim', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    GeocodeResult = require('ripple/platform/tizen/2.0/GeocodeResult');

function _concatAddrString(addr) {
    var ret = "", i, pieces;
    if (typeof addr === "string") {
        pieces = addr.split(" ");
        for (i = 0; i < pieces.length; i++) {
            ret = ret + pieces[i] + "+";
        }
    } else if (typeof addr === "object") {
        if (addr.premises !== null && addr.premises !== undefined) {
            ret = ret + addr.premises + "+";
        }
        if (addr.streetNumber !== null && addr.streetNumber !== undefined) {
            ret = ret + addr.streetNumber + "+";
        }
        if (addr.street !== null && addr.street !== undefined) {
            ret = ret + addr.street + "+";
        }
        if (addr.city !== null && addr.city !== undefined) {
            ret = ret + addr.city + "+";
        }
        if (addr.county !== null && addr.county !== undefined) {
            ret = ret + addr.county + "+";
        }
        if (addr.region !== null && addr.region !== undefined) {
            ret = ret + addr.region + "+";
        }
        if (addr.postalCode !== null && addr.postalCode !== undefined) {
            ret = ret + addr.postalCode + "+";
        }
        if (addr.country !== null && addr.country !== undefined) {
            ret = ret + addr.country + "+";
        }
    } else {
        return undefined;
    }
    ret = ret.slice(0, -1);
    return ret;
}

module.exports = function (prop) {
    var _self = new lbs.LocationServiceProvider(prop);

    _self.geocode = function (address, successCB, errorCB, options) {
        function _geocode() {
            var i, searchStr, coordinates = [], result;

            searchStr = _concatAddrString(address);
            if (searchStr === undefined) {
                throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
            }
            searchStr = "http://nominatim.openstreetmap.org/search?q=" + searchStr + "&format=json&polygon=1&addressdetails=1";

            /* use nominatim online geo service. (http://nominatim.openstreetmap.org) */
            $.getJSON(searchStr, function (data) {
                for (i = 0; i < data.length; i++) {
                    result = new GeocodeResult(parseFloat(data[i].lat), parseFloat(data[i].lon));
                    coordinates.push(result);
                }
                successCB(coordinates);
            }).error(function () {
                if (errorCB) {
                    setTimeout(function () {
                        errorCB(new WebAPIError(errorcode.NETWORK_ERR));
                    }, 1);
                }
            });
        }

        tizen1_utils.validateTypeMismatch(successCB, errorCB, "geocode", _geocode);
    };

    _self.reverseGeocode = function (coordinates, successCB, errorCB, options) {
        function _reverseGeocode() {
            var searchStr = "";
            if (typeof coordinates !== "object" ||
                typeof coordinates.latitude !== "number" ||
                typeof coordinates.longitude !== "number") {
                throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
            }
            searchStr = "http://nominatim.openstreetmap.org/reverse?format=json&lat=" +
                        coordinates.latitude + "&lon=" + coordinates.longitude + "&zoom=18&addressdetails=1";

            /* use nominatim online geo service. (http://nominatim.openstreetmap.org) */
            $.getJSON(searchStr, function (data) {
                var addr;

                if (options && options.resultType === "STRUCTURED") {
                    addr = new lbs.StructuredAddress({
                        country : data.address.country,
                        region : data.address.state,
                        county : data.address.county,
                        city : data.address.city,
                        street : data.address.road,
                        streetNumber : data.address.streetNumber,
                        postalCode : data.address.postcode
                    });
                } else {
                    addr = data.display_name;
                }
                successCB([addr]);
            }).error(function () {
                if (errorCB) {
                    setTimeout(function () {
                        errorCB(new WebAPIError(errorcode.NETWORK_ERR));
                    }, 1);
                }
            });
        }

        tizen1_utils.validateTypeMismatch(successCB, errorCB, "reverseGeocode", _reverseGeocode);
    };

    return _self;
};


});
define('ripple/platform/tizen/2.0/geocoder', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
    ProviderLocal = require('ripple/platform/tizen/2.0/geoBackend_local'),
    ProviderNominatim = require('ripple/platform/tizen/2.0/geoBackend_nominatim'), // Nominatim geocode service
    _getProviders,
    _providers,
    _self;

function _initialize() {
    _providers = [new ProviderNominatim({name : "Nominatim", connectivity : "ONLINE"})
                  /* ,new ProviderLocal({name : "Tizen Database", connectivity : "OFFLINE"}) */];
}

_initialize();

_self = {
    getDefaultProvider : function () {
        return _providers[0];
    },
    getProviders : function () {
        return _providers;
    }
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/lbs_utils', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    _self;

function CoordinateProperties(prop) {
    var _self;
    _self = {
        latitude : prop.latitude || 0,
        longitude : prop.longitude || 0,
        altitude : prop.altitude || 0,
        accuracy : prop.accuracy || 0,
        altitudeAccuracy : prop.altitudeAccuracy || 0,
        heading : prop.heading || 0,
        speed : prop.speed || 0
    };
    return _self;
}

function _checkAddressProperties(p, dst) {
    if (p.country !== null && p.country !== undefined)
        dst.country = String(p.country);
    if (p.region !== null && p.region !== undefined)
        dst.region = String(p.region);
    if (p.county !== null && p.county !== undefined)
        dst.county = String(p.county);
    if (p.city !== null && p.city !== undefined)
        dst.city = String(p.city);
    if (p.street !== null && p.street !== undefined)
        dst.street = String(p.street);
    if (p.streetNumber !== null && p.streetNumber !== undefined)
        dst.streetNumber = String(p.streetNumber);
    if (p.premises !== null && p.premises !== undefined)
        dst.premises = String(p.premises);
    if (p.additionalInformation !== null &&
        p.additionalInformation !== undefined)
        dst.additionalInformation = String(p.additionalInformation);
    if (p.postalCode !== null && p.postalCode !== undefined)
        dst.postalCode = String(p.postalCode);
}

function AddressProperties(prop) {
    var _self;
    _self = {
        country : null,
        region : null,
        county : null,
        city : null,
        street : null,
        streetNumber : null,
        premises : null,
        additionalInformation : null,
        postalCode : null
    };
    if (prop) {
        if (_checkAddressProperties(prop, _self) === false)
            return undefined;
    }
    return _self;
}

_self = {
    LocationServiceProvider : function (prop) {
        var _self;
        _self = {
            name : "",
            metaData : Object,
            attribution : "",
            supportedOptions : [],
            setOptions : function (options, successCB, errorCB) {},
            connectivity : "" // "ONLINE" "OFFLINE" "HYBRID"
        };

        if (prop.name !== null && prop.name !== undefined)
            _self.name = String(prop.name);
        if (prop.metaData !== null && prop.metaData !== undefined)
            _self.metaData = prop.metaData;

        if (prop.attribution !== null && prop.attribution !== undefined)
            _self.attribution = String(prop.attribution);

        if (prop.supportedOptions !== null && prop.supportedOptions !== undefined)
            _self.supportedOptions = [prop.supportedOptions];

        if (prop.setOptions !== null && prop.setOptions !== undefined)
            _self.setOptions = prop.setOptions;

        if (prop.connectivity !== null && prop.connectivity !== undefined)
            _self.connectivity = String(prop.connectivity);

        return _self;
    },

    GeoCoordinates : function (prop) {
        var _self = new CoordinateProperties(prop);
        if (tizen1_utils.isEmptyObject(_self)) {
            return undefined;
        }

        return _self;
    },

    StructuredAddress : function (prop) {
        var _self;
        _self = new AddressProperties(prop);
        if (tizen1_utils.isEmptyObject(_self)) {
            return undefined;
        }

        return _self;
    }
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/map', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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 lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
    mapProviders = [],
    MapStyle,
    MapProvider,
    _self;

function _initialize() {
    // EPSG:3857 is a Spherical Mercator projection coordinate system popularized by web services such as Google and later OpenStreetMap
    // mapStyles are from http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
    var projection = "EPSG:3857",
        mapStyle1 = new MapStyle("Mapnik", "http://b.tile.openstreetmap.org/${z}/${x}/${y}.png"),
        mapStyle2 = new MapStyle("Cycle", "http://b.tile.opencyclemap.org/cycle/${z}/${x}/${y}.png");

    mapProviders = [new MapProvider({name: "OpenStreetMap", connectivity: "ONLINE"}, projection, [mapStyle1, mapStyle2])];
}

_self = {
    getDefaultProvider: function () {
        return mapProviders[0];
    },
    getProviders: function () {
        return mapProviders;
    }
};

MapStyle = function (name, url) {
    return {
        name: name,
        url: url
    };
};

MapProvider = function (prop, projection, mapStyles) {
    var mapProvider = new lbs.LocationServiceProvider(prop);

    mapProvider.__defineGetter__("projection", function () {
        return projection;
    });

    mapProvider.__defineGetter__("mapStyles", function () {
        return mapStyles;
    });

    return mapProvider;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/messaging', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 _self,
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    MessagingService = require('ripple/platform/tizen/2.0/MessagingService'),
    t = require('ripple/platform/tizen/2.0/typedef'),
    TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
    TIZEN_MESSAGING_SMS = "messaging.sms",
    TIZEN_MESSAGING_MMS = "messaging.mms",
    TIZEN_MESSAGING_EMAIL = "messaging.email",
    _security_check = {read: false, write: false},
    _sms_service = null,
    _mms_service = null,
    _email_service = null;

_self = function () {
    this.getMessageServices = function (messageServiceType, onSuccess, onError) {
        var service;

        if (!(new TypeCoerce(t.MessageServiceTag)).match(messageServiceType)) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        if (!(new TypeCoerce(t.MessageServiceArraySuccessCallback)).match(onSuccess)) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        if (onError && !(new TypeCoerce(t.ErrorCallback)).match(onError)) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }

        switch (messageServiceType) {
        case "messaging.sms":
            if (_sms_service === null) {
                _sms_service = [new MessagingService("Tizen SMS Service 1", TIZEN_MESSAGING_SMS, _security_check), new MessagingService("Tizen SMS Service 2", TIZEN_MESSAGING_SMS, _security_check)];
            }
            service = _sms_service;
            break;
        case "messaging.mms":
            if (_mms_service === null) {
                _mms_service = [new MessagingService("Tizen MMS Service", TIZEN_MESSAGING_MMS, _security_check)];
            }
            service = _mms_service;
            break;
        case "messaging.email":
            if (_email_service === null) {
                _email_service = [new MessagingService("Tizen Email Service", TIZEN_MESSAGING_EMAIL, _security_check)];
            }
            service = _email_service;
            break;
        default:
            throw (new WebAPIException(errorcode.INVALID_VALUES_ERR));
        }
        setTimeout(function () {
            onSuccess(service);
        }, 1);
    };
    this.handleSubFeatures = function (subFeatures) {
        if (subFeatures.hasOwnProperty('http://tizen.org/privilege/messaging.read')) {
            _security_check.read = true;
        }
        if (subFeatures.hasOwnProperty('http://tizen.org/privilege/messaging.write')) {
            _security_check.write = true;
        }
    };
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/msg_utils', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    MessageBody = require('ripple/platform/tizen/2.0/MessageBody'),
    _TIZEN_MESSAGE_DB_KEY = "tizen_db_messages",
    MessageElement = function (_type, _id) {
        return {
            type: _type,
            id: _id,
            msg: {},
            conv: {}
        };
    },

    _conversationCount = function (msg, cid, rst) {
        var old_time = new Date(0), t;

        utils.forEach(msg.msg, function (o) {
            if (o.priv.conversationId === cid &&
                o.priv.messageStatus !== "DRAFT") {
                rst.cnt += 1;
                t = new Date(o.priv.timestamp);
                if (t > old_time) {
                    rst.lastid = o.priv.id;
                    old_time = t;
                }
                if (o.isRead === false) {
                    rst.unread++;
                }
            }
        });
    },

    _updateConversation = function (msg, cid) {
        var privConv = {}, lastm, rst = {};

        rst.cnt = 0;
        rst.unread = 0;
        rst.lastid = "";
        _conversationCount(msg, cid, rst);
        if (rst.cnt === 0) {
            if (msg.conv[cid] !== undefined) {
                delete msg.conv[cid];
            }
            return;
        }
        lastm = msg.msg[rst.lastid];

        privConv.id = cid;
        privConv.type = msg.type;
        privConv.timestamp = new Date(lastm.priv.timestamp);
        privConv.messageCount = rst.cnt;
        privConv.unreadMessages = rst.unread;
        privConv.preview = lastm.body.plainBody;
        privConv.subject = lastm.subject;
        privConv.isRead = lastm.isRead;
        privConv.from = lastm.priv.from;
        privConv.to = lastm.to.slice(0);
        privConv.cc = lastm.cc.slice(0);
        privConv.bcc = lastm.bcc.slice(0);
        privConv.lastMessageId = rst.lastid;
        msg.conv[cid] = privConv;
    };

module.exports = {
    conversationCount: _conversationCount,
    setMsg: function (m, newm) {
        if ((m.to === null) || (m.to === undefined)) {
            newm.to = [];
        } else {
            if (tizen1_utils.isValidArray(m.to)) {
                newm.to = m.to.slice(0);
            } else {
                return false;
            }
        }

        if ((m.cc === null) || (m.cc === undefined)) {
            newm.cc = [];
        } else {
            if (tizen1_utils.isValidArray(m.cc)) {
                newm.cc = m.cc.slice(0);
            } else {
                return false;
            }
        }

        if ((m.bcc === null) || (m.bcc === undefined)) {
            newm.bcc = [];
        } else {
            if (tizen1_utils.isValidArray(m.bcc)) {
                newm.bcc = m.bcc.slice(0);
            } else {
                return false;
            }
        }

        if ((m.body === null) || (m.body === undefined)) {
            if (m.htmlBody === null || m.htmlBody === undefined) {
                m.htmlBody = "";
            }
            if (m.plainBody === null || m.plainBody === undefined) {
                m.plainBody = "";
            }
            if (typeof m.plainBody !== 'string' || typeof m.htmlBody !== 'string') {
                return false;
            }
            m.body = new MessageBody(null, true, m.plainBody, m.htmlBody, []);
        } else {
            if (typeof m.body.plainBody !== 'string' || typeof m.body.htmlBody !== 'string') {
                return false;
            }
            m.body = new MessageBody(null, true, m.body.plainBody, m.body.htmlBody, []);
        }
        newm.body = utils.copy(m.body);

        if (typeof m.isRead === 'boolean') {
            newm.isRead = m.isRead;
        } else {
            newm.isRead = false;
        }

        if (typeof m.isHighPriority === 'boolean') {
            newm.isHighPriority = m.isHighPriority;
        } else {
            newm.isHighPriority = false;
        }

        if ((m.subject === null) || (m.subject === undefined)) {
            newm.subject = "";
        } else {
            newm.subject = String(m.subject);
        }

        if ((m.inResponseTo === null) || (m.inResponseTo === undefined)) {
            newm.inResponseTo = null;
        } else {
            newm.inResponseTo = String(m.inResponseTo);
        }

        if ((m.attachments === null) || (m.attachments === undefined)) {
            newm.attachments = [];
        } else {
            newm.attachments = utils.copy(m.attachments);
        }
        return true;
    },

    loadMsg: function (type, id) {
        var i, ret, msg = db.retrieveObject(_TIZEN_MESSAGE_DB_KEY) || null;
        if (msg === null) {
            ret = new MessageElement(type, id);
        } else {
            for (i = 0; i < msg.length; i++) {
                if (msg[i].type === type && msg[i].id === id) {
                    ret = msg[i];
                    break;
                }
            }
            if (ret === undefined) {
                ret = new MessageElement(type, id);
            } else {
                /* after getting Date out of DB, Date will become
                   a string, so need to recast it back to Date */
                for (i in ret.msg) {
                    ret.msg[i].priv.timestamp = new Date(ret.msg[i].priv.timestamp);
                }
            }
        }
        return ret;
    },

    delMsg: function (m) { // m is a PrivMessage
        var i, _msg = db.retrieveObject(_TIZEN_MESSAGE_DB_KEY) || [];
        if (_msg.length === 0) {
            return;
        } else {
            for (i = 0; i < _msg.length; i++) {
                if (_msg[i].type === m.priv.type && _msg[i].id === m.priv.serviceId) {
                    delete _msg[i].msg[m.priv.id];
                    if (m.priv.messageStatus !== "DRAFT") {
                        _updateConversation(_msg[i], m.priv.conversationId);
                    }
                    db.saveObject(_TIZEN_MESSAGE_DB_KEY, _msg);
                    return;
                }
            }
        }
    },

    saveMsg: function (m) { // m is a PrivMessage
        var i, new_msg, _msg = db.retrieveObject(_TIZEN_MESSAGE_DB_KEY) || [];
        if (_msg.length === 0) {
            _msg = new MessageElement(m.priv.type, m.priv.serviceId);
            _msg.msg[m.priv.id] = m;
            if (m.priv.messageStatus !== "DRAFT") {
                _updateConversation(_msg, m.priv.conversationId);
            }
            db.saveObject(_TIZEN_MESSAGE_DB_KEY, [_msg]);
        } else {
            for (i = 0; i < _msg.length; i++) {
                if (_msg[i].type === m.priv.type && _msg[i].id === m.priv.serviceId) {
                    _msg[i].msg[m.priv.id] = m;
                    if (m.priv.messageStatus !== "DRAFT") {
                        _updateConversation(_msg[i], m.priv.conversationId);
                    }
                    db.saveObject(_TIZEN_MESSAGE_DB_KEY, _msg);
                    break;
                }
            }
            if (i === _msg.length) {
                new_msg = new MessageElement(m.priv.type, m.priv.serviceId);
                new_msg.msg[m.priv.id] = m;
                if (m.priv.messageStatus !== "DRAFT") {
                    _updateConversation(new_msg, m.priv.conversationId);
                }
                _msg.push(new_msg);
                db.saveObject(_TIZEN_MESSAGE_DB_KEY, _msg);
            }
        }
    },

    loadConv: function (type, id) {
        var i, ret;
        ret = this.loadMsg(type, id).conv;
        for (i in ret) {
            ret[i].timestamp = new Date(ret[i].timestamp);
        }
        return ret;
    }
};

});
define('ripple/platform/tizen/2.0/navigator', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *  Copyright 2012 Intel Corporation.
 *
 * 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 _original = window.navigator,
    utils = require('ripple/utils'),
    devices = require('ripple/devices'),
    constants = require('ripple/constants'),
    vibration = require('ripple/platform/tizen/2.0/vibration'),
    _self = {};

(function () {
    var key,
        nav = window.navigator;

    function _handle(obj, key) {
        return typeof obj[key] !== "function" ? obj[key] : function () {
            return obj[key].apply(obj, Array.prototype.slice.call(arguments));
        };
    }

    for (key in nav) {
        _self[key] = _handle(nav, key);
    }
}());

_self.__defineGetter__('userAgent', function () {
    var currentUserAgent = devices.getCurrentDevice().userAgent;

    return currentUserAgent === constants.COMMON.USER_AGENT_DEFAULT ?
        _original.userAgent : currentUserAgent;
});

_self.__defineGetter__('vibrate', function () {
    return vibration.vibrate;
});

module.exports = _self;

});
define('ripple/platform/tizen/2.0/networkbearerselection', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
    _security = {
        "http://tizen.org/privilege/networkbearerselection":
            ["requestRouteToHost", "releaseRouteToHost"]
    },
    _self;

_self = function () {
    var networkBearerSelection;

    function requestRouteToHost(networkType, domainName, successCallback, errorCallback) {
        var evNetworkOpened       = "NO_" + networkType + "_" + domainName,
            evNetworkDisconnected = "ND_" + networkType + "_" + domainName;

        if (!_security.requestRouteToHost) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NetworkBearerSelection("requestRouteToHost", arguments);
        
        if (!domainName) {
            if (errorCallback) {
                errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
            }
            return;
        }

        event.once(evNetworkOpened, function (isOpened) {
            if (!isOpened)
                return;

            successCallback.onsuccess();
        });
        event.once(evNetworkDisconnected, successCallback.ondisconnected);
        event.trigger("NetworkRequest", [networkType, domainName]);
    }

    function releaseRouteToHost(networkType, domainName, successCallback, errorCallback) {
        var evNetworkDisconnected = "ND_" + networkType + "_" + domainName;

        if (!_security.releaseRouteToHost) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NetworkBearerSelection("releaseRouteToHost", arguments);
       
        if (!domainName) {
            if (errorCallback) {
                errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
            }
            return;
        }

        event.once(evNetworkDisconnected, successCallback);
        event.trigger("NetworkRelease", [networkType, domainName]);
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    networkBearerSelection = {
        requestRouteToHost: requestRouteToHost,
        releaseRouteToHost: releaseRouteToHost,
        handleSubFeatures:  handleSubFeatures
    };

    return networkBearerSelection;
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/nfc', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 db = require('ripple/db'),
    event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    NDEFRecord = require('ripple/platform/tizen/2.0/NDEFRecord'),
    NDEFMessage = require('ripple/platform/tizen/2.0/NDEFMessage'),
    NFCAdapter,
    NFCAdapterPrototype,
    NFCTag,
    NFCPeer,
    _data = {
        DB_NFC_TAG: "tizen1.0-nfc-tag",
        DB_NFC_PEER: "tizen1.0-nfc-peer",
        DB_NFC_OUTPUT_MESSAGE: "tizen1.0-nfc-output-message",
        INTERVAL: 1000,
        listener: {
            onCardEmulationChanged: null,
            onTagDetected: null,
            onPeerDetected: null,
            onNDEFReceived: null
        },
        pairedNFC: null,
        nfcAdapter: {},
        nfcCardEmulation: {},
        nfcTags: [],
        nfcTag: {},
        nfcPeer: null,
        isNear: false,      // Identify the device is whether near
        isDetectTag: false, // Identify NFC tag is detected
        isPeerConnected: false,
        connectedState: false
    },
    _security = {
        "http://tizen.org/privilege/nfc.admin": ["setPowered"],
        "http://tizen.org/privilege/nfc.common": ["getDefaultAdapter",
                "setExclusiveMode", "getCachedMessage"],
        "http://tizen.org/privilege/nfc.p2p": ["setPeerListener",
                "unsetPeerListener", "setReceiveNDEFListener",
                "unsetReceiveNDEFListener", "sendNDEF"],
        "http://tizen.org/privilege/nfc.tag": ["setTagListener",
                "unsetTagListener", "readNDEF", "writeNDEF", "transceive"]
    },
    _self;

_self = function () {
    var nfc, _exclusiveMode = false;

    function getDefaultAdapter() {
        if (!_security.getDefaultAdapter) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCManager("getDefaultAdapter", arguments);

        if (!_data.nfcAdapter) {
            throw new WebAPIException(errorcode.UNKNOWN_ERR);
        }

        return _data.nfcAdapter;
    }

    /* API Description:
     *   If it gets priority and it is in foreground, system doesn't
     *   send app controls that are usually sent when detecting NFC Tag
     *   or receiving NDEF Message from the connected NFC peer-to-peer target
     *
     * Implementation detail:
     *   due to simulator only support single running instance and doesn't have
     *   other app controls which be called by design. we just put some system
     *   exclusive mode info on the 'System Summary' panel
     */
    function setExclusiveMode(mode) {
        if (!_security.setExclusiveMode) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCManager("setExclusiveMode", arguments);

        _exclusiveMode = mode;
        jQuery("#NFCExclusiveModeValue").text(_exclusiveMode);
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    nfc = {
        getDefaultAdapter: getDefaultAdapter,
        setExclusiveMode:  setExclusiveMode,
        handleSubFeatures: handleSubFeatures
    };

    nfc.__defineGetter__("NFC_RECORD_TNF_EMPTY", function () {
        return 0;
    });

    nfc.__defineGetter__("NFC_RECORD_TNF_WELL_KNOWN", function () {
        return 1;
    });

    nfc.__defineGetter__("NFC_RECORD_TNF_MIME_MEDIA", function () {
        return 2;
    });

    nfc.__defineGetter__("NFC_RECORD_TNF_URI", function () {
        return 3;
    });

    nfc.__defineGetter__("NFC_RECORD_TNF_EXTERNAL_RTD", function () {
        return 4;
    });

    nfc.__defineGetter__("NFC_RECORD_TNF_UNKNOWN", function () {
        return 5;
    });

    nfc.__defineGetter__("NFC_RECORD_TNF_UNCHANGED", function () {
        return 6;
    });

    return nfc;
};

NFCAdapterPrototype = function () {
    var nfcAdapterPrototype,
        interval,
        powered = false, // Identify the device on or off
        polling = false; // Identify the device is polled

    event.trigger("nfc-power-changed", [powered]);
    event.on("nfc-power-setting", function (status) {
        updatePowerStatus(status);
    });
    event.on("nfc-attach-setting", function (type, isAttached) {
        var isDetectTag;

        isDetectTag = (type === "Tag");
        updateIsNear(isDetectTag, isAttached);
    });
    event.on("nfc-tag-send", function (status) {
        var tag;

        if (status) {
            tag = db.retrieveObject(_data.DB_NFC_TAG);
            if (tag.isSupportedNDEF) {
                _data.nfcTag = new NFCTag(tag.type, tag.isSupportedNDEF,
                        tag.ndefSize, null, true, tag.ndefs);
            } else {
                _data.nfcTag = new NFCTag(tag.type, tag.isSupportedNDEF,
                        tag.ndefSize, null, true, tag.rawData);
            }
            if (_data.listener.onTagDetected) {
                _data.listener.onTagDetected.onattach(_data.nfcTag);
            }
        } else {
            tag = {};
            if (_data.listener.onTagDetected) {
                _data.listener.onTagDetected.ondetach();
            }
        }
    });
    event.on("nfc-peer-send", function (status) {
        if (status) {
            if (!_data.nfcPeer) {
                _data.nfcPeer = new NFCPeer(true);
            }
            _data.isPeerConnected = true;
            if (_data.listener.onPeerDetected) {
                _data.listener.onPeerDetected.onattach(_data.nfcPeer);
            }
        } else {
            _data.isPeerConnected = false;
            if (_data.listener.onPeerDetected) {
                _data.listener.onPeerDetected.ondetach();
            }
        }
    });
    event.on("nfc-peer-sending-ndef", function () {
        var peer, _records = [], rec, _ndef, i;

        if (_data.isPeerConnected) {
            peer = db.retrieveObject(_data.DB_NFC_PEER);
            for (i in peer.ndef.records) {
                rec = peer.ndef.records[i];
                _records.push(new NDEFRecord(rec.tnf, rec.type, rec.payload,
                        rec.id));
            }
            _ndef = new NDEFMessage(_records);
            if (_data.listener.onNDEFReceived) {
                _data.listener.onNDEFReceived(_ndef);
            }
        }
    });

    // private
    function updatePowerStatus(status) {
        if (powered === status) {
            return;
        }
        if (!status) {
            updateIsNear(_data.isDetectTag, false);
            if (_data.listener.onTagDetected) {
                _data.listener.onTagDetected.ondetach();
            }

            if (_data.listener.onPeerDetected) {
                _data.listener.onPeerDetected.ondetach();
            }
        }
        powered = status;
        updatePollingStatus(status);

        event.trigger("nfc-power-changed", [powered]);
    }

    function updatePollingStatus(status) {
        if (!powered)
            return;
        if (polling === status) {
            return;
        }
        polling = status;
        event.trigger("nfc-polling-changed", [polling]);
        if (polling) {
            interval = setInterval(poll, _data.INTERVAL);
        } else {
            clearInterval(interval);
        }
    }

    function updateIsNear(isDetectTag, isAttached) {
        _data.isDetectTag = isDetectTag;
        _data.isNear = isAttached;
        if (!_data.isNear) {
            _data.connectedState = false;
            event.trigger("nfc-connectedState-changed", [false]);
        }
    }

    function poll() {
        if (!_data.isNear) {
            return;
        }
        if (!_data.connectedState) {
            _data.connectedState = true;
            event.trigger("nfc-connectedState-changed", [true]);
        }
    }

    // public
    // Turns NFC adapter on or off.
    function setPowered(state, successCallback, errorCallback) {
        if (!_security.setPowered) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCAdapter("setPowered", arguments);

        window.setTimeout(function () {
            updatePowerStatus(state);
            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    // Registers a callback function to invoke when NFC tag is detected.
    function setTagListener(detectCallback, tagFilter) {
        if (!_security.setTagListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCAdapter("setTagListener", arguments);

        //TODO: tagFilter support
        _data.listener.onTagDetected = detectCallback;
    }

    // Registers a callback function to be invoked when NFC peer-to-peer target is detected.
    function setPeerListener(detectCallback) {
        if (!_security.setPeerListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCAdapter("setPeerListener", arguments);

        _data.listener.onPeerDetected = detectCallback;
    }

    // Unregisters the listener for detecting an NFC tag.
    function unsetTagListener() {
        if (!_security.unsetTagListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        if (!_data.listener.onTagDetected) {
            return;
        }

        _data.listener.onTagDetected = null;
    }

    // Unregisters the listener for detecting an NFC peer-to-peer target.
    function unsetPeerListener() {
        if (!_security.unsetPeerListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        if (!_data.listener.onPeerDetected) {
            return;
        }

        _data.listener.onPeerDetected = null;
    }

    // Gets NDEF message cached when the tag is detected.
    function getCachedMessage() {
        if (!_security.getCachedMessage) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCAdapter("getCachedMessage", arguments);

        return _data.pairedNFC || new NDEFMessage([]);
    }

    nfcAdapterPrototype = {
        setPowered:        setPowered,
        setTagListener:    setTagListener,
        setPeerListener:   setPeerListener,
        unsetTagListener:  unsetTagListener,
        unsetPeerListener: unsetPeerListener,
        getCachedMessage:  getCachedMessage
    };

    nfcAdapterPrototype.__defineGetter__("powered", function () {
        return powered;
    });

    return nfcAdapterPrototype;
};

NFCAdapter = function () {
    this.__defineGetter__("powered", function () {
        return this.__proto__.powered;
    });
};

NFCAdapter.prototype = new NFCAdapterPrototype();

NFCTag = function (type, isSupportedNDEF, ndefSize, properties, isConnected, ndefs) {
    var nfcTag, i, j, _ndefs, rec, _records, _ndefs_index = 0;

    type = type || null;
    isSupportedNDEF = isSupportedNDEF || false;
    ndefSize = ndefSize || 1;
    properties = null;
    isConnected = isConnected || false;

    _ndefs = [];
    for (i in ndefs) {
        _records = [];
        for (j in ndefs[i].records) {
            rec = ndefs[i].records[j];
            _records.push(new NDEFRecord(rec.tnf, rec.type, rec.payload,
                    rec.id));
        }
        _ndefs.push(new NDEFMessage(_records));
    }

    // Reads NDEF data.
    function readNDEF(readCallback, errorCallback) {
        if (!_security.readNDEF) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCTag("readNDEF", arguments);

        window.setTimeout(function () {
            if (!_data.isNear || !isSupportedNDEF ||
                    (_ndefs_index >= ndefSize)) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
                }
                return;
            }
            _data.pairedNFC = _ndefs[_ndefs_index];
            readCallback(_ndefs[_ndefs_index]);
            _ndefs_index++;
        }, 1);
    }

    // Writes NDEF data.
    function writeNDEF(ndefMessage, successCallback, errorCallback) {
        if (!_security.writeNDEF) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCTag("writeNDEF", arguments, true);

        window.setTimeout(function () {
            if (!_data.isNear || !isSupportedNDEF) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
                }
                return;
            }
            db.saveObject(_data.DB_NFC_OUTPUT_MESSAGE, ndefMessage);
            event.trigger("nfc-output-msg", []);
            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    // Access the raw format card.
    function transceive(data, dataCallback, errorCallback) {
        if (!_security.transceive) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCTag("transceive", arguments, true);

        window.setTimeout(function () {
            if (!_data.isNear || isSupportedNDEF) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
                }
                return;
            }
            db.saveObject(_data.DB_NFC_OUTPUT_MESSAGE, data);
            event.trigger("nfc-output-msg", []);
            dataCallback(ndefs);
        }, 1);
    }

    // Formats the detected tag that can store NDEF messages.
    /*
    function formatNDEF(successCallback, errorCallback, key) {

        tizen1_utils.validateCallbackType(successCallback, errorCallback);

        if (key) {
            tizen1_utils.validateArgumentType(key, "array",
                new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
        }

        if (!isConnected || !isSupportedNDEF) {
            if (errorCallback) {
                errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
            }
            return;
        }

        successCallback();
    }
    */

    nfcTag = {
        readNDEF:   readNDEF,
        writeNDEF:  writeNDEF,
        transceive: transceive
        //formatNDEF: formatNDEF
    };

    nfcTag.__defineGetter__("type", function () {
        return type;
    });

    nfcTag.__defineGetter__("isSupportedNDEF", function () {
        return isSupportedNDEF;
    });

    nfcTag.__defineGetter__("ndefSize", function () {
        return ndefSize;
    });

    nfcTag.__defineGetter__("properties", function () {
        return properties;
    });

    nfcTag.__defineGetter__("isConnected", function () {
        return _data.isNear;
    });

    return nfcTag;
};

NFCPeer = function (isConnected) {
    var nfcPeer;

    isConnected = isConnected || false;

    // Registers a callback function to be invoked when NDEF message is received from NFC peer-to-peer target connected.
    function setReceiveNDEFListener(successCallback) {
        if (!_security.setReceiveNDEFListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCPeer("setReceiveNDEFListener", arguments);

        if (!_data.isPeerConnected) {
            return;
        }
        _data.listener.onNDEFReceived = successCallback;
    }

    // Unregisters the listener for receiving NDEFMessage from NFC peer-to-peer target connected.
    function unsetReceiveNDEFListener() {
        if (!_security.unsetReceiveNDEFListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        _data.listener.onNDEFReceived = null;
    }

    // Sends data to NFC peer-to-peer target.
    function sendNDEF(ndefMessage, successCallback, errorCallback) {
        if (!_security.sendNDEF) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NFCPeer("sendNDEF", arguments, true);

        window.setTimeout(function () {
            if (!_data.isPeerConnected) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
                }
                return;
            }

            db.saveObject(_data.DB_NFC_OUTPUT_MESSAGE, ndefMessage);
            event.trigger("nfc-output-msg", []);
            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    nfcPeer = {
        setReceiveNDEFListener:   setReceiveNDEFListener,
        unsetReceiveNDEFListener: unsetReceiveNDEFListener,
        sendNDEF:                 sendNDEF
    };

    nfcPeer.__defineGetter__("isConnected", function () {
        return _data.isPeerConnected;
    });

    return nfcPeer;
};

function _initialize() {
    _data.nfcAdapter = new NFCAdapter();
}

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/notification', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    StatusNotification = require('ripple/platform/tizen/2.0/StatusNotification'),
    _notificationStack,
    _security = {
        "http://tizen.org/privilege/notification": ["post", "update", "remove",
                "removeAll"]
    },
    _self;

_self = function () {
    function post(notification) {
        var posted = {};

        if (!_security.post) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NotificationManager("post", arguments);

        if (notification.id !== undefined) {
            return;
        }
        posted.id = Math.uuid(null, 16);

        notification.__defineGetter__("id", function () {
            return posted.id;
        });

        if (!_notificationStack[notification.id]) {
            posted.postedTime = new Date();

            notification.__defineGetter__("postedTime", function () {
                return posted.postedTime;
            });

            _notificationStack[notification.id] = t.Notification(notification,
                    "+");
            db.saveObject("posted-notifications", _notificationStack);
            event.trigger("refreshNotificationUI", [], true);
        }
    }

    function update(notification) {
        if (!_security.update) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NotificationManager("update", arguments);

        if (!_notificationStack[notification.id]) {
            throw new WebAPIException(errorcode.UNKNOWN_ERR);
        }
        _notificationStack[notification.id] = t.Notification(notification,
                "+");
        db.saveObject("posted-notifications", _notificationStack);
        event.trigger("refreshNotificationUI", [], true);
    }

    function remove(id) {
        if (!_security.remove) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.NotificationManager("remove", arguments);

        if (!_notificationStack[id]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        delete _notificationStack[id];
        db.saveObject("posted-notifications", _notificationStack);
        event.trigger('refreshNotificationUI', [], true);
    }

    function removeAll() {
        if (!_security.removeAll) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        _notificationStack = {};
        db.saveObject("posted-notifications", _notificationStack);
        event.trigger('refreshNotificationUI', [], true);
    }

    function get(id) {
        var n, notification;

        t.NotificationManager("get", arguments);

        if (!_notificationStack[id]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        n = _notificationStack[id];
        notification = new StatusNotification(n.statusType, n.title, n);

        notification.__defineGetter__("id", function () {
            return n.id;
        });

        notification.__defineGetter__("postedTime", function () {
            return n.postedTime;
        });

        return notification;
    }

    function getAll() {
        var notifications = [];

        utils.forEach(_notificationStack, function (n) {
            var notification;

            notification = new StatusNotification(n.statusType, n.title, n);

            notification.__defineGetter__("id", function () {
                return n.id;
            });

            notification.__defineGetter__("postedTime", function () {
                return n.postedTime;
            });

            notifications.push(notification);
        });

        return notifications;
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    var notification = {
        post:              post,
        update:            update,
        remove:            remove,
        removeAll:         removeAll,
        get:               get,
        getAll:            getAll,
        handleSubFeatures: handleSubFeatures
    };

    return notification;
};

function _initilize() {
    _notificationStack = db.retrieveObject("posted-notifications") || {};

    utils.forEach(_notificationStack, function (n) {
        n.postedTime = new Date(n.postedTime);
    });

    event.on("refreshNotificationStack", function () {
        _notificationStack = db.retrieveObject("posted-notifications");
    });
}

_initilize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/package', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    app = require('ripple/app'),
    event = require('ripple/event'),
    utils = require('ripple/utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    PackageInformation = require('ripple/platform/tizen/2.0/PackageInformation'),
    _security = {
        "http://tizen.org/privilege/packagemanager.install": ["install", "uninstall"],
        "http://tizen.org/privilege/package.info": ["getPackagesInfo", "getPackageInfo",
                    "setPackageInfoEventListener", "unsetPackageInfoEventListener"]
    },
    DB_PACKAGE_KEY = "tizen-db-package",
    _listeners = [],
    _data = {
        packageList: {},
        installedList: {}
    },
    INTERVAL = 1000, // INTERVAL = 1sec
    INSTALL_AMOUNT = 3072, // installation speed amount = 3072 (KB/sec)
    PSEUDO_PACKAGE_ID = "pseudopack00",
    PSEUDO_APP_ID = "pseudoapp00",
    _self;

function _get() {
    _data = db.retrieveObject(DB_PACKAGE_KEY);
}

function _save() {
    db.saveObject(DB_PACKAGE_KEY, _data);
}

function _exec(callback, name, id, arg1) {
    switch (name) {
    case "onprogress":
        callback[name](id, arg1);
        break;
    case "oncomplete":
        callback[name](id);
        break;
    default:
        break;
    }
}

function _setupCurrentPackage() {
    var info, id, item, tizenAppId;
    info = app.getInfo();
    tizenAppId = info.tizenAppId || PSEUDO_APP_ID;
    id = info.tizenPackageId;
    if (id !== undefined) {
        if (_data.installedList[id]) {
            // already installed
            return;
        }

        item = null;
        utils.forEach(_data.packageList, function (p) {
            if (p.id === id) {
                item = p;
            }
        });

        if (item) {
            _data.installedList[item.id] = new PackageInformation(
                item.id, item.name, item.iconPath, item.version,
                item.totalSize, item.dataSize, new Date(),
                item.author, item.description, item.appIds
            );
            event.trigger("install-current-package", [_data.installedList[item.id]]);
        } else {
            _data.installedList[id] = new PackageInformation(
                id, "Tizen pseudo package", "icon.png", "2.2",
                8264, 50, new Date(),
                "TizenDev", "This is a description which is used in tests.", [tizenAppId]
            );
            event.trigger("install-current-package", [_data.installedList[id]]);
        }
    } else {
        _data.installedList[PSEUDO_PACKAGE_ID] = new PackageInformation(
            PSEUDO_PACKAGE_ID, "Tizen pseudo package", "icon.png", "2.2",
            8264, 50, new Date(),
            "TizenDev", "This is a description which is used in tests.", [tizenAppId]
        );
        event.trigger("install-current-package", [_data.installedList[PSEUDO_PACKAGE_ID]]);
    }
}

function _updatePackage(path, updateFlag) {
    var item, p, info;

    if (!_data.packageList[path]) {
        return;
    }
    _get();
    p = _data.packageList[path];
    item = _data.installedList[p.id];
    utils.forEach(_listeners, function (listener) {
        info = new PackageInformation(
            item.id, item.name, item.iconPath, item.version,
            item.totalSize, item.dataSize, item.lastModified,
            item.author, item.description, item.appIds);
        if (!updateFlag) {
            listener.oninstalled(info);
        } else {
            listener.onupdated(info);
        }
    });
}

function _initialize() {
    _get();

    if (!_data)
        return;

    utils.forEach(_data.installedList, function (item) {
        item.lastModified = new Date(item.lastModified);
    });

    _setupCurrentPackage();

    event.on("install-packge", function (path) {
        _updatePackage(path, false);
    });
    event.on("update-package", function (path) {
        _updatePackage(path, true);
    });

    event.on("uninstall-package", function (id) {
        _get();
        utils.forEach(_listeners, function (listener) {
            listener.onuninstalled(id);
        });
    });
}

_self = function () {
    var package;

    // public
    function install(path, progressCallback, errorCallback) {
        if (!_security.install) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PackageManager("install", arguments);

        window.setTimeout(function () {
            var intervalId, installedSize = 0, packageSize, updateFlag = false,
                item, info, progress;

            if (!_data.packageList[path]) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                }
                return;
            }
            item = _data.packageList[path];
            if (_data.installedList[item.id]) {
                updateFlag = true;
            }
            packageSize = item.totalSize;
            intervalId = setInterval(function () {
                if (installedSize >= packageSize) {
                    // Install complete
                    _data.installedList[item.id] = new PackageInformation(
                        item.id, item.name, item.iconPath, item.version,
                        item.totalSize, item.dataSize, new Date(),
                        item.author, item.description, item.appIds
                    );
                    event.trigger("install-apps", [item.appIds]);
                    _save();
                    _exec(progressCallback, "oncomplete", item.id);
                    clearInterval(intervalId);
                    item = _data.installedList[item.id];
                    utils.forEach(_listeners, function (listener) {
                        info = new PackageInformation(
                            item.id, item.name, item.iconPath, item.version,
                            item.totalSize, item.dataSize, item.lastModified,
                            item.author, item.description, item.appIds);
                        if (!updateFlag) {
                            listener.oninstalled(info);
                        } else {
                            listener.onupdated(info);
                        }
                    });
                    event.trigger("installedList-updated");
                } else {
                    installedSize += INSTALL_AMOUNT;
                    progress = (installedSize > packageSize) ? 100 :
                            Math.floor(installedSize * 100 / packageSize);
                    _exec(progressCallback, "onprogress", item.id, progress);
                }
            }, INTERVAL);
        }, 1);
    }

    function uninstall(id, progressCallback, errorCallback) {
        if (!_security.uninstall) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PackageManager("uninstall", arguments);

        window.setTimeout(function () {
            var intervalId, removedSize = 0, packageSize, item, progress;

            if (!_data.installedList[id]) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.NOT_FOUND_ERR));
                }
                return;
            }
            item = _data.installedList[id];
            packageSize = item.totalSize;
            intervalId = setInterval(function () {
                if (removedSize >= packageSize) {
                    utils.forEach(_data.packageList, function (package) {
                        if (package.id === id) {
                            event.trigger("remove-apps", [package.appIds]);
                        }
                    });
                    delete _data.installedList[item.id];
                    _save();
                    _exec(progressCallback, "oncomplete", item.id);
                    clearInterval(intervalId);
                    item = _data.installedList[item.id];
                    utils.forEach(_listeners, function (listener) {
                        listener.onuninstalled(id);
                    });
                    event.trigger("installedList-updated");
                } else {
                    removedSize += INSTALL_AMOUNT * 10;
                    progress = (removedSize > packageSize) ? 100 :
                            Math.floor(removedSize * 100 / packageSize);
                    _exec(progressCallback, "onprogress", item.id, progress);
                }
            }, INTERVAL);
        }, 1);
    }

    function getPackagesInfo(successCallback, errorCallback) {
        if (!_security.getPackagesInfo) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PackageManager("getPackagesInfo", arguments);

        window.setTimeout(function () {
            var packageArray = [];

            utils.forEach(_data.installedList, function (item) {
                var i;
                i = new PackageInformation(
                        item.id, item.name, item.iconPath, item.version,
                        item.totalSize, item.dataSize, item.lastModified,
                        item.author, item.description, item.appIds
                    );
                packageArray.push(i);
            });
            successCallback(packageArray);
        }, 1);
    }

    function getPackageInfo(id) {
        var p, item;

        if (!_security.getPackageInfo) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PackageManager("getPackageInfo", arguments);

        id = id || "api1pack00";

        if (!_data.installedList[id]) {
            throw new WebAPIException(errorcode.NOT_FOUND_ERR);
        }
        item = _data.installedList[id];
        p = new PackageInformation(item.id, item.name, item.iconPath,
                item.version, item.totalSize, item.dataSize, item.lastModified,
                item.author, item.description, item.appIds);

        return p;
    }

    function setPackageInfoEventListener(eventCallback) {
        if (!_security.setPackageInfoEventListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PackageManager("setPackageInfoEventListener", arguments);

        _listeners.push(eventCallback);
    }

    function unsetPackageInfoEventListener() {
        if (!_security.unsetPackageInfoEventListener) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PackageManager("unsetPackageInfoEventListener", arguments);

        _listeners = [];
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    package = {
        install:                       install,
        uninstall:                     uninstall,
        getPackagesInfo:               getPackagesInfo,
        getPackageInfo:                getPackageInfo,
        setPackageInfoEventListener:   setPackageInfoEventListener,
        unsetPackageInfoEventListener: unsetPackageInfoEventListener,
        handleSubFeatures:             handleSubFeatures
    };

    return package;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/pendingObject', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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.
 */

module.exports = function (pendingObj) {
    var cancelFlag = true;
    this.setCancelFlag = function (flag) {
        cancelFlag = flag;
    };
    this.getCancelFlag = function () {
        return cancelFlag;
    };
    this.userCancel = null;
    this.pendingID = null;
};

});
define('ripple/platform/tizen/2.0/pendingoperation', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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.
 */

module.exports = function (pendingObj) {
    var pending = true;
    this.cancel = function () {
        if (pending === true) {
            if (typeof (pendingObj.getCancelFlag) === "function" && pendingObj.getCancelFlag() === false) {
                pending = false;
                // this clearTimeout is for the case when a 3rd party is invoked to do the task, and it's finished sooner than the intended timeout. therefore, the 3rd party set CancelFlag false, and this cancel is called before timeout
                clearTimeout(pendingObj.pendingID);
                return false;
            }
            if (typeof (pendingObj.userCancel) === "function") {
                pendingObj.userCancel();
            }
            clearTimeout(pendingObj.pendingID);
            pending = false;
            return true;
        } else {
            return false;
        }
    };
};


});
define('ripple/platform/tizen/2.0/poi', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 OpenMapQuestProvider = require('ripple/platform/tizen/2.0/poiBackend_openmapquest'), // opne.MapQuest.xapi service
    _providers,
    _security = {
        "http://tizen.org/api/poi": [],
        "http://tizen.org/api/poi.read": ["find"],
        "http://tizen.org/api/poi.write": ["add", "remove", "update"],
        all: true
    },
    _self;

function _initialize() {
    _providers = [new OpenMapQuestProvider({name : "MapQuest", connectivity : "ONLINE", metaData : _security})];
}

_self = function () {
    var poi;

    poi = {
        getDefaultProvider : function () {
            return _providers[0];
        },
        getProviders : function () {
            return _providers;
        },
        handleSubFeatures: function (subFeatures) {
            var i, subFeature;
            for (subFeature in subFeatures) {
                if (_security[subFeature].length === 0) {
                    _security.all = true;
                    break;
                }
                _security.all = false;
                for (i = 0; i < _security[subFeature].length; i++) {
                    _security[_security[subFeature][i]] = true;
                }
            }
            _initialize();
        }
    };

    return poi;
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/poiBackend_openmapquest', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    POIGeometry = require('ripple/platform/tizen/2.0/POIGeometry'),
    SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
    _security;

function POIPublic(prop) {
    /* This is created for public use */
    var _self, i, copy, attr,  _id = null, _providerName = null;
    if (prop.id) {
        _id = prop.id;
    }
    if (prop.providerName) {
        _providerName = prop.providerName;
    }
    _self = {
        name : null,
        categories : [],
        address : null,
        phoneNumbers : [],
        geometry : null,
        urls : [],
        rating : null,
        tags : null,
        toGeoJSON : function () {
            throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
        }
    };

    _self.__defineGetter__("id", function () {
        return _id;
    });

    _self.__defineGetter__("providerName", function () {
        return _providerName;
    });

    if (prop) {
        if (prop.name) {
            _self.name = String(prop.name);
        }
        if (tizen1_utils.isValidArray(prop.categories)) {
            _self.categories = [];
            for (i in prop.categories) {
                _self.categories.push(String(prop.categories[i]));
            }
        }
        if (prop.address) {
            if (typeof prop.address === "string") {
                _self.address = String(prop.address);
            } else if (Object.prototype.toString.call(prop.address) === "[object Object]") {
                copy = prop.address.constructor();
                for (attr in prop.address) {
                    if (prop.address.hasOwnProperty(attr)) {
                        copy[attr] = prop.address[attr];
                    }
                }
                _self.address = copy;
            }
        }
        if (tizen1_utils.isValidArray(prop.phoneNumbers)) {
            _self.phoneNumbers = [];
            for (i in prop.phoneNumbers) {
                _self.phoneNumbers.push(String(prop.phoneNumbers[i]));
            }
        }
        if (prop.geometry) {
            _self.geometry = new POIGeometry(prop.geometry.position, prop.geometry.viewport, prop.geometry.wkt);
        }
        if (tizen1_utils.isValidArray(prop.urls)) {
            _self.urls = [];
            for (i in prop.urls) {
                _self.urls.push(String(prop.urls[i]));
            }
        }
        if (typeof prop.rating === "number") {
            _self.rating = prop.rating;
        }
        if (Object.prototype.toString.call(prop.tags) === "[object Object]") {
            copy = prop.tags.constructor();
            for (attr in prop.tags) {
                if (prop.tags.hasOwnProperty(attr)) {
                    copy[attr] = prop.tags[attr];
                }
            }
            _self.tags = copy;
        }
    }

    return _self;
}

module.exports = function (prop) {

    var _self = new lbs.LocationServiceProvider(prop);

    if (prop.metaData) {
        _security = prop.metaData;
    }

    _self.__defineGetter__("supportedFilterTypes", function () {
        return [];
    });

    _self.__defineGetter__("supportedPOIFilterAttributes", function () {
        return [];
    });

    _self.__defineGetter__("supportedCategories", function () {
        /* reference: http://wiki.openstreetmap.org/wiki/Map_Features#Amenity */
        return ["bar", "bbq", "biergarten", "cafe", "drinking_water", "fast_food", "food_court", "ice_cream",
                "pub", "restaurant", "college", "kindergarten", "library", "school", "university",
                "bicycle_parking", "bicycle_rental", "bus_station", "car_rental", "car_sharing", "car_wash",
                "ev_charging", "ferry_terminal", "fuel", "grit_bin", "parking", "parking_entrance",
                "parking_space", "taxi", "atm", "bank", "bureau_de_change", "baby_hatch", "clinic",
                "dentist", "doctors", "hospital", "nursing_home", "pharmacy", "social_facility", "veterinary",
                "arts_centre", "cinema", "community_centre", "fountain", "nightclub", "social_centre",
                "stripclub", "studio", "swingerclub", "theatre", "bench", "brothel", "clock", "courthouse",
                "crematorium", "embassy", "fire_station", "grave_yard", "hunting_stand", "marketplace",
                "place_of_worship", "police", "post_box", "post_office", "prison", "public_building",
                "recycling", "sauna", "shelter", "shower", "telephone", "toilets", "townhall", "vending_machine",
                "waste_basket", "waste_disposal", "watering_place"];
    });

    _self.__defineGetter__("capabilities", function () {
        /* The set is empty, indicating that this provider supports only 'find' operations */
        return [];
    });

    _self.find = function (point, successCallback, errorCallback, options) {
        /* This provider only supports searching by "GeoRectBounds" due to MapQuest XAPI limitation */

        function _find() {
            var searchStr, pois = [], isTypeOK = false,
                id, providerName, name, categories = [], geometry;

            if (Object.prototype.toString.call(point) === "[object Object]") {
                if (point.southWest && point.northEast) {
                    if (typeof point.southWest.latitude === "number" &&
                        typeof point.southWest.longitude === "number" &&
                        typeof point.northEast.latitude === "number" &&
                        typeof point.northEast.longitude === "number") {
                        isTypeOK = true;
                    }
                }
            }

            if (!isTypeOK) {
                throw (new WebAPIError(errorcode.TYPE_MISMATCH_ERR));
            }

            searchStr = "http://open.mapquestapi.com/xapi/api/0.6/node";
            if (options && tizen1_utils.isValidArray(options.categories) &&
                options.categories.length > 0 && typeof options.categories[0] === "string") {
                /* xapi support single amenity only */
                searchStr += "[amenity=" + options.categories[0] + "]";
            }
            searchStr += "[bbox=" + point.southWest.longitude + "," + point.southWest.latitude + "," +
                point.northEast.longitude + "," + point.northEast.latitude + "]";

            /* use Open MapQuest online xapi service. (http://open.mapquestapi.com/xapi/) */
            $.ajax({
                type: "GET",
                url: searchStr,
                dataType: "xml",
                timeout: 15000, /* 15 secs timeout */
                success: function (xml) {
                    providerName = $(xml).find("osm").attr("generator");
                    $(xml).find("node").each(function () {
                        var $item = $(this);
                        categories = [];
                        id = $item.attr("id");
                        geometry = new POIGeometry(new SimpleCoordinates($item.attr("lat"), $item.attr("lon")));
                        $item.find("tag").each(function () {
                            if ($(this).attr("k") === "name") {
                                name = $(this).attr("v");
                            } else if ($(this).attr("k") === "amenity") {
                                categories.push($(this).attr("v"));
                            }
                        });
                        pois.push(new POIPublic({id: id, providerName: providerName, name: name,
                                                categories: categories, geometry: geometry}));
                    });
                    successCallback(pois);
                },
                error: function (obj, msg) {
                    if (errorCallback) {
                        if (msg === "timeout") {
                            setTimeout(function () {
                                errorCallback(new WebAPIError(errorcode.TIMEOUT_ERR));
                            }, 1);
                        } else {
                            setTimeout(function () {
                                errorCallback(new WebAPIError(errorcode.NETWORK_ERR));
                            }, 1);
                        }
                    }
                }
            });
        }

        if (!_security.all && !_security.find) {
            throw new WebAPIError(errorcode.SECURITY_ERR);
        }

        tizen1_utils.validateTypeMismatch(successCallback, errorCallback, "find", _find);
    };

    _self.update = function (poi, successCallback, errorCallback) {
        if (!_security.all && !_security.update) {
            throw new WebAPIError(errorcode.SECURITY_ERR);
        }

        throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
    };

    _self.add = function (poi, successCallback, errorCallback) {
        if (!_security.all && !_security.add) {
            throw new WebAPIError(errorcode.SECURITY_ERR);
        }

        throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
    };

    _self.remove = function (poi, successCallback, errorCallback) {
        if (!_security.all && !_security.remove) {
            throw new WebAPIError(errorcode.SECURITY_ERR);
        }

        throw new WebAPIError(errorcode.NOT_SUPPORTED_ERR);
    };

    return _self;
};

});
define('ripple/platform/tizen/2.0/power', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    constants = require('ripple/constants'),
    deviceSettings = require('ripple/deviceSettings'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    _POWER_RESOURCE = constants.POWER_RESOURCE,
    _SCREEN_STATE = constants.POWER_RESOURCE.SCREEN.STATE,
    ScreenState = {"previous" : null, "current" : null},
    _listeners = [],
    _isScreenResourceOccupied = false,
    _originalBrightness,
    _isCPUAwake = false,
    _isScreenOn = true,
    _normalBrightness,
    _minimal_screen_state = null,
    _security = {
        "http://tizen.org/privilege/power": ["request", "setScreenBrightness", "turnScreenOn", "turnScreenOff"]
    },
    _self;

/**initialize**/
function initState() {
    _normalBrightness = deviceSettings.retrieve("DISPLAY.brightness");
    updateResourceState();
}

function getResourceState(value) {
    var state;
    value = Number(value);
    if (value <=  _SCREEN_STATE.SCREEN_OFF.MAX) {
        state = _SCREEN_STATE.SCREEN_OFF.NAME;
    } else if (value < _SCREEN_STATE.SCREEN_DIM.MAX) {
        state = _SCREEN_STATE.SCREEN_DIM.NAME;
    } else if (value < _SCREEN_STATE.SCREEN_NORMAL.MAX) {
        state = _SCREEN_STATE.SCREEN_NORMAL.NAME;
    } else {
        state = _SCREEN_STATE.SCREEN_BRIGHT.NAME;
    }
    return state;
}

function updateResourceState() {
    var brightness, actualState;
    brightness = deviceSettings.retrieve("DISPLAY.brightness");
    actualState = getResourceState(brightness);
    ScreenState.previous = ScreenState.current;
    ScreenState.current = actualState;
}

function callListeners(listeners, previousState, changedState) {
    listeners.forEach(function (listener) {
        setTimeout(function () {
            listener(previousState, changedState);
        }, 1);
    });
}

function triggerListenerCB(stateObj) {
    if (stateObj.previous !== stateObj.current) {
        callListeners(_listeners, stateObj.previous, stateObj.current);
    }
}

_self = function () {
    function request(resource, state) {
        if (!_security.request) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PowerManager("request", arguments);

        //Check state
        if (!_POWER_RESOURCE[resource].STATE.hasOwnProperty(state)) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
        // Exception check: SCREEN_OFF is a state cannot be requested
        if (resource === "SCREEN" && state === "SCREEN_OFF") {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
        switch (resource) {
        case "SCREEN" :
            if ((_minimal_screen_state === null) ||
               (_minimal_screen_state === "SCREEN_DIM" && (state === "SCREEN_NORMAL" || state === "SCREEN_BRIGHT")) ||
               (_minimal_screen_state === "SCREEN_NORMAL" && state === "SCREEN_BRIGHT")) {
                _minimal_screen_state = state;
            }
            break;
        case "CPU" :
            _isCPUAwake = true;
            break;
        default:
            break;
        }
    }

    function release(resource) {
        t.PowerManager("release", arguments);

        switch (resource) {
        case "SCREEN" :
            if (_isScreenResourceOccupied) {
                _isScreenResourceOccupied = false;
                deviceSettings.persist("DISPLAY.brightness", _originalBrightness);
                event.trigger("DisplayBrightnessChangedByPower", [_originalBrightness]);
                updateResourceState();
                triggerListenerCB(ScreenState);
            }
            _minimal_screen_state = null;
            break;
        case "CPU" :
            _isCPUAwake = false;
            break;
        default:
        }
    }

    function setScreenStateChangeListener(listener) {
        t.PowerManager("setScreenStateChangeListener", arguments);

        _listeners.push(listener);
    }

    function unsetScreenStateChangeListener() {
        _listeners = [];
    }

    function getScreenBrightness() {
        var brightness = deviceSettings.retrieve("DISPLAY.brightness");
        return brightness;
    }

    function setScreenBrightness(brightness) {
        if (!_security.setScreenBrightness) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PowerManager("setScreenBrightness", arguments);

        if (brightness < 0 || brightness > 1) {
            throw new WebAPIException(errorcode.INVALID_VALUES_ERR);
        }
        if (!_isScreenResourceOccupied) {
            _originalBrightness = deviceSettings.retrieve("DISPLAY.brightness");
            _isScreenResourceOccupied = true;
        }
        deviceSettings.persist("DISPLAY.brightness", brightness);
        event.trigger("DisplayBrightnessChangedByPower", [brightness]);
        updateResourceState();
        triggerListenerCB(ScreenState);
    }

    function isScreenOn() {
        return _isScreenOn;
    }

    function restoreScreenBrightness() {
        if (_isScreenResourceOccupied) {
            _isScreenResourceOccupied = false;
            deviceSettings.persist("DISPLAY.brightness", _originalBrightness);
            event.trigger("DisplayBrightnessChangedByPower", [_originalBrightness]);
            updateResourceState();
            triggerListenerCB(ScreenState);
        }
    }

    function turnScreenOn() {
        var brightness, value, flag = false;
        if (!_security.turnScreenOn) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        brightness = deviceSettings.retrieve("DISPLAY.brightness");
        switch (_minimal_screen_state) {
        case "SCREEN_DIM":
            if (brightness <= _SCREEN_STATE.SCREEN_OFF.VALUE) {
                if (!_isScreenResourceOccupied) {
                    _originalBrightness = brightness;
                    _isScreenResourceOccupied = true;
                }
                value = _SCREEN_STATE.SCREEN_DIM.VALUE;
                flag = true;
            }
            break;
        case "SCREEN_NORMAL":
            if (brightness < _SCREEN_STATE.SCREEN_NORMAL.MIN) {
                if (!_isScreenResourceOccupied) {
                    _originalBrightness = brightness;
                    _isScreenResourceOccupied = true;
                }
                value = _normalBrightness;
                flag = true;
            }
            break;
        case "SCREEN_BRIGHT":
            if (brightness < _SCREEN_STATE.SCREEN_BRIGHT.MIN) {
                if (!_isScreenResourceOccupied) {
                    _originalBrightness = brightness;
                    _isScreenResourceOccupied = true;
                }
                value = _SCREEN_STATE.SCREEN_BRIGHT.VALUE;
                flag = true;
            }
            break;
        }
        if (flag) {
            deviceSettings.persist("DISPLAY.brightness", value);
            event.trigger("DisplayBrightnessChangedByPower", [value]);
            updateResourceState();
            triggerListenerCB(ScreenState);
        }
        _isScreenOn = true;
    }

    function turnScreenOff() {
        if (!_security.turnScreenOff) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        _isScreenOn = false;
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    var power = {
        request: request,
        release: release,
        setScreenStateChangeListener: setScreenStateChangeListener,
        unsetScreenStateChangeListener: unsetScreenStateChangeListener,
        getScreenBrightness: getScreenBrightness,
        setScreenBrightness: setScreenBrightness,
        isScreenOn: isScreenOn,
        restoreScreenBrightness: restoreScreenBrightness,
        turnScreenOn: turnScreenOn,
        turnScreenOff: turnScreenOff,
        handleSubFeatures : handleSubFeatures
    };

    return power;
};

initState();
event.on("CpuLoadChanged", function (value) {
    var load;
    if (_isCPUAwake && Number(value) === 0) {
        load = _POWER_RESOURCE.CPU.STATE.CPU_AWAKE.DEFAULT_VALUE;
        deviceSettings.persist("CPU.load", load);
        event.trigger("CpuLoadChangedByPower", [load]);
    }
});
event.on("DisplayBrightnessChanged", function () {
    _normalBrightness = deviceSettings.retrieve("DISPLAY.brightness");
    updateResourceState();
    triggerListenerCB(ScreenState);
});

module.exports = _self;

});
define('ripple/platform/tizen/2.0/push', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    Notification = require('ripple/platform/tizen/2.0/notification'),
    StatusNotification = require('ripple/platform/tizen/2.0/StatusNotification'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    PushMessage,
    _data = {
        service: {
/*          "ID_APPLICATION_0": {
 *              appId:          null,
 *              registrationId: null,
 *              appControl:     null,
 *              isRegistered:   false,
 *              isConnected:    false,
 *              onpushed:       null
 *          }
 */
        }
    },
    _security = {
        "http://tizen.org/privilege/push": ["registerService",
            "unregisterService", "connectService", "disconnectService",
            "getRegistrationId"]
    },
    _self;

function _initialize() {
    event.on("PushNotified", function (appId, pushMessage) {
        var appService, notificationDict, statusNotification, notification;

        appService = _data.service[appId];

        if (!appService)
            return;

        if (appService.isConnected) {
            appService.onpushed(new PushMessage(pushMessage));
        } else {
            notificationDict = {
                content: pushMessage.appData,
                appControl: appService.appControl,
                appId: appId
            };
            statusNotification = new StatusNotification("SIMPLE",
                pushMessage.alertMessage, notificationDict);
            notification = new Notification();

            notification.post(statusNotification);
        }
    });
}

function _getCurrentApplicationId() {
    return "ID_APPLICATION_0";
}

_self = function () {
    var push;

    function registerService(appControl, successCallback, errorCallback) {
        if (!_security.registerService) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PushManager("registerService", arguments, true);

        window.setTimeout(function () {
            var appId, appService;

            appId = _getCurrentApplicationId();
            appService = {
                appId:          appId,
                registrationId: null,
                appControl:     appControl,
                isRegistered:   false
            };
            _data.service[appId] = appService;

            event.trigger("PushRequest", ["REGISTER", appService], true);

            if (appService.registrationId === null) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.UNKNOWN_ERR));
                }
                return;
            }

            appService.isRegistered = true;
            successCallback(appService.registrationId);
        }, 1);
    }

    function unregisterService(successCallback, errorCallback) {
        if (!_security.unregisterService) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PushManager("unregisterService", arguments);

        window.setTimeout(function () {
            var appId;

            appId = _getCurrentApplicationId();
            delete _data.service[appId];
            event.trigger("PushRequest", ["UNREGISTER", appId]);
            if (successCallback) {
                successCallback();
            }
        }, 1);
    }

    function connectService(notificationCallback) {
        var appId, appService;

        if (!_security.connectService) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PushManager("connectService", arguments);

        appId = _getCurrentApplicationId();
        appService = _data.service[appId];
        if (!appService || !appService.isRegistered) {
            throw new WebAPIException(errorcode.UNKNOWN_ERR);
        }

        appService.isConnected = true;
        appService.onpushed    = notificationCallback;
        event.trigger("PushRequest", ["CONNECT", appId]);
    }

    function disconnectService() {
        var appId, appService;

        if (!_security.disconnectService) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PushManager("disconnectService", arguments);

        appId = _getCurrentApplicationId();
        appService = _data.service[appId];
        if (!appService || !appService.isRegistered ||
                !appService.isConnected) {
            return;
        }

        appService.onpushed    = null;
        appService.isConnected = false;
        event.trigger("PushRequest", ["DISCONNECT", appId]);
    }

    function getRegistrationId() {
        var appService;

        if (!_security.getRegistrationId) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.PushManager("getRegistrationId", arguments);

        appService = _data.service[_getCurrentApplicationId()];
        if (!appService || !appService.isRegistered) {
            return null;
        }

        return appService.registrationId;
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    push = {
        registerService:   registerService,
        unregisterService: unregisterService,
        connectService:    connectService,
        disconnectService: disconnectService,
        getRegistrationId: getRegistrationId,
        handleSubFeatures: handleSubFeatures
    };

    return push;
};

_initialize();

PushMessage = function (pushMessageInitDict) {
    var appData, alertMessage, date;

    this.__defineGetter__("appData", function () {
        return appData;
    });

    this.__defineGetter__("alertMessage", function () {
        return alertMessage;
    });

    this.__defineGetter__("date", function () {
        return date;
    });

    appData      = pushMessageInitDict.appData || "";
    alertMessage = pushMessageInitDict.alertMessage || "";
    date         = pushMessageInitDict.date || new Date();
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/route', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
    ProviderNominatim = require('ripple/platform/tizen/2.0/routeBackend_navigation'), // navigation route service
    _getProviders,
    _providers,
    _self;

function _initialize() {
    _providers = [new ProviderNominatim({name : "Nominatim", connectivity : "ONLINE"})];
}

_initialize();

_self = {
    getDefaultProvider : function () {
        if (arguments.length !== 0) {
            throw (new WebAPIError(errorcode.INVALID_VALUES_ERR));
        }
        return _providers[0];
    },
    getProviders : function () {
        if (arguments.length !== 0) {
            throw (new WebAPIError(errorcode.INVALID_VALUES_ERR));
        }
        return _providers;
    }
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/routeBackend_local', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    lbs = require('ripple/platform/tizen/2.0/lbs'),
    LocationServiceProvider = {},
    RouteWaypoint,
    RouteDistance,
    RouteDuration,
    RouteStep,
    RouteSegment,
    RouteRequestOptions,
    RouteResultSummary,
    RouteResult,
    _data = {
        DB_ROUTE_LOCATION_KEY: "tizen1-db-route",
        DB_ROUTE_COLLEAGE_KEY: "tizen2-db-route",
        routeProvider: {},
        routes: [],
        RouteDistanceUnit: ["M", "KM", "MI", "FT"],
        providers: [],
        path: []
    },
    _self;

// The RouteWaypoint object
RouteWaypoint = function () {
    return {
        position: {
            latitude: 0,
            longitude: 0
        },
        isStopover: true
    };
};

// The RouteDistance object
RouteDistance = function () {
    return {
        text: "",
        value: 0,
        unit: "KM"
    };
};

// The RouteDuration object
RouteDuration = function () {
    return {
        text: "",
        value: 0 // The duration in a seconds
    };
};

// The RouteStep object
RouteStep = function () {
    var _self = {
        mode: "",        // The way of the travel, for example: car, bike, foot
        instruction: "", // The instruction of this step
        points: []       // The points of this step
    };

    _self.origin      = new SimpleCoordinates(0, 0);
    _self.destination = new SimpleCoordinates(0, 0);
    _self.distance    = new RouteDistance();
    _self.duration    = new RouteDuration();

    return _self;
};

// The RouteSegment object
RouteSegment = function () {
    var _self = {
        steps: []
    };

    _self.origin      = new SimpleCoordinates(0, 0);
    _self.destination = new SimpleCoordinates(0, 0);
    _self.distance    = new RouteDistance();
    _self.duration    = new RouteDuration();

    return _self;
};

// The RouteRequestOptions object
RouteRequestOptions = function () {
    return {
        mode: "", // CAR, BIKE
        unit: "KM",
        routeGoal: "SHORTEST",
        constraints: ["HIGHWAY", "TOLL", "UNPAVED"],
        wayPoints: [],
        maxResults: 1
    };
};

// The RouteResultSummary object
RouteResultSummary = function () {
    var _self = {};

    _self.origin        = new SimpleCoordinates(0, 0);
    _self.destination   = new SimpleCoordinates(0, 0);
    _self.totalDistance = new RouteDistance();
    _self.totalDuration = new RouteDuration();

    return _self;
};

// The RouteResult object
RouteResult = function () {
    var _self = {
        segments: []
    };

    _self.summary = new RouteResultSummary();

    return _self;
};

// Floyd arithmetic in Mathematics, solving the optimal way
function floyd(e, n, startIndex, endIndex) {
    var MAX = Infinity,
        a = new Array(n), i, j, k, p = new Array(n),
        paths, pathWay = [];

    for (i = 1; i < n + 1; i++) {
        a[i] = new Array(n);
    }
    for (i = 1; i < n + 1; i++) {
        p[i] = new Array(n);
    }
    for (i = 1; i < n + 1; i++) {
        for (j = 1; j < n + 1; j++) {
            if (i === j || e[i][j] === "MIN") {
                a[i][j] = 0;
            } else if (e[i][j] !== 0 && e[i][j] !== "MIN") {
                a[i][j] = e[i][j];
            } else {
                a[i][j] = MAX;
            }
            p[i][j] = 0;
        }
    }
    for (i = 1; i < n + 1; i++) {
        a[i][i] = 0;
    }
    for (k = 1; k < n + 1; k++) {
        for (i = 1; i < n + 1; i++) {
            for (j = 1; j < n + 1; j++) {
                if (parseInt(a[i][k], 10) + parseInt(a[k][j], 10) < a[i][j]) {
                    a[i][j] = parseInt(a[i][k], 10) + parseInt(a[k][j], 10);
                    p[i][j] = k;
                }
            }
        }
    }
    _data.path = [];
    paths = findPath(startIndex, endIndex, p);
    pathWay = [];
    pathWay.push(startIndex);
    for (i = 0; i < paths.length; i++) {
        pathWay.push(paths[i]);
    }
    pathWay.push(endIndex);

    return pathWay;
}

// Find the best way in the locations
function findPath(i, j, p) {
    var k = p[i][j];

    if (k === 0 || i === j) {
        return _data.path;
    }
    findPath(i, k, p);
    _data.path.push(k);

    return findPath(k, j, p);
}

// Find the index in the locations by string
function findIndexByStr(str, locations) {
    for (var i in locations) {
        if (locations[i].name === str) {
            return parseInt(i, 10) + 1;
        }
    }
    return -1;
}

// Find the index in the colleages by name1 and name2
function findValueByStr(start, end, locations, colleages) {
    for (var i in colleages) {
        if (colleages[i].name1 === locations[start - 1].name && colleages[i].name2 === locations[end - 1].name) {
            return parseInt(i, 10);
        } else if (colleages[i].name2 === locations[start - 1].name && colleages[i].name1 === locations[end - 1].name) {
            return parseInt(i, 10);
        }
    }
    return -1;
}

// Find the index in the locations by latitude and longitude
function searchIndexBycoodinates(latitude, longitude, locations) {
    if (latitude !== null && longitude !== null) {
        for (var i in locations) {
            if (locations[i].latitude === latitude && locations[i].longitude === longitude) {
                return parseInt(i, 10) + 1;
            }
        }
    }
    return -1;
}

// Get the relation among the locations
function getRelation(n, colleages, locations, goal) {
    var i, j, start, end, relation = new Array(n + 1);
    for (i = 1; i < n + 2; i++) {
        relation[i] = new Array(n + 1);
    }
    for (i = 1; i < n + 1; i++) {
        for (j = 1; j < n + 1; j++) {
            relation[i][j] = 0;
        }
    }
    for (i in colleages) {
        start = findIndexByStr(colleages[i].name1, locations);
        end = findIndexByStr(colleages[i].name2, locations);
        if (start !== -1 && end !== -1 && start !== end) {
            switch (goal) {
            case "distance":
                relation[start][end] = colleages[i].distance;
                relation[end][start] = colleages[i].distance;
                break;

            case "duration":
                relation[start][end] = colleages[i].duration;
                relation[end][start] = colleages[i].duration;
                break;

            case "simple":
                relation[start][end] = 1;
                relation[end][start] = 1;
                break;

            case "scenic":
                if (colleages[i].addition.scenic === "SCENIC") {
                    relation[start][end] = 1;
                    relation[start][end] = 1;
                } else if (colleages[i].addition.scenic === "") {
                    relation[start][end] = "MIN";
                    relation[start][end] = "MIN";
                }
                break;

            case "cheap":
                if (colleages[i].addition.toll === "TOLL") {
                    relation[start][end] = 1;
                    relation[end][start] = 1;
                } else if (colleages[i].addition.toll === "") {
                    relation[start][end] = "MIN";
                    relation[start][end] = "MIN";
                }
                break;

            case "safe":
                if (colleages[i].addition.hazardous === "HAZARDOUS") {
                    relation[start][end] = 1;
                    relation[end][start] = 1;
                } else if (colleages[i].addition.hazardous === "") {
                    relation[start][end] = "MIN";
                    relation[end][start] = "MIN";
                }
                break;

            default:
                return null;
            }
        }
    }

    return relation;
}

// Get the distance relationship among the locations
function distanceRelation(n, colleages, locations) {
    return getRelation(n, colleages, locations, "distance");
}

// Get the duration relationship among the locations
function durationRelation(n, colleages, locations) {
    return getRelation(n, colleages, locations, "duration");
}

// Get the simple relationship among the locations
function simpleRelation(n, colleages, locations) {
    return getRelation(n, colleages, locations, "simple");
}

// Get the cheap relationship among the locations
function cheapRelation(n, colleages, locations) {
    return getRelation(n, colleages, locations, "cheap");
}

// Get the safe relationship among the locations
function safeRelation(n, colleages, locations) {
    return getRelation(n, colleages, locations, "safe");
}

// Get the scenic relationship among the locations
function scenicRelation(n, colleages, locations) {
    return getRelation(n, colleages, locations, "scenic");
}

// Get the shortest way by origin, destination, locations and colleages
function optimalWay(origin, destination, locations, colleages, relation) {
    var n = locations.length, i, steps = [], step, relations, routeLocations,
        originIndex, destinationIndex, startIndex, endIndex, colleageIndex,
        originLatitude, originLongitude, destinationLatitude, destinationLongitude,
        startLatitude, startLongitude, endLatitude, endLongitude,
        originLocation, destinationLocation, segment, result;

    originLatitude = origin.latitude;
    originLongitude = origin.longitude;
    originIndex = searchIndexBycoodinates(originLatitude, originLongitude, locations);

    destinationLatitude = destination.latitude;
    destinationLongitude = destination.longitude;
    destinationIndex = searchIndexBycoodinates(destinationLatitude, destinationLongitude, locations);

    relations = relation(n, colleages, locations);

    if (originIndex !== -1 && destinationIndex !== -1) {
        routeLocations = floyd(relations, n, parseInt(originIndex, 10), parseInt(destinationIndex, 10));

        for (i = 0; i < routeLocations.length - 1; i++) {
            colleageIndex = findValueByStr(routeLocations[i], routeLocations[i + 1], locations, colleages);

            if (colleageIndex !== -1) {
                step = new RouteStep();
                startIndex = parseInt(routeLocations[i], 10) - 1;
                endIndex = parseInt(routeLocations[i + 1], 10) - 1;

                startLatitude = locations[startIndex].latitude;
                startLongitude = locations[startIndex].longitude;
                originLocation = new SimpleCoordinates(startLatitude, startLongitude);

                endLatitude = locations[endIndex].latitude;
                endLongitude = locations[endIndex].longitude;
                destinationLocation = new SimpleCoordinates(endLatitude, endLongitude);

                step.origin = originLocation;
                step.destination = destinationLocation;
                step.distance = colleages[colleageIndex].distance;
                step.duration = colleages[colleageIndex].duration;
                step.mode = colleages[colleageIndex].mode;
                step.addition = colleages[colleageIndex].addition;

                steps.push(step);
            } else if (colleageIndex === -1) {
                return null;
            }
        }

        segment = new RouteSegment();
        segment.steps = steps;
        result = new RouteResult();
        result.segments[0] = segment;

        return result;
    }
    return null;
}

// Get the shortest way by origin, destination, locations and colleages
function shortestWay(origin, destination, locations, colleages) {
    return optimalWay(origin, destination, locations, colleages, distanceRelation);
}

// Get the fastest way by origin, destination, locations and colleages
function fastestWay(origin, destination, locations, colleages) {
    return optimalWay(origin, destination, locations, colleages, durationRelation);
}

// Get the simplest way by origin, destination, locations and colleages
function simplestWay(origin, destination, locations, colleages) {
    return optimalWay(origin, destination, locations, colleages, simpleRelation);
}

// Get the most scenic way by origin, destination, locations and colleages
function mostScenicWay(origin, destination, locations, colleages) {
    return optimalWay(origin, destination, locations, colleages, scenicRelation);
}

// Get the cheapest way by origin, destination, locations and colleages
function cheapestWay(origin, destination, locations, colleages) {
    return optimalWay(origin, destination, locations, colleages, cheapRelation);
}

// Get the safest way by origin, destination, locations and colleages
function safestWay(origin, destination, locations, colleages) {
    return optimalWay(origin, destination, locations, colleages, safeRelation);
}

// Uniquelize the array
function uniquelize(array) {
    var temp = {}, result = [], i;
    for (i = array.length; i--;) {
        temp[array[i]] = array[i];
    }
    for (i in temp) {
        result.push(temp[i]);
    }
    return result;
}

// Is it intersect between the Array a and b
function intersect(a, b) {
    var i, j;

    a = uniquelize(a);
    if (a.length === 0 && b.length === 0) {
        return true;
    }
    for (i in a) {
        for (j in b) {
            if (a[i] === b[j])
                return true;
        }
    }
    return false;
}

function getConstrains(result) {
    var steps = result.segments[0].steps, constrains = [];

    utils.forEach(steps, function (item, index) {
        if (item.addition.highway === "HIGHWAY") {
            constrains.push("HIGHWAY");
        }
        if (item.addition.toll === "TOLL") {
            constrains.push("TOLL");
        }
        if (item.addition.bridge === "BRIDGE") {
            constrains.push("BRIDGE");
        }
        if (item.addition.hazardous === "HAZARDOUS") {
            constrains.push("HAZARDOUS");
        }
        if (item.addition.scenic === "SCENIC") {
            constrains.push("SCENIC");
        }
    });
    if (constrains.length > 0) {
        return uniquelize(constrains);
    }
    return constrains;
}

module.exports = function (prop) {
    var _self = new lbs.LocationServiceProvider(prop);
    _self.find = function (origin, destination, successCallback, errorCallback, options) {
        function _find() {
            var locations, colleages, i, result = {}, emptyResult = [], modes = [], resultModes = [], constrains = [], resultconstrains = [];

            locations = db.retrieveObject(_data.DB_ROUTE_LOCATION_KEY);
            colleages = db.retrieveObject(_data.DB_ROUTE_COLLEAGE_KEY);

            modes = options.modes;
            constrains = options.constrains;
            if (locations.length > 0 && colleages.length > 0) {
                switch (options.routeGoal) {
                case "SHORTEST":
                    result = shortestWay(origin, destination, locations, colleages);
                    break;

                case "FASTEST":
                    result = fastestWay(origin, destination, locations, colleages);
                    break;

                case "SIMPLEST":
                    result = simplestWay(origin, destination, locations, colleages);
                    break;

                case "MOST_SCENIC":
                    result = mostScenicWay(origin, destination, locations, colleages);
                    break;

                case "CHEAPEST":
                    result = cheapestWay(origin, destination, locations, colleages);
                    break;

                case "SAFEST":
                    result = safestWay(origin, destination, locations, colleages);
                    break;

                default:
                    result = shortestWay(origin, destination, locations, colleages);
                    break;
                }
                if (result !== null) {
                    for (i in result.segments[0].steps) {
                        resultModes.push(result.segments[0].steps[i].mode);
                    }
                    resultconstrains = getConstrains(result);
                    if (intersect(resultModes, modes) && intersect(resultconstrains, constrains)) {
                        successCallback(result);
                    } else {
                        successCallback(null);
                    }
                }
            } else {
                successCallback(emptyResult);
            }
        }
        tizen1_utils.validateTypeMismatch(successCallback, errorCallback, "find", _find);
    };
    return _self;
};

});
define('ripple/platform/tizen/2.0/routeBackend_navigation', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    lbs_utils = require('ripple/platform/tizen/2.0/lbs_utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    SimpleCoordinates = require('ripple/platform/tizen/2.0/SimpleCoordinates'),
    RouteWaypoint,
    RouteDistance,
    RouteDuration,
    RouteStep,
    RouteSegment,
    RouteRequestOptions,
    RouteResultSummary,
    RouteResult,
    _data = {
        positionDistance: {},
        positionDuration: {},
        routeProvider: {},
        routes: [],
        RouteDistanceUnit: ["M", "KM", "MI", "FT"],
        providers: [],
        path: []
    },
    _self;

// The RouteWaypoint object
RouteWaypoint = function () {
    return {
        position: {
            latitude: 0,
            longitude: 0
        },
        isStopover: true
    };
};

// The RouteDistance object
RouteDistance = function () {
    return {
        text : "Distance",
        value : "0",
        unit : "KM "
    };
};

// The RouteDuration object
RouteDuration = function () {
    return {
        text : "Duration",
        value : "0" // The duration in a seconds
    };
};

// The RouteStep object
RouteStep = function () {
    var _self = {
        mode: "",        // The way of the travel, for example: car, bike, foot
        instruction: "", // The instruction of this step
        points: []       // The points of this step
    };

    _self.origin      = new SimpleCoordinates(0, 0);
    _self.destination = new SimpleCoordinates(0, 0);
    _self.distance    = new RouteDistance();
    _self.duration    = new RouteDuration();

    return _self;
};
// The RouteSegment object
RouteSegment = function () {
    var _self = {
        steps: []
    };

    _self.origin      = new SimpleCoordinates(0, 0);
    _self.destination = new SimpleCoordinates(0, 0);
    _self.distance    = new RouteDistance();
    _self.duration    = new RouteDuration();

    return _self;
};

// The RouteRequestOptions object
RouteRequestOptions = function () {
    return {
        mode: "", // CAR, BIKE
        unit: "KM",
        routeGoal: "SHORTEST",
        constraints: ["HIGHWAY", "TOLL", "UNPAVED"],
        wayPoints: [],
        maxResults: 1
    };
};

// The RouteResultSummary object
RouteResultSummary = function () {
    var _self = {};

    _self.origin        = new SimpleCoordinates(0, 0);
    _self.destination   = new SimpleCoordinates(0, 0);
    _self.totalDistance = new RouteDistance();
    _self.totalDuration = new RouteDuration();

    return _self;
};

// The RouteResult object
RouteResult = function () {
    var _self, jsonStr, jsonObj;
    jsonObj = {
            "type" : "Point",
            "coordinates" : []
        };
    jsonStr = JSON.stringify(jsonObj);
    _self = {
        segments : [],
        toGeoJSON : function () {
                return jsonStr;
            }
    };
    _self.summary = new RouteResultSummary();
    return _self;
};

function calcDegree(distance) {
    return distance * Math.PI / 180.0;
}

//calcute the distance
function  calculateDistance(lat1, lat2, lon1, lon2) {
    var R = 6371, dLat, dLon, a, c, distance; // km
    dLat = calcDegree(parseFloat(lat2) - parseFloat(lat1));
    dLon = calcDegree(parseFloat(lon2) - parseFloat(lon1));

    lat1 = calcDegree(lat1);
    lat2 = calcDegree(lat2);

    a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
             Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    distance = R * c;
    return distance;
}

function calculateDuration(mode, distance) {
    var duration, v;
    switch (mode) {
    case "motorcar" :
        v = 50;
        duration = distance / v;
        break;
    case "bicycle" :
        v = 20;
        duration = distance / v;
        break;
    case "foot" :
        v = 5;
        duration = distance / v;
        break;
    default:
        duration = 0;
    }
    return duration;
}

function optimalWay(points, mode) {
    var steps = [], startLatitude, startLongitude, originLocation, endLatitude, endLongitude,
    destinationLocation, step, distance, i, routeDistance, routeDuration;
    for (i = 0;i < points.length - 1;i++) {
        startLatitude       = points[i].lat;
        startLongitude      = points[i].lon;
        originLocation      = new SimpleCoordinates(startLatitude, startLongitude);
        endLatitude         = points[i + 1].lat;
        endLongitude        = points[i + 1].lon;
        destinationLocation = new SimpleCoordinates(endLatitude, endLongitude);
        step                = new RouteStep();
        step.origin         = originLocation;
        step.destination    = destinationLocation;
        distance            = calculateDistance(startLatitude, endLatitude, startLongitude, endLongitude);
        routeDistance       = new RouteDistance();
        routeDistance.value = distance;
        routeDistance.unit  = "km";
        step.distance       = routeDistance;
        routeDuration       = new RouteDuration();
        routeDuration.value = calculateDuration(mode, distance);
        step.duration       = routeDuration;
        steps.push(step);
    }
    return steps;
}

function existInSupports(str, array) {
    for (var i in array) {
        if (str === array[i]) {
            return true;
        }
    }
    return false;
}

function navigation(searchStr, flat, flon, tlat, tlon, v, fast) {
    var positions = [];

    _data.positionDistance = {};
    _data.positionDuration = {};
    jQuery.ajax({
        type : "get",
        async : false,
        url : searchStr,
        data : {
            flat : flat,
            flon : flon,
            tlat : tlat,
            tlon : tlon,
            v : v,
            fast : fast,
            layer : 'mapnik',
            format : "geojson"
        },
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        cache : false,
        success : function (data) {
            $.each(data.coordinates, function (i, item) {
                var point = {};
                point.lon = item[0];
                point.lat = item[1];
                positions.push(point);
            });
            $.each(data.properties, function (i, item) {
                if (typeof item === "number") {
                    _data.positionDistance = new RouteDistance();
                    _data.positionDistance.value = item;
                    _data.positionDistance.unit = "km";
                    _data.positionDuration = new RouteDuration();
                    _data.positionDuration.value = calculateDuration(v, item);
                }
            });
        },
        error : function (errorCB) {
            if (errorCB) {
                setTimeout(function () {
                    errorCB(new WebAPIError(errorcode.NETWORK_ERR));
                }, 1);
            }
        }
    });
    return positions;
}


function filterWaypoints(routeWaypoints) {
    var mathWaypoints = [], i;
    for (i in routeWaypoints) {
        if (routeWaypoints[i].position.latitude !== "" &&
            routeWaypoints[i].position.latitude !== undefined &&
            routeWaypoints[i].position.latitude !== null &&
            routeWaypoints[i].position.longitude !== null &&
            routeWaypoints[i].position.longitude !== "" &&
            routeWaypoints[i].position.longitude !== undefined) {
            mathWaypoints.push(routeWaypoints[i]);
        }
    }
    return mathWaypoints;
}

module.exports = function (prop) {
    var _self = new lbs_utils.LocationServiceProvider(prop);

    _self.supportedGoals       = ["SHORTEST", "FASTEST", "MOST_SCENIC", "SIMPLEST", "CHEAPEST", "SAFEST" ];
    _self.supportedModes       = ["motorcar", "bicycle", "foot"];
    _self.supportedConstraints = ["HIGHWAY", "TOLL", "UNPAVED", "BORDER", "GRAVEL_PAVING", "TUNNEL", "BRIDGE", "LEFT_TURN", "CARPOOL", "HAZARDOUS_CARGO" ];
    _self.supportsWayPoints    = true;
    _self.find = function (origin, destination, successCallback, errorCallback, options) {
        function _find() {
            var flat, flon, tlat, tlon, v, fast, searchStr, result,
                routeWaypoints = [],
                segmentPositions = [],
                positions = [],
                segments = [],
                totalDistances = 0, totalDurations = 0,
                k, key, segment, startPosition, endPosition,
                summary, distance, duration;

            v = options.mode;
            //init
            if (!existInSupports(v, _self.supportedModes)) {
                throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
            }
            if (!existInSupports(options.routeGoal, _self.supportedGoals)) {
                throw new WebAPIError(errorcode.TYPE_MISMATCH_ERR);
            }
            switch (options.routeGoal) {
            case "SHORTEST":
                fast = 0;
                break;

            case "FASTEST":
                fast = 1;
                break;

            case "SIMPLEST":
                break;

            case "MOST_SCENIC":
                break;

            case "CHEAPEST":
                break;

            case "SAFEST":
                break;

            default:
                fast = 0;
            }
            searchStr      = "http://www.yournavigation.org/api/dev/gosmore.php";
            routeWaypoints = options.wayPoints;
            routeWaypoints = filterWaypoints(routeWaypoints);
            segmentPositions.push(origin);

            if (routeWaypoints.length > 0) {
                for (k in routeWaypoints) {
                    segmentPositions.push(routeWaypoints[k].position);
                }
            }
            segmentPositions.push(destination);

            for (key = 0; key < segmentPositions.length - 1; key++) {
                segment             = new RouteSegment();
                startPosition       = segmentPositions[key];
                endPosition         = segmentPositions[key + 1];
                segment.origin      = startPosition;
                segment.destination = endPosition;
                flat                = startPosition.latitude;
                flon                = startPosition.longitude;
                tlat                = endPosition.latitude;
                tlon                = endPosition.longitude;
                positions           = navigation(searchStr, flat, flon, tlat, tlon, v, fast);
                segment.steps       = optimalWay(positions, v);
                segment.distance    = _data.positionDistance;
                totalDistances     += _data.positionDistance.value;
                segment.duration    = _data.positionDuration;
                totalDurations     += _data.positionDuration.value;
                segments.push(segment);
            }
            result                = new RouteResult();
            summary               = new RouteResultSummary();
            summary.origin        = segmentPositions[0];
            summary.destination   = segmentPositions[segmentPositions.length - 1];
            distance              = new RouteDistance();
            distance.value        = totalDistances;
            distance.unit         = "km";
            summary.totalDistance = distance;
            duration              = new RouteDuration();
            duration.value        = totalDurations;
            summary.totalDuration = duration;
            result.segments       = segments;
            result.summary        = summary;
            successCallback(result);
        }

        tizen1_utils.validateTypeMismatch(successCallback, errorCallback, "find", _find);
    };

    return _self;
};

});
define('ripple/platform/tizen/2.0/sensors', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    sensors = require('ripple/platform/tizen/2.0/spec/sensor'),
    _sensors = ["Accelerometer", "MagneticField", "Rotation", "Orientation"],
    _permission = true,
    _isWriteable = false,
    _self;

function SensorError(code, msg) {
    this.__defineGetter__("message", function () {
        return msg;
    });
    this.__defineGetter__("code", function () {
        return code;
    });

    this.PERMISSION_DENIED = -100;
}

function SensorRequest() {
    var _self = {
        result: [],
        error: null,
        readyState: "processing"
    };

    this.__defineGetter__("result", function () {
        return _self.result;
    });
    this.__defineSetter__("result", function (resultData) {
        if (_isWriteable) {
            _self.result = utils.copy(resultData);
            _isWriteable = false;
            return;
        }
    });

    this.__defineGetter__("error", function () {
        return _self.error;
    });
    this.__defineSetter__("error", function (errorData) {
        if (_isWriteable) {
            _self.error = utils.copy(errorData);
            _isWriteable = false;
            return;
        }
    });

    this.__defineGetter__("readyState", function () {
        return _self.readyState;
    });
    this.__defineSetter__("readyState", function (readyStateData) {
        if (_isWriteable) {
            _self.readyState = readyStateData;
            _isWriteable = false;
            return;
        }
    });
}

_self = {
    findSensors: function (type) {
        var sensorRequest = new SensorRequest(), index, sensorName = "";

        setTimeout(function () {
            if (_permission) {
                for (index = 0; index < _sensors.length; index++) {
                    sensorName = _sensors[index];
                    if (type === null || type === undefined || type === sensorName) {
                        _isWriteable = true;
                        sensorRequest.result.push(sensors[sensorName]);
                    }
                }

                _isWriteable = true;
                sensorRequest.readyState = "done";

                if (sensorRequest.onsuccess) {
                    sensorRequest.onsuccess();
                }
            }
            else {
                // error event on the request with error code PERMISSION_DENIED must be fired.
                sensorRequest.error = new SensorError(-100, "permission denied!");
                if (sensorRequest.onerror) {
                    sensorRequest.onerror();
                }
            }
        }, 1);

        return sensorRequest;
    }
};

module.exports = _self;


});
define('ripple/platform/tizen/2.0/spec/btdevices', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = {
    "22:33:44:12:34:56": {
        "name": "Tizen Phone",
        "address": "22:33:44:12:34:56",
        "deviceClass": {
            "major": 0x02,
            "majorName": "PHONE",
            "minor": 0x03,
            "minorName": "PHONE_SMARTPHONE",
            "services": [0x0080],
            "servicesName": ["OBJECT_TRANSFER"]
        },
        "isTrusted": false,
        "services": {
            "5bce9431-6c75-32ab-afe0-2ec108a30860" : {
                "name": "Data Exchange",
                "uuid": "5bce9431-6c75-32ab-afe0-2ec108a30860",
                "protocol": "RFCOMM"
            },
            "3537d485-0c1e-445a-a066-43fafcfb61d1" : {
                "name": "Data Transfer",
                "uuid": "3537d485-0c1e-445a-a066-43fafcfb61d1",
                "protocol": "RFCOMM"
            }
        }
    },
    "22:33:44:12:34:88": {
        "name": "Keyboard",
        "address": "22:33:44:12:34:88",
        "deviceClass": {
            "major": 0x05,
            "majorName": "PERIPHERAL",
            "minor": 0x10,
            "minorName": "PERIPHERAL_KEYBOARD",
            "services": [0x0080],
            "servicesName": ["OBJECT_TRANSFER"]
        },
        "isTrusted": true,
        "services": {
            "3537d485-0c1e-445a-a066-43fafcfb61d1" : {
                "name": "Data Exchange",
                "uuid": "3537d485-0c1e-445a-a066-43fafcfb61d1",
                "protocol": "RFCOMM"
            }
        }
    },
    "22:33:44:88:34:58": {
        "name": "Tizen Laptop",
        "address": "22:33:44:88:34:58",
        "deviceClass": {
            "major": 0x01,
            "majorName": "COMPUTER",
            "minor": 0x03,
            "minorName": "COMPUTER_LAPTOP",
            "services": [0x0080],
            "servicesName": ["OBJECT_TRANSFER"]
        },
        "isTrusted": true,
        "services": {
            "3537d485-0c1e-445a-a066-43fafcfb61d1" : {
                "name": "Data Exchange",
                "uuid": "3537d485-0c1e-445a-a066-43fafcfb61d1",
                "protocol": "RFCOMM"
            }
        }
    }
};

});
define('ripple/platform/tizen/2.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    constants = require('ripple/constants');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (configValidationObject) {
        var valid = true;
        // no xmlns:JIL in wac 2.0 spec
        valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;

        return valid;
    },
    extractInfo: function (configValidationObject) {
        if (!configValidationObject) {
            return null;
        }

        var widgetInfo = {},
            configFeatures,
            configPreferences,
            preferenceName,
            platform, rst, i, j,
            settingRst = {
                'screen-orientation': 'portrait',
                'context-menu': 'enable',
                'background-support': 'disable',
                encryption: 'disable',
                'install-location': 'auto',
                'hwkey-event': 'enable'
            };

        widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
        widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
        widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
        if (configValidationObject.widget.children.application.validationResult[0].valid) {
            widgetInfo.tizenAppId = configValidationObject.widget.children.application.validationResult[0].attributes.id.value;
            widgetInfo.tizenPackageId = configValidationObject.widget.children.application.validationResult[0].attributes.package.value;
        }

        widgetInfo.features = {};

        if (configValidationObject.widget.children.setting.hasOwnProperty('validationResult') === true) {
            rst = configValidationObject.widget.children.setting.validationResult;
            // the first one has higher priority per platform implementation
            for (i = rst.length -1 ; i >= 0; i--) {
                if (rst[i].valid === true) {
                    for (j in rst[i].attributes) {
                        if (rst[i].attributes[j].value !== undefined) {
                            settingRst[j] = rst[i].attributes[j].value;
                        }
                    }
                }
            }
            db.save("layout", settingRst["screen-orientation"]);
        }

        configFeatures = configValidationObject.widget.children.feature.validationResult;
        utils.forEach(configFeatures, function (f) {
            if (f.valid === true) {
                var feature = {id: f.attributes.name.value,
                         required: f.attributes.required.valid};
                widgetInfo.features[feature.id] = feature;
            }
        });

        widgetInfo.preferences = {};

        configPreferences = configValidationObject.widget.children.preference.validationResult;

        platform = require('ripple/platform');
        utils.forEach(configPreferences, function (preference) {
            preferenceName = preference.attributes.name.value;
            if (preferenceName) {
                widgetInfo.preferences[preferenceName] = {
                    "key": preferenceName,
                    "value": preference.attributes.value.value || "",
                    "readonly": preference.attributes.readonly.value === "true"
                };

                db.save(preferenceName,
                        widgetInfo.preferences[preferenceName].value,
                        platform.getPersistencePrefix(widgetInfo.id));
            }
        });

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in the configuration document and may have the following child elments: name,description,icon,author,license,content,feature and preference.The \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xmlns:tizen": {
                    attributeName: "xmlns:tizen",
                    required: false,
                    type: "list",
                    listValues: ["http://tizen.org/ns/widgets"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                },
                dir: {
                    attributeName: "dir",
                    required: false,
                    type: "list",
                    listValues: ["ltr", "rtl", "lro", "rlo"]
                },
                id: {
                    attributeName: "id",
                    required: false,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    required: false,
                    type: "string"
                },
                height: {
                    attributeName: "height",
                    required: false,
                    type: "integer"
                },
                width: {
                    attributeName: "width",
                    required: false,
                    type: "integer"
                },
                viewmodes: {
                    attributeName: "viewmodes",
                    required: false,
                    type: "list",
                    listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
                },
                defaultlocale: {
                    attributeName: "defaultlocale",
                    required: false,
                    type: "iso-language"
                }
            },
            children: {
                name: {
                    nodeName: "name",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        "short": {
                            attributeName: "short",
                            required: false,
                            type: "string"
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.URL
                        },
                        email: {
                            attributeName: "email",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.EMAIL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        width: {
                            attributeName: "width",
                            required: false,
                            type: "integer"
                        },
                        height: {
                            attributeName: "height",
                            required: false,
                            type: "integer"
                        }
                    }
                },
                content: {
                    nodeName: "content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        encoding: {
                            attributeName: "encoding",
                            required: false,
                            type: "string"
                        },
                        type: {
                            attributeName: "type",
                            required: false,
                            type: "string"
                        }
                    }
                },
                setting: {
                    nodeName: "tizen:setting",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        'screen-orientation': {
                            attributeName: "screen-orientation",
                            required: false,
                            type: "list",
                            listValues: ['portrait', 'landscape', 'auto']
                        },
                        'context-menu': {
                            attributeName: "context-menu",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'background-support': {
                            attributeName: "background-support",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'encryption': {
                            attributeName: "encryption",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'install-location': {
                            attributeName: "install-location",
                            required: false,
                            type: "list",
                            listValues: ['auto', 'internal-only', 'perfer-external']
                        },
                        'hwkey-event': {
                            attributeName: "hwkey-event",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        }
                    }
                },
                application: {
                    nodeName: "tizen:application",
                    required: true,
                    occurrence: 1,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            type: "string"
                        },
                        required_version: {
                            attributeName: "required_version",
                            required: true,
                            type: "list",
                            listValues: ['1.0', '2.0', '2.1', '2.2']
                        },
                        package: {
                            attributeName: "package",
                            required: false,
                            type: "string"
                        }
                    }
                },
                "tizen:content": {
                    nodeName: "tizen:content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        }
                    }
                },
                control: {
                    nodeName: "tizen:app-control",
                    required: false,
                    occurrence: 0,
                    children: {
                        src: {
                            nodeName: "tizen:src",
                            required: true,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        operation: {
                            nodeName: "tizen:operation",
                            required: true,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        uri: {
                            nodeName: "tizen:uri",
                            required: false,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        mime: {
                            nodeName: "tizen:mime",
                            required: false,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                "app-widget": {
                    nodeName: "tizen:app-widget",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            type: "string"
                        },
                        primary: {
                            attributeName: "primary",
                            required: true,
                            type: "list",
                            listValues: ['true', 'false']
                        },
                        "auto-launch": {
                            attributeName: "auto-launch",
                            required: false,
                            type: "list",
                            listValues: ['true', 'false']
                        },
                        "update-period": {
                            attributeName: "update-period",
                            required: false,
                            type: "integer"
                        }
                    },
                    children: {
                        "box-label": {
                            nodeName: "tizen:box-label",
                            required: true,
                            occurence: 1
                        },
                        "box-icon": {
                            nodeName: "tizen:box-icon",
                            required: true,
                            occurence: 1,
                            attributes: {
                                src: {
                                    attributeName: "src",
                                    required: true,
                                    type: "string"
                                }
                            }
                        },
                        "box-content": {
                            nodeName: "tizen:box-content",
                            required: true,
                            occurence: 1,
                            attributes: {
                                src: {
                                    attributeName: "src",
                                    required: true,
                                    type: "string"
                                },
                                "mouse-event": {
                                    attributeName: "mouse-event",
                                    required: false,
                                    type: "string"
                                },
                                "touch-event": {
                                    attributeName: "touch-event",
                                    required: false,
                                    type: "string"
                                }
                            },
                            children: {
                                "box-size": {
                                    nodeName: "tizen:box-size",
                                    required: false,
                                    occurence: 1,
                                    attributes: {
                                        "preview": {
                                            attributeName: "preview",
                                            required: false,
                                            type: "string"
                                        }
                                    }
                                },
                                pd: {
                                    nodeName: "tizen:pd",
                                    required: false,
                                    occurence: 1,
                                    attributes: {
                                        "src": {
                                            attributeName: "src",
                                            required: true,
                                            type: "string"
                                        },
                                        "width": {
                                            attributeName: "width",
                                            required: true,
                                            type: "integer"
                                        },
                                        "height": {
                                            attributeName: "height",
                                            required: true,
                                            type: "integer"
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                account: {
                    nodeName: "tizen:account",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "multiple-account-support": {
                            attributeName: "multiple-account-support",
                            required: true,
                            type: "list",
                            listValues: ['true', 'false']
                        }
                    },
                    children: {
                        icon: {
                            nodeName: "tizen:icon",
                            required: false,
                            occurence: 1,
                            attributes: {
                                section: {
                                    attributeName: "section",
                                    required: true,
                                    type: "string"
                                }
                            }
                        },
                        "display-name": {
                            nodeName: "tizen:display-name",
                            required: false,
                            occurence: 1,
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        capability: {
                            nodeName: "capability",
                            required: false,
                            occurence: 1
                        }
                    }
                },
                feature: {
                    nodeName: "tizen:privilege",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "list",
                            listValues: ["http://www.w3.org/TR/battery-status/",
                                         "http://www.w3.org/TR/geolocation-API/",
                                         "http://www.w3.org/TR/touch-events/",
                                         "http://www.w3.org/TR/vibration/",
                                         "http://tizen.org/privilege/tizen",
                                         "http://tizen.org/privilege/alarm",
                                         "http://tizen.org/privilege/application.launch",
                                         "http://tizen.org/privilege/appmanager.kill", "http://tizen.org/privilege/appmanager.certificate",
                                         "http://tizen.org/privilege/bluetoothmanager", "http://tizen.org/privilege/bluetooth.admin",
                                         "http://tizen.org/privilege/bluetooth.gap", "http://tizen.org/privilege/bluetooth.spp",
                                         "http://tizen.org/privilege/bookmark.read", "http://tizen.org/privilege/bookmark.write",
                                         "http://tizen.org/privilege/calendar.read", "http://tizen.org/privilege/calendar.write",
                                         "http://tizen.org/privilege/callhistory.read", "http://tizen.org/privilege/callhistory.write",
                                         "http://tizen.org/privilege/contact.read", "http://tizen.org/privilege/contact.write",
                                         "http://tizen.org/privilege/content.read", "http://tizen.org/privilege/content.write",
                                         "http://tizen.org/privilege/datacontrol.consumer",
                                         "http://tizen.org/privilege/datasync",
                                         "http://tizen.org/privilege/download",
                                         "http://tizen.org/privilege/filesystem.read", "http://tizen.org/privilege/filesystem.write",
                                         "http://tizen.org/privilege/messaging.read", "http://tizen.org/privilege/messaging.write",
                                         "http://tizen.org/privilege/networkbearerselection",
                                         "http://tizen.org/privilege/nfc.common", "http://tizen.org/privilege/nfc.admin",
                                         "http://tizen.org/privilege/nfc.tag", "http://tizen.org/privilege/nfc.p2p",
                                         "http://tizen.org/privilege/notification",
                                         "http://tizen.org/privilege/packagemanager.install", "http://tizen.org/privilege/package.info",
                                         "http://tizen.org/privilege/power",
                                         "http://tizen.org/privilege/push",
                                         "http://tizen.org/privilege/setting",
                                         "http://tizen.org/privilege/system", "http://tizen.org/privilege/systemmanager",
                                         "http://tizen.org/privilege/time",
                                         "http://tizen.org/privilege/websetting"]
                        },
                        required: {
                            attributeName: "required",
                            type: "boolean",
                            required: false
                        }
                    },
                    children: {
                        param: {
                            nodeName: "param",
                            required: false,
                            occurrence: 0,
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language"
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                },
                                name: {
                                    attributeName: "name",
                                    required: true,
                                    type: "string"
                                },
                                value: {
                                    attributeName: "value",
                                    required: true,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                preference: {
                    nodeName: "preference",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "string"
                        },
                        value: {
                            type: "string",
                            required: false,
                            attributeName: "value"
                        },
                        readonly: {
                            attributeName: "readonly",
                            type: "boolean",
                            required: false
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/tizen/2.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    StorageTypeTable = {
        "UNKNOWN": "UNKNOWN",
        "INTERNAL": "INTERNAL",
        "MMC": "MMC",
        "USB_HOST": "USB_HOST"
    },
    NetworkTypeTable = {
        "NONE": "NONE",
        "2G": "2G",
        "2.5G": "2.5G",
        "3G": "3G",
        "4G": "4G",
        "WIFI": "WIFI",
        "ETHERNET": "ETHERNET",
        "UNKNOWN": "UNKNOWN"
    },
    LocaleTable = {
        "eng_USA": "eng_USA",
        "eng_CAN": "eng_CAN",
        "deu_DEU": "deu_DEU",
        "jpn_JPN": "jpn_JPN",
        "zho_CHN": "zho_CHN",
        "UNKNOWN": "UNKNOWN"
    },
    SimStateTable = {
        "ABSENT": "ABSENT",
        "INITIALIZING": "INITIALIZING",
        "READY": "READY",
        "PIN_REQUIRED": "PIN_REQUIRED",
        "PUK_REQUIRED":"PUK_REQUIRED",
        "NETWORK_LOCKED": "NETWORK_LOCKED",
        "SIM_LOCKED": "SIM_LOCKED",
        "UNKNOWN": "UNKNOWN"
    };

function deviceStatusEventTrigger(setting) {
    event.trigger("DeviceStatusChanged", [setting]);
}

module.exports = {
    "Config": {
        "vibratingMode": {
            "name": "Vibrator",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("VibratingModeChanged", [setting]);
            }
        },
        "lockScreen": {
            "name": "Lock Screen",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "callback": function (setting) {
                event.trigger("LockScreenChanged", [setting]);
            }
        }
    },
    "DEVICE_ORIENTATION": {
        "status": {
            "name": "Status",
            "control": {
                "type": "label",
                "innertext": "PORTRAIT_PRIMARY",
                "value": "PORTRAIT_PRIMARY"
            },
            "event": "LayoutChanged"
        },
        "isAutoRotation": {
            "name": "Is Auto Rotation",
            "control": {
                "type": "label",
                "value": false
            }
        }
    },
    "CPU": {
        "load": {
            "name": "Load",
            "control": {
                "type": "number",
                "value": 0.1
            },
            "event": "CpuLoadChanged",
            "callback": function (setting) {
                if (setting > 1) setting = 1;
                if (setting < 0) setting = 0;
                event.trigger("CpuLoadChanged", [setting]);
            }
        }
    },
    "STORAGE": {
        "type": {
            "name": "Type",
            "control": {
                "type": "select",
                "value": StorageTypeTable["INTERNAL"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(StorageTypeTable, function (key, value) {
                    optionList[key] = StorageTypeTable[value];
                });

                return optionList;
            }())
        },
        "capacity": {
            "name": "Capacity(bytes)",
            "control": {
                "type": "label",
                "value": 16000000000
            },
        },
        "availableCapacity": {
            "name": "AvailableCapacity(bytes)",
            "control": {
                "type": "number",
                "value": 12000000000
            },
            "callback": function (setting) {
                event.trigger("AvailCapacityChanged", [setting]);
            }
        },
        "isRemovable": {
            "name": "IsRemovable",
            "control": {
                "type": "checkbox",
                "value": true
            }
        }
    },
    "BUILD": {
        "model": {
            "name": "Model",
            "control": {
                "type": "label",
                "innertext": "tizen-2.2 build",
                "value": "tizen-2.2 build"
            }
        },
        "manufacturer": {
            "name": "Manufacturer",
            "control": {
                "type": "label",
                "innertext": "Tizen",
                "value": "Tizen"
            }
        },
        "buildVersion": {
            "name": "Build Version",
            "control": {
                "type": "label",
                "innertext": "TIZEN_WEB_SIMULATOR_000001",
                "value": "TIZEN_WEB_SIMULATOR_000001"
            }
        }
    },
    "LOCALE": {
        "language": {
            "name": "Language",
            "control": {
                "type": "select",
                "value": LocaleTable["eng_USA"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(LocaleTable, function (key, value) {
                    optionList[key] = LocaleTable[value];
                });

                return optionList;
            }())
        },
        "country": {
            "name": "Country",
            "control": {
                "type": "select",
                "value": LocaleTable["eng_USA"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(LocaleTable, function (key, value) {
                    optionList[key] = LocaleTable[value];
                });

                return optionList;
            }())
        }
    },
    "DISPLAY": {
        "resolutionWidth": {
            "name": "Resolution Width(pixels)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "resolutionHeight": {
            "name": "Resolution Height(pixels)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "dotsPerInchWidth": {
            "name": "DPI-X",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "dotsPerInchHeight": {
            "name": "DPI-Y",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "physicalWidth": {
            "name": "Physical Width(millimeters)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "physicalHeight": {
            "name": "Physical Height(millimeters)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "brightness": {
            "name": "Brightness",
            "control": {
                "type": "number",
                "value": 1
            },
            "event": "DisplayBrightnessChanged",
            "callback": function (setting) {
                if (setting > 1) setting = 1;
                if (setting < 0) setting = 0;
                event.trigger("DisplayBrightnessChanged", [setting]);
            }
        }
    },
    "NETWORK": {
        "networkType": {
            "name": "Network Type",
            "control" : {
                "type": "select",
                "value": NetworkTypeTable["NONE"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(NetworkTypeTable, function (key, value) {
                    optionList[key] = NetworkTypeTable[value];
                });

                return optionList;
            }())
        }
    },
    "WIFI_NETWORK": {
        "status": {
            "name": "Status",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "event": "WiFiNetworkStatusChanged",
            "callback": function (setting) {
                event.trigger("WiFiNetworkStatusChanged", [setting]);
            }
        },
        "ssid": {
            "name": "SSID",
            "control": {
                "type": "text",
                "value": "Tizen WiFi"
            }
        },
        "ipAddress": {
            "name": "IP Address",
            "control": {
                "type": "text",
                "value": "192.168.0.1"
            }
        },
        "ipv6Address": {
            "name": "IPv6 Address",
            "control": {
                "type": "text",
                "value": "2001:db8:85a3:0:0:0:70:7334"
            }
        },
        "signalStrength": {
            "name": "Signal Strength",
            "control": {
                "type": "select",
                "value": 0
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 10; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }())
        }
    },
    "CELLULAR_NETWORK": {
        "status": {
            "name": "Status",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "event": "CellularNetworkStatusChanged",
            "callback": function (setting) {
                event.trigger("CellularNetworkStatusChanged", [setting]);
            }
        },
        "apn": {
            "name": "APN",
            "control": {
                "type": "text",
                "value": "Tizen"
            }
        },
        "ipAddress": {
            "name": "IP Address",
            "control": {
                "type": "text",
                "value": "10.0.2.16"
            }
        },
        "ipv6Address": {
            "name": "IPv6 Address",
            "control": {
                "type": "text",
                "value": "2001:db8:85a3:0:0:0:70:7334"
            }
        },
        "mcc": {
            "name": "MCC",
            "control": {
                "type": "number",
                "value": 460
            }
        },
        "mnc": {
            "name": "MNC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "cellId": {
            "name": "Cell ID",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "lac": {
            "name": "LAC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "isRoaming": {
            "name": "Roaming",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "isFlightMode": {
            "name": "Flight Mode",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "callback": function (setting) {
                event.trigger("FlightModeChanged", [setting]);
            }
        },
        "imei": {
            "name": "IMEI",
            "control": {
                "type": "text",
                "value": "012417005203000"
            }
        }
    },
    "SIM": {
        "state": {
            "name": "State",
            "control": {
                "type": "select",
                "value": SimStateTable["READY"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(SimStateTable, function (key, value) {
                    optionList[key] = SimStateTable[value];
                });

                return optionList;
            }())
        },
        "operatorName": {
            "name": "Operator Name",
            "control": {
                "type": "text",
                "value": "Tizen"
            }
        },
        "msisdn": {
            "name": "MSISDN",
            "control": {
                "type": "text",
                "value": "088123456789"
            }
        },
        "iccid": {
            "name": "ICCID",
            "control": {
                "type": "text",
                "value": "123000MFSSYYGXXXXXXP"
            }
        },
        "mcc": {
            "name": "MCC",
            "control": {
                "type": "number",
                "value": 460
            }
        },
        "mnc": {
            "name": "MNC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "msin": {
            "name": "MSIN",
            "control": {
                "type": "text",
                "value": "H1 H2 H3 S 12345"
            }
        },
        "spn": {
            "name": "SPN",
            "control": {
                "type": "text",
                "value": "TizenSPN"
            }
        }
    },
    "PERIPHERAL": {
        "isVideoOutputOn": {
            "name": "Video Output",
            "control": {
                "type": "checkbox",
                "value": false
            }
        }
    }
};


});
define('ripple/platform/tizen/2.0/spec/sensor', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event');

function sensorStatusEventTrigger(setting) {
    event.trigger("SensorStatusChanged", [setting]);
}

module.exports = {
    "Accelerometer": {
        "resolution": 0.039239998906850815,
        "minDelay": 20,
        "range": 20.051639556884766,
        "name": "Accelerometer",
        "type": "Accelerometer"
    },
    "MagneticField": {
        "x": {
            "name": "X",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-xChanged", [setting]);
            }
        },

        "y": {
            "name": "Y",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-yChanged", [setting]);
            }
        },

        "z": {
            "name": "Z",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-zChanged", [setting]);
            }
        },

        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "MagneticField",
        "type": "MagneticField"
    },
    "Rotation": {
        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "Rotation",
        "type": "Rotation"
    },
    "Orientation": {
        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "Orientation",
        "type": "Orientation"
    }
};

});
define('ripple/platform/tizen/2.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "sensors",
        "communication",
        "geoView",
        "widgetConfig",
        "deviceSettings",
        "application",
        "network",
        "power",
        "download",
        "notifications",
        "package"
    ]
};

});
define('ripple/platform/tizen/2.0/spec', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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.
 */

module.exports = {

    id: "tizen",
    version: "2.2",
    name: "TIZEN",

    persistencePrefix: "tizen1-",

    config: require('ripple/platform/tizen/2.0/spec/config'),
    ui: require('ripple/platform/tizen/2.0/spec/ui'),
    device: require('ripple/platform/tizen/2.0/spec/device'),
    sensor: require('ripple/platform/tizen/2.0/spec/sensor'),
    DeviceMotionEvent: require('ripple/platform/tizen/2.0/DeviceMotionEvent'),
    DeviceOrientationEvent: require('ripple/platform/tizen/2.0/DeviceOrientationEvent'),

    objects: {
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        SensorConnection: {
            path: "w3c/1.0/SensorConnection"
        },
        navigator: {
            path: "tizen/2.0/navigator",
            children: {
                geolocation: {
                    path: "wac/2.0/geolocation"
                },
                battery: {
                    path: "tizen/2.0/battery"
                }
            }
        },
        tizen: {
            feature: "http://tizen.org/privilege/tizen",
            children: {
                AlarmAbsolute: {
                    path: "tizen/2.0/AlarmAbsolute"
                },
                AlarmRelative: {
                    path: "tizen/2.0/AlarmRelative"
                },
                ApplicationControl: {
                    path: "tizen/2.0/ApplicationControl"
                },
                ApplicationControlData: {
                    path: "tizen/2.0/ApplicationControlData"
                },
                AttributeFilter: {
                    path: "tizen/2.0/AttributeFilter"
                },
                AttributeRangeFilter: {
                    path: "tizen/2.0/AttributeRangeFilter"
                },
                BookmarkFolder: {
                    path: "tizen/2.0/BookmarkFolder"
                },
                BookmarkItem: {
                    path: "tizen/2.0/BookmarkItem"
                },
                CalendarAlarm: {
                    path: "tizen/2.0/CalendarAlarm"
                },
                CalendarAttendee: {
                    path: "tizen/2.0/CalendarAttendee"
                },
                CalendarEvent: {
                    path: "tizen/2.0/CalendarEvent"
                },
                CalendarEventId: {
                    path: "tizen/2.0/CalendarEventId"
                },
                CalendarRecurrenceRule: {
                    path: "tizen/2.0/CalendarRecurrenceRule"
                },
                CalendarTask: {
                    path: "tizen/2.0/CalendarTask"
                },
                CompositeFilter: {
                    path: "tizen/2.0/CompositeFilter"
                },
                Contact: {
                    path: "tizen/2.0/ContactBase"
                },
                ContactAddress: {
                    path: "tizen/2.0/ContactAddress"
                },
                ContactAnniversary: {
                    path: "tizen/2.0/ContactAnniversary"
                },
                ContactEmailAddress: {
                    path: "tizen/2.0/ContactEmailAddress"
                },
                ContactGroup: {
                    path: "tizen/2.0/ContactGroup"
                },
                ContactName: {
                    path: "tizen/2.0/ContactName"
                },
                ContactOrganization: {
                    path: "tizen/2.0/ContactOrganization"
                },
                ContactPhoneNumber: {
                    path: "tizen/2.0/ContactPhoneNumber"
                },
                ContactRef: {
                    path: "tizen/2.0/ContactRef"
                },
                ContactWebSite: {
                    path: "tizen/2.0/ContactWebSite"
                },
                DownloadRequest: {
                    path: "tizen/2.0/DownloadRequest"
                },
                Message: {
                    path: "tizen/2.0/Message"
                },
                NDEFMessage: {
                    path: "tizen/2.0/NDEFMessage"
                },
                NDEFRecord: {
                    path: "tizen/2.0/NDEFRecord"
                },
                NDEFRecordMedia: {
                    path: "tizen/2.0/NDEFRecordMedia"
                },
                NDEFRecordText: {
                    path: "tizen/2.0/NDEFRecordText"
                },
                NDEFRecordURI: {
                    path: "tizen/2.0/NDEFRecordURI"
                },
                NotificationDetailInfo: {
                    path: "tizen/2.0/NotificationDetailInfo"
                },
                SimpleCoordinates: {
                    path: "tizen/2.0/SimpleCoordinates"
                },
                SortMode: {
                    path: "tizen/2.0/SortMode"
                },
                StatusNotification: {
                    path: "tizen/2.0/StatusNotification"
                },
                SyncInfo: {
                    path: "tizen/2.0/SyncInfo"
                },
                SyncServiceInfo: {
                    path: "tizen/2.0/SyncServiceInfo"
                },
                SyncProfileInfo: {
                    path: "tizen/2.0/SyncProfileInfo"
                },
                TZDate: {
                    path: "tizen/2.0/TZDate"
                },
                TimeDuration: {
                    path: "tizen/2.0/TimeDuration"
                },
                alarm: {
                    path: "tizen/2.0/alarm",
                    feature: "http://tizen.org/privilege/alarm",
                    handleSubfeatures: true
                },
                application: {
                    path: "tizen/2.0/application",
                    feature: "http://tizen.org/privilege/application.launch|http://tizen.org/privilege/appmanager.kill|http://tizen.org/privilege/appmanager.certificate",
                    handleSubfeatures: true
                },
                bluetooth: {
                    path: "tizen/2.0/bluetooth",
                    feature: "http://tizen.org/privilege/bluetoothmanager|http://tizen.org/privilege/bluetooth.admin|http://tizen.org/privilege/bluetooth.gap|http://tizen.org/privilege/bluetooth.spp",
                    handleSubfeatures: true
                },
                bookmark: {
                    path: "tizen/2.0/bookmark",
                    feature: "http://tizen.org/privilege/bookmark.read|http://tizen.org/privilege/bookmark.write",
                    handleSubfeatures: true
                },
                callhistory: {
                    path: "tizen/2.0/callHistory",
                    feature: "http://tizen.org/privilege/callhistory|http://tizen.org/privilege/callhistory.read|http://tizen.org/privilege/callhistory.write",
                    handleSubfeatures: true
                },
                calendar: {
                    path: "tizen/2.0/calendar",
                    feature: "http://tizen.org/privilege/calendar.read|http://tizen.org/privilege/calendar.write",
                    handleSubfeatures: true
                },
                contact: {
                    path: "tizen/2.0/contact",
                    feature: "http://tizen.org/privilege/contact.read|http://tizen.org/privilege/contact.write",
                    handleSubfeatures: true
                },
                content: {
                    path: "tizen/2.0/content",
                    feature: "http://tizen.org/privilege/content.read|http://tizen.org/privilege/content.write",
                    handleSubfeatures: true
                },
                datacontrol: {
                    path: "tizen/2.0/datacontrol",
                    feature: "http://tizen.org/privilege/datacontrol.consumer",
                    handleSubfeatures: true
                },
                datasync: {
                    path: "tizen/2.0/datasync",
                    feature: "http://tizen.org/privilege/datasync",
                    handleSubfeatures: true
                },
                download: {
                    path: "tizen/2.0/download",
                    feature: "http://tizen.org/privilege/download",
                    handleSubfeatures: true
                },
                filesystem: {
                    path: "tizen/2.0/filesystem",
                    feature: "http://tizen.org/privilege/filesystem.read|http://tizen.org/privilege/filesystem.write"
                },
                messaging: {
                    path: "tizen/2.0/messaging",
                    feature: "http://tizen.org/privilege/messaging.send|http://tizen.org/privilege/messaging.read|http://tizen.org/privilege/messaging.write",
                    handleSubfeatures: true
                },
                networkbearerselection: {
                    path: "tizen/2.0/networkbearerselection",
                    feature: "http://tizen.org/privilege/networkbearerselection",
                    handleSubfeatures: true
                },
                nfc: {
                    path: "tizen/2.0/nfc",
                    feature: "http://tizen.org/privilege/nfc.common|http://tizen.org/privilege/nfc.admin|http://tizen.org/privilege/nfc.tag|http://tizen.org/privilege/nfc.p2p",
                    handleSubfeatures: true
                },
                notification: {
                    path: "tizen/2.0/notification",
                    feature: "http://tizen.org/privilege/notification",
                    handleSubfeatures: true
                },
                package: {
                    path: "tizen/2.0/package",
                    feature: "http://tizen.org/privilege/packagemanager.install|http://tizen.org/privilege/package.info",
                    handleSubfeatures: true
                },
                power: {
                    path: "tizen/2.0/power",
                    feature: "http://tizen.org/privilege/power",
                    handleSubfeatures: true
                },
                push: {
                    path: "tizen/2.0/push",
                    feature: "http://tizen.org/privilege/push",
                    handleSubfeatures: true
                },
                systeminfo: {
                    path: "tizen/2.0/systeminfo",
                    feature: "http://tizen.org/privilege/system|http://tizen.org/privilege/systemmanager",
                    handleSubfeatures: true
                },
                systemsetting: {
                    path: "tizen/2.0/systemsetting",
                    feature: "http://tizen.org/privilege/setting",
                    handleSubfeatures: true
                },
                time: {
                    path: "tizen/2.0/time",
                    feature: "http://tizen.org/privilege/time",
                    handleSubfeatures: true
                },
                websetting: {
                    path: "tizen/2.0/websetting",
                    feature: "http://tizen.org/privilege/websetting",
                    handleSubfeatures: true
                }
            }
        }
    }
};

});
define('ripple/platform/tizen/2.0/syncml-js-lib/adapter', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.adapter
// auth: griffin <griffin@uberdev.org>
// date: 2012/10/22
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store');


var _self = (function () {

    var exports = {};

    //---------------------------------------------------------------------------
    exports.Adapter = common.Base.extend({

        // //-------------------------------------------------------------------------
        // constructor: function(context, options, devInfo) {

        //-------------------------------------------------------------------------
        normUri: function(uri) {
            return common.normpath(uri);
        },

        //-------------------------------------------------------------------------
        getStores: function() {
            return _.values(this._stores);
        },

        //-------------------------------------------------------------------------
        getStore: function(uri) {
            return this._stores[this.normUri(uri)];
        },

        //-------------------------------------------------------------------------
        addStore: function(store, cb) {
            var self = this;
            if ( store instanceof storemod.Store )
            {
                store.uri = self.normUri(store.uri);
                store._a  = self;
            }
            else
                store = new storemod.Store(this, store);
            store._updateModel(function(err) {
                if ( err )
                return cb(err);
            self._stores[store.uri] = store;

            // TODO: remove this sensitivity...
            if ( ! self.isLocal )
                return cb();

            self._save(self._c._txn(), function(err) {
                if ( err )
                return cb(err);
            cb(null, store);
            });
            });
        },

        //-------------------------------------------------------------------------
        removeStore: function(uri, cb) {
            var self = this;
            if ( ! self.isLocal )
                // todo: implement
                return cb(new common.LogicalError(
                            'cannot remove remote store "' + uri + '": remote peer responsibility'));
            if ( ! self._stores[uri] )
                return cb(new common.InternalError(
                            'cannot remove store "' + uri + '": no such store'));
            delete self._stores[uri];
            var model = self._getModel();
            model.stores = _.filter(model.stores, function(store) {
                return store.uri != uri;
            });
            _.each(model.peers, function(peer) {
                peer.routes = _.filter(peer.routes, function(route) {
                    return route.localUri != uri;
                });
                _.each(peer.stores, function(store) {
                    if ( store.binding && store.binding.uri == uri )
                    store.binding = null;
                });
            });
            return cb();
        },

        //-------------------------------------------------------------------------
        _isMapper: function() {
            // indicates whether or not this adapter is capable of mapping
            // items. in the standard SyncML peer model, only the server
            // ever does mapping, but in the dream-land of syncml-js, all
            // peers can be mappers, or even better, implements an extension
            // "is-uuid/adopted" that does not require mapping. so, since
            // that is just a dream-land for now, this will try to identify
            // if this adapter represents a server...
            // todo: enhance syncml-js so that it is not needed!...
            if ( ! this.isLocal )
                return this.url && this.url.length > 0;
            return this.devInfo && this.devInfo.devType == constant.DEVTYPE_SERVER;
        },

        //-------------------------------------------------------------------------
        describe: function(stream, cb) {
            var self = this;
            if ( self.url )
                stream.writeln('URL: ' + self.url);
            stream.writeln('Device ID: ' + self.devID);
            var s1 = stream.indented();
            var s2 = s1.indented();

            var describe_stores = function(cb) {
                var stores = self.getStores();
                if ( stores.length <= 0 )
                {
                    stream.writeln('Data stores: (none)');
                    return cb();
                }
                stream.writeln('Data stores:');
                common.cascade(stores, function(store, cb) {
                    s1.writeln(( store.displayName || store.uri ) + ':');
                    store.describe(s2, cb);
                }, cb);
            };

            var describe_peers = function(cb) {
                if ( ! self.getPeers )
                    return cb();
                var peers = self.getPeers();
                if ( peers.length <= 0 )
                {
                    stream.writeln('Known peers: (none)');
                    return cb();
                }
                stream.writeln('Known peers:');
                common.cascade(peers, function(peer, cb) {
                    s1.writeln(( peer.displayName || peer.url ) + ':');
                    peer.describe(s2, cb);
                }, cb);
            }

            describe_stores(function(err) {
                if ( err )
                return cb(err);
            describe_peers(cb);
            });
        }

    });

    return exports;

    })();

    module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/agent', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.agent
// auth: griffin <griffin@uberdev.org>
// date: 2012/10/22
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common');

var _self = (function () {

    var exports = {};

    //---------------------------------------------------------------------------
    exports.Agent = common.Base.extend({

        //-------------------------------------------------------------------------
        constructor: function(options) {
            options = _.defaults(options, {
                hierarchicalSync: false
            });
            this.hierarchicalSync = options.hierarchicalSync;
        },

        //-------------------------------------------------------------------------
        dumpItem: function(item, stream, contentType, version, cb) {
            return this.dumpsItem(
                item, contentType, version,
                function(err, data, new_contentType, new_version) {
                    if ( err ) {
                        return cb(err);
                    }
                    stream.write(data, function(err) {
                        if ( err ) {
                            return cb(err);
                        }
                        cb(null, new_contentType, new_version);
                    });
                });
        },

        //-------------------------------------------------------------------------
        loadItem: function(stream, contentType, version, cb) {
            var self = this;
            stream.read(function(err, data) {
                if ( err ) {
                    cb(err);
                }
                self.loadsItem(data, contentType, version, cb);
            });
        },

        //-------------------------------------------------------------------------
        deleteAllItems: function(cb) {
            var self = this;
            self.getAllItems(function(err, items) {
                if ( err ) {
                    return cb(err);
                }
                common.cascade(items, function(e, cb) {
                    self.deleteItem(e, cb);
                }, cb);
            });
        },

        // TODO: add documentation about all expected methods...

        getAllItems: function(cb) {
            // cb(null, LIST)
            return cb(new common.NotImplementedError());
        },

        dumpsItem: function(item, contentType, version, cb) {
            // cb(null, DATA [, NEW-CONTENTTYPE [, NEW-VERSION]])
            return cb(new common.NotImplementedError());
        },

        loadsItem: function(data, contentType, version, cb) {
            // cb(null, ITEM)
            return cb(new common.NotImplementedError());
        },

        addItem: function(item, cb) {
            // cb(null, ITEM)
            return cb(new common.NotImplementedError());
        },

        getItem: function(itemID, cb) {
            // cb(null, ITEM)
            return cb(new common.NotImplementedError());
        },

        replaceItem: function(item, reportChanges, cb) {
            // cb(null [, CSPEC])
            return cb(new common.NotImplementedError());
        },

        deleteItem: function(itemID, cb) {
            // cb(null)
            return cb(new common.NotImplementedError());
        },

        getContentTypes: function() {
            throw new common.NotImplementedError();
        },

        matchItem: function(item, cb) {
            this.getAllItems(function(err, list) {
                if ( err ) {
                    return cb(err);
                }
                var match = _.find(list, function(cur) {
                    return cur.compare && cur.compare(item) == 0;
                });
                return cb(null, match);
            });
        }

    // TODO: mergeItems()

    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/base64', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
//-----------------------------------------------------------------------------

var _self = (function() {

    // shamelessly scrubbed from:
    //   http://www.webtoolkit.info/javascript-base64.html

    /**
     *
     *  Base64 encode / decode
     *  http://www.webtoolkit.info/
     *
     **/

    var Base64 = {

        // private property
        _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

      // public method for encoding
      encode : function (input) {
          var output = "";
          var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
          var i = 0;

          input = Base64._utf8_encode(input);

          while (i < input.length) {

              chr1 = input.charCodeAt(i++);
              chr2 = input.charCodeAt(i++);
              chr3 = input.charCodeAt(i++);

              enc1 = chr1 >> 2;
              enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
              enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
              enc4 = chr3 & 63;

              if (isNaN(chr2)) {
                  enc3 = enc4 = 64;
              } else if (isNaN(chr3)) {
                  enc4 = 64;
              }

              output = output +
                  this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                  this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

          }

          return output;
      },

      // public method for decoding
      decode : function (input) {
          var output = "";
          var chr1, chr2, chr3;
          var enc1, enc2, enc3, enc4;
          var i = 0;

          input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

          while (i < input.length) {

              enc1 = this._keyStr.indexOf(input.charAt(i++));
              enc2 = this._keyStr.indexOf(input.charAt(i++));
              enc3 = this._keyStr.indexOf(input.charAt(i++));
              enc4 = this._keyStr.indexOf(input.charAt(i++));

              chr1 = (enc1 << 2) | (enc2 >> 4);
              chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
              chr3 = ((enc3 & 3) << 6) | enc4;

              output = output + String.fromCharCode(chr1);

              if (enc3 != 64) {
                  output = output + String.fromCharCode(chr2);
              }
              if (enc4 != 64) {
                  output = output + String.fromCharCode(chr3);
              }

          }

          output = Base64._utf8_decode(output);

          return output;

      },

      // private method for UTF-8 encoding
      _utf8_encode : function (string) {
          string = string.replace(/\r\n/g,"\n");
          var utftext = "";

          for (var n = 0; n < string.length; n++) {

              var c = string.charCodeAt(n);

              if (c < 128) {
                  utftext += String.fromCharCode(c);
              }
              else if((c > 127) && (c < 2048)) {
                  utftext += String.fromCharCode((c >> 6) | 192);
                  utftext += String.fromCharCode((c & 63) | 128);
              }
              else {
                  utftext += String.fromCharCode((c >> 12) | 224);
                  utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                  utftext += String.fromCharCode((c & 63) | 128);
              }

          }

          return utftext;
      },

      // private method for UTF-8 decoding
      _utf8_decode : function (utftext) {
          var string = "";
          var i = 0;
          var c = c1 = c2 = 0;

          while ( i < utftext.length ) {

              c = utftext.charCodeAt(i);

              if (c < 128) {
                  string += String.fromCharCode(c);
                  i++;
              }
              else if((c > 191) && (c < 224)) {
                  c2 = utftext.charCodeAt(i+1);
                  string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                  i += 2;
              }
              else {
                  c2 = utftext.charCodeAt(i+1);
                  c3 = utftext.charCodeAt(i+2);
                  string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                  i += 3;
              }

          }

          return string;
      }

    };

    return Base64;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/codec', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// auth: metagriffin <metagriffin@uberdev.org>
// date: 2012/10/13
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    _self;

_self = (function () {

    var exports = {};

    //---------------------------------------------------------------------------
    exports.Codec = common.Base.extend({

        encode: function(xtree, cb) {
            throw new common.NotImplementedError();
        },

        decode: function(contentType, data, cb) {
            throw new common.NotImplementedError();
        },
    }, {

        factory: function(codec) {
            // todo: should this be converted to callback-based?...
            if ( codec == constant.CODEC_XML )
        return new exports.XmlCodec()
        // TODO
        // if ( codec == constant.CODEC_WBXML )
        //   return exports.WbxmlCodec()
        throw new common.UnknownCodec('unknown or unimplemented codec "' + codec + '"')
        },

            autoEncode: function(xtree, codecName, cb) {
                exports.Codec.factory(codecName).encode(xtree, cb);
            },

            autoDecode: function(contentType, data, cb) {
                if ( contentType.indexOf(constant.TYPE_SYNCML + '+') != 0 )
                    return cb('unknown or unimplemented content type "' + contentType + '"');
                var ct = contentType.slice((constant.TYPE_SYNCML + '+').length).split(';')[0];
                exports.Codec.factory(ct).decode(contentType, data, function(err, tree) {
                    if ( err )
                    return cb(err);
                return cb(null, tree, ct);
                });
            },
    });

    //---------------------------------------------------------------------------
    exports.XmlCodec = exports.Codec.extend({

        name: constant.CODEC_XML,

        encode: function(xtree, cb) {
            // todo: really enforce this charset...
            var ctype = constant.TYPE_SYNCML + '+' + this.name + '; charset=UTF-8';
            var ret = ET.tostring(xtree);
            if ( ret.charAt(0) == '<' && ret.charAt(1) == '?' )
    {
        var idx = ret.indexOf('?>');
        if ( idx >= 0 )
        ret = ret.substr(0, idx + 2).replace(/'/g, '"') + ret.substr(idx + 2);
    }
    cb(null, ctype, ret);
        },

        decode: function(contentType, data, cb) {
            var expCT = constant.TYPE_SYNCML + '+' + this.name;
            if ( contentType.indexOf(expCT) != 0 )
        cb(new common.ProtocolError(
                'received unexpected content-type "' + contentType + '" (expected "'
                    + expCT + '")'));
            try
            {
                return cb(null, ET.parse(data).getroot());
            }
            catch(e)
            {
                return cb(new common.ProtocolError('could not parse XML: ' + e, e));
            }
        }

    });

    //---------------------------------------------------------------------------
    // TODO: implement wbxml...
    // exports.WbXmlCodec = exports.Codec.extend({
    //   encode: function(xtree, cb) {
    //   },
    //   decode: function(contentType, data, cb) {
    //   }
    // });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/common', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// auth: metagriffin <metagriffin@uberdev.org>
// date: 2012/10/13
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    _self;

_self = (function () {
    var exports = {};

    //---------------------------------------------------------------------------
    // object inheritance helper routines shamelessly scrubbed from backbone.js

    // The self-propagating extend function that Backbone classes use.
    var extend = exports.extend = function (protoProps, classProps) {
        var child = inherits(this, protoProps, classProps);
        child.extend = this.extend;
        return child;
    };

    // Shared empty constructor function to aid in prototype-chain creation.
    var ctor = function(){};

    // Helper function to correctly set up the prototype chain, for subclasses.
    // Similar to `goog.inherits`, but uses a hash of prototype properties and
    // class properties to be extended.
    var inherits = function(parent, protoProps, staticProps) {
        var child;

        // The constructor function for the new subclass is either defined by you
        // (the "constructor" property in your `extend` definition), or defaulted
        // by us to simply call the parent's constructor.
        if (protoProps && protoProps.hasOwnProperty('constructor')) {
            child = protoProps.constructor;
        } else {
            child = function(){ parent.apply(this, arguments); };
        }

        // Inherit class (static) properties from parent.
        _.extend(child, parent);

        // Set the prototype chain to inherit from `parent`, without calling
        // `parent`'s constructor function.
        ctor.prototype = parent.prototype;
        child.prototype = new ctor();

        // Add prototype properties (instance properties) to the subclass,
        // if supplied.
        if (protoProps) _.extend(child.prototype, protoProps);

        // Add static properties to the constructor function, if supplied.
        if (staticProps) _.extend(child, staticProps);

        // Correctly set child's `prototype.constructor`.
        child.prototype.constructor = child;

        // Set a convenience property in case the parent's prototype is needed later.
        child.__super__ = parent.prototype;

        return child;
    };

    //-----------------------------------------------------------------------------
    exports.Base = function() {};
    exports.Base.extend = extend;

    //-----------------------------------------------------------------------------
    var SyncmlError = exports.Base.extend({
        constructor: function(msg, exception, attrs) {
            this.message = this.name;
            if ( msg != undefined )
        this.message += ': ' + msg;
    this.exception = exception;
    if ( attrs )
        _.extend(this, attrs);
        },
        toString: function() {
            return this.message;
        }
    });

    //---------------------------------------------------------------------------
    exports.Stream = exports.Base.extend({

        writeln: function(data) {
            if ( data == undefined )
        return;
    return this.write(data + '\n');
        },

        indented: function(indent) {
            return new exports.IndentStream(this, indent || this._indent);
        }

    });

    _.extend(exports, {

        //---------------------------------------------------------------------------
        // exceptions
        SyncmlError:           SyncmlError.extend({name: 'SyncmlError'}),
        TypeError:             SyncmlError.extend({name: 'TypeError'}),
        NotImplementedError:   SyncmlError.extend({name: 'NotImplementedError'}),
        ProtocolError:         SyncmlError.extend({name: 'ProtocolError'}),
        InternalError:         SyncmlError.extend({name: 'InternalError'}),
        ConflictError:         SyncmlError.extend({name: 'ConflictError'}),
        FeatureNotSupported:   SyncmlError.extend({name: 'FeatureNotSupported'}),
        LogicalError:          SyncmlError.extend({name: 'LogicalError'}),
        CredentialsRequired:   SyncmlError.extend({name: 'CredentialsRequired'}),
        InvalidCredentials:    SyncmlError.extend({name: 'InvalidCredentials'}),
        InvalidContext:        SyncmlError.extend({name: 'InvalidContext'}),
        InvalidAdapter:        SyncmlError.extend({name: 'InvalidAdapter'}),
        InvalidStore:          SyncmlError.extend({name: 'InvalidStore'}),
        InvalidContentType:    SyncmlError.extend({name: 'InvalidContentType'}),
        InvalidAgent:          SyncmlError.extend({name: 'InvalidAgent'}),
        InvalidContent:        SyncmlError.extend({name: 'InvalidContent'}),
        InvalidItem:           SyncmlError.extend({name: 'InvalidItem'}),
        UnknownCodec:          SyncmlError.extend({name: 'UnknownCodec'}),
        NoSuchRoute:           SyncmlError.extend({name: 'NoSuchRoute'}),
        UnknownAuthType:       SyncmlError.extend({name: 'UnknownAuthType'}),
        UnknownFormatType:     SyncmlError.extend({name: 'UnknownFormatType'}),

        //---------------------------------------------------------------------------
        // UUID generation
        makeID: function() {
            // shamelessly scrubbed from:
            //   http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
            // (adjusted to remove the dashes)
            // todo: see some of those links on how to make this more "robust"...
            return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                return v.toString(16);
            });
        },

        //-------------------------------------------------------------------------
        synctype2alert: function(type) {
            return constant.SyncTypeToAlert[type];
        },

        //-------------------------------------------------------------------------
        alert2synctype: function(alert) {
            for ( var key in constant.SyncTypeToAlert )
            {
                if ( constant.SyncTypeToAlert[key] == alert )
                    return exports.int(key);
            }
            return null;
        },

        //-------------------------------------------------------------------------
        mode2string: function(code) {
            switch ( code )
            {
                case constant.ALERT_TWO_WAY:                       return 'two-way';
                case constant.ALERT_SLOW_SYNC:                     return 'slow-sync';
                case constant.ALERT_ONE_WAY_FROM_CLIENT:           return 'one-way-from-client';
                case constant.ALERT_REFRESH_FROM_CLIENT:           return 'refresh-from-client';
                case constant.ALERT_ONE_WAY_FROM_SERVER:           return 'one-way-from-server';
                case constant.ALERT_REFRESH_FROM_SERVER:           return 'refresh-from-server';
                case constant.ALERT_TWO_WAY_BY_SERVER:             return 'two-way-by-server';
                case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER: return 'one-way-from-client-by-server';
                case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER: return 'refresh-from-client-by-server';
                case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER: return 'one-way-from-server-by-server';
                case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER: return 'refresh-from-server-by-server';
                default: return 'UNKNOWN';
            }
        },

        //-------------------------------------------------------------------------
        state2string: function(state) {
            switch ( state )
            {
                case constant.ITEM_OK:           return 'ok';
                case constant.ITEM_ADDED:        return 'added';
                case constant.ITEM_MODIFIED:     return 'modified';
                case constant.ITEM_DELETED:      return 'deleted';
                case constant.ITEM_SOFTDELETED:  return 'soft-deleted';
                default: return 'UNKNOWN';
            }
        },

        //-------------------------------------------------------------------------
        oneWay: function(mode) {
            switch ( mode )
            {
                case constant.ALERT_TWO_WAY:
                case constant.ALERT_SLOW_SYNC:
                    return false;
                case constant.ALERT_ONE_WAY_FROM_CLIENT:
                case constant.ALERT_REFRESH_FROM_CLIENT:
                case constant.ALERT_ONE_WAY_FROM_SERVER:
                case constant.ALERT_REFRESH_FROM_SERVER:
                    return true;
                    // case constant.ALERT_TWO_WAY_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
                default:
                    throw new exports.InternalError('invalid mode "' + mode + '"');
            }
        },

        //-------------------------------------------------------------------------
        oneWayIn: function(session, mode) {
            switch ( mode )
            {
                case constant.ALERT_TWO_WAY:
                case constant.ALERT_SLOW_SYNC:
                    return false;
                case constant.ALERT_ONE_WAY_FROM_CLIENT:
                case constant.ALERT_REFRESH_FROM_CLIENT:
                    return !! session.isServer;
                case constant.ALERT_ONE_WAY_FROM_SERVER:
                case constant.ALERT_REFRESH_FROM_SERVER:
                    return ! session.isServer;
                    // case constant.ALERT_TWO_WAY_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
                default:
                    throw new exports.InternalError('invalid mode "' + mode + '"');
            }
        },

        //-------------------------------------------------------------------------
        oneWayOut: function(session, mode) {
            switch ( mode )
            {
                case constant.ALERT_TWO_WAY:
                case constant.ALERT_SLOW_SYNC:
                    return false;
                case constant.ALERT_ONE_WAY_FROM_CLIENT:
                case constant.ALERT_REFRESH_FROM_CLIENT:
                    return ! session.isServer;
                case constant.ALERT_ONE_WAY_FROM_SERVER:
                case constant.ALERT_REFRESH_FROM_SERVER:
                    return !! session.isServer;
                    // case constant.ALERT_TWO_WAY_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
                default:
                    throw new exports.InternalError('invalid mode "' + mode + '"');
            }
        },

        //-------------------------------------------------------------------------
        cascade: function(list, iterator, cb) {
            if ( ! cb && iterator )
            {
                cb = iterator;
                iterator = null;
            }
            if ( ! list )
                return cb();
            var cur = 0;
            var next = function() {
                if ( cur >= list.length )
                    return cb();
                var curcb = function(err) {
                    if ( err )
                        return cb(err);
                    cur += 1;
                    var args = [];
                    for ( var idx=1 ; idx<arguments.length ; idx++ )
                        args.push(arguments[idx]);
                    return next.apply(null, args);
                };
                var func = iterator || list[cur];
                var args = [];
                if ( iterator )
                    args.push(list[cur]);
                for ( var idx=0 ; idx<arguments.length ; idx++ )
                    args.push(arguments[idx]);
                args.push(curcb);
                return func.apply(null, args);
            };
            return next();
        },

        //-------------------------------------------------------------------------
        ts: function() {
            return Math.floor((new Date()).getTime() / 1000);
        },

        //-------------------------------------------------------------------------
        j: function(obj) {
            return JSON.stringify(obj);
        },

        //-------------------------------------------------------------------------
        noop: function(cb) {
            return cb();
        },

        //-------------------------------------------------------------------------
        platformBits: function() {

            // TODO: implement this!...

            return 32;
        },

        //-------------------------------------------------------------------------
        getMaxMemorySize: function(context) {

            // Returns the maximum size of a memory object. By default this
            // is, set to ``sys.maxint``, however the `context` may override
            // this behavior.

            // NOTE: currently, this is being hardcoded to a maximum of 2GB for
            //       compatibility with funambol servers, which croak above that
            //       value.

            // TODO: allow the context to control this, or implement auto-detect to
            //       determine what the remote peer can support...

            return Math.min(Math.pow(2, exports.platformBits() - 1) - 1,
                    Math.pow(2, 31) - 1);
        },

        //-------------------------------------------------------------------------
        normpath: function(path) {
            if ( path == undefined )
                return null;
            if ( path.length <= 0 )
                return '';
            if ( path.indexOf('/') < 0 )
                path = path.replace('\\', '/');
            var ret = [];
            var plist = path.split('/');
            for ( var idx=0 ; idx<plist.length ; idx++ )
            {
                var item = plist[idx];
                if ( item.length <= 0 || item == '.' )
                    continue;
                if ( item != '..' || ret.length <= 0 || ret[ret.length - 1] == '..' )
                {
                    ret.push(item);
                    continue;
                }
                ret.pop();
            }
            ret = ret.join('/');
            if ( path.charAt(0) != '/' )
                return ret;
            return '/' + ret;
        },

        //-------------------------------------------------------------------------
        int: function(str, defval) {
            if ( ! str )
                return defval;
            return parseInt(str, 10);
        },

        //-------------------------------------------------------------------------
        cmp: function(a, b) {
            if ( a < b )
                return -1;
            if ( a > b )
                return 1;
            return 0;
        },

        //-------------------------------------------------------------------------
        // partially emulates python's string.split() method
        splitn: function(str, sep, limit) {
            var ret = str.split(sep);
            if ( ret.length <= ( limit + 1 ) )
                return ret;
            var tmp = ret.slice(0, limit);
            tmp.push(ret.slice(limit).join(sep));
            return tmp;
        },

        //-------------------------------------------------------------------------
        prettyJson: function(obj, indent) {
            indent = indent || '';
            var ret = '';
            if ( _.isArray(obj) )
            {
                if ( obj.length <= 0 )
                    return '[]';
                ret = '[\n' + indent;
                _.each(obj, function(el, idx) {
                    ret += '  ' + exports.prettyJson(el, indent + '  ');
                    if ( idx + 1 < obj.length )
                    ret += ',';
                ret += '\n' + indent;
                });
                return ret + ']';
            }
            if ( _.isObject(obj) )
            {
                var keys = _.keys(obj);
                if ( keys.length <= 0 )
                    return '{}';
                keys.sort();
                ret = '{\n' + indent;
                    _.each(keys, function(key, idx) {
                        ret += '  ' + exports.prettyJson(key)
                        + ': ' + exports.prettyJson(obj[key], indent + '  ');
                    if ( idx + 1 < keys.length )
                        ret += ',';
                    ret += '\n' + indent;
                    });
                    return ret + ( indent.length <= 0 ? '}\n' : '}' );
            }
            return JSON.stringify(obj);
        },

        //-------------------------------------------------------------------------
        urlEncode: function(dat) {
            return ( dat == undefined ? dat : encodeURIComponent(dat) );
        },

        //-------------------------------------------------------------------------
        /*
           rmfr: function(path, cb) {
           fs.stat(path, function(err, stats) {
           if ( err && err.code == 'ENOENT' )
           return cb();
           if ( err )
           return cb(err);
           if ( ! stats.isDirectory() )
           return fs.unlink(path, cb);
           fs.readdir(path, function(err, files) {
           exports.cascade(files, function(file, cb) {
           var curpath = pathmod.join(path, file);
           return exports.rmfr(curpath, cb);
           }, function(err) {
           if ( err )
           return cb(err);
           fs.rmdir(path, cb);
           });
           });
           });
           },
           */
        //-------------------------------------------------------------------------
        /*
           makedirs: function(path, cb) {
        // node sucks. i can't believe it doesn't provide a fs.makedirs(). wtf.
        // clean up the path
        path = pathmod.normalize(path.split(/[\\\/]/).join('/'));
        var paths = path.split('/');
        paths = _.map(paths, function(p, idx) {
        return paths.slice(0, idx + 1).join('/');
        });
        if ( path.charAt(0) == '/' )
        paths.shift();
        exports.cascade(paths, function(path, cb) {
        fs.stat(path, function(err, stats) {
        if ( err && err.code == 'ENOENT' )
        return fs.mkdir(path, cb);
        if ( err )
        return cb(err);
        if ( stats.isDirectory() )
        return cb();
        // this probably won't work, but let's get the error anyhow...
        return fs.mkdir(path, cb);
        });
        }, cb);
        },
        */

        //-------------------------------------------------------------------------
        StringStream: exports.Stream.extend({

            constructor: function(initData) {
                this._data = initData || '';
            },

        write: function(data) {
            if ( data == undefined )
            return;
        this._data += data;
        },

        getData: function() {
            return this._data;
        }

        }),

        //-------------------------------------------------------------------------
        IndentStream: exports.Stream.extend({

            //-----------------------------------------------------------------------
            constructor: function(stream, indent, options) {
                options = options || {};
                this._stream    = stream;
                this._indent    = indent || '  ';
                this._cleared   = true;
                this._stayBlank = !! options.stayBlank;
            },

        //-----------------------------------------------------------------------
        write: function(data) {
            var self = this;
            if ( data == undefined )
            return;
        // if ( ! data || ! data.length || data.length <= 0 )
        //   return;
        var lines = data.split('\n');
        if ( self._cleared )
            self._stream.write(self._indent);
        self._cleared = false;
        for ( var idx=0 ; idx<lines.length ; idx++ )
        {
            var line = lines[idx];
            if ( line == '' )
            {
                if ( idx + 1 >= lines.length )
                    self._cleared = true;
                else
                {
                    if ( idx != 0 && ! self._stayBlank )
                        self._stream.write(self._indent);
                }
            }
            else
            {
                if ( idx != 0 || self._cleared )
                    self._stream.write(self._indent);
                self._stream.write(line);
            }
            if ( idx + 1 < lines.length )
                self._stream.write('\n');
        }
        }

        })

    });

    return exports;
})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/constant', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// desc: SyncML constants
// auth: metagriffin <metagriffin@uberdev.org>
// date: 2012/10/13
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var _self = {
    // SyncML versions
    SYNCML_VERSION_1_0                      : 'SyncML/1.0',
    SYNCML_VERSION_1_1                      : 'SyncML/1.1',
    SYNCML_VERSION_1_2                      : 'SyncML/1.2',
    SYNCML_DTD_VERSION_1_0                  : '1.0',
    SYNCML_DTD_VERSION_1_1                  : '1.1',
    SYNCML_DTD_VERSION_1_2                  : '1.2',

    // SyncML alert/sync codes
    ALERT_DISPLAY                           : 100,
    ALERT_TWO_WAY                           : 200,
    ALERT_SLOW_SYNC                         : 201,
    ALERT_ONE_WAY_FROM_CLIENT               : 202,
    ALERT_REFRESH_FROM_CLIENT               : 203,
    ALERT_ONE_WAY_FROM_SERVER               : 204,
    ALERT_REFRESH_FROM_SERVER               : 205,
    ALERT_TWO_WAY_BY_SERVER                 : 206,
    ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER     : 207,
    ALERT_REFRESH_FROM_CLIENT_BY_SERVER     : 208,
    ALERT_ONE_WAY_FROM_SERVER_BY_SERVER     : 209,
    ALERT_REFRESH_FROM_SERVER_BY_SERVER     : 210,
    // alert codes 211-220 are reserved for future use

    // SyncML SyncCap SyncTypes
    SYNCTYPE_AUTO                           : null,
    SYNCTYPE_TWO_WAY                        : 1,
    SYNCTYPE_SLOW_SYNC                      : 2,
    SYNCTYPE_ONE_WAY_FROM_CLIENT            : 3,
    SYNCTYPE_REFRESH_FROM_CLIENT            : 4,
    SYNCTYPE_ONE_WAY_FROM_SERVER            : 5,
    SYNCTYPE_REFRESH_FROM_SERVER            : 6,
    SYNCTYPE_SERVER_ALERTED                 : 7,

    // Special syncml-js SyncTypes
    SYNCTYPE_DISCOVER                       : 'discover',

    // SyncML synctype-to-alertcode mapping
    // taking advantage of the fact that 1..7 maps to 200..206
    // (more or less... "7" is a bit "nebulous"...)
    SyncTypeToAlert: _.object(_.map(_.range(7), function(i) {
        return [ i + 1, i + 200 ];
    })),

    // Conflict handling policies
    POLICY_ERROR                            : 1,
    POLICY_CLIENT_WINS                      : 2,
    POLICY_SERVER_WINS                      : 3,

    // SyncML XML namespaces
    NAMESPACE_SYNCML_1_0                    : 'syncml:syncml1.0',
    NAMESPACE_SYNCML_1_1                    : 'syncml:syncml1.1',
    NAMESPACE_SYNCML_1_2                    : 'syncml:syncml1.2',
    NAMESPACE_METINF                        : 'syncml:metinf',
    NAMESPACE_DEVINF                        : 'syncml:devinf',
    NAMESPACE_AUTH_BASIC                    : 'syncml:auth-basic',
    NAMESPACE_AUTH_MD5                      : 'syncml:auth-md5',
    NAMESPACE_FILTER_CGI                    : 'syncml:filtertype-cgi',

    // Commonly used content-types
    TYPE_TEXT_PLAIN                         : 'text/plain',
    TYPE_VCARD_V21                          : 'text/x-vcard',
    TYPE_VCARD_V30                          : 'text/vcard',
    TYPE_VCALENDAR                          : 'text/x-vcalendar',
    TYPE_ICALENDAR                          : 'text/calendar',
    TYPE_MESSAGE                            : 'text/message',
    TYPE_SYNCML                             : 'application/vnd.syncml',
    TYPE_SYNCML_DEVICE_INFO                 : 'application/vnd.syncml-devinf',
    TYPE_SYNCML_ICALENDAR                   : 'application/vnd.syncml-xcal',
    TYPE_SYNCML_EMAIL                       : 'application/vnd.syncml-xmsg',
    TYPE_SYNCML_BOOKMARK                    : 'application/vnd.syncml-xbookmark',
    TYPE_SYNCML_RELATIONAL_OBJECT           : 'application/vnd.syncml-xrelational',
    TYPE_OMADS_FOLDER                       : 'application/vnd.omads-folder',
    TYPE_OMADS_FILE                         : 'application/vnd.omads-file',
    TYPE_OMADS_EMAIL                        : 'application/vnd.omads-email',
    TYPE_SQL                                : 'application/sql',
    TYPE_LDAP                               : 'text/directory',
    TYPE_EMAIL                              : 'message/rfc2822',
    TYPE_EMAIL_822                          : 'message/rfc822',
    TYPE_SIF_CONTACT                        : 'text/x-s4j-sifc',
    TYPE_SIF_NOTE                           : 'text/x-s4j-sifn',
    TYPE_SIF_TASK                           : 'text/x-s4j-sift',
    TYPE_SIF_EVENT                          : 'text/x-s4j-sife',

    // non-agent URI paths
    URI_DEVINFO_1_0                         : 'devinf10',
    URI_DEVINFO_1_1                         : 'devinf11',
    URI_DEVINFO_1_2                         : 'devinf12',

    // Response codes - Generic
    STATUS_INVALID_CODE                     : 0,
    // Response codes - Informational 1xx
    STATUS_IN_PROGRESS                      : 101,
    // Response codes - Successful 2xx
    STATUS_OK                               : 200,
    STATUS_ITEM_ADDED                       : 201,
    STATUS_ACCEPTED_FOR_PROCESSING          : 202,
    STATUS_NONAUTHORIATATIVE_RESPONSE       : 203,
    STATUS_NO_CONTENT                       : 204,
    STATUS_RESET_CONTENT                    : 205,
    STATUS_PARTIAL_CONTENT                  : 206,
    STATUS_CONFLICT_RESOLVED_MERGE          : 207,
    STATUS_CONFLICT_RESOLVED_CLIENT_DATA    : 208,
    STATUS_CONFLICT_RESOLVED_DUPLICATE      : 209,
    STATUS_DELETE_WITHOUT_ARCHIVE           : 210,
    STATUS_ITEM_NOT_DELETED                 : 211,
    STATUS_AUTHENTICATION_ACCEPTED          : 212,
    STATUS_CHUNKED_ITEM_ACCEPTED            : 213,
    STATUS_OPERATION_CANCELLED_OK           : 214,
    STATUS_NOT_EXECUTED                     : 215,
    STATUS_ATOMIC_ROLLBACK_OK               : 216,
    STATUS_RESULT_ALERT                     : 221,
    STATUS_NEXT_MESSAGE                     : 222,
    STATUS_NO_END_OF_DATA                   : 223,
    STATUS_SUSPEND                          : 224,
    STATUS_RESUME                           : 225,
    STATUS_DATA_MANAGEMENT                  : 226,
    // status codes 227-250 are reserved for future use,
    // Response codes - Redirection 3xx
    STATUS_MULTIPLE_CHOICES                 : 300,
    STATUS_MOVED_PERMANENTLY                : 301,
    STATUS_FOUND                            : 302,
    STATUS_SEE_ANOTHER_URI                  : 303,
    STATUS_NOT_MODIFIED                     : 304,
    STATUS_USE_PROXY                        : 305,
    // Response codes - Originator Exceptions 4xx
    STATUS_BAD_REQUEST                      : 400,
    STATUS_INVALID_CREDENTIALS              : 401,
    STATUS_PAYMENT_REQUIRED                 : 402,
    STATUS_FORBIDDEN                        : 403,
    STATUS_NOT_FOUND                        : 404,
    STATUS_COMMAND_NOT_ALLOWED              : 405,
    STATUS_OPTIONAL_FEATURE_NOT_SUPPORTED   : 406,
    STATUS_MISSING_CREDENTIALS              : 407,
    STATUS_REQUEST_TIMEOUT                  : 408,
    STATUS_UPDATE_CONFLICT                  : 409,
    STATUS_GONE                             : 410,
    STATUS_SIZE_REQUIRED                    : 411,
    STATUS_INCOMPLETE_COMMAND               : 412,
    STATUS_REQUESTED_ENTITY_TOO_LARGE       : 413,
    STATUS_URI_TOO_LONG                     : 414,
    STATUS_UNSUPPORTED_MEDIA_TYPE           : 415,
    STATUS_REQUESTED_SIZE_TOO_BIG           : 416,
    STATUS_RETRY_LATER                      : 417,
    STATUS_ALREADY_EXISTS                   : 418,
    STATUS_CONFLICT_RESOLVED_SERVER_DATA    : 419,
    STATUS_DEVICE_FULL                      : 420,
    STATUS_UNKNOWN_SEARCH_GRAMMAR           : 421,
    STATUS_BAD_CGI_SCRIPT                   : 422,
    STATUS_SOFT_DELETE_CONFLICT             : 423,
    STATUS_OBJECT_SIZE_MISMATCH             : 424,
    STATUS_PERMISSION_DENIED                : 425,
    // Response codes - Recipient Exceptions 5xx
    STATUS_COMMAND_FAILED                   : 500,
    STATUS_NOT_IMPLEMENTED                  : 501,
    STATUS_BAD_GATEWAY                      : 502,
    STATUS_SERVICE_UNAVAILABLE              : 503,
    STATUS_GATEWAY_TIMEOUT                  : 504,
    STATUS_VERSION_NOT_SUPPORTED            : 505,
    STATUS_PROCESSING_ERROR                 : 506,
    STATUS_ATOMIC_FAILED                    : 507,
    STATUS_REFRESH_REQUIRED                 : 508,
    STATUS_RECIPIENT_EXCEPTION_RESERVED1    : 509,
    STATUS_DATASTORE_FAILURE                : 510,
    STATUS_SERVER_FAILURE                   : 511,
    STATUS_SYNCHRONIZATION_FAILED           : 512,
    STATUS_PROTOCOL_VERSION_NOT_SUPPORTED   : 513,
    STATUS_OPERATION_CANCELLED              : 514,
    STATUS_ATOMIC_ROLLBACK_FAILED           : 516,
    STATUS_ATOMIC_RESPONSE_TOO_LARGE_TO_FIT : 517,

    // SyncML codecs
    CODEC_XML                               : 'xml',
    CODEC_WBXML                             : 'wbxml',
    FORMAT_B64                              : 'b64',
    FORMAT_AUTO                             : 'auto',

    // SyncML nodes
    NODE_SYNCML                             : 'SyncML',
    NODE_SYNCBODY                           : 'SyncBody',

    // SyncML commands
    CMD_SYNCHDR                             : 'SyncHdr',
    CMD_SYNC                                : 'Sync',
    CMD_ALERT                               : 'Alert',
    CMD_STATUS                              : 'Status',
    CMD_GET                                 : 'Get',
    CMD_PUT                                 : 'Put',
    CMD_ADD                                 : 'Add',
    CMD_REPLACE                             : 'Replace',
    CMD_DELETE                              : 'Delete',
    CMD_RESULTS                             : 'Results',
    CMD_ATOMIC                              : 'Atomic',
    CMD_COPY                                : 'Copy',
    CMD_EXEC                                : 'Exec',
    CMD_MAP                                 : 'Map',
    CMD_MAPITEM                             : 'MapItem',
    CMD_SEARCH                              : 'Search',
    CMD_SEQUENCE                            : 'Sequence',
    CMD_FINAL                               : 'Final',

    // SyncML standard device types
    DEVTYPE_HANDHELD                        : 'handheld',
    DEVTYPE_PAGER                           : 'pager',
    DEVTYPE_PDA                             : 'pda',
    DEVTYPE_PHONE                           : 'phone',
    DEVTYPE_SERVER                          : 'server',
    DEVTYPE_SMARTPHONE                      : 'smartphone',
    DEVTYPE_WORKSTATION                     : 'workstation',

    // Item status codes
    ITEM_OK                                 : 0,
    ITEM_ADDED                              : 1,
    ITEM_MODIFIED                           : 2,
    ITEM_DELETED                            : 3,
    ITEM_SOFTDELETED                        : 4,
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/context', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.context
// auth: griffin <griffin@uberdev.org>
// date: 2012/10/22
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
    router = require('ripple/platform/tizen/2.0/syncml-js-lib/router'),
    synchronizer = require('ripple/platform/tizen/2.0/syncml-js-lib/synchronizer'),
    protocol = require('ripple/platform/tizen/2.0/syncml-js-lib/protocol'),
    localadapter = require('ripple/platform/tizen/2.0/syncml-js-lib/localadapter'),
    idxdb = {},
    _self;

// todo: is this the right place to put this?...
//       the reason that i did not put it in the `define` call is
//       because it needs access to `this.indexedDB`...
var idxdb = {};
if ( typeof(window) != 'undefined' && window.indexedDB )
{
    idxdb.indexedDB   = window.indexedDB;
    idxdb.IDBKeyRange = window.IDBKeyRange;
}
else
{
    idxdb.indexedDB   = this.indexedDB;
    idxdb.IDBKeyRange = this.IDBKeyRange;
}

_self = (function () {
    var exports = {};

    //---------------------------------------------------------------------------
    exports.Context = common.Base.extend({

        //-------------------------------------------------------------------------
        constructor: function(options) {
            // options.storage expects the following properties:
            //   - indexedDB
            //   - IDBKeyRange
            options = options || {};
            this.storage      = options.storage || idxdb;
            this.dbname       = ( options.prefix || '' ) + 'syncml-js';
            this.autoCommit   = options.autoCommit == undefined ? true : options.autoCommit;
            this.router       = options.router || new router.SmartRouter();
            this.synchronizer = options.synchronizer || new synchronizer.Synchronizer();
            this.protocol     = options.protocol || new protocol.Protocol();
            this.codec        = options.codec || constant.CODEC_XML;
            this.listener     = options.listener;
            this.ua           = options.ua;
            this.config       = _.defaults({}, options.config, {
                trustDevInfo      : false,
                exposeErrorTrace  : false
            });
            this._db          = null;
            this._dbtxn       = null;
        },

            //-------------------------------------------------------------------------
            getAdapter: function(options, devInfo, cb) {
                options = options || {};
                var self = this;
                if ( this._db == undefined )
                {
                    storage.openDatabase(this, function(err, db) {
                        if ( err ) {
                            return cb(err);
                        }
                        self._db = db;
                        self._db.onerror = function(event) {
                            // todo: remove this?...
                        };
                        self._dbtxn = storage.getTransaction(self._db, null, 'readwrite');
                        self.getAdapter(options, devInfo, cb);
                    });
                }
                else
                {
                    var ret = new localadapter.LocalAdapter(this, options, devInfo);
                    return ret._load(cb);
                }
            },

            //-------------------------------------------------------------------------
            _txn: function() {
                try {
                    // this is a work-around for XPC-based syncml... try to open
                    // a store, if it fails, we need a new transaction.
                    var store = this._dbtxn.objectStore('mapping');
                    return this._dbtxn;
                } catch ( exc ) {
                    this._dbtxn = storage.getTransaction(this._db, null, 'readwrite');
                    return this._dbtxn;
                }
            },

            //-------------------------------------------------------------------------
            getEasyClientAdapter: function(options, cb) {
                try{
                    this._getEasyClientAdapter(options, cb);
                }catch(e){
                    cb(e);
                }
            },

            //-------------------------------------------------------------------------
            _getEasyClientAdapter: function(options, cb) {
                // options should be:= {
                //   // devID,
                //   // displayName,
                //   devInfo: {},
                //   stores: [],
                //   peer: {},
                //   routes: [
                //     [ source, target ],
                //   ]
                // }
                // response: cb(err, adapter, stores, peer);

                var self = this;

                var ret = {
                    adapter: null,
                    stores: [],
                    peer: null
                };

                var setupAdapter = function(cb) {
                    var adapterOptions = _.omit(options, 'devInfo', 'stores', 'peers', 'routes');
                    self.getAdapter(adapterOptions, options.devInfo, function(err, adapter) {
                        if ( err ) {
                            return cb(err);
                        }
                        ret.adapter = adapter;
                        if ( adapter.devInfo ) {
                            return cb();
                        }
                        adapter.setDevInfo(options.devInfo, cb);
                    });
                };

                var setupStores = function(cb) {
                    common.cascade(options.stores, function(storeInfo, cb) {
                        var store = ret.adapter.getStore(storeInfo.uri);
                        if ( store != undefined )
                        {
                            if ( storeInfo.agent ) {
                                store.agent = storeInfo.agent;
                            }
                            ret.stores.push(store);
                            return cb();
                        }
                        ret.adapter.addStore(storeInfo, function(err, store) {
                            if ( err ) {
                                return cb(err);
                            }
                            ret.stores.push(store);
                            return cb();
                        });
                    }, cb);
                };

                var setupPeer = function(cb) {
                    var peer = _.find(ret.adapter.getPeers(), function(p) {
                        return p.url == options.peer.url;
                    });
                    if ( peer )
                    {
                        ret.peer = peer;
                        return cb();
                    }
                    ret.adapter.addPeer(options.peer, function(err, peer) {
                        if ( err ) {
                            return cb(err);
                        }
                        ret.peer = peer;
                        common.cascade(options.routes, function(route, cb) {
                            ret.peer.setRoute(route[0], route[1], cb);
                        }, cb);
                    });
                };
                setupAdapter(function(err) {
                    if ( err ) {
                        return cb(err);
                    }
                    setupStores(function(err) {
                        if ( err ) {
                            return cb(err);
                        }
                        setupPeer(function(err) {
                            if ( err ) {
                                return cb(err);
                            }
                            cb(null, ret.adapter, ret.stores, ret.peer);
                        });
                    });
                });
            },

            //-------------------------------------------------------------------------
            close: function(cb) {
                if ( this._db )
                    this._db.close();
                this._db = null;
                cb(null);
            }

    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/ctype', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// auth: metagriffin <metagriffin@uberdev.org>
// date: 2012/10/13
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------
var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
    _self;

_self = (function () {

    var exports = {};

    //---------------------------------------------------------------------------
    exports.ContentTypeInfo = common.Base.extend({

        //-------------------------------------------------------------------------
        constructor: function(ctype, versions, options) {
            this.ctype    = ctype;
            this.versions = _.isArray(versions) ? versions : [versions];
            _.defaults(this, options || {}, {
                preferred: false,
                transmit:  true,
                receive:   true,
            });
        },

        //-------------------------------------------------------------------------
        merge: function(other) {
            if ( this.ctype != other.ctype
                || ! _.isEqual(this.versions, other.versions)
                || this.preferred != other.preferred )
                return false;
            this.transmit = this.transmit || other.transmit;
            this.receive  = this.receive  || other.receive;
            return true
        },

        //-------------------------------------------------------------------------
        toStruct: function() {
            return {
                ctype: this.ctype,
                versions: this.versions,
                preferred: this.preferred,
                transmit:  this.transmit,
                receive:   this.receive
            };
        },

        //-------------------------------------------------------------------------
        toSyncML: function(nodeName, uniqueVerCt) {
            if ( _.isFunction(nodeName) )
            {
                cb = nodeName;
                nodeName = null;
            }
            else if ( _.isFunction(uniqueVerCt) )
            {
                cb = uniqueVerCt;
                uniqueVerCt = null;
            }
            if ( ! nodeName )
            {
                nodeName = this.transmit ? 'Tx' : 'Rx';
                if ( this.preferred )
                    nodeName += '-Pref';
            }
            if ( this.preferred )
                nodeName += '-Pref';

            if ( uniqueVerCt )
            {
                var ret = _.map(this.versions, function(v) {
                    var tmp = ET.Element(nodeName);
                    ET.SubElement(tmp, 'CTType').text = this.ctype;
                    ET.SubElement(tmp, 'VerCT').text = v;
                    return tmp;
                }, this);
                return ret;
            }
            var ret = ET.Element(nodeName);
            ET.SubElement(ret, 'CTType').text = this.ctype;
            _.each(this.versions, function(v) {
                ET.SubElement(ret, 'VerCT').text = v;
            });
            return ret;
        },

        describe: function(stream, cb) {
            stream.write(this.ctype);
            stream.write(this.versions.length == 1 ? ' version ' : ' versions ');
            stream.write(this.versions.join(', '));
            var flags = [];
            if ( this.preferred )
                flags.push('preferred');
            if ( this.transmit )
                flags.push('tx');
            if ( this.receive )
                flags.push('rx');
            if ( flags.length > 0 )
            {
                stream.write(' (');
                        stream.write(flags.join(', '));
                        stream.write(')');
                        }
                        stream.write('\n');
                        }

                        }, {

                            //-------------------------------------------------------------------------
                            fromStruct: function(struct) {
                                return new exports.ContentTypeInfo(struct.ctype, struct.versions, struct);
                            },

                    //-------------------------------------------------------------------------
                    fromSyncML: function(xnode) {
                        return new exports.ContentTypeInfo(
                            xnode.findtext('CTType'),
                            _.map(xnode.findall('VerCT'), function(e) { return e.text; }),
                            {
                                preferred: xnode.tag.match('-Pref$') != undefined,
                        transmit:  xnode.tag.indexOf('Tx') >= 0,
                        receive:   xnode.tag.indexOf('Rx') >= 0
                            }
                            );
                    }

                        });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/devinfo', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.devinfo
// auth: griffin <griffin@uberdev.org>
// date: 2012/11/06
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
    ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
    _self;

_self = (function () {

    var exports = {};

    var strAttributeMap = [
    ['manufacturerName',    'Man'],
      ['modelName',           'Mod'],
      ['oem',                 'OEM'],
      ['firmwareVersion',     'FwV'],
      ['softwareVersion',     'SwV'],
      ['hardwareVersion',     'HwV'],
      ['devID',               'DevID'],
      ['devType',             'DevTyp']
    ];

var boolAttributeMap = [
    ['utc',                 'UTC'],
      ['largeObjects',        'SupportLargeObjs'],
      ['hierarchicalSync',    'SupportHierarchicalSync'],
      ['numberOfChanges',     'SupportNumberOfChanges']
    ];

//---------------------------------------------------------------------------
exports.DevInfo = common.Base.extend({

    //-------------------------------------------------------------------------
    constructor: function(adapter, options) {
        var self = this;
        var options = _.defaults({}, options, {
            devType           : constant.DEVTYPE_WORKSTATION,
            manufacturerName  : '-',
            modelName         : '-',
            oem               : '-',
            hardwareVersion   : '-',
            firmwareVersion   : '-',
            softwareVersion   : '-',
            utc               : true,
            largeObjects      : true,
            hierarchicalSync  : true,
            numberOfChanges   : true,
            extensions        : {}
        });

        // todo: is there anyway to mark attributes as read-only?...

        //: [read-only] these are all read-only attributes
        this.devID            = options.devID || common.makeID();
        this.devType          = options.devType;
        this.manufacturerName = options.manufacturerName;
        this.modelName        = options.modelName;
        this.oem              = options.oem;
        this.hardwareVersion  = options.hardwareVersion;
        this.firmwareVersion  = options.firmwareVersion;
        this.softwareVersion  = options.softwareVersion;
        this.utc              = options.utc;
        this.largeObjects     = options.largeObjects;
        this.hierarchicalSync = options.hierarchicalSync;
        this.numberOfChanges  = options.numberOfChanges;
        this.extensions       = {};

        _.each(options.extensions, function(values, name) {
            self.setExtension(name, values);
        });

        // --- private attributes
        this._a       = adapter;
    },

        //-------------------------------------------------------------------------
        setExtension: function(name, values) {
            this.extensions[name] = _.isArray(values) ? values : [values];
        },

        //-------------------------------------------------------------------------
        getExtensionKeys: function() {
            return _.keys(this.extensions);
        },

        //-------------------------------------------------------------------------
        getExtension: function(name) {
            return this.extensions[name];
        },

        //-------------------------------------------------------------------------
        _load: function(cb) {
            cb();
        },

        //-------------------------------------------------------------------------
        _updateModel: function(cb) {
            if ( ! this._a._model )
                return cb('devinfo created on un-initialized adapter');
            this._a._model.devInfo = {
                devID            : this.devID,
                devType          : this.devType,
                manufacturerName : this.manufacturerName,
                modelName        : this.modelName,
                oem              : this.oem,
                hardwareVersion  : this.hardwareVersion,
                firmwareVersion  : this.firmwareVersion,
                softwareVersion  : this.softwareVersion,
                utc              : this.utc,
                largeObjects     : this.largeObjects,
                hierarchicalSync : this.hierarchicalSync,
                numberOfChanges  : this.numberOfChanges,
                extensions       : this.extensions
            };
            cb();
        },

        //-------------------------------------------------------------------------
        toSyncML: function(dtdVersion, stores) {
            dtdVersion = dtdVersion || constant.SYNCML_DTD_VERSION_1_2;
            if ( dtdVersion != constant.SYNCML_DTD_VERSION_1_2 )
                throw new Error('unsupported DTD version "' + dtdVersion + '"')
                    var xret = ET.Element('DevInf', {'xmlns': constant.NAMESPACE_DEVINF})
                    ET.SubElement(xret, 'VerDTD').text = dtdVersion;
            for ( var idx=0 ; idx<strAttributeMap.length ; idx++ )
            {
                var map = strAttributeMap[idx];
                // todo: should i enforce the fact that these are all *required*?...
                if ( this[map[0]] != undefined )
                    ET.SubElement(xret, map[1]).text = this[map[0]];
            }
            for ( var idx=0 ; idx<boolAttributeMap.length ; idx++ )
            {
                var map = boolAttributeMap[idx];
                if ( this[map[0]] )
                    ET.SubElement(xret, map[1])
            }
            if ( stores && stores.length > 0 )
                for ( var idx=0 ; idx<stores.length ; idx++ )
                    xret.append(stores[idx].toSyncML());
            var xext = null;
            for ( var name in this.extensions )
            {
                if ( ! xext )
                    xext = ET.SubElement(xret, 'Ext');
                ET.SubElement(xext, 'XNam').text = name;
                var values = this.extensions[name];
                for ( var idx=0 ; idx<values.length ; idx++ )
                    ET.SubElement(xext, 'XVal').text = '' + values[idx];
            };
            return xret;
        },

}, {

    //-------------------------------------------------------------------------
    fromSyncML: function(xnode) {
        var options = {};
        var stores  = []
            var dtdVersion = xnode.findtext('VerDTD')
            if ( dtdVersion != constant.SYNCML_DTD_VERSION_1_2 )
                throw new common.ProtocolError('unsupported DTD version "' + dtdVersion + '"');
        for ( var idx=0 ; idx<strAttributeMap.length ; idx++ )
        {
            var map = strAttributeMap[idx];
            // todo: should i enforce the fact that these are all *required*?...
            options[map[0]] = xnode.findtext(map[1]);
        }
        for ( var idx=0 ; idx<boolAttributeMap.length ; idx++ )
        {
            var map = boolAttributeMap[idx];
            options[map[0]] = xnode.find(map[1]) != undefined;
        }
        _.each(xnode.getchildren(), function(child) {
            if ( child.tag == 'DataStore' )
            return stores.push(storemod.Store.fromSyncML(child));
        if ( child.tag == 'Ext' )
        {
            options.extensions = {};
            var elist = child.getchildren();
            var ecur  = null;
            for ( var idx=0 ; idx<elist.length ; idx++ )
        {
            var eitem = elist[idx];
            if ( eitem.tag == 'XNam' )
        {
            ecur = eitem.text;
            continue;
        }
        if ( ! ecur )
            // paranoia...
            continue;
        if ( ! options.extensions[ecur] )
            options.extensions[ecur] = [];
        options.extensions[ecur].push(eitem.text);
        }
        return;
        }
        });
        return [new exports.DevInfo(null, options), stores];
    }

});

return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/elementtree', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation
 *
 * 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 utils = require('ripple/utils'),
    _parser,
    _serializer,
    _self;

function _find(query, element, type) {
    var querylist = query.split("/"),
        e = element._node,
        tag, i, ret;

    if (querylist.length === 0) {
        return undefined;
    }

    for(i = 0; i < querylist.length; i++) {
        tag = querylist[i];
        try {
            e = e.getElementsByTagName(tag)[0];
        } catch (error) {
            e = undefined;
            break;
        }
    }

    if (e) {
        if (type === "TEXT") {
            return e.textContent;
        } else if (type === "NODE") {
            ret = {
                _doc: element,
                _node: e,
                find: function (query) {
                    return _find(query, this, "NODE");
                },
                findtext: function (query) {
                    return _find(query, this, "TEXT");
                },
                findall: function (query) {
                    return _findall(query, this);
                },
                getchildren: function () {
                    return _getchildren(this);
                },
                append: function (node) {
                    this._node.appendChild(node._node);
                },
                getroot: function () {
                    return this;
                }
            };
            ret.__defineSetter__("text", function (text) {
                this._node.textContent = text;
            });
            ret.__defineGetter__("text", function () {
                return this._node.textContent;
            });
            ret.__defineGetter__("tag", function () {
                return _tag(this);
            });
            return ret;
        }
    } else {
        return undefined;
    }
}

function _findall(query, element) {
    var querylist = query.split("/"),
        e = element._node,
        tag,
        array,
        tmp,
        ret = [],
        i;

    for(i = 0; i < querylist.length - 1; i++) {
        tag = querylist[i];
        try {
            e = e.getElementsByTagName(tag)[0];
        } catch (error) {
            return ret;
        }
    }

    tag = querylist[querylist.length - 1];
    array = e.getElementsByTagName(tag);
    ///return ret;
    for(i = 0; i < array.length; i++) {
        tmp = {
            _doc: element,
            _node: array[i],
            find: function (query) {
                return _find(query, this, "NODE");
            },
            findtext: function (query) {
                return _find(query, this, "TEXT");
            },
            findall: function (query) {
                return _findall(query, this);
            },
            getchildren: function () {
                return _getchildren(this);
            },
            append: function (node) {
                this._node.appendChild(node._node);
            },
            getroot: function () {
                return this;
            }
        };
        tmp.__defineSetter__("text", function (text) {
            this._node.textContent = text;
        });
        tmp.__defineGetter__("text", function () {
            return this._node.textContent;
        });
        tmp.__defineGetter__("tag", function () {
            return _tag(this);
        });
        ret.push(tmp);
    }
    return ret;
}

function _tag(element) {
    var array;
    array = element._node.tagName.split(":");
    return array[array.length - 1];
}

function _getchildren(element) {
    var ret = [], e, i;
    for (i = 0; i < element._node.childNodes.length; i++) {
        e = {
            _doc: element,
            _node: element._node.childNodes[i],
            find: function (query) {
                return _find(query, this, "NODE");
            },
            findtext: function (query) {
                return _find(query, this, "TEXT");
            },
            findall: function (query) {
                return _findall(query, this);
            },
            getchildren: function () {
                return _getchildren(this);
            },
            append: function (node) {
                this._node.appendChild(node._node);
            },
            getroot: function () {
                return this;
            }
        };
        e.__defineSetter__("text", function (text) {
            this._node.textContent = text;
        });
        e.__defineGetter__("text", function () {
            return this._node.textContent;
        });
        e.__defineGetter__("tag", function () {
            return _tag(this);
        });
        ret.push(e);
    }

    return ret;
}


_self = (function () {
    ET = {};

    ET.Element = function(name, attributes) {
        var element = {},
            doc,
            node;

        doc = _parser.parseFromString("<" + name + "></" + name + ">", "text/xml");
        node = doc.childNodes[0];
        if (attributes) {
            utils.forEach(attributes, function (value, key) {
                node.setAttribute(key, value);
            });
        }

        element = {
            _doc: doc,
            _node: node,
            find: function (query) {
                return _find(query, this, "NODE");
            },
            findtext: function (query) {
                return _find(query, this, "TEXT");
            },
            findall: function (query) {
                return _findall(query, this);
            },
            getchildren: function () {
                return _getchildren(this);
            },
            append: function (node) {
                this._node.appendChild(node._node);
            },
            getroot: function () {
                return this;
            }
        };

        element.__defineSetter__("text", function (text) {
            this._node.textContent = text;
        });

        element.__defineGetter__("text", function () {
            return this._node.textContent;
        });

        element.__defineGetter__("tag", function () {
            return _tag(this);
        });

        return element;
    };

    ET.SubElement = function(element, name, attributes) {
        var subElement = {},
            node;
        node = element._doc.createElement(name);
        if (attributes) {
            utils.forEach(attributes, function (value, key) {
                node.setAttribute(key, value);
            });
        }
        element._node.appendChild(node);
        subElement = {
            _doc: element._doc,
            _node: node,
            find: function (query) {
                return _find(query, this, "NODE");
            },
            findtext: function (query) {
                return _find(query, this, "TEXT");
            },
            findall: function (query) {
                return _findall(query, this);
            },
            getchildren: function () {
                return _getchildren(this);
            },
            append: function (node) {
                this._node.appendChild(node._node);
            },
            getroot: function () {
                return this;
            }
        };
        subElement.__defineSetter__("text", function (text) {
            this._node.textContent = text;
        });
        subElement.__defineGetter__("text", function () {
            return this._node.textContent;
        });
        subElement.__defineGetter__("tag", function () {
            return _tag(this);
        });

        return subElement;
    };

    ET.tostring = function(element) {
        return _serializer.serializeToString(element._node);
    };
    ET.parse = function(doc) {
        var element = {};

        element = {
            _doc: doc,
            _node: doc.childNodes[0],
            find: function (query) {
                return _find(query, this, "NODE");
            },
            findtext: function (query) {
                return _find(query, this, "TEXT");
            },
            findall: function (query) {
                return _findall(query, this);
            },
            getchildren: function () {
                return _getchildren(this);
            },
            append: function (node) {
                this._node.appendChild(node._node);
            },
            getroot: function () {
                return this;
            }
        };
        element.__defineSetter__("text", function (text) {
            this._node.textContent = text;
        });
        element.__defineGetter__("text", function () {
            return this._node.textContent;
        });
        element.__defineGetter__("tag", function () {
            return _tag(this);
        });

        return element;
    };

    ET.CdataElement = function(str) {
        var doc, cdata;
        doc = _parser.parseFromString("<data></data>", "text/xml");
        cdata = doc.createCDATASection(str);
        return cdata;
    };

    return ET;
})();

_parser = new DOMParser();
_serializer = new XMLSerializer();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/item', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.item
// auth: griffin <griffin@uberdev.org>
// date: 2012/11/30
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common');

var _self = (function () {
    var exports = {};

    //---------------------------------------------------------------------------
    exports.Item = common.Base.extend({

        //: the unique identifier (within the context of a SyncML datastore)
        //: of the current SyncML item.
        id: null,

        compare: function(other) {
            return ( other === this ? 0 : 1 );
        }

    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/localadapter', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.localadapter
// auth: griffin <griffin@uberdev.org>
// date: 2012/10/22
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    codec = require('ripple/platform/tizen/2.0/syncml-js-lib/codec'),
    storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
    remote = require('ripple/platform/tizen/2.0/syncml-js-lib/remoteadapter'),
    storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
    devinfomod = require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
    adapter = require('ripple/platform/tizen/2.0/syncml-js-lib/adapter'),
    state = require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
    useragent = require('ripple/platform/tizen/2.0/syncml-js-lib/useragent'),
    _self;

_self = (function () {
    var exports = {};

    //---------------------------------------------------------------------------
    exports.LocalAdapter = adapter.Adapter.extend({

        //-------------------------------------------------------------------------
        constructor: function(context, options, devInfo) {

            // todo: is there anyway to mark attributes as read-only?...

            //: [read-only] devInfo describes this adapter's device info and
            //: capabilities.
            this.devInfo = null;

            //: [read-only] the device ID of this adapter.
            this.devID = options.devID || null;

            //: [read-only] specifies whether this Adapter represents a local
            //: or remote peer.
            this.isLocal = true;

            //: [read-only] human-facing name of this adapter
            this.displayName = options.displayName || null;

            //: [read-only] the adapter-wide default value of the maximum
            //: message size.
            this.maxMsgSize = options.maxMsgSize || null;

            //: [read-only] the adapter-wide default value of the maximum
            //: object size.
            this.maxObjSize = options.maxObjSize || null;

            //: [read-only] specifies default conflict resolution policy for
            //: this adapter. if undefined, defaults to constant.POLICY_ERROR.
            this.conflictPolicy = options.conflictPolicy || constant.POLICY_ERROR;

            // --- private attributes
            this.id       = options.id || common.makeID();
            this._c       = context;
            // TODO: use _.pick() for these options...
            this._options = options;
            this._devInfo = devInfo;
            this._model   = null;
            this._stores  = {};
            this._peers   = [];
        },

            //-------------------------------------------------------------------------
            _getModel: function() {
                return this._model;
            },

            //-------------------------------------------------------------------------
            setDevInfo: function(devInfo, cb) {
                if ( this._model == undefined )
                    this._model = {
                        id              : this.id,
                        displayName     : this.displayName,
                        maxMsgSize      : this.maxMsgSize,
                        maxObjSize      : this.maxObjSize,
                        conflictPolicy  : this.conflictPolicy,
                        devInfo         : null,
                        stores          : [],
                        peers           : [],
                        isLocal         : 1
                    };

                var di = new devinfomod.DevInfo(this, devInfo);
                di._updateModel(_.bind(function(err) {
                    if ( err )
                        return cb(err);

                    this._model.devID = this._model.devInfo.devID;
                    this.devID        = this._model.devInfo.devID;
                    this.devInfo      = di;

                // since the local devinfo has changed, we need to ensure that
                // we rebroadcast it (in case there are any affects...), thus
                // resetting all anchors.
                // TODO: this seems a little heavy-handed, since this will force
                //       a slow-sync for each datastore. is that really the best
                //       thing?...
                this._resetAllAnchors();

                this._save(this._c._txn(), cb);

                }, this));
            },

            //-------------------------------------------------------------------------
            _resetAllAnchors: function() {
                _.each(this._model.peers, function(peer) {
                    _.each(peer.stores, function(store) {
                        if ( ! store.binding )
                        return;
                    store.binding.localAnchor  = null;
                    store.binding.remoteAnchor = null;
                    });
                });
            },

            //-------------------------------------------------------------------------
            getPeers: function() {
                return this._peers;
            },

            //-------------------------------------------------------------------------
            addPeer: function(peerInfo, cb) {
                var self = this;

                // TODO: if there is already a peer for the specified URL, then
                //       we may have a problem!...

                // todo: if we are adding a peer to an adapter that already has
                //       non-client peers, then we may have a problem!...
                //       (this is only true while syncml-js is not capable of truly
                //       operating in peer-to-peer mode)

                var peer = new remote.RemoteAdapter(this, peerInfo);
                peer._updateModel(function(err) {
                    if ( err )
                    return cb(err);
                self._peers.push(peer);
                cb(null, peer);
                });
            },

            //-------------------------------------------------------------------------
            save: function(cb) {
                this._save(this._c._txn(), cb);
            },

            //-------------------------------------------------------------------------
            _save: function(dbtxn, cb) {
                var self = this;
                self._updateModel(function(err) {
                    if ( err )
                    return cb(err);
                storage.put(dbtxn.objectStore('adapter'), self._model, cb);
                });
            },

            //-------------------------------------------------------------------------
            _updateModel: function(cb) {
                var self = this;
                var model = self._model;
                model.displayName    = self.displayName;
                model.devID          = self.devID;
                model.maxMsgSize     = self.maxMsgSize;
                model.maxObjSize     = self.maxObjSize;
                model.conflictPolicy = self.conflictPolicy;
                model.isLocal        = 1;
                common.cascade([
                        // update the devInfo model
                        function(cb) {
                            if ( ! self.devInfo )
                    return cb();
                return self.devInfo._updateModel(cb);
                        },
                        // update the stores model
                        function(cb) {
                            model.stores = [];
                            common.cascade(_.values(self._stores), function(store, cb) {
                                store._updateModel(cb);
                            }, cb);
                        },

                        // update the peers model
                        function(cb) {
                            // NOTE: unlike stores, which can completely regenerate the
                            //       model based on the class, the peers store binding
                            //       and routing info is only in the model, so cannot be
                            //       completely deleted...
                            common.cascade(self._peers, function(peer, cb) {
                                peer._updateModel(cb);
                            }, cb);
                        }

                ], cb);
            },

            //-------------------------------------------------------------------------
            _load: function(cb) {
                var self = this;

                // TODO: if options specifies a devID/name/etc, use that...

                storage.getAll(
                    this._c,
                    this._c._txn().objectStore('adapter').index('isLocal'),
                    {only: 1},
                    function(err, adapters) {
                        if ( err ) {
                            return cb(err);
                        }
                        if ( adapters.length > 1 )
                            return cb('multiple local adapters defined - specify which devID to load');
                        if ( adapters.length <= 0 )
                            return cb(null, self);
                        self._loadModel(adapters[0], function(err) {
                            if ( err )
                                return cb(err);
                            return cb(null, self);
                        });
                    }
                );
            },

            //-------------------------------------------------------------------------
            _loadModel: function(model, cb) {
                var self = this;
                self._model         = model;
                self.displayName    = model.displayName;
                self.devID          = model.devID;
                self.maxMsgSize     = model.maxMsgSize;
                self.maxObjSize     = model.maxObjSize;
                self.conflictPolicy = model.conflictPolicy;
                common.cascade([
                        // load device info
                        function(cb) {
                            var di = new devinfomod.DevInfo(self, self._model.devInfo);
                            di._load(function(err) {
                                if ( err )
                                return cb(err);
                            self.devInfo = di;
                            cb();
                            });
                        },
                        // load stores
                        function(cb) {
                            common.cascade(model.stores, function(e, cb) {
                                var store = new storemod.Store(self, e);
                                store._load(function(err) {
                                    if ( err )
                                    return cb(err);
                                self._stores[store.uri] = store;
                                return cb();
                                });
                            }, cb);
                        },
                        // load peers
                        function(cb) {
                            var remotes = _.filter(model.peers, function(e) {
                                return ! e.isLocal;
                            });
                            self._peers = [];
                            common.cascade(remotes, function(e, cb) {
                                var peer = new remote.RemoteAdapter(self, e);
                                peer._load(function(err) {
                                    if ( err )
                                    return cb(err);
                                self._peers.push(peer);
                                return cb();
                                });
                            }, cb);
                        }
                ], cb);
            },

            //-------------------------------------------------------------------------
            sync: function(peer, mode, options, cb) {
                // `options` is optional and can have the following properties:
                //   * `ua`

                // TODO: initialize a new context transaction?...
                // todo: or perhaps add a new session.txn?...

                if ( cb == undefined && _.isFunction(options) )
                {
                    cb = options;
                    options = {};
                }
                options = options || {};

                var self = this;
                var discover = ( mode == constant.SYNCTYPE_DISCOVER );
                if ( discover )
                    mode = constant.SYNCTYPE_SLOW_SYNC;

                if ( ! _.find(self._peers, function(p) { return p === peer; }) )
                    return cb(new common.InvalidAdapter('invalid peer for adapter'));
                if ( mode != constant.SYNCTYPE_AUTO )
                {
                    mode = common.synctype2alert(mode);
                    if ( ! mode )
                        return cb(new common.TypeError('invalid synctype'));
                }
                if ( ! self.devInfo )
                    return cb(new common.InvalidAdapter('cannot synchronize adapter as client: invalid devInfo'));

                var session = state.makeSession({
                    context  : self._c,
                    ua       : new useragent.UserAgentMultiplexer([options.ua, self._c.ua]),
                    txn      : _.bind(self._c._txn, self._c),
                    adapter  : self,
                    peer     : peer,
                    isServer : false,
                    discover : discover,
                    info     : state.makeSessionInfo({
                        id       : ( peer.lastSessionID || 0 ) + 1,
                    msgID    : 1,
                    codec    : self._c.codec,
                    mode     : mode
                    })
                });

                session.send = function(contentType, data, cb) {
                    session.peer.sendRequest(session, contentType, data, function(err, response) {
                        if ( err )
                        return cb(err);
                    // todo: allow the client to force the server to authorize itself as well...
                    self._receive(session, response, null, cb);
                    });
                };

                // TODO: should i do a router.calculate() at this point?
                //       the reason is that if there was a sync, then a
                //       .setRoute(), then things may have changed...
                //       corner-case, yes... but still valid.

                var failed = 0;

                var startSession = function() {
                    session.context.protocol.initialize(session, null, function(err, commands) {
                        if ( err )
                        return cb(err);
                    self._transmit(session, commands, function(err) {
                        if ( err )
                    {
                        if ( ! ( err instanceof common.InvalidCredentials )
                            && ! ( err instanceof common.CredentialsRequired ) )
                            return cb(err);
                        if ( err instanceof common.InvalidCredentials )
                        failed += 1;
                    if ( failed > 100 )
                    {
                        return cb(err);
                    }
                    var credErr = err;
                    var uaEvent = {
                        session : session,
                        auth    : err.auth,
                        count   : failed
                    };
                    return session.ua.fetchCredentials(uaEvent, function(err, auth) {
                        if ( err )
                        return cb(err);
                    if ( ! auth )
                        return cb(credErr);
                    if ( auth.persist )
                    {
                        session.peer.auth = auth.type;
                        session.peer.username = auth.username;
                        session.peer.password = auth.password;
                    }
                    else
                        session.auth = auth;
                    // todo: should i just create a new session?...
                    session.info.id += 1;
                    session.info.msgID = 1;
                    return startSession();
                    });
                    }
                    self._save(session.txn(), function(err) {
                        if ( err )
                        return cb(err);
                    return cb(null, self._session2stats(session));
                    });
                    });
                    });
                };

                session.context.synchronizer.initStoreSync(session, function(err) {
                    if ( err )
                    return cb(err);
                startSession();
                });

            },

            //-------------------------------------------------------------------------
            _session2stats: function(session) {
                var ret = {};
                _.each(_.values(session.info.dsstates), function(ds) {
                    var stats = _.clone(ds.stats);
                    stats.mode = common.alert2synctype(ds.mode);
                    if ( ds.action == 'error' && ds.error )
                    stats.error = ds.error;
                ret[ds.uri] = stats;
                });
                return ret;
            },

            //-------------------------------------------------------------------------
            _transmit: function(session, commands, cb) {
                var self = this;
                if ( session.info.msgID > 20 )
                    return cb('too many client/server messages');
                session.context.protocol.negotiate(session, commands, function(err, commands) {
                    if ( err )
                    return cb(err);
                if ( session.context.protocol.isComplete(session, commands) )
                {
                    // we're done! store all the anchors and session IDs and exit...
                    var pmodel = session.peer._getModel();
                    if ( ! pmodel )
                    return cb('unexpected error: could not locate this peer in local adapter');
                _.each(session.info.dsstates, function(ds, uri) {
                    var pstore = _.find(pmodel.stores, function(s) { return s.uri == ds.peerUri; });
                    if ( ! pstore )
                    return cb('unexpected error: could not locate bound peer store in local adapter');
                pstore.binding.localAnchor  = ds.nextAnchor;
                pstore.binding.remoteAnchor = ds.peerNextAnchor;
                });
                session.peer.lastSessionID = session.info.id;
                pmodel.lastSessionID       = session.info.id;
                return cb();
                }
                session.context.protocol.produce(session, commands, function(err, tree) {
                    if ( err )
                    return cb(err);
                codec.Codec.autoEncode(tree, session.info.codec, function(err, contentType, data) {
                    if ( err )
                    return cb(err);
                // update the session with the last request commands so
                // that when we receive the response package, it can be
                // compared against that.
                // TODO: should that only be done on successful transmit?...
                session.info.lastCommands = commands;
                session.send(contentType, data, function(err) {
                    if ( err )
                    return cb(err);
                cb();
                });
                })
                });
                });
            },

            //-------------------------------------------------------------------------
            authorize: function(request, sessionInfo, authorize, cb) {
                var self = this;
                var ct   = request.headers['Content-Type'];
                codec.Codec.autoDecode(ct, request.body, function(err, xtree, codecName) {
                    if ( err )
                    return cb(err);
                self._c.protocol.authorize(xtree, null, authorize, cb);
                });
            },

            //-------------------------------------------------------------------------
            getTargetID: function(request, sessionInfo, cb) {
                var self = this;
                var ct   = request.headers['Content-Type'];
                codec.Codec.autoDecode(ct, request.body, function(err, xtree, codecName) {
                    if ( err )
                    return cb(err);
                return cb(null, self._c.protocol.getTargetID(xtree));
                });
            },

            //-------------------------------------------------------------------------
            handleRequest: function(request, sessionInfo, authorize, response, options, cb) {

                // TODO: initialize a new context transaction?...
                // todo: or perhaps add a new session.txn?...

                if ( cb == undefined && _.isFunction(options) )
                {
                    cb = options;
                    options = {};
                }
                options = options || {};

                var self = this;
                var session = state.makeSession({
                    context  : self._c,
                    ua       : new useragent.UserAgentMultiplexer([options.ua, self._c.ua]),
                    txn      : _.bind(self._c._txn, self._c),
                    adapter  : self,
                    peer     : null,
                    isServer : true,
                    info     : sessionInfo
                });
                session.send = response;
                this._receive(session, request, authorize, function(err, stats) {
                    if ( err )
                    return cb(err);
                self._save(session.txn(), function(err) {
                    if ( err )
                    return cb(err);
                return cb(null, self._session2stats(session));
                });
                });
            },

            //-------------------------------------------------------------------------
            _receive: function(session, request, authorize, cb) {
                var self = this;
                if ( ! session.isServer )
                {
                    session.info.lastMsgID = session.info.msgID;
                    session.info.msgID += 1;
                }
                var ct = request.headers['Content-Type'];
                codec.Codec.autoDecode(ct, request.body, function(err, xtree, codecName) {
                    if ( err )
                    return cb(err);
                session.info.codec = codecName;
                var do_authorize = ( ! authorize ) ? common.noop : function(cb) {
                    session.context.protocol.authorize(xtree, null, authorize, function(err) {
                        return cb(err);
                    });
                };
                do_authorize(function(err) {
                    if ( err )
                    return cb(err);
                session.context.protocol.consume(
                    session, session.info.lastCommands, xtree,
                    function(err, commands) {
                        if ( err ) {
                            return cb(err);
                        }
                        if ( session.discover && session.peer.devInfo )
                    return cb(null, self._session2stats(session));
                self._transmit(session, commands, function(err) {
                    if ( err )
                    return cb(err);
                if ( ! session.isServer )
                    return cb();
                self._save(session.txn(), function(err) {
                    if ( err )
                    return cb(err);
                return cb(null, self._session2stats(session));
                });
                });
                    }
                );
                });
                })
            },

    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/matcher', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.matcher
// auth: griffin <griffin@uberdev.org>
// date: 2012/12/05
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    _self;

_self = (function () {

    var exports = {};

    //---------------------------------------------------------------------------
    exports._cntpref = function(source, target) {
        return ( source.preferred ? 1 : 0 ) + ( target.preferred ? 1 : 0 );
    };

    //---------------------------------------------------------------------------
    exports._pickTransmitContentType = function(source, target, prefcnt, checkVersion) {
        for ( var sidx=0 ; sidx<source.length ; sidx++ )
{
    var sct = source[sidx];
    for ( var tidx=0 ; tidx<target.length ; tidx++ )
{
    var tct = target[tidx];
    if ( sct.ctype != tct.ctype )
    continue;
if ( ! checkVersion )
{
    if ( exports._cntpref(sct, tct) >= prefcnt )
        return [sct.ctype, sct.versions[sct.versions.length - 1]];
    continue;
}
for ( var svidx=sct.versions.length ; svidx>0 ; svidx-- )
{
    var sv = sct.versions[svidx - 1]
        for ( var tvidx=tct.versions.length ; tvidx>0 ; tvidx-- )
        {
            var tv = tct.versions[tvidx - 1]
                if ( sv != tv )
                    continue;
            if ( exports._cntpref(sct, tct) >= prefcnt )
                return [sct.ctype, sv];
        }
}
}
}
return null;
};

//---------------------------------------------------------------------------
exports.pickTransmitContentType = function(source, target) {

    // TODO: this is probably not the most efficient algorithm!...
    //       (but it works... ;-)

    // order of preference:
    //   - transmit => receive, BOTH preferred, VERSION match
    //   - transmit => receive, ONE preferred, VERSION match
    //   - transmit => receive, neither preferred, VERSION match
    //   - transmit => receive, BOTH preferred, no version match
    //   - transmit => receive, ONE preferred, no version match
    //   - transmit => receive, neither preferred, no version match
    //   - tx/rx => tx/rx, BOTH preferred, VERSION match
    //   - tx/rx => tx/rx, ONE preferred, VERSION match
    //   - tx/rx => tx/rx, neither preferred, VERSION match
    //   - tx/rx => tx/rx, BOTH preferred, no version match
    //   - tx/rx => tx/rx, ONE preferred, no version match
    //   - tx/rx => tx/rx, neither preferred, no version match

    // todo: make it explicit (or overrideable) that i am depending on the ordering
    //       of the versions supported to give an indicator of preference...

    var sct = source.getContentTypes();
    var tct = target.getContentTypes();

    var fct = function(cts, transmit) {
        return _.filter(cts, function(ct) {
            return transmit ? ct.transmit : ct.receive;
        });
    };

    return exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 2, true)
        || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 1, true)
        || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 0, true)
        || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 2, false)
        || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 1, false)
        || exports._pickTransmitContentType(fct(sct, true), fct(tct, false), 0, false)
        || exports._pickTransmitContentType(sct, tct, 2, true)
        || exports._pickTransmitContentType(sct, tct, 1, true)
        || exports._pickTransmitContentType(sct, tct, 0, true)
        || exports._pickTransmitContentType(sct, tct, 2, false)
        || exports._pickTransmitContentType(sct, tct, 1, false)
        || exports._pickTransmitContentType(sct, tct, 0, false)
        || null;

};

// TODO: OH MY GOD.
//       this is insanely inefficient.
//       i'm embarrassed.
//       fortunately, it's hidden really low-level...
//       but now you know, doh! please don't blackmail me!... ;-)

// TODO: this currently requires that both tx and rx match in both
//       directions with the same velocity... it should prioritize
//       that, but then fallback to giving simplex matches priority.

//---------------------------------------------------------------------------
var has_ct = function(a, b, checkVersion, transmit, wildcard) {
    a = _.filter(a, function(e) { return transmit ? e.transmit : e.receive });
    b = _.filter(b, function(e) { return transmit ? e.transmit : e.receive });
    for ( var aidx=0 ; aidx<a.length ; aidx++ )
    {
        var ct_a = a[aidx];
        for ( var bidx=0 ; bidx<b.length ; bidx++ )
        {
            var ct_b = b[bidx];
            if ( ct_a.ctype != ct_b.ctype )
                continue;
            if ( ! checkVersion )
                return true;
            for ( var vaidx=0 ; vaidx<ct_a.versions.length ; vaidx++ )
            {
                var va = ct_a.versions[vaidx];
                for ( var vbidx=0 ; vbidx<ct_b.length ; vbidx++ )
                {
                    var vb = ct_b.versions[vbidx];
                    if ( va == vb )
                        return true;
                }
            }
        }
    } 
    return false;
};

//---------------------------------------------------------------------------
var has_ct_both = function(a, b, checkVersion, wildcard) {
    return has_ct(a, b, checkVersion, true, wildcard)
        && has_ct(a, b, checkVersion, false, wildcard);
};

//---------------------------------------------------------------------------
var cmpStore_ct_set_crit = function(base, ds1, ds2, checkVersion, wildcard) {
    var bds1 = has_ct_both(base, ds1, checkVersion, wildcard);
    var bds2 = has_ct_both(base, ds2, checkVersion, wildcard);
    if ( bds1 && bds2 )
        return 0;
    if ( bds1 )
        return -1;
    if ( bds2 )
        return 1;
    return 0;
};

//---------------------------------------------------------------------------
var cmpStore_ct_set = function(base, ds1, ds2) {
    var ret = cmpStore_ct_set_crit(base, ds1, ds2, true, false);
    if ( ret != 0 )
        return ret;
    ret = cmpStore_ct_set_crit(base, ds1, ds2, false, false);
    if ( ret != 0 )
        return ret;
    ret = cmpStore_ct_set_crit(base, ds1, ds2, true, true);
    if ( ret != 0 )
        return ret;
    ret = cmpStore_ct_set_crit(base, ds1, ds2, false, true);
    if ( ret != 0 )
        return ret;
    return 0;
};

//---------------------------------------------------------------------------
var getct = function(store) {
    return store.getContentTypes ? store.getContentTypes() : store.contentTypes;
};

//---------------------------------------------------------------------------
var cmpStore_ct_pref = function(base, ds1, ds2) {
    var basect = _.filter(getct(base), function(ct) { return ct.preferred; });
    var ds1ct  = _.filter(getct(ds1), function(ct) { return ct.preferred; });
    var ds2ct  = _.filter(getct(ds2), function(ct) { return ct.preferred; });
    return cmpStore_ct_set(basect, ds1ct, ds2ct);
};

//---------------------------------------------------------------------------
var cmpStore_ct_all = function(base, ds1, ds2) {
    return cmpStore_ct_set(getct(base), getct(ds1), getct(ds2));
};

//---------------------------------------------------------------------------
var cmpStore_ct = function(base, ds1, ds2) {
    var ret = cmpStore_ct_pref(base, ds1, ds2)
        if ( ret != 0 )
            return ret;
    return cmpStore_ct_all(base, ds1, ds2);
};

//---------------------------------------------------------------------------
var cmpStore_uri = function(base, ds1, ds2) {
    var ret = difflib.getCloseMatches(base.uri, [ds1.uri, ds2.uri], 1, 0.5);
    if ( ret.length <= 0 )
        return 0;
    if ( ret[0] == ds1.uri )
        return -1;
    return 1;
};

//---------------------------------------------------------------------------
exports.cmpStore = function(base, ds1, ds2) {
    var ret = cmpStore_ct(base, ds1, ds2);
    if ( ret != 0 )
        return ret;
    return cmpStore_uri(base, ds1, ds2);
};

return exports;

})();

module.exports = _self;


});
define('ripple/platform/tizen/2.0/syncml-js-lib/protocol', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.protocol
// auth: griffin <griffin@uberdev.org>
// date: 2012/11/04
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var db = require('ripple/db'),
    common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    devinfo = require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
    state = require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
    base64 = require('ripple/platform/tizen/2.0/syncml-js-lib/base64'),
    ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree'),
    _firstflag = false,
    changednum, _counts;

var _self = (function () {

    var exports = {};

    //---------------------------------------------------------------------------
    var getError = function(xnode) {
        var ret = {
            message: xnode.findtext('Item/Data')
        };
        try{
            var xerr  = xnode.find('Error');
        }catch(e){
            var xerr = null;
        }
        if ( ! xerr )
{
    try{
        var xerr  = xnode.find('Item/Error');
    }catch(e){
        var xerr = null;
    }
}
if ( ! xerr )
{
    if ( ! ret.message )
        return null;
    return ret;
}
ret.code    = xerr.findtext('Code');
ret.message = xerr.findtext('Message');
ret.trace   = xerr.findtext('Trace');
return ret;
}

//---------------------------------------------------------------------------
var badStatus = function(xnode, kls, attrs) {
    if ( ! kls )
        kls = common.ProtocolError;
    var code  = xnode.findtext('Data');
    var cname = xnode.findtext('Cmd');
    var msg   = null;
    if ( kls == common.ProtocolError )
        msg = 'unexpected status code ' + code + ' for command "' + cname + '"';
    else
        msg = 'received status code ' + code + ' for command "' + cname + '"';
    var error = getError(xnode);
    if ( error )
    {
        if ( error.code )
            msg += ': [' + error.code + '] ' + error.message;
        else
            msg += ': ' + error.message;
    }
    return new kls(msg, undefined, attrs)
};

//---------------------------------------------------------------------------
exports.getError  = getError;
exports.badStatus = badStatus;

//---------------------------------------------------------------------------
exports.Protocol = common.Base.extend({

    //-------------------------------------------------------------------------
    constructor: function(options) {
    },

    //-------------------------------------------------------------------------
    authorize: function(xtree, uri, authorize, cb) {

        // TODO: if this session has been authorized before, don't call authorize
        //       ie.:
        //         if ( session.info.authAccepted )
        //           return cb();
        //       BUT this requires the session object... oops.

        if ( ! authorize )
    authorize = function(uri, data, cb) { return cb(null, data); };
if ( xtree.tag != 'SyncML' )
    throw new common.ProtocolError('root element was not "SyncML"');
var xcred = xtree.find('SyncHdr/Cred');
if ( ! xcred )
    return authorize(uri, null, cb);
var data = xcred.findtext('Data');
var authtype = xcred.findtext('Meta/Type');
var format = xcred.findtext('Meta/Format');
if ( format == constant.FORMAT_B64 )
    data = base64.decode(data);
else if ( format )
    throw new common.UnknownFormatType(format);
switch ( authtype )
{
    case constant.NAMESPACE_AUTH_BASIC:
        {
            data = common.splitn(data, ':', 1);
            return authorize(uri, {
                auth:     constant.NAMESPACE_AUTH_BASIC,
                   username: data[0],
                   password: data[1]
            }, cb);
        }
    case constant.NAMESPACE_AUTH_MD5:
        {
            return authorize(uri, {
                auth:   constant.NAMESPACE_AUTH_BASIC,
                   digest: data
            }, cb);
        }
    default:
        {
            return cb(new common.UnknownAuthType(
                        'unknown/unimplemented auth type "' + authtype + '"'));
        }
}
},

    //-------------------------------------------------------------------------
    getTargetID: function(xtree) {
        if ( xtree.tag != 'SyncML' )
            throw new common.ProtocolError('root element was not "SyncML"');
        // todo: do more validity checks?...
        return xtree.findtext('SyncHdr/Target/LocURI');
    },

    //-------------------------------------------------------------------------
    isComplete: function(session, commands) {
        return (! session.isServer
                && commands.length == 3
                && commands[0].name == constant.CMD_SYNCHDR
                && commands[1].name == constant.CMD_STATUS
                && commands[1].statusOf == constant.CMD_SYNCHDR
                && commands[1].statusCode == constant.STATUS_OK
                && commands[2].name == constant.CMD_FINAL
               );
    },

    //----------------------<---------------------------------------------------
    initialize: function(session, xtree, cb) {
        var cmd = state.makeCommand({
            name        : constant.CMD_SYNCHDR,
        cmdID       : 0,
        version     : constant.SYNCML_VERSION_1_2,
        source      : session.info.effectiveID || session.adapter.devID,
        sourceName  : session.adapter.displayName,
        respUri     : session.isServer ? session.info.returnUrl : null
        });

        var checkPeer = ( ! session.isServer ) ? function(cb) {
            if ( ! xtree )
                return cb();
            var xhdr = xtree.find('SyncHdr');
            // todo: check peer id...
            if ( session.info.id != common.int(xhdr.findtext('SessionID')) )
            {
                return cb(new common.ProtocolError('session ID mismatch "'
                            + xhdr.findtext('SessionID')
                            + '" (expected: ' + session.info.id + ')'));
                        }
                        // todo: check message id...
                        cb();
                        } : function(cb) {
                            var xhdr = xtree.find('SyncHdr');
                            var peerID = xhdr.findtext('Source/LocURI');
                            if ( session.info.peerID && session.info.peerID != peerID )
                {
                    return cb(new common.ProtocolError('unexpected peer ID "' + peerID + '"'));
                }
                if ( session.peer && session.peer.devID != peerID )
                {
                    return cb(new common.ProtocolError('unacceptable peer ID "' + peerID + '"'));
                }
                session.info.peerID = peerID;
                // check that no session swapping occurred
                if ( session.info.id != undefined
                    && session.info.id != common.int(xhdr.findtext('SessionID')) )
                {
                    return cb(new common.ProtocolError('session ID mismatch "'
                                + xhdr.findtext('SessionID')
                                + '" (expected: ' + session.info.id + ')'));
                            }
                            session.info.id     = common.int(xhdr.findtext('SessionID'));
                            session.info.msgID  = common.int(xhdr.findtext('MsgID'));
                            if ( session.peer && session.peer.devID == peerID )
                            return cb();
                            // TODO: i should delete unused peers here... ie. anything that
                            //       hasn't been used in some configurable number of seconds,
                            //       which should probably default to something like a month...
                            session.peer = _.find(session.adapter.getPeers(), function(peer) {
                                return ( peer.devID == peerID );
                            });
                            if ( session.peer )
                            {
                                return cb();
                            }
                            var peerInfo = {
                                devID:        peerID,
                           displayName:  xhdr.findtext('Source/LocName'),
                           maxMsgSize:   common.int(xhdr.findtext('Meta/MaxMsgSize')),
                           maxObjSize:   common.int(xhdr.findtext('Meta/MaxObjSize'))
                            };
                            session.adapter.addPeer(peerInfo, function(err, peer) {
                                if ( err )
                                return cb(err);
                            session.peer = peer;
                            return cb();
                            });
                        };

        checkPeer(function(err) {

            session.info.cmdID        = 0;
            session.info.pendingMsgID = ( session.isServer
                ? session.info.msgID
                : session.info.lastMsgID );
            cmd.sessionID   = session.info.id;
            cmd.msgID       = session.info.msgID;
            cmd.target      = session.peer ? session.peer.devID || null : null;
            cmd.targetName  = session.peer ? session.peer.displayName || null : null;
            cmd.auth        = session.auth
            ? session.auth.type
            : session.peer
            ? session.peer.auth
            : null;

        if ( err )
            return cb(err, [cmd]);

        if ( cmd.msgID == 1 )
        {
            // NOTE: normally, the "server" would not send this info. however, in
            //       the syncml-js world where it is much more peer-oriented
            //       instead of client/server, i send this as well... the
            //       idea being, if two "client" peers are communicating in
            //       the event of server unavailability, then they may need
            //       to know each-others limitations...
            cmd.maxMsgSize = common.getMaxMemorySize(session.context);
            cmd.maxObjSize = common.getMaxMemorySize(session.context);
            ///cmd.maxMsgSize = 150000;
            ///cmd.maxObjSize = 4000000;
        }
        cb(null, [cmd]);
        });
    },

    //-------------------------------------------------------------------------
    negotiate: function(session, commands, cb) {
        // // todo: determine why i decided to clone the commands...
        // commands = _.clone(commands);

        if ( commands.length > 0 && _.last(commands).name == constant.CMD_FINAL )
            return cb(null, commands);

        if ( commands.length > 0
                && _.last(commands).name == constant.CMD_ALERT
                && _.last(commands).data == constant.STATUS_NEXT_MESSAGE )
            // todo: should i add a "final" here?...
            // commands.push(state.makeCommand({name: constant.CMD_FINAL}));
            return cb(null, commands);

        var createDevInfoCommands = function(commands, cb) {
            // todo: this flag is crap. instead, the local devInfo should have
            //       a record of which sessionID lead to the recording, and
            //       base it on that. maybe timestamp too... (but it must be
            //       in the minutes, just in case...)
            session.info.gotinfo = true;
            if ( ! session.discover )
            {
                commands.push(state.makeCommand({
                    name       : constant.CMD_PUT,
                    cmdID      : session.nextCmdID(),
                    type       : constant.TYPE_SYNCML_DEVICE_INFO + '+' + session.info.codec,
                    source     : './' + constant.URI_DEVINFO_1_2,
                    data       : session.adapter.devInfo.toSyncML(constant.SYNCML_DTD_VERSION_1_2,
                        _.values(session.adapter._stores))
                }));
            }
            commands.push(state.makeCommand({
                name     : constant.CMD_GET,
                cmdID    : session.nextCmdID(),
                type     : constant.TYPE_SYNCML_DEVICE_INFO + '+' + session.info.codec,
                target   : './' + constant.URI_DEVINFO_1_2
            }));
            return cb(null, commands);
        };

        var createCommands = function(commands, cb) {
            // request the remote device info if not currently available or
            // in discover mode or explicitly re-exchanging it (paranoid mode)
            var putget = false;
            if ( !! session.discover )
            {
                return createDevInfoCommands(commands, cb);
            }
            if ( ! session.peer.devInfo )
            {
                var uaEvent = {session: session};
                return session.ua.acceptDevInfoSwap(uaEvent, function(err) {
                    if ( err )
                {
                    return cb(err);
                }
                return createDevInfoCommands(commands, cb);
                });
            }
            if ( ! session.context.config.trustDevInfo && ! session.info.gotinfo )
            {
                return createDevInfoCommands(commands, cb);
            }
            // NOTE: in the current handling of "trustDevInfo", i am doing a
            //       potentially unnecessary extra request/response phase to
            //       confirm that the devInfo has not changed... i *could*
            //       issue the put/get as well as the alert, *assuming* that
            //       no devInfo is going to change...
            return session.context.synchronizer.actions(session, commands, cb);
        };

        return createCommands(commands, function(err, commands) {
            if ( err )
            return cb(err);
        //Hack: Memotoo service need to send alert command at the beging
        var args, tmp;
        args = db.retrieveObject("syncml-alert-args");
        tmp = {
            name       : constant.CMD_ALERT,
               cmdID      : session.nextCmdID(),
               data       : args.data,
               source     : args.source,
               target     : args.target,
               maxObjSize : "4000000"
        };
        if (args.lastAnchor) {
            tmp.lastAnchor = args.lastAnchor;
        }

        if (args.nextAnchor) {
            tmp.nextAnchor = args.nextAnchor;
        }
        _firstflag = db.retrieveObject("syncml-first-flag");
        if( !_firstflag) {
            commands.push(state.makeCommand(tmp));
            db.saveObject("syncml-first-flag", true);
        }
        commands.push(state.makeCommand({name: constant.CMD_FINAL}));
        cb(null, commands);
        });
    },

    //-------------------------------------------------------------------------
    // NOTE: `produce` is equivalent to the `pysyncml.protocol.commands2tree`...
    // Consumes state.Command commands and converts them to an ET protocol tree
    produce: function(session, commands, cb) {

        if ( commands.length <= 0 )
            return cb('protocol.produce received empty commands');

        var hdrcmd = commands[0];
        commands = _.rest(commands, 1);

        if ( hdrcmd.name != constant.CMD_SYNCHDR )
            return cb('unexpected first command "' + hdrcmd.name + '"');

        if ( hdrcmd.version != constant.SYNCML_VERSION_1_2 )
            return cb('unsupported SyncML version "' + hdrcmd.version + '"');

        var xsync = ET.Element(constant.NODE_SYNCML);
        var xhdr  = ET.SubElement(xsync, hdrcmd.name);
        if ( hdrcmd.version == constant.SYNCML_VERSION_1_2 )
        {
            ET.SubElement(xhdr, 'VerDTD').text = constant.SYNCML_DTD_VERSION_1_2;
            ET.SubElement(xhdr, 'VerProto').text = hdrcmd.version;
        }

        ET.SubElement(xhdr, 'SessionID').text = hdrcmd.sessionID;
        ET.SubElement(xhdr, 'MsgID').text = hdrcmd.msgID;
        var xsrc = ET.SubElement(xhdr, 'Source');
        ET.SubElement(xsrc, 'LocURI').text = hdrcmd.source;
        if ( hdrcmd.sourceName )
            ET.SubElement(xsrc, 'LocName').text = hdrcmd.sourceName;
        var xtgt = ET.SubElement(xhdr, 'Target');
        ET.SubElement(xtgt, 'LocURI').text = hdrcmd.target;
        if ( hdrcmd.targetName )
            ET.SubElement(xtgt, 'LocName').text = hdrcmd.targetName;
        if ( hdrcmd.respUri )
            ET.SubElement(xhdr, 'RespURI').text = hdrcmd.respUri;

        if ( hdrcmd.auth && ! session.info.authAccepted )
        {
            // TODO: implement other auth schemes...
            if ( hdrcmd.auth != constant.NAMESPACE_AUTH_BASIC )
                return cb('auth method "' + hdrcmd.auth + '" not implemented');

            if ( hdrcmd.auth == constant.NAMESPACE_AUTH_BASIC )
            {
                var xcred = ET.SubElement(xhdr, 'Cred');
                var xmeta = ET.SubElement(xcred, 'Meta');
                ET.SubElement(xmeta, 'Format', {'xmlns': constant.NAMESPACE_METINF}).text = 'b64';
                ET.SubElement(xmeta, 'Type', {'xmlns': constant.NAMESPACE_METINF}).text   = hdrcmd.auth;
                ET.SubElement(xcred, 'Data').text = base64.encode(
                        ( session.auth ? session.auth.username : session.peer.username )
                        + ':' + ( session.auth ? session.auth.password : session.peer.password ) );
            }

        }
        if ( hdrcmd.maxMsgSize || hdrcmd.maxObjSize )
        {
            var xmeta = ET.SubElement(xhdr, 'Meta');
            if ( hdrcmd.maxMsgSize )
                ET.SubElement(xmeta, 'MaxMsgSize',
                        {'xmlns': constant.NAMESPACE_METINF}).text = hdrcmd.maxMsgSize;
            if ( hdrcmd.maxObjSize )
                ET.SubElement(xmeta, 'MaxObjSize',
                        {'xmlns': constant.NAMESPACE_METINF}).text = hdrcmd.maxObjSize;
        }

        var xbody = ET.SubElement(xsync, constant.NODE_SYNCBODY);

        for ( var idx=0 ; idx<commands.length ; idx++ )
        {
            var cmd  = commands[idx];
            var xcmd = ET.SubElement(xbody, cmd.name);
            if ( cmd.cmdID != undefined )
                ET.SubElement(xcmd, 'CmdID').text = cmd.cmdID;
            var func = this['_produce_cmd_' + cmd.name.toLowerCase()];
            if ( ! func )
                return cb(new common.InternalError('unexpected command "' + cmd.name + '"'));
            try{
                func.call(this, session, cmd, xcmd);
            }catch(e){
                return cb(new common.InternalError(
                            'failed invoking protocol sub-production of "' + cmd.name + '": ' + e, e));
            }
            if ( cmd.name == constant.CMD_FINAL && idx + 1 != commands.length )
                return cb('command "' + cmd.name + '" not at end of commands');
        }

        cb(null, xsync);
    },

    //-------------------------------------------------------------------------
    _produce_cmd_alert: function(session, cmd, xcmd) {
        ET.SubElement(xcmd, 'Data').text = cmd.data;
        var xitem = ET.SubElement(xcmd, 'Item');
        ET.SubElement(ET.SubElement(xitem, 'Source'), 'LocURI').text = cmd.source;
        ET.SubElement(ET.SubElement(xitem, 'Target'), 'LocURI').text = cmd.target;
        if ( cmd.lastAnchor || cmd.nextAnchor || cmd.maxObjSize )
        {
            var xmeta = ET.SubElement(xitem, 'Meta');
            var xanch = ET.SubElement(xmeta, 'Anchor', {'xmlns': constant.NAMESPACE_METINF});
            if ( cmd.lastAnchor )
                ET.SubElement(xanch, 'Last').text = cmd.lastAnchor;
            if ( cmd.nextAnchor )
                ET.SubElement(xanch, 'Next').text = cmd.nextAnchor;
            if ( cmd.maxObjSize )
                ET.SubElement(xmeta, 'MaxObjSize',
                        {'xmlns': constant.NAMESPACE_METINF}).text = cmd.maxObjSize;
        }
    },

    //-------------------------------------------------------------------------
    _produce_cmd_status: function(session, cmd, xcmd) {
        ET.SubElement(xcmd, 'MsgRef').text    = '' + cmd.msgRef;
        ET.SubElement(xcmd, 'CmdRef').text    = '' + cmd.cmdRef;
        ET.SubElement(xcmd, 'Cmd').text       = cmd.statusOf;
        if ( cmd.sourceRef )
            ET.SubElement(xcmd, 'SourceRef').text = cmd.sourceRef;
        if ( cmd.targetRef )
            ET.SubElement(xcmd, 'TargetRef').text = cmd.targetRef;
        ET.SubElement(xcmd, 'Data').text      = cmd.statusCode;
        var xitem = null;
        var xdata = null;
        if ( cmd.nextAnchor || cmd.lastAnchor )
        {
            xitem = ET.SubElement(xcmd, 'Item');
            xdata = ET.SubElement(xitem, 'Data');
            var xanch = ET.SubElement(xdata, 'Anchor', {'xmlns': constant.NAMESPACE_METINF});
            if ( cmd.lastAnchor )
                ET.SubElement(xanch, 'Last').text = cmd.lastAnchor;
            if ( cmd.nextAnchor )
                ET.SubElement(xanch, 'Next').text = cmd.nextAnchor;
        }
        // NOTE: this is NOT standard SyncML...
        if ( cmd.errorCode || cmd.errorMsg )
        {
            xitem = xitem || ET.SubElement(xcmd, 'Item');
            xdata = xdata || ET.SubElement(xitem, 'Data');
            var xerr = ET.SubElement(xitem, 'Error');
            xdata.text = cmd.errorMsg;
            if ( cmd.errorCode )
                ET.SubElement(xerr, 'Code').text = cmd.errorCode;
            if ( cmd.errorMsg )
                ET.SubElement(xerr, 'Message').text = cmd.errorMsg;
            if ( session.context.config.exposeErrorTrace && cmd.errorTrace )
                ET.SubElement(xerr, 'Trace').text = cmd.errorTrace;
        }
    },

    //-------------------------------------------------------------------------
    _produce_cmd_get: function(session, cmd, xcmd) {
        ET.SubElement(ET.SubElement(xcmd, 'Meta'), 'Type',
                {'xmlns': constant.NAMESPACE_METINF}).text = cmd.type;
        if ( cmd.source || cmd.target || cmd.data )
        {
            var xitem = ET.SubElement(xcmd, 'Item');
            if ( cmd.source )
            {
                var xsrc = ET.SubElement(xitem, 'Source');
                ET.SubElement(xsrc, 'LocURI').text  = cmd.source;
                ET.SubElement(xsrc, 'LocName').text = cmd.source;
            }
            if ( cmd.target )
            {
                var xtgt = ET.SubElement(xitem, 'Target');
                ET.SubElement(xtgt, 'LocURI').text  = cmd.target;
                ET.SubElement(xtgt, 'LocName').text = cmd.target;
            }
            if ( cmd.data )
            {
                if ( _.isString(cmd.data) )
                    ET.SubElement(xitem, 'Data').text = cmd.data;
                else
                    // assuming here that it is an ElementTree object...
                    ET.SubElement(xitem, 'Data').append(cmd.data);
            }
        }
    },

    //-------------------------------------------------------------------------
    _produce_cmd_put: function(session, cmd, xcmd) {
        return this._produce_cmd_get(session, cmd, xcmd);
    },

    //-------------------------------------------------------------------------
    _produce_cmd_results: function(session, cmd, xcmd) {
        ET.SubElement(xcmd, 'MsgRef').text    = cmd.msgRef;
        ET.SubElement(xcmd, 'CmdRef').text    = cmd.cmdRef;
        ET.SubElement(ET.SubElement(xcmd, 'Meta'), 'Type',
                {'xmlns': constant.NAMESPACE_METINF}).text = cmd.type;
        var xitem = ET.SubElement(xcmd, 'Item');
        var xsrc  = ET.SubElement(xitem, 'Source');
        ET.SubElement(xsrc, 'LocURI').text  = cmd.source;
        ET.SubElement(xsrc, 'LocName').text = cmd.source;
        if ( cmd.data )
        {
            if ( _.isString(cmd.data) )
                ET.SubElement(xitem, 'Data').text = cmd.data;
            else
                // assuming here that it is an ElementTree object...
                ET.SubElement(xitem, 'Data').append(cmd.data);
        }
    },

    //-------------------------------------------------------------------------
    _produce_cmd_sync: function(session, cmd, xcmd) {
        ET.SubElement(ET.SubElement(xcmd, 'Source'), 'LocURI').text = cmd.source;
        ET.SubElement(ET.SubElement(xcmd, 'Target'), 'LocURI').text = cmd.target;
        if ( cmd.noc != undefined )
            ET.SubElement(xcmd, 'NumberOfChanges').text = '' + cmd.noc;
        if ( ! cmd.data )
            return;
        for ( var idx=0 ; idx<cmd.data.length ; idx++ )
        {
            var scmd = cmd.data[idx];
            var xscmd = ET.SubElement(xcmd, scmd.name);
            if ( scmd.cmdID )
                ET.SubElement(xscmd, 'CmdID').text = scmd.cmdID;
            if ( scmd.type
                    || ( scmd.format && scmd.format != constant.FORMAT_AUTO ) )
            {
                var xsmeta = ET.SubElement(xscmd, 'Meta')
                    // todo: implement auto encoding determination...
                    //       (the current implementation just lets XML encoding
                    //       do it, which is for most things good enough, but
                    //       not so good for sequences that need a large amount
                    //       of escaping such as binary data...)
                    if ( scmd.format && scmd.format != constant.FORMAT_AUTO )
                        ET.SubElement(xsmeta, 'Format',
                                {'xmlns': constant.NAMESPACE_METINF}).text = scmd.format;
                if ( scmd.type )
                    ET.SubElement(xsmeta, 'Type',
                            {'xmlns': constant.NAMESPACE_METINF}).text = scmd.type;
            }
            var xsitem = ET.SubElement(xscmd, 'Item');
            if ( scmd.source )
                ET.SubElement(ET.SubElement(xsitem, 'Source'),
                        'LocURI').text = scmd.source;
            if ( scmd.sourceParent )
                ET.SubElement(ET.SubElement(xsitem, 'SourceParent'),
                        'LocURI').text = scmd.sourceParent;
            if ( scmd.target )
                ET.SubElement(ET.SubElement(xsitem, 'Target'),
                        'LocURI').text = scmd.target;
            if ( scmd.targetParent )
                ET.SubElement(ET.SubElement(xsitem, 'TargetParent'),
                        'LocURI').text = scmd.targetParent;
            if ( scmd.data )
            {
                if ( _.isString(scmd.data) )
                    ET.SubElement(xsitem, 'Data').text = scmd.data;
                else
                    // assuming here that it is an ElementTree object...
                    ET.SubElement(xsitem, 'Data')._node.appendChild(scmd.data);
            }
        }
    },

    //-------------------------------------------------------------------------
    _produce_cmd_map: function(session, cmd, xcmd) {
        ET.SubElement(ET.SubElement(xcmd, 'Source'), 'LocURI').text = cmd.source;
        ET.SubElement(ET.SubElement(xcmd, 'Target'), 'LocURI').text = cmd.target;
        if ( cmd.sourceItem || cmd.targetItem )
        {
            var xitem = ET.SubElement(xcmd, constant.CMD_MAPITEM);
            if ( cmd.sourceItem )
                ET.SubElement(ET.SubElement(xitem, 'Source'), 'LocURI').text = cmd.sourceItem;
            if ( cmd.targetItem )
                ET.SubElement(ET.SubElement(xitem, 'Target'), 'LocURI').text = cmd.targetItem;
        }
    },

    //-------------------------------------------------------------------------
    _produce_cmd_final: function(session, cmd, xcmd) {
        return;
    },

    //-------------------------------------------------------------------------
    // NOTE: `consume` is equivalent to the `pysyncml.protocol.tree2commands`...
    // consume: function...
    consume: function(session, lastcmds, xsync, cb) {

        // do some preliminary sanity checks...
        // todo: do i really want to be returning an error instead of
        // generating an error response?...

        if ( xsync.tag != constant.NODE_SYNCML
                || xsync.getchildren().length != 2
                || xsync.getchildren()[0].tag != constant.CMD_SYNCHDR
                || xsync.getchildren()[1].tag != constant.NODE_SYNCBODY
           )
        {
            return cb('unexpected SyncML document structure');
        }

        var version = xsync.getchildren()[0].findtext('VerProto');
        if ( version != constant.SYNCML_VERSION_1_2 )
            return cb('unsupported SyncML version "' + version + '"');

        var verdtd = xsync.getchildren()[0].findtext('VerDTD');
        if ( verdtd != constant.SYNCML_DTD_VERSION_1_2 )
            return cb('unsupported SyncML DTD version "' + verdtd + '"');

        var self = this;

        self.initialize(session, xsync, function(err, cmds) {
            var hdrcmd = ( cmds && cmds.length > 0 ) ? cmds[0] : null;
            var makeErrorCommands = function(err, cb) {

                if ( err.exception )

            if ( ! session.isServer )
            return cb(err);

        var errcmd = state.makeCommand({
            name       : constant.CMD_STATUS,
            cmdID      : '1',
            msgRef     : session.info.pendingMsgID,
            cmdRef     : 0,
            sourceRef  : xsync.getchildren()[0].findtext('Source/LocURI'),
            targetRef  : xsync.getchildren()[0].findtext('Target/LocURI'),
            statusOf   : constant.CMD_SYNCHDR,
            statusCode : constant.STATUS_COMMAND_FAILED,
            errorMsg   : 'an error occurred during processing'
        });

        // TODO: make this configurable as to whether or not any error
        //       is sent back to the peer as a SyncML "standardized" error
        //       status...

        // TODO: make sure this is doing what is expected/intended...
        if ( err.code || err.name )
            errcmd.errorCode  = 'syncml-js.' + ( err.code || err.name );
        errcmd.errorMsg   = err.message || common.j(err) || '' + err;

        return cb(null, [hdrcmd, errcmd,
                state.makeCommand({name: constant.CMD_FINAL})]);
            };

            if ( err )
                return makeErrorCommands(err, cb);

            try {
                self._consume(session, lastcmds, xsync, cmds, function(err, commands) {
                    if ( err )
                    return makeErrorCommands(err, cb);
                return cb(null, commands);
                });
            } catch ( exc ) {
                return makeErrorCommands(exc, cb);
            }

        });
    },

    //-------------------------------------------------------------------------
    _consume: function(session, lastcmds, xsync, commands, cb) {

        var self       = this;
        var hdrcmd     = commands[0];
        var statusCode = constant.STATUS_OK;

        // analyze the SyncHdr
        var children = xsync.getchildren()[0].getchildren();
        for ( var idx=0 ; idx<children.length ; idx++ )
        {
            var child = children[idx];


            if ( child.tag == 'VerDTD' )
            {
                if ( hdrcmd.version == constant.SYNCML_VERSION_1_2 )
                {
                    if ( child.text != constant.SYNCML_DTD_VERSION_1_2 )
                        return cb(new common.ProtocolError('bad VerDTD "' + child.text + '"'));
                }
                else
                    return cb(new common.FeatureNotSupported(
                                'unsupported internal SyncML version "' + hdrcmd.version + '"'));
                continue;
            }

            if ( child.tag == 'VerProto' )
                // this was checked earlier...
                continue;

            if ( child.tag == 'SessionID' )
            {
                if ( child.text != hdrcmd.sessionID )
                    return cb(new common.ProtocolError(
                                'session ID mismatch: "' + child.text + '" != "' + hdrcmd.sessionID + '"'));
                continue;
            }

            if ( child.tag == 'MsgID' )
            {
                var chkmsg = ( session.isServer ? hdrcmd.msgID : lastcmds[0].msgID );
                if ( child.text != chkmsg )
                    return cb(new common.ProtocolError(
                                'message ID mismatch: "' + child.text + '" != "' + chkmsg + '"'));
                continue;
            }

            if ( child.tag == 'Target' )
            {
                var uri = child.findtext('LocURI');

                // TODO... server-side...

                if ( uri != hdrcmd.source )
                    return cb(new common.ProtocolError(
                                'incoming target mismatch: "' + uri + '" != "' + hdrcmd.source + '"'));
                continue;
            }

            if ( child.tag == 'Source' )
            {
                var uri = child.findtext('LocURI');
                if ( uri != hdrcmd.target && uri != lastcmds[0].target )
                    return cb(new common.ProtocolError(
                                'incoming source mismatch: "' + uri + '" != "' + hdrcmd.target + '"'));
                continue;
            }

            if ( child.tag == 'RespURI' )
            {
                // hdrcmd.target = child.text
                // session.info.respUri = child.text
                if ( ! session.isServer )
                    session.info.respUri = child.text;
                continue;
            }

            if ( child.tag == 'Cred' )
            {
                // the responsibility is on the calling framework to ensure this is
                // checked long before we get here... ie. Adapter.authorize(...)
                // or via the Adapter.handleRequest() `authorize` parameter...
                statusCode = constant.STATUS_AUTHENTICATION_ACCEPTED;
                continue;
            }

            if ( child.tag == 'Meta' )
            {
                // this should already have been consumed during the protocol.initialize() call
                continue;
            }

            return cb(new common.ProtocolError('unexpected header node "' + child.tag + '"'));
        };

        commands.push(state.makeCommand({
            name       : constant.CMD_STATUS,
            cmdID      : session.nextCmdID(),
            msgRef     : session.info.pendingMsgID,
            cmdRef     : 0,
            sourceRef  : xsync.getchildren()[0].findtext('Source/LocURI'),
            targetRef  : xsync.getchildren()[0].findtext('Target/LocURI'),
            statusOf   : constant.CMD_SYNCHDR,
            statusCode : statusCode
        }));

        // and now evaluate the SyncBody

        var chkcmds = _.filter(lastcmds, function(e) {
            return e.name != constant.CMD_STATUS && e.name != constant.CMD_FINAL;
        });

        // for each "sync" command, search for sub-commands
        // todo: should this be generalized to search for any sub-commands?...
        _.each(chkcmds, function(e) {
            if ( e.name != constant.CMD_SYNC || ! e.data || e.data.length <= 0 )
            return;
        _.each(e.data, function(sub) { chkcmds.push(sub); });
        });

        var children = xsync.getchildren()[1].getchildren();

        // first, check all the 'Status' commands

        var consumeStatus = function(cb) {

            common.cascade(children, function(child, cb) {

                if ( child.tag != constant.CMD_STATUS )
                return cb();

            cname = child.findtext('Cmd');

            var blen   = chkcmds.length;
            var chkcmd = null;
            var chkerr = null;

            chkcmds = _.filter(chkcmds, function(cmd) {
                if ( chkerr )
                return;
            if ( cmd.cmdID != child.findtext('CmdRef')
                || cmd.name != cname
                || lastcmds[0].msgID != child.findtext('MsgRef') )
                return true;
            if ( chkcmd )
                chkerr = new Error('unexpected error: multiple check commands match status command');
            chkcmd = cmd;
            return false;
            });

            if ( chkerr )
                return cb(chkerr);

            if ( chkcmds.length >= blen )
                return cb(new common.ProtocolError(
                            'unexpected status node "s' + session.info.id + '.m' + child.findtext('MsgRef')
                            + '.c' + child.findtext('CmdRef') + ' cmd=' + cname + '"'));

            // TODO: check for unknown elements (and complain?)...

            var code = common.int(child.findtext('Data'));

            if ( code == constant.STATUS_MISSING_CREDENTIALS )
            {
                var authtype = child.findtext('Chal/Meta/Type');
                var attrs = {auth: {type: authtype}};
                return cb(badStatus(child, common.CredentialsRequired, attrs));
            }

            if ( code == constant.STATUS_INVALID_CREDENTIALS )
            {
                // TODO: get the auth type... from where??...
                var authtype = child.findtext('Chal/Meta/Type');
                var attrs = {auth: {type: authtype}};
                return cb(badStatus(child, common.InvalidCredentials, attrs));
            }

            var targetRef = child.findtext('TargetRef');
            if ( targetRef )
            {
                // note: doing a normUri on chkcmd.target because it could be "./devinf12"...
                if ( session.peer.normUri(targetRef) != session.peer.normUri(chkcmd.target) )
                    return cb(new common.ProtocolError('unexpected target-ref "'
                                + targetRef + '" != "' + chkcmd.target
                                + '" for command "' + cname + '"'));
            }

            var sourceRef = child.findtext('SourceRef');
            if ( sourceRef )
            {
                // note: doing a normUri on chkcmd.source because it could be "./devinf12"...
                if ( cname == constant.CMD_SYNCHDR )
                {
                    // this is a little odd, but syncevolution strips the sessionid path
                    // parameter off for some reason, so compensating here...
                    if ( _.indexOf([session.adapter.normUri(chkcmd.source),
                                session.info.effectiveID,
                                session.info.returnUrl],
                                session.adapter.normUri(sourceRef)) < 0
                            && session.adapter.normUri(chkcmd.source).indexOf(session.adapter.normUri(sourceRef)) != 0 )
                        return cb(new common.ProtocolError('unexpected source-ref "'
                                    + sourceRef + '" != "' + chkcmd.source
                                    + '" for command "' + cname + '"'));
                }
                else
                {
                    if ( session.adapter.normUri(sourceRef) != session.adapter.normUri(chkcmd.source) )
                        return cb(new common.ProtocolError('unexpected source-ref "'
                                    + sourceRef + '" != "' + chkcmd.source
                                    + '" for command "' + cname + '"'));
                }
            }

            // todo: any other common elements?...

            switch ( cname )
            {

                case constant.CMD_SYNCHDR:
                    {
                        if ( code != constant.STATUS_OK && code != constant.STATUS_AUTHENTICATION_ACCEPTED )
                            return cb(badStatus(child));
                        if ( code == constant.STATUS_AUTHENTICATION_ACCEPTED )
                        {
                            // TODO: there is currently nothing that can "reset" the
                            //       authAccepted flag...  there should be a trap such
                            //       that if an auth fails, then authAccepted gets set
                            //       to false.
                            session.info.authAccepted = true;
                        }
                        return cb();
                    }

                case constant.CMD_ALERT:
                    {
                        if ( code == constant.STATUS_OK )
                            // TODO: do something with the Item/Data/Anchor/Next?...
                            return cb();
                        if ( code == constant.STATUS_REFRESH_REQUIRED && ! session.isServer )
                        {
                            // TODO: support the ability for the UA to control which kind of
                            //       refresh to do (slow-sync, client-refresh, server-refresh)
                            return cb();
                        }
                        return cb(badStatus(child));
                    }

                case constant.CMD_GET:
                    {
                        if ( code != constant.STATUS_OK )
                            return cb(badStatus(child));
                        return cb();
                    }

                case constant.CMD_PUT:
                    {
                        if ( code != constant.STATUS_OK )
                            return cb(badStatus(child));
                        return cb();
                    }

                case constant.CMD_RESULTS:
                    {
                        if ( code != constant.STATUS_OK )
                            return cb(badStatus(child));
                        return cb();
                    }

                case constant.CMD_SYNC:
                    {
                        // todo: should this be moved into the synchronizer as a "settle" event?...
                        var ds = session.info.dsstates[session.adapter.normUri(chkcmd.source)]
                            if ( code != constant.STATUS_OK )
                            {
                                // check for server-side errors...
                                if ( code >= 500 && code < 600 && child.findtext('Item/Data') )
                                {
                                    ds.action = 'error';
                                    ds.error  = getError(child);
                                    ds.stats.peerErr += 1;
                                    return cb();
                                }
                                return cb(badStatus(child));
                            }
                        if ( ds.action == 'send' )
                        {
                            if ( session.isServer )
                            {
                                ds.action = 'save';
                                return cb();
                            }
                            ds.action = common.oneWayOut(session, ds.mode) ? 'done' : 'recv';
                            return cb();
                        }
                        return cb(new common.ProtocolError('unexpected sync state for action=' + ds.action));
                    }

                case constant.CMD_ADD:
                case constant.CMD_REPLACE:
                case constant.CMD_DELETE:
                    {
                        var scmd = state.makeCommand({
                            name       : cname,
                            msgID      : hdrcmd.msgID,
                            cmdID      : child.findtext('CmdID'),
                            sourceRef  : sourceRef,
                            targetRef  : targetRef,
                            data       : code
                        });

                        session.context.synchronizer.settle(
                                session, scmd, chkcmd, child,
                                function(err, cmds) {
                                    if ( err )
                            return cb(err);
                        _.each(cmds, function(cmd) { commands.push(cmd); });
                        return cb();
                                });
                        return;
                    }

                case constant.CMD_MAP:
                    {
                        if ( session.isServer )
                            return cb(new common.ProtocolError(
                                        'unexpected server-side status for command "' + cname + '"'));
                        if ( code != constant.STATUS_OK )
                            return cb(badStatus(child));
                        return cb();
                    }

                default:
                    {
                        return cb(new common.ProtocolError('unexpected status for command "' + cname + '"'));
                    }

            }

            }, cb);

        };

        // second, check all the non-'Status' commands

        var consumeCommands = function(cb) {

            var gotFinal = false;

            common.cascade(children, function(child, cb) {


                if ( child.tag == constant.CMD_STATUS )
                return cb();

            if ( child.tag == constant.CMD_FINAL )
            {
                gotFinal = true;
                return cb();
            }


            // todo: restrict this to the following commands?...
            //         CMD_ALERT, CMD_GET, CMD_PUT,
            //         CMD_SYNC, CMD_RESULTS, CMD_MAP

            var func = self['_consume_node_' + child.tag.toLowerCase()];

            if ( ! func )
                return cb(new common.ProtocolError('unexpected command node "' + child.tag + '"'));

            try{

                func.call(self, session, lastcmds, xsync, child, function(err, cmds) {
                    if ( err )
                    return cb(err);
                _.each(cmds, function(cmd) { commands.push(cmd); });
                return cb();
                });

            }catch(e){
                // log.error('failed invoking protocol sub-consumption of "%s": %s', child.tag, e);
                // log.error('  ' + stacktrace({e: e}).join('\n  '));
                return cb(new common.InternalError(
                            'failed invoking protocol sub-consumption of "' + child.tag + '": ' + e, e));
            }

            }, function(err) {

                if ( err )
                    return cb(err);

                if ( ! gotFinal )
                {
                    commands.push(state.makeCommand({
                        name       : constant.CMD_ALERT,
                        cmdID      : session.nextCmdID(),
                        data       : constant.STATUS_NEXT_MESSAGE,
                        source     : session.adapter.devID,
                        target     : session.peer.devID,
                    }));
                }

                return cb();

            });

        };

        // do it!

        consumeStatus(function(err) {

            if ( err )
            return cb(err);

        // TODO: is this right?... or should i be getting pissed off and
        //       raising hell that all my commands were not addressed?...

        _.each(chkcmds, function(chkcmd) {
            commands.push(chkcmd);
        });

        return consumeCommands(function(err) {
            if ( err )
            return cb(err);
        return cb(null, commands);
        });

        });

    },

    //-------------------------------------------------------------------------
    _consume_node_get: function(session, lastcmds, xsync, xnode, cb) {
        var cttype = xnode.findtext('Meta/Type');
        var target = xnode.findtext('Item/Target/LocURI');
        if ( cttype.indexOf(constant.TYPE_SYNCML_DEVICE_INFO) == 0
                && session.adapter.normUri(target) == constant.URI_DEVINFO_1_2 )
            return this._consume_node_get_devinf12(session, lastcmds, xsync, xnode, cb);
        // todo: make error status node...
        cb(new common.ProtocolError(
                    'unexpected "' + constant.CMD_GET + '" command for local "' + target + '"'));
    },

    //-------------------------------------------------------------------------
    _consume_node_get_devinf12: function(session, lastcmds, xsync, xnode, cb) {
        var ret = [];
        ret.push(state.makeCommand({
            name       : constant.CMD_STATUS,
            cmdID      : session.nextCmdID(),
            msgRef     : session.info.pendingMsgID,
            cmdRef     : xnode.findtext('CmdID'),
            statusOf   : xnode.tag,
            statusCode : constant.STATUS_OK,
            targetRef  : xnode.findtext('Item/Target/LocURI')
        }));
        ret.push(state.makeCommand({
            name       : constant.CMD_RESULTS,
            cmdID      : session.nextCmdID(),
            msgRef     : session.info.pendingMsgID,
            cmdRef     : xnode.findtext('CmdID'),
            type       : constant.TYPE_SYNCML_DEVICE_INFO + '+' + session.info.codec,
            source     : './' + constant.URI_DEVINFO_1_2,
            data       : session.adapter.devInfo.toSyncML(constant.SYNCML_DTD_VERSION_1_2,
                _.values(session.adapter._stores))

        }));
        cb(null, ret);
    },

    //-------------------------------------------------------------------------
    _consume_node_put: function(session, lastcmds, xsync, xnode, cb) {
        var cttype = xnode.findtext('Meta/Type');
        var source = xnode.findtext('Item/Source/LocURI');
        if ( cttype.indexOf(constant.TYPE_SYNCML_DEVICE_INFO) == 0
                && session.peer.normUri(source) == constant.URI_DEVINFO_1_2 )
            return this._consume_node_put_devinf12(session, lastcmds, xsync, xnode, cb);
        // todo: make error status node...
        cb(new common.ProtocolError(
                    'unexpected "' + constant.CMD_PUT + '" command for remote "' + source + '"'));
    },

    //-------------------------------------------------------------------------
    _consume_node_put_devinf12: function(session, lastcmds, xsync, xnode, cb) {
        var xdev = xnode.find('Item/Data/DevInf');
        var res  = devinfo.DevInfo.fromSyncML(xdev);
        session.peer._setRemoteInfo(res[0], res[1], function(err) {
            if ( err )
            return cb(err);

        var okcmd = state.makeCommand({
            name       : constant.CMD_STATUS,
            cmdID      : session.nextCmdID(),
            msgRef     : xsync.findtext('SyncHdr/MsgID'),
            cmdRef     : xnode.findtext('CmdID'),
            sourceRef  : xnode.findtext('Item/Source/LocURI'),
            statusOf   : xnode.tag,
            statusCode : constant.STATUS_OK
        });

        if ( session.isServer )
            return cb(null, [okcmd]);

        // TODO: this should only cause a `recalculate` if any
        //       meta-information actually changed...

        session.context.router.recalculate(session.adapter, session.peer, function(err) {
            if ( err )
            return cb(err);
        session.context.synchronizer.initStoreSync(session, function(err) {
            if ( err )
            return cb(err);

        // TODO: the call to _setRemoteInfo makes the peer
        //       "dirty" without saving changes to the model...
        //       make sure the `save` executed in Adapter.sync()
        //       or Adapter.handleRequest() appropriately causes
        //       objects to save themselves to the model...

        // session.adapter._save(session.txn(), function(err) {
        //   if ( err )
        //     return cb(err);

        return cb(null, [okcmd]);

        // });

        });
        });
        });
    },

    //-------------------------------------------------------------------------
    _consume_node_results: function(session, lastcmds, xsync, xnode, cb) {
        var cttype = xnode.findtext('Meta/Type');
        var source = xnode.findtext('Item/Source/LocURI');
        if ( cttype.indexOf(constant.TYPE_SYNCML_DEVICE_INFO) == 0
                && session.peer.normUri(source) == constant.URI_DEVINFO_1_2 )
            return this._consume_node_put_devinf12(session, lastcmds, xsync, xnode, cb);
        // todo: make error status node...
        return cb(new common.ProtocolError('unexpected "' + constant.CMD_RESULTS
                    + '" command for remote "' + source + '"'))
    },

    //-------------------------------------------------------------------------
    _consume_node_alert: function(session, lastcmds, xsync, xnode, cb) {
        var code = common.int(xnode.findtext('Data'));
        var statusCode = constant.STATUS_OK
            switch ( code )
            {
                case constant.ALERT_TWO_WAY:
                case constant.ALERT_SLOW_SYNC:
                case constant.ALERT_ONE_WAY_FROM_CLIENT:
                case constant.ALERT_REFRESH_FROM_CLIENT:
                case constant.ALERT_ONE_WAY_FROM_SERVER:
                case constant.ALERT_REFRESH_FROM_SERVER:
                    // todo: these should only be received out-of-band: right?...
                    // case constant.ALERT_TWO_WAY_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
                    {
                        break;
                    }
                default:
                    {
                        if ( session.isServer && code == constant.STATUS_RESUME )
                        {
                            code = constant.ALERT_SLOW_SYNC;
                        }
                        else
                        {
                            return cb(new common.FeatureNotSupported(
                                        'unimplemented sync mode '
                                        + code + ' ("' + common.mode2string(code) + '")'));
                        }
                    }
            }

        if ( session.isServer )
        {
            // TODO: if this is the server, we need to validate that the requested
            //       sync mode is actually feasible... i.e. check:
            //         - do the anchors match?
            //         - have we bound the datastores together?
            //         - is there a pending sync?
        }

        var uri  = session.adapter.normUri(xnode.findtext('Item/Target/LocURI'));
        var ruri = session.peer.normUri(xnode.findtext('Item/Source/LocURI'));

        // TODO: this should really be done by the synchronizer... as it can
        //       then also do a lot of checks - potentially responding with
        //       an error...

        var getDS = function(cb) {
            if ( session.isServer )
            {
                var ds = session.info.dsstates[uri];
                if ( ds )
                {
                    ds.action = 'alert';
                    return cb(null, ds);
                }

                var peerStore = session.peer.getStore(ruri);
                if ( ! peerStore )
                    return cb(new common.ProtocolError(
                                'request to synchronize unknown remote client URI "' + ruri
                                + '" (to local server URI "' + uri + '")'));

                // todo: if already correctly bound, then we don't need to re-bind
                // if ( peerStore._getBinding() )
                // {
                //   log.critical('(currently bound)');
                // }
                // else
                //   log.critical('(currently unbound)');

                session.peer.setRoute(uri, ruri, true, function(err) {
                    if ( err )
                    return cb(err);
                var peerStore = session.peer.getStore(ruri);
                var ds = state.makeStoreSyncState({
                    uri        : uri,
                    peerUri    : ruri,
                    lastAnchor : peerStore._getBinding().localAnchor,
                    mode       : null,
                    action     : 'alert'
                });
                session.info.dsstates[uri] = ds;
                return cb(null, ds);
                });
                return;
            }
            else
            {
                var ds = session.info.dsstates[uri];
                if ( ! ds )
                    return cb(new common.ProtocolError('request for unreflected local datastore "'
                                + uri + '"'));
                ds.action = 'send';
                if ( code == ds.mode )
                    return cb(null, ds);

                var uaEvent = {
                    session   : session,
                    uri       : uri,
                    peerUri   : ruri,
                    modeReq   : ds.mode,
                    modeRes   : code
                };
                session.ua.acceptSyncModeSwitch(uaEvent, function(err) {
                    if ( err )
                {
                    return cb(err);
                }
                if ( session.context.listener )
                    session.context.listener(uaEvent);
                return cb(null, ds);
                });
            }
        };


        getDS(function(err, ds) {

            if ( err )
            return cb(err);

        ds.mode = code;
        ds.peerLastAnchor = xnode.findtext('Item/Meta/Anchor/Last', null);
        ds.peerNextAnchor = xnode.findtext('Item/Meta/Anchor/Next', null);

        if ( ds.peerLastAnchor != session.peer.getStore(ruri)._getBinding().remoteAnchor )
        {
            ds.peerLastAnchor = null;
            switch ( ds.mode )
        {
            case constant.ALERT_SLOW_SYNC:
            case constant.ALERT_REFRESH_FROM_CLIENT:
            case constant.ALERT_REFRESH_FROM_SERVER:
                {
                    break;
                }
            default:
                {
                    if ( session.isServer )
                    {
                        ds.mode = constant.ALERT_SLOW_SYNC;
                        statusCode = constant.STATUS_REFRESH_REQUIRED;
                    }
                    else
                    {
                        // todo: should i assume that the server knows something
                        //       that i don't and just go along with it?...
                        return cb(new common.ProtocolError(
                                    'server-side requested inappropriate ' + common.mode2string(ds.mode)
                                    + ' sync mode on unbound datastore "' + uri + '"'));
                    }
                }
        }
        }

        return cb(null, [state.makeCommand({
            name       : constant.CMD_STATUS,
               cmdID      : session.nextCmdID(),
               msgRef     : xsync.findtext('SyncHdr/MsgID'),
               cmdRef     : xnode.findtext('CmdID'),
               targetRef  : xnode.findtext('Item/Target/LocURI'),
               sourceRef  : xnode.findtext('Item/Source/LocURI'),
               statusOf   : xnode.tag,
               statusCode : statusCode,
               // todo: syncevolution does not echo the remote last anchor... why not?
               lastAnchor : ds.peerLastAnchor,
               nextAnchor : ds.peerNextAnchor
        })]);

        });

    },

    //-------------------------------------------------------------------------
    _consume_node_sync: function(session, lastcmds, xsync, xnode, cb) {
        var self   = this;
        var uri    = xnode.findtext('Target/LocURI');
        var store  = session.adapter.getStore(session.adapter.normUri(uri));
        var ds     = session.info.dsstates[session.adapter.normUri(uri)];
        var commands = [state.makeCommand({
            name        : constant.CMD_SYNC,
            msgID       : xsync.findtext('SyncHdr/MsgID'),
            cmdID       : xnode.findtext('CmdID'),
            source      : xnode.findtext('Source/LocURI'),
            target      : uri,
            data        : [],
        })];
        var noc = common.int(xnode.findtext('NumberOfChanges'));
        if (noc !== undefined) {
            changednum = noc;
            _counts = 0;
        }
        common.cascade(xnode.getchildren(), function(child, cb) {
            switch ( child.tag )
        {
            case 'CmdID':
            case 'Target':
            case 'Source':
            case 'NumberOfChanges':
                {
                    return cb();
                }
            case constant.CMD_ADD:
            case constant.CMD_REPLACE:
            case constant.CMD_DELETE:
                {
                    var func = self['_consume_sync_' + child.tag.toLowerCase()];
                    func.call(self, session, lastcmds, store, xsync, child, function(err, cmds) {
                        if ( err )
                        return cb(err);
                    _.each(cmds, function(cmd) { commands[0].data.push(cmd); });
                    return cb();
                    });
                    return;
                }
            default:
                {
                    return cb(new common.ProtocolError('unexpected sync command "' + child.tag + '"'));
                }
        }
        }, function(err) {
            if ( err )
                return cb(err);
            // confirm that i received the right number of changes...
            /*
               if ( noc != undefined && noc != commands[0].data.length )
               return cb(new common.ProtocolError('number-of-changes mismatch (received '
               + commands[0].data.length + ', expected '
               + noc + ')'));
               */
            _counts =  _counts + commands[0].data.length;
            if ( ds.action != 'error' )
            {
                if ( ! session.isServer )
                {
                    if ( ds.action != 'recv' )
                        return cb(new common.ProtocolError('unexpected sync state for URI "'
                                    + uri + '": action=' + ds.action));
                    if (changednum != undefined && changednum <= _counts)  {
                        ds.action = 'done';
                        changednum = undefined;
                        _counts = 0;
                    }
                }
                else
                {
                    if ( ds.action != 'alert' )
                        return cb(new common.ProtocolError(
                                    'unexpected sync state for URI "' + uri + '": action=' + ds.action));
                    ds.action = common.oneWayIn(session, ds.mode) ? 'save' : 'send';
                }
            }
            return session.context.synchronizer.reactions(session, commands, cb);
        });
    },

    //-------------------------------------------------------------------------
    _consume_xnode2item: function(session, lastcmds, store, xsync, xnode, cb) {
        var ctype  = xnode.findtext('Meta/Type');
        // todo: can the version be specified in the Meta tag?... maybe create an
        //       extension to SyncML to communicate this?...
        var ctver  = null;
        var format = xnode.findtext('Meta/Format');
        var xitem  = xnode.findall('Item/Data');
        if ( xitem.length > 1 )
            return cb(new common.ProtocolError(
                        '"' + xnode.tag + '" command with non-singular item data nodes'));
        if ( xitem.length < 1 )
            return cb(new common.ProtocolError(
                        '"' + xnode.tag + '" command with missing data node'));
        var xitem = xitem[0];
        // todo: confirm that getchildren only returns element nodes...
        if ( xitem.getchildren().length == 1 )
            data = xitem.getchildren()[0];
        else
        {
            data = xitem.text;
            if ( format == constant.FORMAT_B64 )
                data = base64.decode(data);
        }
        return store.agent.loadsItem(data, ctype, ctver, cb);
    },

    //-------------------------------------------------------------------------
    _consume_sync_add: function(session, lastcmds, store, xsync, xnode, cb) {
        this._consume_xnode2item(session, lastcmds, store, xsync, xnode, function(err, item) {
            if ( err )
            return cb(err);
        return cb(null, [state.makeCommand({
            name          : constant.CMD_ADD,
               msgID         : xsync.findtext('SyncHdr/MsgID'),
               cmdID         : xnode.findtext('CmdID'),
               source        : xnode.findtext('Item/Source/LocURI'),
               sourceParent  : xnode.findtext('Item/SourceParent/LocURI'),
               targetParent  : xnode.findtext('Item/TargetParent/LocURI'),
               data          : item
        })]);
        });
    },

    //-------------------------------------------------------------------------
    _consume_sync_replace: function(session, lastcmds, store, xsync, xnode, cb) {
        this._consume_xnode2item(session, lastcmds, store, xsync, xnode, function(err, item) {
            if ( err )
            return cb(err);
        return cb(null, [state.makeCommand({
            name          : constant.CMD_REPLACE,
               msgID         : xsync.findtext('SyncHdr/MsgID'),
               cmdID         : xnode.findtext('CmdID'),
               source        : xnode.findtext('Item/Source/LocURI'),
               sourceParent  : xnode.findtext('Item/SourceParent/LocURI'),
               target        : xnode.findtext('Item/Target/LocURI'),
               targetParent  : xnode.findtext('Item/TargetParent/LocURI'),
               data          : item
        })]);
        });
    },

    //-------------------------------------------------------------------------
    _consume_sync_delete: function(session, lastcmds, store, xsync, xnode, cb) {
        return cb(null, [state.makeCommand({
            name          : constant.CMD_DELETE,
        msgID         : xsync.findtext('SyncHdr/MsgID'),
        cmdID         : xnode.findtext('CmdID'),
        source        : xnode.findtext('Item/Source/LocURI'),
        sourceParent  : xnode.findtext('Item/SourceParent/LocURI'),
        target        : xnode.findtext('Item/Target/LocURI'),
        targetParent  : xnode.findtext('Item/TargetParent/LocURI')
        })]);
    },

    // #----------------------------------------------------------------------------
    // def makeStatus(self, session, xsync, xnode, status=constant.STATUS_OK, **kw):
    //   return state.Command(
    //     name       = constant.CMD_STATUS,
    //     cmdID      = session.nextCmdID(),
    //     msgRef     = xsync.findtext('SyncHdr/MsgID'),
    //     cmdRef     = xnode.findtext('CmdID'),
    //     statusOf   = xnode.tag,
    //     statusCode = status,
    //     **kw
    //     )

    //-------------------------------------------------------------------------
    _consume_node_map: function(session, lastcmds, xsync, xnode, cb) {
        if ( ! session.isServer )
            return cb(new common.ProtocolError(
                        'unexpected "Map" command received by client-side SyncML peer'));
        // TODO: convert the sender-side to support command.items like
        //       this as well...
        var cmd = state.makeCommand({
            name    : constant.CMD_MAP,
            msgID   : xsync.findtext('SyncHdr/MsgID'),
            cmdID   : xnode.findtext('CmdID'),
            source  : xnode.findtext('Source/LocURI'),
            target  : xnode.findtext('Target/LocURI'),
            items   : []
        });
        _.each(xnode.findall('MapItem'), function(xnode) {
            // todo: support hierarchical sync...
            cmd.items.push({
                source        : xnode.findtext('Source/LocURI'),
                // sourceParent  : xnode.findtext('SourceParent/LocURI'),
                target        : xnode.findtext('Target/LocURI'),
                // targetParent  : xnode.findtext('TargetParent/LocURI')
            });
        });
        return session.context.synchronizer.reactions(session, [cmd], cb);
    }


});

return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/remoteadapter', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.remoteadapter
// auth: griffin <griffin@uberdev.org>
// date: 2012/11/04
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    devinfomod = require('ripple/platform/tizen/2.0/syncml-js-lib/devinfo'),
    adapter = require('ripple/platform/tizen/2.0/syncml-js-lib/adapter'),
    storemod = require('ripple/platform/tizen/2.0/syncml-js-lib/store'),
    _self;

_self = (function () {
    var exports = {};

    //---------------------------------------------------------------------------
    exports.RemoteAdapter = adapter.Adapter.extend({

        //-------------------------------------------------------------------------
        constructor: function(adapter, options) {

            //: [read-only] the URL of the remote syncml peer, acting as a server,
            //: to connect to.
            this.url = options.url || null;

            //: [read-only] specifies whether this Adapter represents a local
            //: or remote peer.
            this.isLocal = false;

            //: [read-only] the DevID of the remote syncml peer (which usually
            //: defaults to the URL).
            this.devID = options.devID || options.url || null;

            //: [read-only] the authentication method to use to identify the local
            //: peer to the remote peer.
            ///TODO: this.auth = options.auth || null;
            this.auth = 'syncml:auth-basic';

            //: [read-only] the human-friendly display name of the remote peer.
            this.displayName = options.displayName || null;

            //: [read-only] the username to use during credential-based authentication.
            this.username = options.username || null;

            //: [read-only] the password to use during credential-based authentication.
            this.password = options.password || null;

            //: [read-only] the peer-wide default value of the maximum
            //: message size.
            this.maxMsgSize = options.maxMsgSize || null;

            //: [read-only] the peer-wide default value of the maximum
            //: object size.
            this.maxObjSize = options.maxObjSize || null;

            //: [read-only] the DevInfo object for this remote peer.
            this.devInfo = null;

            this.lastSessionID = options.lastSessionID || null;

            // --- private attributes
            this.id       = options.id || common.makeID();
            this._a       = adapter;
            this._c       = adapter._c;
            this._stores  = {};
            this._proxy   = null;

            // TODO: filter these options for db-valid only properties...
            this._options = options;
        },

            //-------------------------------------------------------------------------
            _load: function(cb) {

                var self  = this;
                var model = this._getModel();

                // todo: should this be loading these?...
                // self.displayName = model.displayName;
                // self.devID       = model.devID;

                var loadDevInfo = function(cb) {
                    var di = new devinfomod.DevInfo(self, model.devInfo);
                    di._load(function(err) {
                        if ( err )
                        return cb(err);
                    self.devInfo = di;
                    cb();
                    });
                };

                var loadStores = function(cb) {
                    common.cascade(model.stores, function(e, cb) {
                        var store = new storemod.Store(self, e);
                        store._load(function(err) {
                            if ( err )
                            return cb(err);
                        self._stores[store.uri] = store;
                        return cb();
                        });
                    }, cb);
                };

                loadDevInfo(function(err) {
                    if ( err )
                    return cb(err);
                loadStores(cb);
                });
            },

            //-------------------------------------------------------------------------
            _updateModel: function(cb) {
                var self = this;
                if ( ! this._a._model || ! this._a._model.peers )
                    return cb(new common.InternalError('peer created on un-initialized adapter'));
                var model = self._getModel();
                // todo: should this be in this._getModel()?...
                if ( ! model )
                {
                    model = {
                        id:       self.id,
                        devInfo:  null,
                        stores:   [],
                        routes:   []
                    };
                    self._a._model.peers.push(model);
                }

                model.isLocal         = 0;
                model.url             = self.url;
                model.devID           = self.devID;
                model.displayName     = self.displayName;
                model.auth            = self.auth;
                model.username        = self.username;
                model.password        = self.password;
                model.lastSessionID   = self.lastSessionID
                    model.maxMsgSize      = self.maxMsgSize;
                model.maxObjSize      = self.maxObjSize;

                common.cascade([

                        // update the devInfo model
                        function(cb) {
                            if ( ! self.devInfo )
                    return cb();
                return self.devInfo._updateModel(cb);
                        },

                        // update the stores model
                        function(cb) {
                            // TODO: this should really be the responsibility of the Store class...
                            // NOTE: since bindings are not stored in Store, they need to be saved
                            //       and re-applied.
                            // TODO: or, perhaps better, i should purge all unwanted stores
                            //       instead of doing this brute-force method...
                            var bindings = _.object(_.map(model.stores, function(store) {
                                return [store.uri, store.binding];
                            }));
                            model.stores = [];
                            common.cascade(_.values(self._stores), function(store, cb) {
                                store._updateModel(cb);
                            }, function(err) {
                                if ( err )
                                return cb(err);
                            _.each(bindings, function(binding, uri) {
                                var store = _.find(model.stores, function(s) { return s.uri == uri; });
                                if ( ! store )
                                return;
                            store.binding = binding;
                            });
                            return cb();
                            });
                        },

                        ], cb);

            },

            //-------------------------------------------------------------------------
            _getModel: function() {
                return _.find(this._a._model.peers,
                        function(e) { return e.id == this.id; }, this);
            },

            //-------------------------------------------------------------------------
            _setRemoteInfo: function(devInfo, stores, cb) {
                var self      = this;
                self._model   = self._getModel();
                devInfo._a    = self;
                self.devInfo  = devInfo;
                self.devInfo._updateModel(function(err) {
                    if ( err )
                    return cb(err);
                // merge the new datastore info with any pre-existing store bindings
                // step 1: prepare the new stores (clean up the URIs)
                var lut = _.object(_.map(stores, function(store) {
                    store.uri = self.normUri(store.uri);
                    return [store.uri, store];
                }));
                // step 2: remove all stores that are no longer mentioned
                self._stores = _.object(
                    _.map(
                        _.filter(_.keys(self._stores), function(oldUri) {
                            return _.indexOf(_.keys(lut), oldUri) >= 0;
                        }), function(uri) {
                            return [uri, self._stores[uri]];
                        }
                        )
                    );
                // step 3: merge the datastore info for existing stores
                var merge_stores = function(cb) {
                    common.cascade(_.values(self._stores), function(store, cb) {
                        store.merge(lut[store.uri], function(err) {
                            if ( err )
                            return cb(err);
                        delete lut[store.uri];
                        return cb();
                        });
                    }, cb);
                };
                // step 4: add new datastores
                var add_stores = function(cb) {
                    common.cascade(_.values(lut), function(store, cb) {
                        self.addStore(store, cb);
                    }, cb);
                };
                merge_stores(function(err) {
                    if ( err )
                    return cb(err);
                add_stores(cb);
                });
                });
            },

            //-------------------------------------------------------------------------
            setRoute: function(localUri, remoteUri, autoMapped, cb) {
                if ( _.isFunction(autoMapped) )
                    // defaulting 'autoMapped' to false
                    return this.setRoute(localUri, remoteUri, false, autoMapped);
                var pmodel = this._getModel();
                if ( ! pmodel )
                    return cb(new common.InternalError('could not locate this peer in local adapter'));
                pmodel.routes = _.filter(pmodel.routes, function(r) {
                    return r.localUri != localUri && r.remoteUri != remoteUri;
                });
                pmodel.routes.push({localUri   : localUri,
                    remoteUri  : remoteUri,
                    autoMapped : autoMapped
                });
                // now search through previous bindings, breaking incorrect ones...
                // NOTE: this requires that a router.recalculate() is called at
                //       some point later since other valid bindings may now be
                //       possible...
                _.each(pmodel.stores, function(store) {
                    if ( store.uri != remoteUri
                        && ( ! store.binding || store.binding.uri != localUri ) )
                    {
                        return;
                    }
                    if ( ! store.binding )
                {
                    store.binding = {
                        uri          : localUri,
                    autoMapped   : autoMapped,
                    localAnchor  : null,
                    remoteAnchor : null
                    };
                    return;
                }
                if ( store.uri == remoteUri && store.binding.uri == localUri )
                {
                    store.binding.autoMapped = store.binding.autoMapped && autoMapped;
                    return;
                }
                store.binding = null;
                return;
                });
                // TODO: this additional route may impact "smart routing" - recalculate?...
                // TODO: saving adapter from peer --- SHOULD IT BE DOING THIS?...
                // TODO: get transaction from a session!...
                this._a._save(this._c._txn(), cb);
            },

            //-------------------------------------------------------------------------
            sendRequest: function(session, contentType, data, cb) {
                var xmlhttp;

                // TODO: shouldn't proxies just overwrite .sendRequest() ?...
                if ( this._proxy )
                    return this._proxy.sendRequest(session, contentType, data, cb);

                var req = {
                    url     : session.info.respUri || this.url,
                    method  : 'POST',
                    headers : {'Content-Type': contentType},
                    body    : data
                };

                xmlhttp = new XMLHttpRequest();
                xmlhttp.open(req.method, req.url, false);

                xmlhttp.setRequestHeader("Content-Type", contentType);
                xmlhttp.send(req.body);

                var response = {
                    headers: {
                        "Content-Type": xmlhttp.getResponseHeader("content-type")
                    },
                    body: xmlhttp.responseXML
                };
                return cb(null, response);
            }

    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/router', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.router
// auth: griffin <griffin@uberdev.org>
// date: 2012/11/04
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    ctype = require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
    matcher = require('ripple/platform/tizen/2.0/syncml-js-lib/matcher'),
    stablematch = require('ripple/platform/tizen/2.0/syncml-js-lib/stablematch'),
    _self;

_self = (function () {

    var exports = {};

    //---------------------------------------------------------------------------
    exports.Router = common.Base.extend({

        //-------------------------------------------------------------------------
        constructor: function(options) {
        },

        //-------------------------------------------------------------------------
        getTargetUri: function(adapter, peer, sourceUri) {
            var pmodel = peer._getModel();
            for ( var idx=0 ; idx<pmodel.routes.length ; idx++ )
    {
        var route = pmodel.routes[idx];
        if ( route.localUri == sourceUri )
        return route.remoteUri;
    }
    for ( var idx=0 ; idx<pmodel.stores.length ; idx++ )
    {
        var store = pmodel.stores[idx];
        if ( store.binding && store.binding.uri == sourceUri )
        return store.uri;
    }
    return null;
        },

        //-------------------------------------------------------------------------
        recalculate: function(adapter, peer, cb) {
            // the non-"SmartRouter" only connects manually-configured routes...
            var routes = _.filter(peer._getModel().routes,
                    function(r) { return ! r.autoMapped; });
            return this._setupRoutes(adapter, peer, routes, cb);
        },

        //-------------------------------------------------------------------------
        _setupRoutes: function(adapter, peer, routes, cb) {
            // available local URIs
            var lset = _.map(adapter._getModel().stores,
                    function(s) { return adapter.normUri(s.uri); });
            // available remote URIs
            var rset = _.map(peer._getModel().stores,
                    function(s) { return peer.normUri(s.uri); });

            // break all routes not listed
            var ruris = _.map(routes, function(r) { return r.remoteUri; });
            var xrset = _.filter(rset, function(uri) {
                return _.indexOf(ruris, uri) < 0;
            });
            _.each(xrset, function(uri) {
                var smodel = peer.getStore(uri)._getModel();
                if ( ! smodel.binding )
                return;
            smodel.binding = null;
            });

            var err = null;
            _.each(routes, function(route) {
                if ( err )
                return;

            route.localUri  = adapter.normUri(route.localUri);
            route.remoteUri = peer.normUri(route.remoteUri);
            if ( _.indexOf(rset, route.remoteUri) < 0
                || _.indexOf(lset, route.localUri) < 0 )
            {
                err = 'unable to route from "' + route.localUri
                + '" (here) to "' + route.remoteUri
                + '" (peer): no such stores or already routed elsewhere';
            return;
            }

            lset = _.filter(lset, function(uri) { return uri != route.localUri; });
            rset = _.filter(rset, function(uri) { return uri != route.remoteUri; });


            var smodel = peer.getStore(route.remoteUri)._getModel();
            if ( smodel.binding && smodel.binding.uri == route.localUri )
                return;
            smodel.binding = {
                uri          : route.localUri,
                autoMapped   : route.autoMapped,
                localAnchor  : null,
                remoteAnchor : null
            };
            });

            if ( err )
                return cb(err);

            return cb();
        },

        //-------------------------------------------------------------------------
        getBestTransmitContentType: function(adapter, peer, uri) {
            var lstore = adapter.getStore(uri);
            var rstore = peer.getStore(this.getTargetUri(adapter, peer, uri));
            return matcher.pickTransmitContentType(lstore, rstore);
        },

    });

    //---------------------------------------------------------------------------
    exports.SmartRouter = exports.Router.extend({

        //-------------------------------------------------------------------------
        recalculate: function(adapter, peer, cb) {

            // note: if you don't want smart routing, assign the non-SmartRouter
            //       router (i.e. syncml-js.Router) to the loaded context

            // available local URIs
            var llut = _.object(
                _.map(adapter._getModel().stores,
                    function(s) { return [adapter.normUri(s.uri), s]; }));
            var lset = _.keys(llut);

            // available remote URIs
            var rlut = _.object(
                _.map(peer._getModel().stores,
                    function(s) { return [adapter.normUri(s.uri), s]; }));
            var rset = _.keys(rlut);

            // TODO: i am directly touching the model here.
            //       total i-rep violation.
            //       i'm embarrassed.
            //       fortunately, it's just between syncml-js classes...
            //       but now you know, doh! please don't blackmail me!... ;-)

            // manual routes
            var pmodel = peer._getModel();
            pmodel.routes = _.filter(pmodel.routes,
                    function(r) { return ! r.autoMapped; });

            // remove manual routes from available routes
            var uris = _.map(pmodel.routes, function(r) { return r.localUri; });
            lset = _.filter(lset, function(uri) {
                return _.indexOf(uris, uri) < 0;
            });
            uris = _.map(pmodel.routes, function(r) { return r.remoteUri; });
            rset = _.filter(rset, function(uri) {
                return _.indexOf(uris, uri) < 0;
            });

            // match remaining stores
            var rankL = function(luri) {
                var ret = _.rest(rset, 0);
                ret.sort(function(a, b) {
                    return matcher.cmpStore(llut[luri], rlut[a], rlut[b]);
                });
                return ret;
            };
            var rankR = function(ruri) {
                var ret = _.rest(lset, 0);
                ret.sort(function(a, b) {
                    return matcher.cmpStore(rlut[ruri], llut[a], llut[b]);
                });
                return ret;
            };
            var matches = stablematch.match(lset, rset, rankL, rankR);

            // add them to the routes (as auto-routed)
            for ( var idx=0 ; idx<matches.length ; idx++ )
            {
                var pair = matches[idx];
                pmodel.routes.push({
                    localUri   : pair[0],
                    remoteUri  : pair[1],
                    autoMapped : true
                });
            }

            return this._setupRoutes(adapter, peer, pmodel.routes, cb);
        },

    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/stablematch', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// desc: implements a solution to the stable matching problem using a
//       left-optimized algorithm. shamelessly adapted from:
//         https://github.com/paulgb/Python-Gale-Shapley/
// auth: metagriffin <mg.npmjs@uberdev.org>
// date: 2012/12/29
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var _self = (function () {

    var exports = {};

    // TODO: figure out how to pull this dynamically from package.json...
    exports.version = '0.0.4';

    //---------------------------------------------------------------------------
    exports.match = function(A, B, rankA, rankB) {
        if ( ! A || ! B || ! A.length || ! B.length ) {
            return [];
        }
        if ( A.length == B.length ) {
            return exports._match(A, B, rankA, rankB);
        }

        // TODO: this is a brute-force implementation of getting both
        //       lists to be of symmetric length... make this "better".
        //       for example, build this directly into _match() or use
        //       deterministic exclusion of the longer data set.

        var sA   = _.rest(A, 0);
        var sB   = _.rest(B, 0);
        var mlen = Math.max(sA, sB);
        while ( sA.length < mlen )
            sA.push(null);
        while ( sB.length < mlen )
            sB.push(null);
        var sRA  = function(a) {
            var ret = rankA(a);
            while ( ret.length < mlen )
                ret.push(null);
            return ret;
        };
        var sRB  = function(b) {
            var ret = rankB(b);
            while ( ret.length < mlen )
                ret.push(null);
            return ret;
        };
        var ret = exports._match(sA, sB, sRA, sRB);
        return _.filter(ret, function(pair) {
            return pair[0] != null && pair[1] != null;
        });
    };

    //---------------------------------------------------------------------------
    exports._match = function(A, B, rankA, rankB) {
        // this translates sets A and B to indeces, since _imatch can only work
        // with sets of elements that can be used as the key in a hash (in this
        // implementation).
        var iA  = _.range(A.length);
        var iB  = _.range(B.length);
        var iRA = function(ia) {
            var ret = rankA(A[ia]);
            return _.map(ret, function(item) {
                return _.indexOf(B, item);
            });
        };
        var iRB = function(ib) {
            var ret = rankB(B[ib]);
            return _.map(ret, function(item) {
                return _.indexOf(A, item);
            });
        };
        var ret = exports._imatch(iA, iB, iRA, iRB);
        return _.map(ret, function(item) {
            return [A[item[0]], B[item[1]]];
        });
    };

    //---------------------------------------------------------------------------
    exports._imatch = function(A, B, rankA, rankB) {
        // TODO: improve this... it was a brute-force porting of
        //         https://github.com/paulgb/Python-Gale-Shapley
        //       without any eye on optimal outcome or performance...
        //: `partners` is a paring hash of { a => [b, rank] }
        var partners = {};
        _.each(A, function(a) {
            partners[a] = [rankA(a)[0], 0];
        });
        //: `stable` indicates stability of the current pairing in `partners`
        var stable = false;
        while ( ! stable )
        {
            stable = true;
            _.each(B, function(b) {
                var paired = false;
                for ( var n=0 ; n<A.length ; n++ )
                {
                    var a = rankB(b)[n];
                    var pair = partners[a];
                    if ( pair[0] == b )
                    {
                        if ( paired )
                        {
                            stable = false;
                            partners[a] = [rankA(a)[pair[1] + 1], pair[1] + 1];
                        }
                        else
                            paired = true;
                    }
                }
            });
        }
        return _.map(_.keys(partners), function(a) {
            return [a, partners[a][0]];
        });
    };

    return exports;
})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/state', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// auth: metagriffin <metagriffin@uberdev.org>
// date: 2012/10/27
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    _self;

_self = (function () {
    var exports = {};

    //---------------------------------------------------------------------------
    exports.makeCommand = function(options) {
        return _.defaults({}, options, {
            // ?
        });
    };

    //---------------------------------------------------------------------------
    exports.makeStats = function(options) {
        return _.defaults({}, options, {
            mode      : null,
               hereAdd   : 0,
               hereMod   : 0,
               hereDel   : 0,
               hereErr   : 0,
               peerAdd   : 0,
               peerMod   : 0,
               peerDel   : 0,
               peerErr   : 0,
               conflicts : 0,
               merged    : 0,
        });
    };

    //---------------------------------------------------------------------------
    exports.makeSessionInfo = function(options) {
        return _.defaults({}, options, {
            id           : null,
               msgID        : null,
               cmdID        : 0,
               dsstates     : {},
               lastCommands : [],
               stats        : exports.makeStats()
        });
    };

    //---------------------------------------------------------------------------
    exports.makeStoreSyncState = function(options) {
        return _.defaults({}, options, {
            uri        : null,
               peerUri    : null,
               lastAnchor : null,
               nextAnchor : '' + common.ts(),
               mode       : constant.ALERT_TWO_WAY,
               action     : null,
               stats      : exports.makeStats()
        });
    };

    //---------------------------------------------------------------------------
    exports.makeSession = function(options) {
        return new (function() {
            this.context   = options.context || null;
            this.ua        = options.ua      || null;
            this.txn       = options.txn     || options.context.txn;
            this.adapter   = options.adapter || null;
            this.peer      = options.peer    || null;
            this.info      = options.info    || null;
            this.discover  = options.discover ? true : false;
            this.isServer  = options.isServer ? true : false;
            this.nextCmdID = function() {
                this.info.cmdID += 1;
                return this.info.cmdID;
            };
        })();

        // return _.defaults({}, options, {
        //   context : null,
        //   adapter : null,
        //   peer    : null,
        //   info    : null
        // });
    };

    var smult = function(s, count) {
        var ret = '';
        for ( var idx=0 ; idx<count ; idx++ )
            ret += s;
        return ret;
    };

    var num2str = function(num) {
        // TODO: i18n...
        // TODO: this is *UGLY*
        // TODO: OMG, i'm *so* embarrassed
        // TODO: but it works... sort of.
        if ( num == 0 )
            return '-';
        var ret = '';
        num = '' + num;
        for ( var idx=num.length ; idx>0 ; idx-=3 )
        {
            if ( ret.length > 0 )
                ret = ',' + ret;
            ret = num.charAt(idx - 1) + ret;
            if ( idx - 1 > 0 )
                ret = num.charAt(idx - 2) + ret;
            if ( idx - 2 > 0 )
                ret = num.charAt(idx - 3) + ret;
        }
        return ret;
    };

    var center = function(s, wid, pad) {
        // todo: is there no way to get sprintf to do this for me???...
        pad = pad || ' ';
        if ( wid <= s.length )
            return s;
        var diff = wid - s.length;
        return smult(pad, Math.floor(diff / 2)) + s + smult(pad, Math.ceil(diff / 2));
    };

    var right = function(s, wid, pad) {
        // todo: is there no way to get sprintf to do this for me???...
        pad = pad || ' ';
        if ( wid <= s.length )
            return s;
        return smult(pad, wid - s.length) + s;
    };

    //---------------------------------------------------------------------------
    // TODO: this should probably be put into another package...
    exports.describeStats = function(stats, stream, options) {

        // ASCII OBJECTIVE:
        // +----------------------------------------------------------------------------------+
        // |                                      TITLE                                       |
        // +----------+------+-------------------------+--------------------------+-----------+
        // |          |      |          Local          |          Remote          | Conflicts |
        // |   Source | Mode |  Add  | Mod | Del | Err |   Add  | Mod | Del | Err | Col | Mrg |
        // +----------+------+-------+-----+-----+-----+--------+-----+-----+-----+-----+-----+
        // | contacts |  <=  |   -   |  -  |  -  |  -  | 10,387 |  -  |  -  |  -  |  -  |  -  |
        // |     note |  SS  | 1,308 |  -  |   2 |  -  |    -   |  -  |  -  |  -  |  -  |  -  |
        // +----------+------+-------+-----+-----+-----+--------+-----+-----+-----+-----+-----+
        // |                  1,310 local changes and 10,387 remote changes.                  |
        // +----------------------------------------------------------------------------------+

        // UNICODE OBJECTIVE:
        // ┌──────────────────────────────────────────────────────────────────────────────────┐
        // │                                      TITLE                                       │
        // ├──────────┬──────┬─────────────────────────┬──────────────────────────┬───────────┤
        // │          │      │          Local          │          Remote          │ Conflicts │
        // │   Source │ Mode │  Add    Mod   Del   Err │   Add    Mod   Del   Err │ Col   Mrg │
        // ├──────────┼──────┼───────┼─────┼─────┼─────┼────────┼─────┼─────┼─────┼─────┼─────┤
        // │ contacts │  <=  │       │     │     │     │ 10,387 │     │     │     │     │     │
        // │     note │  SS  │ 1,308 │     │   2 │     │        │     │     │     │     │     │
        // ├──────────┴──────┴───────┴─────┴─────┴─────┴────────┴─────┴─────┴─────┴─────┴─────┤
        // │                  1,310 local changes and 10,387 remote changes.                  │
        // └──────────────────────────────────────────────────────────────────────────────────┘

        // todo: perhaps the fancy version should have color-coding as well?...

        options = _.defaults({}, options, {
            title      : null,
                details    : true,
                totals     : true,
                ascii      : false,
                gettext    : function(text) { return text; }
        });

        var modeStringLut = _.object([
                [constant.SYNCTYPE_TWO_WAY             , '<>'],
                [constant.SYNCTYPE_SLOW_SYNC           , 'SS'],
                [constant.SYNCTYPE_ONE_WAY_FROM_CLIENT , '->'],
                [constant.SYNCTYPE_REFRESH_FROM_CLIENT , '=>'],
                [constant.SYNCTYPE_ONE_WAY_FROM_SERVER , '<-'],
                [constant.SYNCTYPE_REFRESH_FROM_SERVER , '<=']
                ]);

        if ( options.ascii )
        {

            // unicode graphing characters: ('\xe2\x94\x80' - '\xe2\x94\xc0')
            // mapping table unicode ==> ascii

            glyphs = {
                '─': '-',
                '━': '-',
                '│': '|',
                '┃': '|',
                '┄': '-',
                '┅': '-',
                '┆': '|',
                '┇': '|',
                '┈': '-',
                '┉': '-',
                '┊': '|',
                '┋': '|',
                '┌': '+',
                '┍': '+',
                '┎': '+',
                '┏': '+',
                '┐': '+',
                '┑': '+',
                '┒': '+',
                '┓': '+',
                '└': '+',
                '┕': '+',
                '┖': '+',
                '┗': '+',
                '┘': '+',
                '┙': '+',
                '┚': '+',
                '┛': '+',
                '├': '+',
                '┝': '+',
                '┞': '+',
                '┟': '+',
                '┠': '+',
                '┡': '+',
                '┢': '+',
                '┣': '+',
                '┤': '+',
                '┥': '+',
                '┦': '+',
                '┧': '+',
                '┨': '+',
                '┩': '+',
                '┪': '+',
                '┫': '+',
                '┬': '+',
                '┭': '+',
                '┮': '+',
                '┯': '+',
                '┰': '+',
                '┱': '+',
                '┲': '+',
                '┳': '+',
                '┴': '+',
                '┵': '+',
                '┶': '+',
                '┷': '+',
                '┸': '+',
                '┹': '+',
                '┺': '+',
                '┻': '+',
                '┼': '+',
                '┽': '+',
                '┾': '+',
                '┿': '+',
            };

            var UnicodeToAsciiStream = common.Stream.extend({
                constructor: function(stream) {
                    this.stream = stream;
                },
                write: function(data) {
                    if ( data == undefined )
                return;
            var ascii = '';
            for ( var idx=0 ; idx<data.length ; idx++ )
            {
                var el = data[idx];
                if ( glyphs[el] != undefined )
                ascii += glyphs[el];
                else
                ascii += el;
            }
            this.stream.write(ascii);
                }
            });

            stream = new UnicodeToAsciiStream(stream);

        }

        // todo: this does not handle the case where the title is wider than the table.

        var wSrc  = options.gettext('Source').length;
        var wMode = options.gettext('Mode').length;
        var wCon  = options.gettext('Conflicts').length;
        var wCol  = options.gettext('Col').length;
        var wMrg  = options.gettext('Mrg').length;
        var wHereAdd = wPeerAdd = options.gettext('Add').length;
        var wHereMod = wPeerMod = options.gettext('Mod').length;
        var wHereDel = wPeerDel = options.gettext('Del').length;
        var wHereErr = wPeerErr = options.gettext('Err').length

            var totLoc = 0;
        var totRem = 0;
        var totErr = 0;
        var totCol = 0;
        var totMrg = 0;

        _.each(stats, function(value, key) {
            wSrc  = Math.max(wSrc, key.length);
            wMode = Math.max(wMode, modeStringLut[value.mode].length);
            wCol  = Math.max(wCol, num2str(value.conflicts).length);
            wMrg  = Math.max(wMrg, num2str(value.merged).length);
            wHereAdd = Math.max(wHereAdd, num2str(value.hereAdd).length);
            wPeerAdd = Math.max(wPeerAdd, num2str(value.peerAdd).length);
            wHereMod = Math.max(wHereMod, num2str(value.hereMod).length);
            wPeerMod = Math.max(wPeerMod, num2str(value.peerMod).length);
            wHereDel = Math.max(wHereDel, num2str(value.hereDel).length);
            wPeerDel = Math.max(wPeerDel, num2str(value.peerDel).length);
            wHereErr = Math.max(wHereErr, num2str(value.hereErr).length);
            wPeerErr = Math.max(wPeerErr, num2str(value.peerErr).length);
            totLoc += value.hereAdd + value.hereMod + value.hereDel;
            totRem += value.peerAdd + value.peerMod + value.peerDel;
            totErr += value.hereErr + value.peerErr;
            totCol += value.conflicts;
            totMrg += value.merged;
        });

        // TODO: i'm 100% sure there is a python library that can do this for me...

        if ( wCon > wCol + 3 + wMrg )
        {
            diff = wCon - ( wCol + 3 + wMrg );
            wCol += diff / 2;
            wMrg = wCon - 3 - wCol;
        }
        else
            wCon = wCol + 3 + wMrg;

        if ( options.details )
            tWid = ( wSrc + 3 + wMode + 3
                    + wHereAdd + wHereMod + wHereDel + wHereErr + 9 + 3
                    + wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 + 3
                    + wCon );
        else
            tWid = options.title ? options.title.length : 0;

        if ( options.totals )
        {
            // TODO: oh dear. from an i18n POV, this is *horrible*!...
            sumlist = [];
            // for val, singular, plural in [
            _.each([
                    [totLoc, options.gettext('local change'), options.gettext('local changes')],
                    [totRem, options.gettext('remote change'), options.gettext('remote changes')],
                    [totErr, options.gettext('error'), options.gettext('errors')]
                    ], function(set) {
                        if ( set[0] <= 0 )
                return;
            sumlist.push(num2str(set[0]) + ' ' + ( set[0] == 1 ? set[1] : set[2] ));
                    });
            if ( sumlist.length <= 0 )
                sumlist = options.gettext('No changes');
            else if ( sumlist.length == 1 )
                sumlist = sumlist[0];
            else
                sumlist = ( sumlist.slice(0, -1).join(', ') + ' '
                        + options.gettext('and') + ' ' + sumlist[sumlist.length - 1] );
            if ( totMrg > 0 || totCol > 0 )
            {
                sumlist += ': ';
                if ( totMrg == 1 )
                    sumlist += num2str(totMrg) + ' ' + options.gettext('merge');
                else if ( totMrg > 1 )
                    sumlist += num2str(totMrg) + ' ' + options.gettext('merges');
                if ( totMrg > 0 && totCol > 0 )
                    sumlist += ' ' + options.gettext('and') + ' ';
                if ( totCol == 1 )
                    sumlist += num2str(totCol) + ' ' + options.gettext('conflict');
                else if ( totCol > 1 )
                    sumlist += num2str(totCol) + ' ' + options.gettext('conflicts');
            }
            sumlist += '.';
            if ( sumlist.length > tWid )
            {
                wSrc += sumlist.length - tWid;
                tWid = sumlist.length;
            }
        }

        if ( options.title )
        {
            stream.write('┏━' + smult('━', tWid) + '━┓\n');
            stream.write('┃ ' + center(options.title, tWid) + ' ┃\n');
        }

        if ( options.details )
        {
            if ( options.title )
                stream.write('┡━'
                        + smult('━', wSrc)
                        + '━┯━'
                        + smult('━', wMode)
                        + '━┯━'
                        + smult('━', ( wHereAdd + wHereMod + wHereDel + wHereErr + 9 ))
                        + '━┯━'
                        + smult('━', ( wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 ))
                        + '━┯━'
                        + smult('━', wCon)
                        + '━┩\n'
                        );
            else
                stream.write('┌─'
                        + smult('─', wSrc)
                        + '─┬─'
                        + smult('─', wMode)
                        + '─┬─'
                        + smult('─', ( wHereAdd + wHereMod + wHereDel + wHereErr + 9 ))
                        + '─┬─'
                        + smult('─', ( wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 ))
                        + '─┬─'
                        + smult('─', wCon)
                        + '─┐\n'
                        );

            stream.write('│ ' + smult(' ', wSrc));
            stream.write(' │ ' + smult(' ', wMode));
            stream.write(' │ ' + center(options.gettext('Local'), wHereAdd + wHereMod + wHereDel + wHereErr + 9 ));
            stream.write(' │ ' + center(options.gettext('Remote'), wPeerAdd + wPeerMod + wPeerDel + wPeerErr + 9 ));
            stream.write(' │ ' + center(options.gettext('Conflicts'), wCon));
            stream.write(' │\n');

            stream.write('│ ' + right(options.gettext('Source'), wSrc));
            stream.write(' │ ' + center(options.gettext('Mode'), wMode));
            stream.write(' │ ' + center(options.gettext('Add'), wHereAdd));
            stream.write(( options.ascii ? ' │ ' : '   ' ) + center(options.gettext('Mod'), wHereMod));
            stream.write(( options.ascii ? ' │ ' : '   ' ) + center(options.gettext('Del'), wHereDel));
            stream.write(( options.ascii ? ' │ ' : '   ' ) + center(options.gettext('Err'), wHereErr));
            stream.write(' │ ' + center(options.gettext('Add'), wPeerAdd));
            stream.write(( options.ascii ? ' │ ' : '   ' ) + center(options.gettext('Mod'), wPeerMod));
            stream.write(( options.ascii ? ' │ ' : '   ' ) + center(options.gettext('Del'), wPeerDel));
            stream.write(( options.ascii ? ' │ ' : '   ' ) + center(options.gettext('Err'), wPeerErr));
            stream.write(' │ ' + center(options.gettext('Col'), wCol));
            stream.write(( options.ascii ? ' │ ' : '   ' ) + center(options.gettext('Mrg'), wMrg));
            stream.write(' │\n');

            stream.write('├─' + smult('─', wSrc)
                    + '─┼─' + smult('─', wMode)
                    + '─┼─' + smult('─', wHereAdd)
                    + '─┼─' + smult('─', wHereMod)
                    + '─┼─' + smult('─', wHereDel)
                    + '─┼─' + smult('─', wHereErr)
                    + '─┼─' + smult('─', wPeerAdd)
                    + '─┼─' + smult('─', wPeerMod)
                    + '─┼─' + smult('─', wPeerDel)
                    + '─┼─' + smult('─', wPeerErr)
                    + '─┼─' + smult('─', wCol)
                    + '─┼─' + smult('─', wMrg)
                    + '─┤\n'
                    );

            var numcol = function(val, wid) {
                if ( val == 0 )
                    return ' │ ' + center(options.ascii ? '-' : ' ', wid);
                return ' │ ' + right(num2str(val), wid);
            };

            var keys = _.keys(stats);
            // todo: sort case insensitively...
            keys.sort();
            _.each(keys, function(key) {
                var stat = stats[key];
                stream.write('│ ' + right(key, wSrc));
                stream.write(' │ ' + center(modeStringLut[stat.mode], wMode));
                stream.write(numcol(stat.hereAdd, wHereAdd));
                stream.write(numcol(stat.hereMod, wHereMod));
                stream.write(numcol(stat.hereDel, wHereDel));
                stream.write(numcol(stat.hereErr, wHereErr));
                stream.write(numcol(stat.peerAdd, wPeerAdd));
                stream.write(numcol(stat.peerMod, wPeerMod));
                stream.write(numcol(stat.peerDel, wPeerDel));
                stream.write(numcol(stat.peerErr, wPeerErr));
                stream.write(numcol(stat.conflicts, wCol));
                stream.write(numcol(stat.merged, wMrg));
                stream.write(' │\n');
            });

            if ( options.totals )
                stream.write('├─');
            else
                stream.write('└─');

            stream.write(smult('─', wSrc)
                    + '─┴─' + smult('─', wMode)
                    + '─┴─' + smult('─', wHereAdd)
                    + '─┴─' + smult('─', wHereMod)
                    + '─┴─' + smult('─', wHereDel)
                    + '─┴─' + smult('─', wHereErr)
                    + '─┴─' + smult('─', wPeerAdd)
                    + '─┴─' + smult('─', wPeerMod)
                    + '─┴─' + smult('─', wPeerDel)
                    + '─┴─' + smult('─', wPeerErr)
                    + '─┴─' + smult('─', wCol)
                    + '─┴─' + smult('─', wMrg)
                    );

            if ( options.totals )
                stream.write('─┤\n');
            else
                stream.write('─┘\n');
        }

        // ─━│┃┄┅┆┇┈┉┊┋┼┽┾┿
        // ┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛
        // ├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫
        // ┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻

        if ( options.totals )
        {
            if ( !! options.title && ! options.details )
                stream.write('┌─' + smult('─', tWid) + '─┐\n');
            stream.write('│ ' + center(sumlist, tWid));
            stream.write(' │\n');
            stream.write('└─' + smult('─', tWid) + '─┘\n');
        }

        return;

    };

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/storage', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.storage
// auth: griffin <griffin@uberdev.org>
// date: 2012/10/31
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant');

var _self = (function () {

    var exports = {};

    //---------------------------------------------------------------------------
    _.extend(exports, {

        //-------------------------------------------------------------------------
        errstr: function(target) {
            if ( target.error && typeof(target.error.toString) == 'function' )
        return target.error.toString();
    var ret = '';
    var count = 0;
    for ( var key in target.error )
        count += 1;
    if ( count == 1 && target.error.name )
        ret = '' + target.error.name;
    else
    {
        ret = '{';
        for ( var key in target.error )
    {
        ret += key + ': ' + target.error[key];
        count -= 1;
        if ( count > 0 )
        ret += ', ';
    }
    }
    if ( target.errorCode )
    {
        if ( ret.length <= 0 || ret == '{}' )
            ret = '' + target.errorCode;
        else
            ret = '[' + target.errorCode + '] ' + ret;
    }
    if ( ret.length <= 0 || ret == '{}' )
        // last ditch effort...
        ret = common.prettyJson(target);
    return ret;
        },

            //-------------------------------------------------------------------------
            openDatabase: function(context, cb) {
                var dbreq = context.storage.indexedDB.open(context.dbname, 1);
                dbreq.onblocked = function(event) {
                    cb({code: 'syncml-js.storage.OD.10',
                        message: 'database blocked by other process/tab/window'});
                };
                dbreq.onerror = function(event) {
                    var errmsg = exports.errstr(event.target);
                    cb({code: 'syncml-js.storage.OD.20',
                        message: 'failed to open syncml-js database: ' + errmsg});
                };
                dbreq.onupgradeneeded = function(event) {


                    var db = event.target.result;

                    var adapterTable = db.createObjectStore('adapter', {keyPath: 'id'});
                    adapterTable.createIndex('isLocal', 'isLocal', {unique: false});
                    adapterTable.createIndex('devID', 'devID', {unique: true});

                    var mappingTable = db.createObjectStore(
                            'mapping',
                            {keyPath: ['store_id', 'guid']});
                    mappingTable.createIndex('store_id', 'store_id', {unique: false});
                    // mappingTable.createIndex('guid', 'guid', {unique: false});
                    // mappingTable.createIndex('luid', 'luid', {unique: false});

                    var changeTable = db.createObjectStore(
                            'change',
                            {keyPath: ['store_id', 'item_id']});
                    changeTable.createIndex('store_id', 'store_id', {unique: false});
                    // changeTable.createIndex('item_id', 'item_id', {unique: false});

                };
                dbreq.onsuccess = function(event) {
                    cb(null, event.target.result);
                };
            },

            //-------------------------------------------------------------------------
            getTransaction: function(db, tables, mode) {
                // NOTE: the spec says passing in null should be valid... but
                //       mozilla's indexedDB seems to barf with:
                //         [Exception... "The operation failed because the
                //         requested database object could not be found. For
                //         example, an object store did not exist but was
                //         being opened."  code: "8" nsresult: "0x80660003
                //         (NotFoundError)"
                if ( ! tables )
                    tables = ['adapter','mapping','change'];
                if ( ! mode )
                    mode = 'readwrite';
                return db.transaction(tables, mode);
            },

            //-------------------------------------------------------------------------
            dumpDatabase: function(context, cb) {

                var ret = {};
                var txn = context._txn();

                var steps = [
                    function(cb) {
                        exports.getAll(context, txn.objectStore('adapter'), {}, function(err, adapters) {
                            ret.adapter = adapters;
                            return cb(err);
                        });
                    },
                    function(cb) {
                        exports.getAll(context, txn.objectStore('mapping'), {}, function(err, mappings) {
                            ret.mapping = mappings;
                            return cb(err);
                        });
                    },
                    function(cb) {
                        exports.getAll(context, txn.objectStore('change'), {}, function(err, changes) {
                            ret.change = changes;
                            return cb(err);
                        });
                    }
                ];

                common.cascade(steps, function(step, cb) {
                    return step(cb);
                }, function(err) {
                    return cb(err, ret);
                });
            },

            //-------------------------------------------------------------------------
            clearDatabase: function(context, cb) {
                var dbreq = context.storage.indexedDB.open(context.dbname, 1);
                dbreq.onblocked = function(event) {
                    cb({code: 'syncml-js.storage.CD.10',
                        message: 'database blocked by other process/tab/window'});
                };
                dbreq.onerror = function(event) {
                    var errmsg = exports.errstr(event.target);
                    cb({code: 'syncml-js.storage.CD.20',
                        message: 'failed to open syncml-js database: ' + errmsg});
                };
                dbreq.onsuccess = function(event) {
                    var db = event.target.result;
                    db.onerror = dbreq.onerror;
                    async.map(['adapter', 'mapping', 'change'], function(name, cb) {
                        cb();
                    }, function(err) {
                        if ( err )
                        return cb(err);
                    db.close();
                    });
                };
            },

            //-------------------------------------------------------------------------
            getAll: function(context, source, options, cb) {
                // supported options:
                //   - range
                //   - only
                options = options || {};
                var range = options.range;
                if ( ! range && options.only )
                    range = context.storage.IDBKeyRange.only(options.only);
                var req = source.openCursor(range);
                var ret = [];
                req.onsuccess = function(event) {
                    var cursor = event.target.result;
                    if ( cursor )
                    {
                        ret.push(cursor.value);
                        // ret.push({key: cursor.key, value: cursor.value});
                        return cursor.continue();
                    }
                    cb(null, ret);
                };
                req.onerror = function(event) {
                    cb(exports.errstr(event.target));
                };
            },

            //-------------------------------------------------------------------------
            put: function(store, object, cb) {
                var req = store.put(object);
                req.onsuccess = function(event) { cb(); };
                req.onerror = function(event) {
                    cb(exports.errstr(event.target));
                };
            },

            //-------------------------------------------------------------------------
            delete: function(store, objectID, cb) {
                var req = store.delete(objectID);
                req.onsuccess = function(event) { cb(); };
                req.onerror = function(event) {
                    cb(exports.errstr(event.target));
                };
            },

            //-------------------------------------------------------------------------
            deleteAll: function(source, matches, cb) {
                var req = source.openCursor();
                req.onsuccess = function(event) {
                    var cursor = event.target.result;
                    if ( cursor )
                    {
                        for (key in matches)
                            if ( matches[key] != cursor.value[key] )
                                return cursor.continue();
                        exports.delete(source, cursor.key, function(err) {
                            if ( err )
                            return cb(err);
                        return cursor.continue();
                        });
                        return;
                    }
                    cb(null);
                };
                req.onerror = function(event) {
                    cb(exports.errstr(event.target));
                };
            },

            //-------------------------------------------------------------------------
            iterateCursor: function(openCursor, iterator, cb) {
                openCursor.onsuccess = function(event) {
                    var cursor = event.target.result;
                    if ( ! cursor )
                        return cb();
                    iterator(cursor.value.value, cursor.value.id, function(err) {
                        if ( err )
                        return cb(err);
                    return cursor.continue();
                    });
                };
                openCursor.onerror = function(event) {
                    cb(exports.errstr(event.target));
                };
            }

    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/store', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.store
// auth: griffin <griffin@uberdev.org>
// date: 2012/11/04
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------


var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    ctype = require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
    storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
    ET = require('ripple/platform/tizen/2.0/syncml-js-lib/elementtree');


var _self = (function () {
    var exports = {};

    //---------------------------------------------------------------------------
    exports.Store = common.Base.extend({

        //-------------------------------------------------------------------------
        constructor: function(adapter, options) {

            // todo: some of these attributes should be modifiable...

            //: for local stores, specifies the agent that will implement
            //: the actual item operations -- it must implement the
            //: syncml-js.Agent API.
            this.agent = options.agent || null;

            //: [read-only] specifies the SyncML URI that this store is bound to.
            this.uri = ( adapter ? adapter.normUri(options.uri) : options.uri ) || null;

            //: [read-only] specifies the human-readable name for this store.
            //: if undefined, defaults to URI.
            this.displayName = options.displayName || this.uri || null;

            //: [read-only] specifies the maximum GUID size for items in this store.
            //: if undefined, defaults to adapter setting.
            this.maxGuidSize = options.maxGuidSize || null;

            //: [read-only] specifies the maximum object size for items in this store.
            //: if undefined, defaults to adapter setting.
            this.maxObjSize = options.maxObjSize || null;

            //: [read-only] specifies conflict resolution policy for this store.
            //: if undefined, defaults to adapter setting.
            this.conflictPolicy = options.conflictPolicy || null;

            //: [read-only] specifies which syncTypes this store supports.
            //: (defaults to all.)
            this.syncTypes = options.syncTypes;
            if ( this.syncTypes == undefined || this.syncTypes.length <= 0 )
            {
                this.syncTypes = [
                    constant.SYNCTYPE_TWO_WAY,
                    constant.SYNCTYPE_SLOW_SYNC,
                    constant.SYNCTYPE_ONE_WAY_FROM_CLIENT,
                    constant.SYNCTYPE_REFRESH_FROM_CLIENT,
                    constant.SYNCTYPE_ONE_WAY_FROM_SERVER,
                    constant.SYNCTYPE_REFRESH_FROM_SERVER,
                    constant.SYNCTYPE_SERVER_ALERTED
                ];
            }

            ctypes = options.contentTypes;
            if ( ! ctypes && options.agent )
                ctypes = options.agent.getContentTypes();

            this.contentTypes = _.map(ctypes, function(e) {
                if ( e instanceof ctype.ContentTypeInfo ) {
                    return e;
                }
                return ctype.ContentTypeInfo.fromStruct(e);
            });

            // --- private attributes
            this.id       = options.id || common.makeID();
            this._a       = adapter;
        },

        //-------------------------------------------------------------------------
        _load: function(cb) {
            cb();
        },

        //-------------------------------------------------------------------------
        _getModel: function() {
            var self = this;
            var uri  = self._a.normUri(self.uri);
            return _.find(this._a._getModel().stores,
                    function(s) { return self._a.normUri(s.uri) == uri; });
        },

        //-------------------------------------------------------------------------
        _updateModel: function(cb) {
            if ( ! this._a._model || ! this._a._model.stores )
                return cb('store created on un-initialized adapter');
            // TODO: this squashes any data that may already be there, such
            //       as *BINDING* info!...
            this._a._model.stores = _.filter(this._a._model.stores, function(e) {
                return e.uri != this.uri;
            }, this);
            this._a._model.stores.push({
                id              : this.id,
                uri             : this.uri,
                displayName     : this.displayName,
                syncTypes       : this.syncTypes,
                maxGuidSize     : this.maxGuidSize,
                maxObjSize      : this.maxObjSize,
                conflictPolicy  : this.conflictPolicy,
                contentTypes    : _.map(this.contentTypes, function(e) { return e.toStruct(); })
            });
            cb();
        },

        //-------------------------------------------------------------------------
        _getBinding: function() {
            return this._getModel().binding;
        },

        //-------------------------------------------------------------------------
        _setBinding: function(binding) {
            this._getModel().binding = binding;
        },

        //-------------------------------------------------------------------------
        getContentTypes: function() {
            if ( this.agent != undefined ) {
                return this.agent.getContentTypes();
            }
            return this.contentTypes;
        },

        //-------------------------------------------------------------------------
        getPeerStore: function(peer) {
            var peerUri = null;
            if ( this._a.isLocal ) {
                peerUri = this._a._c.router.getTargetUri(this._a, peer, this.uri);
            }
            else {
                var binding = this.getBinding();
                peerUri = binding ? binding.uri : null;
            }
            if ( ! peerUri ) {
                return null;
            }
            return peer.getStore(peerUri);
        },

        //-------------------------------------------------------------------------
        merge: function(store, cb) {
            if ( this.uri != store.uri )
                return cb(new common.InternalError(
                                'unexpected merging of stores with different URIs ("' + this.uri
                                    + '" != "' + store.uri + '")'));
            if ( ! _.isEqual(this.contentTypes, store.contentTypes) )
            {
                // todo: this is a bit drastic... perhaps have an operational setting
                //       which controls how paranoid to be?...
                this._setBinding(null);
            }
            this.displayName    = store.displayName;
            this.contentTypes   = _.rest(store.contentTypes, 0);
            this.syncTypes      = _.rest(store.syncTypes, 0);
            this.maxGuidSize    = store.maxGuidSize;
            this.maxObjSize     = store.maxObjSize;
            this.agent          = store.agent;
            this.conflictPolicy = store.conflictPolicy;
            return cb();
        },

        //-------------------------------------------------------------------------
        _clearAllMappings: function(cb) {
            if ( this._a.isLocal )
                return cb(new common.InternalError(
                            'unexpected mapping request for local store'));
            var mapping = this._a._c._txn().objectStore('mapping');
            storage.deleteAll(mapping, {store_id: this.id}, cb);
        },

        //-------------------------------------------------------------------------
        _setMapping: function(guid, luid, cb) {
            var self = this;
            if ( this._a.isLocal )
                return cb(new common.InternalError(
                            'unexpected mapping request for local store'));
            // delete all previous mappings for this guid/store (there should
            // be at most one)... but paranoia rules.
            var mapping = this._a._c._txn().objectStore('mapping');
            storage.deleteAll(mapping, {store_id: this.id, guid: guid}, function(err) {
                if ( err ) {
                    return cb(err);
                }
                storage.put(mapping, {store_id: self.id, guid: guid, luid: luid}, function(err) {
                    if ( err ) {
                        return cb(err);
                    }
                    cb();
                });
            });
        },

        //-------------------------------------------------------------------------
        _getMapping: function(guid, cb) {
            if ( this._a.isLocal )
                return cb(new common.InternalError(
                            'unexpected mapping request for local store'));
            // todo: there must be a way to use IndexedDB since i have everything
            //       needed to generate the keyPath!... eg:
            //         objectStore.get({store_id:X,guid:Y})?...
            var mapdb = this._a._c._txn().objectStore('mapping').index('store_id');
            storage.getAll(this._a._c, mapdb, {only: this.id}, function(err, list) {
                if ( err ) {
                    return cb(err);
                }
                var item = _.find(list, function(item) {
                    return item.guid == guid;
                });
                return cb(null, item ? item.luid : null);
            });
        },

        //-------------------------------------------------------------------------
        _getMappings: function(cb) {
            if ( this._a.isLocal )
                return cb(new common.InternalError(
                            'unexpected mapping request for local store'));
            var mapdb = this._a._c._txn().objectStore('mapping').index('store_id');
            storage.getAll(this._a._c, mapdb, {only: this.id}, function(err, list) {
                if ( err )
                    return cb(err);
                return cb(null, _.map(list, function(item) {
                    return [item.guid, item.luid];
                }));
            });
        },

        //-------------------------------------------------------------------------
        _getReverseMapping: function(luid, cb) {
            if ( this._a.isLocal )
                return cb(new common.InternalError(
                            'unexpected mapping request for local store'));
            // todo: there must be a way to use IndexedDB since i have everything
            //       needed to generate the keyPath!... eg:
            //         objectStore.get({store_id:X,guid:Y})?...
            var mapdb = this._a._c._txn().objectStore('mapping').index('store_id');
            storage.getAll(this._a._c, mapdb, {only: this.id}, function(err, list) {
                if ( err )
                    return cb(err);
                var item = _.find(list, function(item) {
                    return item.luid == luid;
                });
                return cb(null, item ? item.guid : null);
            });
        },

        //-------------------------------------------------------------------------
        registerChange: function(itemID, state, options, cb) {
            // options can include:
            //   - changeSpec (string)
            //   - excludePeerID (string)

            if ( ! _.contains([constant.ITEM_ADDED, constant.ITEM_MODIFIED,
                        constant.ITEM_DELETED], state) )
                return cb(new common.TypeError(
                            'registerChange: invalid state "' + state + '"'));

            options = options || {};
            var self = this;
            if ( self._a.isLocal )
            {
                // TODO: THIS NEEDS TO BE SIGNIFICANTLY OPTIMIZED!... either:
                //         a) optimize this reverse lookup, or
                //         b) use a query that targets exactly the set of stores needed
                //       note that a pre-emptive model.session.flush() may be necessary.
                common.cascade(self._a.getPeers(), function(peer, cb) {
                    if ( options.excludePeerID && options.excludePeerID == peer.id )
                        return cb();
                    common.cascade(peer.getStores(), function(store, cb) {
                        var binding = store._getBinding()
                        if ( ! binding || binding.uri != self.uri )
                            return cb();
                        store.registerChange(itemID, state, options, cb);
                    }, cb);
                }, cb);
                return;
            }

            // todo: a non-ADD change event for an ID that has never been
            // seen does not create an error... should it??? that would mean
            // that syncml-js needs to track that. not a good idea.

            itemID = '' + itemID;
            var handled = false;

            // paranoia
            if ( options.changeSpec && state != constant.ITEM_MODIFIED )
            {
                options.changeSpec = null;
            }

            var check_update = function(cb) {
                self._getChange(itemID, function(err, change) {
                    if ( err )
                        return cb(err);
                    if ( ! change)
                        return cb();
                    var badstate = function(action) {
                    };
                // note: many of the following change.state / state combinations
                // should never occur. the following tries to recover gracefully.
                // todo: should i raise an error for "illogical" conditions?
                    switch ( change.state )
                    {
                    case constant.ITEM_ADDED:
                    {
                        if ( state != constant.ITEM_DELETED )
                        {
                            // ADD + anything except DELETE stays ADD
                            handled = true;
                            return cb();
                        }
                        // ADD + DELETE cancels out
                        handled = true;
                        var changeTab = self._a._c._txn().objectStore('change');
                        storage.deleteAll(changeTab, change, function(err) {
                            if ( err )
                                return cb(err);
                            return cb();
                        });
                        return;
                    }
                    case constant.ITEM_MODIFIED:
                    {
                        if ( state == constant.ITEM_ADDED )
                        {
                            badstate('squelching changeSpec');
                            delete change.changeSpec;
                            break;
                        }
                        if ( state == constant.ITEM_DELETED )
                        {
                            change.state = state;
                            delete change.changeSpec;
                            break;
                        }
                        if ( change.changeSpec )
                        {
                            if ( options.changeSpec )
                                change.changeSpec += ';' + options.changeSpec;
                            else
                                delete change.changeSpec;
                        }
                        break;
                    }
                    case constant.ITEM_DELETED:
                    {
                        if ( state == constant.ITEM_DELETED )
                        {
                            badstate('ignoring');
                            handled = true;
                            return cb();
                        }
                        badstate('reverting to modified');
                        change.state = constant.ITEM_MODIFIED;
                        delete change.changeSpec;
                        break;
                    }
                    default:
                    {
                        return cb(new common.InternalError(
                                    'unexpected recorded change state "' + change.state
                                    + '" for item ID "' + itemID + '"'));
                    }
                    }
                    // update the change
                    // todo: do i need to delete it first?
                    handled = true;
                    return storage.put(
                        self._a._c._txn().objectStore('change'),
                        change,
                        cb);
                });
            };

            var check_mapping = ( self._a._isMapper() || state == constant.ITEM_ADDED )
                ? common.noop
                : function(cb) {
                    // doing a `_getMapping` for non-add events to make sure that
                    // the remote peer actually has this object before we tell it
                    // to modify or delete an item...
                    self._getMapping(itemID, function(err, luid) {
                        if ( err )
                        return cb(err);
                    if ( luid )
                        return cb();
                    // this item does not exist as (or has not been mapped to) an
                    // item on the remote peer and is not an `ADD` event, so can
                    // therefore be ignored - mark it as "handled".
                    handled = true;
                    return cb();
                    });
                };

            // todo: there is a weirdness here wrt `handled` in the case
            //       of check_mapping and deletes... ie. there is a bit of
            //       a responsibility violation (handled does not actually
            //       mean handled...)

            check_update(function(err) {
                if ( err )
                    return cb(err);
                if ( handled )
                    return cb();
                check_mapping(function(err) {
                    if ( err )
                        return cb(err);
                    if ( handled && state != constant.ITEM_DELETED )
                        return cb();
                    // note: if it is a delete event, and it has not been mapped
                    // yet, so does not yet exist on the peer, therefore
                    // propagate nothing -- continuing just to execute the
                    // deleteAll().
                    var changeTab = self._a._c._txn().objectStore('change');
                    change = {store_id: self.id, item_id: itemID};
                    // todo: is this deleteAll really necessary?... paranoia rules!
                    storage.deleteAll(changeTab, change, function(err) {
                        if ( err )
                            return cb(err);
                        if ( handled )
                            return cb();
                        change.state = state;
                        change.changeSpec = options.changeSpec;
                        storage.put(changeTab, change, cb);
                    });
                });
            });
        },

        //-------------------------------------------------------------------------
        _getChange: function(itemID, cb) {
            // returns cb(null, CHANGE)
            // change ::= { store_id: ID, item_id: GUID, state: STATE, changeSpec: SPEC }
            itemID = '' + itemID;
            var self = this;
            // todo: there must be a way to use IndexedDB since i have everything
            //       needed to generate the keyPath!... eg:
            //         objectStore.get({store_id:X,guid:Y})?...
            var changedb = self._a._c._txn().objectStore('change').index('store_id');
            storage.getAll(self._a._c, changedb, {only: self.id}, function(err, changes) {
                if ( err )
                    return cb(err);
                var change = _.find(changes, function(change) {
                    return change.item_id == itemID;
                });
                return cb(null, change);
            });
        },

        //-------------------------------------------------------------------------
        _delChange: function(options, cb) {
            // - if options is null/empty, delete all changes recorded
            //   for this store

            // // todo: this is *technically* subject to a race condition... but the
            // //       same peer should really not be synchronizing at the same time...
            // // todo: also potentially check Change.registered...
            // // TODO: this could be solved by:
            // //         a) never updating a Change record (only deleting and replacing)
            // //         b) deleting Change records by ID instead of by store/item/state...

            // var objstore = session.context._txn().objectStore('change');
            // storage.iterateCursor(
            //   objstore.index('store_id').openCursor(peerStore.id),
            //   function(value, key, cb) {
            //     if ( value.itemID != chkcmd.source || value.state != constant.ITEM_ADDED )
            //       return;
            //     storage.delete(objstore, key, cb);
            //   }, cb);

            var dbstore = this._a._c._txn().objectStore('change');
            var matches = {store_id: this.id};
            if ( options.itemID )
                matches.item_id = options.itemID;
            if ( options.state )
                matches.state = options.state;
            storage.deleteAll(dbstore, matches, cb);
        },

        //-------------------------------------------------------------------------
        toSyncML: function() {
            var xstore = ET.Element('DataStore');
            if ( this.uri )
                ET.SubElement(xstore, 'SourceRef').text = this.uri;
            if ( this.displayName )
                ET.SubElement(xstore, 'DisplayName').text = this.displayName;
            if ( this.maxGuidSize )
            {
                // todo: this should ONLY be sent by the client... (according to the
                //       spec, but not according to funambol behavior...)
                ET.SubElement(xstore, 'MaxGUIDSize').text = this.maxGuidSize;
            }
            if ( this.maxObjSize )
                ET.SubElement(xstore, 'MaxObjSize').text = this.maxObjSize;

            var ctypes = this.getContentTypes();

            if ( ctypes && ctypes.length > 0 )
            {
                var pref = _.filter(ctypes, function(ct) { return ct.receive && ct.preferred; });

                // todo: should i just take the first one?...
                if ( pref.length > 1 )
                    throw new Error('agents can prefer at most one receive content-type');

                if ( pref.length == 1 )
                {
                    pref = pref[0].toSyncML('Rx', true);
                    pref[0].tag = 'Rx-Pref';
                    _.each(pref, function(xnode) { xstore.append(xnode); });
                }

                _.each(
                        _.filter(ctypes, function(ct) { return ct.receive && ! ct.preferred; }),
                        function(ct) {
                            _.each(ct.toSyncML('Rx', true), function(xnode) {
                                xstore.append(xnode);
                            });
                        });

                var pref = _.filter(ctypes, function(ct) { return ct.transmit && ct.preferred; });

                // todo: should i just take the first one?...
                if ( pref.length > 1 )
                    throw new Error('agents can prefer at most one transmit content-type');

                if ( pref.length == 1 )
                {
                    pref = pref[0].toSyncML('Tx', true);
                    pref[0].tag = 'Tx-Pref';
                    _.each(pref, function(xnode) { xstore.append(xnode); });
                }

                _.each(
                        _.filter(ctypes, function(ct) { return ct.transmit && ! ct.preferred; }),
                        function(ct) {
                            _.each(ct.toSyncML('Tx', true), function(xnode) {
                                xstore.append(xnode);
                            });
                        });

            }

            if ( this.syncTypes && this.syncTypes.length > 0 )
            {
                var xcap = ET.SubElement(xstore, 'SyncCap');
                for ( var idx=0 ; idx<this.syncTypes.length ; idx++ )
                    ET.SubElement(xcap, 'SyncType').text = this.syncTypes[idx];
            }
            return xstore;

        },

        //-------------------------------------------------------------------------
        describe: function(stream, cb) {
            stream.writeln('URI: ' + this.uri);
            stream.writeln('Max ID size: ' + ( this.maxGuidSize || '(none)' ));
            stream.writeln('Max object size: ' + ( this.maxObjSize || '(none)' ));
            stream.writeln('Sync types: ' + this.syncTypes.join(', '));
            var cts = this.getContentTypes();
            if ( cts.length <= 0 )
            {
                stream.writeln('Capabilities: (none)');
                return cb();
            }
            stream.writeln('Capabilities:');
            var s1 = new common.IndentStream(stream);
            common.cascade(cts, function(ct, cb) {
                s1.write('- ');
                ct.describe(s1);
                return cb();
            }, cb);
        }
    }, {

        //-------------------------------------------------------------------------
        fromSyncML: function(xnode) {
            var options = {
                uri          : xnode.findtext('SourceRef'),
                displayName  : xnode.findtext('DisplayName'),
                maxGuidSize  : common.int(xnode.findtext('MaxGUIDSize')),
                maxObjSize   : common.int(xnode.findtext('MaxObjSize')),
                contentTypes : [],
                syncTypes    : _.map(xnode.findall('SyncCap/SyncType'), function(e) {
                    return common.int(e.text);
                })
            };
            _.each(xnode.getchildren(), function(child) {
                if ( _.indexOf(['Rx-Pref', 'Rx', 'Tx-Pref', 'Tx'], child.tag) < 0 )
                return;
            var cti = ctype.ContentTypeInfo.fromSyncML(child);
            var merged = false;
            _.each(options.contentTypes, function(ct) {
                if ( merged )
                return;
            if ( ct.merge(cti) )
                merged = true;
            });
            if ( ! merged )
                options.contentTypes.push(cti);
            });
            return new exports.Store(null, options);
        },
    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/synchronizer', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.synchronizer
// auth: griffin <griffin@uberdev.org>
// date: 2012/11/05
// copy: (C) CopyLoose 2012 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    ctype = require('ripple/platform/tizen/2.0/syncml-js-lib/ctype'),
    state = require('ripple/platform/tizen/2.0/syncml-js-lib/state'),
    protocol = require('ripple/platform/tizen/2.0/syncml-js-lib/protocol'),
    storage = require('ripple/platform/tizen/2.0/syncml-js-lib/storage'),
    _self;

_self = (function () {

    var exports = {};
    var badStatus = protocol.badStatus;

    //---------------------------------------------------------------------------
    exports.Synchronizer = common.Base.extend({

        //-------------------------------------------------------------------------
        constructor: function(options) {
        },

        //-------------------------------------------------------------------------
        initStoreSync: function(session, cb) {
            async.eachSeries(session.peer._getModel().stores, function(rstore, cb) {
                // TODO: should the server-side be doing this? probably not
                //       since store mapping is a client-side decision...
                var ruri = session.peer.normUri(rstore.uri);
                if ( session.info.dsstates[ruri] || ! rstore.binding )
                return cb();
            var lstore = session.adapter.getStore(rstore.binding.uri);
            if ( ! lstore || ! lstore.agent )
                return cb();
            var ds = state.makeStoreSyncState({
                uri        : lstore.uri,
                peerUri    : ruri,
                lastAnchor : rstore.binding.localAnchor,
                mode       : session.info.mode || constant.ALERT_TWO_WAY,
                action     : 'alert'
            });
            if ( ! ds.lastAnchor )
            {
                switch ( ds.mode )
            {
                case constant.ALERT_SLOW_SYNC:
                case constant.ALERT_REFRESH_FROM_CLIENT:
                case constant.ALERT_REFRESH_FROM_SERVER:
                    {
                        break;
                    }
                case constant.ALERT_TWO_WAY:
                case constant.ALERT_ONE_WAY_FROM_CLIENT:
                case constant.ALERT_ONE_WAY_FROM_SERVER:
                    {
                        if ( session.info.mode == constant.SYNCTYPE_AUTO )
                        {
                            ds.mode = constant.ALERT_SLOW_SYNC;
                            break;
                        }
                        var uaEvent = {
                            session   : session,
                            store     : lstore,
                            peerStore : rstore,
                            modeReq   : ds.mode
                        };
                        return session.ua.chooseRefreshRequired(uaEvent, function(err, mode) {
                            if ( err )
                            return cb(err);
                        if ( ! _.contains([constant.ALERT_SLOW_SYNC,
                                constant.ALERT_REFRESH_FROM_CLIENT,
                                constant.ALERT_REFRESH_FROM_SERVER], mode) )
                            return cb(new common.TypeError(
                                    'invalid mode chosen for refresh: ' + common.j(mode)));
                        ds.mode = mode;
                        session.info.dsstates[ds.uri] = ds;
                        return cb();
                        });
                    }
                default:
                    {
                        return cb(new common.InternalError(
                                    'unexpected sync mode "' + ds.mode + '" requested'));
                    }
            }
            }
            session.info.dsstates[ds.uri] = ds;
            return cb();
            }, cb);
        },

        //-------------------------------------------------------------------------
        // SYNCHRONIZATION PHASE: ACTION
        //-------------------------------------------------------------------------

        //-------------------------------------------------------------------------
        actions: function(session, commands, cb) {
            var self = this;
            common.cascade(_.keys(session.info.dsstates), function(uri, cb) {
                var ds = session.info.dsstates[uri];
                if ( ds.action == 'done' )
                return cb();
            // TODO: is this the right handling of an "error" dsstate?...
            if ( ds.action == 'error' )
                return cb();
            var func = self['_action_' + ds.action.toLowerCase()];
            if ( ! func )
                return cb(new common.InternalError(
                        'unexpected store action "' + ds.action + '"'));
            try{
                func.call(self, session, ds, function(err, cmds) {
                    if ( err )
                    return cb(err);
                _.each(cmds, function(cmd) { commands.push(cmd); });
                return cb();
                });
            }catch(e){
                return cb(new common.InternalError(
                        'failed invoking synchronizer action: ' + e, e));
            }
            }, function(err) {
                if ( err )
                    return cb(err);
                return cb(null, commands);
            });
        },

        //-------------------------------------------------------------------------
        _action_alert: function(session, dsstate, cb) {

            var src = session.adapter.getStore(dsstate.uri);
            var tgt = session.peer.getStore(dsstate.peerUri);

            // TODO: ensure that mode is acceptable...

            // todo: perhaps i should only specify maxObjSize if it differs from
            //       adapter.maxObjSize?...

            return cb(null, [state.makeCommand({
                name        : constant.CMD_ALERT,
                   cmdID       : session.nextCmdID(),
                   data        : dsstate.mode,
                   source      : src.uri,
                   target      : tgt.uri,
                   lastAnchor  : dsstate.lastAnchor,
                   nextAnchor  : dsstate.nextAnchor,
                   maxObjSize  : src.maxObjSize,
            })]);

        },

        //-------------------------------------------------------------------------
        _action_send: function(session, dsstate, cb) {
            var store = session.adapter.getStore(dsstate.uri);
            var agent = store.agent;
            var peerStore = session.peer.getStore(dsstate.peerUri);

            var cmd = state.makeCommand({
                name   : constant.CMD_SYNC,
                cmdID  : session.nextCmdID(),
                source : dsstate.uri,
                // target : adapter.router.getTargetUri(uri),
                target : dsstate.peerUri
            });

            switch ( dsstate.mode )
            {
                case constant.ALERT_TWO_WAY:
                case constant.ALERT_SLOW_SYNC:
                case constant.ALERT_ONE_WAY_FROM_CLIENT:
                case constant.ALERT_REFRESH_FROM_CLIENT:
                case constant.ALERT_ONE_WAY_FROM_SERVER:
                case constant.ALERT_REFRESH_FROM_SERVER:
                    // todo: these should only be received out-of-band, right?...
                    // case constant.ALERT_TWO_WAY_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_CLIENT_BY_SERVER:
                    // case constant.ALERT_ONE_WAY_FROM_SERVER_BY_SERVER:
                    // case constant.ALERT_REFRESH_FROM_SERVER_BY_SERVER:
                    {
                        break;
                    }
                default:
                    {
                        return cb(new common.InternalError(
                                    'unexpected sync mode "' + common.mode2string(dsstate.mode) + '"'));
                    }
            }

            if ( session.isServer )
            {
                if ( dsstate.mode == constant.ALERT_REFRESH_FROM_CLIENT
                        || dsstate.mode == constant.ALERT_ONE_WAY_FROM_CLIENT )
                {
                    cmd.noc = 0;
                    return cb(null, [cmd]);
                }
            }

            if ( ! session.isServer )
            {
                if ( dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER
                        || dsstate.mode == constant.ALERT_ONE_WAY_FROM_SERVER )
                {
                    cmd.noc = 0;
                    return cb(null, [cmd]);
                }
            }

            switch ( dsstate.mode )
            {

                case constant.ALERT_TWO_WAY:
                case constant.ALERT_ONE_WAY_FROM_CLIENT: // when ! session.isServer
                case constant.ALERT_ONE_WAY_FROM_SERVER: // when session.isServer
                    {
                        // send local changes

                        storage.getAll(
                                session.context,
                                session.txn().objectStore('change').index('store_id'),
                                {only: peerStore.id},
                                function(err, changes) {
                                    if ( err )
                            return cb(err);
                        var ctype = session.context.router.getBestTransmitContentType(
                            session.adapter, session.peer, dsstate.uri);
                        cmd.data = [];

                        // TODO: add support for hierarchical operations...
                        //       including MOVE, COPY, etc.

                        // TODO: this assumes that the entire object set can fit in memory...
                        //       perhaps, as a work-around, just keep a reference to the object
                        //       and then stream-based serialize it actually gets converted to
                        //       XML.

                        common.cascade(changes, function(change, cb) {

                            if ( dsstate.conflicts && _.indexOf(dsstate.conflicts, change.item_id) >= 0 )
                            return cb();

                        var scmdtype = null;
                        switch ( change.state )
                        {
                            case constant.ITEM_ADDED:    scmdtype = constant.CMD_ADD;     break;
                            case constant.ITEM_MODIFIED: scmdtype = constant.CMD_REPLACE; break;
                            case constant.ITEM_DELETED:  scmdtype = constant.CMD_DELETE;  break;
                            default:
                                                         {
                                                             return cb();
                                                         }
                        }

                        // todo: do something with the ctype version (ie. ctype[1])?...
                        var scmd = state.makeCommand({
                            name    : scmdtype,
                            cmdID   : session.nextCmdID(),
                            format  : constant.FORMAT_AUTO,
                            type    : change.state != constant.ITEM_DELETED ? ctype[0] : null,
                            uri     : dsstate.uri
                        });

                        // TODO: need to add hierarchical addition support here...

                        var set_data = scmdtype == constant.CMD_DELETE ? common.noop : function(cb) {

                            agent.getItem(change.item_id, function(err, item) {
                                if ( err )
                                return cb(err);
                            agent.dumpsItem(item, ctype[0], ctype[1], function(err, data, nct, nv) {
                                if ( err )
                                return cb(err);
                            scmd.data = data;
                            scmd.type = nct || scmd.type;
                            // todo: what to do with the content-type version?... eg.
                            //         scmd.version = nv || scmd.version;
                            // TODO: support hierarchical sync
                            // if ( agent.hierarchicalSync && item.parent )
                            //   scmd.sourceParent = '' + item.parent
                            return cb();
                            });
                            });
                        };

                        var set_target = scmdtype == constant.CMD_ADD ? function(cb) {
                            scmd.source = change.item_id;
                            cb();
                        } : function(cb) {
                            if ( ! session.isServer )
                            {
                                scmd.source = change.item_id;
                                return cb();
                            }
                            peerStore._getMapping(change.item_id, function(err, luid) {
                                if ( err )
                                return cb(err);
                            if ( luid )
                                scmd.target = luid;
                            else
                                scmd.source = change.item_id;
                            cb();
                            });
                        };

                        set_data(function(err) {
                            if ( err )
                            return cb(err);
                        set_target(function(err) {
                            if ( err )
                            return cb(err);
                        cmd.data.push(scmd);
                        return cb();
                        });
                        });
                        }, function(err) {
                            if ( err )
                                return cb(err);
                            cmd.noc = cmd.data.length;
                            return cb(null, [cmd]);
                        });
                                }
                        );
                        return;
                    }
                case constant.ALERT_SLOW_SYNC:
                case constant.ALERT_REFRESH_FROM_SERVER: // when session.isServer
                case constant.ALERT_REFRESH_FROM_CLIENT: // when ! session.isServer
                    {
                        // todo: this approach assumes that the entire object set can fit
                        //       in memory... perhaps move to an iterator-based approach?...
                        cmd.data = [];

                        agent.getAllItems(function(err, items) {

                            if ( err )
                            return cb(err);

                        // TODO: support hierarchical sync...

                        if ( agent.hierarchicalSync )
                        {
                            return cb(new common.NotImplementedError('hierarchical-sync'));
                            //       orditems = []            # the ordered items
                            //       dunitems = dict()        # lut of the ordered items
                            //       curitems = dict()        # lut of current items (for loop detection)
                            //       lutitems = dict([(item.id, item) for item in items])
                            //       def appenditem(item):
                            //         if item.id in dunitems:
                            //           return
                            //         if item.id in curitems:
                            //           raise common.LogicalError('recursive item hierarchy detected at item %r' % (item,))
                            //         curitems[item.id] = True
                            //         if item.parent is not None:
                            //           appenditem(lutitems[item.parent])
                            //         orditems.append(item)
                            //         dunitems[item.id] = item
                            //       for item in items:
                            //         curitems = dict()
                            //         appenditem(item)
                        }

                        var ctype = session.context.router.getBestTransmitContentType(
                                session.adapter, session.peer, dsstate.uri);

                        common.cascade(items, function(item, cb) {

                            // TODO: these should all be non-deleted items, right?...

                            if ( _.indexOf(dsstate.conflicts, '' + item.id) >= 0 )
                            return cb();

                        // note: need to check for mappings since on slow-sync, the
                        // server will already have received the client's "add" commands
                        // at this point (and therefore should not send them back...)
                        var check_sync = function(cb) {
                            if ( ! session.isServer )
                            return cb(null, true);
                        peerStore._getMapping(item.id, function(err, luid) {
                            return cb(err, luid ? false : true);
                        });
                        };

                        check_sync(function(err, dosync) {
                            if ( err )
                            return cb(err);

                        if ( ! dosync )
                            return cb();

                        agent.dumpsItem(
                            item, ctype[0], ctype[1],
                            function(err, data, new_ct, new_v) {

                                if ( err )
                            return cb(err);

                        // todo: do something with the content-type version...
                        var scmd = state.makeCommand({
                            name    : constant.CMD_ADD,
                            cmdID   : session.nextCmdID(),
                            format  : constant.FORMAT_AUTO,
                            type    : new_ct || ctype[0],
                            uri     : dsstate.uri,
                            source  : '' + item.id,
                            data    : data
                        });

                        if ( agent.hierarchicalSync )
                        {
                            // TODO: support hierarchical sync...
                            // if agent.hierarchicalSync and item.parent is not None:
                            //   scmd.sourceParent = str(item.parent)
                            return cb(new common.NotImplementedError('hierarchical-sync'));
                        }

                        cmd.data.push(scmd);
                        return cb();
                            });

                        });

                        }, function(err) {
                            if ( err )
                                return cb(err);
                            cmd.noc = cmd.data.length;
                            return cb(null, [cmd]);
                        });

                        });
                        return;
                    }
            }

            return cb(new common.InternalError(
                        'unexpected sync situation (action=' + dsstate.action
                            + ', mode=' + common.mode2string(dsstate.mode)
                            + ', isServer=' + ( session.isServer ? '1' : '0' ) + ')'));
                    },

                    //-------------------------------------------------------------------------
                    _action_save: function(session, dsstate, cb) {
                        if ( ! session.isServer )
                // TODO: for now, only servers should take the "save" action - the client
                //       will explicitly do this at the end of the .sync() method.
                //       ... mostly because clients don't call synchronizer.actions()
                //       one final time ...
                //       *BUT* perhaps that should be changed?... for example, .sync()
                //       could call synchronizer.actions() to cause action_save's to occur
                //       *AND* verify that synchronizer.actions() does not return anything...
                return cb(new common.InternalError(
                        'unexpected sync save situation (action=' + dsstate.action
                            + ', mode=' + common.mode2string(dsstate.mode)
                            + ', isServer=' + ( session.isServer ? '1' : '0' ) + ')'));

                    var peerStore = session.peer.getStore(dsstate.peerUri);
                    var binding = peerStore._getBinding();
                    binding.localAnchor  = dsstate.nextAnchor;
                    binding.remoteAnchor = dsstate.peerNextAnchor;
                    return cb(null);
                    },

                    //-------------------------------------------------------------------------
                    // SYNCHRONIZATION PHASE: REACTION
                    //-------------------------------------------------------------------------

                    //-------------------------------------------------------------------------
                    reactions: function(session, commands, cb) {
                        var self = this;
                        var ret  = [];
                        session.hierlut = null;
                        common.cascade(commands, function(cmd, cb) {
                            var func = self['_reaction_' + cmd.name.toLowerCase()];
                            if ( ! func )
                            return cb(new common.InternalError(
                                    'unexpected store reaction "' + cmd.name + '"'));
                        try{
                            func.call(self, session, cmd, function(err, cmds) {
                                if ( err ) {
                                    return cb(err);
                                }
                                _.each(cmds, function(cmd) { ret.push(cmd); });
                                return cb();
                            });
                        }catch(e){
                            return cb(new common.InternalError(
                                    'failed invoking synchronizer reaction: ' + e, e));
                        }
                        }, function(err) {
                            session.hierlut = null;
                            if ( err )
                                return cb(err);
                            return cb(null, ret);
                        });
                    },

                    //-------------------------------------------------------------------------
                    _reaction_sync: function(session, command, cb) {
                        var self = this;
                        var ret  = [state.makeCommand({
                            name       : constant.CMD_STATUS,
                            cmdID      : session.nextCmdID(),
                            msgRef     : command.msgID,
                            cmdRef     : command.cmdID,
                            targetRef  : command.target,
                            sourceRef  : command.source,
                            statusOf   : command.name,
                            statusCode : constant.STATUS_OK
                        })];
                        var store = session.adapter.getStore(session.adapter.normUri(command.target));
                        var dsstate = session.info.dsstates[store.uri];
                        if ( ! store.agent )
                        {
                            // todo: this is a bit different handling than anywhere else...
                            //       should everywhere else be like here, or the other way
                            //       round?...
                            //       the "REAL BIG ISSUE" is that atomicity of the changes
                            //       is a little vague at this point...
                            dsstate.stats.hereErr += 1;
                            dsstate.action = 'error';
                            dsstate.error  = {
                                message:  'Sync agent for store "' + store.uri + '" not available',
                                code:     'syncml-js.TypeError'
                            };
                            ret[0].statusCode = constant.STATUS_SERVICE_UNAVAILABLE;
                            ret[0].errorMsg   = dsstate.error.message;
                            ret[0].errorCode  = dsstate.error.code;
                            return cb(null, ret);
                        }

                        if ( store.agent.hierarchicalSync )
                            session.hierlut = {};

                        var preprocess = common.noop;

                        if ( ( ! session.isServer && dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER )
                                || ( session.isServer && dsstate.mode == constant.ALERT_REFRESH_FROM_CLIENT ) )
                        {
                            // delete all local items
                            preprocess = function(cb) {
                                store.agent.getAllItems(function(err, items) {
                                    if ( err )
                                    return cb(err);
                                common.cascade(items, function(item, cb) {
                                    store.agent.deleteItem(item.id, function(err) {
                                        if ( err )
                                        return cb(err);
                                    dsstate.stats.hereDel += 1;
                                    if ( ! session.isServer )
                                        return cb();
                                    store.registerChange(item.id, constant.ITEM_DELETED,
                                        {excludePeerID: session.peer.id}, cb);
                                    });
                                }, function(err) {
                                    if ( err )
                                    return cb(err);
                                return store.getPeerStore(session.peer)._delChange({}, cb);
                                });
                                });
                            };
                        }

                        if ( dsstate.mode == constant.ALERT_SLOW_SYNC
                                || ( session.isServer && dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER ) )
                        {
                            // delete all mappings and pending changes
                            var peerStore = store.getPeerStore(session.peer);
                            var prepreprocess = preprocess;
                            preprocess = function(cb) {
                                prepreprocess(function(err) {
                                    if ( err )
                                    return cb(err);
                                peerStore._delChange({}, function(err) {
                                    if ( err )
                                    return cb(err);
                                peerStore._clearAllMappings(cb);
                                });
                                });
                            };
                        }

                        preprocess(function(err) {
                            if ( err )
                            return cb(err);

                        if ( command.data.length <= 0 )
                            return cb(null, ret);

                        // paranoia: verify that i should be receiving data...
                        if ( ! ( dsstate.mode == constant.ALERT_TWO_WAY
                                || dsstate.mode == constant.ALERT_SLOW_SYNC
                                || ( ! session.isServer
                                    && ( dsstate.mode == constant.ALERT_ONE_WAY_FROM_SERVER
                                        || dsstate.mode == constant.ALERT_REFRESH_FROM_SERVER ) )
                                || ( session.isServer
                                    && ( dsstate.mode == constant.ALERT_ONE_WAY_FROM_CLIENT
                                        || dsstate.mode == constant.ALERT_REFRESH_FROM_CLIENT ) ) ) )
                            return cb(new common.ProtocolError(
                                    'unexpected sync data (role="'
                                        + ( session.isServer ? 'server' : 'client' )
                                        + '", mode="' + common.mode2string(dsstate.mode)
                                        + '")'));

                        common.cascade(command.data, function(cmd, cb) {

                            // NOTE: commented this paranoia setting out, since the server
                            //       *may* decide to update/delete a client item...
                            //       e.g. conflict-resolved-merge (207)
                            // TODO: perhaps i should only allow non-ADDs for those items
                            //       that i received a conflict-resolved-merge (207) for?...

                            // // paranoia: non-'add' sync commands should only be received in non-refresh modes
                            // if ( cmd.name != constant.CMD_ADD
                            //      && _.indexOf([constant.ALERT_TWO_WAY,
                            //                    constant.ALERT_ONE_WAY_FROM_SERVER,
                            //                    constant.ALERT_ONE_WAY_FROM_CLIENT], dsstate.mode) < 0 )
                            //   return cb(new common.ProtocolError(
                            //     'unexpected non-add sync command (role="'
                            //       + ( session.isServer ? 'server' : 'client' )
                            //       + '", mode="' + common.mode2string(dsstate.mode)
                            //       + '", command="' + cmd.name
                            //       + '")'));

                            self._reaction_syncdispatch(session, cmd, store, dsstate, function(err, cmds) {
                                if ( err )
                                return cb(err);
                            _.each(cmds, function(cmd) { ret.push(cmd); });
                            return cb();
                            });

                        }, function(err) {
                            if ( err )
                                return cb(err);
                            return cb(null, ret);
                        });
                        });
                    },

                    //-------------------------------------------------------------------------
                    _reaction_syncdispatch: function(session, cmd, store, dsstate, cb) {

                        var self = this;
                        var func = self['_reaction_sync_' + cmd.name.toLowerCase()];
                        if ( ! func )
                            return cb(new common.ProtocolError(
                                        'unexpected reaction requested for sync command "' + cmd.name + '"'));

                        var check_for_conflicts = common.noop;

                        if ( session.isServer
                                && cmd.name != constant.CMD_ADD
                                && dsstate.mode != constant.ALERT_REFRESH_FROM_CLIENT )
                        {
                            // server, non-add, non-slowsync, non-refresh commands: check for conflicts.
                            // note that certain types of content could be a conflict even if it is an
                            // "Add" command; for example, two files with the same name cannot be added
                            // from separate clients.

                            check_for_conflicts = function(cb) {

                                // todo: allow agents to raise a ConflictError...
                                //       ==> perhaps this is already covered by the .matchItem() API?...

                                var policy = store.conflictPolicy || session.adapter.conflictPolicy;
                                var peerStore = session.peer.getStore(dsstate.peerUri);
                                self.getSourceMapping(
                                        session, constant.CMD_SYNC, cmd, peerStore, cmd.source,
                                        function(err, itemID) {

                                            if ( err )
                                    return cb(err);
                                if ( ! itemID )
                                    // this shouldn't happen...
                                    return cb();

                                peerStore._getChange(itemID, function(err, change) {
                                    if ( err )
                                    return cb(err);
                                if ( ! change )
                                    return cb();

                                var retcmd = state.makeCommand({
                                    name       : constant.CMD_STATUS,
                                    cmdID      : session.nextCmdID(),
                                    msgRef     : cmd.msgID,
                                    cmdRef     : cmd.cmdID,
                                    sourceRef  : cmd.source,
                                    targetRef  : cmd.target,
                                    statusOf   : cmd.name,
                                    // todo: make this error message a bit more descriptive...
                                    errorMsg   : 'command "' + cmd.name + '" conflict for item ID "'
                                    + itemID + '" (state: ' + common.state2string(change.state) + ')'
                                });


                                    // four possible states: mod-mod, mod-del, del-mod, del-del
                                    if ( ! dsstate.conflicts )
                                    dsstate.conflicts = [];

                                    // handle mod-mod (but only if change-tracking is enabled)
                                    if ( change.state == constant.ITEM_MODIFIED
                                        && cmd.name == constant.CMD_REPLACE )
                                    {
                                        cmd._conflict = retcmd;
                                        cmd._change   = change;
                                        return cb();
                                    }

                                    // handle del-del
                                    if ( change.state == constant.ITEM_DELETED
                                            && cmd.name == constant.CMD_DELETE )
                                    {
                                        // both changes are deletes... that's not a conflict.
                                        // TODO: should i really be doing all this here?... it does not
                                        //       follow the pattern..
                                        peerStore._delChange({
                                            itemID: change.item_id,
                                            state:  change.state
                                        }, function(err) {
                                            if ( err )
                                            return cb(err);
                                        dsstate.stats.peerDel   += 1;
                                        dsstate.stats.hereDel   += 1;
                                        dsstate.stats.merged    += 1;
                                        retcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_MERGE;
                                        retcmd.errorCode  = null;
                                        retcmd.errorMsg   = null;
                                        return cb(null, [retcmd]);
                                        });
                                        return;
                                    }

                                    // handle del-mod or mod-del
                                    if ( ( change.state == constant.ITEM_DELETED
                                                || cmd.name == constant.CMD_DELETE )
                                            && policy != constant.POLICY_ERROR )
                                    {
                                        // one of them is a delete and a conflict that can be solved
                                        // by the framework
                                        cmd._conflict = retcmd;
                                        cmd._change   = change;
                                        return cb();
                                    }

                                    dsstate.conflicts.push(itemID);
                                    dsstate.stats.peerErr   += 1;
                                    dsstate.stats.conflicts += 1;
                                    retcmd.statusCode = constant.STATUS_UPDATE_CONFLICT;
                                    retcmd.errorCode  = 'syncml-js.synchronizer.RSd.10';
                                    return cb(null, [retcmd]);
                                });
                                        }
                                );
                            };
                        }

                        check_for_conflicts(function(err, cmds) {
                            if ( err || cmds )
                            return cb(err, cmds);
                        try{
                            func.call(self, session, cmd, store, dsstate, cb);
                        }catch(e){
                            return cb(new common.InternalError(
                                    'failed invoking synchronizer sync reaction: ' + e, e));
                        }
                        });

                    },

                    //-------------------------------------------------------------------------
                    _reaction_sync_add: function(session, cmd, store, dsstate, cb) {
                        var curitem = null;
                        var item    = null;
                        if ( store.agent.hierarchicalSync )
                        {
                            if ( cmd.targetParent )
                                cmd.data.parent = cmd.targetParent;
                            else if ( cmd.sourceParent )
                                cmd.data.parent = session.hierlut[cmd.sourceParent];
                        }

                        var matcher = common.noop;
                        if ( session.isServer && dsstate.mode == constant.ALERT_SLOW_SYNC )
                        {
                            // TODO: if the matched item is already mapped to another client-side
                            //       object, then this should cancel the matching...
                            matcher = function(cb) {
                                store.agent.matchItem(cmd.data, function(err, match) {
                                    if ( err )
                                    return cb(err);
                                if ( ! match || ! match.compare )
                                    return cb();
                                curitem = match;
                                if ( match.compare(cmd.data) == 0 )
                                    return cb();
                                store.agent.mergeItems(curitem, cmd.data, null, function(err) {
                                    // TODO: if there is a common.ConflictError, set
                                    //       curitem to null and continue without error...
                                    if ( err )
                                    return cb(err);
                                store.registerChange(curitem.id, constant.ITEM_MODIFIED,
                                    {changeSpec: cspec, excludePeerID: session.peer.id},
                                    cb);
                                });
                                });
                            };
                        }

                        matcher(function(err) {
                            if ( err )
                            return cb(err);
                        var adder = common.noop;
                        if ( ! curitem )
                            adder = function(cb) {
                                store.agent.addItem(cmd.data, function(err, newitem) {
                                    if ( err )
                                    return cb(err);
                                item = newitem;
                                dsstate.stats.hereAdd += 1;
                                store.registerChange(item.id, constant.ITEM_ADDED,
                                    {excludePeerID: session.peer.id}, cb);
                                });
                            };
                        else
                            item = curitem;
                        return adder(function(err) {
                            if ( err )
                            return cb(err);

                        if ( store.agent.hierarchicalSync )
                            session.hierlut[cmd.source] = item.id;

                        var ret = [state.makeCommand({
                            name       : constant.CMD_STATUS,
                            cmdID      : session.nextCmdID(),
                            msgRef     : cmd.msgID,
                            cmdRef     : cmd.cmdID,
                            sourceRef  : cmd.source,
                            statusOf   : cmd.name,
                            statusCode : ( curitem
                                ? constant.STATUS_ALREADY_EXISTS
                                : constant.STATUS_ITEM_ADDED )
                        })];

                        if ( ! session.isServer )
                        {
                            ret.push(state.makeCommand({
                                name       : constant.CMD_MAP,
                                cmdID      : session.nextCmdID(),
                                source     : store.uri,
                                target     : dsstate.peerUri,
                                sourceItem : item.id,
                                targetItem : cmd.source
                            }));
                            return cb(null, ret);
                        }

                        var peerStore = session.peer.getStore(dsstate.peerUri);
                        peerStore._setMapping(item.id, cmd.source, function(err) {
                            if ( err )
                            return cb(err);
                        return cb(null, ret);
                        });

                        });
                        });

                    },

                    //-------------------------------------------------------------------------
                    getSourceMapping: function(session, cmdctxt, cmd, peerStore, luid, cb) {
                        peerStore._getReverseMapping(luid, function(err, guid) {

                            if ( err )
                            return cb(err);

                        if ( guid )
                            return cb(null, guid);

                        return cb(new common.InvalidItem(
                                'unexpected "' + cmdctxt + '/' + cmd.name
                                + '" request for unmapped item ID "' + luid + '"'));

                        // todo: pysyncml generates a nice cmd-specific error node:
                        //       (which is probably over-kill)

                        //     curmap = adapter._context._model.Mapping.q(store_id=peerStore.id, luid=luid).one()
                        //     return str(curmap.guid)
                        //   except NoResultFound:
                        //     msg = 'unexpected "%s/%s" request for unmapped item ID: %r' % (cmdctxt, cmd.name, luid)
                        //     # todo: this is a bit of a hack when cmdctxt == 'Status'...
                        //     return state.Command(
                        //       name       = constant.CMD_STATUS,
                        //       cmdID      = session.nextCmdID(),
                        //       msgRef     = cmd.msgID,
                        //       cmdRef     = cmd.cmdID,
                        //       sourceRef  = cmd.source,
                        //       targetRef  = cmd.target,
                        //       statusOf   = cmd.name if cmdctxt != constant.CMD_STATUS else cmdctxt,
                        //       statusCode = constant.STATUS_COMMAND_FAILED,
                        //       errorCode  = __name__ + '.' + self.__class__.__name__ + '.GSM.10',
                        //       errorMsg   = msg,
                        //       )

                        });
                    },

                    //-------------------------------------------------------------------------
                    _reaction_sync_replace: function(session, cmd, store, dsstate, cb) {

                        // TODO: handle hierarchical-sync...
                        var self = this;
                        var item = cmd.data;
                        var get_item_id = ( ! session.isServer ) ? function(cb) {
                            item.id = cmd.target;
                            return cb();
                        } : function(cb) {
                            var peerStore = session.peer.getStore(dsstate.peerUri);
                            self.getSourceMapping(
                                    session, constant.CMD_SYNC, cmd, peerStore, cmd.source,
                                    function(err, guid) {

                                        if ( err )
                                return cb(err);

                            // todo: what if guid is null?...

                            item.id = guid;
                            return cb();
                                    }
                                    );
                        };

                        var okcmd = state.makeCommand({
                            name       : constant.CMD_STATUS,
                            cmdID      : session.nextCmdID(),
                            msgRef     : cmd.msgID,
                            cmdRef     : cmd.cmdID,
                            targetRef  : cmd.target,
                            sourceRef  : cmd.source,
                            statusOf   : cmd.name,
                            statusCode : constant.STATUS_OK
                        });

                        var handle_conflict = ( ! cmd._conflict ) ? common.noop : function(cb) {

                            //   if cmd._conflict is not None:
                            //     try:
                            //       if cmd._change.state == constant.ITEM_DELETED:
                            //         raise common.ConflictError('item deleted')
                            //       if cmd._change.changeSpec is None:
                            //         raise common.ConflictError('no change tracking enabled - falling back to policy')
                            //       cspec = store.agent.mergeItems(store.agent.getItem(item.id), item, cmd._change.changeSpec)
                            //       dsstate.stats.hereMod += 1
                            //       store.registerChange(item.id, constant.ITEM_MODIFIED,
                            //                            changeSpec=cspec, excludePeerID=adapter.peer.id)
                            //       okcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_MERGE
                            //       # NOTE: *not* suppressing the change that is registered from server
                            //       #       to client, since the merge may have resulted in an item that
                            //       #       is not identical to the one on the client.
                            //       return [okcmd]
                            //     except common.ConflictError, e:
                            //       # conflict types: client=mod/server=mod or client=mod/server=del
                            //       if store.conflictPolicy == constant.POLICY_CLIENT_WINS:
                            //         adapter._context._model.session.delete(cmd._change)
                            //         dsstate.stats.merged += 1
                            //         okcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
                            //         if cmd._change.state == constant.ITEM_DELETED:
                            //           # todo: this "re-creation" of a new item is detrimental to
                            //           #       clients that are tracking changes to an item (for
                            //           #       example, a SyncML svn client bridge...). but then, to
                            //           #       them, this item may already have been deleted. ugh.
                            //           dsstate.stats.hereMod += 1
                            //           item = store.agent.addItem(item)
                            //           peerStore = store.peer
                            //           adapter._context._model.Mapping.q(store_id=peerStore.id, guid=item.id).delete()
                            //           newmap = adapter._context._model.Mapping(store_id=peerStore.id,
                            //                                                    guid=item.id,
                            //                                                    luid=cmd.source)
                            //           adapter._context._model.session.add(newmap)
                            //           store.registerChange(item.id, constant.ITEM_ADDED,
                            //                                excludePeerID=adapter.peer.id)
                            //           return [okcmd]
                            //         # falling back to standard handling...
                            //       elif store.conflictPolicy == constant.POLICY_SERVER_WINS:
                            //         dsstate.stats.merged += 1
                            //         okcmd.statusCode = constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA
                            //         return [okcmd]
                            //       else:
                            //         # store.conflictPolicy == constant.POLICY_ERROR or other...
                            //         dsstate.stats.peerErr    += 1
                            //         dsstate.stats.conflicts  += 1
                            //         cmd._conflict.errorMsg   += ', agent failed merge: ' + str(e)
                            //         cmd._conflict.statusCode = constant.STATUS_UPDATE_CONFLICT
                            //         cmd._conflict.errorCode  = common.fullClassname(self) + '.RSR.10'
                            //         dsstate.conflicts.append(str(item.id))
                            //         return [cmd._conflict]

                            cb();

                        };

                        // TODO: support hierarchical-sync...
                        // if ( store.agent.hierarchicalSync )
                        //   session.hierlut[cmd.source] = item.id;

                        get_item_id(function(err) {
                            if ( err )
                            return cb(err);
                        handle_conflict(function(err) {
                            if ( err )
                            return cb(err);
                        store.agent.replaceItem(item, session.isServer, function(err, cspec) {
                            if ( err )
                            return cb(err);
                        dsstate.stats.hereMod += 1;
                        store.registerChange(
                            item.id, constant.ITEM_MODIFIED,
                            {changeSpec: cspec, excludePeerID: session.peer.id},
                            function(err) {
                                if ( err )
                            return cb(err);
                        return cb(null, [okcmd]);
                            }
                            );
                        });
                        });
                        });

                    },

                    //-------------------------------------------------------------------------
                    _reaction_sync_delete: function(session, cmd, store, dsstate, cb) {

                        var self   = this;
                        var status = constant.STATUS_OK;
                        var itemID = null;

                        var get_item_id = ( ! session.isServer ) ? function(cb) {
                            itemID = cmd.target;
                            return cb();
                        } : function(cb) {
                            var peerStore = session.peer.getStore(dsstate.peerUri);
                            self.getSourceMapping(
                                    session, constant.CMD_SYNC, cmd, peerStore, cmd.source,
                                    function(err, guid) {

                                        // if not isinstance(itemID, basestring):
                                        //   return [itemID]

                                        if ( err )
                                return cb(err);

                            // todo: what if guid is null?...

                            itemID = guid;
                            if ( ! cmd._conflict )
                                return cb();
                            var policy = store.conflictPolicy || session.adapter.conflictPolicy;
                            switch ( policy )
                            {

                                case constant.POLICY_CLIENT_WINS:
                                    {


                                        // TODO ::: implement these...

                                        //   //     adapter._context._model.session.delete(cmd._change)
                                        //   //     status = constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
                                        //   //     session.dsstates[store.uri].stats.merged += 1
                                        //   //     # falling back to standard handling...

                                        //   break;

                                    }
                                case constant.POLICY_SERVER_WINS:
                                    {


                                        //   //     adapter._context._model.session.delete(cmd._change)
                                        //   //     store.peer.registerChange(itemID, constant.ITEM_ADDED)
                                        //   //     session.dsstates[store.uri].stats.merged += 1
                                        //   //     cmd._conflict.statusCode = constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA
                                        //   //     cmd._conflict.errorCode  = None
                                        //   //     cmd._conflict.errorMsg   = None
                                        //   //     return [cmd._conflict]

                                        //   break;

                                    }

                                default:
                                    {
                                        // a constant.POLICY_ERROR policy should have been handled by the dispatch
                                        return cb(new common.InternalError(
                                                    'unexpected conflictPolicy: %s', '' + policy));
                                    }
                            }
                                    }
                            );

                        };

                        get_item_id(function(err) {
                            if ( err )
                            return cb(err);
                        store.agent.deleteItem(itemID, function(err) {
                            if ( err )
                            return cb(err);
                        dsstate.stats.hereDel += 1;
                        store.registerChange(
                            itemID, constant.ITEM_DELETED, {excludePeerID: session.peer.id},
                            function(err) {
                                if ( err )
                            return cb(err);
                        return cb(null, [state.makeCommand({
                            name       : constant.CMD_STATUS,
                               cmdID      : session.nextCmdID(),
                               msgRef     : cmd.msgID,
                               cmdRef     : cmd.cmdID,
                               targetRef  : cmd.target,
                               sourceRef  : cmd.source,
                               statusOf   : cmd.name,
                               // todo: should this return DELETE_WITHOUT_ARCHIVE instead of OK?...
                               // statusCode = constant.STATUS_DELETE_WITHOUT_ARCHIVE,
                               statusCode : status
                        })]);
                            }
                            );
                        });
                        });

                    },

                    //-------------------------------------------------------------------------
                    _reaction_map: function(session, command, cb) {
                        var peerStore = session.peer.getStore(command.source);
                        if ( command.target != peerStore._getBinding().uri )
                            return cb(new common.NoSuchRoute(
                                        'unexpected "Map" event for unbound stores (local: "'
                                            + command.target + ', remote: "' + command.source + '")'));
                        common.cascade(command.items, function(item, cb) {
                            // todo: support hierarchical sync...
                            peerStore._setMapping(item.target, item.source, cb);
                        }, function(err) {
                            if ( err )
                            return cb(err);
                        return cb(null, [state.makeCommand({
                            name       : constant.CMD_STATUS,
                               cmdID      : session.nextCmdID(),
                               msgRef     : command.msgID,
                               cmdRef     : command.cmdID,
                               targetRef  : command.target,
                               sourceRef  : command.source,
                               statusOf   : command.name,
                               statusCode : constant.STATUS_OK
                        })]);
                        });
                    },

                    //-------------------------------------------------------------------------
                    // SYNCHRONIZATION PHASE: SETTLE
                    //-------------------------------------------------------------------------

                    //-------------------------------------------------------------------------
                    settle: function(session, cmd, chkcmd, xnode, cb) {

                        // TODO: remove the "xnode" parameter... it is a hack so that i can
                        //       call badStatus() the same way as in protocol.js
                        // todo: there is a bit of a disconnect between how action and reaction
                        //       phases are called (for a list of commands), whereas the settle
                        //       phase is called on a per-item basis... not ideal, but the protocol
                        //       is really set up that way :(
                        // TODO: check all valid values of ``data``...
                        // todo: anything else in common?...
                        // todo: trap errors...

                        var func = this['_settle_' + cmd.name.toLowerCase()];
                        if ( ! func )
                            return cb(new common.ProtocolError('unexpected settle command "' + cmd.name + '"'));
                        return func.call(this, session, cmd, chkcmd, xnode, cb);
                    },

                    //-------------------------------------------------------------------------
                    _settle_add: function(session, cmd, chkcmd, xnode, cb) {
                        switch ( cmd.data )
                        {
                            default:
                                {
                                    return cb(badStatus(xnode));
                                }
                            case constant.STATUS_OK:
                            case constant.STATUS_ITEM_ADDED:
                            case constant.STATUS_CONFLICT_RESOLVED_DUPLICATE:
                                {
                                    session.info.dsstates[chkcmd.uri].stats.peerAdd += 1;
                                    break;
                                }
                            case constant.STATUS_ALREADY_EXISTS:
                            case constant.STATUS_CONFLICT_RESOLVED_MERGE:
                                // todo: should this conflict-resolved-merge status be stored so
                                //       that only this item can have a non-"ADD" during initial
                                //       sync?...
                            case constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA:
                                {
                                    session.info.dsstates[chkcmd.uri].stats.merged += 1;
                                    break;
                                }
                        }

                        var peerStore = session.peer.getStore(
                                session.context.router.getTargetUri(
                                    session.adapter, session.peer, chkcmd.uri));

                        peerStore._delChange({
                            itemID: chkcmd.source,
                            state: constant.ITEM_ADDED
                        }, cb);
                    },

                    //-------------------------------------------------------------------------
                    _settle_replace: function(session, cmd, chkcmd, xnode, cb) {

                        var self = this;
                        var dsstate = session.info.dsstates[chkcmd.uri];

                        if ( ! session.isServer && cmd.data == constant.STATUS_UPDATE_CONFLICT )
                        {
                            dsstate.stats.hereErr   += 1;
                            dsstate.stats.conflicts += 1;
                            return cb();
                        }
                        if ( cmd.data != constant.STATUS_OK
                                && cmd.data != constant.STATUS_CONFLICT_RESOLVED_MERGE
                                && cmd.data != constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
                                && cmd.data != constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
                            return cb(badStatus(xnode));
                        if ( cmd.data == constant.STATUS_CONFLICT_RESOLVED_MERGE
                                || cmd.data == constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA
                                || cmd.data == constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
                            dsstate.stats.merged += 1;
                        if ( cmd.data != constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
                            dsstate.stats.peerMod += 1;

                        var peerStore = session.peer.getStore(
                                session.context.router.getTargetUri(
                                    session.adapter, session.peer, chkcmd.uri));

                        var get_item_id = ( ! session.isServer ) ? function(cb) {
                            return cb(null, chkcmd.source);
                        } : function(cb) {
                            // if not isinstance(locItemID, basestring):
                            //   return locItemID

                            self.getSourceMapping(
                                    session, constant.CMD_STATUS, cmd, peerStore, chkcmd.target,
                                    function(err, guid) { return cb(err, guid); }
                                    );
                        };

                        get_item_id(function(err, locItemID) {

                            if ( err )
                            return cb(err);

                        // todo: this is *technically* subject to a race condition... but the
                        //       same peer should really not be synchronizing at the same time...
                        // todo: also potentially check Change.registered...
                        // TODO: this could be solved by:
                        //         a) never updating a Change record (only deleting and replacing)
                        //         b) deleting Change records by ID instead of by store/item/state...

                        peerStore._delChange({
                            itemID    : locItemID,
                            state     : constant.ITEM_MODIFIED,
                        }, cb);

                        });

                    },

                    //-------------------------------------------------------------------------
                    _settle_delete: function(session, cmd, chkcmd, xnode, cb) {
                        var self    = this;
                        var dsstate = session.info.dsstates[chkcmd.uri];
                        if ( ! session.isServer && cmd.data == constant.STATUS_UPDATE_CONFLICT )
                        {
                            dsstate.stats.hereErr   += 1;
                            dsstate.stats.conflicts += 1;
                            return cb();
                        }
                        if ( ! session.isServer && cmd.data == constant.STATUS_CONFLICT_RESOLVED_MERGE )
                        {
                            dsstate.stats.hereDel   += 1;
                            dsstate.stats.peerDel   += 1;
                            dsstate.stats.merged    += 1;
                        }
                        else if ( ! session.isServer && cmd.data == constant.STATUS_CONFLICT_RESOLVED_CLIENT_DATA )
                        {
                            dsstate.stats.peerDel   += 1;
                            dsstate.stats.merged    += 1;
                        }
                        else if ( ! session.isServer && cmd.data == constant.STATUS_CONFLICT_RESOLVED_SERVER_DATA )
                            dsstate.stats.merged    += 1;
                        else if ( cmd.data == constant.STATUS_ITEM_NOT_DELETED )
                        {
                            // note: the reason that this *may* be ok is that some servers (funambol)
                            //       will report ITEM_NOT_DELETED when the item did not exist, thus this
                            //       is "alright"...
                            // todo: perhaps this should be raised as an error if the
                            //       remote peer != funambol?...
                        }
                        else if ( cmd.data == constant.STATUS_OK )
                            dsstate.stats.peerDel += 1;
                        else
                            return cb(badStatus(xnode));

                        var peerStore = session.peer.getStore(
                                session.context.router.getTargetUri(
                                    session.adapter, session.peer, chkcmd.uri));

                        // todo: handle hierarchical sync...
                        var get_locItemID = ( ! chkcmd.target ) ? function(cb) {
                            cb(null, chkcmd.source);
                        } : function(cb) {
                            self.getSourceMapping(
                                    session, constant.CMD_STATUS, cmd, peerStore, chkcmd.target,
                                    function(err, guid) { return cb(err, guid); }
                                    );
                        };

                        // todo: this is *technically* subject to a race condition... but the
                        //       same peer should really not be synchronizing at the same time...
                        // todo: also potentially check Change.registered...
                        // TODO: this could be solved by:
                        //         a) never updating a Change record (only deleting and replacing)
                        //         b) deleting Change records by ID instead of by store/item/state...

                        get_locItemID(function(err, locItemID) {
                            if ( err )
                            return cb(err);
                        peerStore._delChange({
                            itemID    : locItemID,
                            state     : constant.ITEM_DELETED,
                        }, cb);
                        });

                    }

    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/syncml-js-lib/useragent', function (require, exports, module) {
// -*- coding: utf-8 -*-
//-----------------------------------------------------------------------------
// file: $Id$
// lib:  syncml-js.useragent
// auth: griffin <griffin@uberdev.org>
// date: 2013/06/07
// copy: (C) CopyLoose 2013 UberDev <hardcore@uberdev.org>, No Rights Reserved.
//-----------------------------------------------------------------------------

var common = require('ripple/platform/tizen/2.0/syncml-js-lib/common'),
    constant = require('ripple/platform/tizen/2.0/syncml-js-lib/constant'),
    _self;

_self = (function () {
    var exports = {};

    //---------------------------------------------------------------------------
    exports.UserAgent = common.Base.extend({
        // primary handlers:
        acceptSyncModeSwitch:  null, // function(EVENT, CALLBACK(ERR))
            acceptDevInfoSwap:     null, // function(EVENT, CALLBACK(ERR))
            chooseRefreshRequired: null, // function(EVENT, CALLBACK(ERR, TYPE))
            fetchCredentials:      null, // function(EVENT, CALLBACK(ERR, AUTH))
            // fallback handlers:
            accept:                null, // function(TYPE, EVENT, CALLBACK(ERR))
            choose:                null, // function(TYPE, EVENT, CALLBACK(ERR, CHOICE))
            fetch:                 null, // function(TYPE, EVENT, CALLBACK(ERR, STRUCT))
            // catchall handler:
            handle:                null  // function(ACTION, TYPE, EVENT, CALLBACK(ERR, RESULT...))
    });

    //---------------------------------------------------------------------------
    exports.UserAgentMultiplexer = common.Base.extend({

        //-------------------------------------------------------------------------
        constructor: function(uaList) {
            this.ualist = uaList;
        },

        //-------------------------------------------------------------------------
        _getHandler: function(name) {
            for ( var idx=0 ; idx<this.ualist.length ; idx++ )
    {
        var ua = this.ualist[idx];
        if ( ua && _.isFunction(ua[name]) )
        return ua[name];
    }
    return null;
        },

        //-------------------------------------------------------------------------
        hasHandler: function(name) {
            return !! this._getHandler(name);
        },

        //-------------------------------------------------------------------------
        acceptSyncModeSwitch: function(event, cb) {
            return this._handle({
                handler: 'acceptSyncModeSwitch',
            action:  'accept',
            type:    'sync.mode.switch'
            }, event, cb);
        },

        //-------------------------------------------------------------------------
        acceptDevInfoSwap: function(event, cb) {
            return this._handle({
                handler: 'acceptDevInfoSwap',
            action:  'accept',
            type:    'dev.info.swap'
            }, event, cb);
        },

        //-------------------------------------------------------------------------
        chooseRefreshRequired: function(event, cb) {
            return this._handle({
                handler: 'chooseRefreshRequired',
            action:  'choose',
            type:    'refresh.required',
            choices: [
            {value: constant.SYNCTYPE_SLOW_SYNC, default: true},
            {value: constant.SYNCTYPE_REFRESH_FROM_CLIENT},
            {value: constant.SYNCTYPE_REFRESH_FROM_SERVER}
            ]
            }, event, function(err, choice) {
                if ( err )
                return cb(err);
            // todo: catch the condition where `choice` is not a valid synctype
            return cb(err, common.synctype2alert(choice));
            });
        },

        //-------------------------------------------------------------------------
        fetchCredentials: function(event, cb) {
            return this._handle({
                handler: 'fetchCredentials',
            action:  'fetch',
            type:    'auth.challenge',
            choices: [
            {value: constant.SYNCTYPE_SLOW_SYNC, default: true},
            {value: constant.SYNCTYPE_REFRESH_FROM_CLIENT},
            {value: constant.SYNCTYPE_REFRESH_FROM_SERVER}
            ]
            }, event, cb);
        },

        //-------------------------------------------------------------------------
        _handle: function(spec, event, cb) {
            event = _.extend({}, spec, event, {
                type         : spec.type,
            context      : event.session.context,
            adapter      : event.session.adapter,
            peer         : event.session.peer,
            ua_handler   : spec.handler,
            ua_action    : spec.action
            });
            var handler = this._getHandler(spec.handler);
            if ( handler )
                return handler(event, cb);
            handler = this._getHandler(spec.action);
            if ( handler )
                return handler(spec.type, event, cb);
            handler = this._getHandler('handle');
            if ( handler )
                return handler(spec.action, spec.type, event, cb);
            if ( spec.action == 'accept' )
            {
                return cb();
            }
            if ( spec.action == 'choose'
                    && event.choices && event.choices.length > 0 )
            {
                var choice = _.find(event.choices, function(c) { return c.default; });
                if ( ! choice )
                    choice = event.choices[0];
                if ( choice.value )
                    choice = choice.value;
                return cb(null, choice);
            }
            if ( spec.type == 'auth.challenge' )
                return cb();
            return cb(new common.NotImplementedError(
                        'user-agent handler for event type "' + spec.type + '" (action: "'
                            + spec.action + '") not found or defined'));
        }

    });

    return exports;

})();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/systeminfo', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 deviceSettings = require('ripple/deviceSettings'),
    db = require('ripple/db'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    typedef = require('ripple/platform/tizen/2.0/typedef'),
    constants = require('ripple/constants'),
    event = require('ripple/event'),
    tizen_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    SystemInfoDeviceCapability,
    _systemInfoProperties = typedef.SystemInfoPropertyId,
    _propertyMap = {}, // Object like: {"BATTERY": ["level", "isCharging"], ...}
    _batteryEvent = ["BatteryLevelChanged", "BatteryChargingChanged"],
    _watches = {},
    _firstCall_watches = {},
    _powerData = {},
    _systemInfoDeviceCapability = null,
    _security = {
        "http://tizen.org/privilege/system": ["SystemInfoSIM", "webApiVersion",
                "nativeApiVersion", "platformVersion"],
        "http://tizen.org/privilege/systemmanager": ["NetworkImei"]
    },
    _self;

function _prepareObj(obj, aspect, property, value) {
    if ((aspect === "CELLULAR_NETWORK") && (property === "imei")) {
        obj.__defineGetter__("imei", function () {
            if (!_security.NetworkImei) {
                throw new WebAPIException(errorcode.SECURITY_ERR);
            }
            return deviceSettings.retrieve("CELLULAR_NETWORK.imei");
        });
    } else {
        if (aspect === "WIFI_NETWORK" || aspect === "CELLULAR_NETWORK") {
            if (property === 'status') {
                if (value === true) {
                    value = "ON";
                } else {
                    value = "OFF";
                }
            }
        }
        obj.__defineGetter__(property, function () {
            return value;
        });
    }
}

function _getValue(aspect, successCallback) {
    var properties = [], value, index = 0, property, obj = {};

    if ((aspect === "SIM") && !_security.SystemInfoSIM) {
        throw new WebAPIException(errorcode.SECURITY_ERR);
    }

    if (aspect === "BATTERY") {
        successCallback(_powerData);
        return;
    }

    properties = _propertyMap[aspect];
    for (; index < properties.length; index++) {
        property = properties[index];
        value = deviceSettings.retrieve(aspect + "." + property);
        _prepareObj(obj, aspect, property, value);
    }

    if (aspect === "STORAGE") {
        obj.__defineGetter__("units", function () {
            return [obj];
        });
    }

    successCallback(obj);
}

function _initialize() {
    var aspectName, index, i, vol;

    for (index = 0; index < _systemInfoProperties.length; index++) {
        aspectName = _systemInfoProperties[index];
        _propertyMap[aspectName] = [];
        for (i in deviceSettings.retrieve(aspectName)) {
            _propertyMap[aspectName].push(i);
        }
    }

    _propertyMap.BATTERY.push("level");
    _propertyMap.BATTERY.push("isCharging");

    _powerData.__defineGetter__("isCharging", function () {
        return false;
    });

    vol = db.retrieve(constants.BATTERY.VOLUME) || 100.0;
    _powerData.__defineGetter__("level", function () {
        return Number((vol / 100.0).toFixed(4));
    });

    event.on("BatteryEvent", function (status) {
        _powerData.__defineGetter__("isCharging", function () {
            return status.charging;
        });
        _powerData.__defineGetter__("level", function () {
            return Number(status.level.toFixed(4));
        });
    });
}

function _isPropertyFound(property) {
    if (tizen_utils.isEmptyObject(_propertyMap)) {
        _initialize();
    }

    if (_propertyMap[property]) {
        return true;
    }

    return false;
}

function _delayGetValue(timeout, property, successCallback, errorCallback) {
    return window.setInterval(function () {
        _getValue(property, successCallback, errorCallback);
    }, timeout);
}

_self = function () {
    function getCapabilities() {
        if (_systemInfoDeviceCapability === null) {
            _systemInfoDeviceCapability = new SystemInfoDeviceCapability();
        }
        return _systemInfoDeviceCapability;
    }

    function getPropertyValue(property, successCallback, errorCallback) {
        t.SystemInfo("getPropertyValue", arguments);

        if (!_isPropertyFound(property)) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }

        window.setTimeout(function () {
            _getValue(property, successCallback, errorCallback);
        }, 1);
    }

    function addPropertyValueChangeListener(property, successCallback, options) {
        var WatchOBJ, watchId = Number(Math.uuid(8, 10)),
            _options = new Object(options), properties, prop, index = 0,
            deviceEventType, watchObj, firstCallWatchObj;

        t.SystemInfo("addPropertyValueChangeListener", arguments);

        if (!_isPropertyFound(property)) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }

        WatchOBJ = function (deviceEventType, property, successCallback) {
            var obj = this;

            this.eventType = deviceEventType;
            this.onEvent = function (newValue) {
                if (obj.timeout) {
                    window.clearInterval(obj.intervalId);
                    obj.intervalId = window.setInterval(function () {
                        _getValue(property, successCallback, null);
                    }, obj.timeout);
                }

                if ((obj.highThreshold && (newValue < obj.highThreshold)) ||
                    (obj.lowThreshold && (newValue > obj.lowThreshold))) {
                    return;
                }

                _getValue(property, successCallback, null);
            };
        };

        // A listener will listen all the properties of one aspect, each of the property
        // will have an internal watchObj to record the information.
        _watches[watchId] = [];

        if (property === "BATTERY") {
            properties = _batteryEvent;
        } else {
            properties = _propertyMap[property];
        }

        for (; index < properties.length; index++) {
            prop = properties[index];
            if (property === "BATTERY") {
                deviceEventType = prop;
            } else {
                deviceEventType = deviceSettings.retrieve(property)[prop].event;
            }

            if (deviceEventType === undefined) continue;
            // These two items are needed when delete an event listener.
            watchObj = new WatchOBJ(deviceEventType, property, successCallback);

            if (options && _options.timeout) {
                watchObj.intervalId = _delayGetValue(_options.timeout, property,
                        successCallback, null);
            }

            if ((watchObj.eventType === "CpuLoadChanged") ||
                    (watchObj.eventType === "DisplayBrightnessChanged") ||
                    (watchObj.eventType === "BatteryLevelChanged")) {
                if (options && _options.highThreshold) {
                    watchObj.highThreshold = _options.highThreshold;
                }

                if (options && _options.lowThreshold) {
                    watchObj.lowThreshold = _options.lowThreshold;
                }
            }

            _watches[watchId].push(watchObj);
            if (watchObj.eventType) {
                event.on(watchObj.eventType, watchObj.onEvent);
            }
        }

        firstCallWatchObj = window.setTimeout(function () {
            if (property !== "BATTERY") {
                _getValue(property, successCallback, null);
            }
            delete _firstCall_watches[watchId];
        }, 1);

        _firstCall_watches[watchId] = firstCallWatchObj;

        return watchId;
    }

    function removePropertyValueChangeListener(listenerID) {
        var _handler = listenerID, index = 0, watchObjs = [], watchObj;

        if (!_watches[_handler])
            return;

        watchObjs = _watches[_handler];
        if (watchObjs) {
            for (; index < watchObjs.length; index++) {
                watchObj = watchObjs[index];
                event.deleteEventHandler(watchObj.eventType, watchObj.onEvent);
                if (watchObj.intervalId) {
                    window.clearInterval(watchObj.intervalId);
                }
            }
            delete _watches[_handler];
        }

        if (_firstCall_watches[_handler]) {
            window.clearTimeout(_firstCall_watches[_handler]);
            delete _firstCall_watches[_handler];
        }
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    var systeminfo = {
        getCapabilities: getCapabilities,
        getPropertyValue: getPropertyValue,
        addPropertyValueChangeListener: addPropertyValueChangeListener,
        removePropertyValueChangeListener: removePropertyValueChangeListener,
        handleSubFeatures: handleSubFeatures
    };

    return systeminfo;
};

SystemInfoDeviceCapability = function () {
    this.__defineGetter__("bluetooth", function () {
        return true;
    });
    this.__defineGetter__("nfc", function () {
        return true;
    });
    this.__defineGetter__("nfcReservedPush", function () {
        return false;
    });
    this.__defineGetter__("multiTouchCount", function () {
        return 5;
    });
    this.__defineGetter__("inputKeyboard", function () {
        return false;
    });
    this.__defineGetter__("inputKeyboardLayout", function () {
        return false;
    });
    this.__defineGetter__("wifi", function () {
        return true;
    });
    this.__defineGetter__("wifiDirect", function () {
        return true;
    });
    this.__defineGetter__("opengles", function () {
        return false;
    });
    this.__defineGetter__("openglestextureFormat", function () {
        return "";
    });
    this.__defineGetter__("openglesVersion1_1", function () {
        return false;
    });
    this.__defineGetter__("openglesVersion2_0", function () {
        return false;
    });
    this.__defineGetter__("fmRadio", function () {
        return false;
    });
    this.__defineGetter__("platformVersion", function () {
        if (!_security.platformVersion) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        return "2.2.0";
    });
    this.__defineGetter__("webApiVersion", function () {
        if (!_security.webApiVersion) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        return "2.2";
    });
    this.__defineGetter__("nativeApiVersion", function () {
        if (!_security.nativeApiVersion) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }
        return "2.2";
    });
    this.__defineGetter__("platformName", function () {
        return "Tizen";
    });
    this.__defineGetter__("camera", function () {
        return false;
    });
    this.__defineGetter__("cameraFront", function () {
        return false;
    });
    this.__defineGetter__("cameraFrontFlash", function () {
        return false;
    });
    this.__defineGetter__("cameraBack", function () {
        return false;
    });
    this.__defineGetter__("cameraBackFlash", function () {
        return false;
    });
    this.__defineGetter__("location", function () {
        return true;
    });
    this.__defineGetter__("locationGps", function () {
        return true;
    });
    this.__defineGetter__("locationWps", function () {
        return false;
    });
    this.__defineGetter__("microphone", function () {
        return false;
    });
    this.__defineGetter__("usbHost", function () {
        return true;
    });
    this.__defineGetter__("usbAccessory", function () {
        return false;
    });
    this.__defineGetter__("screenOutputRca", function () {
        return false;
    });
    this.__defineGetter__("screenOutputHdmi", function () {
        return false;
    });
    this.__defineGetter__("platformCoreCpuArch", function () {
        return "x86";
    });
    this.__defineGetter__("platformCoreFpuArch", function () {
        return "ssse3";
    });
    this.__defineGetter__("sipVoip", function () {
        return false;
    });
    this.__defineGetter__("duid", function () {
        return "device unique ID";
    });
    this.__defineGetter__("speechRecognition", function () {
        return false;
    });
    this.__defineGetter__("speechSynthesis", function () {
        return false;
    });
    this.__defineGetter__("accelerometer", function () {
        return true;
    });
    this.__defineGetter__("accelerometerWakeup", function () {
        return false;
    });
    this.__defineGetter__("barometer", function () {
        return false;
    });
    this.__defineGetter__("barometerWakeup", function () {
        return false;
    });
    this.__defineGetter__("gyroscope", function () {
        return true;
    });
    this.__defineGetter__("gyroscopeWakeup", function () {
        return false;
    });
    this.__defineGetter__("magnetometer", function () {
        return false;
    });
    this.__defineGetter__("magnetometerWakeup", function () {
        return false;
    });
    this.__defineGetter__("photometer", function () {
        return false;
    });
    this.__defineGetter__("photometerWakeup", function () {
        return false;
    });
    this.__defineGetter__("proximity", function () {
        return false;
    });
    this.__defineGetter__("proximityWakeup", function () {
        return false;
    });
    this.__defineGetter__("tiltmeter", function () {
        return false;
    });
    this.__defineGetter__("tiltmeterWakeup", function () {
        return false;
    });
    this.__defineGetter__("dataEncryption", function () {
        return false;
    });
    this.__defineGetter__("graphicsAcceleration", function () {
        return false;
    });
    this.__defineGetter__("push", function () {
        return true;
    });
    this.__defineGetter__("telephony", function () {
        return true;
    });
    this.__defineGetter__("telephonyMms", function () {
        return true;
    });
    this.__defineGetter__("telephonySms", function () {
        return true;
    });
    this.__defineGetter__("screenSizeNormal", function () {
        return true;
    });
    this.__defineGetter__("screenSize480_800", function () {
        return true;
    });
    this.__defineGetter__("screenSize720_1280", function () {
        return true;
    });
    this.__defineGetter__("autoRotation", function () {
        return true;
    });
    this.__defineGetter__("shellAppWidget", function () {
        return false;
    });
    this.__defineGetter__("visionImageRecognition", function () {
        return false;
    });
    this.__defineGetter__("visionQrcodeGeneration", function () {
        return false;
    });
    this.__defineGetter__("visionQrcodeRecognition", function () {
        return false;
    });
    this.__defineGetter__("visionFaceRecognition", function () {
        return false;
    });
    this.__defineGetter__("secureElement", function () {
        return true;
    });
    this.__defineGetter__("nativeOspCompatible", function () {
        return false;
    });
    this.__defineGetter__("profile", function () {
        return "MOBILE_WEB";
    });
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/systemsetting', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    event = require('ripple/event'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    _systemSettings = null,
    DBSYSTEMSETTING_KEY = "tizen2-systemsetting",
    _security = {
        "http://tizen.org/privilege/setting": ["setProperty"]
    },
    _self;

function _initialize() {
    _systemSettings = db.retrieveObject(DBSYSTEMSETTING_KEY);
    if (!_systemSettings) {
        _systemSettings = {"HOME_SCREEN": "images/home_screen.jpg", "LOCK_SCREEN": "images/lock_screen.jpg", "INCOMING_CALL": "sounds/incoming.wav", "NOTIFICATION_EMAIL": "sounds/notification.wav"};
        db.saveObject(DBSYSTEMSETTING_KEY, _systemSettings);
        event.trigger("SystemSettingChanged");
    }
}

_self = function () {
    var systemSetting;

    function setProperty(type, value, successCallback, errorCallback) {
        if (!_security.setProperty) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.SystemSettingManager("setProperty", arguments);

        _systemSettings = db.retrieveObject(DBSYSTEMSETTING_KEY);
        _systemSettings[type] = value;
        db.saveObject(DBSYSTEMSETTING_KEY, _systemSettings);
        event.trigger("SystemSettingChanged");
        window.setTimeout(function () {
            successCallback();
        }, 1);
    }

    function getProperty(type, successCallback, errorCallback) {
        t.SystemSettingManager("getProperty", arguments);

        _systemSettings = db.retrieveObject(DBSYSTEMSETTING_KEY);
        window.setTimeout(function () {
            successCallback(_systemSettings[type]);
        }, 1);
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    systemSetting = {
        setProperty:       setProperty,
        getProperty:       getProperty,
        handleSubFeatures: handleSubFeatures
    };

    return systemSetting;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/time', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typecast'),
    TZDate = require('ripple/platform/tizen/2.0/TZDate'),
    db = require('ripple/db'),
    tz = require('ripple/platform/tizen/2.0/timezone_info'),
    _timeFormat = "h:m:s ap", _shortDateFormat = "d/m/y",
    _longDateFormat = "D, M d, y", _self;

_self = {
    getCurrentDateTime: function () {
        t.TimeUtil("getCurrentDateTime", arguments);
        return new TZDate();
    },
    getLocalTimezone: function () {
        t.TimeUtil("getLocalTimezone", arguments);
        var localtz = db.retrieve("tizen-timezone") || "UTC";
        return localtz;
    },
    getAvailableTimezones: function () {
        t.TimeUtil("getAvailableTimezones", arguments);
        var ret = tz.getAllTimezone();
        return ret;
    },
    getDateFormat: function (shortformat) {
        t.TimeUtil("getDateFormat", arguments);

        if (shortformat) {
            return _shortDateFormat;
        } else {
            return _longDateFormat;
        }
    },
    getTimeFormat: function () {
        t.TimeUtil("getTimeFormat", arguments);
        return _timeFormat;
    },
    isLeapYear: function (year) {
        t.TimeUtil("isLeapYear", arguments);
        return ((year % 4 === 0) && (year % 100 !== 0 || year % 400 === 0));
    }
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/timezone_info', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 _timezone_data = {
    "UTC": {diff: 0, abbr: "UTC"},
    "Africa/Cairo": {diff: 2, abbr: "EET"},
    "Africa/Casablanca": {diff: 0, abbr: "UTC"},
    "Africa/Dakar": {diff: 0, abbr: "UTC"},
    "Africa/Freetown": {diff: 0, abbr: "UTC"},
    "Africa/Johannesburg": {diff: 2, abbr: "SAST"},
    "Africa/Luanda": {diff: 1, abbr: "WAT"},
    "America/Anchorage": {diff: -9, abbr: "AKDT"},
    "America/Antigua": {diff: -4, abbr: "AST"},
    "America/Aruba": {diff: -4, abbr: "AST"},
    "America/Barbados": {diff: -4, abbr: "AST"},
    "America/Belize": {diff: -6, abbr: "CST"},
    "America/Bogota": {diff: -5, abbr: "COT"},
    "America/Buenos_Aires": {diff: -3, abbr: "ART"},
    "America/Cancun": {diff: -6, abbr: "CDT"},
    "America/Cayenne": {diff: -3, abbr: "GFT"},
    "America/Cayman": {diff: -5, abbr: "EST"},
    "America/Chicago": {diff: -6, abbr: "CST"},
    "America/Chihuahua": {diff: -7, abbr: "MST"},
    "America/Costa_Rica": {diff: -6, abbr: "CST"},
    "America/Denver": {diff: -7, abbr: "MST"},
    "America/Detroit": {diff: -5, abbr: "EST"},
    "America/Dominica": {diff: -4, abbr: "AST"},
    "America/Edmonton": {diff: -7, abbr: "MST"},
    "America/El_Salvador": {diff: -6, abbr: "CST"},
    "America/Guatemala": {diff: -6, abbr: "CST"},
    "America/Havana": {diff: -5, abbr: "CST"},
    "America/Indianapolis": {diff: -5, abbr: "EST"},
    "America/Jamaica": {diff: -5, abbr: "EST"},
    "America/Lima": {diff: -5, abbr: "PET"},
    "America/Los_Angeles": {diff: -8, abbr: "PST"},
    "America/Louisville": {diff: -5, abbr: "EST"},
    "America/Mexico_City": {diff: -6, abbr: "CST"},
    "America/Montevideo": {diff: -2, abbr: "UYST"},
    "America/Montreal": {diff: -5, abbr: "EST"},
    "America/New_York": {diff: -5, abbr: "EST"},
    "America/Panama": {diff: -5, abbr: "EST"},
    "America/Phoenix": {diff: -7, abbr: "MST"},
    "America/Puerto_Rico": {diff: -4, abbr: "AST"},
    "America/Santiago": {diff: -3, abbr: "CLST"},
    "America/Santo_Domingo": {diff: -4, abbr: "AST"},
    "America/Sao_Paulo": {diff: -4, abbr: "AST"},
    "America/Tijuana": {diff: -8, abbr: "PST"},
    "America/Vancouver": {diff: -8, abbr: "PST"},
    "America/Winnipeg": {diff: -6, abbr: "CST"},
    "Antarctica/South_Pole": {diff: 13, abbr: "NZDT"},
    "Arctic/Longyearbyen": {diff: 13, abbr: "CET"},
    "Asia/Amman": {diff: 2, abbr: "EET"},
    "Asia/Baghdad": {diff: 3, abbr: "AST"},
    "Asia/Bahrain": {diff: 3, abbr: "AST"},
    "Asia/Bangkok": {diff: 7, abbr: "ICT"},
    "Asia/Beirut": {diff: 2, abbr: "EET"},
    "Asia/Chungking": {diff: 8, abbr: "CST"},
    "Asia/Dubai": {diff: 4, abbr: "GST", desc:"GMT+0400 United Arab Emirates Time"},
    "Asia/Harbin": {diff: 8, abbr: "CST"},
    "Asia/Ho_Chi_Minh": {diff: 7, abbr: "IST"},
    "Asia/Hong_Kong": {diff: 8, abbr: "HKT"},
    "Asia/Istanbul": {diff: 2, abbr: "EET"},
    "Asia/Jakarta": {diff: 7, abbr: "WIT"},
    "Asia/Jerusalem": {diff: 2, abbr: "IST"},
    "Asia/Karachi": {diff: 5, abbr: "PKT"},
    "Asia/Kuala_Lumpur": {diff: 8, abbr: "MYT"},
    "Asia/Kuwait": {diff: 3, abbr: "AST"},
    "Asia/Macao": {diff: 8, abbr: "CST"},
    "Asia/Manila": {diff: 8, abbr: "PHT"},
    "Asia/Pyongyang": {diff: 9, abbr: "KST"},
    "Asia/Qatar": {diff: 3, abbr: "AST"},
    "Asia/Saigon": {diff: 7, abbr: "ICT"},
    "Asia/Seoul": {diff: 9, abbr: "KST", desc:"GMT+0900 South Korea Time"},
    "Asia/Shanghai": {diff: 8, abbr: "CST"},
    "Asia/Singapore": {diff: 8, abbr: "SGT"},
    "Asia/Taipei": {diff: 8, abbr: "CST"},
    "Asia/Tel_Aviv": {diff: 2, abbr: "IST"},
    "Asia/Tokyo": {diff: 9, abbr: "JST"},
    "Asia/Urumqi": {diff: 8, abbr: "CST"},
    "Atlantic/Bermuda": {diff: -4, abbr: "AST"},
    "Atlantic/Canary": {diff: 0, abbr: "WET"},
    "Atlantic/Cape_Verde": {diff: -1, abbr: "CVT"},
    "Atlantic/Reykjavik": {diff: 0, abbr: "GMT"},
    "Australia/Brisbane": {diff: 10, abbr: "EST"},
    "Australia/Canberra": {diff: 11, abbr: "EST"},
    "Australia/Darwin": {diff: 9.5, abbr: "CST"},
    "Australia/Melbourne": {diff: 11, abbr: "EST"},
    "Australia/North": {diff: 9.5, abbr: "CST"},
    "Australia/Perth": {diff: 8, abbr: "WST"},
    "Australia/Queensland": {diff: 10, abbr: "EST"},
    "Australia/South": {diff: 10.5, abbr: "CST"},
    "Australia/Sydney": {diff: 11, abbr: "EST"},
    "Australia/West": {diff: 8, abbr: "WST"},
    "Australia/Victoria": {diff: 11, abbr: "EST"},
    "Europe/Amsterdam": {diff: 1, abbr: "CET"},
    "Europe/Athens": {diff: 2, abbr: "EET"},
    "Europe/Belgrade": {diff: 1, abbr: "CET"},
    "Europe/Berlin": {diff: 1, abbr: "CET"},
    "Europe/Brussels": {diff: 1, abbr: "CET"},
    "Europe/Bucharest": {diff: 2, abbr: "EET"},
    "Europe/Budapest": {diff: 1, abbr: "CET"},
    "Europe/Copenhagen": {diff: 1, abbr: "CET"},
    "Europe/Dublin": {diff: 0, abbr: "GMT"},
    "Europe/Helsinki": {diff: 2, abbr: "EET"},
    "Europe/Istanbul": {diff: 2, abbr: "EET"},
    "Europe/Kaliningrad": {diff: 3, abbr: "FET"},
    "Europe/Kiev": {diff: 2, abbr: "EET"},
    "Europe/Lisbon": {diff: 0, abbr: "WET"},
    "Europe/London": {diff: 0, abbr: "GMT"},
    "Europe/Luxembourg": {diff: 1, abbr: "CET"},
    "Europe/Madrid": {diff: 1, abbr: "CET"},
    "Europe/Minsk": {diff: 3, abbr: "FET"},
    "Europe/Monaco": {diff: 1, abbr: "CET"},
    "Europe/Moscow": {diff: 4, abbr: "MSK"},
    "Europe/Oslo": {diff: 1, abbr: "CET"},
    "Europe/Paris": {diff: 1, abbr: "CET"},
    "Europe/Prague": {diff: 1, abbr: "CET"},
    "Europe/Rome": {diff: 1, abbr: "CET"},
    "Europe/San_Marino": {diff: 1, abbr: "CET"},
    "Europe/Sarajevo": {diff: 1, abbr: "CET"},
    "Europe/Stockholm": {diff: 1, abbr: "CET"},
    "Europe/Vatican": {diff: 1, abbr: "CET"},
    "Europe/Vienna": {diff: 1, abbr: "CET"},
    "Europe/Warsaw": {diff: 1, abbr: "CET"},
    "Europe/Zurich": {diff: 2, abbr: "EET"},
    "Indian/Christmas": {diff: 7, abbr: "CXT"},
    "Indian/Maldives": {diff: 5, abbr: "MVT"},
    "Pacific/Auckland": {diff: 12, abbr: "NZST"},
    "Pacific/Easter": {diff: -6, abbr: "EAST"},
    "Pacific/Fiji": {diff: 12, abbr: "FJT"},
    "Pacific/Guam": {diff: 10, abbr: "ChST"},
    "Pacific/Honolulu": {diff: -10, abbr: "HST"},
    "Pacific/Midway": {diff: -11, abbr: "SST"},
    "Pacific/Saipan": {diff: 10, abbr: "ChST"},
    "Pacific/Samoa": {diff: -11, abbr: "SST"},
    "Pacific/Tahiti": {diff: -10, abbr: "TAHT"},
    "UCT": {diff: 0, abbr: "UCT"},
    "SST": {diff: 0, abbr: "SST"},
    "GMT": {diff: 0, abbr: "GMT"},
    "Greenwich": {diff: 0, abbr: "GMT"},
    "US/Alaska": {diff: -9, abbr: "AKST"},
    "US/Eastern": {diff: -5, abbr: "EST"},
    "US/Central": {diff: -6, abbr: "CST"},
    "US/Mountain": {diff: -7, abbr: "MST"},
    "US/Pacific": {diff: -8, abbr: "PST"},
    "Universal": {diff: 0, abbr: "UTC"},
    "Zulu": {diff: 0, abbr: "UTC"},
    "Etc/GMT": {diff: 0, abbr: "Etc/GMT"},
    "Etc/GMT+0": {diff: 0, abbr: "Etc/GMT+0"},
    "Etc/GMT+1": {diff: -1, abbr: "Etc/GMT+1"},
    "Etc/GMT+10": {diff: -10, abbr: "Etc/GMT+10"},
    "Etc/GMT+11": {diff: -11, abbr: "Etc/GMT+11"},
    "Etc/GMT+12": {diff: -12, abbr: "Etc/GMT+12"},
    "Etc/GMT+2": {diff: -2, abbr: "Etc/GMT+2"},
    "Etc/GMT+3": {diff: -3, abbr: "Etc/GMT+3"},
    "Etc/GMT+4": {diff: -4, abbr: "Etc/GMT+4"},
    "Etc/GMT+5": {diff: -5, abbr: "Etc/GMT+5"},
    "Etc/GMT+6": {diff: -6, abbr: "Etc/GMT+6"},
    "Etc/GMT+7": {diff: -7, abbr: "Etc/GMT+7"},
    "Etc/GMT+8": {diff: -8, abbr: "Etc/GMT+8"},
    "Etc/GMT+9": {diff: -9, abbr: "Etc/GMT+9"},
    "Etc/GMT-0": {diff: 0, abbr: "Etc/GMT-0"},
    "Etc/GMT-1": {diff: 1, abbr: "Etc/GMT-1"},
    "Etc/GMT-10": {diff: 10, abbr: "Etc/GMT-10"},
    "Etc/GMT-11": {diff: 11, abbr: "Etc/GMT-11"},
    "Etc/GMT-12": {diff: 12, abbr: "Etc/GMT-12"},
    "Etc/GMT-13": {diff: 13, abbr: "Etc/GMT-13"},
    "Etc/GMT-14": {diff: 14, abbr: "Etc/GMT-14"},
    "Etc/GMT-2": {diff: 2, abbr: "Etc/GMT-2"},
    "Etc/GMT-3": {diff: 3, abbr: "Etc/GMT-3"},
    "Etc/GMT-4": {diff: 4, abbr: "Etc/GMT-4"},
    "Etc/GMT-5": {diff: 5, abbr: "Etc/GMT-5"},
    "Etc/GMT-6": {diff: 6, abbr: "Etc/GMT-6"},
    "Etc/GMT-7": {diff: 7, abbr: "Etc/GMT-7"},
    "Etc/GMT-8": {diff: 8, abbr: "Etc/GMT-8"},
    "Etc/GMT-9": {diff: 9, abbr: "Etc/GMT-9"},
    "Etc/GMT0": {diff: 0, abbr: "Etc/GMT0"},
    "Etc/Greenwich": {diff: 0, abbr: "GMT"}
};

module.exports = {
    getAllTimezone: function () {
        var i, ret = [];
        for (i in _timezone_data)
            ret.push(i);
        return ret;
    },
    getTimezoneDiff: function (zone) {
        return _timezone_data[zone].diff;
    },
    getTimezoneAbbr: function (zone) {
        return _timezone_data[zone].abbr;
    },
    getTimezoneDesc: function (zone) {
        if (_timezone_data[zone].desc) {
            return _timezone_data[zone].desc;
        } else {
            return null;
        }
    },
    isValidTimezone: function (zone) {
        return (_timezone_data[zone] === undefined) ? false : true;
    }
};


});
define('ripple/platform/tizen/2.0/tizen1_utils', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 self,
    utils = require('ripple/utils'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException');

self = module.exports = {
    _wac2_regexSanitize: function (regexString) {
        var escapePattern = /([^\\]|^)(%)/g, percentPattern = /\\%/g;
        return regexString.replace("^", "\\^")
                .replace("$", "\\$")
                .replace("(", "\\(")
                .replace(")", "\\)")
                .replace("<", "\\<")
                .replace("[", "\\[")
                .replace("{", "\\{")
                .replace(/\\([^%])/, "\\\\$1")    /* don't replace \\% */
                .replace("|", "\\|")
                .replace(">", "\\>")
                .replace(".", "\\.")
                .replace("*", "\\*")
                .replace("+", "\\+")
                .replace("?", "\\?")
                .replace(escapePattern, "$1.*")  /* replace % with .* */
                .replace(percentPattern, "%");   /* strip excape of % */
    },

    isValidDate: function (d) {
        if (Object.prototype.toString.call(d) !== "[object Date]")
            return false;
        return !isNaN(d.getTime());
    },
    isValidTZDate: function (d) {
        if (d &&  (d instanceof tizen.TZDate)) {
            return true;
        }
        return false;
    },
    isValidArray: function (a) {
        return (Object.prototype.toString.call(a) === "[object Array]");
    },

    matchOptionArrayString: function (src, attr, pattern) {
        /* src.obj[attr] is a StringArray */
        var _pattern, re, _stringMatch;
        _pattern = this._wac2_regexSanitize(pattern);
        re = new RegExp("^" + _pattern + "$", "i");

        _stringMatch = function (obj, index) {
            if (pattern.search(/^%*$/i) === 0)
                return true;
            if (obj[attr] === undefined || obj[attr] === null)
                return false;
            return obj[attr].some(function (f) {
                return f.search(re) !== -1;
            });
        };
        return utils.filter(src, _stringMatch);
    },

    matchAttributeBooleanFilter: function (src, attr, value) {
        // only support EXACTLY matchFlag
        var _booleanMatch, atr = attr.split(".");

        if (atr.length === 2) {
            _booleanMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                return (obj[atr[0]][atr[1]] === value);
            };
        } else {
            _booleanMatch = function (obj, index) {
                return (obj[attr] === value);
            };
        }

        return utils.filter(src, _booleanMatch);
    },

    matchAttributeArrayFilter: function (src, attr, matchFlag, value) {
        var _re, _arrayMatch, atr = attr.split("."), _existMatch;

        if (atr.length === 2) {
            _existMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                return (obj[atr[0]][atr[1]] !== undefined);
            };
        } else {
            _existMatch = function (obj, index) {
                return (obj[attr] !== undefined);
            };
        }

        if (value === undefined || value === null) {
            return utils.filter(src, _existMatch);
        }

        switch (matchFlag)
        {
        case "EXACTLY":
            _re = new RegExp("^" + value + "$");
            break;
        case "FULLSTRING":
            _re = new RegExp("^" + value + "$", "i");
            break;
        case "CONTAINS":
            _re = new RegExp(value, "i");
            break;
        case "STARTSWITH":
            _re = new RegExp("^" + value, "i");
            break;
        case "ENDSWITH":
            _re = new RegExp(value + "$", "i");
            break;
        case "EXISTS":
            return utils.filter(src, _existMatch);
        default:
            return [];
        }

        if (atr.length === 2) {
            _arrayMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                return (obj[atr[0]][atr[1]] && obj[atr[0]][atr[1]].some(function (o) {
                    return (o.search(_re) !== -1);
                }));
            };
        } else {
            _arrayMatch = function (obj, index) {
                return (obj[attr] && obj[attr].some(function (o) {
                    return (o.search(_re) !== -1);
                }));
            };
        }

        return utils.filter(src, _arrayMatch);
    },

    matchAttributeRangeFilter: function (src, attr, low, high) {
        var _rangeMatch, atr = attr.split(".");

        if (atr.length === 2) {
            _rangeMatch = function (obj, index) {
                var matched = true;

                if (!obj[atr[0]])
                    return false;

                if (low !== null && low !== undefined) {
                    matched = (obj[atr[0]][atr[1]] >= low);
                }
                if (matched && (high !== null && high !== undefined)) {
                    matched = (obj[atr[0]][atr[1]] <= high);
                }
                return matched;
            };
        } else {
            _rangeMatch = function (obj, index) {
                var matched = true;

                if (low !== null && low !== undefined) {
                    matched = (obj[attr] >= low);
                }
                if (matched && (high !== null && high !== undefined)) {
                    matched = (obj[attr] <= high);
                }
                return matched;
            };
        }
        return utils.filter(src, _rangeMatch);
    },

    matchAttributeFilter: function (src, attr, matchFlag, value) {
        var _re, _stringMatch, atr = attr.split("."),
            _existMatch;

        if (atr.length === 2) {
            _existMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                return (obj[atr[0]][atr[1]] !== undefined);
            };
        } else {
            _existMatch = function (obj, index) {
                return (obj[attr] !== undefined);
            };
        }

        if (value === undefined || value === null) {
            return utils.filter(src, _existMatch);
        }

        switch (matchFlag)
        {
        case "EXACTLY":
            _re = new RegExp("^" + value + "$");
            break;
        case "FULLSTRING":
            _re = new RegExp("^" + value + "$", "i");
            break;
        case "CONTAINS":
            _re = new RegExp(value, "i");
            break;
        case "STARTSWITH":
            _re = new RegExp("^" + value, "i");
            break;
        case "ENDSWITH":
            _re = new RegExp(value + "$", "i");
            break;
        case "EXISTS":
            return utils.filter(src, _existMatch);
        default:
            return [];
        }
        if (atr.length === 2) {
            _stringMatch = function (obj, index) {
                if (!obj[atr[0]])
                    return false;

                if (matchFlag === "EXACTLY") {
                    return (obj[atr[0]][atr[1]] === value);
                } else if (typeof obj[atr[0]][atr[1]] !== 'string') {
                    return false;
                }

                return (obj[atr[0]][atr[1]].search(_re) !== -1);
            };
        } else {
            _stringMatch = function (obj, index) {
                if (matchFlag === "EXACTLY") {
                    return (obj[attr] === value);
                } else if (typeof obj[attr] !== 'string') {
                    return false;
                }

                return (obj[attr].search(_re) !== -1);
            };
        }
        return utils.filter(src, _stringMatch);
    },

    matchOptionString: function (src, attr, pattern) {
        /* src.obj[attr] is a string */
        var _stringMatch, _pattern, _re;
        _pattern = this._wac2_regexSanitize(pattern);
        _re = new RegExp("^" + _pattern + "$", "mi");

        _stringMatch = function (obj, index) {
            return (obj[attr].search(_re) !== -1);
        };
        return utils.filter(src, _stringMatch);
    },

    matchOptionDate: function (src, attr, filterStart, filterEnd) {
        var _dateMatch;
        _dateMatch = function (obj, index) {
            var matched = true, valueDate = obj[attr];

            if (filterStart !== undefined && filterStart !== null) {
                matched = (valueDate.getTime() >= filterStart.getTime());
            }
            if (matched && (filterEnd !== undefined && filterEnd !== null)) {
                matched = (valueDate.getTime() <= filterEnd.getTime());
            }
            return matched;
        };
        return utils.filter(src, _dateMatch);
    },

    matchOptionShortArray: function (src, attr, filterArray) {
        /* src.obj[attr] is a short, filterArray is an array
           i.e. find status is [CONFRIMED or TENTATIVE] */
        var arraySome = function (obj, index) {
            return filterArray.some(function (f) {
                return f === obj[attr];
            });
        };
        return utils.filter(src, arraySome);
    },

    validateArgumentType: function (arg, argType, errorObj) {
        var invalidArg = false;

        switch (argType) {
        case "array":
            if (!arg instanceof Array) {
                invalidArg = true;
            }
            break;
        case "date":
            if (!arg instanceof Date) {
                invalidArg = true;
            }
            break;
        case "integer":
            if (typeof Number(arg) !== "number" || Number(arg) !== Math.floor(arg)) {
                invalidArg = true;
            }
            break;
        default:
            if (typeof arg !== argType) {
                invalidArg = true;
            }
            break;
        }

        if (invalidArg) {
            throw errorObj;
        }
    },

    validateCallbackType: function (successCallback, errorCallback) {
        if (successCallback) {
            this.validateArgumentType(successCallback, "function",
                new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
        }
        if (errorCallback) {
            this.validateArgumentType(errorCallback, "function",
                new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
        }
    },

    validateEqualArrays: function (arrayOne, arrayTwo) {
        var isEqual = false, i;

        if (Object.prototype.toString.call(arrayTwo) === "[object Array]" &&
            Object.prototype.toString.call(arrayTwo) === "[object Array]" &&
            arrayOne.length === arrayTwo.length) {
            isEqual = true;
            for (i in arrayOne) {
                if (arrayOne[i] !== arrayTwo[i]) {
                    isEqual = false;
                    break;
                }
            }
        }
        return isEqual;
    },

    validateTypeMismatch: function (onSuccess, onError, name, callback) {

        if (onSuccess === undefined || onSuccess === null) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }
        this.validateArgumentType(onSuccess, "function",
                                  new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
        if (onError !== null && onError !== undefined) {
            this.validateArgumentType(onError, "function",
                                      new WebAPIException(errorcode.TYPE_MISMATCH_ERR));
        }

        return callback && callback();
    },

    isEmptyObject: function (obj) {
        var prop;

        for (prop in obj) {
            return false;
        }
        return true;
    },

    arrayComposite: function (mode, arrayA, arrayB) {
        var combinedArray = arrayA.concat(arrayB),
            intersectionArray = arrayA.filter(function (value) {
                if (utils.arrayContains(arrayB, value)) {
                    return true;
                }

                return false;
            });

        switch (mode) {
        case "AND":
        case "INTERSECTION":
            return intersectionArray;
        case "OR":
        case "UNION":
            return intersectionArray.concat(combinedArray.filter(function (value) {
                if (utils.arrayContains(intersectionArray, value)) {
                    return false;
                }

                return true;
            }));
        default:
            return undefined;
        }
    },

    isEqual: function (srcObj, aimObj) {
        var i;

        if (typeof srcObj !== typeof aimObj) {
            return false;
        }

        if (srcObj === null || srcObj === undefined || typeof srcObj === 'number' ||
            typeof srcObj === 'string' || typeof srcObj === 'boolean') {
            return srcObj === aimObj;
        }

        for (i in srcObj) {
            if (!aimObj.hasOwnProperty(i) || !self.isEqual(srcObj[i], aimObj[i])) {
                return false;
            }
        }

        return true;
    },

    query: function (objects, filter, sortMode, count, offset) {
        function isCompositeFilter(filter) {
            return (filter.type) ? true : false;
        }

        function isAttributeFilter(filter) {
            return (filter.matchFlag) ? true : false;
        }

        function getValue(obj, key) {
            var keys = key.split("."),
                value = obj[keys[0]],
                i;

            for (i = 1; i < keys.length; i++) {
                if (value[keys[i]]) {
                    value = value[keys[i]];
                }
            }

            return value;
        }

        function _filter(objects, filter) {
            var i, results, eachResult, filterFunc;

            if (isCompositeFilter(filter)) {
                for (i in filter.filters) {
                    eachResult = _filter(objects, filter.filters[i]);
                    results = (results === undefined) ? eachResult : self.arrayComposite(filter.type, results, eachResult);
                }
                return results;
            }

            if (isAttributeFilter(filter)) {
                for (i in objects) {
                    if (filter.attributeName in objects[i])
                        break;
                }
                filterFunc = self.isValidArray(objects[i][filter.attributeName]) ? self.matchAttributeArrayFilter : self.matchAttributeFilter;
                results = filterFunc(objects, filter.attributeName, filter.matchFlag, filter.matchValue);
            } else {
                results = self.matchAttributeRangeFilter(objects, filter.attributeName, filter.initialValue, filter.endValue);
            }

            return results;
        }

        function _sort(objects, sortMode) {
            objects.sort(function (a, b) {
                return (sortMode.order === "ASC") ?
                    (getValue(a, sortMode.attributeName) < getValue(b, sortMode.attributeName) ? -1 : 1):
                    (getValue(a, sortMode.attributeName) > getValue(b, sortMode.attributeName) ? -1 : 1);
            });

            return objects;
        }

        var res = objects;

        if (filter) {
            res = _filter(res, filter);
        }

        if (sortMode) {
            _sort(res, sortMode);
        }

        if (offset || count) {
            offset = (offset > 0) ? offset : 0;
            res = (count > 0) ? res.slice(offset, offset + count) : res.slice(offset);
        }

        return res;
    },

    copyString: function (str) {
        var newStr, charConvert = [], i;

        if (typeof str !== 'string') {
            return str;
        }
        for (i = 0; i < str.length; i++) {
            charConvert[i] = str.charAt(i);
        }
        newStr = charConvert.join("");

        return newStr;
    },

    copy: function (obj) {
        var i,
            newObj = jQuery.isArray(obj) ? [] : {};

        if (typeof obj === 'number' ||
            typeof obj === 'string' ||
            typeof obj === 'boolean' ||
            obj === null ||
            obj === undefined) {
            return obj;
        }

        if (obj instanceof Date) {
            return new Date(obj);
        }

        if (obj instanceof RegExp) {
            return new RegExp(obj);
        }

        for (i in obj) {
            if (obj.hasOwnProperty(i)) {
                if (obj.__lookupGetter__(i)) {
                    newObj.__defineGetter__(i, (function (key) {
                        return function () {
                            return self.copy(obj[key]);
                        };
                    }(i)));
                }
                else {
                    newObj[i] = self.copy(obj[i]);
                }
            }
        }

        return newObj;
    }
};

});
define('ripple/platform/tizen/2.0/touchEvent', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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 emulatorBridge = require('ripple/emulatorBridge'),
    event = require('ripple/event'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    Touch,
    TouchList,
    TouchEvent,
    _touchCanvasElements = [],
    _dataEnlargeRatio = 4,
    _self;

function _isValidTouch(touches) {
    var touche, _touches = [], i;
    if (!touches) {
        return false;
    }
    if (!tizen1_utils.isValidArray(touches)) {
        _touches = [touches];
    }

    for (i = 0; i < _touches.length; i++) {
        touche = _touches[i];
        if ((touche !== undefined) &&
            ((typeof touche !== "object") ||
            (typeof touche.target !== "object") ||
            (touche.identifier !== undefined) && (typeof touche.identifier !== "number") ||
            (touche.screenX !== undefined) && (typeof touche.screenX !== "number") ||
            (touche.screenY !== undefined) && (typeof touche.screenY !== "number") ||
            (touche.clientX !== undefined) && (typeof touche.clientX !== "number") ||
            (touche.clientY !== undefined) && (typeof touche.clientY !== "number") ||
            (touche.pageX !== undefined) && (typeof touche.pageX !== "number") ||
            (touche.pageY !== undefined) && (typeof touche.pageY !== "number")))
            return false;
    }
    return true;
}

function _dispatchAllEvents(event) {
    _touchCanvasElements.forEach(function (value) {
        if (value !== undefined) {
            value.dispatchEvent(event);
        }
    });
}

function _touchMove(event) {
    var data = event.data,
        touches = [],
        removedTouches = [],
        touchList,
        simulatedEvent,
        dataId,
        ids = [],
        intervalId,
        currentIndex,
        item = {};

    if (_touchCanvasElements.length === 0)
        return;

    for (dataId in data) {
        if (!data[dataId].length || data[dataId].length === 0)
            return;

        ids.push(dataId);
        item = data[dataId][0];
        touches.push(new Touch(item.target, dataId, item.pageX * _dataEnlargeRatio, item.pageY * _dataEnlargeRatio, item.screenX * _dataEnlargeRatio,
                               item.screenY * _dataEnlargeRatio, item.offsetX * _dataEnlargeRatio, item.offsetY * _dataEnlargeRatio));
    }

    // touch start
    touchList = new TouchList(touches);
    simulatedEvent = new TouchEvent("touchstart", true, true, touchList, touchList, touchList, event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
    _dispatchAllEvents(simulatedEvent);
    currentIndex = 0;

    // touch move and touch end
    intervalId = setInterval(function () {
        touches = [];
        removedTouches = [];

        ids.forEach(function (id) {
            var points = data[id],
                touchItem, removedItem;

            if (currentIndex < points.length) {
                touchItem = points[currentIndex];
            } else {
                removedItem = points[points.length - 1];
            }

            if (touchItem)
                touches.push(new Touch(touchItem.target, id, touchItem.pageX * _dataEnlargeRatio, touchItem.pageY * _dataEnlargeRatio, touchItem.screenX * _dataEnlargeRatio,
                                       touchItem.screenY * _dataEnlargeRatio, touchItem.offsetX * _dataEnlargeRatio, touchItem.offsetY * _dataEnlargeRatio));
            if (removedItem)
                removedTouches.push(new Touch(removedItem.target, id, removedItem.pageX * _dataEnlargeRatio, removedItem.pageY * _dataEnlargeRatio, removedItem.screenX * _dataEnlargeRatio,
                                    removedItem.screenY * _dataEnlargeRatio, removedItem.offsetX * _dataEnlargeRatio, removedItem.offsetY * _dataEnlargeRatio));
        });

        if (touches.length > 0) {
            simulatedEvent = new TouchEvent("touchmove", true, true, new TouchList(touches), new TouchList(touches), new TouchList(touches),
                event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
            _dispatchAllEvents(simulatedEvent);
        } else {
            clearInterval(intervalId);
        }

        if (removedTouches.length > 0) {
            simulatedEvent = new TouchEvent("touchend", true, true, new TouchList(removedTouches), new TouchList(removedTouches), new TouchList(removedTouches),
                event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
            _dispatchAllEvents(simulatedEvent);
        }
        currentIndex++;
    }, 50);
}

function _touchCancel(event) {
    var mousedownEvent = event.touchEvent,
        simulatedEvent;

    simulatedEvent = new TouchEvent("touchcancel", true, true, new TouchList([]), new TouchList([]), new TouchList([]),
        event.altKey, event.metaKey, event.ctrlKey, event.shiftKey);
    _dispatchAllEvents(simulatedEvent);
}

function _initialize() {
    event.on("touchCancel", _touchCancel);
    event.on("touchEvent", _touchMove);
}

Touch = function (target, identifier, pageX, pageY, screenX, screenY, clientX, clientY) {
    var _identifier = Number(identifier) || 0,
        _screenX = Number(screenX) || 0,
        _screenY = Number(screenY) || 0,
        _clientX = Number(clientX) || 0,
        _clientY = Number(clientY) || 0,
        _pageX = Number(pageX) || 0,
        _pageY = Number(pageY) || 0;

    this.__defineGetter__("identifier", function () {
        return _identifier;
    });
    this.__defineGetter__("target", function () {
        return target;
    });
    this.__defineGetter__("screenX", function () {
        return _screenX;
    });
    this.__defineGetter__("screenY", function () {
        return _screenY;
    });
    this.__defineGetter__("clientX", function () {
        return _clientX;
    });
    this.__defineGetter__("clientY", function () {
        return _clientY;
    });
    this.__defineGetter__("pageX", function () {
        return _pageX;
    });
    this.__defineGetter__("pageY", function () {
        return _pageY;
    });
};

TouchList = function (touches) {
    var _touches = _isValidTouch(touches) ? tizen1_utils.copy(touches) : [],
        i, _self;

    _self = {
        item : function (index) {
            if (typeof index !== "number") {
                return null;
            }
            if (index.toString().indexOf(".") !== -1) {
                return null;
            }
            if (/^\\d+$/.test(index) || index >= _touches.length) {
                return null;
            }
            if (!_touches) {
                return null;
            }
            return _touches[index];
        },

        identifiedTouch : function (identifier) {
            if (typeof identifier !== "number") {
                return null;
            }
            if (!_touches) {
                return null;
            }
            for (var i in _touches) {
                if (_touches[i].identifier === identifier) {
                    return _touches[i];
                }
            }
            return null;
        }
    };

    for (i = 0; i < _touches.length; i++) {
        _self.__defineGetter__(i, (function (index) {
            return function () {
                return _touches[index];
            };
        }(i)));
    }

    _self.__defineGetter__("length", function () {
        return _touches.length;
    });

    return _self;
};

TouchEvent = function (type, canBubble, cancelable, touches, targetTouches, changedTouches, altKey, metaKey, ctrlKey, shiftKey) {
    var touchEvent = emulatorBridge.document().createEvent("UIEvents");
    touchEvent.initUIEvent(type, canBubble, cancelable, emulatorBridge.window(), 1);

    touchEvent.__defineGetter__("touches", function () {
        return touches;
    });
    touchEvent.__defineGetter__("targetTouches", function () {
        return targetTouches;
    });
    touchEvent.__defineGetter__("changedTouches", function () {
        return changedTouches;
    });
    touchEvent.__defineGetter__("altKey", function () {
        return altKey;
    });
    touchEvent.__defineGetter__("metaKey", function () {
        return metaKey;
    });
    touchEvent.__defineGetter__("ctrlKey", function () {
        return ctrlKey;
    });
    touchEvent.__defineGetter__("shiftKey", function () {
        return shiftKey;
    });
    return touchEvent;
};

_self = {
    mask: function (frame) {
        frame.addEventListener("DOMContentLoaded", function () {
            /*
            var widgetDocument = frame.contentDocument,
                getElementByIdOri = widgetDocument.getElementById;

            widgetDocument.getElementById = function () {
                var element, addEventListenerOri;

                element = getElementByIdOri.apply(widgetDocument, Array.prototype.slice.call(arguments));

                if (element) {
                    addEventListenerOri = element.addEventListener;
                    element.addEventListener = function (event, callback, useCapture) {
                        if (event === "touchstart") {
                            _touchCanvasElements.push(element);
                        }
                        addEventListenerOri.apply(element, arguments);
                    };
                }
                return element;
            };

            widgetDocument.createTouch = function (view, target, identifier, pageX, pageY, screenX, screenY) {
                return new Touch(view, target, identifier, pageX, pageY, screenX, screenY);
            };

            widgetDocument.createTouchList = function (pattern) {
                if (arguments.length !== 1) {
                    return null;
                }
                return new TouchList(pattern);
            };
            */
        });
    }
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tizen/2.0/typecast', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 typedef = require('ripple/platform/tizen/2.0/typedef'),
    errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    TypeCoerce = require('ripple/platform/tizen/2.0/typecoerce'),
    _self = {};

function _cast(pattern, obj, isDuplicate) {
    var tc, tcFunc;

    if (pattern === null)
        return;

    tc = new TypeCoerce(pattern);
    tcFunc = isDuplicate ? tc.copy : tc.cast;

    if ((obj = tcFunc(obj)) === null) {
        throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
    }

    return obj;
}

function _castType(pattern) {
    /*
     * Type cast for each known type. The function name is the exact name of the
     * corresponding type.
     *
     * obj
     *    Variable to be casted
     *
     * aux
     *    Auxiliary descriptor of obj. It can be any one or combination of below
     *    strings, or ignored in most cases.
     *
     *    "?"     Nullable types
     *    "[]"    Array
     *    "+"     Deep copy
     *
     * Return
     *    Casted or duplicated object.
     */

    return function (obj, aux) {
        var type, isNullable, isDuplicate;

        aux = aux ? String(aux) : "";
        type = (aux.indexOf("[]") !== -1) ? [pattern] : pattern;
        isNullable = (aux.indexOf("?") !== -1);
        isDuplicate = (aux.indexOf("+") !== -1);

        if (isNullable && ((obj === null) || (obj === undefined))) {
            return obj;
        }

        return _cast(type, obj, isDuplicate);
    };
}

function _castConstructor(name) {
    var constructors, hook, vtc, isOverloaded, castConstructor;

    /*
     * Type cast for constructor. The function name is the exact name of the
     * object type.
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     */

    function castUnique(argv) {
        _cast(constructors, argv, false);
    }

    /*
     * Type cast for overloaded constructors. The function name is the exact
     * name of the object type.
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     *
     * scope
     *    'this' of the original constructor.
     *
     * voc
     *    Array of overloaded constructors callback
     */

    function castOverload(argv, scope, voc) {
        var iOverload;

        if (!vtc) {
            vtc = [];
            constructors.forEach(function (c) {
                vtc.push((c === null) ? null : new TypeCoerce(c));
            });
        }

        vtc.some(function (tc, index) {
            if (tc && (tc.cast(argv) === null))
                return false;

            iOverload = index;
            return true;
        });

        if (iOverload === undefined) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }

        return (voc && voc[iOverload].apply(scope, argv));
    }

    constructors = typedef.constructor[name];

    if (name in _self) {
        hook = _self[name];
    }

    isOverloaded = (Object.prototype.toString.call(constructors) ===
            "[object Array]");
    castConstructor = isOverloaded ? castOverload : castUnique;

    return function (argv, scope) {
        if (Object.prototype.toString.call(argv) !== "[object Arguments]") {
            return (hook && hook.apply(this, arguments));
        }

        if (!(scope instanceof argv.callee)) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR, null, "TypeError");
        }

        castConstructor.apply(this, arguments);
    };
}

function _castInterface(name) {
    var interface, hook;

    interface = typedef.interface[name];

    if (name in _self) {
        hook = _self[name];
    }

    /*
     * Type cast for each known method of interface. The function name is the
     * exact name of the corresponding interface.
     *
     * method
     *    String of method name
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     *
     * isDuplicate
     *    A boolean value to indicate whether arguments will be copied or not.
     */

    return function (method, argv, isDuplicate) {
        if ((typeof method !== "string") || (typeof argv !== "object")) {
            return (hook && hook.apply(this, arguments));
        }

        _cast(interface[method], argv, isDuplicate);
    };
}

(function () {
    var i;

    for (i in typedef) {
        _self[i] = _castType(typedef[i]);
    }

    for (i in typedef.constructor) {
        _self[i] = _castConstructor(i);
        typedef[i]._constructor = i;
    }

    for (i in typedef.interface) {
        _self[i] = _castInterface(i);
    }
}());

module.exports = _self;

});
define('ripple/platform/tizen/2.0/typecoerce', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tizen/2.0/typedef'),
    _MAX_INT_BITS = 53,
    _MAX_INT = Math.pow(2, _MAX_INT_BITS) - 1,
    _self;

_self = function (pattern) {
    var typeCoerce, typeOfPattern;

    // private
    function getExtendedType(val) {
        var type = Object.prototype.toString.call(val), attr;

        switch (type) {
        case "[object Array]":
            if ((typeof val[0] === "string") && (val[0].length > 0)) {
                type = "enum";
            } else {
                type = "Union";
            }
            return type;

        case "[object Object]":
            if ("_dictionary" in val) {
                return "dictionary";
            }

            type = "Object";

            for (attr in val) {
                if (attr === "0") {
                    type = "Arguments";
                } else if (val[attr] === "Callback") {
                    type = "Callback";
                }
                break;
            }

            return type;
        }

        switch (val) {
        case "Callback":
            type = "Function";
            break;

        case "TZDate":
        case "any":
        case "byte":
        case "float":
        case "long":
        case "long long":
        case "octet":
        case "short":
        case "unsigned long":
        case "unsigned long long":
        case "unsigned short":
            type = val;
            break;

        case "double":
            type = "float";
            break;

        default:    // Derivative type name: e.g., "AbstractFilter"
            type = "";
            break;
        }

        return type;
    }

    function getType(val, isPattern) {
        var type = Object.prototype.toString.call(val);

        switch (type) {
        case "[object Array]":
            type = (isPattern && (val.length > 1)) ? getExtendedType(val) :
                    "Array";
            break;

        case "[object Arguments]":
            type = "Arguments";
            break;

        case "[object Boolean]":
            type = "boolean";
            break;

        case "[object Date]":
            type = "Date";
            break;

        case "[object Function]":
            type = "Function";
            break;

        case "[object Number]":
            type = "Number";
            break;

        case "[object Object]":
            type = isPattern ? getExtendedType(val) : "Object";
            break;

        case "[object String]":
            type = (isPattern && !!val) ? getExtendedType(val) : "DOMString";
            break;
        }

        return type;
    }

    function isConstructed(obj) {
        if (!("_constructor" in pattern))
            return true;

        if (obj instanceof window.tizen[pattern._constructor])
            return true;

        if ("_derived" in pattern)
            return true;

        return false;
    }

    function toInteger(x) {
        return (x < 0) ? Math.ceil(x) : Math.floor(x);
    }

    function isBitsOverflowed(bits) {
        return (bits >= _MAX_INT_BITS);
    }

    function toJsInt(x, isUnsigned) {
        var min, max;

        min = isUnsigned ? 0 : -_MAX_INT;
        max = _MAX_INT;

        if ((x < min) || (x > max))
            return null;

        return toInteger(x);
    }

    function modulo(a, b) {
        return (a - Math.floor(a / b) * b);
    }

    function toInt(x, bits) {
        var p;

        x = Number(x);

        if (isNaN(x) || !isFinite(x))
            return null;

        if (isBitsOverflowed(bits))
            return toJsInt(x, false);

        p = Math.pow(2, bits);
        x = modulo(toInteger(x), p);

        return (x >= Math.pow(2, bits - 1)) ? (x - p) : x;
    }

    function toUInt(x, bits) {
        x = Number(x);

        if (isNaN(x) || !isFinite(x))
            return null;

        if (isBitsOverflowed(bits))
            return toJsInt(x, true);

        return modulo(toInteger(x), Math.pow(2, bits));
    }

    function toInt8(x) {
        return toInt(x, 8);
    }

    function toInt16(x) {
        return toInt(x, 16);
    }

    function toInt32(x) {
        return toInt(x, 32);
    }

    function toInt64(x) {
        return toInt(x, 64);
    }

    function toUInt8(x) {
        return toUInt(x, 8);
    }

    function toUInt16(x) {
        return toUInt(x, 16);
    }

    function toUInt32(x) {
        return toUInt(x, 32);
    }

    function toUInt64(x) {
        return toUInt(x, 64);
    }

    // public
    function cast(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Arguments": function () {
                var i, isNullable, ret;

                for (i in pattern) {
                    if (i === "_optional")
                        continue;

                    isNullable = !!(pattern._optional && pattern._optional[i]);

                    if (i > obj.length - 1) {
                        if (!isNullable) {
                            return null;
                        }
                        break;
                    }

                    if (!isNullable || (obj[i] !== null)) {
                        ret = _self(pattern[i]).cast(obj[i]);
                        if (ret === null) {
                            return null;
                        }
                        obj[i] = ret;
                    }
                }

                return obj;
            },

            "Array": function () {
                var elementType, i, ret;

                if (typeOfObj !== typeOfPattern) {
                    return null;
                }

                elementType = _self(pattern[0]);
                for (i in obj) {
                    ret = elementType.cast(obj[i]);
                    if (ret === null) {
                        return null;
                    }
                    obj[i] = ret;
                }

                return obj;
            },

            "Callback": function () {
                var attr;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        obj[attr] = _self(pattern[attr]).cast(obj[attr]);
                        if (obj[attr] === null) {
                            return null;
                        }
                    }
                }

                return obj;
            },

            "DOMString": function () {
                switch (typeOfObj) {
                case "DOMString":
                case "Date":
                case "Number":
                case "boolean":
                    obj = String(obj);
                    break;

                default:
                    if ((obj === null) || (obj === undefined)) {
                        obj = String(obj);
                    } else {
                        obj = null;
                    }
                    break;
                }

                return obj;
            },

            "Date": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "Function": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "Object": function () {
                var ret, attr, i;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return null;
                    }
                    if (!("_derived" in pattern)) {
                        return null;
                    }
                }

                if (!isConstructed(obj)) {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            ret = _self(pattern._derived[i]).cast(obj);
                            if (ret !== null)
                                break;
                        }
                        if (ret === null) {
                            if ("_constructor" in pattern)
                                break;

                            return null;
                        }
                        break;

                    default:
                        if (!pattern._optional || !pattern._optional[attr] ||
                                (obj[attr] !== undefined) &&
                                (obj[attr] !== null)) {
                            ret = _self(pattern[attr]).cast(obj[attr]);
                            if (ret === null) {
                                return null;
                            }
                            obj[attr] = ret;
                        }
                        break;
                    }
                }

                return obj;
            },

            "TZDate": function () {
                if (typeOfObj !== "Object") {
                    return null;
                }
                return (obj instanceof window.tizen.TZDate) ? obj : null;
            },

            "Union": function () {
                var ret, i;

                for (i in pattern) {
                    ret = _self(pattern[i]).cast(obj);
                    if (ret !== null)
                        break;
                }

                return ret;
            },

            "any": function () {
                return obj;
            },

            "boolean": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "byte": function () {
                return toInt8(obj);
            },

            "dictionary": function () {
                var attr, ret;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            ret = _self(pattern._dictionary).cast(obj);
                            if (ret === null) {
                                return null;
                            }
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            ret = _self(pattern[attr]).cast(obj[attr]);
                            if (ret === null) {
                                return null;
                            }
                            obj[attr] = ret;
                        }
                        break;
                    }
                }

                return obj;
            },

            "enum": function () {
                var i;

                obj = String(obj).trim();
                for (i in pattern) {
                    if (obj === pattern[i]) {
                        return obj;
                    }
                }

                return null;
            },

            "float": function () {
                var f = parseFloat(obj, 10);

                return (isNaN(f) ? null : f);
            },

            "long": function () {
                return toInt32(obj);
            },

            "long long": function () {
                return toInt64(obj);
            },

            "octet": function () {
                return toUInt8(obj);
            },

            "short": function () {
                return toInt16(obj);
            },

            "unsigned long": function () {
                return toUInt32(obj);
            },

            "unsigned long long": function () {
                return toUInt64(obj);
            },

            "unsigned short": function () {
                return toUInt16(obj);
            },

            "": function () {
                return _self(t[pattern]).cast(obj);
            }
        };

        return typeMap[typeOfPattern]();
    }

    function copy(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Arguments": function () {
                var i, isNullable, ret = [];

                for (i in pattern) {
                    if (i === "_optional")
                        continue;

                    isNullable = !!(pattern._optional && pattern._optional[i]);

                    if (i > obj.length - 1) {
                        if (!isNullable) {
                            return null;
                        }
                        break;
                    }

                    if (!isNullable || (obj[i] !== null)) {
                        ret[i] = _self(pattern[i]).copy(obj[i]);
                        if (ret[i] === null) {
                            return null;
                        }
                    }
                }

                for (i in ret) {
                    obj[i] = ret[i];
                }

                return obj;
            },

            "Array": function () {
                var arr = [], elementType, i;

                if (typeOfObj !== typeOfPattern) {
                    return null;
                }

                elementType = _self(pattern[0]);
                for (i in obj) {
                    if (obj[i] !== undefined) {
                        arr[i] = elementType.copy(obj[i]);
                        if (arr[i] === null)
                            return null;
                    }
                }

                return arr;
            },

            "Callback": function () {
                var ret = {}, attr;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                        if (ret[attr] === null) {
                            return null;
                        }
                    }
                }

                return ret;
            },

            "Object": function () {
                var ret = {}, attr, i, derived;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return null;
                    }
                    if (!("_derived" in pattern)) {
                        return null;
                    }
                }

                if (!isConstructed(obj)) {
                    return null;
                }
                if ("_constructor" in pattern) {
                    ret.__proto__ = window.tizen[pattern._constructor].prototype;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            derived = _self(pattern._derived[i]).copy(obj);
                            if (derived !== null)
                                break;
                        }
                        if (derived === null) {
                            if ("_constructor" in pattern)
                                break;

                            return null;
                        }
                        for (attr in derived) {
                            ret[attr] = derived[attr];
                        }
                        break;

                    default:
                        if (!pattern._optional || !pattern._optional[attr] ||
                                (obj[attr] !== undefined) &&
                                (obj[attr] !== null)) {
                            ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                            if (ret[attr] === null) {
                                return null;
                            }
                        }
                        break;
                    }
                }

                return ret;
            },

            "Union": function () {
                var ret, i;

                for (i in pattern) {
                    ret = _self(pattern[i]).copy(obj);
                    if (ret !== null)
                        break;
                }

                return ret;
            },

            "dictionary": function () {
                var ret = {}, attr, base, i;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            base = _self(pattern._dictionary).copy(obj);
                            if (base === null) {
                                return null;
                            }
                            for (i in base) {
                                ret[i] = base[i];
                            }
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                            if (ret[attr] === null) {
                                return null;
                            }
                        }
                        break;
                    }
                }

                return ret;
            },

            "": function () {
                return _self(t[pattern]).copy(obj);
            }
        };

        return (typeOfPattern in typeMap) ? typeMap[typeOfPattern]() :
                cast(obj);
    }

    function match(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Array": function () {
                var elementType, i;

                if (typeOfObj !== typeOfPattern)
                    return false;

                elementType = _self(pattern[0]);
                for (i in obj) {
                    if (!elementType.match(obj[i])) {
                        return false;
                    }
                }

                return true;
            },

            "Callback": function () {
                var attr, isMatched = true;

                if (typeOfObj !== "Object") {
                    return false;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        isMatched = _self(pattern[attr]).match(obj[attr]);
                        if (!isMatched) {
                            break;
                        }
                    }
                }

                return isMatched;
            },

            "DOMString": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Date": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Function": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Object": function () {
                var attr, isMatched = false, i;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return false;
                    }
                    if (!("_derived" in pattern)) {
                        return false;
                    }
                    return false;
                }

                if (!isConstructed(obj)) {
                    return false;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            isMatched = _self(pattern._derived[i]).match(obj);
                            if (isMatched)
                                break;
                        }
                        break;

                    default:
                        if (pattern._optional && pattern._optional[attr]) {
                            isMatched = ((obj[attr] === null) ||
                                    (obj[attr] === undefined) ||
                                    _self(pattern[attr]).match(obj[attr]));
                        } else {
                            isMatched = (obj[attr] !== undefined) &&
                                    _self(pattern[attr]).match(obj[attr]);
                        }
                        break;
                    }

                    if (!isMatched)
                        break;
                }

                /*// Check if verbose attributes are present
                if (isMatched) {
                    for (attr in obj) {
                        if (pattern[attr] === undefined) {
                            isMatched = false;
                            break;
                        }
                    }
                }*/

                return isMatched;
            },

            "Union": function () {
                var isMatched, i;

                for (i in pattern) {
                    isMatched = _self(pattern[i]).match(obj);
                    if (isMatched)
                        break;
                }

                return isMatched;
            },

            "any": function () {
                return true;
            },

            "boolean": function () {
                return (typeOfObj === typeOfPattern);
            },

            "byte": function () {
                return (obj === toInt8(obj));
            },

            "dictionary": function () {
                var attr, isMatched = true;

                if (typeOfObj !== "Object") {
                    return false;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            isMatched = _self(pattern._dictionary).match(obj);
                            if (!isMatched)
                                break;
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            isMatched = _self(pattern[attr]).match(obj[attr]);
                            if (!isMatched)
                                break;
                        }
                        break;
                    }
                }

                return isMatched;
            },

            "enum": function () {
                for (var i in pattern) {
                    if (obj === pattern[i]) {
                        return true;
                    }
                }

                return false;
            },

            "float": function () {
                return (typeOfObj === "Number");
            },

            "long": function () {
                return (obj === toInt32(obj));
            },

            "long long": function () {
                return (obj === toInt64(obj));
            },

            "octet": function () {
                return (obj === toUInt8(obj));
            },

            "short": function () {
                return (obj === toInt16(obj));
            },

            "unsigned long": function () {
                return (obj === toUInt32(obj));
            },

            "unsigned long long": function () {
                return (obj === toUInt64(obj));
            },

            "unsigned short": function () {
                return (obj === toUInt16(obj));
            },

            "Arguments": function () {
                return true;
            },

            "": function () {
                return _self(t[pattern]).match(obj);
            }
        };

        return typeMap[typeOfPattern]();
    }

    typeOfPattern = getType(pattern, true);

    typeCoerce = {
        cast:  cast,
        copy:  copy,
        match: match
    };

    return typeCoerce;
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/typedef', function (require, exports, module) {
/*
 *  Copyright 2013 Intel Corporation.
 *
 * 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 _t, _c, _i;

/*
 * Primitive type definition
 */

_t = {
    // Basic
    Callback:                           "Callback",
    DOMString:                          "",
    Date:                               new Date(),
    Function:                           function () {},
    TZDate:                             "TZDate",
    any:                                "any",
    boolean:                            false,
    byte:                               "byte",
    double:                             "double",
    float:                              "float",
    long:                               "long",
    octet:                              "octet",
    short:                              "short",
    long_long:                          "long long",
    unsigned_long:                      "unsigned long",
    unsigned_long_long:                 "unsigned long long",
    unsigned_short:                     "unsigned short",

    // Common
    FilterMatchFlag:                    ["EXACTLY", "FULLSTRING", "CONTAINS",
                                         "STARTSWITH", "ENDSWITH", "EXISTS"],
    SortModeOrder:                      ["ASC", "DESC"],
    CompositeFilterType:                ["UNION", "INTERSECTION"],

    // Bluetooth
    BluetoothSocketState:               ["CLOSED", "OPEN"],
    BluetoothProfileType:               ["HEALTH", "HEALTH"],
    BluetoothHealthChannelType:         ["RELIABLE", "STREAMING"],

    // Calendar
    CalendarType:                       ["EVENT", "TASK"],
    CalendarTextFormat:                 ["ICALENDAR_20", "VCALENDAR_10"],
    AlarmMethod:                        ["SOUND", "DISPLAY"],
    RecurrenceRuleFrequency:            ["DAILY", "WEEKLY", "MONTHLY",
                                         "YEARLY"],
    ByDayValue:                         ["MO", "TU", "WE", "TH", "FR", "SA",
                                         "SU"],
    EventAvailability:                  ["BUSY", "FREE"],
    AttendeeType:                       ["INDIVIDUAL", "GROUP", "RESOURCE",
                                         "ROOM", "UNKNOWN"],
    AttendeeStatus:                     ["PENDING", "ACCEPTED", "DECLINED",
                                         "TENTATIVE", "DELEGATED", "COMPLETED",
                                         "IN_PROCESS"],
    AttendeeRole:                       ["REQ_PARTICIPANT", "OPT_PARTICIPANT",
                                         "NON_PARTICIPANT", "CHAIR"],
    CalendarItemPriority:               ["HIGH", "MEDIUM", "LOW"],
    CalendarItemVisibility:             ["PUBLIC", "PRIVATE", "CONFIDENTIAL"],
    CalendarItemStatus:                 ["TENTATIVE", "CONFIRMED", "CANCELLED",
                                         "NEEDS_ACTION", "IN_PROCESS",
                                         "COMPLETED"],

    // Contact
    ContactTextFormat:                  ["VCARD_30", "VCARD_30"],    // Enum must has more than one value

    // Content
    ContentDirectoryStorageType:        ["INTERNAL", "EXTERNAL"],
    ContentType:                        ["IMAGE", "VIDEO", "AUDIO", "OTHER"],
    AudioContentLyricsType:             ["SYNCHRONIZED", "UNSYNCHRONIZED"],
    ImageContentOrientation:            ["NORMAL", "FLIP_HORIZONTAL",
                                         "ROTATE_180", "FLIP_VERTICAL",
                                         "TRANSPOSE", "ROTATE_90", "TRANSVERSE",
                                         "ROTATE_270"],

    // Data Control
    DataType:                           ["MAP", "SQL"],

    // Data Synchronization
    SyncMode:                           ["MANUAL", "PERIODIC", "PUSH"],
    SyncType:                           ["TWO_WAY", "SLOW",
                                         "ONE_WAY_FROM_CLIENT",
                                         "REFRESH_FROM_CLIENT",
                                         "ONE_WAY_FROM_SERVER",
                                         "REFRESH_FROM_SERVER"],
    SyncInterval:                       ["5_MINUTES", "15_MINUTES", "1_HOUR",
                                         "4_HOURS", "12_HOURS", "1_DAY",
                                         "1_WEEK", "1_MONTH"],
    SyncServiceType:                    ["CONTACT", "EVENT"],
    SyncStatus:                         ["SUCCESS", "FAIL", "STOP", "NONE"],

    // Download
    DownloadState:                      ["QUEUED", "DOWNLOADING", "PAUSED",
                                         "CANCELED", "COMPLETED", "FAILED"],
    DownloadNetworkType:                ["CELLULAR", "WIFI", "ALL"],

    // Messaging
    MessageServiceTag:                  ["messaging.sms", "messaging.mms",
                                         "messaging.email"],

    // Network Bearer Selection
    NetworkType:                        ["CELLULAR", "UNKNOWN"],

    // NFC
    NDEFRecordTextEncoding:             ["UTF8", "UTF16"],
    NFCTagType:                         ["GENERIC_TARGET", "ISO14443_A",
                                         "ISO14443_4A", "ISO14443_3A",
                                         "MIFARE_MINI", "MIFARE_1K",
                                         "MIFARE_4K", "MIFARE_ULTRA",
                                         "MIFARE_DESFIRE", "ISO14443_B",
                                         "ISO14443_4B", "ISO14443_BPRIME",
                                         "FELICA", "JEWEL", "ISO15693",
                                         "UNKNOWN_TARGET"],

    // Notification
    NotificationType:                   ["STATUS", "STATUS"],
    StatusNotificationType:             ["SIMPLE", "THUMBNAIL", "ONGOING",
                                         "PROGRESS"],
    NotificationProgressType:           ["PERCENTAGE", "BYTE"],

    // Power
    PowerResource:                      ["SCREEN", "CPU"],
    PowerScreenState:                   ["SCREEN_OFF", "SCREEN_DIM",
                                         "SCREEN_NORMAL"],
    PowerCpuState:                      ["CPU_AWAKE"],
    PowerState:                         ["SCREEN_OFF", "SCREEN_DIM",
                                         "SCREEN_NORMAL", "CPU_AWAKE"],

    // System Info
    SystemInfoPropertyId:               ["BATTERY", "CPU", "STORAGE", "DISPLAY",
                                         "DEVICE_ORIENTATION", "BUILD",
                                         "LOCALE", "NETWORK", "WIFI_NETWORK",
                                         "CELLULAR_NETWORK", "SIM",
                                         "PERIPHERAL"],
    SystemInfoNetworkType:              ["NONE", "2G", "2.5G", "3G", "4G",
                                         "WIFI", "ETHERNET", "UNKNOWN"],
    SystemInfoDeviceOrientationStatus:  ["PORTRAIT_PRIMARY",
                                         "PORTRAIT_SECONDARY",
                                         "LANDSCAPE_PRIMARY",
                                         "LANDSCAPE_SECONDARY"],
    SystemInfoSimState:                 ["ABSENT", "INITIALIZING", "READY",
                                         "PIN_REQUIRED", "PUK_REQUIRED",
                                         "NETWORK_LOCKED", "SIM_LOCKED",
                                         "UNKNOWN"],
    SystemInfoProfile:                  ["MOBILE_FULL", "MOBILE_WEB"],

    // System Setting
    SystemSettingType:                  ["HOME_SCREEN", "LOCK_SCREEN",
                                         "INCOMING_CALL", "NOTIFICATION_EMAIL"],

    // Time
    TimeDurationUnit:                   ["MSECS", "SECS", "MINS", "HOURS",
                                         "DAYS"]
};

/*
 * Derivative type definition
 */

/*
 * Object
 *
 * attributes
 *     Specify a type for each attribute.
 *
 * _optional
 *     Optional attributes table, which consists of two types of attributes,
 *
 *     nullable
 *         Nullable attributes, marked as '?' in IDL.
 *
 *     undefined
 *         Array type attributes, that not definitely specified to be
 *         initialized as an empty array, i.e., undefined-initialized array.
 *
 * _derived
 *     Subtype list, which consists of derived subtypes. It exists in the
 *     definition of a base type.
 *
 * _dictionary
 *     Dictionary type, which indicates that the object is a dictionary type.
 */

/*
 * Union types
 *     An array consists of two or more other types.
 */

/*
 * Common
 */

_t.AttributeFilter = {
    attributeName: _t.DOMString,
    matchFlag:     _t.FilterMatchFlag,
    matchValue:    _t.any,

    _optional: {
        // nullable
        matchValue: true
    }
};

_t.AttributeRangeFilter = {
    attributeName: _t.DOMString,
    initialValue:  _t.any,
    endValue:      _t.any,

    _optional: {
        // nullable
        initialValue: true,
        endValue:     true
    }
};

_t.CompositeFilter = {
    type:    _t.CompositeFilterType,
    filters: ["AbstractFilter"]     // Recursive expansion
};

_t.AbstractFilter = {
    _derived: [_t.AttributeFilter, _t.AttributeRangeFilter, _t.CompositeFilter]
};

_t.SortMode = {
    attributeName: _t.DOMString,
    order:         _t.SortModeOrder
};

_t.SimpleCoordinates = {
    latitude:  _t.double,
    longitude: _t.double
};

_t.SuccessCallback = _t.Function;
_t.ErrorCallback   = _t.Function;

/*
 * Time
 */

_t.TimeDuration = {
    length:      _t.long_long,
    unit:        _t.TimeDurationUnit,
    difference:  _t.Function,
    equalsTo:    _t.Function,
    lessThan:    _t.Function,
    greaterThan: _t.Function
};

/*
 * Alarm
 */

_t.AlarmId = _t.DOMString;

_t.AlarmRelative = {
    delay:               _t.unsigned_long_long,
    period:              _t.unsigned_long_long,
    getRemainingSeconds: _t.Function,

    _optional: {
        // nullable
        period:              true,
        getRemainingSeconds: true
    }
};

_t.AlarmAbsolute = {
    date:                 _t.Date,
    period:               _t.unsigned_long_long,
    daysOfTheWeek:        [_t.ByDayValue],
    getNextScheduledDate: _t.Function,

    _optional: {
        // nullable
        period:               true,
        getNextScheduledDate: true
    }
};

_t.Alarm = {
    id: _t.AlarmId,

    _optional: {
        // nullable
        id: true
    },

    _derived: [_t.AlarmRelative, _t.AlarmAbsolute]
};

/*
 * Application
 */

_t.ApplicationId                              = _t.DOMString;
_t.ApplicationContextId                       = _t.DOMString;
_t.ApplicationInformationArraySuccessCallback = _t.Function;
_t.FindAppControlSuccessCallback              = _t.Function;
_t.ApplicationContextArraySuccessCallback     = _t.Function;

_t.ApplicationControlData = {
    key:   _t.DOMString,
    value: [_t.DOMString]
};

_t.ApplicationControl = {
    operation: _t.DOMString,
    uri:       _t.DOMString,
    mime:      _t.DOMString,
    category:  _t.DOMString,
    data:      [_t.ApplicationControlData],

    _optional: {
        // nullable
        uri:      true,
        mime:     true,
        category: true
    }
};

_t.ApplicationControlDataArrayReplyCallback = {
    onsuccess: _t.Callback,
    onfailure: _t.Callback
};

_t.ApplicationInformationEventCallback = {
    oninstalled:   _t.Callback,
    onupdated:     _t.Callback,
    onuninstalled: _t.Callback
};

/*
 * Bluetooth
 */

_t.BluetoothAddress                          = _t.DOMString;
_t.BluetoothUUID                             = _t.DOMString;
_t.BluetoothDeviceSuccessCallback            = _t.Function;
_t.BluetoothDeviceArraySuccessCallback       = _t.Function;
_t.BluetoothSocketSuccessCallback            = _t.Function;
_t.BluetoothServiceSuccessCallback           = _t.Function;
_t.BluetoothHealthApplicationSuccessCallback = _t.Function;
_t.BluetoothHealthChannelSuccessCallback     = _t.Function;

_t.BluetoothClass = {
    major:      _t.octet,
    minor:      _t.octet,
    services:   [_t.unsigned_short],
    hasService: _t.Function
};

_t.BluetoothDevice = {
    name:                   _t.DOMString,
    address:                _t.BluetoothAddress,
    deviceClass:            _t.BluetoothClass,
    isBonded:               _t.boolean,
    isTrusted:              _t.boolean,
    isConnected:            _t.boolean,
    uuids:                  [_t.BluetoothUUID],
    connectToServiceByUUID: _t.Function
};

_t.BluetoothHealthApplication = {
    dataType:   _t.unsigned_short,
    name:       _t.DOMString,
    onconnect:  _t.BluetoothHealthChannelSuccessCallback,
    unregister: _t.Function,

    _optional: {
        onconnect: true
    }
};

_t.BluetoothAdapterChangeCallback = {
    onstatechanged:      _t.Callback,
    onnamechanged:       _t.Callback,
    onvisibilitychanged: _t.Callback
};

_t.BluetoothDiscoverDevicesSuccessCallback = {
    onstarted:           _t.Callback,
    ondevicefound:       _t.Callback,
    ondevicedisappeared: _t.Callback,
    onfinished:          _t.Callback
};

_t.BluetoothHealthChannelChangeCallback = {
    onmessage: _t.Callback,
    onclose:   _t.Callback
};

/*
 * Bookmark
 */

_t.BookmarkFolder = {
    parent: "BookmarkFolder",
    title:  _t.DOMString,

    _optional: {
        // nullable
        parent: true
    }
};

_t.BookmarkItem = {
    parent: _t.BookmarkFolder,
    title:  _t.DOMString,
    url:    _t.DOMString,

    _optional: {
        // nullable
        parent: true
    }
};

_t.Bookmark = [_t.BookmarkItem, _t.BookmarkFolder];

/*
 * Contact
 */

_t.AddressBookId  = _t.DOMString;
_t.ContactId      = _t.DOMString;
_t.PersonId       = _t.DOMString;
_t.ContactGroupId = _t.DOMString;

_t.Person = {
    id:               _t.PersonId,
    displayName:      _t.DOMString,
    contactCount:     _t.long,
    hasPhoneNumber:   _t.boolean,
    hasEmail:         _t.boolean,
    isFavorite:       _t.boolean,
    photoURI:         _t.DOMString,
    ringtoneURI:      _t.DOMString,
    displayContactId: _t.ContactId,

    _optional: {
        // nullable
        photoURI:    true,
        ringtoneURI: true
    }
};

_t.ContactRef = {
    addressBookId: _t.AddressBookId,
    contactId:     _t.ContactId
};

_t.ContactName = {
    prefix:            _t.DOMString,
    suffix:            _t.DOMString,
    firstName:         _t.DOMString,
    middleName:        _t.DOMString,
    lastName:          _t.DOMString,
    nicknames:         [_t.DOMString],
    phoneticFirstName: _t.DOMString,
    phoneticLastName:  _t.DOMString,
    displayName:       _t.DOMString,

    _optional: {
        // nullable
        prefix:            true,
        suffix:            true,
        firstName:         true,
        middleName:        true,
        lastName:          true,
        phoneticFirstName: true,
        phoneticLastName:  true,
        displayName:       true
    }
};

_t.ContactOrganization = {
    name:       _t.DOMString,
    department: _t.DOMString,
    title:      _t.DOMString,
    role:       _t.DOMString,
    logoURI:    _t.DOMString,

    _optional: {
        // nullable
        name:       true,
        department: true,
        title:      true,
        role:       true,
        logoURI:    true
    }
};

_t.ContactWebSite = {
    url:  _t.DOMString,
    type: _t.DOMString,

    _optional: {
        // nullable
        type: true
    }
};

_t.ContactAnniversary = {
    date:  _t.Date,
    label: _t.DOMString,

    _optional: {
        // nullable
        label: true
    }
};

_t.ContactAddress = {
    country:               _t.DOMString,
    region:                _t.DOMString,
    city:                  _t.DOMString,
    streetAddress:         _t.DOMString,
    additionalInformation: _t.DOMString,
    postalCode:            _t.DOMString,
    isDefault:             _t.boolean,
    types:                 [_t.DOMString],

    _optional: {
        // nullable
        country:               true,
        region:                true,
        city:                  true,
        streetAddress:         true,
        additionalInformation: true,
        postalCode:            true,
        // undefined
        types:                 true
    }
};

_t.ContactPhoneNumber = {
    number:    _t.DOMString,
    isDefault: _t.boolean,
    types:     [_t.DOMString],

    _optional: {
        // undefined
        types: true
    }
};

_t.ContactEmailAddress = {
    email:     _t.DOMString,
    isDefault: _t.boolean,
    types:     [_t.DOMString],

    _optional: {
        // undefined
        types: true
    }
};

_t.Contact = {
    id:              _t.ContactId,
    personId:        _t.PersonId,
    addressBookId:   _t.AddressBookId,
    lastUpdated:     _t.Date,
    isFavorite:      _t.boolean,
    name:            _t.ContactName,
    addresses:       [_t.ContactAddress],
    photoURI:        _t.DOMString,
    phoneNumbers:    [_t.ContactPhoneNumber],
    emails:          [_t.ContactEmailAddress],
    birthday:        _t.Date,
    anniversaries:   [_t.ContactAnniversary],
    organizations:   [_t.ContactOrganization],
    notes:           [_t.DOMString],
    urls:            [_t.ContactWebSite],
    ringtoneURI:     _t.DOMString,
    groupIds:        [_t.ContactGroupId],
    convertToString: _t.Function,
    clone:           _t.Function,

    _optional: {
        // nullable
        id:            true,
        personId:      true,
        addressBookId: true,
        lastUpdated:   true,
        name:          true,
        photoURI:      true,
        birthday:      true,
        ringtoneURI:   true
    }
};

_t.ContactGroup = {
    id:            _t.ContactGroupId,
    addressBookId: _t.AddressBookId,
    name:          _t.DOMString,
    ringtoneURI:   _t.DOMString,
    photoURI:      _t.DOMString,
    readOnly:      _t.boolean,

    _optional: {
        // nullable
        id:            true,
        addressBookId: true,
        ringtoneURI:   true,
        photoURI:      true
    }
};

_t.PersonArraySuccessCallback      = _t.Function;
_t.ContactArraySuccessCallback     = _t.Function;
_t.AddressBookArraySuccessCallback = _t.Function;

_t.AddressBookChangeCallback = {
    oncontactsadded:   _t.Callback,
    oncontactsupdated: _t.Callback,
    oncontactsremoved: _t.Callback
};

_t.PersonsChangeCallback = {
    onpersonsadded:   _t.Callback,
    onpersonsupdated: _t.Callback,
    onpersonsremoved: _t.Callback
};

_t.ContactInit = {
    name:          _t.ContactName,
    addresses:     [_t.ContactAddress],
    photoURI:      _t.DOMString,
    phoneNumbers:  [_t.ContactPhoneNumber],
    emails:        [_t.ContactEmailAddress],
    birthday:      _t.Date,
    anniversaries: [_t.ContactAnniversary],
    organizations: [_t.ContactOrganization],
    notes:         [_t.DOMString],
    urls:          [_t.ContactWebSite],
    ringtoneURI:   _t.DOMString,
    groupIds:      [_t.ContactGroupId],

    _dictionary: null
};

_t.ContactNameInit = {
    prefix:            _t.DOMString,
    suffix:            _t.DOMString,
    firstName:         _t.DOMString,
    middleName:        _t.DOMString,
    lastName:          _t.DOMString,
    nicknames:         [_t.DOMString],
    phoneticFirstName: _t.DOMString,
    phoneticLastName:  _t.DOMString,

    _dictionary: null
};

_t.ContactOrganizationInit = {
    name:       _t.DOMString,
    department: _t.DOMString,
    title:      _t.DOMString,
    role:       _t.DOMString,
    logoURI:    _t.DOMString,

    _dictionary: null
};

_t.ContactAddressInit = {
    country:               _t.DOMString,
    region:                _t.DOMString,
    city:                  _t.DOMString,
    streetAddress:         _t.DOMString,
    additionalInformation: _t.DOMString,
    postalCode:            _t.DOMString,
    isDefault:             _t.boolean,
    types:                 [_t.DOMString],

    _dictionary: null
};

/*
 * Calendar
 */

_t.CalendarId                        = _t.DOMString;
_t.CalendarTaskId                    = _t.DOMString;
_t.CalendarEventArraySuccessCallback = _t.Function;
_t.CalendarItemArraySuccessCallback  = _t.Function;
_t.CalendarArraySuccessCallback      = _t.Function;

_t.CalendarEventId = {
    uid: _t.DOMString,
    rid: _t.DOMString,

    _optional: {
        // nullable
        rid: true
    }
};

_t.CalendarItemId = [_t.CalendarEventId, _t.CalendarTaskId];

_t.CalendarAlarm = {
    absoluteDate: _t.TZDate,
    before:       _t.TimeDuration,
    method:       _t.AlarmMethod,
    description:  _t.DOMString,

    _optional: {
        // nullable
        absoluteDate: true,
        before:       true,
        description:  true
    }
};

_t.CalendarAttendee = {
    uri:          _t.DOMString,
    name:         _t.DOMString,
    role:         _t.AttendeeRole,
    status:       _t.AttendeeStatus,
    RSVP:         _t.boolean,
    type:         _t.AttendeeType,
    group:        _t.DOMString,
    delegatorURI: _t.DOMString,
    delegateURI:  _t.DOMString,
    contactRef:   _t.ContactRef,

    _optional: {
        // nullable
        name:         true,
        group:        true,
        delegatorURI: true,
        delegateURI:  true,
        contactRef:   true
    }
};

_t.CalendarRecurrenceRule = {
    frequency:       _t.RecurrenceRuleFrequency,
    interval:        _t.unsigned_short,
    untilDate:       _t.TZDate,
    occurrenceCount: _t.long,
    daysOfTheWeek:   [_t.ByDayValue],
    setPositions:    [_t.short],
    exceptions:      [_t.TZDate],

    _optional: {
        // nullable
        untilDate: true
    }
};

_t.CalendarTask = {
    dueDate:       _t.TZDate,
    completedDate: _t.TZDate,
    progress:      _t.unsigned_short,

    _optional: {
        // nullable
        dueDate:       true,
        completedDate: true
    }
};

_t.CalendarEvent = {
    isDetached:       _t.boolean,
    endDate:          _t.TZDate,
    availability:     _t.EventAvailability,
    recurrenceRule:   _t.CalendarRecurrenceRule,
    expandRecurrence: _t.Function,

    _optional: {
        // nullable
        endDate:        true,
        recurrenceRule: true
    }
};

_t.CalendarItem = {
    id:                   _t.CalendarItemId,
    calendarId:           _t.CalendarId,
    lastModificationDate: _t.TZDate,
    description:          _t.DOMString,
    summary:              _t.DOMString,
    isAllDay:             _t.boolean,
    startDate:            _t.TZDate,
    duration:             _t.TimeDuration,
    location:             _t.DOMString,
    geolocation:          _t.SimpleCoordinates,
    organizer:            _t.DOMString,
    visibility:           _t.CalendarItemVisibility,
    status:               _t.CalendarItemStatus,
    priority:             _t.CalendarItemPriority,
    alarms:               [_t.CalendarAlarm],
    categories:           [_t.DOMString],
    attendees:            [_t.CalendarAttendee],
    convertToString:      _t.Function,
    clone:                _t.Function,

    _optional: {
        // nullable
        id:                   true,
        calendarId:           true,
        lastModificationDate: true,
        description:          true,
        summary:              true,
        startDate:            true,
        duration:             true,
        location:             true,
        geolocation:          true,
        organizer:            true
    },

    _derived: [_t.CalendarTask, _t.CalendarEvent]
};

_t.CalendarItemInit = {
    description: _t.DOMString,
    summary:     _t.DOMString,
    isAllDay:    _t.boolean,
    startDate:   _t.TZDate,
    duration:    _t.TimeDuration,
    location:    _t.DOMString,
    geolocation: _t.SimpleCoordinates,
    organizer:   _t.DOMString,
    visibility:  _t.CalendarItemVisibility,
    status:      _t.CalendarItemStatus,
    priority:    _t.CalendarItemPriority,
    alarms:      [_t.CalendarAlarm],
    categories:  [_t.DOMString],
    attendees:   [_t.CalendarAttendee],

    _dictionary: null
};

_t.CalendarTaskInit = {
    dueDate:       _t.TZDate,
    completedDate: _t.TZDate,
    progress:      _t.short,

    _dictionary: _t.CalendarItemInit
};

_t.CalendarEventInit = {
    endDate:        _t.TZDate,
    availability:   _t.EventAvailability,
    recurrenceRule: _t.CalendarRecurrenceRule,

    _dictionary: _t.CalendarItemInit
};

_t.CalendarAttendeeInit = {
    name:         _t.DOMString,
    role:         _t.AttendeeRole,
    status:       _t.AttendeeStatus,
    RSVP:         _t.boolean,
    type:         _t.AttendeeType,
    group:        _t.DOMString,
    delegatorURI: _t.DOMString,
    delegateURI:  _t.DOMString,
    contactRef:   _t.ContactRef,

    _dictionary: null
};

_t.CalendarRecurrenceRuleInit = {
    interval:        _t.short,
    untilDate:       _t.TZDate,
    occurrenceCount: _t.long,
    daysOfTheWeek:   [_t.ByDayValue],
    setPositions:    [_t.short],
    exceptions:      [_t.TZDate],

    _dictionary: null
};

_t.CalendarChangeCallback = {
    onitemsadded:   _t.Callback,
    onitemsupdated: _t.Callback,
    onitemsremoved: _t.Callback
};

/*
 * CallHistory
 */

_t.CallHistoryEntryArraySuccessCallback = _t.Function;

_t.RemoteParty = {
    remoteParty: _t.DOMString,
    personId:    _t.PersonId,

    _optional: {
        // nullable
        remoteParty: true,
        personId:    true
    }
};

_t.CallHistoryEntry = {
    uid:           _t.DOMString,
    type:          _t.DOMString,
    features:      [_t.DOMString],
    remoteParties: [_t.RemoteParty],
    startTime:     _t.Date,
    duration:      _t.unsigned_long,
    direction:     _t.DOMString,

    _optional: {
        // nullable
        features: true
    }
};

_t.CallHistoryChangeCallback = {
    onadded:   _t.Callback,
    onchanged: _t.Callback,
    onremoved: _t.Callback
};

/*
 * Content
 */

_t.ContentId                            = _t.DOMString;
_t.ContentDirectoryId                   = _t.DOMString;
_t.ContentArraySuccessCallback          = _t.Function;
_t.ContentDirectoryArraySuccessCallback = _t.Function;
_t.ContentScanSuccessCallback           = _t.Function;

_t.ContentChangeCallback = {
    oncontentadded:   _t.Callback,
    oncontentupdated: _t.Callback,
    oncontentremoved: _t.Callback
};

_t.VideoContent = {
    geolocation: _t.SimpleCoordinates,
    album:       _t.DOMString,
    artists:     [_t.DOMString],
    duration:    _t.unsigned_long,
    width:       _t.unsigned_long,
    height:      _t.unsigned_long,

    _optional: {
        // nullable
        geolocation: true,
        album:       true,
        artists:     true
    }
};

_t.AudioContentLyrics = {
    type:       _t.AudioContentLyricsType,
    timestamps: [_t.unsigned_long],
    texts:      [_t.DOMString],

    _optional: {
        // undefined
        timestamps: true
    }
};

_t.AudioContent = {
    album:       _t.DOMString,
    genres:      [_t.DOMString],
    artists:     [_t.DOMString],
    composers:   [_t.DOMString],
    lyrics:      _t.AudioContentLyrics,
    copyright:   _t.DOMString,
    bitrate:     _t.unsigned_long,
    trackNumber: _t.unsigned_short,
    duration:    _t.unsigned_long,

    _optional: {
        // nullable
        album:       true,
        genres:      true,
        artists:     true,
        composers:   true,
        lyrics:      true,
        copyright:   true,
        trackNumber: true
    }
};

_t.ImageContent = {
    geolocation: _t.SimpleCoordinates,
    width:       _t.unsigned_long,
    height:      _t.unsigned_long,
    orientation: _t.ImageContentOrientation,

    _optional: {
        // nullable
        geolocation: true
    }
};

_t.Content = {
    editableAttributes: [_t.DOMString],
    id:                 _t.ContentId,
    name:               _t.DOMString,
    type:               _t.ContentType,
    mimeType:           _t.DOMString,
    title:              _t.DOMString,
    contentURI:         _t.DOMString,
    thumbnailURIs:      [_t.DOMString],
    releaseDate:        _t.Date,
    modifiedDate:       _t.Date,
    size:               _t.unsigned_long,
    description:        _t.DOMString,
    rating:             _t.float,

    _optional: {
        // nullable
        thumbnailURIs: true,
        releaseDate:   true,
        modifiedDate:  true,
        description:   true
    },

    _derived: [_t.VideoContent, _t.AudioContent, _t.ImageContent]
};

/*
 * Data Control
 */

_t.DataControlSuccessCallback         = _t.Function;
_t.DataControlErrorCallback           = _t.Function;
_t.DataControlInsertSuccessCallback   = _t.Function;
_t.DataControlSelectSuccessCallback   = _t.Function;
_t.DataControlGetValueSuccessCallback = _t.Function;

_t.RowData = {
    columns: [_t.DOMString],
    values:  [_t.DOMString]
};

/*
 * Data Synchronization
 */

_t.SyncProfileId = _t.DOMString;

_t.SyncInfo = {
    url:      _t.DOMString,
    id:       _t.DOMString,
    password: _t.DOMString,
    mode:     _t.SyncMode,
    type:     _t.SyncType,
    interval: _t.SyncInterval,

    _optional: {
        // nullable
        id:       true,
        password: true,
        type:     true,
        interval: true
    }
};

_t.SyncServiceInfo = {
    enable:            _t.boolean,
    serviceType:       _t.SyncServiceType,
    serverDatabaseUri: _t.DOMString,
    id:                _t.DOMString,
    password:          _t.DOMString,

    _optional: {
        // nullable
        id:       true,
        password: true
    }
};

_t.SyncProfileInfo = {
    profileId:   _t.SyncProfileId,
    profileName: _t.DOMString,
    syncInfo:    _t.SyncInfo,
    serviceInfo: [_t.SyncServiceInfo],

    _optional: {
        // nullable
        profileId:   true,
        serviceInfo: true
    }
};

_t.SyncProgressCallback = {
    onprogress:  _t.Callback,
    oncompleted: _t.Callback,
    onstopped:   _t.Callback,
    onfailed:    _t.Callback
};

/*
 * Download
 */

_t.DownloadHTTPHeaderFields = {};

_t.DownloadRequest = {
    url:         _t.DOMString,
    destination: _t.DOMString,
    fileName:    _t.DOMString,
    networkType: _t.DownloadNetworkType,
    httpHeader:  _t.DownloadHTTPHeaderFields,

    _optional: {
        destination: true,
        fileName:    true,
        networkType: true,
        httpHeader:  true
    }
};

_t.DownloadCallback = {
    onprogress:  _t.Callback,
    onpaused:    _t.Callback,
    oncanceled:  _t.Callback,
    oncompleted: _t.Callback,
    onfailed:    _t.Callback
};

/*
 * Messaging
 */

_t.MessageId                               = _t.DOMString;
_t.MessageAttachmentId                     = _t.DOMString;
_t.MessageConvId                           = _t.DOMString;
_t.MessageFolderId                         = _t.DOMString;
_t.MessageServiceArraySuccessCallback      = _t.Function;
_t.MessageRecipientsCallback               = _t.Function;
_t.MessageBodySuccessCallback              = _t.Function;
_t.MessageAttachmentSuccessCallback        = _t.Function;
_t.MessageArraySuccessCallback             = _t.Function;
_t.MessageConversationArraySuccessCallback = _t.Function;
_t.MessageFolderArraySuccessCallback       = _t.Function;

_t.MessageFolder = {
    id:             _t.MessageFolderId,
    parentId:       _t.MessageFolderId,
    serviceId:      _t.DOMString,
    contentType:    _t.MessageServiceTag,
    name:           _t.DOMString,
    path:           _t.DOMString,
    type:           _t.DOMString,
    synchronizable: _t.boolean,

    _optional: {
        // nullable
        parentId: true
    }
};

_t.MessagesChangeCallback = {
    messagesadded:   _t.Callback,
    messagesupdated: _t.Callback,
    messagesremoved: _t.Callback
};

_t.MessageConversationsChangeCallback = {
    conversationsadded:   _t.Callback,
    conversationsupdated: _t.Callback,
    conversationsremoved: _t.Callback
};

_t.MessageFoldersChangeCallback = {
    foldersadded:   _t.Callback,
    foldersupdated: _t.Callback,
    foldersremoved: _t.Callback
};

/*
 * Network Bearer Selection
 */

_t.NetworkSuccessCallback = {
    onsuccess:      _t.Callback,
    ondisconnected: _t.Callback
};

/*
 * NFC
 */

_t.NDEFMessageReadCallback  = _t.Function;
_t.ByteArraySuccessCallback = _t.Function;

_t.NFCTagDetectCallback = {
    onattach: _t.Callback,
    ondetach: _t.Callback
};

_t.NFCPeerDetectCallback = {
    onattach: _t.Callback,
    ondetach: _t.Callback
};

_t.NDEFRecordText = {
    text:         _t.DOMString,
    languageCode: _t.DOMString,
    encoding:     _t.NDEFRecordTextEncoding
};

_t.NDEFRecordURI = {
    uri: _t.DOMString
};

_t.NDEFRecordMedia = {
    mimeType: _t.DOMString
};

_t.NDEFRecord = {
    tnf:     _t.short,
    type:    [_t.byte],
    id:      [_t.byte],
    payload: [_t.byte],

    _derived: [_t.NDEFRecordText, _t.NDEFRecordURI, _t.NDEFRecordMedia]
};

_t.NDEFMessage = {
    recordCount: _t.long,
    records:     [_t.NDEFRecord],
    toByte:      _t.Function
};

/*
 * Notification
 */

_t.NotificationId = _t.DOMString;

_t.NotificationDetailInfo = {
    mainText: _t.DOMString,
    subText:  _t.DOMString,

    _optional: {
        // nullable
        subText: true
    }
};

_t.StatusNotificationInit = {
    content:             _t.DOMString,
    iconPath:            _t.DOMString,
    soundPath:           _t.DOMString,
    vibration:           _t.boolean,
    appControl:          _t.ApplicationControl,
    appId:               _t.ApplicationId,
    progressType:        _t.NotificationProgressType,
    progressValue:       _t.unsigned_long,
    number:              _t.long,
    subIconPath:         _t.DOMString,
    detailInfo:          [_t.NotificationDetailInfo],
    ledColor:            _t.DOMString,
    ledOnPeriod:         _t.unsigned_long,
    ledOffPeriod:        _t.unsigned_long,
    backgroundImagePath: _t.DOMString,
    thumbnails:          [_t.DOMString],

    _dictionary: null
};

_t.StatusNotification = {
    statusType:          _t.StatusNotificationType,
    iconPath:            _t.DOMString,
    subIconPath:         _t.DOMString,
    number:              _t.long,
    detailInfo:          [_t.NotificationDetailInfo],
    ledColor:            _t.DOMString,
    ledOnPeriod:         _t.unsigned_long,
    ledOffPeriod:        _t.unsigned_long,
    backgroundImagePath: _t.DOMString,
    thumbnails:          [_t.DOMString],
    soundPath:           _t.DOMString,
    vibration:           _t.boolean,
    appControl:          _t.ApplicationControl,
    appId:               _t.ApplicationId,
    progressType:        _t.NotificationProgressType,
    progressValue:       _t.unsigned_long,

    _optional: {
        // nullable
        iconPath:            true,
        subIconPath:         true,
        number:              true,
        detailInfo:          true,
        ledColor:            true,
        backgroundImagePath: true,
        thumbnails:          true,
        soundPath:           true,
        appControl:          true,
        appId:               true,
        progressValue:       true
    }
};

_t.Notification = {
    id:         _t.NotificationId,
    type:       _t.NotificationType,
    postedTime: _t.Date,
    title:      _t.DOMString,
    content:    _t.DOMString,

    _optional: {
        // nullable
        id:         true,
        postedTime: true,
        content:    true
    },

    _derived: [_t.StatusNotification]
};

/*
 * Power
 */

_t.ScreenStateChangeCallback = _t.Function;

/*
 * Push
 */

_t.PushRegistrationId          = _t.DOMString;
_t.PushRegisterSuccessCallback = _t.Function;
_t.PushNotificationCallback    = _t.Function;

/*
 * Package
 */

_t.PackageId = _t.DOMString;
_t.PackageInformationArraySuccessCallback = _t.Function;

_t.PackageProgressCallback = {
    onprogress: _t.Callback,
    oncomplete: _t.Callback
};

_t.PackageInfomationEventCallback = {
    oninstalled:   _t.Callback,
    onupdated:     _t.Callback,
    onuninstalled: _t.Callback
};

/*
 * System Info
 */

_t.SystemInfoPropertySuccessCallback = _t.Callback;

_t.SystemInfoOptions = {
    timeout:       _t.unsigned_long,
    highThreshold: _t.double,
    lowThreshold:  _t.double,

    _dictionary: null
};

/*
 * System Setting
 */

_t.SystemSettingSuccessCallback = _t.Function;

/*
 * Constructor list definition
 */

/*
 * Generic constructor
 *     Construct a prototype of constructor. A fake array of arguments type is
 *     specified for constructor.
 *
 * Overloaded constructors
 *     Construct an array of prototype of constructor. Each array element is
 *     specified for one of constructors. The constructor with extra arguments
 *     are recommended to be defined ahead of the one with fewer same arguments
 *     for exact match.
 */

_c = {
    // Alarm
    AlarmAbsolute: [],

    // Calendar
    CalendarTask:  [],
    CalendarEvent: [],
    CalendarAlarm: [],

    // Contact
    Contact:       [],

    // NFC
    NDEFMessage:   [],
    NDEFRecord:    [],

    // Data Synchronization
    SyncInfo:      [],

    // Time
    TZDate:        []
};

/*
 * Common
 */

// AttributeFilter
_c.AttributeFilter = {
    0: _t.DOMString,
    1: _t.FilterMatchFlag,
    2: _t.any,

    _optional: {
        1: true,
        2: true
    }
};

// AttributeRangeFilter
_c.AttributeRangeFilter = {
    0: _t.DOMString,
    1: _t.any,
    2: _t.any,

    _optional: {
        1: true,
        2: true
    }
};

// CompositeFilter
_c.CompositeFilter = {
    0: _t.CompositeFilterType,
    1: [_t.AbstractFilter],

    _optional: {
        1: true
    }
};

// SortMode
_c.SortMode = {
    0: _t.DOMString,
    1: _t.SortModeOrder,

    _optional: {
        1: true
    }
};

// SimpleCoordinates
_c.SimpleCoordinates = {
    0: _t.double,
    1: _t.double
};

/*
 * Alarm
 */

// AlarmRelative
_c.AlarmRelative = {
    0: _t.long,
    1: _t.long,

    _optional: {
        1: true
    }
};

// AlarmAbsolute
_c.AlarmAbsolute[0] = {
    0: _t.Date,
    1: [_t.ByDayValue]
};

_c.AlarmAbsolute[1] = {
    0: _t.Date,
    1: _t.long
};

_c.AlarmAbsolute[2] = {
    0: _t.Date
};

/*
 * Application
 */

// ApplicationControlData
_c.ApplicationControlData = {
    0: _t.DOMString,
    1: [_t.DOMString]
};

// ApplicationControl
_c.ApplicationControl = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.DOMString,
    3: _t.DOMString,
    4: [_t.ApplicationControlData],

    _optional: {
        1: true,
        2: true,
        3: true,
        4: true
    }
};

/*
 * Bookmark
 */

// BookmarkItem
_c.BookmarkItem = {
    0: _t.DOMString,
    1: _t.DOMString
};

// BookmarkFolder
_c.BookmarkFolder = {
    0: _t.DOMString
};

/*
 * Calendar
 */

// CalendarTask
_c.CalendarTask[0] = {
    0: _t.CalendarTaskInit,

    _optional: {
        // nullable
        0: true
    }
};

_c.CalendarTask[1] = {
    0: _t.DOMString,
    1: _t.CalendarTextFormat
};

// CalendarEvent
_c.CalendarEvent[0] = {
    0: _t.CalendarEventInit,

    _optional: {
        // nullable
        0: true
    }
};

_c.CalendarEvent[1] = {
    0: _t.DOMString,
    1: _t.CalendarTextFormat
};

// CalendarAttendee
_c.CalendarAttendee = {
    0: _t.DOMString,
    1: _t.CalendarAttendeeInit,

    _optional: {
        1: true
    }
};

// CalendarRecurrenceRule
_c.CalendarRecurrenceRule = {
    0: _t.RecurrenceRuleFrequency,
    1: _t.CalendarRecurrenceRuleInit,

    _optional: {
        1: true
    }
};

// CalendarEventId
_c.CalendarEventId = {
    0: _t.DOMString,
    1: _t.DOMString,

    _optional: {
        1: true
    }
};

// CalendarAlarm
_c.CalendarAlarm[0] = {
    0: _t.TZDate,
    1: _t.AlarmMethod,
    2: _t.DOMString,

    _optional: {
        2: true
    }
};

_c.CalendarAlarm[1] = {
    0: _t.TimeDuration,
    1: _t.AlarmMethod,
    2: _t.DOMString,

    _optional: {
        2: true
    }
};

/*
 * Contact
 */

// Contact
_c.Contact[0] = {
    0: _t.ContactInit,

    _optional: {
        0: true
    }
};

_c.Contact[1] = {
    0: _t.DOMString
};

// ContactRef
_c.ContactRef = {
    0: _t.AddressBookId,
    1: _t.ContactId
};

// ContactName
_c.ContactName = {
    0: _t.ContactNameInit,

    _optional: {
        0: true
    }
};

// ContactOrganization
_c.ContactOrganization = {
    0: _t.ContactOrganizationInit,

    _optional: {
        0: true
    }
};

// ContactWebSite
_c.ContactWebSite = {
    0: _t.DOMString,
    1: _t.DOMString,

    _optional: {
        1: true
    }
};

// ContactAnniversary
_c.ContactAnniversary = {
    0: _t.Date,
    1: _t.DOMString,

    _optional: {
        1: true
    }
};

// ContactAddress
_c.ContactAddress = {
    0: _t.ContactAddressInit,

    _optional: {
        0: true
    }
};

// ContactPhoneNumber
_c.ContactPhoneNumber = {
    0: _t.DOMString,
    1: [_t.DOMString],
    2: _t.boolean,

    _optional: {
        1: true,
        2: true
    }
};

// ContactEmailAddress
_c.ContactEmailAddress = {
    0: _t.DOMString,
    1: [_t.DOMString],
    2: _t.boolean,

    _optional: {
        1: true,
        2: true
    }
};

// ContactGroup
_c.ContactGroup = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.DOMString,

    _optional: {
        1: true,
        2: true
    }
};

/*
 * Data Synchronization
 */

// SyncInfo
_c.SyncInfo[0] = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.DOMString,
    3: _t.SyncMode,
    4: _t.SyncType
};

_c.SyncInfo[1] = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.DOMString,
    3: _t.SyncMode,
    4: _t.SyncInterval
};

_c.SyncInfo[2] = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.DOMString,
    3: _t.SyncMode
};

// SyncServiceInfo
_c.SyncServiceInfo = {
    0: _t.boolean,
    1: _t.SyncServiceType,
    2: _t.DOMString,
    3: _t.DOMString,
    4: _t.DOMString,

    _optional: {
        3: true,
        4: true
    }
};

// SyncProfileInfo
_c.SyncProfileInfo = {
    0: _t.DOMString,
    1: _t.SyncInfo,
    2: [_t.SyncServiceInfo],

    _optional: {
        2: true
    }
};

/*
 * Download
 */

// DownloadRequest
_c.DownloadRequest = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.DOMString,
    3: _t.DownloadNetworkType,
    4: _t.DownloadHTTPHeaderFields,

    _optional: {
        1: true,
        2: true,
        3: true,
        4: true
    }
};

/*
 * NFC
 */

// NDEFMessage
_c.NDEFMessage[0] = {
    0: [_t.NDEFRecord]
};

_c.NDEFMessage[1] = {
    0: [_t.byte]
};

_c.NDEFMessage[2] = null;

// NDEFRecord
_c.NDEFRecord[0] = {
    0: _t.short,
    1: [_t.byte],
    2: [_t.byte],
    3: [_t.byte],

    _optional: {
        3: true
    }
};

_c.NDEFRecord[1] = {
    0: [_t.byte]
};

// NDEFRecordText
_c.NDEFRecordText = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.DOMString,

    _optional: {
        2: true
    }
};

// NDEFRecordURI
_c.NDEFRecordURI = {
    0: _t.DOMString
};

// NDEFRecordMedia
_c.NDEFRecordMedia = {
    0: _t.DOMString,
    1: [_t.byte]
};

/*
 * Notification
 */

// StatusNotification
_c.StatusNotification = {
    0: _t.StatusNotificationType,
    1: _t.DOMString,
    2: _t.StatusNotificationInit,

    _optional: {
        2: true
    }
};

// NotificationDetailInfo
_c.NotificationDetailInfo = {
    0: _t.DOMString,
    1: _t.DOMString,

    _optional: {
        1: true
    }
};

/*
 * Time
 */

// TZDate
_c.TZDate[0] = {
    0: _t.Date,
    1: _t.DOMString,

    _optional: {
        // nullable
        0: true,
        1: true
    }
};

_c.TZDate[1] = {
    0: _t.long,
    1: _t.long,
    2: _t.long,
    3: _t.long,
    4: _t.long,
    5: _t.long,
    6: _t.long,
    7: _t.DOMString,

    _optional: {
        // nullable
        3: true,
        4: true,
        5: true,
        6: true,
        7: true
    }
};

// TimeDuration
_c.TimeDuration = {
    0: _t.long_long,
    1: _t.TimeDurationUnit,

    _optional: {
        // nullable
        1: true
    }
};

/*
 * Interface prototype definition
 */

_i = {
    // Alarm
    AlarmManager:                  {},

    // Application
    ApplicationManager:            {},
    Application:                   {},
    RequestedApplicationControl:   {},

    // Bluetooth
    BluetoothManager:              {},
    BluetoothAdapter:              {},
    BluetoothDevice:               {},
    BluetoothSocket:               {},
    BluetoothClass:                {},
    BluetoothServiceHandler:       {},
    BluetoothHealthProfileHandler: {},
    BluetoothHealthApplication:    {},
    BluetoothHealthChannel:        {},

    // Bookmark
    BookmarkManager:               {},

    // Calendar
    CalendarManager:               {},
    Calendar:                      {},
    CalendarItem:                  {},
    CalendarEvent:                 {},

    // Call History
    CallHistory:                   {},

    // Contact
    ContactManager:                {},
    AddressBook:                   {},
    Person:                        {},
    Contact:                       {},

    // Content
    ContentManager:                {},

    // Data Control
    DataControlManager:            {},
    SQLDataControlConsumer:        {},
    MappedDataControlConsumer:     {},

    // Data Synchronization
    DataSynchronizationManager:    {},

    // Download
    DownloadManager:               {},

    // Network Bearer Selection
    NetworkBearerSelection:        {},

    // NFC
    NFCManager:                    {},
    NFCAdapter:                    {},
    NFCTag:                        {},
    NFCPeer:                       {},
    NDEFMessage:                   {},

    // Notification
    NotificationManager:           {},

    // Message
    Messaging:                     {},
    MessageService:                {},
    MessageStorage:                {},

    // Package
    PackageManager:                {},

    // Power
    PowerManager:                  {},

    // Push
    PushManager:                   {},

    // System Info
    SystemInfo:                    {},

    // System Setting
    SystemSettingManager:          {},

    // Time
    TimeUtil:                      {},
    TZDate:                        {},
    TimeDuration:                  {},

    // Web Setting
    WebSettingManager:             {}
};

/*
 * Alarm
 */

// AlarmManager
_i.AlarmManager.add = {
    0: _t.Alarm,
    1: _t.ApplicationId,
    2: _t.ApplicationControl,

    _optional: {
        2: true
    }
};

_i.AlarmManager.remove = {
    0: _t.AlarmId
};

_i.AlarmManager.removeAll = null;

_i.AlarmManager.get = {
    0: _t.AlarmId
};

_i.AlarmManager.getAll = null;

/*
 * Application
 */

// ApplicationManager
_i.ApplicationManager.getCurrentApplication = null;

_i.ApplicationManager.kill = {
    0: _t.ApplicationContextId,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.ApplicationManager.launch = {
    0: _t.ApplicationId,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.ApplicationManager.launchAppControl = {
    0: _t.ApplicationControl,
    1: _t.ApplicationId,
    2: _t.SuccessCallback,
    3: _t.ErrorCallback,
    4: _t.ApplicationControlDataArrayReplyCallback,

    _optional: {
        1: true,
        2: true,
        3: true,
        4: true
    }
};

_i.ApplicationManager.findAppControl = {
    0: _t.ApplicationControl,
    1: _t.FindAppControlSuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

_i.ApplicationManager.getAppsContext = {
    0: _t.ApplicationContextArraySuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        1: true
    }
};

_i.ApplicationManager.getAppContext = {
    0: _t.ApplicationContextId,

    _optional: {
        0: true
    }
};

_i.ApplicationManager.getAppsInfo = {
    0: _t.ApplicationInformationArraySuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        1: true
    }
};

_i.ApplicationManager.getAppInfo = {
    0: _t.ApplicationId,

    _optional: {
        0: true
    }
};

_i.ApplicationManager.getAppCerts = {
    0: _t.ApplicationId,

    _optional: {
        0: true
    }
};

_i.ApplicationManager.getAppSharedURI = {
    0: _t.ApplicationId,

    _optional: {
        0: true
    }
};

_i.ApplicationManager.getAppMetaData = {
    0: _t.ApplicationId,

    _optional: {
        0: true
    }
};

_i.ApplicationManager.addAppInfoEventListener = {
    0: _t.ApplicationInformationEventCallback
};

_i.ApplicationManager.removeAppInfoEventListener = {
    0: _t.long
};

// Application
_i.Application.exit = null;
_i.Application.hide = null;
_i.Application.getRequestedAppControl = null;

// RequestedApplicationControl
_i.RequestedApplicationControl.replyResult = {
    0: [_t.ApplicationControlData],

    _optional: {
        0: true
    }
};

_i.RequestedApplicationControl.replyFailure = null;

/*
 * Bluetooth
 */

// BluetoothManager
_i.BluetoothManager.getDefaultAdapter = null;

// BluetoothAdapter
_i.BluetoothAdapter.setName = {
    0: _t.DOMString,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.BluetoothAdapter.setPowered = {
    0: _t.boolean,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.BluetoothAdapter.setVisible = {
    0: _t.boolean,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,
    3: _t.unsigned_short,

    _optional: {
        1: true,
        2: true,
        3: true
    }
};

_i.BluetoothAdapter.setChangeListener = {
    0: _t.BluetoothAdapterChangeCallback
};

_i.BluetoothAdapter.unsetChangeListener = null;

_i.BluetoothAdapter.discoverDevices = {
    0: _t.BluetoothDiscoverDevicesSuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        1: true
    }
};

_i.BluetoothAdapter.stopDiscovery = {
    0: _t.SuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        0: true,
        1: true
    }
};

_i.BluetoothAdapter.getKnownDevices = {
    0: _t.BluetoothDeviceArraySuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        1: true
    }
};

_i.BluetoothAdapter.getDevice = {
    0: _t.BluetoothAddress,
    1: _t.BluetoothDeviceSuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

_i.BluetoothAdapter.createBonding = {
    0: _t.BluetoothAddress,
    1: _t.BluetoothDeviceSuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

_i.BluetoothAdapter.destroyBonding = {
    0: _t.BluetoothAddress,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.BluetoothAdapter.registerRFCOMMServiceByUUID = {
    0: _t.BluetoothUUID,
    1: _t.DOMString,
    2: _t.BluetoothServiceSuccessCallback,
    3: _t.ErrorCallback,

    _optional: {
        3: true
    }
};

_i.BluetoothAdapter.getBluetoothProfileHandler = {
    0: _t.BluetoothProfileType
};

// BluetoothDevice
_i.BluetoothDevice.connectToServiceByUUID = {
    0: _t.BluetoothUUID,
    1: _t.BluetoothSocketSuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

// BluetoothSocket
_i.BluetoothSocket.readData = null;
_i.BluetoothSocket.close = null;

_i.BluetoothSocket.writeData = {
    0: [_t.byte]
};

// BluetoothClass
_i.BluetoothClass.hasService = {
    0: _t.unsigned_short
};

// BluetoothServiceHandler
_i.BluetoothServiceHandler.unregister = {
    0: _t.SuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        0: true,
        1: true
    }
};

// BluetoothHealthProfileHandler
_i.BluetoothHealthProfileHandler.registerSinkApplication = {
    0: _t.unsigned_short,
    1: _t.DOMString,
    2: _t.BluetoothHealthApplicationSuccessCallback,
    3: _t.ErrorCallback,

    _optional: {
        3: true
    }
};

_i.BluetoothHealthProfileHandler.connectToSource = {
    0: _t.BluetoothDevice,
    1: _t.BluetoothHealthApplication,
    2: _t.BluetoothHealthChannelSuccessCallback,
    3: _t.ErrorCallback,

    _optional: {
        3: true
    }
};

// BluetoothHealthApplication
_i.BluetoothHealthApplication.unregister = {
    0: _t.SuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        0: true,
        1: true
    }
};

// BluetoothHealthChannel
_i.BluetoothHealthChannel.close = null;
_i.BluetoothHealthChannel.unsetListener = null;

_i.BluetoothHealthChannel.sendData = {
    0: [_t.byte]
};

_i.BluetoothHealthChannel.setListener = {
    0: _t.BluetoothHealthChannelChangeCallback
};

/*
 * Bookmark
 */

// BookmarkManager
_i.BookmarkManager.get = {
    0: _t.BookmarkFolder,
    1: _t.boolean,

    _optional: {
        0: true,
        1: true
    }
};

_i.BookmarkManager.add = {
    0: _t.Bookmark,
    1: _t.BookmarkFolder,

    _optional: {
        1: true
    }
};

_i.BookmarkManager.remove = {
    0: _t.Bookmark,

    _optional: {
        0: true
    }
};

/*
 * Calendar
 */

// CalendarManager
_i.CalendarManager.getCalendars = {
    0: _t.CalendarType,
    1: _t.CalendarArraySuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

_i.CalendarManager.getUnifiedCalendar = {
    0: _t.CalendarType
};

_i.CalendarManager.getDefaultCalendar = {
    0: _t.CalendarType
};

_i.CalendarManager.getCalendar = {
    0: _t.CalendarType,
    1: _t.CalendarId
};

// Calendar
_i.Calendar.get = {
    0: _t.CalendarItemId
};

_i.Calendar.add = {
    0: _t.CalendarItem
};

_i.Calendar.addBatch = {
    0: [_t.CalendarItem],
    1: _t.CalendarItemArraySuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.Calendar.update = {
    0: _t.CalendarItem,
    1: _t.boolean,

    _optional: {
        1: true
    }
};

_i.Calendar.updateBatch = {
    0: [_t.CalendarItem],
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,
    3: _t.boolean,

    _optional: {
        1: true,
        2: true,
        3: true
    }
};

_i.Calendar.remove = {
    0: _t.CalendarItemId
};

_i.Calendar.removeBatch = {
    0: [_t.CalendarItemId],
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.Calendar.find = {
    0: _t.CalendarItemArraySuccessCallback,
    1: _t.ErrorCallback,
    2: _t.AbstractFilter,
    3: _t.SortMode,

    _optional: {
        1: true,
        2: true,
        3: true
    }
};

_i.Calendar.addChangeListener = {
    0: _t.CalendarChangeCallback
};

_i.Calendar.removeChangeListener = {
    0: _t.long
};

// CalendarItem
_i.CalendarItem.convertToString = {
    0: _t.CalendarTextFormat
};

_i.CalendarItem.clone = null;

// CalendarEvent
_i.CalendarEvent.expandRecurrence = {
    0: _t.TZDate,
    1: _t.TZDate,
    2: _t.CalendarEventArraySuccessCallback,
    3: _t.ErrorCallback,

    _optional: {
        3: true
    }
};

/*
 * Call History
 */

// CallHistory
_i.CallHistory.find = {
    0: _t.CallHistoryEntryArraySuccessCallback,
    1: _t.ErrorCallback,
    2: _t.AbstractFilter,
    3: _t.SortMode,
    4: _t.unsigned_long,
    5: _t.unsigned_long,

    _optional: {
        // nullable
        1: true,
        2: true,
        3: true,
        4: true,
        5: true
    }
};

_i.CallHistory.remove = {
    0: _t.CallHistoryEntry
};

_i.CallHistory.removeBatch = {
    0: [_t.CallHistoryEntry],
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        // nullable
        1: true,
        2: true
    }
};

_i.CallHistory.removeAll = {
    0: _t.SuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        // nullable
        0: true,
        1: true
    }
};

_i.CallHistory.addChangeListener = {
    0: _t.CallHistoryChangeCallback
};

_i.CallHistory.removeChangeListener = {
    0: _t.long
};

/*
 * Contact
 */

// ContactManager
_i.ContactManager.getAddressBooks = {
    0: _t.AddressBookArraySuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        1: true
    }
};

_i.ContactManager.getUnifiedAddressBook = null;
_i.ContactManager.getDefaultAddressBook = null;

_i.ContactManager.getAddressBook = {
    0: _t.AddressBookId
};

_i.ContactManager.get = {
    0: _t.PersonId
};

_i.ContactManager.update = {
    0: _t.Person
};

_i.ContactManager.updateBatch = {
    0: [_t.Person],
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.ContactManager.remove = {
    0: _t.PersonId
};

_i.ContactManager.removeBatch = {
    0: [_t.PersonId],
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.ContactManager.find = {
    0: _t.PersonArraySuccessCallback,
    1: _t.ErrorCallback,
    2: _t.AbstractFilter,
    3: _t.SortMode,

    _optional: {
        1: true,
        2: true,
        3: true
    }
};

_i.ContactManager.addChangeListener = {
    0: _t.PersonsChangeCallback
};

_i.ContactManager.removeChangeListener = {
    0: _t.long
};

// AddressBook
_i.AddressBook.get = {
    0: _t.ContactId
};

_i.AddressBook.add = {
    0: _t.Contact
};

_i.AddressBook.addBatch = {
    0: [_t.Contact],
    1: _t.ContactArraySuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.AddressBook.update = {
    0: _t.Contact
};

_i.AddressBook.updateBatch = {
    0: [_t.Contact],
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.AddressBook.remove = {
    0: _t.ContactId
};

_i.AddressBook.removeBatch = {
    0: [_t.ContactId],
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.AddressBook.find = {
    0: _t.ContactArraySuccessCallback,
    1: _t.ErrorCallback,
    2: _t.AbstractFilter,
    3: _t.SortMode,

    _optional:{
        1: true,
        2: true,
        3: true
    }
};

_i.AddressBook.addChangeListener = {
    0: _t.AddressBookChangeCallback,
    1: _t.ErrorCallback,

    _optional: {
        1: true
    }
};

_i.AddressBook.removeChangeListener = {
    0: _t.long
};

_i.AddressBook.getGroup = {
    0: _t.ContactGroupId
};

_i.AddressBook.addGroup = {
    0: _t.ContactGroup
};

_i.AddressBook.updateGroup = {
    0: _t.ContactGroup
};

_i.AddressBook.removeGroup = {
    0: _t.ContactGroupId
};

_i.AddressBook.getGroups = null;

// Person
_i.Person.link = {
    0: _t.PersonId
};

_i.Person.unlink = {
    0: _t.ContactId
};

// Contact
_i.Contact.convertToString = {
    0: _t.ContactTextFormat,

    _optional: {
        0: true
    }
};

_i.Contact.clone = null;

/*
 * Content
 */

// ContentManager
_i.ContentManager.update = {
    0: _t.Content
};

_i.ContentManager.updateBatch = {
    0: [_t.Content],
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.ContentManager.getDirectories = {
    0: _t.ContentDirectoryArraySuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        1: true
    }
};

_i.ContentManager.find = {
    0: _t.ContentArraySuccessCallback,
    1: _t.ErrorCallback,
    2: _t.ContentDirectoryId,
    3: _t.AbstractFilter,
    4: _t.SortMode,
    5: _t.unsigned_long,
    6: _t.unsigned_long,

    _optional: {
        1: true,
        2: true,
        3: true,
        4: true,
        5: true,
        6: true
    }
};

_i.ContentManager.scanFile = {
    0: _t.DOMString,
    1: _t.ContentScanSuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.ContentManager.setChangeListener = {
    0: _t.ContentChangeCallback
};

_i.ContentManager.unsetChangeListener = null;

/*
 * Data Control
 */

// DataControlManager
_i.DataControlManager.getDataControlConsumer = {
    0: _t.DOMString,
    1: _t.DOMString,
    2: _t.DataType
};

// SQLDataControlConsumer
_i.SQLDataControlConsumer.insert = {
    0: _t.unsigned_long,
    1: _t.RowData,
    2: _t.DataControlInsertSuccessCallback,
    3: _t.DataControlErrorCallback,

    _optional: {
        2: true,
        3: true
    }
};

_i.SQLDataControlConsumer.update = {
    0: _t.unsigned_long,
    1: _t.RowData,
    2: _t.DOMString,
    3: _t.DataControlSuccessCallback,
    4: _t.DataControlErrorCallback,

    _optional: {
        3: true,
        4: true
    }
};

_i.SQLDataControlConsumer.remove = {
    0: _t.unsigned_long,
    1: _t.DOMString,
    2: _t.DataControlSuccessCallback,
    3: _t.DataControlErrorCallback,

    _optional: {
        2: true,
        3: true
    }
};

_i.SQLDataControlConsumer.select = {
    0: _t.unsigned_long,
    1: [_t.DOMString],
    2: _t.DOMString,
    3: _t.DataControlSelectSuccessCallback,
    4: _t.DataControlErrorCallback,
    5: _t.unsigned_long,
    6: _t.unsigned_long,

    _optional: {
        4: true,
        5: true,
        6: true
    }
};

// MappedDataControlConsumer
_i.MappedDataControlConsumer.addValue = {
    0: _t.unsigned_long,
    1: _t.DOMString,
    2: _t.DOMString,
    3: _t.DataControlSuccessCallback,
    4: _t.DataControlErrorCallback,

    _optional: {
        3: true,
        4: true
    }
};

_i.MappedDataControlConsumer.removeValue = {
    0: _t.unsigned_long,
    1: _t.DOMString,
    2: _t.DOMString,
    3: _t.DataControlSuccessCallback,
    4: _t.DataControlErrorCallback,

    _optional: {
        4: true
    }
};

_i.MappedDataControlConsumer.getValue = {
    0: _t.unsigned_long,
    1: _t.DOMString,
    2: _t.DataControlGetValueSuccessCallback,
    3: _t.DataControlErrorCallback,

    _optional: {
        3: true
    }
};

_i.MappedDataControlConsumer.updateValue = {
    0: _t.unsigned_long,
    1: _t.DOMString,
    2: _t.DOMString,
    3: _t.DOMString,
    4: _t.DataControlSuccessCallback,
    5: _t.DataControlErrorCallback,

    _optional: {
        5: true
    }
};

/*
 * Data Synchronization
 */

// DataSynchronizationManager
_i.DataSynchronizationManager.getMaxProfilesNum = null;
_i.DataSynchronizationManager.getProfilesNum    = null;
_i.DataSynchronizationManager.getAll            = null;

_i.DataSynchronizationManager.add = {
    0: _t.SyncProfileInfo
};

_i.DataSynchronizationManager.update = {
    0: _t.SyncProfileInfo
};

_i.DataSynchronizationManager.remove = {
    0: _t.SyncProfileId
};

_i.DataSynchronizationManager.get = {
    0: _t.SyncProfileId
};

_i.DataSynchronizationManager.startSync = {
    0: _t.SyncProfileId,
    1: _t.SyncProgressCallback,

    _optional: {
        1: true
    }
};

_i.DataSynchronizationManager.stopSync = {
    0: _t.SyncProfileId
};

_i.DataSynchronizationManager.getLastSyncStatistics = {
    0: _t.SyncProfileId
};

/*
 * Download
 */

// DownloadManager
_i.DownloadManager.start = {
    0: _t.DownloadRequest,
    1: _t.DownloadCallback,

    _optional: {
        1: true
    }
};

_i.DownloadManager.cancel = {
    0: _t.long
};

_i.DownloadManager.pause = {
    0: _t.long
};

_i.DownloadManager.resume = {
    0: _t.long
};

_i.DownloadManager.getState = {
    0: _t.long
};

_i.DownloadManager.getDownloadRequest = {
    0: _t.long
};

_i.DownloadManager.getMIMEType = {
    0: _t.long
};

_i.DownloadManager.setListener = {
    0: _t.long,
    1: _t.DownloadCallback
};

/*
 * Network Bearer Selection
 */

// NetworkBearerSelection
_i.NetworkBearerSelection.requestRouteToHost = {
    0: _t.NetworkType,
    1: _t.DOMString,
    2: _t.NetworkSuccessCallback,
    3: _t.ErrorCallback,

    _optional: {
        3: true
    }
};

_i.NetworkBearerSelection.releaseRouteToHost = {
    0: _t.NetworkType,
    1: _t.DOMString,
    2: _t.SuccessCallback,
    3: _t.ErrorCallback,

    _optional: {
        3: true
    }
};

/*
 * NFC
 */

// NFCManager
_i.NFCManager.getDefaultAdapter = null;
_i.NFCManager.setExclusiveMode = {
    0: _t.boolean
};

// NFCAdapter
_i.NFCAdapter.setPowered = {
    0: _t.boolean,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.NFCAdapter.setTagListener = {
    0: _t.NFCTagDetectCallback,
    1: [_t.NFCTagType],

    _optional: {
        1: true
    }
};

_i.NFCAdapter.setPeerListener = {
    0: _t.NFCPeerDetectCallback
};

_i.NFCAdapter.unsetTagListener  = null;
_i.NFCAdapter.unsetPeerListener = null;
_i.NFCAdapter.getCachedMessage  = null;

// NFCTag
_i.NFCTag.readNDEF = {
    0: _t.NDEFMessageReadCallback,
    1: _t.ErrorCallback,

    _optional: {
        1: true
    }
};

_i.NFCTag.writeNDEF = {
    0: _t.NDEFMessage,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.NFCTag.transceive = {
    0: [_t.byte],
    1: _t.ByteArraySuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

// NFCPeer
_i.NFCPeer.setReceiveNDEFListener = {
    0: _t.NDEFMessageReadCallback
};

_i.NFCPeer.unsetReceiveNDEFListener = null;

_i.NFCPeer.sendNDEF = {
    0: _t.NDEFMessage,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

// NDEFMessage
_i.NDEFMessage.toByte = null;

/*
 * Notification
 */

// NotificationManager
_i.NotificationManager.post = {
    0: _t.Notification
};

_i.NotificationManager.update = {
    0: _t.Notification
};

_i.NotificationManager.remove = {
    0: _t.NotificationId
};

_i.NotificationManager.get = {
    0: _t.NotificationId
};

_i.NotificationManager.removeAll = null;
_i.NotificationManager.getAll = null;

/*
 * Package
 */

// PackageManager
_i.PackageManager.install = {
    0: _t.DOMString,
    1: _t.PackageProgressCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

_i.PackageManager.uninstall = {
    0: _t.PackageId,
    1: _t.PackageProgressCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

_i.PackageManager.getPackagesInfo = {
    0: _t.PackageInformationArraySuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        1: true
    }
};

_i.PackageManager.getPackageInfo = {
    0: _t.PackageId,

    _optional: {
        0: true
    }
};

_i.PackageManager.setPackageInfoEventListener = {
    0: _t.PackageInfomationEventCallback
};

_i.PackageManager.unsetPackageInfoEventListener = null;

/*
 * Power
 */

// PowerManager
_i.PowerManager.request = {
    0: _t.PowerResource,
    1: _t.PowerState
};

_i.PowerManager.release = {
    0: _t.PowerResource
};

_i.PowerManager.setScreenStateChangeListener = {
    0: _t.ScreenStateChangeCallback
};

_i.PowerManager.unsetScreenStateChangeListener = null;

_i.PowerManager.getScreenBrightness = null;

_i.PowerManager.setScreenBrightness = {
    0: _t.double
};

_i.PowerManager.isScreenOn = null;

_i.PowerManager.restoreScreenBrightness = null;

_i.PowerManager.turnScreenOn = null;

_i.PowerManager.turnScreenOff = null;

/*
 * Push
 */

// PushManager
_i.PushManager.registerService = {
    0: _t.ApplicationControl,
    1: _t.PushRegisterSuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

_i.PushManager.unregisterService = {
    0: _t.SuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        0: true,
        1: true
    }
};

_i.PushManager.connectService = {
    0: _t.PushNotificationCallback
};

_i.PushManager.disconnectService = null;
_i.PushManager.getRegistrationId = null;

/*
 * System Info
 */

// SystemInfo
_i.SystemInfo.getCapabilities = null;

_i.SystemInfo.getPropertyValue = {
    0: _t.SystemInfoPropertyId,
    1: _t.SystemInfoPropertySuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

_i.SystemInfo.addPropertyValueChangeListener = {
    0: _t.SystemInfoPropertyId,
    1: _t.SystemInfoPropertySuccessCallback,
    2: _t.SystemInfoOptions,

    _optional: {
        2: true
    }
};

_i.SystemInfo.removePropertyValueChangeListener = {
    0: _t.unsigned_long
};

/*
 * System Setting
 */

// SystemSettingManager
_i.SystemSettingManager.setProperty = {
    0: _t.SystemSettingType,
    1: _t.DOMString,
    2: _t.SuccessCallback,
    3: _t.ErrorCallback,

    _optional: {
        3: true
    }
};

_i.SystemSettingManager.getProperty = {
    0: _t.SystemSettingType,
    1: _t.SystemSettingSuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        2: true
    }
};

/*
 * Time
 */

// TimeUtil
_i.TimeUtil.getCurrentDateTime    = null;
_i.TimeUtil.getLocalTimezone      = null;
_i.TimeUtil.getAvailableTimezones = null;
_i.TimeUtil.getTimeFormat         = null;

_i.TimeUtil.getDateFormat = {
    0: _t.boolean,

    _optional: {
        0: true
    }
};

_i.TimeUtil.isLeapYear = {
    0: _t.long
};

// TimeDuration
_i.TimeDuration.difference = {
    0: _t.TimeDuration
};

_i.TimeDuration.equalsTo = {
    0: _t.TimeDuration
};

_i.TimeDuration.lessThan = {
    0: _t.TimeDuration
};

_i.TimeDuration.greaterThan = {
    0: _t.TimeDuration
};

/*
 * Web Setting
 */

// WebSettingManager
_i.WebSettingManager.setUserAgentString = {
    0: _t.DOMString,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        1: true,
        2: true
    }
};

_i.WebSettingManager.removeAllCookies = {
    0: _t.SuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        0: true,
        1: true
    }
};

// Exports
_t.constructor = _c;
_t.interface   = _i;

module.exports = _t;

});
define('ripple/platform/tizen/2.0/vibration', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    deviceSettings = require('ripple/deviceSettings'),
    constants = require('ripple/constants'),
    tizen1_utils = require('ripple/platform/tizen/2.0/tizen1_utils'),
    emulatorBridge = require('ripple/emulatorBridge'),
    curPost,
    _self;

function isVibratorOn() {
    return deviceSettings.retrieve("Config.vibratingMode");
}

var vibrator = (function () {
    var vibratorPattern,
        isVibrating = false,
        runTime = 0,
        vibrateTimeout = null,
        MILLILSECONDS_OF_ONE_VIBRATION = 100,
        node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
        movementIndex = 0,
        movement = [{ left: -10 }, { left: 0 }, { left: 10 }, { left: 0 },
                    {top: -10 }, { top: 0 }, {top: 10 }, { top: 0 }];

    function _clearTimeout() {
        if (vibrateTimeout) {
            clearInterval(vibrateTimeout);
            vibrateTimeout = null;
        }
    }

    function stopVibrate() {
        isVibrating = false;
        _clearTimeout();
        node.css({left: 0, top: 0}, MILLILSECONDS_OF_ONE_VIBRATION);
    }

    function vibrate() {
        node.css(movement[movementIndex]);
        movementIndex = (movementIndex + 1) % 8;
    }

    function changePulse() {
        if (emulatorBridge.document().hidden) {
            return;
        }

        //run time
        runTime = runTime + MILLILSECONDS_OF_ONE_VIBRATION;
        if (curPost >= vibratorPattern.length) {
            setTimeout(stopVibrate, 1);
        }
        if (runTime > vibratorPattern[curPost]) {
            curPost = curPost + 1;
            runTime = 0;
        } else {
            if ((curPost % 2) === 0) {
                vibrate();
            }
        }
    }

    function startVibrate(_pattern) {
        if (!isVibratorOn())
            return;

        vibratorPattern = _pattern;
        _clearTimeout();
        movementIndex = 0;
        if (_pattern) {
            runTime = 0;
            vibrateTimeout = setInterval(changePulse, MILLILSECONDS_OF_ONE_VIBRATION);
        }
        isVibrating = true;
    }

    return {
        isVibrating: isVibrating,
        startVibrate: startVibrate,
        stopVibrate: stopVibrate
    };
}());

_self = {
    vibrate: function () {
        var pattern = arguments[0],
            i;

        // If vibrator is off, stop the vibration
        event.on("VibratingModeChanged", function (value) {
            if (value === false) {
                vibrator.stopVibrate();
            }
        });

        //1. If the hidden attribute [PAGE-VISIBILITY] is set to true, abort these steps.
        if (emulatorBridge.document().hidden) {
            return;
        }

        //2. Let pattern be the value of the first argument.
        if (!tizen1_utils.isValidArray(pattern)) {
            pattern |= 0;
        } else {
            for (i = 0; i < pattern.length; i++) {
                pattern[i] |= 0;
            }
        }

        //3. If pattern is 0, or an empty list, cancel the pre-existing instance of the processing vibration patterns algorithm, if any, and abort these steps.
        if (pattern === 0 || (tizen1_utils.isValidArray(pattern) && pattern.length === 0)) {
            vibrator.stopVibrate();
            return;
        }

        //4. If pattern is a list, proceed to the next step. Otherwise run the following substeps:
        //a. Let list be an initially empty list, and add pattern to list.
        //b. Let pattern be list.
        if (!tizen1_utils.isValidArray(pattern)) {
            pattern = [pattern];
        }

        //5. If any entry of pattern exceeds an implementation-dependent limit, then the user agent may throw a NotSupportedError exception and abort these steps.

        //6. If the length of pattern is even, then remove the last entry in pattern.
        if (pattern.length % 2 === 0) {
            pattern.pop();
        }

        //7. Cancel the pre-existing instance of the processing vibration patterns algorithm, if any.
        if (vibrator.isVibrating) {
            vibrator.stopVibrate();
        }

        curPost = 0;
        vibrator.startVibrate(pattern);
    }
};

module.exports = _self;

});
define('ripple/platform/tizen/2.0/websetting', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/tizen/2.0/errorcode'),
    t = require('ripple/platform/tizen/2.0/typecast'),
    WebAPIError = require('ripple/platform/tizen/2.0/WebAPIError'),
    WebAPIException = require('ripple/platform/tizen/2.0/WebAPIException'),
    _data = {
        userAgent: null
    },
    _security = {
        "http://tizen.org/privilege/websetting": ["removeAllCookies"]
    },
    _self;

function _isInvalidString(str) {
    str = str.trim();

    return (/\t|\n|\r|\v/.test(str)) || (str.length === 0);
}

function _clearAllCookies() {
    var cookies = document.cookie.split(";"),
        i, equalPos, name;

    for (i = 0; i < cookies.length; i++) {
        equalPos = cookies[i].indexOf("=");
        name = (equalPos > -1) ? cookies[i].substr(0, equalPos) : cookies[i];

        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
}

_self = function () {
    var websetting;

    function setUserAgentString(userAgent, successCallback, errorCallback) {
        t.WebSettingManager("setUserAgentString", arguments, true);

        window.setTimeout(function () {
            if (_isInvalidString(userAgent)) {
                if (errorCallback) {
                    errorCallback(new WebAPIError(errorcode.INVALID_VALUES_ERR));
                }
                return;
            }

            if (_data.userAgent === null) {
                navigator.__defineGetter__("userAgent", function() {
                    return _data.userAgent;
                });
            }

            _data.userAgent = userAgent;

            successCallback();
        }, 1);
    }

    function removeAllCookies(successCallback, errorCallback) {
        if (!_security.removeAllCookies) {
            throw new WebAPIException(errorcode.SECURITY_ERR);
        }

        t.WebSettingManager("removeAllCookies", arguments);

        window.setTimeout(function () {
            _clearAllCookies();
            successCallback();
        }, 1);
    }

    function handleSubFeatures(subFeatures) {
        var i, subFeature;

        for (subFeature in subFeatures) {
            for (i in _security[subFeature]) {
                _security[_security[subFeature][i]] = true;
            }
        }
    }

    websetting = {
        setUserAgentString: setUserAgentString,
        removeAllCookies: removeAllCookies,
        handleSubFeatures: handleSubFeatures
    };

    return websetting;
};

module.exports = _self;

});
define('ripple/platform/tv/1.0/WebAPIError', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/wearable/2.0/errorcode');

var msg = {
        0: "Generic Error",
        1: "Index or size is negative, or greater than the allowed value.",
        2: "Specified range of text does not fit into a DOMString.",
        3: "Node is inserted somewhere it doesn't belong.",
        4: "Node is used in a different document than the one that created it (that doesn't support it).",
        5: "An invalid or illegal character is specified.",
        6: "Data is specified for a Node which does not support data.",
        7: "An attempt is made to modify an object where modifications are not allowed.",
        8: "An attempt is made to reference a Node in a context where it does not exist.",
        9: "The implementation does not support the requested type of object or operation.",
        10: "An attempt is made to add an attribute that is already in use elsewhere.",
        11: "An attempt is made to use an object that is not, or is no longer, usable.",
        12: "An invalid or illegal string is specified.",
        13: "An attempt is made to modify the type of the underlying object.",
        14: "An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.",
        15: "A parameter or an operation is not supported by the underlying object.",
        16: "A call to a method such as insertBefore or removeChild would make the Node invalid with respect to \"partial validity\", this exception would be raised and the operation would not be done.",
        17: "The type of an object is incompatible with the expected type of the parameter associated to the object.",
        18: "An attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.",
        19: "A network error occurs in synchronous requests.",
        20: "The abort error occurs in asynchronous requests by user prompt.",
        21: "The operation could not be completed because the URL does not match.",
        22: "The quota has been exceeded.",
        23: "The operation timed out.",
        24: "The supplied node is incorrect or has an incorrect ancestor for this operation.",
        25: "The object can not be cloned.",
        99: "The content of an object does not include valid values.",
        100: "Error occurred in communication with the underlying implementation that meant the requested method could not complete.",
        111: "Requested service is not available.",
        112: "The authentication token of remote peer agent is not generated."
    },
    errType = {
        0: "UnknownError",
        1: "IndexSizeError",
        2: "DOMStringSizeError",
        3: "HierarchyRequestError",
        4: "WrongDocumentError",
        5: "InvalidCharacterError",
        6: "NoDataAllowedError",
        7: "NoModificationAllowedError",
        8: "NotFoundError",
        9: "NotSupportedError",
        10: "InuseAttributeError",
        11: "InvalidStateError",
        12: "SyntaxError",
        13: "InvalidModificationError",
        14: "NamespaceError",
        15: "InvalidAccessError",
        16: "ValidationError",
        17: "TypeMismatchError",
        18: "SecurityError",
        19: "NetworkError",
        20: "AbortError",
        21: "URLMismatchError",
        22: "QuotaExceededError",
        23: "TimeoutError",
        24: "InvalidNodeTypeError",
        25: "DataCloneError",
        99: "InvalidValuesError",
        100: "IOError",
        111: "ServiceNotAvailableError",
        112: "TokenNotGeneratedError"
    };

/*
 support 3 types of error:
 - WebAPIError()
 code = errorcode.UNKNOWN_ERR
 message = errorcode.message[UNKNOWN_ERR]
 - WebAPIError(errorcode."TYPE_MISMATCH_ERR")
 code = 17
 message = errorcode.message[17]
 - WebAPIError(my_own_error_code, "This is my error message.")
 code = my_own_error_code(number)
 message = "This is my error message."
 */

module.exports = function (code, message, name) {
    var _code, _message, _name;

    if (typeof code !== 'number') {
        _code = errorcode.UNKNOWN_ERR;
        _message = msg[_code];
        _name = errType[_code];
    } else {
        _code = code;
        if (typeof message === 'string') {
            _message = message;
        } else {
            _message = msg[_code];
        }
        if (typeof name === 'string') {
            _name = name;
        } else {
            _name = errType[_code];
        }
    }

    this.__defineGetter__("code", function () {
        return _code;
    });
    this.__defineGetter__("message", function () {
        return _message;
    });
    this.__defineGetter__("name", function () {
        return _name;
    });
};

});
define('ripple/platform/tv/1.0/WebAPIException', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/wearable/2.0/errorcode');

var msg = {
        0: "Generic Error",
        1: "Index or size is negative, or greater than the allowed value.",
        2: "Specified range of text does not fit into a DOMString.",
        3: "Node is inserted somewhere it doesn't belong.",
        4: "Node is used in a different document than the one that created it (that doesn't support it).",
        5: "An invalid or illegal character is specified.",
        6: "Data is specified for a Node which does not support data.",
        7: "An attempt is made to modify an object where modifications are not allowed.",
        8: "An attempt is made to reference a Node in a context where it does not exist.",
        9: "The implementation does not support the requested type of object or operation.",
        10: "An attempt is made to add an attribute that is already in use elsewhere.",
        11: "An attempt is made to use an object that is not, or is no longer, usable.",
        12: "An invalid or illegal string is specified.",
        13: "An attempt is made to modify the type of the underlying object.",
        14: "An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.",
        15: "A parameter or an operation is not supported by the underlying object.",
        16: "A call to a method such as insertBefore or removeChild would make the Node invalid with respect to \"partial validity\", this exception would be raised and the operation would not be done.",
        17: "The type of an object is incompatible with the expected type of the parameter associated to the object.",
        18: "An attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.",
        19: "A network error occurs in synchronous requests.",
        20: "The abort error occurs in asynchronous requests by user prompt.",
        21: "The operation could not be completed because the URL does not match.",
        22: "The quota has been exceeded.",
        23: "The operation timed out.",
        24: "The supplied node is incorrect or has an incorrect ancestor for this operation.",
        25: "The object can not be cloned.",
        99: "The content of an object does not include valid values.",
        100: "Error occurred in communication with the underlying implementation that meant the requested method could not complete.",
        111: "Requested service is not available.",
        112: "The authentication token of remote peer agent is not generated."
    },
    errType = {
        0: "UnknownError",
        1: "IndexSizeError",
        2: "DOMStringSizeError",
        3: "HierarchyRequestError",
        4: "WrongDocumentError",
        5: "InvalidCharacterError",
        6: "NoDataAllowedError",
        7: "NoModificationAllowedError",
        8: "NotFoundError",
        9: "NotSupportedError",
        10: "InuseAttributeError",
        11: "InvalidStateError",
        12: "SyntaxError",
        13: "InvalidModificationError",
        14: "NamespaceError",
        15: "InvalidAccessError",
        16: "ValidationError",
        17: "TypeMismatchError",
        18: "SecurityError",
        19: "NetworkError",
        20: "AbortError",
        21: "URLMismatchError",
        22: "QuotaExceededError",
        23: "TimeoutError",
        24: "InvalidNodeTypeError",
        25: "DataCloneError",
        99: "InvalidValuesError",
        100: "IOError",
        111: "ServiceNotAvailableError",
        112: "TokenNotGeneratedError"
    };

/*
 support 3 types of error:
 - WebAPIError()
 code = errorcode.UNKNOWN_ERR
 message = errorcode.message[UNKNOWN_ERR]
 - WebAPIError(errorcode."TYPE_MISMATCH_ERR")
 code = 17
 message = errorcode.message[17]
 - WebAPIError(my_own_error_code, "This is my error message.")
 code = my_own_error_code(number)
 message = "This is my error message."
 */

module.exports = function (code, message, name) {
    var _code, _message, _name;

    if (typeof code !== 'number') {
        _code = errorcode.UNKNOWN_ERR;
        _message = msg[_code];
        _name = errType[_code];
    } else {
        _code = code;
        if (typeof message === 'string') {
            _message = message;
        } else {
            _message = msg[_code];
        }
        if (typeof name === 'string') {
            _name = name;
        } else {
            _name = errType[_code];
        }
    }

    this.__defineGetter__("code", function () {
        return _code;
    });
    this.__defineGetter__("message", function () {
        return _message;
    });
    this.__defineGetter__("name", function () {
        return _name;
    });
};

});
define('ripple/platform/tv/1.0/dbinit', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 exception = require('ripple/exception'),
    DBBuilder,
    _data = {
        dbBuilder: null
    },
    _self = {};

function _initialize() {
    _data.dbBuilder = new DBBuilder();
}

DBBuilder = function () {
    var self;

    // private
    function formatString(str) {
        return str.replace(/^\s+|[\t\n\r\v]+|\s+$/g, "").replace(/\s+/g, "");
    }

    // private
    function formatHex(str) {
        return str.replace(/,(0x[0-9a-fA-F]+?),/g, ',"$1",');
    }

    // public
    function register(type, dbFile, Extension) {
        _data[type] = Extension ? new Extension() : {};

        if (!dbFile)
            return;

        _self.__defineGetter__(type, function () {
            var fnInit;

            if (!_data[type].db) {
                fnInit = _data[type].initdb || initdb;
                _data[type].db = fnInit(dbFile);
            }

            return _data[type].db;
        });
    }

    function initdb(dbFile) {
        var xmlHttp, res;

        try {
            xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", "dbsamples/" + dbFile, false);
            xmlHttp.send();
        } catch (e) {
            exception.handle(e);
        }

        if (!xmlHttp.responseText) {
            return null;
        }

        res = formatHex(formatString(xmlHttp.responseText));

        return JSON.parse(res);
    }

    self = {
        register: register,
        initdb:   initdb
    };

    return self;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/tv/1.0/errorcode', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 _self = {};

_self.__defineGetter__("UNKNOWN_ERR", function () {
    return 0;
});

_self.__defineGetter__("INDEX_SIZE_ERR", function () {
    return 1;
});

_self.__defineGetter__("DOMSTRING_SIZE_ERR", function () {
    return 2;
});

_self.__defineGetter__("HIERARCHY_REQUEST_ERR", function () {
    return 3;
});

_self.__defineGetter__("WRONG_DOCUMENT_ERR", function () {
    return 4;
});

_self.__defineGetter__("INVALID_CHARACTER_ERR", function () {
    return 5;
});

_self.__defineGetter__("NO_DATA_ALLOWED_ERR", function () {
    return 6;
});

_self.__defineGetter__("NO_MODIFICATION_ALLOWED_ERR", function () {
    return 7;
});

_self.__defineGetter__("NOT_FOUND_ERR", function () {
    return 8;
});

_self.__defineGetter__("NOT_SUPPORTED_ERR", function () {
    return 9;
});

_self.__defineGetter__("INUSE_ATTRIBUTE_ERR", function () {
    return 10;
});

_self.__defineGetter__("INVALID_STATE_ERR", function () {
    return 11;
});

_self.__defineGetter__("SYNTAX_ERR", function () {
    return 12;
});

_self.__defineGetter__("INVALID_MODIFICATION_ERR", function () {
    return 13;
});

_self.__defineGetter__("NAMESPACE_ERR", function () {
    return 14;
});

_self.__defineGetter__("INVALID_ACCESS_ERR", function () {
    return 15;
});

_self.__defineGetter__("VALIDATION_ERR", function () {
    return 16;
});

_self.__defineGetter__("TYPE_MISMATCH_ERR", function () {
    return 17;
});

_self.__defineGetter__("SECURITY_ERR", function () {
    return 18;
});

_self.__defineGetter__("NETWORK_ERR", function () {
    return 19;
});

_self.__defineGetter__("ABORT_ERR", function () {
    return 20;
});

_self.__defineGetter__("URL_MISMATCH_ERR", function () {
    return 21;
});

_self.__defineGetter__("QUOTA_EXCEEDED_ERR", function () {
    return 22;
});

_self.__defineGetter__("TIMEOUT_ERR", function () {
    return 23;
});

_self.__defineGetter__("INVALID_NODE_TYPE_ERR", function () {
    return 24;
});

_self.__defineGetter__("DATA_CLONE_ERR", function () {
    return 25;
});

_self.__defineGetter__("INVALID_VALUES_ERR", function () {
    return 99;
});

_self.__defineGetter__("IO_ERR", function () {
    return 100;
});

_self.__defineGetter__("SERVICE_NOT_AVAILABLE_ERR", function () {
    return 111;
});

_self.__defineGetter__("TOKEN_NOT_GENERATED_ERR", function () {
    return 112;
});

module.exports = _self;


});
define('ripple/platform/tv/1.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2014 Research In Motion Limited.
 *  Copyright 2014 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    constants = require('ripple/constants');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (configValidationObject) {
        var valid = true;
        // no xmlns:JIL in wac 2.0 spec
        valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;

        return valid;
    },
    extractInfo: function (configValidationObject) {
        if (!configValidationObject) {
            return null;
        }

        var widgetInfo = {},
            configFeatures,
            configPreferences,
            preferenceName,
            platform, rst, i, j,
            settingRst = {
                'screen-orientation': 'portrait',
                'context-menu': 'enable',
                'background-support': 'disable',
                encryption: 'disable',
                'install-location': 'auto',
                'hwkey-event': 'enable'
            };

        widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
        widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
        widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
        if (configValidationObject.widget.children.application.validationResult[0].valid) {
            widgetInfo.tizenAppId = configValidationObject.widget.children.application.validationResult[0].attributes.id.value;
            widgetInfo.tizenPackageId = configValidationObject.widget.children.application.validationResult[0].attributes.package.value;
        }

        widgetInfo.features = {};

        if (configValidationObject.widget.children.setting.hasOwnProperty('validationResult') === true) {
            rst = configValidationObject.widget.children.setting.validationResult;
            // the first one has higher priority per platform implementation
            for (i = rst.length -1 ; i >= 0; i--) {
                if (rst[i].valid === true) {
                    for (j in rst[i].attributes) {
                        if (rst[i].attributes[j].value !== undefined) {
                            settingRst[j] = rst[i].attributes[j].value;
                        }
                    }
                }
            }
            db.save("layout", settingRst["screen-orientation"]);
        }

        configFeatures = configValidationObject.widget.children.feature.validationResult;
        utils.forEach(configFeatures, function (f) {
            if (f.valid === true) {
                var feature = {id: f.attributes.name.value,
                         required: f.attributes.required.valid};
                widgetInfo.features[feature.id] = feature;
            }
        });

        widgetInfo.metadata = {};
        if (configValidationObject.widget.children.metadata.hasOwnProperty('validationResult') === true) {
            widgetInfo.metadata.key = configValidationObject.widget.children.metadata.validationResult[0].attributes.key.value;
            widgetInfo.metadata.value = configValidationObject.widget.children.metadata.validationResult[0].attributes.value.value;
        }
        
        widgetInfo.category = {};
        if (configValidationObject.widget.children.category.hasOwnProperty('validationResult') === true) {
            widgetInfo.metadata.name = configValidationObject.widget.children.category.validationResult[0].attributes.name.value;
        }

        widgetInfo.preferences = {};

        configPreferences = configValidationObject.widget.children.preference.validationResult;

        platform = require('ripple/platform');
        utils.forEach(configPreferences, function (preference) {
            preferenceName = preference.attributes.name.value;
            if (preferenceName) {
                widgetInfo.preferences[preferenceName] = {
                    "key": preferenceName,
                    "value": preference.attributes.value.value || "",
                    "readonly": preference.attributes.readonly.value === "true"
                };

                db.save(preferenceName,
                        widgetInfo.preferences[preferenceName].value,
                        platform.getPersistencePrefix(widgetInfo.id));
            }
        });

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in the configuration document and may have the following child elments: name,description,icon,author,license,content,feature and preference.The \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xmlns:tizen": {
                    attributeName: "xmlns:tizen",
                    required: false,
                    type: "list",
                    listValues: ["http://tizen.org/ns/widgets"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                },
                dir: {
                    attributeName: "dir",
                    required: false,
                    type: "list",
                    listValues: ["ltr", "rtl", "lro", "rlo"]
                },
                id: {
                    attributeName: "id",
                    required: false,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    required: false,
                    type: "string"
                },
                height: {
                    attributeName: "height",
                    required: false,
                    type: "integer"
                },
                width: {
                    attributeName: "width",
                    required: false,
                    type: "integer"
                },
                viewmodes: {
                    attributeName: "viewmodes",
                    required: false,
                    type: "list",
                    listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
                },
                defaultlocale: {
                    attributeName: "defaultlocale",
                    required: false,
                    type: "iso-language"
                }
            },
            children: {
                name: {
                    nodeName: "name",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        "short": {
                            attributeName: "short",
                            required: false,
                            type: "string"
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.URL
                        },
                        email: {
                            attributeName: "email",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.EMAIL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        width: {
                            attributeName: "width",
                            required: false,
                            type: "integer"
                        },
                        height: {
                            attributeName: "height",
                            required: false,
                            type: "integer"
                        }
                    }
                },
                content: {
                    nodeName: "content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        encoding: {
                            attributeName: "encoding",
                            required: false,
                            type: "string"
                        },
                        type: {
                            attributeName: "type",
                            required: false,
                            type: "string"
                        }
                    }
                },
                setting: {
                    nodeName: "tizen:setting",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        'screen-orientation': {
                            attributeName: "screen-orientation",
                            required: false,
                            type: "list",
                            listValues: ['portrait', 'landscape', 'auto']
                        },
                        'context-menu': {
                            attributeName: "context-menu",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'background-support': {
                            attributeName: "background-support",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'encryption': {
                            attributeName: "encryption",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'install-location': {
                            attributeName: "install-location",
                            required: false,
                            type: "list",
                            listValues: ['auto', 'internal-only', 'perfer-external']
                        },
                        'hwkey-event': {
                            attributeName: "hwkey-event",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        }
                    }
                },
                application: {
                    nodeName: "tizen:application",
                    required: true,
                    occurrence: 1,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            type: "string"
                        },
                        required_version: {
                            attributeName: "required_version",
                            required: true,
                            type: "list",
                            listValues: ['1.0', '2.0', '2.1', '2.2']
                        },
                        package: {
                            attributeName: "package",
                            required: false,
                            type: "string"
                        }
                    }
                },
                "tizen:content": {
                    nodeName: "tizen:content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        }
                    }
                },
                control: {
                    nodeName: "tizen:app-control",
                    required: false,
                    occurrence: 0,
                    children: {
                        src: {
                            nodeName: "tizen:src",
                            required: true,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        operation: {
                            nodeName: "tizen:operation",
                            required: true,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        uri: {
                            nodeName: "tizen:uri",
                            required: false,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        mime: {
                            nodeName: "tizen:mime",
                            required: false,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                "app-widget": {
                    nodeName: "tizen:app-widget",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            type: "string"
                        },
                        primary: {
                            attributeName: "primary",
                            required: true,
                            type: "list",
                            listValues: ['true', 'false']
                        },
                        "auto-launch": {
                            attributeName: "auto-launch",
                            required: false,
                            type: "list",
                            listValues: ['true', 'false']
                        },
                        "update-period": {
                            attributeName: "update-period",
                            required: false,
                            type: "integer"
                        }
                    },
                    children: {
                        "box-label": {
                            nodeName: "tizen:box-label",
                            required: true,
                            occurence: 1
                        },
                        "box-icon": {
                            nodeName: "tizen:box-icon",
                            required: true,
                            occurence: 1,
                            attributes: {
                                src: {
                                    attributeName: "src",
                                    required: true,
                                    type: "string"
                                }
                            }
                        },
                        "box-content": {
                            nodeName: "tizen:box-content",
                            required: true,
                            occurence: 1,
                            attributes: {
                                src: {
                                    attributeName: "src",
                                    required: true,
                                    type: "string"
                                },
                                "mouse-event": {
                                    attributeName: "mouse-event",
                                    required: false,
                                    type: "string"
                                },
                                "touch-event": {
                                    attributeName: "touch-event",
                                    required: false,
                                    type: "string"
                                }
                            },
                            children: {
                                "box-size": {
                                    nodeName: "tizen:box-size",
                                    required: false,
                                    occurence: 1,
                                    attributes: {
                                        "preview": {
                                            attributeName: "preview",
                                            required: false,
                                            type: "string"
                                        }
                                    }
                                },
                                pd: {
                                    nodeName: "tizen:pd",
                                    required: false,
                                    occurence: 1,
                                    attributes: {
                                        "src": {
                                            attributeName: "src",
                                            required: true,
                                            type: "string"
                                        },
                                        "width": {
                                            attributeName: "width",
                                            required: true,
                                            type: "integer"
                                        },
                                        "height": {
                                            attributeName: "height",
                                            required: true,
                                            type: "integer"
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                account: {
                    nodeName: "tizen:account",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "multiple-account-support": {
                            attributeName: "multiple-account-support",
                            required: true,
                            type: "list",
                            listValues: ['true', 'false']
                        }
                    },
                    children: {
                        icon: {
                            nodeName: "tizen:icon",
                            required: false,
                            occurence: 1,
                            attributes: {
                                section: {
                                    attributeName: "section",
                                    required: true,
                                    type: "string"
                                }
                            }
                        },
                        "display-name": {
                            nodeName: "tizen:display-name",
                            required: false,
                            occurence: 1,
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        capability: {
                            nodeName: "capability",
                            required: false,
                            occurence: 1
                        }
                    }
                },
                feature: {
                    nodeName: "tizen:privilege",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "list",
                            listValues: ["http://www.w3.org/TR/battery-status/",
                                         "http://www.w3.org/TR/geolocation-API/",
                                         "http://www.w3.org/TR/touch-events/",
                                         "http://www.w3.org/TR/vibration/",
                                         "http://tizen.org/privilege/tizen",
                                         "http://tizen.org/privilege/alarm",
                                         "http://tizen.org/privilege/application.launch",
                                         "http://tizen.org/privilege/appmanager.kill", "http://tizen.org/privilege/appmanager.certificate",
                                         "http://tizen.org/privilege/content.read", "http://tizen.org/privilege/content.write",
                                         "http://tizen.org/privilege/filesystem.read", "http://tizen.org/privilege/filesystem.write",
                                         "http://tizen.org/privilege/packagemanager.install", "http://tizen.org/privilege/package.info",
                                         "http://tizen.org/privilege/power",
                                         "http://tizen.org/privilege/system", "http://tizen.org/privilege/systemmanager",
                                         "http://tizen.org/privilege/time"]
                        },
                        required: {
                            attributeName: "required",
                            type: "boolean",
                            required: false
                        }
                    },
                    children: {
                        param: {
                            nodeName: "param",
                            required: false,
                            occurrence: 0,
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language"
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                },
                                name: {
                                    attributeName: "name",
                                    required: true,
                                    type: "string"
                                },
                                value: {
                                    attributeName: "value",
                                    required: true,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                category: {
                    nodeName: "tizen:category",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "name": {
                            attributeName: "name",
                            required: true,
                            type: "string"
                        }
                    }
                },
                metadata: {
                    nodeName: "tizen:metadata",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "key": {
                            attributeName: "key",
                            required: true,
                            type: "string"
                        },
                        "value": {
                            attributeName: "value",
                            required: true,
                            type: "string"
                        }
                    }
                },
                preference: {
                    nodeName: "preference",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "string"
                        },
                        value: {
                            type: "string",
                            required: false,
                            attributeName: "value"
                        },
                        readonly: {
                            attributeName: "readonly",
                            type: "boolean",
                            required: false
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/tv/1.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    StorageTypeTable = {
        "UNKNOWN": "UNKNOWN",
        "INTERNAL": "INTERNAL",
        "MMC": "MMC",
        "USB_HOST": "USB_HOST"
    },
    NetworkTypeTable = {
        "NONE": "NONE",
        "2G": "2G",
        "2.5G": "2.5G",
        "3G": "3G",
        "4G": "4G",
        "WIFI": "WIFI",
        "ETHERNET": "ETHERNET",
        "UNKNOWN": "UNKNOWN"
    },
    LocaleTable = {
        "eng_USA": "eng_USA",
        "eng_CAN": "eng_CAN",
        "deu_DEU": "deu_DEU",
        "jpn_JPN": "jpn_JPN",
        "zho_CHN": "zho_CHN",
        "UNKNOWN": "UNKNOWN"
    },
    SimStateTable = {
        "ABSENT": "ABSENT",
        "INITIALIZING": "INITIALIZING",
        "READY": "READY",
        "PIN_REQUIRED": "PIN_REQUIRED",
        "PUK_REQUIRED":"PUK_REQUIRED",
        "NETWORK_LOCKED": "NETWORK_LOCKED",
        "SIM_LOCKED": "SIM_LOCKED",
        "UNKNOWN": "UNKNOWN"
    };

function deviceStatusEventTrigger(setting) {
    event.trigger("DeviceStatusChanged", [setting]);
}

module.exports = {
    "Config": {
        "vibratingMode": {
            "name": "Vibrator",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("VibratingModeChanged", [setting]);
            }
        },
        "lockScreen": {
            "name": "Lock Screen",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "callback": function (setting) {
                event.trigger("LockScreenChanged", [setting]);
            }
        }
    },
    "DEVICE_ORIENTATION": {
        "status": {
            "name": "Status",
            "control": {
                "type": "label",
                "innertext": "PORTRAIT_PRIMARY",
                "value": "PORTRAIT_PRIMARY"
            },
            "event": "LayoutChanged"
        },
        "isAutoRotation": {
            "name": "Is Auto Rotation",
            "control": {
                "type": "label",
                "value": false
            }
        }
    },
    "CPU": {
        "load": {
            "name": "Load",
            "control": {
                "type": "number",
                "value": 0.1
            },
            "event": "CpuLoadChanged",
            "callback": function (setting) {
                if (setting > 1) setting = 1;
                if (setting < 0) setting = 0;
                event.trigger("CpuLoadChanged", [setting]);
            }
        }
    },
    "STORAGE": {
        "type": {
            "name": "Type",
            "control": {
                "type": "select",
                "value": StorageTypeTable["INTERNAL"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(StorageTypeTable, function (key, value) {
                    optionList[key] = StorageTypeTable[value];
                });

                return optionList;
            }())
        },
        "capacity": {
            "name": "Capacity(bytes)",
            "control": {
                "type": "label",
                "value": 16000000000
            }
        },
        "availableCapacity": {
            "name": "AvailableCapacity(bytes)",
            "control": {
                "type": "number",
                "value": 12000000000
            },
            "callback": function (setting) {
                event.trigger("AvailCapacityChanged", [setting]);
            }
        },
        "isRemovable": {
            "name": "IsRemovable",
            "control": {
                "type": "checkbox",
                "value": true
            }
        }
    },
    "BUILD": {
        "model": {
            "name": "Model",
            "control": {
                "type": "label",
                "innertext": "tizen-2.2 build",
                "value": "tizen-2.2 build"
            }
        },
        "manufacturer": {
            "name": "Manufacturer",
            "control": {
                "type": "label",
                "innertext": "Tizen",
                "value": "Tizen"
            }
        },
        "buildVersion": {
            "name": "Build Version",
            "control": {
                "type": "label",
                "innertext": "TIZEN_WEB_SIMULATOR_000001",
                "value": "TIZEN_WEB_SIMULATOR_000001"
            }
        }
    },
    "LOCALE": {
        "language": {
            "name": "Language",
            "control": {
                "type": "select",
                "value": LocaleTable["eng_USA"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(LocaleTable, function (key, value) {
                    optionList[key] = LocaleTable[value];
                });

                return optionList;
            }())
        },
        "country": {
            "name": "Country",
            "control": {
                "type": "select",
                "value": LocaleTable["eng_USA"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(LocaleTable, function (key, value) {
                    optionList[key] = LocaleTable[value];
                });

                return optionList;
            }())
        }
    },
    "DISPLAY": {
        "resolutionWidth": {
            "name": "Resolution Width(pixels)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "resolutionHeight": {
            "name": "Resolution Height(pixels)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "dotsPerInchWidth": {
            "name": "DPI-X",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "dotsPerInchHeight": {
            "name": "DPI-Y",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "physicalWidth": {
            "name": "Physical Width(millimeters)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "physicalHeight": {
            "name": "Physical Height(millimeters)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "brightness": {
            "name": "Brightness",
            "control": {
                "type": "number",
                "value": 1
            },
            "event": "DisplayBrightnessChanged",
            "callback": function (setting) {
                if (setting > 1) setting = 1;
                if (setting < 0) setting = 0;
                event.trigger("DisplayBrightnessChanged", [setting]);
            }
        }
    },
    "NETWORK": {
        "networkType": {
            "name": "Network Type",
            "control" : {
                "type": "select",
                "value": NetworkTypeTable["NONE"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(NetworkTypeTable, function (key, value) {
                    optionList[key] = NetworkTypeTable[value];
                });

                return optionList;
            }())
        }
    },
    "WIFI_NETWORK": {
        "status": {
            "name": "Status",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "event": "WiFiNetworkStatusChanged",
            "callback": function (setting) {
                event.trigger("WiFiNetworkStatusChanged", [setting]);
            }
        },
        "ssid": {
            "name": "SSID",
            "control": {
                "type": "text",
                "value": "Tizen WiFi"
            }
        },
        "ipAddress": {
            "name": "IP Address",
            "control": {
                "type": "text",
                "value": "192.168.0.1"
            }
        },
        "ipv6Address": {
            "name": "IPv6 Address",
            "control": {
                "type": "text",
                "value": "2001:db8:85a3:0:0:0:70:7334"
            }
        },
        "signalStrength": {
            "name": "Signal Strength",
            "control": {
                "type": "select",
                "value": 0
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 10; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }())
        }
    },
    "CELLULAR_NETWORK": {
        "status": {
            "name": "Status",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "event": "CellularNetworkStatusChanged",
            "callback": function (setting) {
                event.trigger("CellularNetworkStatusChanged", [setting]);
            }
        },
        "apn": {
            "name": "APN",
            "control": {
                "type": "text",
                "value": "Tizen"
            }
        },
        "ipAddress": {
            "name": "IP Address",
            "control": {
                "type": "text",
                "value": "10.0.2.16"
            }
        },
        "ipv6Address": {
            "name": "IPv6 Address",
            "control": {
                "type": "text",
                "value": "2001:db8:85a3:0:0:0:70:7334"
            }
        },
        "mcc": {
            "name": "MCC",
            "control": {
                "type": "number",
                "value": 460
            }
        },
        "mnc": {
            "name": "MNC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "cellId": {
            "name": "Cell ID",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "lac": {
            "name": "LAC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "isRoaming": {
            "name": "Roaming",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "isFlightMode": {
            "name": "Flight Mode",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "callback": function (setting) {
                event.trigger("FlightModeChanged", [setting]);
            }
        },
        "imei": {
            "name": "IMEI",
            "control": {
                "type": "text",
                "value": "012417005203000"
            }
        }
    },
    "SIM": {
        "state": {
            "name": "State",
            "control": {
                "type": "select",
                "value": SimStateTable["READY"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(SimStateTable, function (key, value) {
                    optionList[key] = SimStateTable[value];
                });

                return optionList;
            }())
        },
        "operatorName": {
            "name": "Operator Name",
            "control": {
                "type": "text",
                "value": "Tizen"
            }
        },
        "msisdn": {
            "name": "MSISDN",
            "control": {
                "type": "text",
                "value": "088123456789"
            }
        },
        "iccid": {
            "name": "ICCID",
            "control": {
                "type": "text",
                "value": "123000MFSSYYGXXXXXXP"
            }
        },
        "mcc": {
            "name": "MCC",
            "control": {
                "type": "number",
                "value": 460
            }
        },
        "mnc": {
            "name": "MNC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "msin": {
            "name": "MSIN",
            "control": {
                "type": "text",
                "value": "H1 H2 H3 S 12345"
            }
        },
        "spn": {
            "name": "SPN",
            "control": {
                "type": "text",
                "value": "TizenSPN"
            }
        }
    },
    "PERIPHERAL": {
        "isVideoOutputOn": {
            "name": "Video Output",
            "control": {
                "type": "checkbox",
                "value": false
            }
        }
    }
};

});
define('ripple/platform/tv/1.0/spec/sensor', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event');

function sensorStatusEventTrigger(setting) {
    event.trigger("SensorStatusChanged", [setting]);
}

module.exports = {
    "Accelerometer": {
        "resolution": 0.039239998906850815,
        "minDelay": 20,
        "range": 20.051639556884766,
        "name": "Accelerometer",
        "type": "Accelerometer"
    },
    "MagneticField": {
        "x": {
            "name": "X",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-xChanged", [setting]);
            }
        },

        "y": {
            "name": "Y",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-yChanged", [setting]);
            }
        },

        "z": {
            "name": "Z",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-zChanged", [setting]);
            }
        },

        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "MagneticField",
        "type": "MagneticField"
    },
    "Rotation": {
        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "Rotation",
        "type": "Rotation"
    },
    "Orientation": {
        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "Orientation",
        "type": "Orientation"
    }
};

});
define('ripple/platform/tv/1.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "sensors",
        "communication",
        "geoView",
        "widgetConfig",
        "deviceSettings",
        "application",
        "network",
        "power",
        "download",
        "notifications",
        "package",
        "messagePort",
        "secureElement"
    ]
};

});
define('ripple/platform/tv/1.0/spec', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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.
 */

module.exports = {

    id: "tv",
    version: "1.0",
    name: "TV",

    persistencePrefix: "tv2-",

    config: require('ripple/platform/tv/1.0/spec/config'),
    ui: require('ripple/platform/tv/1.0/spec/ui'),
    device: require('ripple/platform/tv/1.0/spec/device'),
    sensor: require('ripple/platform/tv/1.0/spec/sensor'),
    DeviceMotionEvent: require('ripple/platform/tizen/2.0/DeviceMotionEvent'),
    DeviceOrientationEvent: require('ripple/platform/tizen/2.0/DeviceOrientationEvent'),

    objects: {
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        SensorConnection: {
            path: "w3c/1.0/SensorConnection"
        },
        navigator: {
            path: "tizen/2.0/navigator",
            children: {
                geolocation: {
                    path: "wac/2.0/geolocation"
                },
                battery: {
                    path: "tizen/2.0/battery"
                }
            }
        },
        tizen: {
            feature: "http://tizen.org/privilege/tizen",
            children: {
                AlarmAbsolute: {
                    path: "tizen/2.0/AlarmAbsolute"
                },
                AlarmRelative: {
                    path: "tizen/2.0/AlarmRelative"
                },
                ApplicationControl: {
                    path: "tizen/2.0/ApplicationControl"
                },
                ApplicationControlData: {
                    path: "tizen/2.0/ApplicationControlData"
                },
                AttributeFilter: {
                    path: "tizen/2.0/AttributeFilter"
                },
                AttributeRangeFilter: {
                    path: "tizen/2.0/AttributeRangeFilter"
                },
                BookmarkFolder: {
                    path: "tizen/2.0/BookmarkFolder"
                },
                BookmarkItem: {
                    path: "tizen/2.0/BookmarkItem"
                },
                CalendarAlarm: {
                    path: "tizen/2.0/CalendarAlarm"
                },
                CalendarAttendee: {
                    path: "tizen/2.0/CalendarAttendee"
                },
                CalendarEvent: {
                    path: "tizen/2.0/CalendarEvent"
                },
                CalendarEventId: {
                    path: "tizen/2.0/CalendarEventId"
                },
                CalendarRecurrenceRule: {
                    path: "tizen/2.0/CalendarRecurrenceRule"
                },
                CalendarTask: {
                    path: "tizen/2.0/CalendarTask"
                },
                CompositeFilter: {
                    path: "tizen/2.0/CompositeFilter"
                },
                Contact: {
                    path: "tizen/2.0/ContactBase"
                },
                ContactAddress: {
                    path: "tizen/2.0/ContactAddress"
                },
                ContactAnniversary: {
                    path: "tizen/2.0/ContactAnniversary"
                },
                ContactEmailAddress: {
                    path: "tizen/2.0/ContactEmailAddress"
                },
                ContactGroup: {
                    path: "tizen/2.0/ContactGroup"
                },
                ContactName: {
                    path: "tizen/2.0/ContactName"
                },
                ContactOrganization: {
                    path: "tizen/2.0/ContactOrganization"
                },
                ContactPhoneNumber: {
                    path: "tizen/2.0/ContactPhoneNumber"
                },
                ContactRef: {
                    path: "tizen/2.0/ContactRef"
                },
                ContactWebSite: {
                    path: "tizen/2.0/ContactWebSite"
                },
                DownloadRequest: {
                    path: "tizen/2.0/DownloadRequest"
                },
                Message: {
                    path: "tizen/2.0/Message"
                },
                NDEFMessage: {
                    path: "tizen/2.0/NDEFMessage"
                },
                NDEFRecord: {
                    path: "tizen/2.0/NDEFRecord"
                },
                NDEFRecordMedia: {
                    path: "tizen/2.0/NDEFRecordMedia"
                },
                NDEFRecordText: {
                    path: "tizen/2.0/NDEFRecordText"
                },
                NDEFRecordURI: {
                    path: "tizen/2.0/NDEFRecordURI"
                },
                NotificationDetailInfo: {
                    path: "tizen/2.0/NotificationDetailInfo"
                },
                SimpleCoordinates: {
                    path: "tizen/2.0/SimpleCoordinates"
                },
                SortMode: {
                    path: "tizen/2.0/SortMode"
                },
                StatusNotification: {
                    path: "tizen/2.0/StatusNotification"
                },
                SyncInfo: {
                    path: "tizen/2.0/SyncInfo"
                },
                SyncServiceInfo: {
                    path: "tizen/2.0/SyncServiceInfo"
                },
                SyncProfileInfo: {
                    path: "tizen/2.0/SyncProfileInfo"
                },
                TZDate: {
                    path: "tizen/2.0/TZDate"
                },
                TimeDuration: {
                    path: "tizen/2.0/TimeDuration"
                },
                alarm: {
                    path: "tizen/2.0/alarm",
                    feature: "http://tizen.org/privilege/alarm",
                    handleSubfeatures: true
                },
                application: {
                    path: "tizen/2.0/application",
                    feature: "http://tizen.org/privilege/application.launch|http://tizen.org/privilege/appmanager.kill|http://tizen.org/privilege/appmanager.certificate",
                    handleSubfeatures: true
                },
                bluetooth: {
                    path: "tizen/2.0/bluetooth",
                    feature: "http://tizen.org/privilege/bluetoothmanager|http://tizen.org/privilege/bluetooth.admin|http://tizen.org/privilege/bluetooth.gap|http://tizen.org/privilege/bluetooth.spp",
                    handleSubfeatures: true
                },
                bookmark: {
                    path: "tizen/2.0/bookmark",
                    feature: "http://tizen.org/privilege/bookmark.read|http://tizen.org/privilege/bookmark.write",
                    handleSubfeatures: true
                },
                callhistory: {
                    path: "tizen/2.0/callHistory",
                    feature: "http://tizen.org/privilege/callhistory|http://tizen.org/privilege/callhistory.read|http://tizen.org/privilege/callhistory.write",
                    handleSubfeatures: true
                },
                calendar: {
                    path: "tizen/2.0/calendar",
                    feature: "http://tizen.org/privilege/calendar.read|http://tizen.org/privilege/calendar.write",
                    handleSubfeatures: true
                },
                contact: {
                    path: "tizen/2.0/contact",
                    feature: "http://tizen.org/privilege/contact.read|http://tizen.org/privilege/contact.write",
                    handleSubfeatures: true
                },
                content: {
                    path: "tizen/2.0/content",
                    feature: "http://tizen.org/privilege/content.read|http://tizen.org/privilege/content.write",
                    handleSubfeatures: true
                },
                datacontrol: {
                    path: "tizen/2.0/datacontrol",
                    feature: "http://tizen.org/privilege/datacontrol.consumer",
                    handleSubfeatures: true
                },
                datasync: {
                    path: "tizen/2.0/datasync",
                    feature: "http://tizen.org/privilege/datasync",
                    handleSubfeatures: true
                },
                download: {
                    path: "tizen/2.0/download",
                    feature: "http://tizen.org/privilege/download",
                    handleSubfeatures: true
                },
                filesystem: {
                    path: "tizen/2.0/filesystem",
                    feature: "http://tizen.org/privilege/filesystem.read|http://tizen.org/privilege/filesystem.write"
                },
                messageport: {
                    path: "tizen/2.0/messageport"
                },
                messaging: {
                    path: "tizen/2.0/messaging",
                    feature: "http://tizen.org/privilege/messaging.send|http://tizen.org/privilege/messaging.read|http://tizen.org/privilege/messaging.write",
                    handleSubfeatures: true
                },
                networkbearerselection: {
                    path: "tizen/2.0/networkbearerselection",
                    feature: "http://tizen.org/privilege/networkbearerselection",
                    handleSubfeatures: true
                },
                nfc: {
                    path: "tizen/2.0/nfc",
                    feature: "http://tizen.org/privilege/nfc.common|http://tizen.org/privilege/nfc.admin|http://tizen.org/privilege/nfc.tag|http://tizen.org/privilege/nfc.p2p",
                    handleSubfeatures: true
                },
                notification: {
                    path: "tizen/2.0/notification",
                    feature: "http://tizen.org/privilege/notification",
                    handleSubfeatures: true
                },
                package: {
                    path: "tizen/2.0/package",
                    feature: "http://tizen.org/privilege/packagemanager.install|http://tizen.org/privilege/package.info",
                    handleSubfeatures: true
                },
                power: {
                    path: "tizen/2.0/power",
                    feature: "http://tizen.org/privilege/power",
                    handleSubfeatures: true
                },
                push: {
                    path: "tizen/2.0/push",
                    feature: "http://tizen.org/privilege/push",
                    handleSubfeatures: true
                },
                seService: {
                    path: "tizen/2.0/secureelement",
                    feature: "http://tizen.org/privilege/secureelement",
                    handleSubfeatures: true
                },
                systeminfo: {
                    path: "tizen/2.0/systeminfo",
                    feature: "http://tizen.org/privilege/system|http://tizen.org/privilege/systemmanager",
                    handleSubfeatures: true
                },
                systemsetting: {
                    path: "tizen/2.0/systemsetting",
                    feature: "http://tizen.org/privilege/setting",
                    handleSubfeatures: true
                },
                time: {
                    path: "tizen/2.0/time",
                    feature: "http://tizen.org/privilege/time",
                    handleSubfeatures: true
                },
                websetting: {
                    path: "tizen/2.0/websetting",
                    feature: "http://tizen.org/privilege/websetting",
                    handleSubfeatures: true
                }
            }
        }
    }
};

});
define('ripple/platform/tv/1.0/typecast', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 typedef = require('ripple/platform/tv/1.0/typedef'),
    errorcode = require('ripple/platform/tv/1.0/errorcode'),
    WebAPIException = require('ripple/platform/tv/1.0/WebAPIException'),
    TypeCoerce = require('ripple/platform/tv/1.0/typecoerce'),
    _self = {};

function _cast(pattern, obj, isDuplicate) {
    var tc, tcFunc;

    if (pattern === null)
        return;

    tc = new TypeCoerce(pattern);
    tcFunc = isDuplicate ? tc.copy : tc.cast;

    if ((obj = tcFunc(obj)) === null) {
        throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
    }

    return obj;
}

function _castType(pattern) {
    /*
     * Type cast for each known type. The function name is the exact name of the
     * corresponding type.
     *
     * obj
     *    Variable to be casted
     *
     * aux
     *    Auxiliary descriptor of obj. It can be any one or combination of below
     *    strings, or ignored in most cases.
     *
     *    "?"     Nullable types
     *    "[]"    Array
     *    "+"     Deep copy
     *
     * Return
     *    Casted or duplicated object.
     */

    return function (obj, aux) {
        var type, isNullable, isDuplicate;

        aux = aux ? String(aux) : "";
        type = (aux.indexOf("[]") !== -1) ? [pattern] : pattern;
        isNullable = (aux.indexOf("?") !== -1);
        isDuplicate = (aux.indexOf("+") !== -1);

        if (isNullable && ((obj === null) || (obj === undefined))) {
            return obj;
        }

        return _cast(type, obj, isDuplicate);
    };
}

function _castConstructor(name) {
    var constructors, hook, vtc, isOverloaded, castConstructor;

    /*
     * Type cast for constructor. The function name is the exact name of the
     * object type.
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     */

    function castUnique(argv) {
        _cast(constructors, argv, false);
    }

    /*
     * Type cast for overloaded constructors. The function name is the exact
     * name of the object type.
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     *
     * scope
     *    'this' of the original constructor.
     *
     * voc
     *    Array of overloaded constructors callback
     */

    function castOverload(argv, scope, voc) {
        var iOverload;

        if (!vtc) {
            vtc = [];
            constructors.forEach(function (c) {
                vtc.push((c === null) ? null : new TypeCoerce(c));
            });
        }

        vtc.some(function (tc, index) {
            if (tc && (tc.cast(argv) === null))
                return false;

            iOverload = index;
            return true;
        });

        if (iOverload === undefined) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }

        return (voc && voc[iOverload].apply(scope, argv));
    }

    constructors = typedef.constructor[name];

    if (name in _self) {
        hook = _self[name];
    }

    isOverloaded = (Object.prototype.toString.call(constructors) ===
            "[object Array]");
    castConstructor = isOverloaded ? castOverload : castUnique;

    return function (argv, scope) {
        if (Object.prototype.toString.call(argv) !== "[object Arguments]") {
            return (hook && hook.apply(this, arguments));
        }

        if (!(scope instanceof argv.callee)) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR, null, "TypeError");
        }

        castConstructor.apply(this, arguments);
    };
}

function _castInterface(name) {
    var interface, hook;

    interface = typedef.interface[name];

    if (name in _self) {
        hook = _self[name];
    }

    /*
     * Type cast for each known method of interface. The function name is the
     * exact name of the corresponding interface.
     *
     * method
     *    String of method name
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     *
     * isDuplicate
     *    A boolean value to indicate whether arguments will be copied or not.
     */

    return function (method, argv, isDuplicate) {
        if ((typeof method !== "string") || (typeof argv !== "object")) {
            return (hook && hook.apply(this, arguments));
        }

        _cast(interface[method], argv, isDuplicate);
    };
}

(function () {
    var i;

    for (i in typedef) {
        _self[i] = _castType(typedef[i]);
    }

    for (i in typedef.constructor) {
        _self[i] = _castConstructor(i);
        typedef[i]._constructor = i;
    }

    for (i in typedef.interface) {
        _self[i] = _castInterface(i);
    }
}());

module.exports = _self;

});
define('ripple/platform/tv/1.0/typecoerce', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 t = require('ripple/platform/tv/1.0/typedef'),
    _MAX_INT_BITS = 53,
    _MAX_INT = Math.pow(2, _MAX_INT_BITS) - 1,
    _self;

_self = function (pattern) {
    var typeCoerce, typeOfPattern;

    // private
    function getExtendedType(val) {
        var type = Object.prototype.toString.call(val), attr;

        switch (type) {
        case "[object Array]":
            if ((typeof val[0] === "string") && (val[0].length > 0)) {
                type = "enum";
            } else {
                type = "Union";
            }
            return type;

        case "[object Object]":
            if ("_dictionary" in val) {
                return "dictionary";
            }

            type = "Object";

            for (attr in val) {
                if (attr === "0") {
                    type = "Arguments";
                } else if (val[attr] === "Callback") {
                    type = "Callback";
                }
                break;
            }

            return type;
        }

        switch (val) {
        case "Callback":
            type = "Function";
            break;

        case "TZDate":
        case "any":
        case "byte":
        case "float":
        case "long":
        case "long long":
        case "octet":
        case "short":
        case "unsigned long":
        case "unsigned long long":
        case "unsigned short":
            type = val;
            break;

        case "double":
            type = "float";
            break;

        default:    // Derivative type name: e.g., "AbstractFilter"
            type = "";
            break;
        }

        return type;
    }

    function getType(val, isPattern) {
        var type = Object.prototype.toString.call(val);

        switch (type) {
        case "[object Array]":
            type = (isPattern && (val.length > 1)) ? getExtendedType(val) :
                    "Array";
            break;

        case "[object Arguments]":
            type = "Arguments";
            break;

        case "[object Boolean]":
            type = "boolean";
            break;

        case "[object Date]":
            type = "Date";
            break;

        case "[object Function]":
            type = "Function";
            break;

        case "[object Number]":
            type = "Number";
            break;

        case "[object Object]":
            type = isPattern ? getExtendedType(val) : "Object";
            break;

        case "[object String]":
            type = (isPattern && !!val) ? getExtendedType(val) : "DOMString";
            break;
        }

        return type;
    }

    function isConstructed(obj) {
        if (!("_constructor" in pattern))
            return true;

        if (obj instanceof window.tizen[pattern._constructor])
            return true;

        if ("_derived" in pattern)
            return true;

        return false;
    }

    function toInteger(x) {
        return (x < 0) ? Math.ceil(x) : Math.floor(x);
    }

    function isBitsOverflowed(bits) {
        return (bits >= _MAX_INT_BITS);
    }

    function toJsInt(x, isUnsigned) {
        var min, max;

        min = isUnsigned ? 0 : -_MAX_INT;
        max = _MAX_INT;

        if ((x < min) || (x > max))
            return null;

        return toInteger(x);
    }

    function modulo(a, b) {
        return (a - Math.floor(a / b) * b);
    }

    function toInt(x, bits) {
        var p;

        x = Number(x);

        if (isNaN(x) || !isFinite(x))
            return null;

        if (isBitsOverflowed(bits))
            return toJsInt(x, false);

        p = Math.pow(2, bits);
        x = modulo(toInteger(x), p);

        return (x >= Math.pow(2, bits - 1)) ? (x - p) : x;
    }

    function toUInt(x, bits) {
        x = Number(x);

        if (isNaN(x) || !isFinite(x))
            return null;

        if (isBitsOverflowed(bits))
            return toJsInt(x, true);

        return modulo(toInteger(x), Math.pow(2, bits));
    }

    function toInt8(x) {
        return toInt(x, 8);
    }

    function toInt16(x) {
        return toInt(x, 16);
    }

    function toInt32(x) {
        return toInt(x, 32);
    }

    function toInt64(x) {
        return toInt(x, 64);
    }

    function toUInt8(x) {
        return toUInt(x, 8);
    }

    function toUInt16(x) {
        return toUInt(x, 16);
    }

    function toUInt32(x) {
        return toUInt(x, 32);
    }

    function toUInt64(x) {
        return toUInt(x, 64);
    }

    // public
    function cast(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Arguments": function () {
                var i, isNullable, ret;

                for (i in pattern) {
                    if (i === "_optional")
                        continue;

                    isNullable = !!(pattern._optional && pattern._optional[i]);

                    if (i > obj.length - 1) {
                        if (!isNullable) {
                            return null;
                        }
                        break;
                    }

                    if (!isNullable || (obj[i] !== null)) {
                        ret = _self(pattern[i]).cast(obj[i]);
                        if (ret === null) {
                            return null;
                        }
                        obj[i] = ret;
                    }
                }

                return obj;
            },

            "Array": function () {
                var elementType, i, ret;

                if (typeOfObj !== typeOfPattern) {
                    return null;
                }

                elementType = _self(pattern[0]);
                for (i in obj) {
                    ret = elementType.cast(obj[i]);
                    if (ret === null) {
                        return null;
                    }
                    obj[i] = ret;
                }

                return obj;
            },

            "Callback": function () {
                var attr;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        obj[attr] = _self(pattern[attr]).cast(obj[attr]);
                        if (obj[attr] === null) {
                            return null;
                        }
                    }
                }

                return obj;
            },

            "DOMString": function () {
                switch (typeOfObj) {
                case "DOMString":
                case "Date":
                case "Number":
                case "boolean":
                    obj = String(obj);
                    break;

                default:
                    if ((obj === null) || (obj === undefined)) {
                        obj = String(obj);
                    } else {
                        obj = null;
                    }
                    break;
                }

                return obj;
            },

            "Date": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "Function": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "Object": function () {
                var ret, attr, i;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return null;
                    }
                    if (!("_derived" in pattern)) {
                        return null;
                    }
                }

                if (!isConstructed(obj)) {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            ret = _self(pattern._derived[i]).cast(obj);
                            if (ret !== null)
                                break;
                        }
                        if (ret === null) {
                            if ("_constructor" in pattern)
                                break;

                            return null;
                        }
                        break;

                    default:
                        if (!pattern._optional || !pattern._optional[attr] ||
                                (obj[attr] !== undefined) &&
                                (obj[attr] !== null)) {
                            ret = _self(pattern[attr]).cast(obj[attr]);
                            if (ret === null) {
                                return null;
                            }
                            obj[attr] = ret;
                        }
                        break;
                    }
                }

                return obj;
            },

            "TZDate": function () {
                if (typeOfObj !== "Object") {
                    return null;
                }
                return (obj instanceof window.tizen.TZDate) ? obj : null;
            },

            "Union": function () {
                var ret, i;

                for (i in pattern) {
                    ret = _self(pattern[i]).cast(obj);
                    if (ret !== null)
                        break;
                }

                return ret;
            },

            "any": function () {
                return obj;
            },

            "boolean": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "byte": function () {
                return toInt8(obj);
            },

            "dictionary": function () {
                var attr, ret;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            ret = _self(pattern._dictionary).cast(obj);
                            if (ret === null) {
                                return null;
                            }
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            ret = _self(pattern[attr]).cast(obj[attr]);
                            if (ret === null) {
                                return null;
                            }
                            obj[attr] = ret;
                        }
                        break;
                    }
                }

                return obj;
            },

            "enum": function () {
                var i;

                obj = String(obj).trim();
                for (i in pattern) {
                    if (obj === pattern[i]) {
                        return obj;
                    }
                }

                return null;
            },

            "float": function () {
                var f = parseFloat(obj, 10);

                return (isNaN(f) ? null : f);
            },

            "long": function () {
                return toInt32(obj);
            },

            "long long": function () {
                return toInt64(obj);
            },

            "octet": function () {
                return toUInt8(obj);
            },

            "short": function () {
                return toInt16(obj);
            },

            "unsigned long": function () {
                return toUInt32(obj);
            },

            "unsigned long long": function () {
                return toUInt64(obj);
            },

            "unsigned short": function () {
                return toUInt16(obj);
            },

            "": function () {
                return _self(t[pattern]).cast(obj);
            }
        };

        return typeMap[typeOfPattern]();
    }

    function copy(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Arguments": function () {
                var i, isNullable, ret = [];

                for (i in pattern) {
                    if (i === "_optional")
                        continue;

                    isNullable = !!(pattern._optional && pattern._optional[i]);

                    if (i > obj.length - 1) {
                        if (!isNullable) {
                            return null;
                        }
                        break;
                    }

                    if (!isNullable || (obj[i] !== null)) {
                        ret[i] = _self(pattern[i]).copy(obj[i]);
                        if (ret[i] === null) {
                            return null;
                        }
                    }
                }

                for (i in ret) {
                    obj[i] = ret[i];
                }

                return obj;
            },

            "Array": function () {
                var arr = [], elementType, i;

                if (typeOfObj !== typeOfPattern) {
                    return null;
                }

                elementType = _self(pattern[0]);
                for (i in obj) {
                    if (obj[i] !== undefined) {
                        arr[i] = elementType.copy(obj[i]);
                        if (arr[i] === null)
                            return null;
                    }
                }

                return arr;
            },

            "Callback": function () {
                var ret = {}, attr;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                        if (ret[attr] === null) {
                            return null;
                        }
                    }
                }

                return ret;
            },

            "Object": function () {
                var ret = {}, attr, i, derived;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return null;
                    }
                    if (!("_derived" in pattern)) {
                        return null;
                    }
                }

                if (!isConstructed(obj)) {
                    return null;
                }
                if ("_constructor" in pattern) {
                    ret.__proto__ = window.tizen[pattern._constructor].prototype;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            derived = _self(pattern._derived[i]).copy(obj);
                            if (derived !== null)
                                break;
                        }
                        if (derived === null) {
                            if ("_constructor" in pattern)
                                break;

                            return null;
                        }
                        for (attr in derived) {
                            ret[attr] = derived[attr];
                        }
                        break;

                    default:
                        if (!pattern._optional || !pattern._optional[attr] ||
                                (obj[attr] !== undefined) &&
                                (obj[attr] !== null)) {
                            ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                            if (ret[attr] === null) {
                                return null;
                            }
                        }
                        break;
                    }
                }

                return ret;
            },

            "Union": function () {
                var ret, i;

                for (i in pattern) {
                    ret = _self(pattern[i]).copy(obj);
                    if (ret !== null)
                        break;
                }

                return ret;
            },

            "dictionary": function () {
                var ret = {}, attr, base, i;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            base = _self(pattern._dictionary).copy(obj);
                            if (base === null) {
                                return null;
                            }
                            for (i in base) {
                                ret[i] = base[i];
                            }
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                            if (ret[attr] === null) {
                                return null;
                            }
                        }
                        break;
                    }
                }

                return ret;
            },

            "": function () {
                return _self(t[pattern]).copy(obj);
            }
        };

        return (typeOfPattern in typeMap) ? typeMap[typeOfPattern]() :
                cast(obj);
    }

    function match(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Array": function () {
                var elementType, i;

                if (typeOfObj !== typeOfPattern)
                    return false;

                elementType = _self(pattern[0]);
                for (i in obj) {
                    if (!elementType.match(obj[i])) {
                        return false;
                    }
                }

                return true;
            },

            "Callback": function () {
                var attr, isMatched = true;

                if (typeOfObj !== "Object") {
                    return false;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        isMatched = _self(pattern[attr]).match(obj[attr]);
                        if (!isMatched) {
                            break;
                        }
                    }
                }

                return isMatched;
            },

            "DOMString": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Date": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Function": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Object": function () {
                var attr, isMatched = false, i;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return false;
                    }
                    if (!("_derived" in pattern)) {
                        return false;
                    }
                    return false;
                }

                if (!isConstructed(obj)) {
                    return false;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            isMatched = _self(pattern._derived[i]).match(obj);
                            if (isMatched)
                                break;
                        }
                        break;

                    default:
                        if (pattern._optional && pattern._optional[attr]) {
                            isMatched = ((obj[attr] === null) ||
                                    (obj[attr] === undefined) ||
                                    _self(pattern[attr]).match(obj[attr]));
                        } else {
                            isMatched = (obj[attr] !== undefined) &&
                                    _self(pattern[attr]).match(obj[attr]);
                        }
                        break;
                    }

                    if (!isMatched)
                        break;
                }

                /*// Check if verbose attributes are present
                if (isMatched) {
                    for (attr in obj) {
                        if (pattern[attr] === undefined) {
                            isMatched = false;
                            break;
                        }
                    }
                }*/

                return isMatched;
            },

            "Union": function () {
                var isMatched, i;

                for (i in pattern) {
                    isMatched = _self(pattern[i]).match(obj);
                    if (isMatched)
                        break;
                }

                return isMatched;
            },

            "any": function () {
                return true;
            },

            "boolean": function () {
                return (typeOfObj === typeOfPattern);
            },

            "byte": function () {
                return (obj === toInt8(obj));
            },

            "dictionary": function () {
                var attr, isMatched = true;

                if (typeOfObj !== "Object") {
                    return false;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            isMatched = _self(pattern._dictionary).match(obj);
                            if (!isMatched)
                                break;
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            isMatched = _self(pattern[attr]).match(obj[attr]);
                            if (!isMatched)
                                break;
                        }
                        break;
                    }
                }

                return isMatched;
            },

            "enum": function () {
                for (var i in pattern) {
                    if (obj === pattern[i]) {
                        return true;
                    }
                }

                return false;
            },

            "float": function () {
                return (typeOfObj === "Number");
            },

            "long": function () {
                return (obj === toInt32(obj));
            },

            "long long": function () {
                return (obj === toInt64(obj));
            },

            "octet": function () {
                return (obj === toUInt8(obj));
            },

            "short": function () {
                return (obj === toInt16(obj));
            },

            "unsigned long": function () {
                return (obj === toUInt32(obj));
            },

            "unsigned long long": function () {
                return (obj === toUInt64(obj));
            },

            "unsigned short": function () {
                return (obj === toUInt16(obj));
            },

            "Arguments": function () {
                return true;
            },

            "": function () {
                return _self(t[pattern]).match(obj);
            }
        };

        return typeMap[typeOfPattern]();
    }

    typeOfPattern = getType(pattern, true);

    typeCoerce = {
        cast:  cast,
        copy:  copy,
        match: match
    };

    return typeCoerce;
};

module.exports = _self;

});
define('ripple/platform/tv/1.0/typedef', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 _t, _c, _i;

/*
 * Primitive type definition
 */

_t = {
    // Basic
    Callback:                       "Callback",
    DOMString:                      "",
    Date:                           new Date(),
    Function:                       function () {},
    TZDate:                         "TZDate",
    any:                            "any",
    boolean:                        false,
    byte:                           "byte",
    double:                         "double",
    float:                          "float",
    long:                           "long",
    octet:                          "octet",
    short:                          "short",
    long_long:                      "long long",
    unsigned_long:                  "unsigned long",
    unsigned_long_long:             "unsigned long long",
    unsigned_short:                 "unsigned short"
};

/*
 * Derivative type definition
 */

/*
 * Object attributes
 *     Contruct a prototype of an object. Specify a primitive type for each attribute.
 *
 * _optional
 *     Optional attributes table, which consists of two types of attributes,
 *
 *     nullable
 *         Nullable attributes, marked as '?' in IDL.
 *
 *     undefined
 *         Array type attributes, that not definitely specified to be
 *         initialized as an empty array, i.e., undefined-initialized array.
 *
 * _derived
 *     Derived types, which used in two cases of definition,
 *
 *     Subtype list
 *         An array consists of derived subtypes. It exists in the definition of
 *         a base type.
 *
 *     Union types
 *         An array consists of member types. It exists in the definition of
 *         a union type.
 *
 * _dictionary
 *     Dictionary type, which indicates that the object is a dictionary type.
 */

/*
 * Constructor list definition
 */

/*
 * Generic constructor
 *     Construct a prototype of constructor. A fake array of arguments type is
 *     specified for constructor.
 *
 * Overloaded constructors
 *     Construct an array of prototype of constructor. Each array element is
 *     specified for one of constructors. The constructor with extra arguments
 *     are recommended to be defined ahead of the one with fewer same arguments
 *     for exact match.
 */

_c = {};

/*
 * Interface prototype definition
 */

_i = {};

// Exports
_t.constructor = _c;
_t.interface   = _i;

module.exports = _t;

});
define('ripple/platform/w3c/1.0/Acceleration', function (require, exports, module) {
module.exports = function (x, y, z) {
    return {
        x: x || 0,    //Acceleration in the 'x' expressed in m/s^2. (Number)
        y: y || 0,    //Acceleration in the 'y' expressed in m/s^2. (Number)
        z: z || 0     //Acceleration in the 'z' expressed in m/s^2. (Number)
    };
};

});
define('ripple/platform/w3c/1.0/Coordinates', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function (latitude, longitude, altitude, accuracy, altitudeAccuracy, heading, speed) {
    return {
        latitude: latitude || 0,                    //Latitude in decimal degrees. (Number)
        longitude: longitude || 0,                  //Longitude in decimal degrees. (Number)
        altitude: altitude || 0,                    //Height of the position in meters above the ellipsoid. (Number)
        accuracy: accuracy || 0,                    //Accuracy level of the latitude and longitude coordinates in meters. (Number)
        altitudeAccuracy: altitudeAccuracy || 0,    //Accuracy level of the altitude coordinate in meters. (Number)
        heading: heading || 0,                      //Direction of travel, specified in degrees counting clockwise relative to the true north. (Number)
        speed: speed || 0                           //Current ground speed of the device, specified in meters per second. (Number)
    };
};

});
define('ripple/platform/w3c/1.0/Position', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 Coordinates = require('ripple/platform/w3c/1.0/Coordinates');

module.exports = function () {
    return {
        coords: new Coordinates(),
        timestamp: new Date().getTime()
    };
};

});
define('ripple/platform/w3c/1.0/PositionError', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self = function () {
    return {
        code: undefined,
        message: undefined
    };
};

_self.PERMISSION_DENIED = "PERMISSION_DENIED";
_self.POSITION_UNAVAILABLE = "POSITION_UNAVAILABLE";
_self.TIMEOUT = "TIMEOUT";

module.exports = _self;

});
define('ripple/platform/w3c/1.0/Rotation', function (require, exports, module) {
module.exports = function (alpha, beta, gamma) {
    return {
        alpha: alpha || 0,    //Rotation about the 'z' axis expressed in degrees [0, 360].    (Number)
        beta: beta || 0,      //Rotation about the 'x' axis expressed in degrees [-180, 180]. (Number)
        gamma: gamma || 0     //Rotation about the 'y' axis expressed in degrees [-90, 90].   (Number)
    };
};

});
define('ripple/platform/w3c/1.0/SensorConnection', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    platform = require('ripple/platform'),
    event = require('ripple/event'),
    sensorSettings = require('ripple/sensorSettings'),
    accelerometer = require('ripple/accelerometer'),
    exception = require('ripple/exception'),

    _permission = true,
    _self;

function ErrorMsg() {
    this.__defineGetter__("UNKNOWN_ERROR", function () {
        return "An unknown error has occurred.";
    });

    this.__defineGetter__("TYPE_MISMATCH_ERROR", function () {
        return "The object type is incompatible with the expected type.";
    });

    this.__defineGetter__("INVALID_VALUES_ERROR", function () {
        return "The content of an object does not contain valid values.";
    });

    this.__defineGetter__("ILLEGAL_STATE", function () {
        return "The status of connection is illegal.";
    });
}

// TODO: Should be replaced by a global object in tizen 1.0
function ErrorCode() {
    this.__defineGetter__("UNKNOWN_ERR", function () {
        return 0;
    });

    this.__defineGetter__("INVALID_VALUES_ERROR", function () {
        return 1;
    });

    this.__defineGetter__("TYPE_MISMATCH_ERROR", function () {
        return 2;
    });

    this.__defineGetter__("ILLEGAL_STATE", function () {
        return 3;
    });
}

function SensorError(code, msg) {
    this.__defineGetter__("message", function () {
        return msg;
    });
    this.__defineGetter__("code", function () {
        return code;
    });

    this.PERMISSION_DENIED = -100;
}

function Event() {
    var _self = {
        CAPTURING_PHASE: 1,
        AT_TARGET:  2,
        BUBBLING_PHASE: 3,

        type: '',
        target: null, //new EventTarget(),
        currentTarget: null, //new EventTarget(),
        eventPhase: 0,
        bubbles: false,
        cancelable: false,
        timeStamp: 0
    };
        
    this.__defineGetter__("type", function () {
        return _self.type;
    });

    this.__defineGetter__("target", function () {
        return _self.target;
    });

    this.__defineGetter__("currentTarget", function () {
        return _self.currentTarget;
    });

    this.__defineGetter__("eventPhase", function () {
        return _self.eventPhase;
    });    

    this.__defineGetter__("bubbles", function () {
        return _self.bubbles;
    });

    this.__defineGetter__("cancelable", function () {
        return _self.cancelable;
    });
    
    this.__defineGetter__("timeStamp", function () {
        return _self.timeStamp;
    });

    this.stopPropagation = function () {};

    this.preventDefault = function () {};

    this.initEvent = function (eventTypeArg, canBubbleArg, cancelableArg) {
        _self.type = eventTypeArg;
        _self.bubbles = canBubbleArg;
        _self.cancelable = cancelableArg;
    };

    return _self;
}

function SensorDataEvent() {
    var _self = {
        data: 0,
        accuracy: 0,
        timestamp: 0,
        reason: ''
    };

    // This type of event inherit from Event
    Event.call(this);

    this.__defineGetter__("data", function () {
        return _self.data;
    });

    this.__defineGetter__("accuracy", function () {
        return _self.accuracy;
    });

    this.__defineGetter__("timestamp", function () {
        return _self.timestamp;
    });

    this.__defineGetter__("reason", function () {
        return _self.reason;
    });

    this.initSensorDataEvent = function (type, bubbles, cancelable, reason, timestamp, accuracy, data) {
        this.initEvent(type, bubbles, cancelable);

        _self.reason = reason;
        _self.timestamp = timestamp;
        _self.accuracy = accuracy;
        
        // If the data has only one part, just return the value, not the data object    
        if (utils.count(data) === 1) {
            utils.forEach(data, function (section, key) {
                _self.data = data[key];
            });
        }
        else {
            _self.data = utils.copy(data);
        }
    };
}

// As only one sensor will be used during the simulation with a SensorConnection object,
// we can get that sensor object first and then the following read or write operations will be simplified
function _getSensorObj(type, name) {
    var settings = platform.current().sensor, _sensor;

    utils.forEach(settings, function (settingSection, settingType) {
        if (settingSection.type === type) {

            if (settingSection.name && settingSection.name !== name) {
                return;
            }

            _sensor = utils.copy(settingSection);
        }
    });

    return _sensor;
}

function _getAccelerometerData(dataType) {
    var accelerometerData, data = {};

    switch (dataType) {
    case "Accelerometer":
        accelerometerData = accelerometer.getInfo();
        data = {
            x: accelerometerData.acceleration.x,
            y: accelerometerData.acceleration.y,
            z: accelerometerData.acceleration.z
        };
        break;
    case "Rotation":
        accelerometerData = accelerometer.getInfo();
        data = {
            x: accelerometerData.orientation.alpha,
            y: accelerometerData.orientation.beta,
            z: accelerometerData.orientation.gamma
        };
        break;
    case "Orientation":
        accelerometerData = accelerometer.getInfo();
        data = {
            alpha: accelerometerData.orientation.alpha,
            beta: accelerometerData.orientation.beta,
            gamma: accelerometerData.orientation.gamma
        };
        break;
    default:
        break;
    }

    return data;
}

// The parameter of event callback is an object that contains the latest value, not the value itself,
// so we need a function to create such object.
function _getSensorData(sensorType, sensor, onerror) {
    var data = {}, value;

    if (sensorType === "Accelerometer" || sensorType === "Rotation" || sensorType === "Orientation") {
        return _getAccelerometerData(sensorType);
    }

    utils.forEach(sensor, function (sensorSection, key) {
        try {
            value = sensorSettings.retrieve(sensorType + "." + key);
        }
        catch (e) {
            if (onerror) {
                onerror(e);
            }
        }
        
        if (value) {
            data[key] = value;
        }                    
    });
    
    return data;
}

// As the event type in sensor.js file are named in this way, so we can get it with this function.
function _getSensorEventTypes(type, sensor) {
    var types = [];

    if (type === "Accelerometer" || type === "Rotation" || type === "Orientation") {
        return ["AccelerometerInfoChangedEvent"];
    }

    utils.forEach(sensor, function (sensorSection, sensorType) {
        if (typeof sensorSection === "object") {
            types.push(type + "-" + sensorType + "Changed");
        }
    });

    return types;
}

function _onEventCallback(type, options, currentSensor, length, eventCallback, onerror) {
    return function (values) {
        var sensorEvent = new SensorDataEvent();

        // Only the sensor that has one attribute could be compared with the threshold
        if (options && options.threshold && length === 1 && values[0] < options.threshold) {
            return;
        }

        if (eventCallback) {
            sensorEvent.initSensorDataEvent(type, false, false, "read", (new Date()).getTime(), 
                                            currentSensor.resolution, _getSensorData(type, currentSensor, onerror));

            eventCallback(sensorEvent);
        }
    };
}

function _bind(name, obj) {
    var callback = null;

    obj.__defineGetter__(name, function () {
        return callback;
    });

    obj.__defineSetter__(name, function (cb) {
        callback = cb;
    });

    return {
        get: function () {
            return callback;
        },
        set: function (value) {
            callback = value;
        },
        exec: function (arg) {
            return callback && callback(arg);
        },
        unbind: function (cb) {
            callback = cb === callback ? null : callback;
        }
    };
}

function SensorConnection(type, name) {
    var _self,
        currentSensor = _getSensorObj(type, name),
        sensorEvent = new SensorDataEvent(),
        sensorEventTypes = _getSensorEventTypes(type, currentSensor),
        watches = [],
        _errorCode = new ErrorCode(),
        _errorMsg = new ErrorMsg(),
        sensorListener;

    if (currentSensor) {
        _self = {
            sensor: {
                resolution: currentSensor.resolution,
                minDelay: currentSensor.minDelay,
                range: currentSensor.range,
                name: currentSensor.name,
                type: currentSensor.type
            },
            status: "open",
            error: null,
            read: function () {

                if (_self.status !== "open" && _self.status !== "watching") {
                    exception.raise(exception.types.Argument, "illegal state", new SensorError(_errorCode.ILLEGAL_STATE, _errorMsg.ILLEGAL_STATE));
                    return;
                }                

                setTimeout(function () {
                    if (sensorListener.get()) {
                        sensorEvent.initSensorDataEvent(type, false, false, "read", (new Date()).getTime(), 
                                                        currentSensor.resolution, _getSensorData(type, currentSensor, _self.onerror));

                        sensorListener.exec(sensorEvent);
                    }
                }, 1);  

                return;
            },

            startWatch: function (options) {
                var index, watchId, watchObj = {};

                if (_self.status !== "open") {
                    exception.raise(exception.types.Argument, "illegal state", new SensorError(_errorCode.ILLEGAL_STATE, _errorMsg.ILLEGAL_STATE));
                    return;
                }
                    
                if (typeof options !== "object") {
                    if (_self.onerror) {
                        _self.onerror(new SensorError(_errorCode.TYPE_MISMATCH_ERROR, _errorMsg.TYPE_MISMATCH_ERROR));
                    }
                }

                setTimeout(function () {
                    watchId = (new Date()).getTime();   

                    // As there will be many attributes for some sensor, each of them is needed to be watched.
                    for (index = 0; index < sensorEventTypes.length; index++) {
                        watchObj = {
                            eventType: sensorEventTypes[index],
                            onEvent: _onEventCallback(type, options, currentSensor, sensorEventTypes.length, sensorListener.get(), _self.onerror),
                        };

                        watches.push(watchObj);
                        if (watchObj.eventType) {
                            event.on(watchObj.eventType, watchObj.onEvent);                                               
                        }
                    }

                    
                    if (options && options.interval) {
                        watchObj.intervalId = setInterval(_onEventCallback(type, options, currentSensor, sensorEventTypes.length, sensorListener.get(), _self.onerror), 
                                                          options.interval);
                    }

                    _self.status = "watching";
                    if (_self.onstatuschange) {
                        _self.onstatuschange();
                    }
                                                                                                        
                }, 1);  

                return;
            },

            endWatch: function () {
                var index, watchObj;

                if (_self.status !== "watching") {
                    exception.raise(exception.types.Argument, "illegal state", new SensorError(_errorCode.ILLEGAL_STATE, _errorMsg.ILLEGAL_STATE));
                    return;
                }

                for (index = 0; index < watches.length; index++) {
                    watchObj = watches[index];

                    try {
                        event.deleteEventHandler(watchObj.eventType, watchObj.onEvent);  
                    }
                    catch (e) {
                        if (_self.onerror) {
                            _self.onerror(e);
                        }
                    }

                    if (watchObj.intervalId) {
                        clearInterval(watchObj.intervalId);
                    }                
                }

                watches = [];

                _self.status = "open";
                if (_self.onstatuschange) {
                    _self.onstatuschange();
                }
            },

            // These functions are inherited from the EventTarget object
            addEventListener: function (eventType, callback, useCapture) {
                var sensorEvent;
                
                if (eventType === "sensordata") {
                    sensorListener.set(callback);  

                    event.on("sensordata", function (data) {
                        sensorEvent = new SensorDataEvent();        
                        sensorEvent.initSensorDataEvent("sensordata", false, false, "read", (new Date()).getTime(), 
                                                        currentSensor.resolution, _getSensorData(type, currentSensor, _self.onerror));           

                        sensorListener.exec(sensorEvent);
                    });             
                }               
            },

            removeEventListener: function (eventType, callback) {
                event.clear(eventType, callback);
                sensorListener.unbind(callback);                                
            },

            dispatchEvent: function (evt) {
                event.trigger("sensordata", evt);
            }
        };

        sensorListener = _bind("onsensordata", _self);
    }    

    return _self;
}

module.exports = function (option) {
 
    var connectionObj,
        _errorCode = new ErrorCode(),
        _errorMsg = new ErrorMsg();

    if (option === null || option === undefined) {
        return null;
    }

    // There are two ways to construct an object
    if (typeof option === "object") {
        if ((option.type === null || option.type === undefined) &&
            (option.name === null || option.name === undefined)) {
            // Spec: If none of the dictionary members are defined then raise an instantiation exception    
            exception.raise(exception.types.Argument, "type illegal", new SensorError(_errorCode.ILLEGAL_TYPE, _errorMsg.ILLEGAL_TYPE));             
        }

        connectionObj = new SensorConnection(option.type, option.name);
    }
    else if (typeof option === "string") {
        connectionObj = new SensorConnection(option, option);
    }

    return connectionObj;
};

});
define('ripple/platform/w3c/1.0/geolocation', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 geo = require('ripple/geo'),
    Position = require('ripple/platform/w3c/1.0/Position'),
    PositionError = require('ripple/platform/w3c/1.0/PositionError'),
    _watches = {},
    _self;

function createPosition() {
    var position = new Position(),
        positionInfo = geo.getPositionInfo();

    position.coords.latitude = positionInfo.latitude;
    position.coords.longitude = positionInfo.longitude;
    position.coords.altitude = positionInfo.altitude;
    position.coords.altitudeAccuracy = positionInfo.altitudeAccuracy;
    position.coords.accuracy = positionInfo.accuracy;
    position.coords.heading = positionInfo.heading;
    position.coords.speed = positionInfo.speed;
    position.timestamp = positionInfo.timeStamp.getTime();

    return position;
}

_self = {
    getCurrentPosition: function (onSuccess, onError) {
        var delay = ((geo.delay || 0) * 1000) || 1,
            timeout = geo.timeout;

        window.setTimeout(function () {
            if (timeout) {
                var error = new PositionError();
                error.code = PositionError.TIMEOUT;
                error.message = "postion timed out";

                onError(error);
            }
            else {
                // TODO: build facility to trigger onError() from emulator
                // see pivotal item: https://www.pivotaltracker.com/story/show/7040343
                _self.lastPosition = createPosition();
                onSuccess(_self.lastPosition);
            }
        }, delay);
    },

    watchPosition: function (geolocationSuccess, geolocationError, geolocationOptions) {
        var watchId = (new Date()).getTime().toString(),
            watchObj = {},
            timeout;

        if (geolocationOptions) {
            timeout = geolocationOptions.timeout || 10000;

            watchObj = {
                onSuccess: geolocationSuccess,
                onError: geolocationError,
                interval: timeout
            };

            _watches[watchId] = watchObj;

            _watches[watchId].intervalId = window.setInterval(function () {
                _self.getCurrentPosition(_watches[watchId].onSuccess, _watches[watchId].onError);
            }, timeout);

        }
        else {
            if (typeof geolocationError === "function") {
                window.setTimeout(function () {
                    geolocationError();
                }, 1);
            }
        }

        return watchId;
    },

    lastPosition: null,

    clearWatch: function (watchId) {
        window.clearInterval(_watches[watchId].intervalId);
        delete _watches[watchId];
    }
};

module.exports = _self;

});
define('ripple/platform/w3c/1.0/navigator', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _original = window.navigator,
    utils = require('ripple/utils'),
    devices = require('ripple/devices'),
    constants = require('ripple/constants'),
    _self = {};

(function () {
    var key,
        nav = window.navigator;

    function _handle(obj, key) {
        return typeof obj[key] !== "function" ? obj[key] : function () {
            return obj[key].apply(obj, Array.prototype.slice.call(arguments));
        };
    }

    for (key in nav) {
        _self[key] = _handle(nav, key);
    }
}());

_self.__defineGetter__('userAgent', function () {
    var currentUserAgent = devices.getCurrentDevice().userAgent;

    return currentUserAgent === constants.COMMON.USER_AGENT_DEFAULT ?
        _original.userAgent : currentUserAgent;
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/AccelerometerInfo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 accelerometer = require('ripple/accelerometer'),
    _self = {};

_self.__defineGetter__("xAxis", function () {
    return accelerometer.getInfo().accelerationIncludingGravity.x;
});

_self.__defineGetter__("yAxis", function () {
    return accelerometer.getInfo(true).accelerationIncludingGravity.y;
});

_self.__defineGetter__("zAxis", function () {
    return accelerometer.getInfo(true).accelerationIncludingGravity.z;
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/Account', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 deviceSettings = require('ripple/deviceSettings'),
    _self;

_self = {
    accountName: undefined,
    accountId: undefined
};

_self.__defineGetter__("accountName", function () {
    return deviceSettings.retrieve("Account.accountName");
});

_self.__defineGetter__("accountId", function () {
    return deviceSettings.retrieve("Account.accountId");
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/AccountInfo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 deviceSettings = require('ripple/deviceSettings'),
    _self = {
        phoneUserUniqueId: undefined,
        phoneMSISDN: undefined,
        phoneOperatorName: undefined,
        userAccountBalance: undefined,
        userSubscriptionType: undefined
    };

_self.__defineGetter__("phoneUserUniqueId", function () {
    return deviceSettings.retrieve("AccountInfo.phoneUserUniqueId");
});

_self.__defineGetter__("phoneMSISDN", function () {
    return deviceSettings.retrieve("AccountInfo.phoneMSISDN");
});

_self.__defineGetter__("phoneOperatorName", function () {
    return deviceSettings.retrieve("AccountInfo.phoneOperatorName");
});

_self.__defineGetter__("userAccountBalance", function () {
    return deviceSettings.retrieve("AccountInfo.userAccountBalance");
});

_self.__defineGetter__("userSubscriptionType", function () {
    return deviceSettings.retrieve("AccountInfo.userSubscriptionType");
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/AddressBookItem', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    db = require('ripple/db'),
    constants = require('ripple/constants'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes');

function _validateArgs(min, max, len) {
    utils.validateNumberOfArguments(min, max, len,
        ExceptionTypes.INVALID_PARAMETER, "invalid number of parameters", new Exception());
}

function _validateType(arg, argType) {
    utils.validateArgumentType(arg, argType,
        ExceptionTypes.INVALID_PARAMETER,  "argument of wrong type provided",
        new Exception());
}

module.exports = function () {
    function _throwUnsupportedException(method) {
        exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
    }

    this.addressBookItemId = undefined;
    this.fullName = undefined;
    this.mobilePhone = undefined;
    this.homePhone = undefined;
    this.workPhone = undefined;
    this.eMail = undefined;
    this.company = undefined;
    this.title = undefined;
    this.address = undefined;

    this.setAttributeValue = function (attribute, value) {
        _validateArgs(2, 2, arguments.length);
        _validateType(attribute, "string");
        this[attribute] = value;
    };
    this.setAddressGroupNames = function (groups) {
        _throwUnsupportedException("PIM.AddressBookItem.setAddressGroupNames");
    };
    this.getAttributeValue = function (attribute) {
        _validateArgs(1, 1, arguments.length);
        _validateType(attribute, "string");
        return this[attribute];
    };
    this.getAddressGroupNames = function () {
        _throwUnsupportedException("PIM.AddressBookItem.getAddressGroupNames");
    };
    this.getAvailableAttributes = function () {
        return utils.reduce(this, function (attributes, value, key) {
            if (typeof(value) !== 'function') {
                attributes.push(key);
            }
            return attributes;
        }, []).sort();
    };
    this.update = function () {
        var items = db.retrieveObject(constants.PIM.ADDRESS_LIST_KEY),
            that = this,
            itemIndex = items.reduce(function (current, value, i) {
                return value.addressBookItemId === that.addressBookItemId ?
                    i : current;
            }, -1);

        if (itemIndex >= 0) {
            items[itemIndex] = this;
            db.saveObject(constants.PIM.ADDRESS_LIST_KEY, items);
        }
        else {
            exception.raise(ExceptionTypes.INVALID_PARAMETER, "Address Book Item not found: " + (this.addressBookItemId || ""), new Exception());
        }

    };
};

});
define('ripple/platform/wac/1.0/ApplicationTypes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    constants = require('ripple/constants'),
    _self = {};

utils.forEach(constants.PLATFORMS.WAC.APPLICATIONS, function (application) {
    _self.__defineGetter__(application, function () {
        return application;
    });
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/Attachment', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function () {
    this.fileName = "";
    this.MIMEType = "";
    this.size = 0;
};

});
define('ripple/platform/wac/1.0/AudioPlayer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    event = require('ripple/event'),
    exception = require('ripple/exception'),
    utils = require('ripple/utils'),
    fileSystem = require('ripple/fileSystem'),
    _console = require('ripple/console'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    _self,
    _state = null,
    _STATES = constants.MULTIMEDIA.AUDIO_STATES,
    _currentAudioFile,
    _audio, _loopCount;

event.on("MultimediaAudioStateChanged", function updateAudioState(state) {
    _state = state;
    if (typeof _self.onStateChange === 'function') {
        _self.onStateChange.apply(_self, arguments);
    }
});

_audio = utils.createElement("audio", {
    "id": "multimedia-audio"
});

_audio.addEventListener('error', function () {
    _console.warn("AudioPlayer encountered an error: " + _audio.error.code);
    if (_audio.error.code === 4) {
        _console.warn("AudioPlayer error 4 could be caused by missing codecs");
    }
    _state = null;
    event.trigger("MultimediaAudioStateChanged", [null], true);
});

_audio.addEventListener('ended', function handleAudioEnded() {
    event.trigger("MultimediaAudioStateChanged", [_STATES.COMPLETED], true);
    if (_loopCount > 1) {
        _self.open(_currentAudioFile);
        _self.play(_loopCount--);
    }
});

document.getElementById("ui").appendChild(_audio);

function _validateAndSet(state, validStates, callbackBeforeSuccess) {
    var i, valid = false;

    for (i = 0; i < validStates.length; i++) {
        if (validStates[i] === _state) {
            valid = true;
        }
    }

    if (!valid) {
        _console.warn("Attempted to initiate AudioPlayer." + state +
            " in invalid state. current state: " + _state);
    } else {
        if (typeof(callbackBeforeSuccess) === "function") {
            callbackBeforeSuccess.apply();
        }
        event.trigger("MultimediaAudioStateChanged", [state], true);
    }

    return valid;
}

function _validateAudioType(fileUrl) {
    var matched = fileUrl.match(/\.(\w*)$/),
        type = matched ? matched[1] : "";

    if (_audio && _audio.canPlayType("audio/" + type) === "") {
        _console.warn("Attempting to load an audio that might not work in the current browser [" + fileUrl + "]");
    }
}

_self = {
    onStateChange: undefined,

    open: function (fileUrl) {
        utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.open wrong number of arguments", new Exception());
        utils.validateArgumentType(fileUrl, "string", ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.open invalid parameter! expected string, fileUrl: " +
            fileUrl, new Exception());

        if (fileUrl.match(/^rtsp:\/\//)) {
            exception.raise(exception.types.MethodNotImplemented, "rtsp:// scheme not yet supported. sorry :(");
        }

        _validateAndSet(_STATES.OPENED, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED, null], function () {
            _validateAudioType(fileUrl);
            _currentAudioFile = fileSystem.getURI(fileUrl);
            _audio.setAttribute("src", _currentAudioFile);
            _audio.load();
        });
    },

    play: function (repeatTimes) {
        utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.play wrong number of arguments", new Exception());
        utils.validateArgumentType(repeatTimes, "integer", ExceptionTypes.INVALID_PARAMETER, "Multimedia.js.AudioPlayer.play invalid parameter! expected integer, repeatTimes: " + repeatTimes, new Exception());

        if (repeatTimes < 0) {
            exception.raise(ExceptionTypes.INVALID_PARAMETER, "value of repeatTimes must be greater than 0", new Exception());
        }

        if (repeatTimes !== 0) {
            _validateAndSet(_STATES.PLAYING, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED], function () {
                _loopCount = repeatTimes;
                _audio.play();
            });
        }
    },

    pause: function () {
        _validateAndSet(_STATES.PAUSED, [_STATES.PLAYING], function () {
            _audio.pause();
        });
    },

    resume: function () {
        _validateAndSet(_STATES.PLAYING, [_STATES.PAUSED], function () {
            _audio.play();
        });
    },

    stop: function () {
        _validateAndSet(_STATES.STOPPED, [_STATES.PAUSED, _STATES.PLAYING], function () {
            try {
                _audio.pause();
                _audio.currentTime = 0;
            } catch (e) {
                //HACK: do nothing, this could throw a dom exception 11 sometimes when playing an mp3 or before the file has loaded.
                //see http://developer.palm.com/distribution/viewtopic.php?f=11&t=7568
            }
        });
    }
};

module.exports = _self;

});
define('ripple/platform/wac/1.0/CalendarItem', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    db = require('ripple/db'),
    exception = require('ripple/exception'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes');

module.exports = function () {
    this.calendarItemId = undefined;
    this.alarmDate = undefined;
    this.eventStartTime = undefined;
    this.eventEndTime = undefined;
    this.eventName = undefined;
    this.eventNotes = undefined;
    this.alarmed = undefined;

    this.update = function () {
        var events = db.retrieveObject(constants.PIM.CALENDAR_LIST_KEY) || [],
            that = this,
            eventIndex = events.reduce(function (match, value, i) {
                return value.calendarItemId === that.calendarItemId ?
                    i : match;
            }, -1);


        if (eventIndex >= 0) {
            events[eventIndex] = this;
            db.saveObject(constants.PIM.CALENDAR_LIST_KEY, events);
        }
        else {
            exception.raise(ExceptionTypes.INVALID_PARAMETER, "Calendar Item not found: " + (this.calendarItemId || ""), new Exception());
        }
    };
};

});
define('ripple/platform/wac/1.0/CallRecord', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function () {
    this.callRecordType = undefined;
    this.callRecordId = undefined;
    this.callRecordAddress = undefined;
    this.callRecordName = undefined;
    this.durationSeconds = undefined;
    this.startTime = undefined;
};

});
define('ripple/platform/wac/1.0/CallRecordTypes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    RECEIVED: "received",
    OUTGOING: "outgoing",
    MISSED: "missed"
};

});
define('ripple/platform/wac/1.0/Camera', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 exception = require('ripple/exception'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    constants = require('ripple/constants'),
    _console = require('ripple/console'),
    utils = require('ripple/utils'),
    notifications = require('ripple/notifications'),
    _currentlySet,
    _img,
    _buttons,
    _self,
    _videoCapture;


function _populateWindow(domObject) {
    var record = document.createElement("button"),
        pause = document.createElement("button"),
        stop = document.createElement("button");

    _img = document.createElement("img");
    _img.setAttribute("id", "jil-camera-window");
    //_img.setAttribute("src", document.querySelector("#extension-url").innerHTML + constants.CAMERA.WINDOW_ANIMATION);
    _img.setAttribute("src", document.documentURI.replace(/index\.html$/, "") + constants.CAMERA.WINDOW_ANIMATION);
    _img.setAttribute("width", "100%");
    _currentlySet = domObject;
    domObject.appendChild(_img);

    _buttons = document.createElement("div");
    _buttons.setAttribute("id", "jil-camera-window-buttons");
    _buttons.setAttribute("style", "display: none");

    record.setAttribute("id", "jil-camera-window-buttons-record");
    record.innerHTML = "Record";
    pause.setAttribute("id", "jil-camera-window-buttons-pause");
    pause.innerHTML = "Pause";
    stop.setAttribute("id", "jil-camera-window-buttons-stop");
    stop.innerHTML = "Stop";
    stop.addEventListener("click", _self.stopVideoCapture);

    _buttons.appendChild(record);
    _buttons.appendChild(pause);
    _buttons.appendChild(stop);

    domObject.appendChild(_buttons);

}

function _verifySetWindow(method) {
    if (!_img) {
        exception.raise(ExceptionTypes.UNKNOWN, "Camera." +
          method + " was (most likely) called before using the setWindow method.", new Exception());
    }
}

_self = {
    onCameraCaptured: undefined, //function (fileName) { }

    captureImage: function (fileName, lowRes) {
        utils.validateNumberOfArguments(2, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "captureImage invalid number of parameters", new Exception());
        utils.validateMultipleArgumentTypes([fileName, lowRes], ['string', 'boolean'], ExceptionTypes.INVALID_PARAMETER, "invalid parameter type", new Exception());

        _verifySetWindow("captureImage");
        var msg = constants.CAMERA.WARNING_TEXT;
        msg = msg.replace("{file}", fileName);
        notifications.openNotification("normal", msg);
        _console.log("simulated saved image as: " + fileName);
        if (_self.onCameraCaptured) {
            _self.onCameraCaptured.apply(_self, [fileName]);
        }

        return fileName;
    },
    setWindow: function (domObject) {

        if (_currentlySet) {
            _currentlySet.removeChild(_img);
            _currentlySet.removeChild(_buttons);
            _currentlySet = null;
            _img = null;
            _buttons = null;
        }
        if (domObject !== null) {
            _populateWindow(domObject);
        }
    },
    startVideoCapture: function (fileName, lowRes, maxDurationSeconds, showDefaultControls) {
        _verifySetWindow("startVideoCapture");
        utils.validateNumberOfArguments(1, 4, arguments.length, ExceptionTypes.INVALID_PARAMETER, "startVideoCapture invalid number of parameters", new Exception());
        utils.validateMultipleArgumentTypes(
            [fileName, lowRes, maxDurationSeconds, showDefaultControls],
            ['string', 'boolean', 'integer', 'boolean'],
            ExceptionTypes.INVALID_PARAMETER,
            "invalid parameter type", new Exception());
        _console.log("started recording video");
        var interval = window.setTimeout(function () {
            _self.stopVideoCapture();
        }, maxDurationSeconds * 1000);

        if (showDefaultControls) {
            _buttons.removeAttribute("style");
        }

        _videoCapture = {
            fileName: fileName,
            stop: function () {
                window.clearInterval(interval);
                var msg = constants.CAMERA.WARNING_TEXT;
                msg = msg.replace("{file}", fileName);
                notifications.openNotification("normal", msg);
                if (_self.onCameraCaptured) {
                    _self.onCameraCaptured.apply(_self, [fileName]);
                }
            }
        };

        return fileName;
    },
    stopVideoCapture: function () {
        utils.validateNumberOfArguments(0, 0, arguments.length, ExceptionTypes.INVALID_PARAMETER, "stopVideoCapture invalid number of parameters", new Exception());
        if (_videoCapture) {
            _console.log("simulated saving a video as: " + _videoCapture.fileName);
            if (_buttons) {
                _buttons.setAttribute("style", "display: none");
            }
            _videoCapture.stop();
            _videoCapture = null;
        }
    }

};

module.exports = _self;

});
define('ripple/platform/wac/1.0/Config', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    notifications = require('ripple/notifications'),
    constants = require('ripple/constants'),
    deviceSettings = require('ripple/deviceSettings'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    _self = {
        ringtoneVolume: undefined,
        msgRingtoneVolume: undefined,
        vibrationSetting: undefined,

        setDefaultRingtone: function (ringtoneUrl) {
            utils.validateArgumentType(ringtoneUrl, "string", ExceptionTypes.INVALID_PARAMETER, "ringtoneUrl paramter is not a string", new Exception());
            notifications.openNotification("normal", "Setting default ringtone to: " + ringtoneUrl);
        },

        setAsWallpaper: function (wallpaperUrl) {
            utils.validateArgumentType(wallpaperUrl, "string", ExceptionTypes.INVALID_PARAMETER, "wallpaperUrl paramter is not a string", new Exception());
            notifications.openNotification("normal", "Setting wallpaper to: " + wallpaperUrl);
        }
    };

_self.__defineGetter__("ringtoneVolume", function () {
    return deviceSettings.retrieve("Config.ringtoneVolume");
});

_self.__defineGetter__("msgRingtoneVolume", function () {
    return deviceSettings.retrieve("Config.msgRingtoneVolume");
});

_self.__defineGetter__("vibrationSetting", function () {
    return deviceSettings.retrieve("Config.vibrationSetting");
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/DataNetworkConnectionTypes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    _self = {
        "BLUETOOTH": undefined,
        "EDGE": undefined,
        "EVDO": undefined,
        "GPRS": undefined,
        "IRDA": undefined,
        "LTE": undefined,
        "ONEXRTT": undefined,
        "WIFI": undefined
    };

utils.forEach(_self, function (value, property) {
    _self.__defineGetter__(property, function () {
        return property;
    });
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/DataNetworkInfo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    _console = require('ripple/console'),
    deviceSettings = require('ripple/deviceSettings'),
    DataNetworkConnectionTypes = require('ripple/platform/wac/1.0/DataNetworkConnectionTypes'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),

_self = {
    isDataNetworkConnected: undefined,
    networkConnectionType: undefined,
    onNetworkConnectionChanged: undefined,

    getNetworkConnectionName: function (networkConnectionType) {
        var foundConnectionType;
        utils.validateArgumentType(networkConnectionType, "string", ExceptionTypes.INVALID_PARAMETER, "networkConnectionType is invalid, expected a string", new Exception());
        foundConnectionType = DataNetworkConnectionTypes[networkConnectionType.toUpperCase()];
        return foundConnectionType || null;
    }
};

event.on("DataNetworkConnectionChanged", function (newConnectionName) {
    var callback = _self.onNetworkConnectionChanged,
        msg = "Fired onNetworkConnectionChanged with newConnectionName: " + newConnectionName;

    if (callback && typeof callback === "function") {
        callback.apply(null, [newConnectionName]);
    }
    else {
        msg += " --> BUT there was no registered callback found.";
    }

    _console.log(msg);
});

_self.__defineGetter__("isDataNetworkConnected", function () {
    return deviceSettings.retrieveAsBoolean("DataNetworkInfo.isDataNetworkConnected");
});

_self.__defineGetter__("networkConnectionType", function () {
    var value = deviceSettings.retrieve("DataNetworkInfo.networkConnectionType");
    return value instanceof Array ? value : [value];
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/Device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    exception = require('ripple/exception'),
    _console = require('ripple/console'),
    utils = require('ripple/utils'),
    notifications = require('ripple/notifications'),
    ApplicationTypes = require('ripple/platform/wac/1.0/ApplicationTypes'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    _applicationTypes = {
        FILES: "FILES",
        MEDIAPLAYER: "MEDIAPLAYER",
        PHONECALL: "PHONECALL",
        PICTURES: "PICTURES"
    },
    _self;

function _throwUnsupportedException(method) {
    exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
}

_self = {
    // Properties
    clipboardString: undefined,
    widgetEngineName: undefined,
    widgetEngineProvider: undefined,
    widgetEngineVersion: undefined,

    // Methods
    getAvailableApplications: function () {
        return constants.PLATFORMS.WAC.APPLICATIONS || [];
    },

    getDirectoryFileNames: function () {
        _throwUnsupportedException("Device.getDirectoryFileNames");
    },
    getFile: function () {
        _throwUnsupportedException("Device.getFile");
    },

    launchApplication: function launchApplication(application, startParameter) {
        if (!application || typeof(application) !== "string") {
            exception.raise(ExceptionTypes.INVALID_PARAMETER,
                    "Invalid argument 'application' at Device.launchApplication(): expected to be of type 'string' but was of type: " + (application ? typeof(application) : "null"),
                    Exception);
        }

        if (startParameter && typeof(startParameter) !== "string") {
            exception.raise(ExceptionTypes.INVALID_PARAMETER,
                    "Invalid argument 'startParameter' at Device.launchApplication(): expected to be 'string' but was : " + typeof(startParameter),
                    Exception);
        }

        // rudimentary implementation for now
        var message = "The widget has requested application: '" + application + "' to be launched. \n\n";

        if (startParameter) {
            message += "The following start parameter was sent in: " + startParameter + "\n\n";
        }

        if (_applicationTypes[application] && !startParameter) {
            message += "Launching this application can also be done with an optional startParameter which was not provided" + "\n\n";
        }

        if (!ApplicationTypes[application]) {
            message += "Note: the application requested is not part of the common values specified by the WAC API.";
        }

        notifications.openNotification("normal", message);
        _console.log(message);
    },

    copyFile: function () {
        _throwUnsupportedException("Device.copyFile");
    },
    deleteFile: function () {
        _throwUnsupportedException("Device.deleteFile");
    },
    findFiles: function () {
        _throwUnsupportedException("Device.findFiles");
    },
    getFileSystemRoots: function () {
        _throwUnsupportedException("Device.getFileSystemRoots");
    },
    getFileSystemSize: function () {
        _throwUnsupportedException("Device.getFileSystemSize");
    },
    moveFile: function () {
        _throwUnsupportedException("Device.moveFile");
    },
    onFilesFound: function () {
        _throwUnsupportedException("Device.onFilesFound");
    },
    setRingtone: function () {
        _throwUnsupportedException("Device.setRingtone");
    },

    vibrate: function (duration) {
        utils.validateArgumentType(duration, "number", ExceptionTypes.INVALID_PARAMETER, "duration paramter is not a number", new Exception());
        notifications.openNotification("normal", "Vibrating for " + duration + " second(s).");
    }

};

_self.__defineGetter__("widgetEngineName", function () {
    return constants.PLATFORMS.WAC.DEVICE.WIDGET_ENGINE_NAME;
});

_self.__defineGetter__("widgetEngineProvider", function () {
    return constants.PLATFORMS.WAC.DEVICE.WIDGET_ENGINE_PROVIDER;
});

_self.__defineGetter__("widgetEngineVersion", function () {
    return constants.PLATFORMS.WAC.DEVICE.WIDGET_ENGINE_VERSION;
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/DeviceInfo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    deviceSettings = require('ripple/deviceSettings'),
    platform = require('ripple/platform'),
    devices = require('ripple/devices'),
    _self;

_self = {
    ownerInfo: undefined, // return AddressBookItem
    phoneColorDepthDefault: undefined,
    phoneFirmware: undefined,
    phoneManufacturer: undefined,
    phoneModel: undefined,
    phoneOS: undefined,
    phoneSoftware: undefined,
    phoneScreenHeightDefault: undefined,
    phoneScreenWidthDefault: undefined,
    totalMemory: undefined
};

function _getDeviceAttribute(attr) {
    var devicePointer = devices.getCurrentDevice();
    utils.forEach(attr.split("."), function (dot) {
        devicePointer = devicePointer[dot];
    });
    return devicePointer;
}

_self.__defineGetter__("phoneColorDepthDefault", function () {
    return deviceSettings.retrieveAsInt("DeviceInfo.phoneColorDepthDefault");
});

_self.__defineGetter__("phoneFirmware", function () {
    return _getDeviceAttribute("firmware");
});

_self.__defineGetter__("phoneManufacturer", function () {
    return _getDeviceAttribute("manufacturer");
});

_self.__defineGetter__("phoneOS", function () {
    return _getDeviceAttribute("osName") + " " + _getDeviceAttribute("osVersion");
});

_self.__defineGetter__("phoneModel", function () {
    return _getDeviceAttribute("model");
});

_self.__defineGetter__("phoneSoftware", function () {
    return _getDeviceAttribute("osVersion");
});

_self.__defineGetter__("phoneScreenHeightDefault", function () {
    return _getDeviceAttribute("screen.height");
});

_self.__defineGetter__("phoneScreenWidthDefault", function () {
    return _getDeviceAttribute("screen.width");
});

_self.__defineGetter__("totalMemory", function () {
    return deviceSettings.retrieveAsInt("DeviceInfo.totalMemory");
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/DeviceStateInfo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    _console = require('ripple/console'),
    geo = require('ripple/geo'),
    event = require('ripple/event'),
    deviceSettings = require('ripple/deviceSettings'),
    PositionInfo = require('ripple/platform/wac/1.0/PositionInfo'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    _self;

event.on("ScreenChangeDimensions", function (width, height) {
    try {
        if (typeof _self.onScreenChangeDimensions === 'function') {
            _self.onScreenChangeDimensions(width, height);
        }
        _console.log("called DeviceStateInfo.onScreenChangeDimensions callback function with width = " + width + " and height = " + height);
    } catch (e) {
        exception.handle(e, false);
    }
});

_self = {
    availableMemory: undefined,
    language: undefined,
    keypadLightOn: undefined,
    backLightOn: undefined,
    processorUtilizationPercent: undefined,
    audioPath: undefined,

    onPositionRetrieved: undefined,

    requestPositionInfo: function (method) {
        utils.validateNumberOfArguments(1, 1, arguments.length,
            ExceptionTypes.INVALID_PARAMETER, "requestPositionInfo invalid number of parameters", new Exception());
        utils.validateArgumentType(method, "string",
            ExceptionTypes.INVALID_PARAMETER, "requestPositionInfo invalid parameter", new Exception());

        if (!(method.match(/gps|agps|cellid/))) {
            exception.raise(ExceptionTypes.INVALID_PARAMETER,
                    "Invalid method, expected (gps, agps or cellid)", Exception);
        }

        if (typeof _self.onPositionRetrieved === "function") {
            var delay = geo.delay * 1000,
                timeout = geo.timeout;
            setTimeout(function () {
                var pos = PositionInfo,
                    errorObj = {};

                if (timeout) {
                    //create
                    utils.forEach(pos, function (val, key) {
                        errorObj[key] = undefined;
                    });
                    pos = errorObj;
                }
                _self.onPositionRetrieved(pos, method);
            }, delay);
        }
    },

    onScreenChangeDimensions: undefined,

    onFlipEvent: undefined
};

_self.__defineGetter__("availableMemory", function () {
    return deviceSettings.retrieveAsInt("DeviceStateInfo.availableMemory");
});

_self.__defineGetter__("language", function () {
    return deviceSettings.retrieve("DeviceStateInfo.language");
});

_self.__defineGetter__("keypadLightOn", function () {
    return deviceSettings.retrieveAsBoolean("DeviceStateInfo.keypadLightOn");
});

_self.__defineGetter__("backLightOn", function () {
    return deviceSettings.retrieveAsBoolean("DeviceStateInfo.backLightOn");
});

_self.__defineGetter__("audioPath", function () {
    return deviceSettings.retrieve("DeviceStateInfo.audioPath");
});

_self.__defineGetter__("processorUtilizationPercent", function () {
    return deviceSettings.retrieve("DeviceStateInfo.processorUtilizationPercent");
});

module.exports = _self;


});
define('ripple/platform/wac/1.0/EventRecurrenceTypes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    NOT_REPEAT: "NOT_REPEAT",
    DAILY: "DAILY",
    EVERY_WEEKDAY: "EVERY_WEEKDAY",
    WEEKLY_ON_DAY: "WEEKLY_ON_DAY",
    MONTHLY_ON_DAY: "MONTHLY_ON_DAY",
    MONTHLY_ON_DAY_COUNT: "MONTHLY_ON_DAY_COUNT",
    YEARLY: "YEARLY"
};

});
define('ripple/platform/wac/1.0/Exception', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = function () {
    this.message = "";
    this.type =  "";

    this.toString = function () {
        var result = this.type + ': "' + this.message + '"';

        if (this.stack) {
            result += "\n" + this.stack;
        }
        return result;
    };
};

});
define('ripple/platform/wac/1.0/ExceptionTypes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self =  {};

_self.__defineGetter__("INVALID_PARAMETER", function () {
    return "invalid_parameter";
});

_self.__defineGetter__("SECURITY", function () {
    return "security";
});

_self.__defineGetter__("UNKNOWN", function () {
    return "unknown";
});

_self.__defineGetter__("UNSUPPORTED", function () {
    return "unsupported";
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/File', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.expots = function () {
    this.createDate = undefined;
    this.fileName = undefined;
    this.filePath = undefined;
    this.fileSize = undefined;
    this.isDirectory = undefined;
    this.lastModifyDate = undefined;
};

});
define('ripple/platform/wac/1.0/Message', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 exception = require('ripple/exception'),
    Attachment = require('ripple/platform/wac/1.0/Attachment'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    Exception = require('ripple/platform/wac/1.0/Exception');

function _throwUnsupportedException(method) {
    exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
}

module.exports = function () {
    this.messageId = Math.uuid(undefined, 16);
    this.callbackNumber = undefined;
    this.destinationAddress = [];
    this.isRead = undefined;
    this.messagePriority = undefined;
    this.messageType = undefined;
    this.subject = undefined;
    this.body = undefined;
    this.sourceAddress = undefined;
    this.validityPeriodHours = undefined;
    this.time = undefined;
    this.ccAddress = [];
    this.bccAddress = [];
    this.attachments = [];

    this.addAttachment = function (fileFullName) {
        var attachment = new Attachment();
        attachment.fileName = fileFullName;
        this.attachments.push(attachment);
    };
    this.deleteAttachment = function (attachment) {

        for (var i = this.attachments.length - 1; i >= 0; i--) {
            if (this.attachments[i].fileName === attachment.fileName) {
                this.attachments.splice(i, 1);
            }
        }
    };
    this.saveAttachment = function (fileFullName, attachment) {
        _throwUnsupportedException("Widget.Messaging.Message.addAddress");
    };
    this.addAddress = function (type, address) {

        var addresses = address.split(";");

        switch (type) {
        case "destination":
            this.destinationAddress = this.destinationAddress.concat(addresses);
            break;
        case "cc":
            this.ccAddress = this.ccAddress.concat(addresses);
            break;
        case "bcc":
            this.bccAddress = this.bccAddress.concat(addresses);
            break;
        }
    };

    this.deleteAddress = function (type, address) {
        var addresses = address.split(";"),
            filter = function (orig) {
                return orig.filter(function (address) {
                    return !addresses.some(function (x) {
                        return address === x;
                    });
                });
            };

        switch (type) {
        case "destination":
            this.destinationAddress = filter(this.destinationAddress);
            break;
        case "cc":
            this.ccAddress = filter(this.ccAddress);
            break;
        case "bcc":
            this.bccAddress = filter(this.bccAddress);
            break;
        }
    };

};

});
define('ripple/platform/wac/1.0/MessageFolderTypes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    DRAFTS: "drafts",
    INBOX: "inbox",
    OUTBOX: "outbox",
    SENTBOX: "sentbox"
};

});
define('ripple/platform/wac/1.0/MessageQuantities', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    totalMessageCnt: undefined,
    totalMessageReadCnt: undefined,
    totalMessageUnreadCnt: undefined
};

});
define('ripple/platform/wac/1.0/MessageTypes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    EmailMessage: "email",
    MMSMessage: "mms",
    SMSMessage: "sms"
};

});
define('ripple/platform/wac/1.0/Messaging', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 exception = require('ripple/exception'),
    utils = require('ripple/utils'),
    constants = require('ripple/constants'),
    notifications = require('ripple/notifications'),
    _console = require('ripple/console'),
    Message = require('ripple/platform/wac/1.0/Message'),
    MessageTypes = require('ripple/platform/wac/1.0/MessageTypes'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes');

function _throwUnsupportedException(method) {
    exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
}

module.exports = {
    onMessageArrived: undefined,
    onMessageSendingFailure: undefined,
    onMessagesFound: undefined,

    createMessage: function (messageType) {
        utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "createMessage invalid number of arguments", new Exception());
        utils.validateArgumentType(messageType, "string", ExceptionTypes.INVALID_PARAMETER, "createMessage invalid arguments", new Exception());

        if (!utils.some(MessageTypes, function (value) {
                return value === messageType;
            })) {
            exception.raise(ExceptionTypes.INVALID_PARAMETER, "createMessage invalid arguments", new Exception());
        }

        var message = new Message();
        message.messageType = messageType;

        return message;
    },
    deleteMessage: function () {
        _throwUnsupportedException("Messaging.deleteMessage");
    },
    getMessage: function () {
        _throwUnsupportedException("Messaging.getMessage");
    },
    getMessageQuantities: function () {
        _throwUnsupportedException("Messaging.getMessageQuantities");
    },
    sendMessage: function (msg) {
        utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.UNSUPPORTED, "sendMessage invalid number of arguments", new Exception());
        if (msg instanceof Message === false) {
            exception.raise(ExceptionTypes.INVALID_PARAMETER, "expected a valid Message object", new Exception());
        }

        //TODO: Must be modded to fail and to then call the onMessageSendingFailure callback
        var message = "Sent " + msg.messageType + " " + msg.messageId + " to " + msg.destinationAddress;

        // insert fail check here
        notifications.openNotification("normal", message);
        _console.log(message);
    },
    moveMessageToFolder: function () {
        _throwUnsupportedException("Messaging.moveMessageToFolder");
    },
    copyMessageToFolder: function () {
        _throwUnsupportedException("Messaging.copyMessageToFolder");
    },
    createFolder: function () {
        _throwUnsupportedException("Messaging.createFolder");
    },
    deleteFolder: function () {
        _throwUnsupportedException("Messaging.deleteFolder");
    },
    getFolderNames: function () {
        _throwUnsupportedException("Messaging.getFolderNames");
    },
    findMessages: function () {
        _throwUnsupportedException("Messaging.findMessages");
    },
    getCurrentEmailAccount: function () {
        _throwUnsupportedException("Messaging.getCurrentEmailAccount");
    },
    getEmailAccounts: function () {
        _throwUnsupportedException("Messaging.getEmailAccounts");
    },
    setCurrentEmailAccount: function () {
        _throwUnsupportedException("Messaging.setCurrentEmailAccount");
    },
    deleteEmailAccount: function () {
        _throwUnsupportedException("Messaging.deleteEmailAccount");
    }

};

});
define('ripple/platform/wac/1.0/Multimedia', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    VideoPlayer = require('ripple/platform/wac/1.0/VideoPlayer'),
    AudioPlayer = require('ripple/platform/wac/1.0/AudioPlayer'),
    constants = require('ripple/constants'),
    _volume = 5,
    _audioState,
    _videoState,
    _self;

event.on("MultimediaVolumeChanged", function updateVolume(volume) {
    _volume = volume;
});

event.on("MultimediaAudioStateChanged", function updateAudioState(state) {
    _audioState = state;
});

event.on("MultimediaVideoStateChanged", function updateVideoState(state) {
    _videoState = state;
});

_self = {

    isAudioPlaying: undefined,
    isVideoPlaying: undefined,

    getVolume: function () {
        return _volume;
    },

    stopAll: function () {
        VideoPlayer.stop();
        AudioPlayer.stop();
    }
};

_self.__defineGetter__("isAudioPlaying", function () {
    return _audioState === constants.MULTIMEDIA.AUDIO_STATES.PLAYING;
});

_self.__defineGetter__("isVideoPlaying", function () {
    return _videoState === "playing";
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/PIM', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    exception = require('ripple/exception'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    AddressBookItem = require('ripple/platform/wac/1.0/AddressBookItem'),
    CalendarItem = require('ripple/platform/wac/1.0/CalendarItem'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    constants = require('ripple/constants');

function _throwUnsupportedException(method) {
    exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
}

function _toAddressBookItem(contact) {
    if (!contact) {
        return null;
    }

    var addressBookItem = new AddressBookItem();

    utils.forEach(contact, function (prop, key) {
        addressBookItem[key] = contact[key];
    });

    return addressBookItem;
}

function _toCalendarItem(item) {
    if (!item) {
        return null;
    }

    var calendarItem = new CalendarItem();

    utils.forEach(item, function (prop, key) {
        calendarItem[key] = item[key];
    });

    return calendarItem;
}

function _getData(type) {
    var data = db.retrieveObject(type) || [];
    return data;
}

function _saveData(type, items) {
    db.saveObject(type, items);
}

function _getContacts() {
    var contacts = _getData(constants.PIM.ADDRESS_LIST_KEY),
        gord,
        dan,
        brent,
        pj,
        mark;

    if (contacts.length === 0) {

        gord = new AddressBookItem();
        gord.addressBookItemId = "0";
        gord.fullName = "Gord Tanner";
        gord.eMail = "gord@tinyHippos.com";
        gord.company = "tinyHippos Inc";
        gord.title = "Code Poet";
        gord.address = "121 Charles Street W, Kitchener, Ontario, Canada";

        dan = new AddressBookItem();
        dan.addressBookItemId = "1";
        dan.fullName = "Dan Silivestru";
        dan.eMail = "dan@tinyHippos.com";
        dan.company = "tinyHippos Inc";
        dan.title = "Co-Founder And Chief Technology Officer";
        dan.address = "121 Charles Street W, Kitchener, Ontario, Canada";

        pj = new AddressBookItem();
        pj.addressBookItemId = "2";
        pj.fullName = "PJ Lowe";
        pj.eMail = "pj@tinyHippos.com";
        pj.company = "tinyHippos Inc";
        pj.title = "Co-Founder And Chief Operations Officer";
        pj.address = "121 Charles Street W, Kitchener, Ontario, Canada";

        brent = new AddressBookItem();
        brent.addressBookItemId = "2";
        brent.fullName = "Brent Lintner";
        brent.eMail = "brent@tinyHippos.com";
        brent.company = "tinyHippos Inc";
        brent.title = "Co-Founder And Chief Operations Officer";
        brent.address = "121 Charles Street W, Kitchener, Ontario, Canada";

        mark = new AddressBookItem();
        mark.addressBookItemId = "3";
        mark.fullName = "Mark McArdle";
        mark.eMail = "mark@tinyHippos.com";
        mark.company = "tinyHippos Inc";
        mark.title = "Chief Executive Officer";
        mark.address = "121 Charles Street W, Kitchener, Ontario, Canada";

        contacts.push(gord);
        contacts.push(dan);
        contacts.push(pj);
        contacts.push(brent);
        contacts.push(mark);

        _saveData(constants.PIM.ADDRESS_LIST_KEY, contacts);
    }
    return contacts.map(_toAddressBookItem);
}

function _getEvents() {
    var events = _getData(constants.PIM.CALENDAR_LIST_KEY);
    return events.map(_toCalendarItem);
}

function _get(type, id, fetchIDFunc) {
    var items = _getData(type);
    return items.reduceRight(function (match, item) {
        return fetchIDFunc(item) === id ? item : match;
    }, null);
}

function _getAddressBookID(item) {
    return item.addressBookItemId;
}

function _getCalendarID(item) {
    return item.calendarItemId;
}

function _getContact(id) {
    return _toAddressBookItem(_get(constants.PIM.ADDRESS_LIST_KEY, id, _getAddressBookID));
}

function _getEvent(id) {
    return _toCalendarItem(_get(constants.PIM.CALENDAR_LIST_KEY, id, _getCalendarID));
}

function _add(type, item, idProp) {
    var items = _getData(type);

    if (!item[idProp]) {
        item[idProp] = Math.uuid(undefined, 16);
    }

    items.push(item);
    _saveData(type, items);
}

function _delete(type, id, fetchIDFunc) {
    var items = _getData(type);

    _saveData(type, items.filter(function (item) {
        return fetchIDFunc(item) !== id;
    }));
}

function _validateArgs(min, max, len) {
    utils.validateNumberOfArguments(min, max, len,
        ExceptionTypes.INVALID_PARAMETER, "invalid number of parameters", new Exception());
}

function _validateType(arg, argType) {
    utils.validateArgumentType(arg, argType,
        ExceptionTypes.INVALID_PARAMETER,  "argument of wrong type provided",
        new Exception());
}

function _validateAddressBookItem(item) {
    if ((item instanceof AddressBookItem) === false) {
        exception.raise(ExceptionTypes.INVALID_PARAMETER, "invalid contact, not instance of AddressBookItem.", new Exception());
    }
}

_self = {
    addAddressBookItem: function (contact) {
        _validateArgs(1, 1, arguments.length);
        _validateAddressBookItem(contact);

        _add(constants.PIM.ADDRESS_LIST_KEY, contact, "addressBookItemId");
    },
    createAddressBookGroup: function (groupName) {
        _throwUnsupportedException("Widget.PIM.createAddressBookGroup");
    },
    createAddressBookItem: function () {
        return new AddressBookItem();
    },
    deleteAddressBookItem: function (contactid) {
        _validateArgs(1, 1, arguments.length);
        _validateType(contactid, "string");
        _delete(constants.PIM.ADDRESS_LIST_KEY, contactid, _getAddressBookID);
    },
    deleteAddressBookGroup: function (groupName) {
        _throwUnsupportedException("Widget.PIM.deleteAddressBookGroup");
    },
    getAddressBookItem: function (contactid) {
        _validateArgs(1, 1, arguments.length);
        _validateType(contactid, "string");
        return _getContact(contactid);
    },
    getAddressBookItemsCount: function () {
        _validateArgs(0, 0, arguments.length);
        var items = _getContacts();
        return items.length;
    },
    getAvailableAddressGroupNames: function () {
        _throwUnsupportedException("Widget.PIM.getAvailableAddressGroupNames");
    },
    getAddressBookGroupMembers: function (groupName) {
        _throwUnsupportedException("Widget.PIM.getAddressBookGroupMembers");
    },
    findAddressBookItems: function (comparisonContact, startInx, endInx) {
        _validateArgs(3, 3, arguments.length);
        utils.validateMultipleArgumentTypes([comparisonContact, startInx, endInx], ["object", "number", "number"], ExceptionTypes.INVALID_PARAMETER,  "argument of wrong type provided",
            new Exception());

        if (endInx < 0) {
            exception.raise(ExceptionTypes.INVALID_PARAMETER, "invalid number of parameters", new Exception());
        }

        startInx = startInx < 0 ? 0 : startInx;

        var contacts = _getContacts();
        utils.find(comparisonContact, contacts, startInx, endInx, _self.onAddressBookItemsFound);
    },

    addCalendarItem: function (calendarItem) {
        _validateArgs(1, 1, arguments.length);
        _add(constants.PIM.CALENDAR_LIST_KEY, calendarItem, "calendarItemId");
    },
    deleteCalendarItem: function (calendarId) {
        _validateArgs(1, 1, arguments.length);
        _delete(constants.PIM.CALENDAR_LIST_KEY, calendarId, _getCalendarID);
    },
    getCalendarItem: function (calendarId) {
        _validateArgs(1, 1, arguments.length);
        return _getEvent(calendarId);
    },
    findCalendarItems: function (itemToMatch, startInx, endInx) {
        _validateArgs(1, 3, arguments.length);
        var events = _getEvents();
        utils.find(itemToMatch, events, startInx, endInx, _self.onCalendarItemsFound);
    },
    getCalendarItems: function (startTime, endTime) {
        var events = _getEvents();

        return events.reduce(function (matches, event) {
            if (event.eventStartTime >= startTime && event.eventStartTime <= endTime) {
                matches.push(event);
            }
            return matches;
        }, []);
    },
    exportAsVCard: function (addressBookItems) {
        _throwUnsupportedException("Widget.PIM.exportAsVCard");
    },

    onAddressBookItemsFound: undefined, // function (addressBookItemsFound) { }
    onCalendarItemsFound: undefined, // function (calendarItemsFound) { }
    onCalendarItemAlert: undefined, // function (calendarItem) { }
    onVCardExportingFinish: undefined // function (vCardFilePath) { }
};

module.exports = _self;

});
define('ripple/platform/wac/1.0/PositionInfo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 geo = require('ripple/geo'),
    event = require('ripple/event'),
    exception = require('ripple/exception'),
    utils = require('ripple/utils'),
    _self = {
        latitude: undefined,
        longitude: undefined,
        altitude: undefined,
        cellID: undefined,
        accuracy: undefined,
        altitudeAccuracy: undefined,
        timeStamp: undefined
    };

utils.forEach(_self, function (value, property) {
    _self.__defineGetter__(property, function () {
        return geo.getPositionInfo()[property];
    });
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/PowerInfo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    event = require('ripple/event'),
    _console = require('ripple/console'),
    deviceSettings = require('ripple/deviceSettings'),
    _lastPercentRemaining;

_self = {
    isCharging: undefined,
    percentRemaining: undefined,

    onChargeStateChange: undefined,
    onLowBattery: undefined,
    onChargeLevelChange: undefined
};

function _getCurrentChargeState(percentRemaining, isCharging) {
    var batteryState;
    if (percentRemaining === 100 && isCharging) {
        batteryState = "full";
    }
    else if (!isCharging) {
        batteryState = "discharging";
    }
    else {
        batteryState = "charging";
    }
    return batteryState;
}

event.on("DeviceBatteryStateChanged", function (isCharging) {
    var callback = _self.onChargeStateChange,
        msg = "",
        batteryLevel = _self.percentRemaining,
        batteryState;

    batteryState = _getCurrentChargeState(batteryLevel, isCharging);

    msg += "Fired onChargeStateChange with batteryState: " + batteryState;

    if (callback && typeof callback === "function") {
        callback.apply(null, [batteryState]);
    }
    else {
        msg += " --> BUT there was no registered callback found.";
    }

    _console.log(msg);
});

event.on("DeviceBatteryLevelChanged", function (percentRemaining) {

    var callback = _self.onChargeLevelChange,
        lowBatteryCallback = _self.onLowBattery,
        msg = "Fired onChargeLevelChange with percentRemaining: " + percentRemaining;

    // blah, stupid Options returning strings
    percentRemaining = parseInt(percentRemaining, 10);

    if (callback && typeof callback === "function") {
        callback.apply(null, [percentRemaining]);
    }
    else {
        msg += " --> BUT there was no registered callback found.";
    }

    _console.log(msg);

    if (percentRemaining <= 10) {

        msg = "Fired onLowBattery with percentRemaining: " + percentRemaining;

        if (lowBatteryCallback && typeof lowBatteryCallback === "function") {
            lowBatteryCallback.apply(null, [percentRemaining]);
        }
        else {
            msg += " --> BUT there was no registered callback found.";
        }

        _console.log(msg);
    }

    if (percentRemaining === 100 || (percentRemaining < 100 && _lastPercentRemaining === 100)) {
        event.trigger("DeviceBatteryStateChanged", [_self.isCharging]);
    }

    _lastPercentRemaining = percentRemaining;

});

_self.__defineGetter__("isCharging", function () {
    return deviceSettings.retrieveAsBoolean("PowerInfo.isCharging");
});

_self.__defineGetter__("percentRemaining", function () {
    return deviceSettings.retrieveAsInt("PowerInfo.percentRemaining");
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/RadioInfo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    event = require('ripple/event'),
    _console = require('ripple/console'),
    deviceSettings = require('ripple/deviceSettings');

_self = {
    isRoaming: undefined,
    radioSignalStrengthPercent: undefined,
    isRadioEnabled: undefined,
    radioSignalSource: undefined,
    onSignalSourceChange: undefined
};

event.on("RadioSignalSourceChanged", function () {
    var callback = _self.onSignalSourceChange,
        isRoaming = _self.isRoaming,
        signalSource = _self.radioSignalSource,
        msg = "Fired onSignalSourceChange. signalSource: " + signalSource + ", isRoaming: " + isRoaming;

    if (callback && typeof callback === "function") {
        callback.apply(null, [signalSource, isRoaming]);
    }
    else {
        msg += " --> BUT there was no registered callback found.";
    }

    _console.log(msg);
});

_self.__defineGetter__("radioSignalSource", function () {
    return deviceSettings.retrieve("RadioInfo.radioSignalSource");
});

_self.__defineGetter__("isRoaming", function () {
    return deviceSettings.retrieveAsBoolean("RadioInfo.isRoaming");
});

_self.__defineGetter__("isRadioEnabled", function () {
    return deviceSettings.retrieveAsBoolean("RadioInfo.isRadioEnabled");
});

_self.__defineGetter__("radioSignalStrengthPercent", function () {
    return deviceSettings.retrieveAsInt("RadioInfo.radioSignalStrengthPercent");
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/RadioSignalSourceTypes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    utils = require('ripple/utils');

_self = {
    "CDMA": undefined,
    "GSM": undefined,
    "LTE": undefined,
    "TDSCDMA": undefined,
    "WCDMA": undefined
};

utils.forEach(_self, function (value, property) {
    _self.__defineGetter__(property, function () {
        return property;
    });
});

module.exports = _self;

});
define('ripple/platform/wac/1.0/Telephony', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    exception = require('ripple/exception'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    constants = require('ripple/constants'),
    Device = require('ripple/platform/wac/1.0/Device'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    Exception = require('ripple/platform/wac/1.0/Exception');


function _throwUnsupportedException(method) {
    exception.raise(ExceptionTypes.UNSUPPORTED, "Method not supported." + (method || ""), new Exception());
}

_self = {

    // Public Callbacks
    onCallEvent: undefined,// function (callType, phoneNumber) { },
    onCallRecordsFound: undefined,// function (callRecords) { };

    // Public Methods
    initiateVoiceCall: function (phoneNumber) {
        utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "initiateVoiceCall invalid number of parameters", new Exception());
        //HACK: should this be hardcoded?
        //I am still not even sure this is the correct behaviour
        Device.launchApplication("PHONECALL", phoneNumber);

        if (_self.onCallEvent) {
            //HACK: shouldn't be hardcoded
            //also what should the context be? isn't spec'ed
            _self.onCallEvent.apply(_self, ["outgoing", phoneNumber]);
        }
    },
    getCallRecordCnt: function (callRecordType) {
        utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "getCallRecordCnt invalid number of parameters", new Exception());
        var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY);

        return utils.sum(calls, function (call) {
            return call.callRecordType === callRecordType;
        });
    },
    getCallRecord: function (callRecordType, id) {
        utils.validateNumberOfArguments(2, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "getCallRecord invalid number of parameters", new Exception());
        var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY);

        return utils.map(calls, function (call) {
            return call.callRecordType === callRecordType ? call : null;
        }).reduce(function (match, call) {
            return match || call.callRecordId === id || null;
        }, null);
    },
    deleteCallRecord: function (callRecordType, id) {
        utils.validateNumberOfArguments(2, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "deleteCallRecord invalid number of parameters", new Exception());
        var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY),
            indexToDelete = calls.reduce(function (result, call, index) {
                return call.callRecordType === callRecordType &&
                       call.callRecordId === id ? index : result;
            }, -1);

        if (indexToDelete >= 0) {
            calls.splice(indexToDelete, 1);
            db.saveObject(constants.TELEPHONY.CALL_LIST_KEY, calls);
        }

    },

    deleteAllCallRecords: function (callRecordType) {
        utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "deleteAllCallRecords invalid number of parameters", new Exception());
        var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY),
            indexesToDelete = calls.reduce(function (result, call, index) {
                if (call.callRecordType === callRecordType) {
                    result.push(index);
                }
                return result;
            }, []);

        utils.forEach(indexesToDelete, function (index) {
            calls.splice(index, 1);
        });

        if (indexesToDelete.length > 0) {
            db.saveObject(constants.TELEPHONY.CALL_LIST_KEY, calls);
        }

    },

    findCallRecords: function (comparisonRecord, startInx, endInx) {
        utils.validateNumberOfArguments(1, 3, arguments.length, ExceptionTypes.INVALID_PARAMETER, "findCallRecords invalid number of parameters", new Exception());
        var calls = db.retrieveObject(constants.TELEPHONY.CALL_LIST_KEY);
        utils.find(comparisonRecord, calls, startInx, endInx, _self.onCallRecordsFound);

    }

};

module.exports = _self;

});
define('ripple/platform/wac/1.0/VideoPlayer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    _console = require('ripple/console'),
    event = require('ripple/event'),
    utils = require('ripple/utils'),
    fileSystem = require('ripple/fileSystem'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    exception = require('ripple/exception'),
    _currentlySet,
    _currentVideoFile,
    _state = null,
    _loopCount, _video,
    _STATES = {
        "OPENED": "opened",
        "STOPPED": "stopped",
        "PAUSED": "paused",
        "PLAYING": "playing",
        "COMPLETED": "completed"
    };

function _validateVideoType(fileUrl) {
    var matched = fileUrl.match(/\.(\w*)$/),
        maps = {
            "ogv": "ogg",
            "flv": "mp4"
        },
        type = matched ? matched[1] : "";

    if (_video && _video.canPlayType("video/" + (maps[type] || type)) === "") {
        _console.warn("Attempting to load a video that might not work in the current browser [" + fileUrl + "]");
    }
}

function _validateAndSet(state, validStates, callbackBeforeSuccess) {
    var i, valid = false;

    for (i = 0; i < validStates.length; i++) {
        if (validStates[i] === _state) {
            valid = true;
        }
    }

    if (!valid) {
        _console.warn("Attempted to initiate VideoPlayer." + state +
            " in invalid state. current state: " + _state);
    } else {
        if (typeof(callbackBeforeSuccess) === "function") {
            callbackBeforeSuccess.apply();
        }
        event.trigger("MultimediaVideoStateChanged", [state], true);
    }

    return valid;
}

event.on("MultimediaVideoStateChanged", function (state) {
    _state = state;
    if (typeof _self.onStateChange === "function") {
        _self.onStateChange.apply(_self, [state]);
    }
});

_self = module.exports = {
    onStateChange: undefined,

    open: function (fileUrl) {
        utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER,
           "VideoPlayer.open invalid number of arguments", new Exception());
        utils.validateArgumentType(fileUrl, "string", ExceptionTypes.INVALID_PARAMETER,
           "VideoPlayer.open expected valid fileUrl but got ->" + fileUrl, new Exception());

        if (!_video) {
            return;
        }

        _validateAndSet(_STATES.OPENED, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED, null], function () {
            _validateVideoType(fileUrl);
            _currentVideoFile = fileSystem.getURI(fileUrl);
            _video.setAttribute("src", _currentVideoFile);
            _video.setAttribute("width", "100%");
            _video.addEventListener("ended", function () {
                event.trigger("MultimediaVideoStateChanged", [_STATES.COMPLETED], true);
                if (_loopCount > 1) {
                    _self.open(_currentVideoFile);
                    _self.play(_loopCount--);
                }
            }, false);
        });
    },

    setWindow: function (domObject) {
        utils.validateNumberOfArguments(0, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER,
           "VideoPlayer.setWindow invalid number of arguments", new Exception());

        if (_currentlySet) {
            _currentlySet.removeChild(_video);
            _currentlySet = null;
            _video = null;
        }

        if (domObject !== null) {
            _video = utils.createElement("video", {
                "id": "multimedia-video"
            });
            domObject.appendChild(_video);
            _currentlySet = domObject;
            event.trigger("MultimediaAppVideoPlayerCreated", [_video], true);
        }
    },

    play: function (repeatTimes) {
        utils.validateNumberOfArguments(1, 1, arguments.length,
            ExceptionTypes.INVALID_PARAMETER, "invalid number of arguments (expected one)", new Exception());

        if (typeof repeatTimes !== "number" || repeatTimes < 0) {
            exception.raise(ExceptionTypes.INVALID_PARAMETER, "VideoPlayer.play was passed an invalid number of play times: " + repeatTimes, new Exception());
        }
        if (repeatTimes !== 0) {
            if (!_video) {
                return;
            }
            _loopCount = repeatTimes;
            _validateAndSet(_STATES.PLAYING, [_STATES.OPENED, _STATES.STOPPED, _STATES.COMPLETED], function () {
                _video.play();
            });
        }
    },

    pause: function () {
        if (!_video) {
            return;
        }
        _validateAndSet(_STATES.PAUSED, [_STATES.PLAYING], function () {
            _video.pause();
        });
    },

    resume: function () {
        if (!_video) {
            return;
        }
        _validateAndSet(_STATES.PLAYING, [_STATES.PAUSED], function () {
            _video.play();
        });
    },

    stop: function () {
        if (!_video) {
            return;
        }
        _validateAndSet(_STATES.STOPPED, [_STATES.PAUSED, _STATES.PLAYING], function () {
            _video.pause();
            _video.setAttribute("src", _currentVideoFile); // hack
        });
    }

};

});
define('ripple/platform/wac/1.0/Widget', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    _console = require('ripple/console'),
    app = require('ripple/app'),
    platform = require('ripple/platform'),
    exception = require('ripple/exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    Exception = require('ripple/platform/wac/1.0/Exception'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    _self;

event.on("ScreenChangeDimensions", function (height, width) {
    try {
        // TODO: are these per spec to call?
        if (typeof app.onMaximize === 'function') {
            app.onMaximize();
        }
        if (typeof app.onRestore === 'function') {
            app.onRestore();
        }
        _console.log("called Widget.onRestore and Widget.onMaximize callback function");
    }
    catch (e) {
        exception.handle(e, false);
    }
});

event.on("WidgetWakeup", function () {
    if (_self.onWakeup) {
        _self.onWakeup();
    }
});

event.on("WidgetMaximize", function () {
    if (_self.onMaximize) {
        _self.onMaximize();
    }
});

event.on("WidgetFocus", function () {
    if (_self.onFocus) {
        _self.onFocus();
    }
});

event.on("WidgetRestore", function () {
    if (_self.onRestore) {
        _self.onRestore();
    }
});

_self = {
    onWakeup: undefined,
    onMaximize: undefined,
    onFocus: undefined,
    onRestore: undefined,

    openURL: function (url) {
        window.open(url);
    },

    setPreferenceForKey: function (value, key) {

        utils.validateNumberOfArguments(1, 2, arguments.length, ExceptionTypes.INVALID_PARAMETER, "setPreferenceForKey invalid number of paramters", new Exception());
        utils.validateArgumentType(key, "string", ExceptionTypes.INVALID_PARAMETER, "setPreferenceForKey invalid parameter! Key:" +
            key + ", Value: " + value, new Exception());

        var msg = "",
            prefix;
        if (app.isPreferenceReadOnly(key)) {
            msg += "Cannot modify a read only preference. Preference key: " + key;
        }
        else {
            prefix = platform.getPersistencePrefix();
            if (value === null) {
                msg += "deleting preference " + key;
                db.remove(key, prefix);
            }
            else {
                msg += "setting preference " + key + " == " + value;
                utils.validateArgumentType(value, "string", ExceptionTypes.INVALID_PARAMETER, msg, new Exception());
                db.save(key, value, prefix);
            }
        }


        _console.log(msg);

        // Trigger storageUpdatedEvent
        event.trigger("StorageUpdatedEvent");

    },

    // return value or undefined
    preferenceForKey: function (key) {

        utils.validateNumberOfArguments(1, 1, arguments.length, ExceptionTypes.INVALID_PARAMETER, "preferenceForKey invalid number of parameters", new Exception());
        utils.validateArgumentType(key, "string", ExceptionTypes.INVALID_PARAMETER, "preferenceForKey invalid paramters", new Exception());

        var prefix = platform.getPersistencePrefix(),
            value = db.retrieve(key, prefix);

        if (!value && value !== "") {
            value = undefined;
        }

        _console.log("retrieving preference " + key + " == " + value);

        return value;

    }
};

module.exports = _self;

});
define('ripple/platform/wac/1.0/WidgetManager', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 exception = require('ripple/exception'),
    ExceptionTypes = require('ripple/platform/wac/1.0/ExceptionTypes'),
    Exception = require('ripple/platform/wac/1.0/Exception');

module.exports = {
    // This method is used to check the installation status of a specific widget.
    checkWidgetInstallationStatus: function () {

        exception.raise(ExceptionTypes.UNSUPPORTED, "WidgetManager.checkWidgetInstallationStatus not supported", new Exception());
    }
};

});
define('ripple/platform/wac/1.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 platform = require('ripple/platform'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    constants = require('ripple/constants');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (configValidationObject) {
        var valid = true;
        valid = !((!configValidationObject.widget.validationResult[0].attributes.xmlns.valid) ||
            (!configValidationObject.widget.validationResult[0].attributes["xmlns:JIL"].valid));

        return valid;
    },
    extractInfo: function (configValidationObject) {
        if (!configValidationObject) {
            return null;
        }

        var widgetInfo = {},
            configFeatures,
            configPreferences,
            preferenceName,
            platform;

        widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
        widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
        widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;

        widgetInfo.features = {};

        configFeatures = configValidationObject.widget.children.feature.validationResult;
        utils.forEach(configFeatures, function (f) {
            if (f.valid === true) {
                var feature = {id: f.attributes.name.value,
                         required: f.attributes.required.valid};
                widgetInfo.features[feature.id] = feature;
            }
        });

        widgetInfo.preferences = {};

        configPreferences = configValidationObject.widget.children.preference.validationResult;

        platform = require('ripple/platform');
        utils.forEach(configPreferences, function (preference) {
            preferenceName = preference.attributes.name.value;
            if (preferenceName) {
                widgetInfo.preferences[preferenceName] = {
                    "key": preferenceName,
                    "value": preference.attributes.value.value || "",
                    "readonly": preference.attributes.readonly.value === "true"
                };

                db.save(preferenceName,
                        widgetInfo.preferences[preferenceName].value,
                        platform.getPersistencePrefix(widgetInfo.id));
            }
        });

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in configuration document and may have following child elments: name,description,icon,author,license,content,maximum_display_mode,update,feature,access,billing. \"widget\" element MAY have following attributes: id,version,height,width,xml:lang",
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xmlns:JIL": {
                    attributeName: "xmlns:JIL",
                    required: true,
                    type: "list",
                    listValues: ["http://www.jil.org/ns/widgets1.2"]
                },
                "xmlns:its": {
                    attributeName: "xmlns:its",
                    helpText: "Indicates Text Directionality can be used. According to W3C spec, this feature is at risk, therefore we don't currently validate this.",
                    required: false,
                    type: "string"
                },
                id: {
                    attributeName: "id",
                    required: true,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    helpText: "Version must be in the following format: jil-rec-version-tag = major-version \".\" minor-version [\".\" version-desc]",
                    required: true,
                    type: "regex",
                    regex: /^\d{1,2}\.\d{1,2}(\.[A-Za-z0-9]{1,10})?$/
                },
                height: {
                    attributeName: "height",
                    required: true,
                    type: "integer"
                },
                width: {
                    attributeName: "width",
                    required: true,
                    type: "integer"
                },
                viewmodes: {
                    attributeName: "viewmodes",
                    required: false,
                    type: "list",
                    listValues: ["floating", "fullscreen"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                }
            },
            children: {
                preference: {
                    nodeName: "preference",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        name: {
                            attributeName: "name",
                            type: "string",
                            required: true
                        },
                        value: {
                            type: "string",
                            attributeName: "value",
                            required: false
                        },
                        readonly: {
                            attributeName: "readonly",
                            type: "boolean",
                            required: false
                        }
                    }
                },
                name: {
                    nodeName: "name",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "short": {
                            attributeName: "short",
                            type: "string",
                            required: false
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        src: {
                            attributeName: "src",
                            type: "string",
                            required: true
                        },
                        height: {
                            attributeName: "height",
                            required: false,
                            type: "integer"
                        },
                        width: {
                            attributeName: "width",
                            required: false,
                            type: "integer"
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 1,
                    type: "string",
                    attributes: {
                        email: {
                            attributeName: "email",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.EMAIL
                        },
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 1,
                    type: "string",
                    attributes: {
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            type: "string",
                            required: false,
                            unique: true
                        }
                    }
                },
                content: {
                    nodeName: "content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        src: {
                            attributeName: "src",
                            type: "string",
                            required: true
                        },
                        encoding: {
                            attributeName: "encoding",
                            type: "string",
                            required: false
                        },
                        type: {
                            attributeName: "type",
                            type: "string",
                            required: false
                        }
                    }
                },
                feature: {
                    nodeName: "feature",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        name: {
                            attributeName: "name",
                            type: "list",
                            required: true,
                            listValues: ["http://jil.org/jil/api/1.1/widget", "http://jil.org/jil/api/1.1.5/exception",
                                            "http://jil.org/jil/api/1.1.5/exceptiontypes", "http://jil.org/jil/api/1.1/device",
                                            "http://jil.org/jil/api/1.1/accountinfo", "http://jil.org/jil/api/1.1/deviceinfo",
                                            "http://jil.org/jil/api/1.1.1/datanetworkinfo", "http://jil.org/jil/api/1.1/devicestateinfo",
                                            "http://jil.org/jil/api/1.1/accelerometerinfo", "http://jil.org/jil/api/1.1/config",
                                            "http://jil.org/jil/api/1.1.1/file", "http://jil.org/jil/api/1.1/positioninfo",
                                            "http://jil.org/jil/api/1.1/powerinfo", "http://jil.org/jil/api/1.1.1/radioinfo",
                                            "http://jil.org/jil/api/1.1.5/radiosignalsourcetypes", "http://jil.org/jil/api/1.1.5/applicationtypes",
                                            "http://jil.org/jil/api/1.1/messaging", "http://jil.org/jil/api/1.1/account",
                                            "http://jil.org/jil/api/1.1/attachment", "http://jil.org/jil/api/1.1/message",
                                            "http://jil.org/jil/api/1.1.4/messagefoldertypes", "http://jil.org/jil/api/1.1/messagequantities",
                                            "http://jil.org/jil/api/1.1/messagetypes", "http://jil.org/jil/api/1.1/multimedia",
                                            "http://jil.org/jil/api/1.1/audioplayer", "http://jil.org/jil/api/1.1.2/camera",
                                            "http://jil.org/jil/api/1.1.2/videoplayer", "http://jil.org/jil/api/1.1.1/pim",
                                            "http://jil.org/jil/api/1.1/addressbookitem", "http://jil.org/jil/api/1.1/calendaritem",
                                            "http://jil.org/jil/api/1.1/eventrecurrencetypes", "http://jil.org/jil/api/1.1.1/telephony",
                                            "http://jil.org/jil/api/1.1/callrecord", "http://jil.org/jil/api/1.1.1/callrecordtypes",
                                            "http://jil.org/jil/api/1.1.1/widgetmanager"]
                        },
                        required: {
                            attributeName: "required",
                            type: "boolean",
                            required: false
                        }
                    }
                },
                "JIL:maximum_display_mode": {
                    nodeName: "JIL:maximum_display_mode",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        height: {
                            attributeName: "height",
                            type: "integer",
                            required: false
                        },
                        width: {
                            attributeName: "width",
                            type: "integer",
                            required: false
                        }
                    }
                },
                "JIL:update": {
                    nodeName: "JIL:update",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: true,
                            regex: constants.REGEX.URL
                        },
                        period: {
                            attributeName: "period",
                            helpText: "Possible values for the period attribute are: 0, 1, 2, 3 meaning: every time the widget is opened in maximum display mode, every day, every week, every month; respectivly",
                            type: "list",
                            required: true,
                            listValues: ["0", "1", "2", "3"]
                        }
                    }
                },
                "JIL:access": {
                    nodeName: "JIL:access",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        network: {
                            attributeName: "network",
                            type: "boolean",
                            required: false
                        },
                        localfs: {
                            attributeName: "localfs",
                            type: "boolean",
                            required: false
                        },
                        remote_scripts: {
                            attributeName: "remote_scripts",
                            type: "boolean",
                            required: false
                        }
                    }
                },
                "JIL:billing": {
                    nodeName: "JIL:billing",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        required: {
                            attributeName: "required",
                            type: "boolean",
                            required: true
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/wac/1.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    event = require('ripple/event');

module.exports = {
    "AccountInfo": {
        "phoneUserUniqueId": {
            "name": "User Unique Id",
            "control": {
                "type": "text",
                "value": new Date().getTime().toString()
            }
        },
        "phoneMSISDN":  {
            "name": "MSISDN",
            "control": {
                "type": "text",
                "value": "15199999999"
            }
        },
        "phoneOperatorName":  {
            "name": "Operator Name",
            "control": {
                "type": "text",
                "value": ""
            }
        },
        "userAccountBalance":  {
            "name": "Account Balance",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "userSubscriptionType":  {
            "name": "Subscription Type",
            "control": {
                "type": "select",
                "value": "other"
            },
            "options": {
                "other": "other",
                "prepaid": "prepaid",
                "postpaid": "postpaid"
            }
        }
    },
    "RadioInfo": {
        "isRoaming": {
            "name": "Is Roaming",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "callback": function () {
                event.trigger("RadioSignalSourceChanged");
            }
        },
        "isRadioEnabled":  {
            "name": "Is Radio Enabled",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "radioSignalSource": {
            "name": "Radio Signal Source",
            "control": {
                "type": "select",
                "value": "GSM"
            },
            // TODO: try not to duplicate from RadioSignalSourceTypes
            "options": {
                "CDMA": "cdma",
                "GSM": "gsm",
                "LTE": "lte",
                "TDSCDMA": "tdscdma",
                "WCDMA": "wcdma"
            },
            "callback": function () {
                event.trigger("RadioSignalSourceChanged");
            }
        },
        "radioSignalStrengthPercent": {
            "name": "Signal Strength %",
            "control": {
                "type": "select",
                "value": 80
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 100; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }())
        }
    },
    "Config": {
        "ringtoneVolume": {
            "name": "Ringtone Volume",
            "control": {
                "type": "select",
                "value": 10
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 10; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }())
        },
        "msgRingtoneVolume":  {
            "name": "Msg Ringtone Volume",
            "control": {
                "type": "select",
                "value": 10
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 10; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }())
        },
        "vibrationSetting":  {
            "name": "Vibration",
            "control": {
                "type": "select",
                "value": "off"
            },
            "options": {
                "on": "ON",
                "off": "OFF"
            }
        }
    },
    "Account": {
        "accountName":  {
            "name": "Name",
            "control": {
                "type": "text",
                "value": ""
            }
        },
        "accountId":  {
            "name": "Id",
            "control": {
                "type": "text",
                "value": ""
            }
        }
    },
    "DeviceInfo": {
        "totalMemory": {
            "name": "Total Memory",
            "control": {
                "type": "range",
                "value": 262144,
                "min": 0,
                "max": 4096000
            }
        },
        "phoneColorDepthDefault": {
            "name": "Color Depth",
            "control": {
                "type": "number",
                "value": 24
            }
        }
    },
    "DeviceStateInfo": {
        "availableMemory": {
            "name": "Available Memory",
            "control": {
                "type": "range",
                "value": 262144,
                "min": 0,
                "max": 4096000
            }
        },
        "keypadLightOn":   {
            "name": "Keypad Light On",
            "control": {
                "type": "checkbox",
                "value": false
            }
        },
        "backLightOn": {
            "name": "Back Light On",
            "control": {
                "type": "checkbox",
                "value": false
            }
        },
        "audioPath":  {
            "name": "Audio Path",
            "control": {
                "type": "select",
                "value": "receiver"
            },
            "options": {
                "speaker": "speaker",
                "receiver": "receiver",
                "earphone": "earphone"
            }
        },
        "processorUtilizationPercent":  {
            "name": "CPU Utilization %",
            "control": {
                "type": "select",
                "value": "5"
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 100; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }())
        },
        "language":  {
            "name": "Language",
            "control": {
                "type": "select",
                "value": "eng"
            },
            "options": (function () {
                var i,
                    optionList = {},
                    iterator = constants.LANG.ISO6392_LIST;

                for (i = 0; i <= iterator.length; i++) {
                    optionList[iterator[i]] = iterator[i];
                }

                return optionList;
            }())
        }
    },
    "DataNetworkInfo": {
        "isDataNetworkConnected": {
            "name": "Data Network Is Connected",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "networkConnectionType": {
            "name": "Network Connection Type",
            "control": {
                "type": "select",
                "value": ["GPRS"]
            },
            // TODO: try not to duplicate from DataNetworkConnectionTypes
            "options": {
                "BLUETOOTH": "bluetooth",
                "EDGE": "edge",
                "EVDO": "evdo",
                "GPRS": "gprs",
                "IRDA": "irda",
                "LTE": "lte",
                "ONEXRTT": "1xrtt",
                "WIFI": "wifi"
            },
            "callback": function (setting) {
                event.trigger("DataNetworkConnectionChanged", [setting]);
            }
        }
    },
    "PowerInfo": {
        "isCharging": {
            "name": "Battery Is Charging",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("DeviceBatteryStateChanged", [setting]);
            }
        },
        "percentRemaining":  {
            "name": "Battery Remaining %",
            "control": {
                "type": "select",
                "value": 100
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 100; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }()),
            "callback": function (setting) {
                event.trigger("DeviceBatteryLevelChanged", [setting]);
            }
        }
    }
};

});
define('ripple/platform/wac/1.0/spec/events', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event');

module.exports = {
    "WidgetWakeup": {
        callback: function () {
            event.trigger("WidgetWakeup");
        }
    },
    "WidgetMaximize": {
        callback: function () {
            event.trigger("WidgetMaximize");
        }
    },
    "WidgetFocus": {
        callback: function () {
            event.trigger("WidgetFocus");
        }
    },
    "WidgetRestore": {
        callback: function () {
            event.trigger("WidgetRestore");
        }
    }
};

});
define('ripple/platform/wac/1.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "accelerometer",
        //"deviceSettings",
        "fileSystem",
        "geoView",
/*
        "multimedia",
        "audioPlayer",
        "telephony",
*/
        "platformEvents",
        "storage",
        "widgetConfig"
    ]
};

});
define('ripple/platform/wac/1.0/spec', function (require, exports, module) {
module.exports = {

    id: "wac",
    version: "1.0",
    name: "WAC",
    type: "plaform",

    persistencePrefix: "wac-",

    config: require('ripple/platform/wac/1.0/spec/config'),
    device: require('ripple/platform/wac/1.0/spec/device'),
    ui: require('ripple/platform/wac/1.0/spec/ui'),
    events: require('ripple/platform/wac/1.0/spec/events'),

    objects: {
        navigator: {
            path: "w3c/1.0/navigator"
        },
        WidgetManager: {
            path: "wac/1.0/WidgetManager",
            feature: "http://jil.org/jil/api/1.1.1/widgetmanager"
        },
        Widget: {
            path: "wac/1.0/Widget",
            feature: "http://jil.org/jil/api/1.1/widget",
            children: {
                Device: {
                    path: "wac/1.0/Device",
                    feature: "http://jil.org/jil/api/1.1/device",
                    children: {
                        AccountInfo: {
                            path: "wac/1.0/AccountInfo",
                            feature: "http://jil.org/jil/api/1.1/accountinfo"
                        },
                        ApplicationTypes: {
                            path: "wac/1.0/ApplicationTypes",
                            feature: "http://jil.org/jil/api/1.1.5/applicationtypes"
                        },
                        DataNetworkInfo: {
                            path: "wac/1.0/DataNetworkInfo",
                            feature: "http://jil.org/jil/api/1.1.1/datanetworkinfo",
                            children: {
                                DataNetworkConnectionTypes: {
                                    path: "wac/1.0/DataNetworkConnectionTypes"
                                }
                            }
                        },
                        DeviceInfo: {
                            path: "wac/1.0/DeviceInfo",
                            feature: "http://jil.org/jil/api/1.1/deviceinfo"
                        },
                        DeviceStateInfo: {
                            path: "wac/1.0/DeviceStateInfo",
                            feature: "http://jil.org/jil/api/1.1/devicestateinfo",
                            children: {
                                Config: {
                                    path: "wac/1.0/Config",
                                    feature: "http://jil.org/jil/api/1.1/config"
                                },
                                AccelerometerInfo: {
                                    path: "wac/1.0/AccelerometerInfo",
                                    feature: "http://jil.org/jil/api/1.1/accelerometerinfo"
                                }
                            }
                        },
                        File: {
                            path: "wac/1.0/File",
                            feature: "http://jil.org/jil/api/1.1.1/file"
                        },
                        PositionInfo: {
                            path: "wac/1.0/PositionInfo",
                            feature: "http://jil.org/jil/api/1.1/positioninfo"
                        },
                        RadioInfo: {
                            path: "wac/1.0/RadioInfo",
                            feature: "http://jil.org/jil/api/1.1.1/radioinfo",
                            children: {
                                RadioSignalSourceTypes: {
                                    path: "wac/1.0/RadioSignalSourceTypes",
                                    feature: "http://jil.org/jil/api/1.1.5/radiosignalsourcetypes"
                                }
                            }
                        },
                        PowerInfo: {
                            path: "wac/1.0/PowerInfo",
                            feature: "http://jil.org/jil/api/1.1/powerinfo"
                        }
                    }
                },
                ExceptionTypes: {
                    path: "wac/1.0/ExceptionTypes",
                    feature: "http://jil.org/jil/api/1.1.5/exceptiontypes"
                },
                Exception: {
                    path: "wac/1.0/Exception",
                    feature: "http://jil.org/jil/api/1.1.5/exception"
                },
                Multimedia: {
                    path: "wac/1.0/Multimedia",
                    feature: "http://jil.org/jil/api/1.1/multimedia",
                    children: {
                        Camera: {
                            path: "wac/1.0/Camera",
                            feature: "http://jil.org/jil/api/1.1.2/camera"
                        },
                        AudioPlayer: {
                            path: "wac/1.0/AudioPlayer",
                            feature: "http://jil.org/jil/api/1.1/audioplayer"
                        },
                        VideoPlayer: {
                            path: "wac/1.0/VideoPlayer",
                            feature: "http://jil.org/jil/api/1.1.2/videoplayer"
                        }
                    }
                },
                Telephony: {
                    path: "wac/1.0/Telephony",
                    feature: "http://jil.org/jil/api/1.1.1/telephony",
                    children: {
                        CallRecord: {
                            path: "wac/1.0/CallRecord",
                            feature: "http://jil.org/jil/api/1.1/callrecord"
                        },
                        CallRecordTypes: {
                            path: "wac/1.0/CallRecordTypes",
                            feature: "http://jil.org/jil/api/1.1.1/callrecordtypes"
                        }
                    }
                },
                PIM: {
                    path: "wac/1.0/PIM",
                    feature: "http://jil.org/jil/api/1.1.1/pim",
                    children: {
                        AddressBookItem: {
                            path: "wac/1.0/AddressBookItem",
                            feature: "http://jil.org/jil/api/1.1/addressbookitem"
                        },
                        CalendarItem: {
                            path: "wac/1.0/CalendarItem",
                            feature: "http://jil.org/jil/api/1.1/calendaritem"
                        },
                        EventRecurrenceTypes: {
                            path: "wac/1.0/EventRecurrenceTypes",
                            feature: "http://jil.org/jil/api/1.1/eventrecurrencetypes"
                        }
                    }
                },
                Messaging: {
                    path: "wac/1.0/Messaging",
                    feature: "http://jil.org/jil/api/1.1/messaging",
                    children: {
                        Account: {
                            path: "wac/1.0/Account",
                            feature: "http://jil.org/jil/api/1.1/account"
                        },
                        Attachment: {
                            path: "wac/1.0/Attachment",
                            feature: "http://jil.org/jil/api/1.1/attachment"
                        },
                        Message: {
                            path: "wac/1.0/Message",
                            feature: "http://jil.org/jil/api/1.1/message"
                        },
                        MessageFolderTypes: {
                            path: "wac/1.0/MessageFolderTypes",
                            feature: "http://jil.org/jil/api/1.1.4/messagefoldertypes"
                        },
                        MessageQuantities: {
                            path: "wac/1.0/MessageQuantities",
                            feature: "http://jil.org/jil/api/1.1/messagequantities"
                        },
                        MessageTypes: {
                            path: "wac/1.0/MessageTypes",
                            feature: "http://jil.org/jil/api/1.1/messagetypes"
                        }
                    }
                }
            }
        }
    }

};

});
define('ripple/platform/wac/2.0/accelerometer', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    event = require('ripple/event'),
    Acceleration = function (x, y, z) {
        return {
            xAxis: x || 0,
            yAxis: y || 0,
            zAxis: z || 0
        };
    },
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
    _accelerometerInfo = new Acceleration(),
    _defaultInterval = 100,
    _watches = {},
    _self;

module.exports = _self = {
    getCurrentAcceleration: function (onSuccess, onError) {
        function _getCurrentAcceleration() {
            setTimeout(function () {
                onSuccess(utils.copy(_accelerometerInfo));
            }, 1);
            return null;
        }

        return wac2_utils.validateTypeMismatch(onSuccess, onError, "getCurrentAcceleration", _getCurrentAcceleration); 
    },

    watchAcceleration: function (accelerometerSuccess, accelerometerError, options) {
        function _watchAcceleration() {
            var watchId = (new Date()).getTime() | 0,
                watchObj = {},
                opt = Object(options),
                minNotificationInterval = opt.minNotificationInterval | 0,
                accelerometerInterval = _defaultInterval;

            if (minNotificationInterval > 0) {
                accelerometerInterval = minNotificationInterval;
            }

            watchObj = {
                onSuccess: accelerometerSuccess,
                onError: accelerometerError,
                interval: accelerometerInterval
            };

            _watches[watchId] = watchObj;

            _watches[watchId].intervalId = setInterval(function () {
                _self.getCurrentAcceleration(_watches[watchId].onSuccess, _watches[watchId].onError);
            }, _watches[watchId].interval);

            return watchId;
        }

        return wac2_utils.validateTypeMismatch(accelerometerSuccess, accelerometerError, "watchAcceleration", _watchAcceleration); 
    },

    clearWatch: function (watchId) {

        var id = watchId | 0;

        if (_watches[id]) {
            clearInterval(_watches[id].intervalId);
            delete(_watches[id]);
            return null;
        }

        return undefined;
    }
};

event.on("AccelerometerInfoChangedEvent", function (accelerometerInfo) {
    _accelerometerInfo.xAxis = accelerometerInfo.accelerationIncludingGravity.x;
    _accelerometerInfo.yAxis = accelerometerInfo.accelerationIncludingGravity.y;
    _accelerometerInfo.zAxis = accelerometerInfo.accelerationIncludingGravity.z;
});


});
define('ripple/platform/wac/2.0/calendar', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    constants = require('ripple/constants'),
    errorcode = require('ripple/platform/wac/2.0/errorcode'),
    PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
    PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
    _console = require('ripple/console'),
    DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
    _SIM_CALENDAR = 0, _DEVICE_CALENDAR = 1,
    _NO_RECURRENCE = 0, _DAILY_RECURRENCE = 1, _WEEKLY_RECURRENCE = 2,
    _MONTHLY_RECURRENCE = 3, _YEARLY_RECURRENCE = 4,
    _TENTATIVE_STATUS = 0, _CONFIRMED_STATUS = 1, _CANCELLED_STATUS = 2,
    _NO_ALARM = 0, _SILENT_ALARM = 1, _SOUND_ALARM = 2,
    _calendars = [], _DB_CALENDARS_KEY = "wac2-db-calendars",
    _FAKEWAITTIME = 5, _FAKE_LONG_WAITTIME = 10,
    _save_calendars, _eventPropCheck, _eventFilterCheck,
    _addEventAllowed = true, _deleteEventAllowed = true,
    _updateEventAllowed = true, _findEventsAllowed = true,
    CalendarEventProperties, Calendar, CalendarEvent;

_save_calendars = function (_name, _type, _events) {
    var i;
    for (i = 0; i < _calendars.length; i++) {
        if (_calendars[i].name === _name && _calendars[i].type === _type) {
            _calendars[i].events = _events;
            break;
        }
    }
    db.saveObject(_DB_CALENDARS_KEY, _calendars);
};

_eventPropCheck = function (prop, dst) {
    var i;
    if (prop.description !== null && prop.description !== undefined) {
        dst.description = String(prop.description);
    }
    if (prop.summary !== null && prop.summary !== undefined) {
        dst.summary = String(prop.summary);
    } 
    if (prop.startTime !== null && prop.startTime !== undefined) {
        if (!wac2_utils.isValidDate(prop.startTime)) {
            return false;
        }
        dst.startTime = new Date(prop.startTime);
    }
    dst.duration = prop.duration | 0;
    if (prop.location !== null && prop.location !== undefined) {
        dst.location = String(prop.location);
    }
    if (prop.categories !== null && prop.categories !== undefined) {
        if (!wac2_utils.isValidArray(prop.categories))  {
            return false;
        }
        dst.categories = [];
        for (i = 0; i < prop.categories.length; i++) {
            dst.categories.push(String(prop.categories[i]));
        }
    }
    if (prop.recurrence !== null && prop.recurrence !== undefined) {
        if (prop.recurrence === _NO_RECURRENCE ||
            prop.recurrence === _DAILY_RECURRENCE ||
            prop.recurrence === _WEEKLY_RECURRENCE ||
            prop.recurrence === _MONTHLY_RECURRENCE ||
            prop.recurrence === _YEARLY_RECURRENCE) {
            dst.recurrence = prop.recurrence | 0;
        } else {
            return false;
        }
    }
    if (dst.recurrence === _NO_RECURRENCE) {
        dst.expires = null;
        dst.interval = null;
    } else {
        // expires and interval matters when recurrence is not NO_RECURRENCE
        if (prop.expires !== null && prop.expires !== undefined) {
            if (!wac2_utils.isValidDate(prop.expires)) {
                return false;
            }
            dst.expires = new Date(prop.expires);
        }
        // expires === undefined -> to recur indefinitely
        // expires === null -> keep dst.expires unchanged, even it's null
        if (prop.expires === undefined) {
            dst.expires = null;
        }
        if (prop.interval !== null && prop.interval !== undefined) {
            dst.interval = prop.interval | 0;
        }
    }

    if (prop.status !== null && prop.status !== undefined) {
        if (prop.status === _TENTATIVE_STATUS ||
            prop.status === _CONFIRMED_STATUS ||
            prop.status === _CANCELLED_STATUS) {
            dst.status = prop.status | 0;
        } else {
            return false;
        }
    }

    if (prop.alarmType !== null && prop.alarmType !== undefined) {
        if (prop.alarmType === _NO_ALARM ||
            prop.alarmType === _SILENT_ALARM ||
            prop.alarmType === _SOUND_ALARM) {
            dst.alarmType = prop.alarmType;
        } else {
            return false;
        }
    } 
    if (dst.alarmType !== _NO_ALARM && prop.alarmTrigger !== undefined && prop.alarmTrigger !== undefined) {
        dst.alarmTrigger = prop.alarmTrigger | 0;
    }
};

_eventFilterCheck = function (filter) {
    if (filter.id !== undefined && filter.id !== null) {
        filter.id = String(filter.id);
    } else {
        filter.id = undefined;
    }
    if (filter.summary !== undefined && filter.summary !== null) {
        filter.summary = String(filter.summary);
    } else {
        filter.summary = undefined;
    }
    if (filter.description !== undefined && filter.description !== null) {
        filter.description = String(filter.description);
    } else {
        filter.description = undefined;
    }
    if (filter.location !== undefined && filter.location !== null) {
        filter.location = String(filter.location);
    } else {
        filter.location = undefined;
    }
    if (filter.catetory !== undefined && filter.catetory !== null) {
        filter.catetory = String(filter.catetory);
    } else {
        filter.catetory = undefined;
    }
    if (filter.status !== undefined && filter.status !== null) {
        var i;
        if (!wac2_utils.isValidArray(filter.status))  {
            return false;
        }
        for (i = 0; i < filter.status.length; i++) {
            filter.status[i] = filter.status[i] | 0;
            if (filter.status[i] > _CANCELLED_STATUS || filter.status[i] < _TENTATIVE_STATUS)
                return false;
        }
    } else {
        filter.status = undefined;
    }
    if (filter.initialStartDate !== undefined && filter.initialStartDate !== null) {
        if (!wac2_utils.isValidDate(filter.initialStartDate)) {
            return false;
        }
        filter.initialStartDate = new Date(filter.initialStartDate);
    } else {
        filter.initialStartDate = undefined;
    }
    if (filter.endStartDate !== undefined && filter.endStartDate !== null) {
        if (!wac2_utils.isValidDate(filter.endStartDate)) {
            return false;
        }
        filter.endStartDate = new Date(filter.endStartDate);
    } else {
        filter.endStartDate = undefined;
    }
    return true;
};

CalendarEventProperties = function (prop) {
    var _self;
    _self = {
        description : "",
        summary : "",
        startTime : new Date(),
        duration : 0,
        location : "",
        categories : undefined,
        recurrence : _NO_RECURRENCE,
        expires : null,  // ignored if recurrence == NO_RECURRENCE
        interval : null, // ignored if recurrence == NO_RECURRENCE
        status : _CONFIRMED_STATUS,
        alarmTrigger : 0,
        alarmType : _NO_ALARM
    };
    if (prop) {
        if (_eventPropCheck(prop, _self) === false) {
            return undefined;
        }
    }
    return _self;
};

CalendarEvent = function (prop, genNewID) {
    var id, _self = new CalendarEventProperties(prop);

    /* if error occurs during checking, _self is an empty object.
       so i randomly pick description to check if property check fails */
    if (_self.description === undefined) {
        return undefined;
    }

    if (genNewID === true) {
        id = Math.uuid(undefined, 16);
    } else {
        id = prop.id;
    }
    _self.__defineGetter__("id", function () {
        return id;
    });
    return _self;
};

Calendar = function (type, name, events) {
    var _type = type,
        _name = name,
        _events = events, _self;

    _self = {
        createEvent: function (evtProp) {
            var rst = {};
            rst = new CalendarEventProperties(evtProp);
            /* if error occurs during checking, rst is an empty object.
               so i randomly pick description to check if property check fails */
            if (rst.description === undefined) {
                exception.raise(exception.types.Argument, "EventProperties: input parameter contains invalid values", new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                return undefined;
            } else {
                return rst;
            }
        },

        addEvent: function (onSuccess, onError, calEvent) {
            var pendingOperation, pendingObj = {},
                newEvent = {}, _doAddEvent, _calEvent = Object(calEvent);

            _doAddEvent = function () {
                if (!_addEventAllowed) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                newEvent = new CalendarEvent(_calEvent, true);
                /* if newEvent.id === undefined,
                   means somthing wrong in calEvent  */
                if (newEvent.id === undefined) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                pendingObj = new PendingObject();
                pendingObj.pendingID = setTimeout(function () {
                    pendingObj.setCancelFlag(false);
                    _events[newEvent.id] = newEvent;
                    _save_calendars(_name, _type, _events);
                    onSuccess(new CalendarEvent(newEvent), false);
                }, _FAKEWAITTIME);
                pendingOperation = new PendingOperation(pendingObj);
                return pendingOperation;
            };

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:addEvent", _doAddEvent);
        },

        updateEvent: function (onSuccess, onError, calEvent) {
            var pendingOperation, pendingObj = {},
                chkEvent, _doUpdateEvent, _calEvent = Object(calEvent);

            _doUpdateEvent = function () {
                if (!_updateEventAllowed) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                if (!_events[_calEvent.id]) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                chkEvent = new CalendarEvent(_events[_calEvent.id], false);
                /* _eventPropCheck will also update chkEvent btw */
                if (_eventPropCheck(_calEvent, chkEvent) === false) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                pendingObj = new PendingObject();
                pendingObj.pendingID = setTimeout(function () {
                    pendingObj.setCancelFlag(false);

                    _events[chkEvent.id] = chkEvent;
                    _save_calendars(_name, _type, _events);
                    onSuccess();
                }, _FAKEWAITTIME);
                pendingOperation = new PendingOperation(pendingObj);
                return pendingOperation;
            };

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:updateEvent", _doUpdateEvent);
        },

        deleteEvent: function (onSuccess, onError, id) {
            var pendingOperation, pendingObj = {},
                _doDeleteEvent;

            _doDeleteEvent = function () {
                /* according to spec  "If any of the input parameters are not 
                   compatible with the expected type for that parameter, 
                   a DeviceAPIError with code TYPE_MISMATCH_ERR MUST be 
                   synchronously thrown." 
                   so an error is raised synchronously */
                utils.validateArgumentType(id, "string", null,
                                       "Calendar:deleteEvent: " + " invalid id parameter",
                                       new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));

                if (!_deleteEventAllowed) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                if (!_events[id]) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                pendingObj = new PendingObject();
                pendingObj.pendingID = setTimeout(function () {
                    pendingObj.setCancelFlag(false);

                    delete _events[id];
                    _save_calendars(_name, _type, _events);
                    onSuccess();
                }, _FAKEWAITTIME);
                pendingOperation = new PendingOperation(pendingObj);
                return pendingOperation;
            };

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:deleteEvent", _doDeleteEvent);
        },

        findEvents: function (onSuccess, onError, eventFilter) {
            var pendingOperation, pendingObj = {}, i,
                tmp = [], valid_tmp = false, rst = [], _doFindEvents,
                _eventFilter = Object(eventFilter);

            _doFindEvents = function () {
                if (!_eventFilterCheck(_eventFilter)) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                if (!_findEventsAllowed) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                pendingObj = new PendingObject();
                pendingObj.pendingID = setTimeout(function () {
                    pendingObj.setCancelFlag(false);
                    if (_eventFilter.id !== undefined) {
                        tmp = wac2_utils.matchOptionString(_events, "id", _eventFilter.id);
                        valid_tmp = true;
                    }
                    if (_eventFilter.summary !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionString(tmp, "summary", _eventFilter.summary);
                        } else {
                            tmp = wac2_utils.matchOptionString(_events, "summary", _eventFilter.summary);
                            valid_tmp = true;
                        }
                    }
                    if (_eventFilter.description !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionString(tmp, "description", _eventFilter.description);
                        } else {
                            tmp = wac2_utils.matchOptionString(_events, "description", _eventFilter.description);
                            valid_tmp = true;
                        }
                    }
                    if (_eventFilter.location !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionString(tmp, "location", _eventFilter.location);
                        } else {
                            tmp = wac2_utils.matchOptionString(_events, "location", _eventFilter.location);
                            valid_tmp = true;
                        }
                    }
                    if (_eventFilter.category !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionArrayString(tmp, "categories", _eventFilter.category);
                        } else {
                            tmp = wac2_utils.matchOptionArrayString(_events, "categories", _eventFilter.category);
                            valid_tmp = true;
                        }
                    }
                    if (_eventFilter.status !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionShortArray(tmp, "status", _eventFilter.status);
                        } else {
                            tmp = wac2_utils.matchOptionShortArray(_events, "status", _eventFilter.status);
                            valid_tmp = true;
                        }
                    }
                    if (_eventFilter.initialStartDate !== undefined ||
                        _eventFilter.endStartDate !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionDate(tmp, "startTime", _eventFilter.initialStartDate, _eventFilter.endStartDate);
                        } else {
                            tmp = wac2_utils.matchOptionDate(_events, "startTime", _eventFilter.initialStartDate, _eventFilter.endStartDate);
                            valid_tmp = true;
                        }
                    }

                    // to make id readonly
                    if (valid_tmp) {
                        for (i = 0; i < tmp.length; i++) {
                            rst.push(new CalendarEvent(tmp[i], false));
                        }
                    } else {
                        for (var e in _events) {
                            rst.push(new CalendarEvent(_events[e], false));
                        }
                    }
                    onSuccess(rst);
                }, _FAKE_LONG_WAITTIME);
                pendingOperation = new PendingOperation(pendingObj);
                return pendingOperation;
            };

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "Calendar:findEvent", _doFindEvents);
        },
    };
    _self.__defineGetter__("type", function () {
        return _type;
    });
    _self.__defineGetter__("name", function () {
        return name;
    });
    return _self;
};

module.exports = function () {
    this.__defineGetter__("SIM_CALENDAR", function () {
        return 0;
    });
    this.__defineGetter__("DEVICE_CALENDAR", function () {
        return 1;
    });
    this.__defineGetter__("NO_RECURRENCE", function () { 
        return 0;
    });
    this.__defineGetter__("DAILY_RECURRENCE", function () {
        return 1;
    });
    this.__defineGetter__("WEEKLY_RECURRENCE", function () {
        return 2;
    });
    this.__defineGetter__("MONTHLY_RECURRENCE", function () {
        return 3;
    });
    this.__defineGetter__("YEARLY_RECURRENCE", function () {
        return 4;
    });
    this.__defineGetter__("TENTATIVE_STATUS", function () {
        return 0;
    });
    this.__defineGetter__("CONFIRMED_STATUS", function () {
        return 1;
    });
    this.__defineGetter__("CANCELLED_STATUS", function () {
        return 2;
    });
    this.__defineGetter__("NO_ALARM", function () {
        return 0;
    });
    this.__defineGetter__("SILENT_ALARM", function () {
        return 1;
    });
    this.__defineGetter__("SOUND_ALARM", function () {
        return 2;
    });

    this.getCalendars = function (onSuccess, onError) {
        var i, pendingOperation, pendingObj = {}, cal, _doGetCalendars;

        _doGetCalendars = function () {
            pendingObj = new PendingObject();

            pendingObj.pendingID = setTimeout(function () {
                pendingObj.setCancelFlag(false);
                cal = db.retrieveObject(_DB_CALENDARS_KEY) || [];
                _calendars = [];
                if (cal.length === 0) {
                    _calendars.push(new Calendar(_SIM_CALENDAR, "sim cal", {}));
                    _calendars.push(new Calendar(_DEVICE_CALENDAR, "dev cal", {}));
                } else {
                    for (i = 0; i < cal.length; i++) {
                        /* after getting Date out of DB, Date will become 
                           a string, so need to recast it back to Date */
                        /* NOTE: id becomes writable, so need to recast it
                           before passing to application */
                        for (var e in cal[i].events) {
                            if ((cal[i].events[e].startTime !== undefined) &&
                                cal[i].events[e].startTime !== null) {
                                cal[i].events[e].startTime = new Date(cal[i].events[e].startTime);
                            }
                            if ((cal[i].events[e].expires !== undefined) &&
                                cal[i].events[e].expires !== null) {
                                cal[i].events[e].expires = new Date(cal[i].events[e].expires);
                            }
                        }
                        _calendars.push(new Calendar(cal[i].type, cal[i].name, cal[i].events));
                    }
                }
                if (_calendars.length !== 0) {
                    onSuccess(utils.copy(_calendars));
                } else {
                    if (onError) {
                        onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
                    }
                }
            }, _FAKEWAITTIME);
            pendingOperation = new PendingOperation(pendingObj);
            return pendingOperation;
        };
    
        return wac2_utils.validateTypeMismatch(onSuccess, onError, "getCalendars", _doGetCalendars);
    };

    this.handleSubFeatures = function (subFeatures) {
        if (wac2_utils.isEmptyObject(subFeatures) ||
            subFeatures["http://wacapps.net/api/pim.calendar"] ||
            (subFeatures["http://wacapps.net/api/pim.calendar.read"] &&
            subFeatures["http://wacapps.net/api/pim.calendar.write"])) {
            return;
        } 
        if (subFeatures["http://wacapps.net/api/pim.calendar.read"]) {
            _addEventAllowed = false;
            _deleteEventAllowed = false;
            _updateEventAllowed = false;
            return;
        } 
        if (subFeatures["http://wacapps.net/api/pim.calendar.write"]) {
            _findEventsAllowed = false;
            return;
        } 
        _console.warn("WAC-2.0-Calendar-handleSubFeatures: something wrong");
    };
};

});
define('ripple/platform/wac/2.0/camera', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    constants = require('ripple/constants'),
    _console = require('ripple/console'),
    errorcode = require('ripple/platform/wac/2.0/errorcode'),
    PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
    PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
    DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils');

module.exports = function () {
    var _cameraArray, Camera, _videoStatus = {},
        _captureImage, _startVideoCapture,
        _doCaptureImage, _doStartVideoCapture,
        _doGetPreview, _doGetCameras,
        _stopVideoCapture, _createPreviewNode,
        _FAKEWAITTIME = 5,
        _defaultHighRes = true,
        _defaultImageFilename = "_capture.jpg",
        _defaultVideoFilename = "_capture.avi",
        _captureImageAllowed = true,
        _startVideoCaptureAllowed = true,
        _stopVideoCaptureAllowed = true,
        _createPreviewNodeAllowed = true;

    _doCaptureImage = function (onSuccess, onError, capFilename, capHighRes, pendingObj) {
        pendingObj.pendingID = setTimeout(function () {
            var dname = "", fname = "";
            //pretend to do sth.
            pendingObj.setCancelFlag(false);  // too late to cancel
            if (capFilename.indexOf("/") !== -1) {
                dname = capFilename.replace(/(.*\/)[^\/]+$/i, "$1");
                fname = capFilename.replace(/.*\/([^\/]*)$/i, "$1");
                //replace extension with jpg
                fname = fname.replace(/\.[^\/\.]+$/i, ".jpg");
            } else {
                dname = "";
                fname = capFilename.replace(/\.[^\/\.]+$/i, ".jpg");
            }
            if (fname === "") {
                fname = _defaultImageFilename;
            }
            if (fname.search(/\.jpg$/) === -1) {
                fname = fname + ".jpg";
            }
            if (capHighRes) {
                onSuccess(dname + "high-" + fname);
            } else {
                onSuccess(dname + "low-" + fname);
            }
        }, _FAKEWAITTIME);
    };

    _captureImage = function (onSuccess, onError, options) {
        var pendingOperation = {}, pendingObj,
            filename = this.id + _defaultImageFilename,
            highRes = _defaultHighRes, opt;

        if (onSuccess) {
            utils.validateArgumentType(onSuccess, "function", null, "captureImage: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }
        if (onError) {
            utils.validateArgumentType(onError, "function", null, "captureImage: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }
        if (options) {
            opt = new Object(options);
            /* NOTE: if desktinationFilename or highRes is not provided by
               user, i.e. undefined or null, a default value is used.
             */
            if (opt.destinationFilename !== null && opt.destinationFilename !== undefined) {
            // TODO: validate filename via Filesystem.resolve()
                filename = String(opt.destinationFilename);
            }
            if (opt.highRes !== null && opt.highRes !== undefined) {
                highRes = Boolean(opt.highRes);
            }
        }
        if (!_captureImageAllowed) {
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.SECURITY_ERR));
                }, 1);
            }
            return undefined;
        }

        if (onSuccess) {
            pendingObj = new PendingObject();
            _doCaptureImage(onSuccess, onError, filename, highRes, pendingObj);
            pendingOperation = new PendingOperation(pendingObj);
            return pendingOperation;
        } else {
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                }, 1);
            }
        }
        return undefined;
    };

    _stopVideoCapture = function () {
        var dname = "", fname = "", capFilename = _videoStatus[this.id].capFilename;
        if (_videoStatus[this.id]) {
            if (capFilename.indexOf("/") !== -1) {
                dname = capFilename.replace(/(.*\/)[^\/]+$/i, "$1");
                fname = capFilename.replace(/.*\/([^\/]*)$/i, "$1");
                //replace extension with avi
                fname = fname.replace(/\.[^\/\.]+$/i, ".avi");
            } else {
                dname = "";
                fname = capFilename.replace(/\.[^\/\.]+$/i, ".avi");
            }
            if (fname === "") {
                fname = _defaultVideoFilename;
            }
            if (fname.search(/\.avi$/) === -1) {
                fname = fname + ".avi";
            }
            if (_videoStatus[this.id].capHighRes) {
                _videoStatus[this.id].capSuccess(dname + "high-" + fname);
            } else {
                _videoStatus[this.id].capSuccess(dname + "low-" + fname);
            }
            delete _videoStatus[this.id];
        }
    };

    _doStartVideoCapture = function (camID, onSuccess, onError, filename, highRes, pendingObj) {
        var videoStatus = {};
        _videoStatus[camID] = videoStatus;
        pendingObj.userCancel = function () {
            delete _videoStatus[camID];
        };
        pendingObj.getCancelFlag = function () {
            return !!_videoStatus[camID];
        };
        pendingObj.pendingID = setTimeout(function () {
            // waiting to be cancelled
            videoStatus = {
                capSuccess: onSuccess,
                capError: onError,
                capFilename: filename,
                capHighRes: highRes
            };
            _videoStatus[camID] = videoStatus;
        }, _FAKEWAITTIME);
    };

    _startVideoCapture = function (onSuccess, onError, options) {
        var pendingOperation = {}, pendingObj,
            filename = this.id + _defaultVideoFilename,
            highRes = _defaultHighRes, opt;

        if (onSuccess) {
            utils.validateArgumentType(onSuccess, "function", null, "startVideoCapture: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }
        if (onError) {
            utils.validateArgumentType(onError, "function", null, "startVideoCapture: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }
        if (options) {
            opt = new Object(options);
            /* NOTE: if desktinationFilename or highRes is not provided by
               user, i.e. undefined or null, a default value is used.
             */
            if (opt.destinationFilename !== null && opt.destinationFilename !== undefined) {
            // TODO: validate filename via Filesystem.resolve()
                filename = String(opt.destinationFilename);
            }
            if (opt.highRes !== null && opt.highRes !== undefined) {
                highRes = Boolean(opt.highRes);
            }
        }
        if (!_captureImageAllowed) {
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.SECURITY_ERR));
                }, 1);
            }
            return undefined;
        }
        if (_videoStatus[this.id]) { 
            // capture already started
            _console.warn("WAC-2.0-startVideoCapture: capture already started");
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
                }, 1);
            }
            return undefined;
        }

        if (onSuccess) {
            pendingObj = new PendingObject();
            _doStartVideoCapture(this.id, onSuccess, onError, filename, highRes, pendingObj);
            
            pendingOperation = new PendingOperation(pendingObj);
            return pendingOperation;
        } else {
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                }, 1);
            }
        }
        return undefined;
    };

    _doGetPreview = function (camID, onSuccess, onError, pendingObj) {
        var container, demoImg, loc, imageSrc;
        container = document.createElement("div");
        container.setAttribute("id", camID + "-wac-2-0-camera-preview-container");
        demoImg = document.createElement("img");
        demoImg.setAttribute("id", camID + "-wac-2-0-camera-demo-image");
        loc = document.location;
        imageSrc = loc.protocol + "//" + loc.hostname + loc.pathname.replace(/index\.html$/, "") + constants.CAMERA.WINDOW_ANIMATION;
        demoImg.setAttribute("src", imageSrc);
        demoImg.setAttribute("width", "100%");
        container.appendChild(demoImg);
        
        pendingObj.pendingID = setTimeout(function () {
            pendingObj.setCancelFlag(false);  // too late to cancel
            onSuccess(container);
        }, _FAKEWAITTIME);
    };

    _createPreviewNode = function (onSuccess, onError) {
        var pendingOperation, pendingObj = {};
        if (onSuccess) {
            utils.validateArgumentType(onSuccess, "function", null, "createPreviewNode: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }
        if (onError) {
            utils.validateArgumentType(onError, "function", null, "createPreviewNode: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }
        if (!_createPreviewNodeAllowed) {
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.SECURITY_ERR));
                }, 1);
            }
            return undefined;
        }
        if (onSuccess) {
            pendingObj = new PendingObject();
            _doGetPreview(this.id, onSuccess, onError, pendingObj);
            pendingOperation = new PendingOperation(pendingObj);
            return pendingOperation;
        } else {
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                }, 1);
            }
        }
        return undefined;
    };

    Camera = function (cameraID) {
        return {
            id: cameraID,
            captureImage: _captureImage,
            startVideoCapture: _startVideoCapture,
            stopVideoCapture: _stopVideoCapture,
            createPreviewNode: _createPreviewNode
        };
    };

    _cameraArray = [new Camera("rear"), new Camera("front")];

    _doGetCameras = function (onSuccess, onError, pendingObj) {
        pendingObj.pendingID = setTimeout(function () {
            pendingObj.setCancelFlag(false);  // too late to cancel
            if (_cameraArray.length !== 0) {
                onSuccess(utils.copy(_cameraArray));
            } else {
                // no camera
                if (onError) {
                    setTimeout(function () {
                        onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
                    }, 1);
                }
            }
        }, _FAKEWAITTIME);
    };

    this.getCameras = function (onSuccess, onError) {
        var pendingOperation, pendingObj = {};
        if (onSuccess) {
            utils.validateArgumentType(onSuccess, "function", null, "getCameras: invalid successCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }
        if (onError) {
            utils.validateArgumentType(onError, "function", null, "getCameras: invalid errorCallback parameter", new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }
        if (onSuccess) {
            pendingObj = new PendingObject();
            _doGetCameras(onSuccess, onError, pendingObj);
            pendingOperation = new PendingOperation(pendingObj);
            return pendingOperation;
        } else {
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                }, 1);
            }
        }
        return undefined;
    };

    this.handleSubFeatures = function (subFeatures) {
        if (wac2_utils.isEmptyObject(subFeatures) ||
            subFeatures["http://wacapps.net/api/camera"] ||
            (subFeatures["http://wacapps.net/api/camera.capture"] &&
            subFeatures["http://wacapps.net/api/camera.show"])) {
            return;
        }
        if (subFeatures["http://wacapps.net/api/camera.show"] &&
           !subFeatures["http://wacapps.net/api/camera.capture"]) {
            _captureImageAllowed = false;
            _startVideoCaptureAllowed = false;
            _stopVideoCaptureAllowed = false;
            return;
        }
        if (subFeatures["http://wacapps.net/api/camera.capture"] &&
           !subFeatures["http://wacapps.net/api/camera.show"]) {
            _createPreviewNodeAllowed = false;
            return;
        }
        _console.warn("WAC-2.0-Camera-handleSubFeatures: something wrong");
    };
};

});
define('ripple/platform/wac/2.0/contact', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    constants = require('ripple/constants'),
    exception = require('ripple/exception'),
    errorcode = require('ripple/platform/wac/2.0/errorcode'),
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
    DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
    PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
    PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
    TypeCoerce = require('ripple/platform/wac/2.0/typecoerce'),
    Filter = require('ripple/platform/wac/2.0/contactfilter'),
    AddressBook,
    ContactProperties,
    Contact,
    Address,
    ContactAddress,
    PhoneNumber,
    EmailAddress,
    ContactFilter,
    _KEY = "wac2-pim-contact",
    _PENDING_TIME = 600,
    _addressBooks = [],
    _contacts = {},
    _security = {
        "http://wacapps.net/api/pim.contact": [],
        "http://wacapps.net/api/pim.contact.read": ["findContacts"],
        "http://wacapps.net/api/pim.contact.write": ["addContact", "updateContact", "deleteContact"],
        all: true
    },
    _self;

function _errorOccurred(onError, code) {
    if (!onError)
        return;

    setTimeout(function () {
        onError(new DeviceApiError(code));
    }, 1);
}

function _pendingOperate(operate, scope) {
    var i, argumentVector = [];

    for (i = 0; i < arguments.length - 2; i++)
        argumentVector[i] = arguments[i + 2];

    return function () {
        var pendingObj, pendingOperation;

        pendingObj = new PendingObject();
        pendingObj.pendingID = window.setTimeout(function () {
            pendingObj.setCancelFlag(false);
            operate.apply(scope, argumentVector);
        }, _PENDING_TIME);

        pendingOperation = new PendingOperation(pendingObj);

        return pendingOperation;
    };
}

function _defaultContacts() {
    var id1 = Math.uuid(null, 16),
        id2 = Math.uuid(null, 16),
        id3 = Math.uuid(null, 16),
        id4 = Math.uuid(null, 16),
        contacts = {};

    contacts.PHONE_ADDRESS_BOOK = {
        type: _self().PHONE_ADDRESS_BOOK,
        items: [{
            id: id1,
            firstName: "Leonardo",
            lastName: "Gates",
            nicknames: ["Leo"],
            phoneticName: "",
            addresses: [{streetAddress: "Gran Via, 32", postalCode: "50013", city: "Zaragoza", country: "ES"}],
            photoURI: "",
            phoneNumbers: [],
            emails: ["leo@underground.com"]
        }, {
            id: id2,
            firstName: "Jordan",
            lastName: "",
            nicknames: [""],
            phoneticName: "",
            addresses: [],
            photoURI: "",
            phoneNumbers: [],
            emails: ["jordan@underground.com"]
        }]
    };

    contacts.SIM_ADDRESS_BOOK = {
        type: _self().SIM_ADDRESS_BOOK,
        items: [{
            id: id3,
            firstName: "Raphael",
            lastName: "",
            nicknames: [""],
            phoneticName: "",
            addresses: [],
            photoURI: "",
            phoneNumbers: [],
            emails: ["raph@underground.com"]
        }]
    };

    contacts.DEVICE_ADDRESS_BOOK = {
        type: _self().DEVICE_ADDRESS_BOOK,
        items: [{
            id: id4,
            firstName: "Michelangelo",
            lastName: "",
            nicknames: [""],
            phoneticName: "",
            addresses: [],
            photoURI: "",
            phoneNumbers: [],
            emails: ["mike@underground.com"]
        }]
    };

    return contacts;
}

function _get() {
    _contacts = db.retrieveObject(_KEY) || _defaultContacts();
}

function _save() {
    db.saveObject(_KEY, _contacts);
}

function _initAddressBooks() {
    _get();
    utils.forEach(_contacts, function (contactObj, name) {
        _addressBooks.push(new AddressBook(contactObj.type, name));
    });
}

_self = function () {
    var contact = {
        getAddressBooks: function (successCallback, errorCallback) {
            function _getAddressBooks() {
                if (_addressBooks.length === 0) {
                    _initAddressBooks();
                }
                successCallback(_addressBooks);
            }
            return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "getAddressBooks", _getAddressBooks);
        },

        handleSubFeatures: function (subFeatures) {
            for (var subFeature in subFeatures) {
                if (_security[subFeature].length === 0) {
                    _security.all = true;
                    return;
                }
                _security.all = false;
                utils.forEach(_security[subFeature], function (method) {
                    _security[method] = true;
                });
            }
        }
    };

    contact.__defineGetter__("SIM_ADDRESS_BOOK", function () {
        return 0x0000;
    });

    contact.__defineGetter__("DEVICE_ADDRESS_BOOK", function () {
        return 0x000F;
    });

    contact.__defineGetter__("PHONE_ADDRESS_BOOK", function () {
        return 0x00FF;
    });

    return contact;
};

AddressBook = function (type, name) {
    var addressBook,
        contactItems = _contacts[name].items;

    addressBook = {
        createContact: function (contactProperties) {
            var cp, contact = new Contact();

            if ((contactProperties !== undefined) &&
                (contactProperties !== null)) {
                cp = TypeCoerce(ContactProperties).cast(contactProperties);
                !cp.firstName    || (contact.firstName    = utils.copy(cp.firstName));
                !cp.lastName     || (contact.lastName     = utils.copy(cp.lastName));
                !cp.nicknames    || (contact.nicknames    = utils.copy(cp.nicknames));
                !cp.phoneticName || (contact.phoneticName = utils.copy(cp.phoneticName));
                !cp.addresses    || (contact.addresses    = utils.copy(cp.addresses));
                !cp.photoURI     || (contact.photoURI     = utils.copy(cp.photoURI));
                !cp.phoneNumbers || (contact.phoneNumbers = utils.copy(cp.phoneNumbers));
                !cp.emails       || (contact.emails       = utils.copy(cp.emails));
            }

            return contact;
        },

        addContact: function (successCallback, errorCallback, contact) {
            function _addContact() {
                var c;

                if (!contact)
                    exception.raise(exception.types.Argument, "addContact invalid message parameter", new DeviceApiError(errorcode.INVALID_VALUES_ERR));

                if (!_security.all && !_security.addContact)
                    return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);

                c = TypeCoerce(new Contact()).cast(contact);
                contactItems.push(c);
                _save();
                successCallback(c);
            }
            return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "addContact", _pendingOperate(_addContact));
        },

        updateContact: function (successCallback, errorCallback, contact) {
            function _updateContact() {
                var c, isFound = false;

                if (!contact)
                    exception.raise(exception.types.Argument, "updateContact invalid message parameter", new DeviceApiError(errorcode.INVALID_VALUES_ERR));

                if (!_security.all && !_security.updateContact)
                    return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);

                c = TypeCoerce(new Contact()).cast(contact);
                utils.forEach(contactItems, function (contactItem) {
                    if (contactItem.id === c.id) {
                        !c.firstName    || (contactItem.firstName    = utils.copy(c.firstName));
                        !c.lastName     || (contactItem.lastName     = utils.copy(c.lastName));
                        !c.nicknames    || (contactItem.nicknames    = utils.copy(c.nicknames));
                        !c.phoneticName || (contactItem.phoneticName = utils.copy(c.phoneticName));
                        !c.addresses    || (contactItem.addresses    = utils.copy(c.addresses));
                        !c.photoURI     || (contactItem.photoURI     = utils.copy(c.photoURI));
                        !c.phoneNumbers || (contactItem.phoneNumbers = utils.copy(c.phoneNumbers));
                        !c.emails       || (contactItem.emails       = utils.copy(c.emails));

                        _save();
                        isFound = true;
                        successCallback();
                    }
                });

                if (!isFound)
                    _errorOccurred(errorCallback, errorcode.NOT_FOUND_ERR);
            }
            return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "updateContact", _pendingOperate(_updateContact));
        },

        deleteContact: function (successCallback, errorCallback, id) {
            function _deleteContact() {
                var isFound = false;

                if (!_security.all && !_security.deleteContact)
                    return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);

                utils.forEach(contactItems, function (contactItem, index) {
                    if (contactItem.id === id) {
                        contactItems.splice(index, 1);
                        _save();
                        isFound = true;
                        successCallback();
                    }
                });

                if (!isFound)
                    _errorOccurred(errorCallback, errorcode.NOT_FOUND_ERR);
            }
            return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "deleteContact", _pendingOperate(_deleteContact));
        },

        findContacts: function (successCallback, errorCallback, filter) {
            function _findContacts() {
                var contact, result = [];

                if (!_security.all && !_security.findContacts)
                    return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);

                utils.forEach(contactItems, function (contactItem) {
                    if ((filter              === undefined || filter === null) ||
                        (filter.id           === undefined || Filter(filter.id).match(contactItem.id)) &&
                        (filter.firstName    === undefined || Filter(filter.firstName).match(contactItem.firstName)) &&
                        (filter.lastName     === undefined || Filter(filter.lastName).match(contactItem.lastName)) &&
                        (filter.phoneticName === undefined || Filter(filter.phoneticName).match(contactItem.phoneticName)) &&
                        (filter.nickname     === undefined || Filter(filter.nickname).match(contactItem.nicknames)) &&
                        (filter.phoneNumber  === undefined || Filter(filter.phoneNumber).match(contactItem.phoneNumbers)) &&
                        (filter.email        === undefined || Filter(filter.email).match(contactItem.emails)) &&
                        (filter.address      === undefined || Filter(filter.address).match(contactItem.addresses))) {
                        contact = new Contact(contactItem.id);

                        contact.firstName    = utils.copy(contactItem.firstName);
                        contact.lastName     = utils.copy(contactItem.lastName);
                        contact.nicknames    = utils.copy(contactItem.nicknames);
                        contact.phoneticName = utils.copy(contactItem.phoneticName);
                        contact.addresses    = utils.copy(contactItem.addresses);
                        contact.photoURI     = utils.copy(contactItem.photoURI);
                        contact.phoneNumbers = utils.copy(contactItem.phoneNumbers);
                        contact.emails       = utils.copy(contactItem.emails);

                        result.push(contact);
                    }
                });
                successCallback(result);
            }
            return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "findContacts", _pendingOperate(_findContacts));
        }
    };

    addressBook.__defineGetter__("type", function () {
        return type;
    });

    addressBook.__defineGetter__("name", function () {
        return name;
    });

    return addressBook;
};

Address = {
    country: "",
    region: "",
    county: "",
    city: "",
    streetAddress: "",
    additionalInformation: "",
    postalCode: ""
};

ContactAddress = function () {
    this.types = [""]; // "WORK", "PREF", "HOME"
};

ContactAddress.prototype = Address;

PhoneNumber = {
    number: "",
    types: [""] // "WORK", "PREF", "HOME", "VOICE", "FAX", "MSG", "CELL",
                // "PAGER", "BBS", "MODEM", "CAR", "ISDN", "VIDEO", "PCS"
};

EmailAddress = {
    email: "",
    types: [""] // "WORK", "PREF", "HOME"
};

ContactProperties = {
    firstName: "",
    lastName: "",
    nicknames: [""],
    phoneticName: "",
    addresses: [new ContactAddress()],
    photoURI: "",
    phoneNumbers: [PhoneNumber],
    emails: [EmailAddress]
};

Contact = function (id) {
    id = id || Math.uuid(null, 16);

    this.__defineGetter__("id", function () {
        return id;
    });
};

Contact.prototype = ContactProperties;

ContactFilter = {
    id: "",
    firstName: "",
    lastName: "",
    phoneticName: "",
    nickname: "",
    phoneNumber: "",
    email: "",
    address: ""
};

module.exports = _self;

});
define('ripple/platform/wac/2.0/contactfilter', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    _self;

_self = function (criteria) {
    var pattern,
        contactFilter;

    contactFilter = {
        match: function (target) {
            var result = false, key, value, index;

            switch (Object.prototype.toString.call(target)) {
            case "[object String]":
                result = pattern.test(target);
                break;

            case "[object Object]":
                for (key in criteria) {
                    result = true;
                    value = criteria[key];
                    if ((value !== undefined) && (!_self(value).match(target[key])))
                        return false;
                }
                break;

            case "[object Array]":
                for (index in target) {
                    if (contactFilter.match(target[index]))
                        return true;
                }
                break;
            }

            return result;
        }
    };

    if (typeof criteria === "string")
        pattern = new RegExp(criteria.replace(/(^|[^\\])%+/g, "$1.*").replace(/\\%/g, "%").replace(/.*/, "^$&$"), "i");

    return contactFilter;
};

module.exports = _self;

});
define('ripple/platform/wac/2.0/dbfs', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *  Copyright 2011 Intel Corporation.
 *
 * 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.
 */

/* We know the dbfs is not an accurate simulation of WAC 2.0 filesystem.
 *
 * 1) We have tried W3C File API, as some of WAC filesystem APIs are synchronous, 
 * it is impossible to simulate them by using the asynchronous API in the main
 * UI thread and although we could use synchronous W3C API in a worker, it is
 * not reasonable to limit WAC filesystem API usage in a worker.
 *
 * 2) The problem is partially solved by using database to simulate the filesystem,
 * For the asynchronous aspect, actually all the files are read into memory (cache 
 * object in this file) and the cache operation is synchronous. It is not perfect.
 * And the database has 5MB limitation when running in Chrome.
 *
 * In the future, we might use ajax or NPAPI to get a better simulation.
 */

/* Note: The entry object is shared between this module and filesystem */

var db = require('ripple/db'),
    utils = require('ripple/utils'),
    _console = require('ripple/console'),
    _cache = {},
    _self;

function _get(path) {
    return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
        return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
    }, _cache);
}

function _getInfo(path) {
    var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
        name = parent.splice(parent.length - 1, 1).join("");

    return {
        name: name,
        parent: parent.join("/") || "/"
    };
}

function _set(path, obj) {
    var parent = _cache,
        tokens = path.replace(/^\//, '').split("/"),
        child = tokens.splice(tokens.length - 1, 1).join("");

    tokens.forEach(function (token) {
        parent = parent.children[token];
    });

    parent.children = parent.children || {};
    parent.children[child] = obj;
}

function _delete(path) {
    var parent = _cache,
        tokens = path.replace(/^\//, '').split("/"),
        child = tokens.splice(tokens.length - 1, 1).join("");

    tokens.forEach(function (token) {
        parent = parent.children[token];
    });

    delete parent.children[child];
}

function _save() {
    db.saveObject("wac2-db-filesystem", _cache);
}

function _walk(path, parent) { 
    _self.ls(path, function (entries) { 
        parent.children = parent.children || {}; 

        entries.forEach(function (entry) { 
            parent.children[entry.name] = entry; 

            if (entry.isDirectory) { 
                _walk(entry.fullPath, entry); 
            } else { 
                /* after getting Date out of DB, Date will become 
                   a string, so need to recast it back to Date */
                if (entry.lastModifiedDate !== null && entry.lastModifiedDate !== undefined)
                    entry.lastModifiedDate = new Date(entry.lastModifiedDate);

                _self.read(entry.fullPath, function (data) { 
                    parent.children[entry.name].data = data; 
                }, function (e) { 
                    _console.error(e); 
                }); 
            } 
        }); 
    }, function (e) { 
        _console.error(e); 
    }); 
} 
 
function _createPath(path) { 
    var parts = path.replace(/^\//, '').split("/"), 
        workflow = jWorkflow.order(); 
 
    parts.forEach(function (part, index) { 
        var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/"); 
 
        workflow.andThen(function (prev, baton) { 
            baton.take(); 
            _self.mkdir(dir, baton.pass, baton.pass); 
        }); 
    }); 
 
    workflow.start(); 
}

_self = {
    // The order is consistent with _virtualRoots in filesystem.js
    roots: ["/opt/documents", "/opt/images", "/opt/music", "/opt/videos", "/opt/downloads", "/home/user/appdata/simulatedapp/wgt-package", "/home/user/appdata/simulatedapp/wgt-private", "/home/user/appdata/simulatedapp/wgt-private-tmp", "/SDCard", "/opt/attachments"],
    initialize: function () {
        // TODO: Initialize at bootstrap and emulatorBridge.link 
        _cache = db.retrieveObject("wac2-db-filesystem") || {};
        // create real root paths if empty
        _self.roots.every(function (root) {
            _createPath(root);
            return true;
        }); 
       // build the file system cache so that we could access information synchronously
        _walk("/", _cache);
    },
    ls: function (path, success, error) {
        try {
            var dir = _get(path),
                items = [];

            if (dir) {
                utils.forEach(dir.children, function (item) {
                    items.push(item);
                });
            }
            else {
                items = {};
            }

            success(items);
        }
        catch (e) {
            e.code = 1;
            error(e);
        }
    },
    rm: function (path, success, error, options) {
        _delete(path);
        _save();
        success();
    },
    rmdir: function (path, success, error, options) {
        _delete(path);
        _save();
        success();
    },
    mkdir: function (path, success, error) {
        var entry = _get(path),
            info = _getInfo(path);

        if (!entry) {
            _set(path, {
                name: info.name,
                isDirectory: true,
                fullPath: path
            });
            entry = _get(path);
            _save();
        }
        
        if (entry) {
            success(entry);
        }
        else {
            error({code: 1});
        }
    },
    mv: function (from, to, success, error) {
        try {
            var fromEntry = _get(from),
                toInfo = _getInfo(to);

            fromEntry.fullPath = to;
            fromEntry.name = toInfo.name;

            _set(to, fromEntry);
            _delete(from);
            _save();
            success();
        }
        catch (e) {
            e.code = 1;
            error(e);
        }
    },
    touch: function (path, success, error) {
        var entry = _get(path),
            info  = _getInfo(path);

        if (!entry) {
            _set(path, {
                lastModifiedDate: new Date(),
                name: info.name,
                isDirectory: false,
                fullPath: path,
                data: ""
            });
            entry = _get(path);
        }
        _save();
        success(entry);
    },
    cp: function (from, to, success, error) {
        try {
            var fromEntry = _get(from),
                copied = utils.copy(fromEntry);

            copied.name  = _getInfo(to).name;
            copied.fullPath = to;
            _set(to, copied);
            _save();
            success();
        }
        catch (e) {
            e.code = 1;
            error(e);
        }
    },
    stat: function (path, success, error) {
        var entry = _get(path);
        
        if (entry) {
            success(entry);
        } else {
            error({code: 1});
        }
    },
    write: function (path, contents, success, error, options) {
        var entry = _get(path);

        if (entry) {
            entry.lastModifiedDate = new Date();
            entry.data = contents;
            _save();
            success();
        } else {
            error({code: 1});
        }

    },
    read: function (path, success, error) {
        var entry = _get(path);

        if (entry) {
            success(utils.copy(entry.data));
        }
        else {
            error({code: 1});
        }
    }
};

module.exports = _self;


});
define('ripple/platform/wac/2.0/deviceapierror', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/wac/2.0/errorcode');

module.exports = function (code) {
    for (var c in errorcode) {
        var g = errorcode.__lookupGetter__(c);
        if (g) {
            this.__defineGetter__(c, g);
        }
    }

    this.code = code;
    this.message = errorcode.message[code];
    this.type =  "";

    this.toString = function () {
        var result = this.type + ': "' + this.message + '"';

        if (this.stack) {
            result += "\n" + this.stack;
        }
        return result;
    };
};


});
define('ripple/platform/wac/2.0/deviceapis', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 platform = require('ripple/platform'),
    app = require('ripple/app'),
    utils = require('ripple/utils'),
    init_done = false,
    _activatedSet = {},
    _activatedFeatures = [],
    _availableSet = {},
    _availableFeatures = [],
    _features = {},
    initFeaturesSet,
    populateFeatures;

populateFeatures = function (objects) {
    utils.forEach(objects, function (obj, key) {
        var objFeatures = {}, rpt, i, j;
        if (obj.feature) {
            objFeatures = obj.feature.split('|');
            utils.forEach(objFeatures, function (feature) {
                var avail = {uri: feature,
                             required: false,
                             param: null};
                _availableSet[feature] = avail;
            });
            if (_features) {
                rpt = objFeatures.length;
                j = 0;
                for (i = 0; i < rpt; i++) {
                    if (!_features[objFeatures[j]]) {
                        objFeatures.splice(j, 1);
                    } else {
                        j++;
                    }
                }
            }
            utils.forEach(objFeatures, function (feature) {
                var avail = {uri: feature,
                             required: true,
                             param: null};
                _activatedSet[feature] = avail;
            });
        }
        if (obj.children) {
            populateFeatures(obj.children);
        }
    });
};

initFeaturesSet = function () {
    _features = utils.copy(app.getInfo().features);
    populateFeatures(platform.current().objects);
    utils.forEach(_activatedSet, function (obj, key) {
            _activatedFeatures.push(obj);
        });
    utils.forEach(_availableSet, function (obj, key) {
            _availableFeatures.push(obj);
        });
    init_done = true;
};

module.exports = {
    listAvailableFeatures: function () {
        if (!init_done)
            initFeaturesSet();
        return _availableFeatures;
    },

    listActivatedFeatures: function () {
        if (!init_done)
            initFeaturesSet();
        return _activatedFeatures;
    }
};


});
define('ripple/platform/wac/2.0/deviceinteraction', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 notifications = require('ripple/notifications'),
    constants = require('ripple/constants'),
    PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
    PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
    DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
    errorcode = require('ripple/platform/wac/2.0/errorcode'),
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    deviceSettings = require('ripple/deviceSettings'),
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
    _self,
    NOTIFY_DURATION_LIMIT = 5000;

function pendingOperation(f) {
    var _FAKEWAITTIME = 0,
        pendingObj;
    
    if (_FAKEWAITTIME === 0) {
        f();
        return undefined;
    }
    else {
        pendingObj = new PendingObject();
        pendingObj.pendingID = setTimeout(function () {
            pendingObj.setCancelFlag(false);
            f();
        }, _FAKEWAITTIME);
        return new PendingOperation(pendingObj);
    }
}

function checkDuration(duration) {
    if (duration) {
        duration = duration | 0;  
        if (duration <= 0 || duration > NOTIFY_DURATION_LIMIT) {
            return NOTIFY_DURATION_LIMIT;
        } else {
            return duration;
        }
    } else {
        return NOTIFY_DURATION_LIMIT;
    }
}

function isMute() {
    return deviceSettings.retrieve("Config.soundVolume") <= 0;
}

function isInVibrateMode() {
    return deviceSettings.retrieve("Config.vibratingMode");
}

function isBacklightOn() {
    return deviceSettings.retrieve("Config.backlight");
}

var vibrator = (function () {
    var isVibrating = false,
        terminateAfterPattern = false,
        pattern = null,
        pulseIndex = 0,
        vibrateTimeout = null,
        terminateTimeout = null,
        MILLILSECONDS_OF_ONE_VIBRATION = 100,
        node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
        movementIndex = 0,
        movement = [{ left: -10 }, { left: 0 }, { left: 10 }, { left: 0 },
             {top: -10 }, { top: 0 }, {top: 10 }, { top: 0 }];

    function _clearTimeout() {
        if (vibrateTimeout) {
            clearInterval(vibrateTimeout);
            vibrateTimeout = null;        
        }
        if (terminateTimeout) {
            clearTimeout(terminateTimeout);
            terminateTimeout = null;        
        }
    }  
    
    function stopVibrate() {
        isVibrating = false;
        _clearTimeout();
        node.css({left: 0, top: 0}, MILLILSECONDS_OF_ONE_VIBRATION);
    }
    
    function vibrate() {
        //node.animate(movement[movementIndex], MILLILSECONDS_OF_ONE_VIBRATION);
        node.css(movement[movementIndex]);
        movementIndex = (movementIndex + 1) % 8;
    }
    
    function changePulse() {
        //pattern != null
        var pulse = pattern[pulseIndex];
        if (pulse === '.') vibrate();
        ++pulseIndex;
        if (pulseIndex >= pattern.length) {
            if (terminateAfterPattern) {
                setTimeout(stopVibrate, 1);
                return;
            }
            pulseIndex = 0;
        }
    }
    
    function terminateVibrate() {
        terminateAfterPattern = true;
        terminateTimeout = null;
        if (pattern === null) {
            stopVibrate();        
        }
    }  
  
    function startVibrate(duration, _pattern) {
        if (!isInVibrateMode()) return;
        _clearTimeout();
        terminateAfterPattern = false;
        movementIndex = 0;
        
        if (_pattern) {
            pattern = _pattern;
            pulseIndex = 0;
            vibrateTimeout = setInterval(changePulse, MILLILSECONDS_OF_ONE_VIBRATION);
            if (duration) 
                terminateAfterPattern = false;
            else 
                terminateAfterPattern = true;
        } else {
            pattern = null;
            vibrateTimeout = setInterval(vibrate, MILLILSECONDS_OF_ONE_VIBRATION);
        }
        terminateTimeout = setTimeout(terminateVibrate, checkDuration(duration));        
        isVibrating = true;
    }

    event.on("VibratingModeChanged", function (value) {
        if (value === false) {
            stopVibrate();
        }
    });

    return {
        startVibrate: startVibrate,
        stopVibrate: stopVibrate
    };
}()); //jslint style

var backlight = (function () {
    var timeout = null,
        isNotifying = false,
        node = jQuery("#" + constants.COMMON.VIEWPORT_CONTAINER);
        
    function _clearTimeout() {
        if (timeout) {
            clearTimeout(timeout); 
            timeout = null;
        }
    }
    
    function _switch(on) {
        node.css('opacity', on ? '':'0.4');
    }
    
    function switchOff() {
        if (!isNotifying) return;
        _clearTimeout();
        _switch(false);
        isNotifying = false;
    }
    
    function switchOn(duration) {
        if (isBacklightOn()) return;
        _clearTimeout();
        _switch(true);
        timeout = setTimeout(switchOff, checkDuration(duration));
        isNotifying = true;
    }

    _switch(isBacklightOn());
    event.on("BacklightChanged", function (value) {
        _clearTimeout();
        isNotifying = false;
        _switch(value);
    });

    return {
        switchOn  : switchOn,
        switchOff : switchOff
    };
}()); //jslint style

var beeper = (function () {
    var isBeeping = false,
        timeout = null,
        beepFile = "beep.wav", //TODO: license issues
        errorHandler = null,
        _beeper = utils.createElement("audio", {"id": "notify-beeper"});
        
    document.getElementById("ui").appendChild(_beeper);
    _beeper.setAttribute("src", beepFile);
    _beeper.setAttribute("loop", "true");
    _beeper.load();
    
    function _clearTimeout() {
        if (timeout) {
            clearTimeout(timeout);
            timeout = false;
        }
    }
    
    function raiseError() {
        if (errorHandler) {
            setTimeout(function () {
                errorHandler(new DeviceApiError(errorcode.UNKNOWN_ERR));
            }, 1);
        }
    }
    
    function stopBeep() {
        _clearTimeout();
        if (isBeeping) {
            try {
                _beeper.pause();
            } catch (e) {}
            isBeeping = false;
        }
    }
    
    _beeper.addEventListener('error', function () {
        stopBeep();
        raiseError();
    });
   
    function startBeep(onSuccess, onError, duration) {
        errorHandler = onError;
        try {
            stopBeep();
            _beeper.currentTime = 0;
            _beeper.play();
            isBeeping = true;
            timeout = setTimeout(stopBeep, checkDuration(duration));
            setTimeout(function () {
                onSuccess();
            }, 1);
        }catch (e) {
            raiseError();
        }
    }
    
    event.on("VolumeChanged", function (value) {
        value = value | 0;
        if (value < 0) value = 0;
        else if (value > 100) value = 100;       
        _beeper.volume = value / 100.0;
    });
    
    return {
        startBeep : startBeep,
        stopBeep  : stopBeep
    };
}()); //jslint style

module.exports = _self = {

    startNotify : function (onSuccess, onError, duration) {
        return wac2_utils.validateTypeMismatch(onSuccess, onError, "startNotify", function () {
            if (!isMute()) {
                return pendingOperation(function () {
                    beeper.startBeep(onSuccess, onError, duration);
                });
            } else if (isInVibrateMode()) {
                return _self.startVibrate(onSuccess, onError, duration);
            } else {
                return _self.lightOn(onSuccess, onError, duration);
            }
        });
    },

    stopNotify : function () {
        beeper.stopBeep();
        vibrator.stopVibrate();
        backlight.switchOff();
    },

    startVibrate : function (onSuccess, onError, duration, pattern) {       
        return wac2_utils.validateTypeMismatch(onSuccess, onError, "startVibrate", function () {
            if (pattern) {
                pattern = String(pattern);
                if (!pattern.match(/[\._]{1,10}/)) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }   
            }
            
            if (!isInVibrateMode()) {
                if (onError) {
                    setTimeout(function () {
                        onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
                    }, 1);
                }
                return undefined;          
            }
  
            setTimeout(function () {
                onSuccess();
            }, 1);
            return pendingOperation(function () {
                vibrator.startVibrate(duration, pattern);
            });

        });
    },
    
    stopVibrate : function () {
        vibrator.stopVibrate();
    },

    lightOn : function (onSuccess, onError, duration) {
        return wac2_utils.validateTypeMismatch(onSuccess, onError, "lightOn", function () {
            if (isBacklightOn()) {
                if (onError) {
                    setTimeout(function () {
                        onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
                    }, 1);
                }
                return undefined;               
            }
        
            setTimeout(function () {
                onSuccess();
            }, 1);
            return pendingOperation(function () {
                backlight.switchOn(duration);
            });
        });
    },

    lightOff : function () {
        backlight.switchOff();
    },

    setWallpaper : function (onSuccess, onError, fileName) {
        //TODO: file name, existance, extension checking.
        return wac2_utils.validateTypeMismatch(onSuccess, onError, "setWallpaper", function () {
            return pendingOperation(function () {
                notifications.openNotification("normal", "setWallpaper:" + fileName);
                setTimeout(function () {
                    onSuccess();
                }, 1);
            });
        });
    }
};


});
define('ripple/platform/wac/2.0/devicestatus', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
    errorcode = require('ripple/platform/wac/2.0/errorcode'),
    _console = require('ripple/console'),
    DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
    deviceSettings = require('ripple/deviceSettings'),    
    event = require('ripple/event'),    
    PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
    PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
    _getDeviceInfoAspect = true,
    _getNetworkInfoAspect = true,    
    _deviceInfoAspect = ["Battery", "Device", "Display", "MemoryUnit", "OperatingSystem", "WebRuntime"],    
    _networkInfoAspect = ["CellularHardware", "CellularNetwork", "WiFiHardware", "WiFiNetwork"],
    _aspectArray = [], 
    _propertyMap = {},
    _watches = {},
    _self;

function _asynchErrorCallback(errorCallback, errorCode) {
    if (errorCallback) {        
        setTimeout(function () {
            errorCallback(errorCode);
        }, 1);  
    }
}

function _initialize() {
    var aspectName, index, i;

    _aspectArray = _deviceInfoAspect.concat(_networkInfoAspect);
    for (index = 0; index < _aspectArray.length; index++) {
        aspectName = _aspectArray[index];
        _propertyMap[aspectName] = [];
        for (i in deviceSettings.retrieve(aspectName)) {
            _propertyMap[aspectName].push(i);
        }
    }     
}

function _isPropertyFound(aspect, property) {
    if (_aspectArray.length === 0) {
        _initialize();
    }

    if (_propertyMap[aspect]) {
        if (property) {
            return _propertyMap[aspect].some(function (prop) {
                return prop === property;
            });
        }
        return true;
    }
    return false;
}

function _isPropertyAllowed(aspect) {
    function hasAspect(asp) {
        return asp === aspect;
    }

    if ((_deviceInfoAspect.some(hasAspect) && _getDeviceInfoAspect === false) ||
        (_networkInfoAspect.some(hasAspect) && _getNetworkInfoAspect === false)) {
        return false;
    }

    return true;
}

function _isPropertyValid(prop, errorCallback) {
    var _prop = Object(prop);

    if (_prop && _prop.aspect && _prop.property) {
        if (_isPropertyFound(_prop.aspect, _prop.property) === false) {
            _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.NOT_FOUND_ERR));
            return false;
        }
        else if (_isPropertyAllowed(_prop.aspect) === false) {
            _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.SECURITY_ERR));
            return false;
        }
    } 
    else {
        _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.INVALID_VALUES_ERR));
        return false;
    }
    return true;
}

module.exports = function () {
    return {  
        getComponents: function (aspect) {
            if (_isPropertyFound(aspect))
                return ["_default"];
            return null;              
        },

        isSupported: function (aspect, property) {
            return _isPropertyFound(aspect, property);
        },

        getPropertyValue: function (successCallback, errorCallback, prop) {
            return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "getPropertyValue", function () {                                  
                if (_isPropertyValid(prop, errorCallback) !== true)
                    return undefined;
                
                var value = deviceSettings.retrieve(prop.aspect + "." + prop.property);
                if (value !== undefined) {
                    successCallback(value, prop);
                }
                else {
                    _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.NOT_AVAILABLE_ERR)); 
                }
                
                return null;    
            });        
        },
       
        watchPropertyChange: function (successCallback, errorCallback, prop, options) {  
            return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "watchPropertyChange", function () {
                if (_isPropertyValid(prop, errorCallback) !== true)
                    return undefined;

                var _options = Object(options),
                    eventType = deviceSettings.retrieve(prop.aspect)[prop.property].event,
                    watchObj = {
                        eventType: eventType,
                        onEvent: function (newValue) {
                            if (watchObj.timeStamp && 
                                ((new Date()).getTime() - watchObj.timeStamp < options.minNotificationInterval)) {
                                return undefined;
                            }                       
                            else if (watchObj.value &&
                                     (newValue > watchObj.value * (1 - _options.minChangePercent) && 
                                      newValue < watchObj.value * (1 + _options.minChangePercent))) {
                                return undefined;
                            }

                            if (watchObj.intervalId) {
                                clearInterval(watchObj.intervalId);
                                watchObj.intervalId = setInterval(function () {
                                    successCallback(deviceSettings.retrieve(prop.aspect + "." + prop.property), prop);
                                }, _options.maxNotificationInterval);
                            }
                            successCallback(newValue, prop);
                            if (watchObj.timeStamp) {
                                watchObj.timeStamp = (new Date()).getTime();
                            }
                            if (watchObj.value) {
                                watchObj.value = newValue;
                            }
                        }                              
                    },
                    watchId = (new Date()).getTime() | 0;

                if (options && _options.minNotificationInterval && _options.maxNotificationInterval && 
                    (_options.minNotificationInterval < 0 || _options.maxNotificationInterval < 0 || 
                     _options.minNotificationInterval >= _options.maxNotificationInterval)) {
                    _asynchErrorCallback(errorCallback, new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                    return undefined;
                }

                if (options && _options.maxNotificationInterval) {
                    watchObj.intervalId = setInterval(function () {
                        successCallback(deviceSettings.retrieve(prop.aspect + "." + prop.property), prop);
                    }, _options.maxNotificationInterval);
                }    

                if (options && _options.minNotificationInterval) {
                    watchObj.timeStamp = (new Date()).getTime();
                }                    

                if (options && _options.minChangePercent) {
                    if (_options.minNotificationInterval || _options.maxNotificationInterval) {}
                    else {                
                        watchObj.value = deviceSettings.retrieve(prop.aspect + "." + prop.property);
                    }
                }
               
                _watches[watchId] = watchObj;
                if (watchObj.eventType) {
                    event.on(watchObj.eventType, watchObj.onEvent);
                }

                return watchId;
            });             
        },

        clearPropertyChange: function (watchHandler) {
            var _handler = watchHandler | 0;
            
            if (_watches[_handler]) {
                event.deleteEventHandler(_watches[_handler].eventType, _watches[_handler].onEvent);            
                if (_watches[_handler].intervalId) {
                    clearInterval(_watches[_handler].intervalId);
                }
                delete(_watches[_handler]); 
            }
            return null;
        },

        handleSubFeatures: function (subFeatures) {
            if (wac2_utils.isEmptyObject(subFeatures) ||
                subFeatures["http://wacapps.net/api/devicestatus"] || 
                (subFeatures["http://wacapps.net/api/devicestatus.deviceinfo"] &&
                 subFeatures["http://wacapps.net/api/devicestatus.networkinfo"])) {
                return;
            }
            if (subFeatures["http://wacapps.net/api/devicestatus.deviceinfo"]) {
                _getNetworkInfoAspect = false;
                return;
            }
            if (subFeatures["http://wacapps.net/api/devicestatus.networkinfo"]) {
                _getDeviceInfoAspect = false;
                return;
            }
            _console.warn("WAC-2.0-Devicestatus-handleSubFeatures: something wrong");
        }
    };
};


});
define('ripple/platform/wac/2.0/errorcode', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 _self = {
    message : []
};

_self.__defineGetter__("UNKNOWN_ERR", function () {
    return 0;
});

_self.__defineGetter__("INDEX_SIZE_ERR", function () {
    return 1;
});

_self.__defineGetter__("DOMSTRING_SIZE_ERR", function () {
    return 2;
});

_self.__defineGetter__("HIERARCHY_REQUEST_ERR", function () {
    return 3;
});

_self.__defineGetter__("WRONG_DOCUMENT_ERR", function () {
    return 4;
});

_self.__defineGetter__("INVALID_CHARACTER_ERR", function () {
    return 5;
});

_self.__defineGetter__("NO_DATA_ALLOWED_ERR", function () {
    return 6;
});

_self.__defineGetter__("NO_MODIFICATION_ALLOWED_ERR", function () {
    return 7;
});

_self.__defineGetter__("NOT_FOUND_ERR", function () {
    return 8;
});

_self.__defineGetter__("NOT_SUPPORTED_ERR", function () {
    return 9;
});

_self.__defineGetter__("INUSE_ATTRIBUTE_ERR", function () {
    return 10;
});

_self.__defineGetter__("INVALID_STATE_ERR", function () {
    return 11;
});

_self.__defineGetter__("SYNTAX_ERR", function () {
    return 12;
});

_self.__defineGetter__("INVALID_MODIFICATION_ERR", function () {
    return 13;
});

_self.__defineGetter__("NAMESPACE_ERR", function () {
    return 14;
});

_self.__defineGetter__("INVALID_ACCESS_ERR", function () {
    return 15;
});

_self.__defineGetter__("VALIDATION_ERR", function () {
    return 16;
});

_self.__defineGetter__("TYPE_MISMATCH_ERR", function () {
    return 17;
});

_self.__defineGetter__("SECURITY_ERR", function () {
    return 18;
});

_self.__defineGetter__("NETWORK_ERR", function () {
    return 19;
});

_self.__defineGetter__("ABORT_ERR", function () {
    return 20;
});

_self.__defineGetter__("TIMEOUT_ERR", function () {
    return 21;
});

_self.__defineGetter__("INVALID_VALUES_ERR", function () {
    return 22;
});

_self.__defineGetter__("IO_ERR", function () {
    return 100;
});

_self.__defineGetter__("NOT_AVAILABLE_ERR", function () {
    return 101;
});

function _setMessage(_self) {
    var c, g;
    for (c in _self) {
        g = _self.__lookupGetter__(c);
        if (g) {
            _self.message[g()] = c;
        }
    }
}

_setMessage(_self);

module.exports = _self;


});
define('ripple/platform/wac/2.0/filesystem', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/wac/2.0/errorcode'),
    DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
    utils = require('ripple/utils'),
    dbfs  = require('ripple/platform/wac/2.0/dbfs'),
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
    _console = require('ripple/console'),
    _maxPathLength = 256,
    _virtualRoots = ["documents", "images", "music", "videos", "downloads", "wgt-package", "wgt-private", "wgt-private-tmp", "removable", "attachments"],
    _realRoots = dbfs.roots,
    _r2vmap = {},
    _v2rmap = {},
    _initialized = false,
    _readOnly  = false,
    _writeOnly = false,
    _defaultMode = "rw",
    File, 
    FileStream;

function _isValidChar(c) {
    return  (c >= '0' && c <= '9') || 
        (c >= 'a' && c <= 'z') || 
        (c >= 'A' && c <= 'Z') || 
        (c === ' ') || 
        (c === '_') ||
        (c === '-') ||
        (c === '.');
}

function _isValidFileName(name) {
    var _valid = true,
        _c;

    if (name === '' || name === '.' || name === '..' || (name.length > _maxPathLength)) {
        _valid = false;
    } else {
        for (_c = 0; _c < name.length; _c++) {
            if (!_isValidChar(name[_c])) {
                _valid = false;
                break;
            }
        }
    }
    
    return _valid;
}

function _initialize() {
    var _i;

    dbfs.initialize();
    
    // set up the map between real path and virtual path
    for (_i = 0; _i < _virtualRoots.length; _i++) {
        _r2vmap[_realRoots[_i]] = _virtualRoots[_i];
    }

    utils.forEach(_r2vmap, function (value, key) {
        _v2rmap[value] = key;
    });
}

function _resolveSync(srcLocation, onSuccess, onError, accessMode) {
    var _parts = srcLocation.replace(/\/$/, '').split("/"),
        _header, _fullPath,
        _i;

    // TODO: Initialize at bootstrap and emulatorBridge.link 
    if (!_initialized) {
        _initialize();
        _initialized = true;
    }

    for (_i = 0; _i < _parts.length; _i++) {
        if (!_isValidFileName(_parts[_i])) {
            if (onError) {
                onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
            }
            return;
        }
    }

    _header = _v2rmap[_parts[0]];
    if (_header === undefined) {
        if (onError) {
            onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
        }
        return;
    }

    if (_parts.length === 1) {
        _fullPath = _header;
    } else {
        _fullPath = _header + "/" + _parts.splice(1, _parts.length - 1).join("/");
    }

    dbfs.stat(_fullPath, 
            function (entry) {
                onSuccess(new File(entry, accessMode));
            }, 
            function () {
                if (onError) {
                    onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
                }    
            });
}

function _resolveAsync(onSuccess, onError, srcLocation, accessMode) {
    _resolveSync(srcLocation,
                function (file) {
                    setTimeout(function () {
                        onSuccess(file);
                    }, 1);
                },
                function (e) {
                    setTimeout(function () {
                        onError(e);
                    }, 1);
                },
                accessMode);
}

File = function (entry, mode) {
    var _entry = entry,
        _mode = mode,
        _parent,
        _self;

    function _r2v(rpath) {
        var i, v, r, regExp;

        for (i = 0; i < _virtualRoots.length; i++) {
            v = _virtualRoots[i];
            r = _v2rmap[v];
            if (rpath.match("^" + r)) {
                regExp = new RegExp("^" + r);
                return rpath.replace(regExp, v);
            }
        }

        return ""; 
    }

    function _v2r(vpath) {
        var i, v, r, regExp;

        for (i = 0; i < _virtualRoots.length; i++) {
            v = _virtualRoots[i];
            r = _v2rmap[v];
            if (vpath.match("^" + v)) {
                regExp = new RegExp("^" + v);
                return vpath.replace(regExp, r);
            }
        }

        return ""; 
    }

    function _copyMoveInternal(onSuccess, onError, src, dst, overwrite, func) {
        var _srcName = String(src),
            _dstName = String(dst),
            _src = null,
            _dst = null,
            _error = false,
            _dstParent = null,
            _dstParts  = _dstName.split("/"),
            _dstParentName = _dstParts.splice(0, _dstParts.length - 1).join("/");

        if (!_entry.isDirectory) {
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.IO_ERR));
                }, 1);
            }
            return undefined;
        }

        _resolveSync(_srcName, 
                function (file) {
                    _src = file;
                },
                function (e) {
                    setTimeout(function () {
                        onError(e);
                    }, 1);
                },
                _mode);

        if (_src) {
            if (_src.parent.fullPath === _self.fullPath) {
                if (!_readOnly && _mode !== "r") {
                    _resolveSync(_dstParentName, 
                            function (file) {
                                _dstParent = file;
                            },
                            function (e) {
                                setTimeout(function () {
                                    onError(e);
                                }, 1);
                            },
                            _mode);

                    if (_dstParent === null) {
                        return undefined;
                    }

                    _resolveSync(_dstName, 
                            function (file) {
                                _dst = file;
                            },
                            function (e) {
                                if (e.code !== errorcode.NOT_FOUND_ERR) {
                                    setTimeout(function () {
                                        onError(e);
                                    }, 1);
                                    _error = true;
                                } 
                            },
                            _mode);

                    if (_error) {
                        return undefined;
                    }

                    if (_src.isFile) {
                        if (_dst === null) {
                            func(_v2r(_srcName), _v2r(_dstName),
                                    function () {
                                        setTimeout(function () {
                                            onSuccess();
                                        }, 1);
                                    },
                                    function () {});
                            return null;
                        } else {
                            if (_dst.isFile && Boolean(overwrite) && (_srcName !== _dstName)) {
                                func(_v2r(_srcName), _v2r(_dstName),
                                        function () {
                                            setTimeout(function () {
                                                onSuccess();
                                            }, 1);
                                        },
                                        function () {});
                                return null;
                            } else {
                                setTimeout(function () {
                                    onError(new DeviceApiError(errorcode.IO_ERR));
                                }, 1);
                            }
                        }
                    } else {
                        if (_dst === null) {
                            func(_v2r(_srcName), _v2r(_dstName),
                                function () {
                                    setTimeout(function () {
                                        onSuccess();
                                    }, 1);
                                },
                                function () {});
                            return null;
                        } else {
                            setTimeout(function () {
                                onError(new DeviceApiError(errorcode.IO_ERR));
                            }, 1);
                        } 
                    }
                } else {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                }
            } else {
                if (onError) {
                    setTimeout(function () {
                        onError(new DeviceApiError(errorcode.IO_ERR));
                    }, 1);
                }
            }
        }

        return undefined;
    }

    _self = {
        toURI: function () {
            return "file://" + _entry.fullPath;
        },
        listFiles: function (onSuccess, onError, filter) {
            var _filter = Object(filter),
                _filterName = _filter.name,
                _startModified = _filter.startModified,
                _endModified   = _filter.endModified;

            function _matchName(fileName) {
                var _matched = true, 
                    _name1 = String(_filterName).toLowerCase(),
                    _name2 = fileName.toLowerCase(),
                    _pattern;

                if (_filterName !== undefined && _filterName !== null) {
                    if (!_name1.match("\\\\%")) {
                        if (_name1.match("%")) {
                            _pattern = new RegExp("^" + _name1.replace(/%/g, ".*") + "$");
                            _matched = _name2.match(_pattern) ? true : false;
                        } else {
                            _matched = (_name1 === _name2);
                        }
                    } else {
                        // % is not allowed as a part of file name
                        _matched = false;
                    }
                }
                
                return _matched;
            }

            function _matchDate(date) {
                var _matched = true;

                if (_startModified !== undefined && _startModified !== null) {
                    _matched = (date.getTime() >= _startModified.getTime());
                }

                if (_matched && (_endModified !== undefined && _endModified !== null)) {
                    _matched = (date.getTime() <= _endModified.getTime());
                }

                return _matched;
            }

            function _matchFilter(entry) {
                return _matchName(entry.name) && _matchDate(entry.lastModifiedDate);
            } 

            function _listFiles() {
                var _files = [];

                if ((_startModified !== undefined && !wac2_utils.isValidDate(_startModified)) ||
                    (_endModified !== undefined && !wac2_utils.isValidDate(_endModified))) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                if (!_entry.isDirectory) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.IO_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                utils.forEach(_entry.children, function (child) {
                    if (_matchFilter(child)) {
                        _files.push(new File(child, _mode));
                    }
                });

                setTimeout(function () {
                    onSuccess(_files);
                }, 1);

                return null;
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "listFiles", _listFiles);
        },
        openStream: function (onSuccess, onError, mode, encoding) {
            function _openStream() {
                var  _openMode = String(mode),
                    _encoding = encoding ? String(encoding) : "UTF-8";

                if (_openMode !== "r" && _openMode !== "w" && _openMode !== "a") {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                
                if (((_readOnly || _mode === "r") && (_openMode === "w" || _openMode === "a")) ||
                    (_writeOnly && _openMode === "r")) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                 
                setTimeout(function () {
                    onSuccess(new FileStream(_entry, _openMode, _encoding));
                }, 1);

                return null;
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "openStream", _openStream);
        },
        readAsText: function (onSuccess, onError, encoding) {
            function _readAsText() {
                var _encoding = encoding ? String(encoding) : "UTF-8";
                if (_encoding !== "UTF-8" && _encoding !== "ISO-8859-1") {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                if (_writeOnly) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                if (_self.isFile) {
                    dbfs.read(_entry.fullPath, 
                            function (data) {
                                setTimeout(function () {
                                    onSuccess(data);
                                }, 1);
                            },
                            function () {});
                    return null;
                } else {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.IO_ERR));
                        }, 1);
                    }
                }

                return undefined;
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "readAsText", _readAsText);
        },
        copyTo: function (onSuccess, onError, src, dst, overwrite) {
            function _copyTo() {
                return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.cp);
            }
            
            return wac2_utils.validateTypeMismatch(onSuccess, onError, "copyTo", _copyTo);
        },
        moveTo: function (onSuccess, onError, src, dst, overwrite) {
            function _moveTo() {
                return _copyMoveInternal(onSuccess, onError, src, dst, overwrite, dbfs.mv);
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "moveTo", _moveTo);
        },
        createDirectory: function (dirPath) {
            var _path  = String(dirPath),
                _parts = _path.replace(/\/$/, "").split("/"),
                _dir   = null,
                _exist = null,
                _current = _entry.fullPath,
                _i;

            function onSuccess(entry) {
                _dir = entry;
            }

            for (_i = 0; _i < _parts.length; _i++) {
                if (!_isValidFileName(_parts[_i])) {
                    throw new DeviceApiError(errorcode.INVALID_VALUES_ERR);
                }
            }
      
            if (!entry.isDirectory) {
                throw new DeviceApiError(errorcode.IO_ERR);
            }

            _exist = _parts.reduce(function (obj, token) {
                return token === "" ? obj : (obj.children ? obj.children[token] || null : null);
            }, _entry);

            if (_exist) {
                throw new DeviceApiError(errorcode.IO_ERR);
            }

            if (_readOnly || _mode === "r") {
                throw new DeviceApiError(errorcode.SECURITY_ERR);
            }

            for (_i = 0; _i < _parts.length; _i++) {
                _current = _current + "/" + _parts[_i];
                dbfs.mkdir(_current, onSuccess);
            }
            
            return new File(_dir, _mode);
        },
        createFile: function (filePath) {
            var _name = String(filePath),
                _file = null;

            if (!_isValidFileName(_name)) {
                throw new DeviceApiError(errorcode.INVALID_VALUES_ERR);
            }

            if (!entry.isDirectory || (_entry.children && _entry.children[_name])) {
                throw new DeviceApiError(errorcode.IO_ERR);
            }

            if (_readOnly || _mode === "r") {
                throw new DeviceApiError(errorcode.SECURITY_ERR);
            }

            dbfs.touch(_entry.fullPath + "/" + _name,
                        function (entry) {
                            _file = new File(entry, _mode);
                        },
                        function () {});
            
            return _file;
        },
        resolve: function (filePath) {
            var _fullPath = _self.fullPath + "/" + String(filePath),
                _file = null;
 
            if (!_entry.isDirectory) {
                throw new DeviceApiError(errorcode.IO_ERR); 
            }

            _resolveSync(_fullPath,
                    function (file) {
                        _file = file;
                    },
                    function (e) {
                        throw (e);
                    },
                    _mode);

            return _file;
        }, 
        deleteDirectory: function (onSuccess, onError, directory, recursive) {
            function _deleteDirectory() {
                var _dir = null,
                    _dirName = String(directory);
                _resolveSync(_dirName, 
                        function (file) {
                            _dir = file;
                        },
                        function (e) {
                            setTimeout(function () {
                                onError(e);
                            }, 1);
                        },
                        _mode);

                if (_dir) {
                    if (_dir.isDirectory && 
                        _dir.parent.fullPath === _self.fullPath &&
                        (!recursive && _dir.length === 0)) {
                        if (!_readOnly && _mode !== "r") {
                            dbfs.rmdir(_v2r(_dirName),
                                    function () {
                                        setTimeout(function () {
                                            onSuccess();
                                        }, 1);
                                    },
                                    function () {});
                            return null;
                        } else {
                            if (onError) {
                                setTimeout(function () {
                                    onError(new DeviceApiError(errorcode.SECURITY_ERR));
                                }, 1);
                            }
                        }
                    } else {
                        if (onError) {
                            setTimeout(function () {
                                onError(new DeviceApiError(errorcode.IO_ERR));
                            }, 1);
                        }
                    }
                }

                return undefined; 
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "deleteDirectory", _deleteDirectory);
        },
        deleteFile: function (onSuccess, onError, fileName) {
            function _deleteFile() {
                var _file = null;
                _resolveSync(String(fileName),
                        function (file) {
                            _file = file;
                        },
                        function (e) {
                            if (onError) {
                                setTimeout(function () {
                                    onError(e);
                                }, 1);
                            }
                        },
                        _mode);

                if (_file) {
                    if (_file.isFile && _file.parent.fullPath === _self.fullPath) {
                        if (!_readOnly && _mode !== "r") {
                            dbfs.rm(_v2r(fileName),
                                    function () {
                                        setTimeout(function () {
                                            onSuccess();
                                        }, 1);
                                    },
                                    function () {});
                            return null;
                        } else {
                            if (onError) {
                                setTimeout(function () {
                                    onError(new DeviceApiError(errorcode.SECURITY_ERR));
                                }, 1);
                            }
                        }
                    } else {
                        if (onError) {
                            setTimeout(function () {
                                onError(new DeviceApiError(errorcode.IO_ERR));
                            }, 1);
                        }
                    }
                }

                return undefined; 
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "deleteFile", _deleteFile);
        }
    };

    _self.__defineGetter__("parent", function () {
        var _parts = _self.fullPath.split("/");

        if (_parent === undefined) {
            if (_parts.length === 1) {
                // virtual root's parent is null
                _parent = null;
            } else {
                _resolveSync(_parts.splice(0, _parts.length - 1).join("/"), 
                        function (file) {
                            _parent = file;
                        },
                        function () {},
                        _mode);
            }
            return _parent;
        } else { 
            return _parent;
        }
    });

    _self.__defineGetter__("readOnly", function () {
        return false;
    });

    _self.__defineGetter__("isFile", function () {
        return !_entry.isDirectory;
    });

    _self.__defineGetter__("isDirectory", function () {
        return _entry.isDirectory;
    });

    _self.__defineGetter__("created", function () {
        return undefined;
    });

    _self.__defineGetter__("modified", function () {
        if (_entry.isDirectory) {
            return undefined;
        } else {
            return _entry.lastModifiedDate;
        }
    });

    _self.__defineGetter__("path", function () {
        var _parts = _self.fullPath.split("/");

        if (_parts.length === 1) {
            // virtual root
            return _parts.join("");
        } else {
            return _parts.splice(0, _parts.length - 1).join("/") + "/";
        }
    });

    _self.__defineGetter__("name", function () {
        return _entry.name;
    });

    _self.__defineGetter__("fullPath", function () {
        return _r2v(_entry.fullPath);
    });

    _self.__defineGetter__("fileSize", function () {
        if (_entry.isDirectory) {
            return undefined;
        } else {
            return _entry.data.length;
        }
    });

    _self.__defineGetter__("length", function () {
        var _l = 0;
        if (_entry.isDirectory) {
            utils.forEach(_entry.children, function () {
                _l++;
            });
            return _l;
        } else {
            return undefined;
        }
    });

    return _self;
};

FileStream = function (entry, mode, encoding) {
    var _entry = entry,
        _data = entry.data,
        _mode = mode,
        _position = (_mode === "a" ? _data.length : 0),
        _self;

    _self = {
        close: function () {
            var _element;
            if (mode === "a" || mode === "w") {
                dbfs.write(_entry.fullPath, _data, function () {}, function () {});
            }
            for (_element in _self) {
                delete _self[_element];
            }
        },
        read: function (charCount) {
            var _count  = charCount | 0,
                _substr = _data.substring(_position, _position + _count);

            if (_position + _count > _data.length) {
                _position = _data.length;
            } else {
                _position += _count;
            }

            return _substr; 
        },
        readBytes: function (byteCount) {
            var _substr = _self.read(byteCount),
                _bytes = [],
                _i;

            for (_i = 0; _i < _substr.length; _i++) {
                _bytes.push(_substr.charCodeAt(_i));
            }

            return _bytes;
        },
        readBase64: function (byteCount) {
            var _substr = _self.read(byteCount);

            return window.atob(_substr);
        },
        write: function (stringData) {
            var _stringData = String(stringData),
                _substr = _data.substring(0, _position);

            _data = _substr.concat(_stringData);
            _position = _data.length;
        },
        writeBytes: function (byteData) {
            _self.write(String.fromCharCode.apply(String, byteData));
        },
        writeBase64: function (base64Data) {
            _self.write(window.btoa(String(base64Data)));
        }
    };

    _self.__defineGetter__("eof", function () {
        return _position === _data.length;
    });

    _self.__defineGetter__("position", function () {
        return _position;
    });

    _self.__defineSetter__("position", function (value) {
        var _value = value | 0;

        if (_value >= 0 && _value <= _data.length) {
            _position = _value;
        } else {
            throw new DeviceApiError(errorcode.INVALID_VALUES_ERR);
        }
    });

    _self.__defineGetter__("bytesAvailable", function () {
        return (_data.length - _position) || -1;
    });

    return _self;
};

module.exports = function () {
    return {
        maxPathLength: _maxPathLength,
        resolve: function (onSuccess, onError, srcLocation, accessMode) {
            function _resolve() {
                var _mode = accessMode ? String(accessMode) : _defaultMode;

                if (_mode === "r" || _mode === "rw") {
                    _resolveAsync(onSuccess, onError, String(srcLocation), _mode);
                    return null;
                } else {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                }
                return undefined;
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "resolve", _resolve);
        },
        handleSubFeatures: function (subFeatures) {
            if (wac2_utils.isEmptyObject(subFeatures) ||
                subFeatures["http://wacapps.net/api/filesystem"] ||
                (subFeatures["http://wacapps.net/api/filesystem.read"] &&
                subFeatures["http://wacapps.net/api/filesystem.write"])) {
                return;
            }
            if (subFeatures["http://wacapps.net/api/filesystem.read"]) {
                _readOnly = true;
                return;
            }
            if (subFeatures["http://wacapps.net/api/filesystem.write"]) {
                _writeOnly = true;
                return;
            }
            _console.warn("WAC-2.0-Filesystem: something wrong in handleSubFeatures");
        }
    }; 
};


});
define('ripple/platform/wac/2.0/geolocation', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 geo = require('ripple/geo'),
    Position = require('ripple/platform/w3c/1.0/Position'),
    PositionError = require('ripple/platform/w3c/1.0/PositionError'),
    _lastPosition = null,
    _watches = {},
    _defaultInterval = 100,
    _defaultDelay = 50,
    _self;

function _createPosition() {
    var position = new Position(),
        positionInfo = geo.getPositionInfo();

    position.coords.latitude = positionInfo.latitude;
    position.coords.longitude = positionInfo.longitude;
    position.coords.altitude = positionInfo.altitude;
    position.coords.altitudeAccuracy = positionInfo.altitudeAccuracy;
    position.coords.accuracy = positionInfo.accuracy;
    position.coords.heading = positionInfo.heading;
    position.coords.speed = positionInfo.speed;
    position.timestamp = positionInfo.timeStamp.getTime();

    return position;
}

function _isValid(onSuccess, onError, options, argLength) {
    if (argLength < 1 || argLength > 3)
        return false;

    if (typeof onSuccess !== "function")   // imply onSuccess == null
        return false;

    if (onError && (typeof onError !== "function"))
        return false;

    if ((options !== undefined) &&
        ((typeof options !== "object") ||
        (options.enableHighAccuracy !== undefined) && (typeof options.enableHighAccuracy !== "boolean") ||
        (options.timeout            !== undefined) && (typeof options.timeout            !== "number") ||
        (options.maximumAge         !== undefined) && (typeof options.maximumAge         !== "number")))
        return false;

    return true;
}

function _processOptions(options) {
    var validOptions = {
        enableHighAccuracy: false,
        timeout: 0,
        maximumAge: 0
    };

    if (options !== undefined &&
        options.maximumAge !== undefined &&
        options.maximumAge === Math.floor(options.maximumAge) &&
        options.maximumAge >= 0) {
        validOptions.maximumAge = options.maximumAge | 0;
    } else {
        validOptions.maximumAge = 0;
    }

    if (options !== undefined &&
        options.timeout !== undefined &&
        options.timeout === Math.floor(options.timeout)) {
        validOptions.timeout = (options.timeout >= 0) ? (options.timeout | 0) : 0;
    } else {
        validOptions.timeout = Infinity;
    }

    if (options !== undefined && options.enableHighAccuracy !== undefined) {
        validOptions.enableHighAccuracy = options.enableHighAccuracy;
    } else {
        validOptions.enableHighAccuracy = false;
    }

    validOptions.delay = geo.delay * 1000 || _defaultDelay;

    return validOptions;
}

function _errorOccur(code, onError) {
    if (!onError)
        return;

    var error = new PositionError();

    error.code = code;
    switch (code) {
    case PositionError.POSITION_UNAVAILABLE:
        error.message = "Position unavailable";
        break;

    case PositionError.TIMEOUT:
        error.message = "Position timed out";
        break;
    }

    onError(error);
}

function _execute(data) {
    return function () {
        if (_lastPosition !== null &&
            ((new Date()).getTime() - _lastPosition.timestamp <= data.maximumAge)) {
            window.setTimeout(function () {
                data.onSuccess(_lastPosition);
            }, 1);
        } else if (data.timeout === 0) {
            _errorOccur(PositionError.TIMEOUT, data.onError);
        } else {
            window.setTimeout(function () {
                if (data.delay <= data.timeout) {
                    _lastPosition = _createPosition();

                    if (_lastPosition !== null) {
                        data.onSuccess(_lastPosition);
                    } else {
                        _errorOccur(PositionError.POSITION_UNAVAILABLE, data.onError);
                    }
                } else {
                    _errorOccur(PositionError.TIMEOUT, data.onError);
                }
            }, Math.min(data.delay, data.timeout));
        }
    };
}

function _interval(k, n) { 
    return k * Math.floor((n + k - 1) / k) || k;
}

_self = {
    getCurrentPosition: function (onSuccess, onError, options) {
        if (!_isValid(onSuccess, onError, options, arguments.length))
            return;

        var validData = _processOptions(options);

        validData.onSuccess = onSuccess;
        validData.onError   = onError;

        _execute(validData)();
    },

    watchPosition: function (geolocationSuccess, geolocationError, geolocationOptions) {
        if (!_isValid(geolocationSuccess, geolocationError, geolocationOptions, arguments.length))
            return undefined;

        var validData = _processOptions(geolocationOptions),
            watchId = (new Date()).getTime() | 0,
            watchObj = {
                onSuccess:          geolocationSuccess,
                onError:            geolocationError,
                enableHighAccuracy: validData.enableHighAccuracy,
                timeout:            validData.timeout,
                maximumAge:         validData.maximumAge,
                delay:              validData.delay,
                interval:           _interval(validData.maximumAge || _defaultInterval,
                                        Math.min(validData.delay, validData.timeout)),
            };

        _watches[watchId] = watchObj;

        _watches[watchId].intervalId = window.setInterval(_execute(_watches[watchId]),
            _watches[watchId].interval);

        return watchId;
    },

    clearWatch: function (watchId) {
        if (arguments.length !== 1)
            return undefined;

        var id = watchId | 0;

        if (_watches[id]) {
            window.clearInterval(_watches[id].intervalId);
            delete _watches[id];

            return null;
        }

        return undefined;
    }
};

module.exports = _self;

});
define('ripple/platform/wac/2.0/messagefilter', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 _self;

_self = function (criteria) {
    var pattern,
        messageFilter;

    messageFilter = {
        match: function (target) {
            var result = false, index;

            if (Object.prototype.toString.call(criteria) === "[object Array]") {
                for (index in criteria) {
                    if (_self(criteria[index]).match(target))
                        return true;
                }
                return false;
            }

            switch (Object.prototype.toString.call(target)) {
            case "[object Number]":
                result = (criteria === target);
                break;

            case "[object String]":
                result = pattern.test(target);
                break;

            case "[object Array]":
                for (index in target) {
                    if (messageFilter.match(target[index]))
                        return true;
                }
                break;
            }

            return result;
        }
    };

    if (typeof criteria === "string")
        pattern = new RegExp(criteria.replace(/(^|[^\\])%+/g, "$1.*").replace(/\\%/g, "%").replace(/.*/, "^$&$"), "i");

    return messageFilter;
};

module.exports = _self;

});
define('ripple/platform/wac/2.0/messaging', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    event = require('ripple/event'),
    db = require('ripple/db'),
    exception = require('ripple/exception'),
    errorcode = require('ripple/platform/wac/2.0/errorcode'),
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
    DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
    PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
    PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
    TypeCoerce = require('ripple/platform/wac/2.0/typecoerce'),
    Filter = require('ripple/platform/wac/2.0/messagefilter'),
    FileSystem = require('ripple/platform/wac/2.0/filesystem'),
    MessageSendCallback,
    Message,
    MessageFilter,
    Recipients,
    _KEY = "wac2-pim-messaging",
    _PENDING_TIME = 600,
    _messages = {},
    _subscriber = {
        onSMS: {},
        onMMS: {},
        onEmail: {}
    },
    _sentStatus = {},
    _security = {
        "http://wacapps.net/api/messaging": [],
        "http://wacapps.net/api/messaging.send": ["sendMessage"],
        "http://wacapps.net/api/messaging.find": ["findMessages"],
        "http://wacapps.net/api/messaging.subscribe": ["onSMS", "onMMS", "onEmail"],
        "http://wacapps.net/api/messaging.write": ["update"],
        all: true
    },
    _fileSystem,
    _initialized = false,
    _self;

function _initialize() {
    _get();
    if (!_fileSystem) {
        _fileSystem = new FileSystem();
    }
    _initialized = true;
}

function _get() {
    _messages = db.retrieveObject(_KEY) || {1: [], 2: [], 3: [], 4: []};
    utils.forEach(_messages, function (folder) {
        utils.forEach(folder, function (messageItem) {
            if (messageItem.timestamp)
                messageItem.timestamp = new Date(messageItem.timestamp);
        });
    });
}

function _save() {
    db.saveObject(_KEY, _messages);
}

function _updateDB(message, duplicate) {
    _get();
    _messages[message.folder].push(message);
    if (duplicate)
        _messages[duplicate.folder].push(duplicate);
    _save();
}

function _processAttachments(message) {
    var attachmentsFileName = [],
        attachmentsContent = [];

    function _generateAttachmentFileName(attachment) {
        var lastDot = attachment.filename.lastIndexOf(".");
        return attachment.filename.substring(0, lastDot) + "_" + Math.uuid(8, 16) + attachment.filename.substring(lastDot);
    }

    function _onResolveSuccess(file) {
        var fileAttachment = file.createFile(attachmentsFileName[0]);

        fileAttachment.openStream(
            function (fs) {
                fs.write(attachmentsContent[0]);
                fs.close();
            }, null, "w");
    }

    function _onResolveError() {
    }

    if (message.attachments.length === 0)
        return;

    attachmentsFileName.push(_generateAttachmentFileName(message.attachments[0]));
    attachmentsContent.push(message.attachments[0].content);

    _fileSystem.resolve(_onResolveSuccess, _onResolveError, "attachments", "rw");

    message.attachments = utils.copy(attachmentsFileName);
}

function _errorOccurred(onError, code) {
    if (!onError)
        return;

    setTimeout(function () {
        onError(new DeviceApiError(code));
    }, 1);
}

function _pendingOperate(operate, scope) {
    var i, argumentVector = [];

    for (i = 0; i < arguments.length - 2; i++)
        argumentVector[i] = arguments[i + 2];

    return function () {
        var pendingObj, pendingOperation;

        pendingObj = new PendingObject();
        pendingObj.pendingID = window.setTimeout(function () {
            pendingObj.setCancelFlag(false);
            if (operate)
                operate.apply(scope, argumentVector);
        }, _PENDING_TIME);

        pendingOperation = new PendingOperation(pendingObj);

        return pendingOperation;
    };
}

function _onMessage(onMessage, messageHandler) {
    if (!messageHandler)
        exception.raise(exception.types.Argument,
            onMessage + " invalid messageHandler parameter",
            new DeviceApiError(errorcode.INVALID_VALUES_ERR));

    utils.validateArgumentType(messageHandler, "function", null,
        "messageHandler invalid function parameter",
        new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));

    if (!_security.all && !_security[onMessage])
        exception.raise(exception.types.Argument,
            onMessage + " access denied", new DeviceApiError(errorcode.SECURITY_ERR));

    var idSubscribe = (new Date()).getTime() | 0;
    _subscriber[onMessage][idSubscribe] = messageHandler;

    return idSubscribe;
}

function _validateRecipients(message) {
    var i;

    for (i = 0; i < message.to.length;) {
        message.to[i] = message.to[i].replace(/^\s*(\S*)\s*$/, '$1');
        if (message.to[i] === "")
            message.to.splice(i, 1);
        else
            i++;
    }
    for (i = 0; i < message.cc.length;) {
        message.cc[i] = message.cc[i].replace(/^\s*(\S*)\s*$/, '$1');
        if (message.cc[i] === "")
            message.cc.splice(i, 1);
        else
            i++;
    }
    for (i = 0; i < message.bcc.length;) {
        message.bcc[i] = message.bcc[i].replace(/^\s*(\S*)\s*$/, '$1');
        if (message.bcc[i] === "")
            message.bcc.splice(i, 1);
        else
            i++;
    }
    if (message.to.length + message.cc.length + message.bcc.length === 0)
        exception.raise(exception.types.Argument,
            "sendMessage invalid message.to parameter",
            new DeviceApiError(errorcode.INVALID_VALUES_ERR));
}

function _isValid(onSuccess, onError, message) {
    if (onSuccess &&
        typeof onSuccess !== "function" &&
        typeof onSuccess !== "object") {
        exception.raise(exception.types.Argument,
            "sendMessage invalid successCallback parameter",
            new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
    }

    if (onError) {
        utils.validateArgumentType(onError, "function", null,
            "sendMessage invalid errorCallback parameter",
            new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
    }

    if (!onSuccess) {
        _errorOccurred(onError, errorcode.INVALID_VALUES_ERR);
        return false;
    }

    if (message) {
        utils.validateArgumentType(message, "object", null,
            "sendMessage invalid message parameter",
            new DeviceApiError(errorcode.INVALID_VALUES_ERR));
    } else {
        _errorOccurred(onError, errorcode.INVALID_VALUES_ERR);
        return false;
    }

    if (message.type !== _self().TYPE_SMS &&
        message.type !== _self().TYPE_MMS &&
        message.type !== _self().TYPE_EMAIL)
        exception.raise(exception.types.Argument,
            "sendMessage invalid message.type parameter",
            new DeviceApiError(errorcode.INVALID_VALUES_ERR));

    if (!_security.all && !_security.sendMessage) {
        _errorOccurred(onError, errorcode.SECURITY_ERR);
        return false;
    }

    TypeCoerce(Message(0)).cast(message);
    _validateRecipients(message);

    return true;
}

function _getEachSentStatus(onMessageSentSuccess, onMessageSentError, message,
                            sucRecipients, failRecipients, recType) {
    utils.forEach(message[recType], function (recipient) {
        if (_sentStatus[recipient]) {
            sucRecipients[recType].push(recipient);
            if (onMessageSentSuccess) {
                onMessageSentSuccess(recipient);
            }
        } else {
            failRecipients[recType].push(recipient);
            if (onMessageSentError) {
                onMessageSentError(new DeviceApiError(errorcode.UNKNOWN_ERR), recipient);
            }
        }
    });
}

function _getSentStatus(onSuccess, onError, message, onMessageSentSuccess, onMessageSentError) {
    var allSentSuccess,
        sucRecipients = new Recipients(),
        failRecipients = new Recipients(),
        duplicate;

    _getEachSentStatus(onMessageSentSuccess, onMessageSentError,
        message, sucRecipients, failRecipients, "to");

    if (message.type === _self().TYPE_EMAIL) {
        _getEachSentStatus(onMessageSentSuccess, onMessageSentError,
            message, sucRecipients, failRecipients, "cc");
        _getEachSentStatus(onMessageSentSuccess, onMessageSentError,
            message, sucRecipients, failRecipients, "bcc");
    }

    allSentSuccess = (failRecipients.total() === 0);

    if (allSentSuccess) {
        message.folder = _self().FOLDER_SENTBOX;
    } else if (sucRecipients.total() === 0) {
        message.folder = _self().FOLDER_DRAFTS;
    } else {
        duplicate = utils.copy(message);

        message.to = sucRecipients.to;
        message.cc = sucRecipients.cc;
        message.bcc = sucRecipients.bcc;
        message.folder = _self().FOLDER_SENTBOX;

        duplicate.to = failRecipients.to;
        duplicate.cc = failRecipients.cc;
        duplicate.bcc = failRecipients.bcc;
        duplicate.folder = _self().FOLDER_DRAFTS;
    }

    _updateDB(message, duplicate);

    if (allSentSuccess) {
        onSuccess();
    } else if (onError) {
        onError(new DeviceApiError(errorcode.UNKNOWN_ERR));
    }
}

_self = function () {
    var messaging = {
        createMessage: function (type) {
            type = type | 0;

            if (type < _self().TYPE_SMS || type > _self().TYPE_EMAIL)
                exception.raise(exception.types.Argument,
                "type invalid value", new DeviceApiError(errorcode.INVALID_VALUES_ERR));

            var msg = new Message(type);

            return msg;
        },

        sendMessage: function (successCallback, errorCallback, message) {
            var ret;

            function _sendMessage() {
                event.trigger("OutsideMessageReceived", [message]);

                return _pendingOperate(_getSentStatus, undefined,
                    successCallback, errorCallback, message)();
            }

            function _sendEachMessage() {
                utils.forEach(successCallback, function (value, key) {
                    utils.validateArgumentType(value, "function", null,
                        "sendMessage invalid successCallback." + key + " parameter",
                        new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
                });

                event.trigger("OutsideMessageReceived", [message]);

                return _pendingOperate(_getSentStatus, undefined,
                    successCallback.onsuccess, errorCallback, message,
                    successCallback.onmessagesendsuccess, successCallback.onmessagesenderror)();
            }

            if (!_isValid(successCallback, errorCallback, message))
                return null;

            switch (typeof successCallback) {
            case "function":
                ret = _sendMessage();
                break;

            case "object":
                ret = _sendEachMessage();
                break;
            }

            return ret;
        },

        findMessages: function (successCallback, errorCallback, filter) {
            function _findMessages() {
                var message, result = [];

                if (!_security.all && !_security.findMessages)
                    return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);

                utils.forEach(_messages, function (folder) {
                    utils.forEach(folder, function (messageItem) {
                        if ((filter                 === undefined || filter === null) ||
                            (filter.id              === undefined || Filter(filter.id).match(messageItem.id)) &&
                            (filter.type            === undefined || Filter(filter.type).match(messageItem.type)) &&
                            (filter.folder          === undefined || Filter(filter.folder).match(messageItem.folder)) &&
                            (filter.startTimestamp  === undefined || (messageItem.timestamp >= filter.startTimestamp)) &&
                            (filter.endTimestamp    === undefined || (messageItem.timestamp <= filter.endTimestamp)) &&
                            (filter.from            === undefined || Filter(filter.from).match(messageItem.from)) &&
                            (filter.to              === undefined || Filter(filter.to).match(messageItem.to)) &&
                            (filter.cc              === undefined || Filter(filter.cc).match(messageItem.cc)) &&
                            (filter.bcc             === undefined || Filter(filter.bcc).match(messageItem.bcc)) &&
                            (filter.body            === undefined || Filter(filter.body).match(messageItem.body)) &&
                            (filter.isRead          === undefined || (messageItem.isRead === filter.isRead)) &&
                            (filter.messagePriority === undefined || (messageItem.priority === filter.messagePriority)) &&
                            (filter.subject         === undefined || Filter(filter.subject).match(messageItem.subject))) {
                            message = utils.copy(messageItem);
                            result.push(message);
                        }
                    });
                });
                successCallback(result);
            }
            return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "findMessages", _pendingOperate(_findMessages));
        },

        onSMS: function (messageHandler) {
            return _onMessage("onSMS", messageHandler);
        },

        onMMS: function (messageHandler) {
            return _onMessage("onMMS", messageHandler);
        },

        onEmail: function (messageHandler) {
            return _onMessage("onEmail", messageHandler);
        },

        unsubscribe: function (subscriptionHandler) {
            var onMessage, idSubscribe;

            utils.validateArgumentType(subscriptionHandler, "integer",
                null, "subscriptionHandler invalid function parameter",
                new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));

            for (onMessage in _subscriber) {
                for (idSubscribe in _subscriber[onMessage]) {
                    if (idSubscribe == subscriptionHandler) {
                        delete _subscriber[onMessage][idSubscribe];
                        return;
                    }
                }
            }
        },

        handleSubFeatures: function (subFeatures) {
            for (var subFeature in subFeatures) {
                if (_security[subFeature].length === 0) {
                    _security.all = true;
                    return;
                }
                _security.all = false;
                utils.forEach(_security[subFeature], function (method) {
                    _security[method] = true;
                });
            }
        }
    };

    messaging.__defineGetter__("TYPE_SMS", function () {
        return 1;
    });

    messaging.__defineGetter__("TYPE_MMS", function () {
        return 2;
    });

    messaging.__defineGetter__("TYPE_EMAIL", function () {
        return 3;
    });

    messaging.__defineGetter__("FOLDER_INBOX", function () {
        return 1;
    });

    messaging.__defineGetter__("FOLDER_OUTBOX", function () {
        return 2;
    });

    messaging.__defineGetter__("FOLDER_DRAFTS", function () {
        return 3;
    });

    messaging.__defineGetter__("FOLDER_SENTBOX", function () {
        return 4;
    });

    if (!_initialized)
        _initialize();

    return messaging;
};

MessageSendCallback = {
    onsuccess: function () {},
    onmessagesendsuccess: function (recipient) {},
    onmessagesenderror: function (error, recipient) {}
};

Message = function (type) {
    this.id = Math.uuid(null, 16);
    this.type = type;
    this.folder = 0;
    this.timestamp = new Date();
    this.from = "";
    this.to = [""];
    this.cc = [""];
    this.bcc = [""];
    this.body = "";
    this.isRead = false;
    this.priority = false;
    this.subject = "";
    this.attachments = [""];

    this.update = function (successCallback, errorCallback) {
        function _update() {
            var isFound = false;

            if (!_security.all && !_security.update)
                return _errorOccurred(errorCallback, errorcode.SECURITY_ERR);

            TypeCoerce(new Message(0)).cast(this);
            _get();
            utils.forEach(_messages[this.folder], function (messageItem) {
                if (messageItem.id === this.id) {
                    !this.isRead || (messageItem.isRead = this.isRead);
                    if (this.folder === _self().FOLDER_DRAFTS) {
                        !this.type        || (messageItem.type        = this.type);
                        !this.to          || (messageItem.to          = utils.copy(this.to));
                        !this.cc          || (messageItem.cc          = utils.copy(this.cc));
                        !this.bcc         || (messageItem.bcc         = utils.copy(this.bcc));
                        !this.body        || (messageItem.body        = this.body);
                        !this.priority    || (messageItem.priority    = this.priority);
                        !this.subject     || (messageItem.subject     = this.subject);
                        !this.attachments || (messageItem.attachments = utils.copy(this.attachments));
                    }
                    isFound = true;
                }
            });

            if (isFound) {
                _save();
                successCallback();
            } else {
                _errorOccurred(errorCallback, errorcode.NOT_FOUND_ERR);
            }
        }
        return wac2_utils.validateTypeMismatch(successCallback, errorCallback, "update", _pendingOperate(_update, this));
    };
};

MessageFilter = {
    id: "",
    type: [0],
    folder: [0],
    startTimestamp: new Date(),
    endTimestamp: new Date(),
    from: "",
    to: [""],
    cc: [""],
    bcc: [""],
    body: "",
    isRead: false,
    messagePriority: false,
    subject: ""
};

Recipients = function () {
    this.to  = [];
    this.cc  = [];
    this.bcc = [];

    this.total = function () {
        return (this.to.length + this.cc.length + this.bcc.length);
    };
};

event.on("MessageReceived", function (message) {
    var onMessage;

    switch (message.type) {
    case "sms":
        message.type = _self().TYPE_SMS;
        onMessage = "onSMS";
        break;

    case "mms":
        message.type = _self().TYPE_MMS;
        onMessage = "onMMS";
        break;

    case "email":
        message.type = _self().TYPE_EMAIL;
        onMessage = "onEmail";
        break;

    default:
        break;
    }

    message.folder = _self().FOLDER_INBOX;
    _processAttachments(message);
    _updateDB(message);
    utils.forEach(_subscriber[onMessage], function (subscriberCallback) {
        subscriberCallback(message);
    });
});

event.on("MessageSent", function (sentStatus) {
    _sentStatus = sentStatus;
});

module.exports = _self;

});
define('ripple/platform/wac/2.0/orientation', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    event = require('ripple/event'),
    Rotation = function (alpha, beta, gamma) {
        return {
            alpha: alpha || 0,
            beta:  beta  || 0,
            gamma: gamma || 0
        };
    },
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
    _rotationInfo = new Rotation(),
    _defaultInterval = 100,
    _watches = {},
    _self;

module.exports = _self = {
    getCurrentOrientation: function (onSuccess, onError) {
        function _getCurrentOrientation() {
            setTimeout(function () {
                onSuccess(utils.copy(_rotationInfo));
            }, 1);
            return null;
        }

        return wac2_utils.validateTypeMismatch(onSuccess, onError, "getCurrentOrientation", _getCurrentOrientation);
    },

    watchOrientation: function (orientationSuccess, orientationError, options) {
        function _watchOrientation() {
            var watchId = (new Date()).getTime() | 0,
                watchObj = {},
                opt = Object(options),
                minNotificationInterval = opt.minNotificationInterval | 0,
                orientationInterval = _defaultInterval;

            if (minNotificationInterval > 0) {
                orientationInterval = minNotificationInterval;
            }

            watchObj = {
                onSuccess: orientationSuccess,
                onError: orientationError,
                interval: orientationInterval
            };

            _watches[watchId] = watchObj;

            _watches[watchId].intervalId = setInterval(function () {
                _self.getCurrentOrientation(_watches[watchId].onSuccess, _watches[watchId].onError);
            }, _watches[watchId].interval);

            return watchId;
        }

        return wac2_utils.validateTypeMismatch(orientationSuccess, orientationError, "watchOrientation", _watchOrientation);
    },

    clearWatch: function (watchId) {

        var id = watchId | 0;
        if (_watches[id]) {
            clearInterval(_watches[id].intervalId);
            delete(_watches[id]);
            return null;
        }

        return undefined;
    }
};

event.on("AccelerometerInfoChangedEvent", function (orientationInfo) {
    _rotationInfo.alpha = orientationInfo.orientation.alpha;
    _rotationInfo.beta  = orientationInfo.orientation.beta;
    _rotationInfo.gamma = orientationInfo.orientation.gamma;
});


});
define('ripple/platform/wac/2.0/pendingObject', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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.
 */

module.exports = function (pendingObj) {
    var cancelFlag = true;
    this.setCancelFlag = function (flag) {
        cancelFlag = flag;
    };
    this.getCancelFlag = function () {
        return cancelFlag;
    };
    this.userCancel = null;
    this.pendingID = null;
};

});
define('ripple/platform/wac/2.0/pendingoperation', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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.
 */

module.exports = function (pendingObj) {
    var pending = true;
    this.cancel = function () {
        if (pending === true) {
            if (typeof (pendingObj.getCancelFlag) === "function" && pendingObj.getCancelFlag() === false) {
                pending = false;
                // this clearTimeout is for the case when a 3rd party is invoked to do the task, and it's finished sooner than the intended timeout. therefore, the 3rd party set CancelFlag false, and this cancel is called before timeout
                clearTimeout(pendingObj.pendingID);
                return false;
            }
            if (typeof (pendingObj.userCancel) === "function") {
                pendingObj.userCancel();
            }
            clearTimeout(pendingObj.pendingID);
            pending = false;
            return true;
        } else {
            return false;
        }
    };
};


});
define('ripple/platform/wac/2.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 platform = require('ripple/platform'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    constants = require('ripple/constants');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (configValidationObject) {
        var valid = true;
        // no xmlns:JIL in wac 2.0 spec
        valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;

        return valid;
    },
    extractInfo: function (configValidationObject) {
        if (!configValidationObject) {
            return null;
        }

        var widgetInfo = {},
            configFeatures,
            configPreferences,
            preferenceName,
            platform;

        widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
        widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
        widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;

        widgetInfo.features = {};

        configFeatures = configValidationObject.widget.children.feature.validationResult;
        utils.forEach(configFeatures, function (f) {
            if (f.valid === true) {
                var feature = {id: f.attributes.name.value,
                         required: f.attributes.required.valid};
                widgetInfo.features[feature.id] = feature;
            }
        });

        widgetInfo.preferences = {};

        configPreferences = configValidationObject.widget.children.preference.validationResult;

        platform = require('ripple/platform');
        utils.forEach(configPreferences, function (preference) {
            preferenceName = preference.attributes.name.value;
            if (preferenceName) {
                widgetInfo.preferences[preferenceName] = {
                    "key": preferenceName,
                    "value": preference.attributes.value.value || "",
                    "readonly": preference.attributes.readonly.value === "true"
                };

                db.save(preferenceName,
                        widgetInfo.preferences[preferenceName].value,
                        platform.getPersistencePrefix(widgetInfo.id));
            }
        });

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in configuration document and may have following child elments: name,description,icon,author,license,content,feature and preference. \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                },
                dir: {
                    attributeName: "dir",
                    required: false,
                    type: "list",
                    listValues: ["ltr", "rtl", "lro", "rlo"]
                },
                id: {
                    attributeName: "id",
                    required: false,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    required: false,
                    type: "string"
                },
                height: {
                    attributeName: "height",
                    required: false,
                    type: "integer"
                },
                width: {
                    attributeName: "width",
                    required: false,
                    type: "integer"
                },
                viewmodes: {
                    attributeName: "viewmodes",
                    required: false,
                    type: "list",
                    listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
                },
                defaultlocale: {
                    attributeName: "defaultlocale",
                    required: false,
                    type: "iso-language"
                },
            },
            children: {
                name: {
                    nodeName: "name",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        "short": {
                            attributeName: "short",
                            required: false,
                            type: "string"
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.URL
                        },
                        email: {
                            attributeName: "email",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.EMAIL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        width: {
                            attributeName: "width",
                            required: false,
                            type: "integer"
                        },
                        height: {
                            attributeName: "height",
                            required: false,
                            type: "integer"
                        }
                    }
                },
                content: {
                    nodeName: "content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        encoding: {
                            attributeName: "encoding",
                            required: false,
                            type: "string"
                        },
                        type: {
                            attributeName: "type",
                            required: false,
                            type: "string"
                        }
                    }
                },
                feature: {
                    nodeName: "feature",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "list",
                            listValues: ["http://www.w3.org/TR/geolocation-API/",
                                            "http://wacapps.net/api/deviceapis", "http://wacapps.net/api/accelerometer",
                                            "http://wacapps.net/api/orientation", "http://wacapps.net/api/camera",
                                            "http://wacapps.net/api/camera.show", "http://wacapps.net/api/camera.capture",
                                            "http://wacapps.net/api/devicestatus", "http://wacapps.net/api/devicestatus.deviceinfo",
                                            "http://wacapps.net/api/devicestatus.networkinfo", "http://wacapps.net/api/filesystem",
                                            "http://wacapps.net/api/filesystem.read", "http://wacapps.net/api/filesystem.write",
                                            "http://wacapps.net/api/messaging", "http://wacapps.net/api/messaging.send", 
                                            "http://wacapps.net/api/messaging.find", "http://wacapps.net/api/messaging.subscribe",
                                            "http://wacapps.net/api/messaging.write", "http://wacapps.net/api/pim.contact",
                                            "http://wacapps.net/api/pim.contact.read", "http://wacapps.net/api/pim.contact.write",
                                            "http://wacapps.net/api/pim.calendar", "http://wacapps.net/api/pim.calendar.read",
                                            "http://wacapps.net/api/pim.calendar.write", "http://wacapps.net/api/pim.task", 
                                            "http://wacapps.net/api/pim.task.read", "http://wacapps.net/api/pim.task.write",
                                            "http://wacapps.net/api/deviceinteraction"]
                        },
                        required: {
                            attributeName: "required",
                            type: "boolean",
                            required: false
                        }
                    },
                    children: {
                        param: {
                            nodeName: "param",
                            required: false,
                            occurrence: 0,
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                },
                                name: {
                                    attributeName: "name",
                                    required: true,
                                    type: "string",
                                },
                                value: {
                                    attributeName: "value",
                                    required: true,
                                    type: "string",
                                }
                            }
                        }
                    }
                },
                preference: {
                    nodeName: "preference",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "string"
                        },
                        value: {
                            type: "string",
                            required: false,
                            attributeName: "value"
                        },
                        readonly: {
                            attributeName: "readonly",
                            type: "boolean",
                            required: false
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/wac/2.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 event = require('ripple/event');

function deviceStatusEventTrigger(setting) {
    event.trigger("DeviceStatusChanged", [setting]);
}

module.exports = {
    "Config": {
        "vibratingMode": {
            "name": "Vibrator",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("VibratingModeChanged", [setting]);
            }
        },
        "soundVolume": {
            "name": "Sound Volume",
            "control": {
                "type": "range",
                "value": 100,
                "min": 0,
                "max": 100
            },
            "callback": function (setting) {
                event.trigger("VolumeChanged", [setting]);
            }
        },
        "backlight": {
            "name": "Backlight",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("BacklightChanged", [setting]);
            }
        }
    },
    "Battery": {
        "batteryLevel": {
            "name": "Battery Remaining %",
            "control": {
                "type": "select",
                "value": 100
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 100; i += 10) {
                    optionList[i] = i;
                }

                return optionList;
            }()),
            "event": "BatteryLevelChanged",
            "callback": function (setting) {
                event.trigger("BatteryLevelChanged", [setting]);
            }
        },

        "batteryBeingCharged": {
            "name": "Battery Is Charging",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "event": "BatteryBeingChargedChanged",
            "callback": function (setting) {
                event.trigger("BatteryBeingChargedChanged", [setting]);
            }
        },
    },
    "CellularHardware": {
        "status": {
            "name": "status",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "event": "CellularHardwareStatusChanged",
            "callback": function (setting) {
                event.trigger("CellularHardwareStatusChanged", [setting]);
            }
        }
    },
    "CellularNetwork": {
        "isInRoaming": {
            "name": "Roaming",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "event": "CellularNetworkIsInRoamingChanged",
            "callback": function (setting) {
                event.trigger("CellularNetworkIsInRoamingChanged", [setting]);
            }
        }, 
        "mcc": {
            "name": "mcc",
            "control": {
                "type": "text",
                "value": "460",
                "readonly": "readonly"
            }
        }, 
        "mnc": {
            "name": "mnc",
            "control": {
                "type": "text",
                "value": "0",
                "readonly": "readonly"
            }
        }, 
        "signalStrength": {
            "name": "Signal Strength",
            "control": {
                "type": "select",
                "value": 100
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 100; i += 10) {
                    optionList[i] = i;
                }

                return optionList;
            }()),
            "event": "CellularNetworkSignalStrengthChanged",
            "callback": function (setting) {
                event.trigger("CellularNetworkSignalStrengthChanged", [setting]);
            }
        }, 
        "operatorName": {
            "name": "Operator Name",
            "control": {
                "type": "text",
                "value": "CMCC",
                "readonly": "readonly"
            }
        }
    },
    "Device": {
        "imei": {
            "name": "IMEI",
            "control": {
                "type": "text",
                "value": "860398001689659",
                "readonly": "readonly"
            }
        }, 
        "model": {
            "name": "Model",
            "control": {
                "type": "text",
                "value": "",
                "readonly": "readonly"
            }
        }, 
        "version": {
            "name": "Version",
            "control": {
                "type": "text",
                "value": "",
                "readonly": "readonly"
            }
        }, 
        "vendor": {
            "name": "Vendor.",
            "control": {
                "type": "text",
                "value": "",
                "readonly": "readonly"
            }
        }
    },
    "Display": {
        "resolutionHeight": {
            "name": "Resolution Height",
            "control": {
                "type": "number",
                "value": 0,
                "readonly": "readonly"
            }
        }, 
        "resolutionWidth": {
            "name": "Resolution Width",
            "control": {
                "type": "number",
                "value": 0,
                "readonly": "readonly"
            }
        }, 
        "pixelAspectRatio": {
            "name": "Pixel Aspectratio",
            "control": {
                "type": "number",
                "value": 0,
                "readonly": "readonly"
            }
        }, 
        "dpiY": {
            "name": "DPI-Y",
            "control": {
                "type": "number",
                "value": 0,
                "readonly": "readonly"
            }
        },         
        "dpiX": {
            "name": "DPI-X",
            "control": {
                "type": "number",
                "value": 0,
                "readonly": "readonly"
            }
        }, 
        "colorDepth": {
            "name": "Color Depth",
            "control": {
                "type": "number",
                "value": 32,
                "readonly": "readonly"
            }
        }
    },
    "MemoryUnit": {
        "removable": {
            "name": "Removable",
            "control": {
                "type": "checkbox",
                "value": true,
                "readonly": "readonly"
            }
        },
        "size": {
            "name": "Total Memory",
            "control": {
                "type": "number",
                "value": 262144,
                "readonly": "readonly"
            }
        },        
        "availableSize": {
            "name": "Available Size",
            "control": {
                "type": "range",
                "value": 16384,
                "min": 0,
                "max": 262144
            },
            "event": "MemoryUnitAvailableSizeChanged",
            "callback": function (setting) {
                event.trigger("MemoryUnitAvailableSizeChanged", [setting]);
            }
        }
    },
    "OperatingSystem": {
        "language": {
            "name": "Language",
            "control": {
                "type": "text",
                "value": "English",
                "readonly": "readonly"
            }
        }, 
        "version": {
            "name": "Version",
            "control": {
                "type": "text",
                "value": "",
                "readonly": "readonly"
            }
        }, 
        "name": {
            "name": "Name",
            "control": {
                "type": "text",
                "value": "",
                "readonly": "readonly"
            }
        }, 
        "vendor": {
            "name": "Vendor",
            "control": {
                "type": "text",
                "value": "",
                "readonly": "readonly"
            }
        }
    },
    "WebRuntime": {
        "wacVersion": {
            "name": "WAC Version",
            "control": {
                "type": "text",
                "value": "2.0",
                "readonly": "readonly"
            }
        }, 
        "supportedImageFormats": {
            "name": "Image Formats",
            "control": {
                "type": "text",
                "value": "gif87, gif89, png, jpeg",
                "readonly": "readonly"
            },
            "event": "WebRuntimeSupportedImageFormatsChanged",
            "callback": function (setting) {
                event.trigger("WebRuntimeSupportedImageFormatsChanged", [setting]);
            }
        }, 
        "version": {
            "name": "Web Runtime Version",
            "control": {
                "type": "text",
                "value": "1.0",
                "readonly": "readonly"
            }
        }, 
        "name": {
            "name": "Web Runtime Name",
            "control": {
                "type": "text",
                "value": "Tizen Web Simulator",
                "readonly": "readonly"
            }
        }, 
        "vendor": {
            "name": "Vendor Name",
            "control": {
                "type": "text",
                "value": "Tizen SDK team",
                "readonly": "readonly"
            }
        }
    },
    "WiFiHardware": {
        "status": {
            "name": "Status",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "event": "WiFiHardwareStatusChanged",
            "callback": function (setting) {
                event.trigger("WiFiHardwareStatusChanged", [setting]);
            }
        }
    },
    "WiFiNetwork": {
        "ssid": {
            "name": "SSID",
            "control": {
                "type": "text",
                "value": "OfficeWLAN"
            },
            "event": "WiFiHardwareSsidChanged",
            "callback": function (setting) {
                event.trigger("WiFiHardwareSsidChanged", [setting]);
            }
        }, 
        "signalStrength": {
            "name": "Signal Strength",
            "control": {
                "type": "select",
                "value": 10
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 10; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }()),
            "event": "WiFiHardwareSignalStrengthChanged",
            "callback": function (setting) {
                event.trigger("WiFiHardwareSignalStrengthChanged", [setting]);
            }
        }, 
        "networkStatus": {
            "name": "Network Status",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "event": "WiFiHardwareNetworkStatusChanged",
            "callback": function (setting) {
                event.trigger("WiFiHardwareNetworkStatusChanged", [setting]);
            }
        }
    }
};


});
define('ripple/platform/wac/2.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "accelerometer",
        "messaging",
        "geoView",
        "widgetConfig",
        "deviceSettings"
    ]
};

});
define('ripple/platform/wac/2.0/spec', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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.
 */

module.exports = {

    id: "wac",
    version: "2.0",
    name: "WAC",

    persistencePrefix: "wac2-",

    config: require('ripple/platform/wac/2.0/spec/config'),
    ui: require('ripple/platform/wac/2.0/spec/ui'),
    device: require('ripple/platform/wac/2.0/spec/device'),

    objects: {
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        navigator: {
            path: "w3c/1.0/navigator",
            children: {
                geolocation: {
                    path: "wac/2.0/geolocation",
                    feature: "http://www.w3.org/TR/geolocation-API/"
                }
            }
        },
        deviceapis: {
            path: "wac/2.0/deviceapis",
            feature: "http://wacapps.net/api/deviceapis",
            /*
             * Before we inject those cloned objects into the simulated application
             * namespace, we will handle the feature requests from config.xml.
             * Especially for:
             * - camera.show, camera.capture
             * - devicestatus.deviceinfo, devicestatus.networkinfo
             * - filesystem.read, filesystem.write
             * - messaging.send, messaging.find, messaging.subscribe, messaging.write
             * - pim
             *  - contact.read, contact.write
             *  - calendar.read, calendar.write
             *  - task.read, task.write
             */
            children: {
                accelerometer: {
                    path: "wac/2.0/accelerometer",
                    feature: "http://wacapps.net/api/accelerometer"
                },
                orientation: {
                    path: "wac/2.0/orientation",
                    feature: "http://wacapps.net/api/orientation"
                },
                camera: {
                    path: "wac/2.0/camera",
                    feature: "http://wacapps.net/api/camera|http://wacapps.net/api/camera.show|http://wacapps.net/api/camera.capture",
                    handleSubfeatures: true
                },
                devicestatus: {
                    path: "wac/2.0/devicestatus",
                    feature: "http://wacapps.net/api/devicestatus|http://wacapps.net/api/devicestatus.deviceinfo|http://wacapps.net/api/devicestatus.networkinfo",
                    handleSubfeatures: true
                },
                filesystem: {
                    path: "wac/2.0/filesystem",
                    feature: "http://wacapps.net/api/filesystem|http://wacapps.net/api/filesystem.read|http://wacapps.net/api/filesystem.write",
                    handleSubfeatures: true
                },
                messaging: {
                    path: "wac/2.0/messaging",
                    feature: "http://wacapps.net/api/messaging|http://wacapps.net/api/messaging.send|http://wacapps.net/api/messaging.find|http://wacapps.net/api/messaging.subscribe|http://wacapps.net/api/messaging.write",
                    handleSubfeatures: true
                },
                pim: {
                    children: {
                        contact: {
                            path: "wac/2.0/contact",
                            feature: "http://wacapps.net/api/pim.contact|http://wacapps.net/api/pim.contact.read|http://wacapps.net/api/pim.contact.write",
                            handleSubfeatures: true
                        },
                        calendar: {
                            path: "wac/2.0/calendar",
                            feature: "http://wacapps.net/api/pim.calendar.write|http://wacapps.net/api/pim.calendar.read|http://wacapps.net/api/pim.calendar",
                            handleSubfeatures: true
                        },
                        task: {
                            path: "wac/2.0/task",
                            feature: "http://wacapps.net/api/pim.task|http://wacapps.net/api/pim.task.read|http://wacapps.net/api/pim.task.write",
                            handleSubfeatures: true
                        }
                    }
                },
                deviceinteraction: {
                    path: "wac/2.0/deviceinteraction",
                    feature: "http://wacapps.net/api/deviceinteraction"
                }
            }
        }
    }
};


});
define('ripple/platform/wac/2.0/task', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    _console = require('ripple/console'),
    exception = require('ripple/exception'),
    errorcode = require('ripple/platform/wac/2.0/errorcode'),
    wac2_utils = require('ripple/platform/wac/2.0/wac2_utils'),
    PendingObject = require('ripple/platform/wac/2.0/pendingObject'),
    DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror'),
    PendingOperation = require('ripple/platform/wac/2.0/pendingoperation'),
    Task, TaskList, _get,
    _ID_WITHOUT = 0, _ID_GEN_NEW = 1, _ID_FROM_PROP = 2,
    _SIM_TASK_LIST = 0, _DEVICE_TASK_LIST = 1,
    _HIGH_PRIORITY = 0, _MEDIUM_PRIORITY = 1, _LOW_PRIORITY = 2,
    _STATUS_COMPLETED = 0, _STATUS_NEEDS_ACTION = 1, _STATUS_IN_PROCESS = 2, _STATUS_CANCELLED = 3,
    _TASK_OBJECTS = "wac2.0-pim-task-objects",
    _addTaskAllowed = true, _deleteTaskAllowed = true,
    _updateTaskAllowed = true, _findTasksAllowed = true;


module.exports = function () {
    var _taskListArray = [],
        _PENDING_TIME = 10;

    function _pendingOperate(operate) {
        var pendingObj, pendingOperation, i, argumentVector = [];

        for (i = 0; i < arguments.length - 1; i++)
            argumentVector[i] = arguments[i + 1];

        pendingObj = new PendingObject();

        pendingObj.pendingID = window.setTimeout(function () {
            pendingObj.setCancelFlag(false);
            operate.apply(this, argumentVector);
        }, _PENDING_TIME);

        pendingOperation = new PendingOperation(pendingObj);

        return pendingOperation;
    }

    /* taskProperties attribute check & paste */
    function _checkAndPasteProperties(p, dst) {

        if (p.summary !== null && p.summary !== undefined)
            dst.summary = String(p.summary);

        if (p.description !== null && p.description !== undefined)
            dst.description = String(p.description);

        if (p.status !== null && p.status !== undefined) {
            if (p.status === _STATUS_COMPLETED ||
                p.status === _STATUS_NEEDS_ACTION ||
                p.status === _STATUS_IN_PROCESS ||
                p.status === _STATUS_CANCELLED) {
                dst.status = p.status;
            } else
                return false;
        }

        if (p.priority !== null && p.priority !== undefined) {
            if (p.priority === _HIGH_PRIORITY ||
                p.priority === _MEDIUM_PRIORITY ||
                p.priority === _LOW_PRIORITY) {
                dst.priority = p.priority;
            } else
                return false;
        }

        if (p.dueDate !== null && p.dueDate !== undefined) {
            if (!wac2_utils.isValidDate(p.dueDate))
                return false;
            dst.dueDate = new Date(p.dueDate);
        }

        /* dueDate is a option properties.
           "The default value is undefined.
             If no value is provided, the task has no due date."
           If p.dueDate is set its default value 'undefined',
           we assign default value to dst.dueDate */
        if (p.dueDate === undefined) {
            dst.dueDate = undefined;
        }

        return true;
    }

    function _taskFilterCheck(filter) {
        var i;
        if (filter.id !== undefined && filter.id !== null) {
            filter.id = String(filter.id);
        } else {
            filter.id = undefined;
        }
        if (filter.summary !== undefined && filter.summary !== null) {
            filter.summary = String(filter.summary);
        } else {
            filter.summary = undefined;
        }
        if (filter.description !== undefined && filter.description !== null) {
            filter.description = String(filter.description);
        } else {
            filter.description = undefined;
        }
        if (filter.status !== undefined && filter.status !== null) {
            if (!wac2_utils.isValidArray(filter.status))  {
                return false;
            }
            for (i = 0; i < filter.status.length; i++) {
                filter.status[i] = filter.status[i] | 0;
                if (filter.status[i] !== _STATUS_COMPLETED &&
                    filter.status[i] !== _STATUS_NEEDS_ACTION &&
                    filter.status[i] !== _STATUS_IN_PROCESS &&
                    filter.status[i] !== _STATUS_CANCELLED) {
                    return false;
                }
            }
        } else {
            filter.status = undefined;
        }
        if (filter.priority !== undefined && filter.priority !== null) {
            if (!wac2_utils.isValidArray(filter.priority))  {
                return false;
            }
            for (i = 0; i < filter.priority.length; i++) {
                filter.priority[i] = filter.priority[i] | 0;
                if (filter.priority[i] !== _HIGH_PRIORITY &&
                    filter.priority[i] !== _MEDIUM_PRIORITY &&
                    filter.priority[i] !== _LOW_PRIORITY) {
                    return false;
                }
            }
        } else {
            filter.priority = undefined;
        }
        if (filter.dueDate !== undefined && filter.dueDate !== null) {
            if (!wac2_utils.isValidDate(filter.dueDate)) {
                return false;
            }
            filter.dueDate = new Date(filter.dueDate);
        } else {
            filter.dueDate = undefined;
        }
        return true;
    }

    function TaskProperties(prop) {
        var _self;
        _self = {
            priority : _LOW_PRIORITY,
            description : "",
            summary : "",
            dueDate : undefined,
            status : _STATUS_NEEDS_ACTION
        };
        if (prop) {
            if (_checkAndPasteProperties(prop, _self) === false)
                return undefined;
        }
        return _self;
    }

    function Task(prop, idChoice) {
        var id, _self = new TaskProperties(prop);
        /* if error occurs during checking, _self is an empty object.
           so i randomly pick description to check if property check fails */
        if (_self.description === undefined)
            return undefined;

        switch (idChoice) {
        case _ID_WITHOUT:
            // do nothing
            break;
        case _ID_GEN_NEW:
            id = Math.uuid(undefined, 16);
            _self.__defineGetter__("id", function () {
                return id;
            });
            break;
        case _ID_FROM_PROP:
            id = String(prop.id);
            _self.__defineGetter__("id", function () {
                return id;
            });
            break;
        }

        return _self;
    }

    function _get() {
        var taskListArray = [],
            data = db.retrieveObject(_TASK_OBJECTS);
        utils.forEach(data, function (taskList) {
            for (var t in taskList._list) {
                if (taskList._list[t].dueDate !== undefined &&
                    taskList._list[t].dueDate !== null)
                    taskList._list[t].dueDate = new Date(taskList._list[t].dueDate);
            }
            taskListArray.push(new TaskList(taskList._list, taskList.type, taskList.name));
        });

        /* add default taskList if taskListArray is empty */
        if (taskListArray.length === 0) {
            taskListArray = [new TaskList({}, 0, "Office tasks"), new TaskList({}, 1, "Home tasks")];
        }

        return taskListArray;
    }

    function _save() {
        db.saveObject(_TASK_OBJECTS, _taskListArray);
    }

    function TaskList(taskList, type, name) {
        var task;
        this._list = taskList;
        this.type = type;
        this.name = name;

        this.createTask = function (properties) {
            task = new Task(properties, _ID_WITHOUT);
            /* if error occurs during checking, task is an empty object.
               so i randomly pick summary to check if property check fails */
            if (task.summary === undefined) {
                exception.raise(exception.types.Argument,
                        "EventProperties: input parameter contains invalid values",
                        new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                return undefined;
            }
            return task;
        };

        this.addTask = function (onSuccess, onError, task) {
            var inner = this,
                newTask, _task = Object(task);
            function _addTask() {
                var ret;
                if (!_addTaskAllowed) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                newTask = new Task(_task, _ID_GEN_NEW);
                /* if error occurs during checking, newTask is an empty object.
                    so i randomly pick id to check if property check fails */
                if (newTask.id === undefined) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                ret = _pendingOperate(function () {
                    inner._list[newTask.id] = newTask;
                    _save();
                    onSuccess(new Task(newTask, _ID_FROM_PROP));
                });
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "addTask", _addTask);
        };

        this.updateTask = function (onSuccess, onError, task) {
            var inner = this,
                newTask, _task = Object(task);
            function _updateTask() {
                var ret;
                if (!_updateTaskAllowed) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                if (_checkAndPasteProperties(_task, _task) === false) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }

                ret = _pendingOperate(function () {
                    if (inner._list[_task.id]) {
                        newTask = new Task(inner._list[_task.id], _ID_FROM_PROP);
                        /* Don't need to double check the return of _checkAndPasteProperties 
                           _task has been checked & pasted already */
                        _checkAndPasteProperties(_task, newTask);
                        inner._list[newTask.id] = newTask;
                        _save();
                        onSuccess();
                    } else {
                        if (onError) {
                            onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
                        }
                    }
                });
                return ret;
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "updateTask", _updateTask);
        };

        this.deleteTask = function (onSuccess, onError, id) {
            var inner = this;
            function _deleteTask() {
                var ret;
                /* according to spec  "If any of the input parameters are not 
                   compatible with the expected type for that parameter, 
                   a DeviceAPIError with code TYPE_MISMATCH_ERR MUST be 
                   synchronously thrown." so an error is raised synchronously */
                utils.validateArgumentType(id, "string", null,
                        "Task:deleteTask: " + " invalid id parameter",
                        new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
                if (!_deleteTaskAllowed) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                ret = _pendingOperate(function () {
                    if (inner._list[id]) {
                        delete inner._list[id];
                        _save();
                        onSuccess();
                    } else {
                        if (onError)
                            onError(new DeviceApiError(errorcode.NOT_FOUND_ERR));
                    }
                });
                return ret;
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "deleteTask", _deleteTask);
        };

        this.findTasks = function (onSuccess, onError, filter) {
            var inner = this, _filter = Object(filter), tmp = [], rst = [], valid_tmp = false;
            function _findTasks() {
                var ret;
                if (!_taskFilterCheck(_filter)) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                if (!_findTasksAllowed) {
                    if (onError) {
                        setTimeout(function () {
                            onError(new DeviceApiError(errorcode.SECURITY_ERR));
                        }, 1);
                    }
                    return undefined;
                }
                ret = _pendingOperate(function () {
                    var i, e;
                    if (_filter.id !== undefined) {
                        tmp = wac2_utils.matchOptionString(inner._list, "id", _filter.id);
                        valid_tmp = true;
                    }
                    if (_filter.summary !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionString(tmp, "summary", _filter.summary);
                        } else {
                            tmp = wac2_utils.matchOptionString(inner._list, "summary", _filter.summary);
                            valid_tmp = true;
                        }
                    }
                    if (_filter.description !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionString(tmp, "description", _filter.description);
                        } else {
                            tmp = wac2_utils.matchOptionString(inner._list, "description", _filter.description);
                            valid_tmp = true;
                        }
                    }
                    if (_filter.status !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionShortArray(tmp, "status", _filter.status);
                        } else {
                            tmp = wac2_utils.matchOptionShortArray(inner._list, "status", _filter.status);
                            valid_tmp = true;
                        }
                    }
                    if (_filter.priority !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionShortArray(tmp, "priority", _filter.priority);
                        } else {
                            tmp = wac2_utils.matchOptionShortArray(inner._list, "priority", _filter.priority);
                            valid_tmp = true;
                        }
                    }
                    if (_filter.initialDueDate !== undefined ||
                        _filter.endDueDate !== undefined) {
                        if (valid_tmp) {
                            tmp = wac2_utils.matchOptionDate(tmp, "dueDate", _filter.initialDueDate, _filter.endDueDate);
                        } else {
                            tmp = wac2_utils.matchOptionDate(inner._list, "dueDate", _filter.initialDueDate, _filter.endDueDate);
                            valid_tmp = true;
                        }
                    }

                    if (valid_tmp) {
                        for (i = 0; i < tmp.length; i++) {
                            rst.push(new Task(tmp[i], _ID_FROM_PROP));
                        } 
                    } else {
                        for (e in inner._list) {
                            rst.push(new Task(inner._list[e], _ID_FROM_PROP));
                        }
                    }
                    onSuccess(rst);
                });
                return ret;
            }

            return wac2_utils.validateTypeMismatch(onSuccess, onError, "findTasks", _findTasks);
        };
    }

    this.getTaskLists = function (onSuccess, onError) {
        function _getTaskLists() {
            var ret;
            ret = _pendingOperate(function () {
                if (_taskListArray.length === 0) {
                    _taskListArray = _get();
                }
                onSuccess(_taskListArray);
            }, 1);
            return ret;
        }

        return wac2_utils.validateTypeMismatch(onSuccess, onError, "getTaskLists", _getTaskLists);
    };

    this.__defineGetter__("SIM_TASK_LIST", function () {
        return 0;
    });
    this.__defineGetter__("DEVICE_TASK_LIST", function () {
        return 1;
    });
    this.__defineGetter__("HIGH_PRIORITY", function () {
        return 0;
    });
    this.__defineGetter__("MEDIUM_PRIORITY", function () {
        return 1;
    });
    this.__defineGetter__("LOW_PRIORITY", function () {
        return 2;
    });
    this.__defineGetter__("STATUS_COMPLETED", function () {
        return 0;
    });
    this.__defineGetter__("STATUS_NEEDS_ACTION", function () {
        return 1;
    });
    this.__defineGetter__("STATUS_IN_PROCESS", function () {
        return 2;
    });
    this.__defineGetter__("STATUS_CANCELLED", function () {
        return 3;
    });

    this.handleSubFeatures = function (subFeatures) {
        if (wac2_utils.isEmptyObject(subFeatures) ||
            subFeatures["http://wacapps.net/api/pim.task"] ||
            (subFeatures["http://wacapps.net/api/pim.task.read"] &&
            subFeatures["http://wacapps.net/api/pim.task.write"])) {
            return;
        }
        if (subFeatures["http://wacapps.net/api/pim.task.read"] &&
           !subFeatures["http://wacapps.net/api/pim.task.write"]) {
            _addTaskAllowed = false;
            _deleteTaskAllowed = false;
            _updateTaskAllowed = false;
            return;
        }
        if (subFeatures["http://wacapps.net/api/pim.task.write"] &&
           !subFeatures["http://wacapps.net/api/pim.task.read"]) {
            _findTasksAllowed = false;
            return;
        }
        _console.warn("WAC-2.0-Task-handleSubFeatures: something wrong");
    };

};


});
define('ripple/platform/wac/2.0/typecoerce', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    _self;

_self = function (pattern) {
    var typeCoerce,
        typeOfPattern = Object.prototype.toString.call(pattern);

    typeCoerce = {
        cast: function (obj) {
            var validObj,
                validValue,
                elementType,
                typeOfObj = Object.prototype.toString.call(obj);

            switch (typeOfPattern) {
            case "[object String]":
                validObj = (typeOfObj !== typeOfPattern) ? String(obj) : obj;
                break;

            case "[object Number]":
                validObj = (typeOfObj !== typeOfPattern) ? (Number(obj) | 0) : obj;
                break;

            case "[object Object]":
                if (typeOfObj !== typeOfPattern) {
                    validObj = {};
                } else {
                    validObj = obj;
                    utils.forEach(validObj, function (value, key) {
                        if (pattern[key] === undefined) {
                            delete validObj[key];
                        } else {
                            validValue = _self(pattern[key]).cast(value);
                            if (validObj[key] !== validValue)
                                validObj[key] = validValue;
                        }
                    });
                }
                break;

            case "[object Array]":
                if (typeOfObj !== typeOfPattern) {
                    validObj = [];
                } else {
                    validObj = obj;
                    elementType = _self(pattern[0]);
                    utils.forEach(validObj, function (element, index) {
                        validObj[index] = elementType.cast(element);
                    });
                }
                break;
            }

            return validObj;
        }
    };

    return typeCoerce;
};

module.exports = _self;

});
define('ripple/platform/wac/2.0/wac2_utils', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    errorcode = require('ripple/platform/wac/2.0/errorcode'),
    DeviceApiError = require('ripple/platform/wac/2.0/deviceapierror');

module.exports = {
    _wac2_regexSanitize: function (regexString) {
        var escapePattern = /([^\\]|^)(%)/g, percentPattern = /\\%/g;
        return regexString.replace("^", "\\^")
                .replace("$", "\\$")
                .replace("(", "\\(")
                .replace(")", "\\)")
                .replace("<", "\\<")
                .replace("[", "\\[")
                .replace("{", "\\{")
                .replace(/\\([^%])/, "\\\\$1")    /* don't replace \\% */
                .replace("|", "\\|")
                .replace(">", "\\>")
                .replace(".", "\\.")
                .replace("*", "\\*")
                .replace("+", "\\+")
                .replace("?", "\\?")
                .replace(escapePattern, "$1.*")  /* replace % with .* */
                .replace(percentPattern, "%");   /* strip excape of % */ 
    }, 

    isValidDate: function (d) {
        if (Object.prototype.toString.call(d) !== "[object Date]")
            return false;
        return !isNaN(d.getTime());
    },

    isValidArray: function (a) {
        return (Object.prototype.toString.call(a) === "[object Array]");
    },
    
    matchOptionArrayString: function (src, attr, pattern) {
        /* src.obj[attr] is a StringArray */
        var _pattern, re, _stringMatch;
        _pattern = this._wac2_regexSanitize(pattern); 
        re = new RegExp("^" + _pattern + "$", "i");

        _stringMatch = function (obj, index) {
            if (pattern.search(/^%*$/i) === 0) 
                return true;
            if (obj[attr] === undefined || obj[attr] === null)
                return false;
            return obj[attr].some(function (f) {
                return f.search(re) !== -1;
            });
        };
        return utils.filter(src, _stringMatch);
    },

    matchOptionString: function (src, attr, pattern) {
        /* src.obj[attr] is a string */
        var _stringMatch, _pattern, _re;
        _pattern = this._wac2_regexSanitize(pattern); 
        _re = new RegExp("^" + _pattern + "$", "mi");

        _stringMatch = function (obj, index) {
            return (obj[attr].search(_re) !== -1);
        };
        return utils.filter(src, _stringMatch);
    },

    matchOptionDate: function (src, attr, filterStart, filterEnd) {
        var _dateMatch;
        _dateMatch = function (obj, index) {
            var matched = true, valueDate = obj[attr];
    
            if (filterStart !== undefined && filterStart !== null) {
                matched = (valueDate.getTime() >= filterStart.getTime());
            }
            if (matched && (filterEnd !== undefined && filterEnd !== null)) {
                matched = (valueDate.getTime() <= filterEnd.getTime());
            }
            return matched;
        };
        return utils.filter(src, _dateMatch);
    },

    matchOptionShortArray: function (src, attr, filterArray) {
        /* src.obj[attr] is a short, filterArray is an array 
           i.e. find status is [CONFRIMED or TENTATIVE] */
        var arraySome = function (obj, index) {
            return filterArray.some(function (f) {
                return f === obj[attr];  
            });
        };
        return utils.filter(src, arraySome);
    },

    validateTypeMismatch: function (onSuccess, onError, name, callback) {
        if (onSuccess) {
            utils.validateArgumentType(onSuccess, "function", null,
                                       name + " invalid successCallback parameter",
                                       new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }

        if (onError) {
            utils.validateArgumentType(onError, "function", null,
                                       name + " invalid errorCallback parameter",
                                       new DeviceApiError(errorcode.TYPE_MISMATCH_ERR));
        }

        if (onSuccess) {
            return callback && callback();
        } else {
            if (onError) {
                setTimeout(function () {
                    onError(new DeviceApiError(errorcode.INVALID_VALUES_ERR));
                }, 1);
            }
        }
        return undefined;
    },

    isEmptyObject: function (obj) {
        var prop;

        for (prop in obj) {
            return false;
        }
        return true;
    }
};


});
define('ripple/platform/wearable/2.0/WebAPIError', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/wearable/2.0/errorcode');

var msg = {
        0: "Generic Error",
        1: "Index or size is negative, or greater than the allowed value.",
        2: "Specified range of text does not fit into a DOMString.",
        3: "Node is inserted somewhere it doesn't belong.",
        4: "Node is used in a different document than the one that created it (that doesn't support it).",
        5: "An invalid or illegal character is specified.",
        6: "Data is specified for a Node which does not support data.",
        7: "An attempt is made to modify an object where modifications are not allowed.",
        8: "An attempt is made to reference a Node in a context where it does not exist.",
        9: "The implementation does not support the requested type of object or operation.",
        10: "An attempt is made to add an attribute that is already in use elsewhere.",
        11: "An attempt is made to use an object that is not, or is no longer, usable.",
        12: "An invalid or illegal string is specified.",
        13: "An attempt is made to modify the type of the underlying object.",
        14: "An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.",
        15: "A parameter or an operation is not supported by the underlying object.",
        16: "A call to a method such as insertBefore or removeChild would make the Node invalid with respect to \"partial validity\", this exception would be raised and the operation would not be done.",
        17: "The type of an object is incompatible with the expected type of the parameter associated to the object.",
        18: "An attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.",
        19: "A network error occurs in synchronous requests.",
        20: "The abort error occurs in asynchronous requests by user prompt.",
        21: "The operation could not be completed because the URL does not match.",
        22: "The quota has been exceeded.",
        23: "The operation timed out.",
        24: "The supplied node is incorrect or has an incorrect ancestor for this operation.",
        25: "The object can not be cloned.",
        99: "The content of an object does not include valid values.",
        100: "Error occurred in communication with the underlying implementation that meant the requested method could not complete.",
        111: "Requested service is not available.",
        112: "The authentication token of remote peer agent is not generated.",
        113: "The remote Accessory Peer Agent already exists.",
        114: "The remote Accessory Peer Agent is unreachable or no longer available, perhaps it has been powered off or the connectivity has been turned off.",
        115: "The remote Accessory Peer Agent timedout.",
        116: "The remote Accessory Peer Agent rejected the request.",
        117: "The remote Accessory Peer Agent closed the Service Connection",
        118: "The remote Accessory Peer Agent Accessory Device has been detached.",
        119: "The remote peer rejected/cancelled the file request."
    },
    errType = {
        0: "UnknownError",
        1: "IndexSizeError",
        2: "DOMStringSizeError",
        3: "HierarchyRequestError",
        4: "WrongDocumentError",
        5: "InvalidCharacterError",
        6: "NoDataAllowedError",
        7: "NoModificationAllowedError",
        8: "NotFoundError",
        9: "NotSupportedError",
        10: "InuseAttributeError",
        11: "InvalidStateError",
        12: "SyntaxError",
        13: "InvalidModificationError",
        14: "NamespaceError",
        15: "InvalidAccessError",
        16: "ValidationError",
        17: "TypeMismatchError",
        18: "SecurityError",
        19: "NetworkError",
        20: "AbortError",
        21: "URLMismatchError",
        22: "QuotaExceededError",
        23: "TimeoutError",
        24: "InvalidNodeTypeError",
        25: "DataCloneError",
        99: "InvalidValuesError",
        100: "IOError",
        111: "ServiceNotAvailableError",
        112: "TokenNotGeneratedError",
        113: "AlreadyExistError",
        114: "DeviceUnreachableError",
        115: "PeerAgentNoResponseError",
        116: "PeerAgentRejectedError",
        117: "PeerDisconnectedError",
        118: "DeviceDetachecError",
        119: "PeerRejectedError"
    };

/*
 support 3 types of error:
 - WebAPIError()
 code = errorcode.UNKNOWN_ERR
 message = errorcode.message[UNKNOWN_ERR]
 - WebAPIError(errorcode."TYPE_MISMATCH_ERR")
 code = 17
 message = errorcode.message[17]
 - WebAPIError(my_own_error_code, "This is my error message.")
 code = my_own_error_code(number)
 message = "This is my error message."
 */

module.exports = function (code, message, name) {
    var _code, _message, _name;

    if (typeof code !== 'number') {
        _code = errorcode.UNKNOWN_ERR;
        _message = msg[_code];
        _name = errType[_code];
    } else {
        _code = code;
        if (typeof message === 'string') {
            _message = message;
        } else {
            _message = msg[_code];
        }
        if (typeof name === 'string') {
            _name = name;
        } else {
            _name = errType[_code];
        }
    }

    this.__defineGetter__("code", function () {
        return _code;
    });
    this.__defineGetter__("message", function () {
        return _message;
    });
    this.__defineGetter__("name", function () {
        return _name;
    });
};

});
define('ripple/platform/wearable/2.0/WebAPIException', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 errorcode = require('ripple/platform/wearable/2.0/errorcode');

var msg = {
        0: "Generic Error",
        1: "Index or size is negative, or greater than the allowed value.",
        2: "Specified range of text does not fit into a DOMString.",
        3: "Node is inserted somewhere it doesn't belong.",
        4: "Node is used in a different document than the one that created it (that doesn't support it).",
        5: "An invalid or illegal character is specified.",
        6: "Data is specified for a Node which does not support data.",
        7: "An attempt is made to modify an object where modifications are not allowed.",
        8: "An attempt is made to reference a Node in a context where it does not exist.",
        9: "The implementation does not support the requested type of object or operation.",
        10: "An attempt is made to add an attribute that is already in use elsewhere.",
        11: "An attempt is made to use an object that is not, or is no longer, usable.",
        12: "An invalid or illegal string is specified.",
        13: "An attempt is made to modify the type of the underlying object.",
        14: "An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.",
        15: "A parameter or an operation is not supported by the underlying object.",
        16: "A call to a method such as insertBefore or removeChild would make the Node invalid with respect to \"partial validity\", this exception would be raised and the operation would not be done.",
        17: "The type of an object is incompatible with the expected type of the parameter associated to the object.",
        18: "An attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.",
        19: "A network error occurs in synchronous requests.",
        20: "The abort error occurs in asynchronous requests by user prompt.",
        21: "The operation could not be completed because the URL does not match.",
        22: "The quota has been exceeded.",
        23: "The operation timed out.",
        24: "The supplied node is incorrect or has an incorrect ancestor for this operation.",
        25: "The object can not be cloned.",
        99: "The content of an object does not include valid values.",
        100: "Error occurred in communication with the underlying implementation that meant the requested method could not complete.",
        111: "Requested service is not available.",
        112: "The authentication token of remote peer agent is not generated.",
        113: "The remote Accessory Peer Agent already exists.",
        114: "The remote Accessory Peer Agent is unreachable or no longer available, perhaps it has been powered off or the connectivity has been turned off.",
        115: "The remote Accessory Peer Agent timedout.",
        116: "The remote Accessory Peer Agent rejected the request.",
        117: "The remote Accessory Peer Agent closed the Service Connection",
        118: "The remote Accessory Peer Agent Accessory Device has been detached.",
        119: "The remote peer rejected/cancelled the file request."
    },
    errType = {
        0: "UnknownError",
        1: "IndexSizeError",
        2: "DOMStringSizeError",
        3: "HierarchyRequestError",
        4: "WrongDocumentError",
        5: "InvalidCharacterError",
        6: "NoDataAllowedError",
        7: "NoModificationAllowedError",
        8: "NotFoundError",
        9: "NotSupportedError",
        10: "InuseAttributeError",
        11: "InvalidStateError",
        12: "SyntaxError",
        13: "InvalidModificationError",
        14: "NamespaceError",
        15: "InvalidAccessError",
        16: "ValidationError",
        17: "TypeMismatchError",
        18: "SecurityError",
        19: "NetworkError",
        20: "AbortError",
        21: "URLMismatchError",
        22: "QuotaExceededError",
        23: "TimeoutError",
        24: "InvalidNodeTypeError",
        25: "DataCloneError",
        99: "InvalidValuesError",
        100: "IOError",
        111: "ServiceNotAvailableError",
        112: "TokenNotGeneratedError",
        113: "AlreadyExistError",
        114: "DeviceUnreachableError",
        115: "PeerAgentNoResponseError",
        116: "PeerAgentRejectedError",
        117: "PeerDisconnectedError",
        118: "DeviceDetachecError",
        119: "PeerRejectedError"
    };

/*
 support 3 types of error:
 - WebAPIError()
 code = errorcode.UNKNOWN_ERR
 message = errorcode.message[UNKNOWN_ERR]
 - WebAPIError(errorcode."TYPE_MISMATCH_ERR")
 code = 17
 message = errorcode.message[17]
 - WebAPIError(my_own_error_code, "This is my error message.")
 code = my_own_error_code(number)
 message = "This is my error message."
 */

module.exports = function (code, message, name) {
    var _code, _message, _name;

    if (typeof code !== 'number') {
        _code = errorcode.UNKNOWN_ERR;
        _message = msg[_code];
        _name = errType[_code];
    } else {
        _code = code;
        if (typeof message === 'string') {
            _message = message;
        } else {
            _message = msg[_code];
        }
        if (typeof name === 'string') {
            _name = name;
        } else {
            _name = errType[_code];
        }
    }

    this.__defineGetter__("code", function () {
        return _code;
    });
    this.__defineGetter__("message", function () {
        return _message;
    });
    this.__defineGetter__("name", function () {
        return _name;
    });
};

});
define('ripple/platform/wearable/2.0/dbinit', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 exception = require('ripple/exception'),
    DBBuilder,
    _data = {
        dbBuilder: null
    },
    _self = {};

function _initialize() {
    _data.dbBuilder = new DBBuilder();
}

DBBuilder = function () {
    var self;

    // private
    function formatString(str) {
        return str.replace(/^\s+|[\t\n\r\v]+|\s+$/g, "").replace(/\s+/g, "");
    }

    // private
    function formatHex(str) {
        return str.replace(/,(0x[0-9a-fA-F]+?),/g, ',"$1",');
    }

    // public
    function register(type, dbFile, Extension) {
        _data[type] = Extension ? new Extension() : {};

        if (!dbFile)
            return;

        _self.__defineGetter__(type, function () {
            var fnInit;

            if (!_data[type].db) {
                fnInit = _data[type].initdb || initdb;
                _data[type].db = fnInit(dbFile);
            }

            return _data[type].db;
        });
    }

    function initdb(dbFile) {
        var xmlHttp, res;

        try {
            xmlHttp = new XMLHttpRequest();
            xmlHttp.open("GET", "dbsamples/" + dbFile, false);
            xmlHttp.send();
        } catch (e) {
            exception.handle(e);
        }

        if (!xmlHttp.responseText) {
            return null;
        }

        res = formatHex(formatString(xmlHttp.responseText));

        return JSON.parse(res);
    }

    self = {
        register: register,
        initdb:   initdb
    };

    return self;
};

_initialize();

module.exports = _self;

});
define('ripple/platform/wearable/2.0/errorcode', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 _self = {};

_self.__defineGetter__("UNKNOWN_ERR", function () {
    return 0;
});

_self.__defineGetter__("INDEX_SIZE_ERR", function () {
    return 1;
});

_self.__defineGetter__("DOMSTRING_SIZE_ERR", function () {
    return 2;
});

_self.__defineGetter__("HIERARCHY_REQUEST_ERR", function () {
    return 3;
});

_self.__defineGetter__("WRONG_DOCUMENT_ERR", function () {
    return 4;
});

_self.__defineGetter__("INVALID_CHARACTER_ERR", function () {
    return 5;
});

_self.__defineGetter__("NO_DATA_ALLOWED_ERR", function () {
    return 6;
});

_self.__defineGetter__("NO_MODIFICATION_ALLOWED_ERR", function () {
    return 7;
});

_self.__defineGetter__("NOT_FOUND_ERR", function () {
    return 8;
});

_self.__defineGetter__("NOT_SUPPORTED_ERR", function () {
    return 9;
});

_self.__defineGetter__("INUSE_ATTRIBUTE_ERR", function () {
    return 10;
});

_self.__defineGetter__("INVALID_STATE_ERR", function () {
    return 11;
});

_self.__defineGetter__("SYNTAX_ERR", function () {
    return 12;
});

_self.__defineGetter__("INVALID_MODIFICATION_ERR", function () {
    return 13;
});

_self.__defineGetter__("NAMESPACE_ERR", function () {
    return 14;
});

_self.__defineGetter__("INVALID_ACCESS_ERR", function () {
    return 15;
});

_self.__defineGetter__("VALIDATION_ERR", function () {
    return 16;
});

_self.__defineGetter__("TYPE_MISMATCH_ERR", function () {
    return 17;
});

_self.__defineGetter__("SECURITY_ERR", function () {
    return 18;
});

_self.__defineGetter__("NETWORK_ERR", function () {
    return 19;
});

_self.__defineGetter__("ABORT_ERR", function () {
    return 20;
});

_self.__defineGetter__("URL_MISMATCH_ERR", function () {
    return 21;
});

_self.__defineGetter__("QUOTA_EXCEEDED_ERR", function () {
    return 22;
});

_self.__defineGetter__("TIMEOUT_ERR", function () {
    return 23;
});

_self.__defineGetter__("INVALID_NODE_TYPE_ERR", function () {
    return 24;
});

_self.__defineGetter__("DATA_CLONE_ERR", function () {
    return 25;
});

_self.__defineGetter__("INVALID_VALUES_ERR", function () {
    return 99;
});

_self.__defineGetter__("IO_ERR", function () {
    return 100;
});

_self.__defineGetter__("SERVICE_NOT_AVAILABLE_ERR", function () {
    return 111;
});

_self.__defineGetter__("TOKEN_NOT_GENERATED_ERR", function () {
    return 112;
});

_self.__defineGetter__("ALREADY_EXIST", function () {
    return 113;
});

_self.__defineGetter__("DEVICE_UNREACHABLE", function () {
    return 114;
});

_self.__defineGetter__("PEERAGENT_NO_RESPONSE", function () {
    return 115;
});

_self.__defineGetter__("PEERAGENT_REJECTED", function () {
    return 116;
});

_self.__defineGetter__("PEER_DISCONNECTED", function () {
    return 117;
});

_self.__defineGetter__("DEVICE_DETACHED", function () {
    return 118;
});

_self.__defineGetter__("PEER_REJECTED", function () {
    return 119;
});

module.exports = _self;


});
define('ripple/platform/wearable/2.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2014 Research In Motion Limited.
 *  Copyright 2014 Intel Corporation.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    constants = require('ripple/constants');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (configValidationObject) {
        var valid = true;
        // no xmlns:JIL in wac 2.0 spec
        valid = !!configValidationObject.widget.validationResult[0].attributes.xmlns.valid;

        return valid;
    },
    extractInfo: function (configValidationObject) {
        if (!configValidationObject) {
            return null;
        }

        var widgetInfo = {},
            configFeatures,
            configPreferences,
            preferenceName,
            platform, rst, i, j,
            settingRst = {
                'screen-orientation': 'portrait',
                'context-menu': 'enable',
                'background-support': 'disable',
                encryption: 'disable',
                'install-location': 'auto',
                'hwkey-event': 'enable'
            };

        widgetInfo.id = configValidationObject.widget.validationResult[0].attributes.id.value || "";
        widgetInfo.name = configValidationObject.widget.children.name.validationResult[0].value;
        widgetInfo.icon = configValidationObject.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = configValidationObject.widget.validationResult[0].attributes.version.value;
        if (configValidationObject.widget.children.application.validationResult[0].valid) {
            widgetInfo.tizenAppId = configValidationObject.widget.children.application.validationResult[0].attributes.id.value;
            widgetInfo.tizenPackageId = configValidationObject.widget.children.application.validationResult[0].attributes.package.value;
        }

        widgetInfo.features = {};

        if (configValidationObject.widget.children.setting.hasOwnProperty('validationResult') === true) {
            rst = configValidationObject.widget.children.setting.validationResult;
            // the first one has higher priority per platform implementation
            for (i = rst.length -1 ; i >= 0; i--) {
                if (rst[i].valid === true) {
                    for (j in rst[i].attributes) {
                        if (rst[i].attributes[j].value !== undefined) {
                            settingRst[j] = rst[i].attributes[j].value;
                        }
                    }
                }
            }
            db.save("layout", settingRst["screen-orientation"]);
        }

        configFeatures = configValidationObject.widget.children.feature.validationResult;
        utils.forEach(configFeatures, function (f) {
            if (f.valid === true) {
                var feature = {id: f.attributes.name.value,
                         required: f.attributes.required.valid};
                widgetInfo.features[feature.id] = feature;
            }
        });

        widgetInfo.metadata = {};
        if (configValidationObject.widget.children.metadata.hasOwnProperty('validationResult') === true) {
            widgetInfo.metadata.key = configValidationObject.widget.children.metadata.validationResult[0].attributes.key.value;
            widgetInfo.metadata.value = configValidationObject.widget.children.metadata.validationResult[0].attributes.value.value;
        }
        
        widgetInfo.category = {};
        if (configValidationObject.widget.children.category.hasOwnProperty('validationResult') === true) {
            widgetInfo.metadata.name = configValidationObject.widget.children.category.validationResult[0].attributes.name.value;
        }

        widgetInfo.preferences = {};

        configPreferences = configValidationObject.widget.children.preference.validationResult;

        platform = require('ripple/platform');
        utils.forEach(configPreferences, function (preference) {
            preferenceName = preference.attributes.name.value;
            if (preferenceName) {
                widgetInfo.preferences[preferenceName] = {
                    "key": preferenceName,
                    "value": preference.attributes.value.value || "",
                    "readonly": preference.attributes.readonly.value === "true"
                };

                db.save(preferenceName,
                        widgetInfo.preferences[preferenceName].value,
                        platform.getPersistencePrefix(widgetInfo.id));
            }
        });

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            helpText: "\"widget\" element describes widget information in configuration documents and serves as a container for other elements. It must be used in the configuration document and may have the following child elments: name,description,icon,author,license,content,feature and preference.The \"widget\" element MAY have following attributes: id,version,height,width, defaultlocale, xml:lang and dir",
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xmlns:tizen": {
                    attributeName: "xmlns:tizen",
                    required: false,
                    type: "list",
                    listValues: ["http://tizen.org/ns/widgets"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                },
                dir: {
                    attributeName: "dir",
                    required: false,
                    type: "list",
                    listValues: ["ltr", "rtl", "lro", "rlo"]
                },
                id: {
                    attributeName: "id",
                    required: false,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    required: false,
                    type: "string"
                },
                height: {
                    attributeName: "height",
                    required: false,
                    type: "integer"
                },
                width: {
                    attributeName: "width",
                    required: false,
                    type: "integer"
                },
                viewmodes: {
                    attributeName: "viewmodes",
                    required: false,
                    type: "list",
                    listValues: ["windowed", "floating", "fullscreen", "maximized", "minimized"]
                },
                defaultlocale: {
                    attributeName: "defaultlocale",
                    required: false,
                    type: "iso-language"
                }
            },
            children: {
                name: {
                    nodeName: "name",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        "short": {
                            attributeName: "short",
                            required: false,
                            type: "string"
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.URL
                        },
                        email: {
                            attributeName: "email",
                            required: false,
                            type: "regex",
                            regex: constants.REGEX.EMAIL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 0,
                    type: "string",
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        href: {
                            attributeName: "href",
                            type: "regex",
                            required: false,
                            regex: constants.REGEX.URL
                        }
                    },
                    children: {
                        span: {
                            nodeName: "span",
                            required: false,
                            type: "string",
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language",
                                    unique: true
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                }
                            }
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        width: {
                            attributeName: "width",
                            required: false,
                            type: "integer"
                        },
                        height: {
                            attributeName: "height",
                            required: false,
                            type: "integer"
                        }
                    }
                },
                content: {
                    nodeName: "content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language",
                            unique: true
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        encoding: {
                            attributeName: "encoding",
                            required: false,
                            type: "string"
                        },
                        type: {
                            attributeName: "type",
                            required: false,
                            type: "string"
                        }
                    }
                },
                setting: {
                    nodeName: "tizen:setting",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        'screen-orientation': {
                            attributeName: "screen-orientation",
                            required: false,
                            type: "list",
                            listValues: ['portrait', 'landscape', 'auto']
                        },
                        'context-menu': {
                            attributeName: "context-menu",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'background-support': {
                            attributeName: "background-support",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'encryption': {
                            attributeName: "encryption",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        },
                        'install-location': {
                            attributeName: "install-location",
                            required: false,
                            type: "list",
                            listValues: ['auto', 'internal-only', 'perfer-external']
                        },
                        'hwkey-event': {
                            attributeName: "hwkey-event",
                            required: false,
                            type: "list",
                            listValues: ['enable', 'disable']
                        }
                    }
                },
                application: {
                    nodeName: "tizen:application",
                    required: true,
                    occurrence: 1,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            type: "string"
                        },
                        required_version: {
                            attributeName: "required_version",
                            required: true,
                            type: "list",
                            listValues: ['1.0', '2.0', '2.1', '2.2']
                        },
                        package: {
                            attributeName: "package",
                            required: false,
                            type: "string"
                        }
                    }
                },
                "tizen:content": {
                    nodeName: "tizen:content",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        }
                    }
                },
                control: {
                    nodeName: "tizen:app-control",
                    required: false,
                    occurrence: 0,
                    children: {
                        src: {
                            nodeName: "tizen:src",
                            required: true,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        operation: {
                            nodeName: "tizen:operation",
                            required: true,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        uri: {
                            nodeName: "tizen:uri",
                            required: false,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        mime: {
                            nodeName: "tizen:mime",
                            required: false,
                            occurence: 0,
                            attributes: {
                                name: {
                                    attributeName: "name",
                                    required: false,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                "app-widget": {
                    nodeName: "tizen:app-widget",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            type: "string"
                        },
                        primary: {
                            attributeName: "primary",
                            required: true,
                            type: "list",
                            listValues: ['true', 'false']
                        },
                        "auto-launch": {
                            attributeName: "auto-launch",
                            required: false,
                            type: "list",
                            listValues: ['true', 'false']
                        },
                        "update-period": {
                            attributeName: "update-period",
                            required: false,
                            type: "integer"
                        }
                    },
                    children: {
                        "box-label": {
                            nodeName: "tizen:box-label",
                            required: true,
                            occurence: 1
                        },
                        "box-icon": {
                            nodeName: "tizen:box-icon",
                            required: true,
                            occurence: 1,
                            attributes: {
                                src: {
                                    attributeName: "src",
                                    required: true,
                                    type: "string"
                                }
                            }
                        },
                        "box-content": {
                            nodeName: "tizen:box-content",
                            required: true,
                            occurence: 1,
                            attributes: {
                                src: {
                                    attributeName: "src",
                                    required: true,
                                    type: "string"
                                },
                                "mouse-event": {
                                    attributeName: "mouse-event",
                                    required: false,
                                    type: "string"
                                },
                                "touch-event": {
                                    attributeName: "touch-event",
                                    required: false,
                                    type: "string"
                                }
                            },
                            children: {
                                "box-size": {
                                    nodeName: "tizen:box-size",
                                    required: false,
                                    occurence: 1,
                                    attributes: {
                                        "preview": {
                                            attributeName: "preview",
                                            required: false,
                                            type: "string"
                                        }
                                    }
                                },
                                pd: {
                                    nodeName: "tizen:pd",
                                    required: false,
                                    occurence: 1,
                                    attributes: {
                                        "src": {
                                            attributeName: "src",
                                            required: true,
                                            type: "string"
                                        },
                                        "width": {
                                            attributeName: "width",
                                            required: true,
                                            type: "integer"
                                        },
                                        "height": {
                                            attributeName: "height",
                                            required: true,
                                            type: "integer"
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                account: {
                    nodeName: "tizen:account",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "multiple-account-support": {
                            attributeName: "multiple-account-support",
                            required: true,
                            type: "list",
                            listValues: ['true', 'false']
                        }
                    },
                    children: {
                        icon: {
                            nodeName: "tizen:icon",
                            required: false,
                            occurence: 1,
                            attributes: {
                                section: {
                                    attributeName: "section",
                                    required: true,
                                    type: "string"
                                }
                            }
                        },
                        "display-name": {
                            nodeName: "tizen:display-name",
                            required: false,
                            occurence: 1,
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "string"
                                }
                            }
                        },
                        capability: {
                            nodeName: "capability",
                            required: false,
                            occurence: 1
                        }
                    }
                },
                feature: {
                    nodeName: "tizen:privilege",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "list",
                            listValues: ["http://developer.samsung.com/privilege/accessoryprotocol",
                                         "http://developer.samsung.com/privilege/healthinfo",
                                         "http://www.w3.org/TR/battery-status/",
                                         "http://www.w3.org/TR/geolocation-API/",
                                         "http://www.w3.org/TR/touch-events/",
                                         "http://www.w3.org/TR/vibration/",
                                         "http://tizen.org/privilege/tizen",
                                         "http://tizen.org/privilege/alarm",
                                         "http://tizen.org/privilege/application.launch",
                                         "http://tizen.org/privilege/appmanager.kill", "http://tizen.org/privilege/appmanager.certificate",
                                         "http://tizen.org/privilege/content.read", "http://tizen.org/privilege/content.write",
                                         "http://tizen.org/privilege/filesystem.read", "http://tizen.org/privilege/filesystem.write",
                                         "http://tizen.org/privilege/packagemanager.install", "http://tizen.org/privilege/package.info",
                                         "http://tizen.org/privilege/power",
                                         "http://tizen.org/privilege/system", "http://tizen.org/privilege/systemmanager",
                                         "http://tizen.org/privilege/time"]
                        },
                        required: {
                            attributeName: "required",
                            type: "boolean",
                            required: false
                        }
                    },
                    children: {
                        param: {
                            nodeName: "param",
                            required: false,
                            occurrence: 0,
                            attributes: {
                                "xml:lang": {
                                    attributeName: "xml:lang",
                                    required: false,
                                    type: "iso-language"
                                },
                                dir: {
                                    attributeName: "dir",
                                    required: false,
                                    type: "list",
                                    listValues: ["ltr", "rtl", "lro", "rlo"]
                                },
                                name: {
                                    attributeName: "name",
                                    required: true,
                                    type: "string"
                                },
                                value: {
                                    attributeName: "value",
                                    required: true,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                category: {
                    nodeName: "tizen:category",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "name": {
                            attributeName: "name",
                            required: true,
                            type: "string"
                        }
                    }
                },
                metadata: {
                    nodeName: "tizen:metadata",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "key": {
                            attributeName: "key",
                            required: true,
                            type: "string"
                        },
                        "value": {
                            attributeName: "value",
                            required: true,
                            type: "string"
                        }
                    }
                },
                preference: {
                    nodeName: "preference",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        dir: {
                            attributeName: "dir",
                            required: false,
                            type: "list",
                            listValues: ["ltr", "rtl", "lro", "rlo"]
                        },
                        name: {
                            attributeName: "name",
                            required: true,
                            type: "string"
                        },
                        value: {
                            type: "string",
                            required: false,
                            attributeName: "value"
                        },
                        readonly: {
                            attributeName: "readonly",
                            type: "boolean",
                            required: false
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/wearable/2.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    StorageTypeTable = {
        "UNKNOWN": "UNKNOWN",
        "INTERNAL": "INTERNAL",
        "MMC": "MMC",
        "USB_HOST": "USB_HOST"
    },
    NetworkTypeTable = {
        "NONE": "NONE",
        "2G": "2G",
        "2.5G": "2.5G",
        "3G": "3G",
        "4G": "4G",
        "WIFI": "WIFI",
        "ETHERNET": "ETHERNET",
        "UNKNOWN": "UNKNOWN"
    },
    LocaleTable = {
        "eng_USA": "eng_USA",
        "eng_CAN": "eng_CAN",
        "deu_DEU": "deu_DEU",
        "jpn_JPN": "jpn_JPN",
        "zho_CHN": "zho_CHN",
        "UNKNOWN": "UNKNOWN"
    },
    SimStateTable = {
        "ABSENT": "ABSENT",
        "INITIALIZING": "INITIALIZING",
        "READY": "READY",
        "PIN_REQUIRED": "PIN_REQUIRED",
        "PUK_REQUIRED":"PUK_REQUIRED",
        "NETWORK_LOCKED": "NETWORK_LOCKED",
        "SIM_LOCKED": "SIM_LOCKED",
        "UNKNOWN": "UNKNOWN"
    };

function deviceStatusEventTrigger(setting) {
    event.trigger("DeviceStatusChanged", [setting]);
}

module.exports = {
    "Config": {
        "vibratingMode": {
            "name": "Vibrator",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("VibratingModeChanged", [setting]);
            }
        },
        "lockScreen": {
            "name": "Lock Screen",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "callback": function (setting) {
                event.trigger("LockScreenChanged", [setting]);
            }
        }
    },
    "DEVICE_ORIENTATION": {
        "status": {
            "name": "Status",
            "control": {
                "type": "label",
                "innertext": "PORTRAIT_PRIMARY",
                "value": "PORTRAIT_PRIMARY"
            },
            "event": "LayoutChanged"
        },
        "isAutoRotation": {
            "name": "Is Auto Rotation",
            "control": {
                "type": "label",
                "value": false
            }
        }
    },
    "CPU": {
        "load": {
            "name": "Load",
            "control": {
                "type": "number",
                "value": 0.1
            },
            "event": "CpuLoadChanged",
            "callback": function (setting) {
                if (setting > 1) setting = 1;
                if (setting < 0) setting = 0;
                event.trigger("CpuLoadChanged", [setting]);
            }
        }
    },
    "STORAGE": {
        "type": {
            "name": "Type",
            "control": {
                "type": "select",
                "value": StorageTypeTable["INTERNAL"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(StorageTypeTable, function (key, value) {
                    optionList[key] = StorageTypeTable[value];
                });

                return optionList;
            }())
        },
        "capacity": {
            "name": "Capacity(bytes)",
            "control": {
                "type": "label",
                "value": 16000000000
            }
        },
        "availableCapacity": {
            "name": "AvailableCapacity(bytes)",
            "control": {
                "type": "number",
                "value": 12000000000
            },
            "callback": function (setting) {
                event.trigger("AvailCapacityChanged", [setting]);
            }
        },
        "isRemovable": {
            "name": "IsRemovable",
            "control": {
                "type": "checkbox",
                "value": true
            }
        }
    },
    "BUILD": {
        "model": {
            "name": "Model",
            "control": {
                "type": "label",
                "innertext": "tizen-2.2 build",
                "value": "tizen-2.2 build"
            }
        },
        "manufacturer": {
            "name": "Manufacturer",
            "control": {
                "type": "label",
                "innertext": "Tizen",
                "value": "Tizen"
            }
        },
        "buildVersion": {
            "name": "Build Version",
            "control": {
                "type": "label",
                "innertext": "TIZEN_WEB_SIMULATOR_000001",
                "value": "TIZEN_WEB_SIMULATOR_000001"
            }
        }
    },
    "LOCALE": {
        "language": {
            "name": "Language",
            "control": {
                "type": "select",
                "value": LocaleTable["eng_USA"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(LocaleTable, function (key, value) {
                    optionList[key] = LocaleTable[value];
                });

                return optionList;
            }())
        },
        "country": {
            "name": "Country",
            "control": {
                "type": "select",
                "value": LocaleTable["eng_USA"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(LocaleTable, function (key, value) {
                    optionList[key] = LocaleTable[value];
                });

                return optionList;
            }())
        }
    },
    "DISPLAY": {
        "resolutionWidth": {
            "name": "Resolution Width(pixels)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "resolutionHeight": {
            "name": "Resolution Height(pixels)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "dotsPerInchWidth": {
            "name": "DPI-X",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "dotsPerInchHeight": {
            "name": "DPI-Y",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "physicalWidth": {
            "name": "Physical Width(millimeters)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "physicalHeight": {
            "name": "Physical Height(millimeters)",
            "control": {
                "type": "label",
                "value": 0
            }
        },
        "brightness": {
            "name": "Brightness",
            "control": {
                "type": "number",
                "value": 1
            },
            "event": "DisplayBrightnessChanged",
            "callback": function (setting) {
                if (setting > 1) setting = 1;
                if (setting < 0) setting = 0;
                event.trigger("DisplayBrightnessChanged", [setting]);
            }
        }
    },
    "NETWORK": {
        "networkType": {
            "name": "Network Type",
            "control" : {
                "type": "select",
                "value": NetworkTypeTable["NONE"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(NetworkTypeTable, function (key, value) {
                    optionList[key] = NetworkTypeTable[value];
                });

                return optionList;
            }())
        }
    },
    "WIFI_NETWORK": {
        "status": {
            "name": "Status",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "event": "WiFiNetworkStatusChanged",
            "callback": function (setting) {
                event.trigger("WiFiNetworkStatusChanged", [setting]);
            }
        },
        "ssid": {
            "name": "SSID",
            "control": {
                "type": "text",
                "value": "Tizen WiFi"
            }
        },
        "ipAddress": {
            "name": "IP Address",
            "control": {
                "type": "text",
                "value": "192.168.0.1"
            }
        },
        "ipv6Address": {
            "name": "IPv6 Address",
            "control": {
                "type": "text",
                "value": "2001:db8:85a3:0:0:0:70:7334"
            }
        },
        "signalStrength": {
            "name": "Signal Strength",
            "control": {
                "type": "select",
                "value": 0
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 10; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }())
        }
    },
    "CELLULAR_NETWORK": {
        "status": {
            "name": "Status",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "event": "CellularNetworkStatusChanged",
            "callback": function (setting) {
                event.trigger("CellularNetworkStatusChanged", [setting]);
            }
        },
        "apn": {
            "name": "APN",
            "control": {
                "type": "text",
                "value": "Tizen"
            }
        },
        "ipAddress": {
            "name": "IP Address",
            "control": {
                "type": "text",
                "value": "10.0.2.16"
            }
        },
        "ipv6Address": {
            "name": "IPv6 Address",
            "control": {
                "type": "text",
                "value": "2001:db8:85a3:0:0:0:70:7334"
            }
        },
        "mcc": {
            "name": "MCC",
            "control": {
                "type": "number",
                "value": 460
            }
        },
        "mnc": {
            "name": "MNC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "cellId": {
            "name": "Cell ID",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "lac": {
            "name": "LAC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "isRoaming": {
            "name": "Roaming",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "isFlightMode": {
            "name": "Flight Mode",
            "control": {
                "type": "checkbox",
                "value": false
            },
            "callback": function (setting) {
                event.trigger("FlightModeChanged", [setting]);
            }
        },
        "imei": {
            "name": "IMEI",
            "control": {
                "type": "text",
                "value": "012417005203000"
            }
        }
    },
    "SIM": {
        "state": {
            "name": "State",
            "control": {
                "type": "select",
                "value": SimStateTable["READY"]
            },
            "options": (function () {
                var optionList = {};
                utils.forEach(SimStateTable, function (key, value) {
                    optionList[key] = SimStateTable[value];
                });

                return optionList;
            }())
        },
        "operatorName": {
            "name": "Operator Name",
            "control": {
                "type": "text",
                "value": "Tizen"
            }
        },
        "msisdn": {
            "name": "MSISDN",
            "control": {
                "type": "text",
                "value": "088123456789"
            }
        },
        "iccid": {
            "name": "ICCID",
            "control": {
                "type": "text",
                "value": "123000MFSSYYGXXXXXXP"
            }
        },
        "mcc": {
            "name": "MCC",
            "control": {
                "type": "number",
                "value": 460
            }
        },
        "mnc": {
            "name": "MNC",
            "control": {
                "type": "number",
                "value": 0
            }
        },
        "msin": {
            "name": "MSIN",
            "control": {
                "type": "text",
                "value": "H1 H2 H3 S 12345"
            }
        },
        "spn": {
            "name": "SPN",
            "control": {
                "type": "text",
                "value": "TizenSPN"
            }
        }
    },
    "PERIPHERAL": {
        "isVideoOutputOn": {
            "name": "Video Output",
            "control": {
                "type": "checkbox",
                "value": false
            }
        }
    }
};

});
define('ripple/platform/wearable/2.0/spec/sensor', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event');

function sensorStatusEventTrigger(setting) {
    event.trigger("SensorStatusChanged", [setting]);
}

module.exports = {
    "Accelerometer": {
        "resolution": 0.039239998906850815,
        "minDelay": 20,
        "range": 20.051639556884766,
        "name": "Accelerometer",
        "type": "Accelerometer"
    },
    "MagneticField": {
        "x": {
            "name": "X",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-xChanged", [setting]);
            }
        },

        "y": {
            "name": "Y",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-yChanged", [setting]);
            }
        },

        "z": {
            "name": "Z",
            "control": {
                "type": "range",
                "value": 100.0000000000000000,
                "min": 0.0000000000000000,
                "max": 200.0000000000000000,
                "step": 0.0000000000000001
            },
            "callback": function (setting) {
                event.trigger("MagneticField-zChanged", [setting]);
            }
        },

        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "MagneticField",
        "type": "MagneticField"
    },
    "Rotation": {
        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "Rotation",
        "type": "Rotation"
    },
    "Orientation": {
        "resolution": 1,
        "minDelay": 20,
        "range": 359,
        "name": "Orientation",
        "type": "Orientation"
    }
};

});
define('ripple/platform/wearable/2.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "sensors",
        "geoView",
        "widgetConfig",
        "deviceSettings",
        "application",
        "power",
        "package"
    ]
};

});
define('ripple/platform/wearable/2.0/spec', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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.
 */

module.exports = {

    id: "wearable",
    version: "2.0",
    name: "WEARABLE",

    persistencePrefix: "wearable2-",

    config: require('ripple/platform/wearable/2.0/spec/config'),
    ui: require('ripple/platform/wearable/2.0/spec/ui'),
    device: require('ripple/platform/wearable/2.0/spec/device'),
    sensor: require('ripple/platform/wearable/2.0/spec/sensor'),
    DeviceMotionEvent: require('ripple/platform/tizen/2.0/DeviceMotionEvent'),
    DeviceOrientationEvent: require('ripple/platform/tizen/2.0/DeviceOrientationEvent'),

    objects: {
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        SensorConnection: {
            path: "w3c/1.0/SensorConnection"
        },
        navigator: {
            path: "tizen/2.0/navigator",
            children: {
                geolocation: {
                    path: "wac/2.0/geolocation"
                },
                battery: {
                    path: "tizen/2.0/battery"
                }
            }
        },
        tizen: {
            feature: "http://tizen.org/privilege/tizen",
            children: {
                AlarmAbsolute: {
                    path: "tizen/2.0/AlarmAbsolute"
                },
                AlarmRelative: {
                    path: "tizen/2.0/AlarmRelative"
                },
                ApplicationControl: {
                    path: "tizen/2.0/ApplicationControl"
                },
                ApplicationControlData: {
                    path: "tizen/2.0/ApplicationControlData"
                },
                AttributeFilter: {
                    path: "tizen/2.0/AttributeFilter"
                },
                AttributeRangeFilter: {
                    path: "tizen/2.0/AttributeRangeFilter"
                },
                TZDate: {
                    path: "tizen/2.0/TZDate"
                },
                TimeDuration: {
                    path: "tizen/2.0/TimeDuration"
                },
                alarm: {
                    path: "tizen/2.0/alarm",
                    feature: "http://tizen.org/privilege/alarm",
                    handleSubfeatures: true
                },
                application: {
                    path: "tizen/2.0/application",
                    feature: "http://tizen.org/privilege/application.launch|http://tizen.org/privilege/appmanager.kill|http://tizen.org/privilege/appmanager.certificate",
                    handleSubfeatures: true
                },
                content: {
                    path: "tizen/2.0/content",
                    feature: "http://tizen.org/privilege/content.read|http://tizen.org/privilege/content.write",
                    handleSubfeatures: true
                },
                filesystem: {
                    path: "tizen/2.0/filesystem",
                    feature: "http://tizen.org/privilege/filesystem.read|http://tizen.org/privilege/filesystem.write"
                },
                package: {
                    path: "tizen/2.0/package",
                    feature: "http://tizen.org/privilege/packagemanager.install|http://tizen.org/privilege/package.info",
                    handleSubfeatures: true
                },
                power: {
                    path: "tizen/2.0/power",
                    feature: "http://tizen.org/privilege/power",
                    handleSubfeatures: true
                },
                systeminfo: {
                    path: "tizen/2.0/systeminfo",
                    feature: "http://tizen.org/privilege/system|http://tizen.org/privilege/systemmanager",
                    handleSubfeatures: true
                },
                time: {
                    path: "tizen/2.0/time",
                    feature: "http://tizen.org/privilege/time",
                    handleSubfeatures: true
                }
            }
        }
    }
};

});
define('ripple/platform/wearable/2.0/typecast', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 typedef = require('ripple/platform/wearable/2.0/typedef'),
    errorcode = require('ripple/platform/wearable/2.0/errorcode'),
    WebAPIException = require('ripple/platform/wearable/2.0/WebAPIException'),
    TypeCoerce = require('ripple/platform/wearable/2.0/typecoerce'),
    _self = {};

function _cast(pattern, obj, isDuplicate) {
    var tc, tcFunc;

    if (pattern === null)
        return;

    tc = new TypeCoerce(pattern);
    tcFunc = isDuplicate ? tc.copy : tc.cast;

    if ((obj = tcFunc(obj)) === null) {
        throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
    }

    return obj;
}

function _castType(pattern) {
    /*
     * Type cast for each known type. The function name is the exact name of the
     * corresponding type.
     *
     * obj
     *    Variable to be casted
     *
     * aux
     *    Auxiliary descriptor of obj. It can be any one or combination of below
     *    strings, or ignored in most cases.
     *
     *    "?"     Nullable types
     *    "[]"    Array
     *    "+"     Deep copy
     *
     * Return
     *    Casted or duplicated object.
     */

    return function (obj, aux) {
        var type, isNullable, isDuplicate;

        aux = aux ? String(aux) : "";
        type = (aux.indexOf("[]") !== -1) ? [pattern] : pattern;
        isNullable = (aux.indexOf("?") !== -1);
        isDuplicate = (aux.indexOf("+") !== -1);

        if (isNullable && ((obj === null) || (obj === undefined))) {
            return obj;
        }

        return _cast(type, obj, isDuplicate);
    };
}

function _castConstructor(name) {
    var constructors, hook, vtc, isOverloaded, castConstructor;

    /*
     * Type cast for constructor. The function name is the exact name of the
     * object type.
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     */

    function castUnique(argv) {
        _cast(constructors, argv, false);
    }

    /*
     * Type cast for overloaded constructors. The function name is the exact
     * name of the object type.
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     *
     * scope
     *    'this' of the original constructor.
     *
     * voc
     *    Array of overloaded constructors callback
     */

    function castOverload(argv, scope, voc) {
        var iOverload;

        if (!vtc) {
            vtc = [];
            constructors.forEach(function (c) {
                vtc.push((c === null) ? null : new TypeCoerce(c));
            });
        }

        vtc.some(function (tc, index) {
            if (tc && (tc.cast(argv) === null))
                return false;

            iOverload = index;
            return true;
        });

        if (iOverload === undefined) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR);
        }

        return (voc && voc[iOverload].apply(scope, argv));
    }

    constructors = typedef.constructor[name];

    if (name in _self) {
        hook = _self[name];
    }

    isOverloaded = (Object.prototype.toString.call(constructors) ===
            "[object Array]");
    castConstructor = isOverloaded ? castOverload : castUnique;

    return function (argv, scope) {
        if (Object.prototype.toString.call(argv) !== "[object Arguments]") {
            return (hook && hook.apply(this, arguments));
        }

        if (!(scope instanceof argv.callee)) {
            throw new WebAPIException(errorcode.TYPE_MISMATCH_ERR, null, "TypeError");
        }

        castConstructor.apply(this, arguments);
    };
}

function _castInterface(name) {
    var interface, hook;

    interface = typedef.interface[name];

    if (name in _self) {
        hook = _self[name];
    }

    /*
     * Type cast for each known method of interface. The function name is the
     * exact name of the corresponding interface.
     *
     * method
     *    String of method name
     *
     * argv
     *    arguments. The keyword 'arguments' will always be passed in.
     *
     * isDuplicate
     *    A boolean value to indicate whether arguments will be copied or not.
     */

    return function (method, argv, isDuplicate) {
        if ((typeof method !== "string") || (typeof argv !== "object")) {
            return (hook && hook.apply(this, arguments));
        }

        _cast(interface[method], argv, isDuplicate);
    };
}

(function () {
    var i;

    for (i in typedef) {
        _self[i] = _castType(typedef[i]);
    }

    for (i in typedef.constructor) {
        _self[i] = _castConstructor(i);
        typedef[i]._constructor = i;
    }

    for (i in typedef.interface) {
        _self[i] = _castInterface(i);
    }
}());

module.exports = _self;

});
define('ripple/platform/wearable/2.0/typecoerce', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 t = require('ripple/platform/wearable/2.0/typedef'),
    _MAX_INT_BITS = 53,
    _MAX_INT = Math.pow(2, _MAX_INT_BITS) - 1,
    _self;

_self = function (pattern) {
    var typeCoerce, typeOfPattern;

    // private
    function getExtendedType(val) {
        var type = Object.prototype.toString.call(val), attr;

        switch (type) {
        case "[object Array]":
            if ((typeof val[0] === "string") && (val[0].length > 0)) {
                type = "enum";
            } else {
                type = "Union";
            }
            return type;

        case "[object Object]":
            if ("_dictionary" in val) {
                return "dictionary";
            }

            type = "Object";

            for (attr in val) {
                if (attr === "0") {
                    type = "Arguments";
                } else if (val[attr] === "Callback") {
                    type = "Callback";
                }
                break;
            }

            return type;
        }

        switch (val) {
        case "Callback":
            type = "Function";
            break;

        case "TZDate":
        case "any":
        case "byte":
        case "float":
        case "long":
        case "long long":
        case "octet":
        case "short":
        case "unsigned long":
        case "unsigned long long":
        case "unsigned short":
            type = val;
            break;

        case "double":
            type = "float";
            break;

        default:    // Derivative type name: e.g., "AbstractFilter"
            type = "";
            break;
        }

        return type;
    }

    function getType(val, isPattern) {
        var type = Object.prototype.toString.call(val);

        switch (type) {
        case "[object Array]":
            type = (isPattern && (val.length > 1)) ? getExtendedType(val) :
                    "Array";
            break;

        case "[object Arguments]":
            type = "Arguments";
            break;

        case "[object Boolean]":
            type = "boolean";
            break;

        case "[object Date]":
            type = "Date";
            break;

        case "[object Function]":
            type = "Function";
            break;

        case "[object Number]":
            type = "Number";
            break;

        case "[object Object]":
            type = isPattern ? getExtendedType(val) : "Object";
            break;

        case "[object String]":
            type = (isPattern && !!val) ? getExtendedType(val) : "DOMString";
            break;
        }

        return type;
    }

    function isConstructed(obj) {
        if (!("_constructor" in pattern))
            return true;

        if (obj instanceof window.tizen[pattern._constructor])
            return true;

        if ("_derived" in pattern)
            return true;

        return false;
    }

    function toInteger(x) {
        return (x < 0) ? Math.ceil(x) : Math.floor(x);
    }

    function isBitsOverflowed(bits) {
        return (bits >= _MAX_INT_BITS);
    }

    function toJsInt(x, isUnsigned) {
        var min, max;

        min = isUnsigned ? 0 : -_MAX_INT;
        max = _MAX_INT;

        if ((x < min) || (x > max))
            return null;

        return toInteger(x);
    }

    function modulo(a, b) {
        return (a - Math.floor(a / b) * b);
    }

    function toInt(x, bits) {
        var p;

        x = Number(x);

        if (isNaN(x) || !isFinite(x))
            return null;

        if (isBitsOverflowed(bits))
            return toJsInt(x, false);

        p = Math.pow(2, bits);
        x = modulo(toInteger(x), p);

        return (x >= Math.pow(2, bits - 1)) ? (x - p) : x;
    }

    function toUInt(x, bits) {
        x = Number(x);

        if (isNaN(x) || !isFinite(x))
            return null;

        if (isBitsOverflowed(bits))
            return toJsInt(x, true);

        return modulo(toInteger(x), Math.pow(2, bits));
    }

    function toInt8(x) {
        return toInt(x, 8);
    }

    function toInt16(x) {
        return toInt(x, 16);
    }

    function toInt32(x) {
        return toInt(x, 32);
    }

    function toInt64(x) {
        return toInt(x, 64);
    }

    function toUInt8(x) {
        return toUInt(x, 8);
    }

    function toUInt16(x) {
        return toUInt(x, 16);
    }

    function toUInt32(x) {
        return toUInt(x, 32);
    }

    function toUInt64(x) {
        return toUInt(x, 64);
    }

    // public
    function cast(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Arguments": function () {
                var i, isNullable, ret;

                for (i in pattern) {
                    if (i === "_optional")
                        continue;

                    isNullable = !!(pattern._optional && pattern._optional[i]);

                    if (i > obj.length - 1) {
                        if (!isNullable) {
                            return null;
                        }
                        break;
                    }

                    if (!isNullable || (obj[i] !== null)) {
                        ret = _self(pattern[i]).cast(obj[i]);
                        if (ret === null) {
                            return null;
                        }
                        obj[i] = ret;
                    }
                }

                return obj;
            },

            "Array": function () {
                var elementType, i, ret;

                if (typeOfObj !== typeOfPattern) {
                    return null;
                }

                elementType = _self(pattern[0]);
                for (i in obj) {
                    ret = elementType.cast(obj[i]);
                    if (ret === null) {
                        return null;
                    }
                    obj[i] = ret;
                }

                return obj;
            },

            "Callback": function () {
                var attr;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        obj[attr] = _self(pattern[attr]).cast(obj[attr]);
                        if (obj[attr] === null) {
                            return null;
                        }
                    }
                }

                return obj;
            },

            "DOMString": function () {
                switch (typeOfObj) {
                case "DOMString":
                case "Date":
                case "Number":
                case "boolean":
                    obj = String(obj);
                    break;

                default:
                    if ((obj === null) || (obj === undefined)) {
                        obj = String(obj);
                    } else {
                        obj = null;
                    }
                    break;
                }

                return obj;
            },

            "Date": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "Function": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "Object": function () {
                var ret, attr, i;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return null;
                    }
                    if (!("_derived" in pattern)) {
                        return null;
                    }
                }

                if (!isConstructed(obj)) {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            ret = _self(pattern._derived[i]).cast(obj);
                            if (ret !== null)
                                break;
                        }
                        if (ret === null) {
                            if ("_constructor" in pattern)
                                break;

                            return null;
                        }
                        break;

                    default:
                        if (!pattern._optional || !pattern._optional[attr] ||
                                (obj[attr] !== undefined) &&
                                (obj[attr] !== null)) {
                            ret = _self(pattern[attr]).cast(obj[attr]);
                            if (ret === null) {
                                return null;
                            }
                            obj[attr] = ret;
                        }
                        break;
                    }
                }

                return obj;
            },

            "TZDate": function () {
                if (typeOfObj !== "Object") {
                    return null;
                }
                return (obj instanceof window.tizen.TZDate) ? obj : null;
            },

            "Union": function () {
                var ret, i;

                for (i in pattern) {
                    ret = _self(pattern[i]).cast(obj);
                    if (ret !== null)
                        break;
                }

                return ret;
            },

            "any": function () {
                return obj;
            },

            "boolean": function () {
                return (typeOfObj === typeOfPattern) ? obj : null;
            },

            "byte": function () {
                return toInt8(obj);
            },

            "dictionary": function () {
                var attr, ret;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            ret = _self(pattern._dictionary).cast(obj);
                            if (ret === null) {
                                return null;
                            }
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            ret = _self(pattern[attr]).cast(obj[attr]);
                            if (ret === null) {
                                return null;
                            }
                            obj[attr] = ret;
                        }
                        break;
                    }
                }

                return obj;
            },

            "enum": function () {
                var i;

                obj = String(obj).trim();
                for (i in pattern) {
                    if (obj === pattern[i]) {
                        return obj;
                    }
                }

                return null;
            },

            "float": function () {
                var f = parseFloat(obj, 10);

                return (isNaN(f) ? null : f);
            },

            "long": function () {
                return toInt32(obj);
            },

            "long long": function () {
                return toInt64(obj);
            },

            "octet": function () {
                return toUInt8(obj);
            },

            "short": function () {
                return toInt16(obj);
            },

            "unsigned long": function () {
                return toUInt32(obj);
            },

            "unsigned long long": function () {
                return toUInt64(obj);
            },

            "unsigned short": function () {
                return toUInt16(obj);
            },

            "": function () {
                return _self(t[pattern]).cast(obj);
            }
        };

        return typeMap[typeOfPattern]();
    }

    function copy(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Arguments": function () {
                var i, isNullable, ret = [];

                for (i in pattern) {
                    if (i === "_optional")
                        continue;

                    isNullable = !!(pattern._optional && pattern._optional[i]);

                    if (i > obj.length - 1) {
                        if (!isNullable) {
                            return null;
                        }
                        break;
                    }

                    if (!isNullable || (obj[i] !== null)) {
                        ret[i] = _self(pattern[i]).copy(obj[i]);
                        if (ret[i] === null) {
                            return null;
                        }
                    }
                }

                for (i in ret) {
                    obj[i] = ret[i];
                }

                return obj;
            },

            "Array": function () {
                var arr = [], elementType, i;

                if (typeOfObj !== typeOfPattern) {
                    return null;
                }

                elementType = _self(pattern[0]);
                for (i in obj) {
                    if (obj[i] !== undefined) {
                        arr[i] = elementType.copy(obj[i]);
                        if (arr[i] === null)
                            return null;
                    }
                }

                return arr;
            },

            "Callback": function () {
                var ret = {}, attr;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                        if (ret[attr] === null) {
                            return null;
                        }
                    }
                }

                return ret;
            },

            "Object": function () {
                var ret = {}, attr, i, derived;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return null;
                    }
                    if (!("_derived" in pattern)) {
                        return null;
                    }
                }

                if (!isConstructed(obj)) {
                    return null;
                }
                if ("_constructor" in pattern) {
                    ret.__proto__ = window.tizen[pattern._constructor].prototype;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            derived = _self(pattern._derived[i]).copy(obj);
                            if (derived !== null)
                                break;
                        }
                        if (derived === null) {
                            if ("_constructor" in pattern)
                                break;

                            return null;
                        }
                        for (attr in derived) {
                            ret[attr] = derived[attr];
                        }
                        break;

                    default:
                        if (!pattern._optional || !pattern._optional[attr] ||
                                (obj[attr] !== undefined) &&
                                (obj[attr] !== null)) {
                            ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                            if (ret[attr] === null) {
                                return null;
                            }
                        }
                        break;
                    }
                }

                return ret;
            },

            "Union": function () {
                var ret, i;

                for (i in pattern) {
                    ret = _self(pattern[i]).copy(obj);
                    if (ret !== null)
                        break;
                }

                return ret;
            },

            "dictionary": function () {
                var ret = {}, attr, base, i;

                if (typeOfObj !== "Object") {
                    return null;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            base = _self(pattern._dictionary).copy(obj);
                            if (base === null) {
                                return null;
                            }
                            for (i in base) {
                                ret[i] = base[i];
                            }
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            ret[attr] = _self(pattern[attr]).copy(obj[attr]);
                            if (ret[attr] === null) {
                                return null;
                            }
                        }
                        break;
                    }
                }

                return ret;
            },

            "": function () {
                return _self(t[pattern]).copy(obj);
            }
        };

        return (typeOfPattern in typeMap) ? typeMap[typeOfPattern]() :
                cast(obj);
    }

    function match(obj) {
        var typeMap,
            typeOfObj = getType(obj, false);

        typeMap = {
            "Array": function () {
                var elementType, i;

                if (typeOfObj !== typeOfPattern)
                    return false;

                elementType = _self(pattern[0]);
                for (i in obj) {
                    if (!elementType.match(obj[i])) {
                        return false;
                    }
                }

                return true;
            },

            "Callback": function () {
                var attr, isMatched = true;

                if (typeOfObj !== "Object") {
                    return false;
                }

                for (attr in pattern) {
                    if (attr in obj) {
                        isMatched = _self(pattern[attr]).match(obj[attr]);
                        if (!isMatched) {
                            break;
                        }
                    }
                }

                return isMatched;
            },

            "DOMString": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Date": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Function": function () {
                return (typeOfObj === typeOfPattern);
            },

            "Object": function () {
                var attr, isMatched = false, i;

                if (typeOfObj !== typeOfPattern) {
                    if ((obj === null) || (obj === undefined)) {
                        return false;
                    }
                    if (!("_derived" in pattern)) {
                        return false;
                    }
                    return false;
                }

                if (!isConstructed(obj)) {
                    return false;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_optional":
                    case "_constructor":
                        break;

                    case "_derived":
                        for (i in pattern._derived) {
                            isMatched = _self(pattern._derived[i]).match(obj);
                            if (isMatched)
                                break;
                        }
                        break;

                    default:
                        if (pattern._optional && pattern._optional[attr]) {
                            isMatched = ((obj[attr] === null) ||
                                    (obj[attr] === undefined) ||
                                    _self(pattern[attr]).match(obj[attr]));
                        } else {
                            isMatched = (obj[attr] !== undefined) &&
                                    _self(pattern[attr]).match(obj[attr]);
                        }
                        break;
                    }

                    if (!isMatched)
                        break;
                }

                /*// Check if verbose attributes are present
                if (isMatched) {
                    for (attr in obj) {
                        if (pattern[attr] === undefined) {
                            isMatched = false;
                            break;
                        }
                    }
                }*/

                return isMatched;
            },

            "Union": function () {
                var isMatched, i;

                for (i in pattern) {
                    isMatched = _self(pattern[i]).match(obj);
                    if (isMatched)
                        break;
                }

                return isMatched;
            },

            "any": function () {
                return true;
            },

            "boolean": function () {
                return (typeOfObj === typeOfPattern);
            },

            "byte": function () {
                return (obj === toInt8(obj));
            },

            "dictionary": function () {
                var attr, isMatched = true;

                if (typeOfObj !== "Object") {
                    return false;
                }

                for (attr in pattern) {
                    switch (attr) {
                    case "_dictionary":
                        if (pattern._dictionary !== null) {
                            isMatched = _self(pattern._dictionary).match(obj);
                            if (!isMatched)
                                break;
                        }
                        break;

                    default:
                        if ((attr in obj) && (obj[attr] !== null) &&
                                (obj[attr] !== undefined)) {
                            isMatched = _self(pattern[attr]).match(obj[attr]);
                            if (!isMatched)
                                break;
                        }
                        break;
                    }
                }

                return isMatched;
            },

            "enum": function () {
                for (var i in pattern) {
                    if (obj === pattern[i]) {
                        return true;
                    }
                }

                return false;
            },

            "float": function () {
                return (typeOfObj === "Number");
            },

            "long": function () {
                return (obj === toInt32(obj));
            },

            "long long": function () {
                return (obj === toInt64(obj));
            },

            "octet": function () {
                return (obj === toUInt8(obj));
            },

            "short": function () {
                return (obj === toInt16(obj));
            },

            "unsigned long": function () {
                return (obj === toUInt32(obj));
            },

            "unsigned long long": function () {
                return (obj === toUInt64(obj));
            },

            "unsigned short": function () {
                return (obj === toUInt16(obj));
            },

            "Arguments": function () {
                return true;
            },

            "": function () {
                return _self(t[pattern]).match(obj);
            }
        };

        return typeMap[typeOfPattern]();
    }

    typeOfPattern = getType(pattern, true);

    typeCoerce = {
        cast:  cast,
        copy:  copy,
        match: match
    };

    return typeCoerce;
};

module.exports = _self;

});
define('ripple/platform/wearable/2.0/typedef', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 _t, _c, _i;

/*
 * Primitive type definition
 */

_t = {
    // Basic
    Callback:                       "Callback",
    DOMString:                      "",
    Date:                           new Date(),
    Function:                       function () {},
    TZDate:                         "TZDate",
    any:                            "any",
    boolean:                        false,
    byte:                           "byte",
    double:                         "double",
    float:                          "float",
    long:                           "long",
    octet:                          "octet",
    short:                          "short",
    long_long:                      "long long",
    unsigned_long:                  "unsigned long",
    unsigned_long_long:             "unsigned long long",
    unsigned_short:                 "unsigned short",

    // Motion
    MotionType:                     ["PEDOMETER", "WRIST_UP"],
    // SAP
    AuthenticationType:             ["AUTHENTICATION_TYPE_NONE",
                                     "AUTHENTICATION_TYPE_CERTIFICATE_X509"],
    TransportType:                  ["TRANSPORT_BLE", "TRANSPORT_BT",
                                     "TRANSPORT_USB", "TRANSPORT_WIFI"]
};

/*
 * Derivative type definition
 */

/*
 * Object attributes
 *     Contruct a prototype of an object. Specify a primitive type for each attribute.
 *
 * _optional
 *     Optional attributes table, which consists of two types of attributes,
 *
 *     nullable
 *         Nullable attributes, marked as '?' in IDL.
 *
 *     undefined
 *         Array type attributes, that not definitely specified to be
 *         initialized as an empty array, i.e., undefined-initialized array.
 *
 * _derived
 *     Derived types, which used in two cases of definition,
 *
 *     Subtype list
 *         An array consists of derived subtypes. It exists in the definition of
 *         a base type.
 *
 *     Union types
 *         An array consists of member types. It exists in the definition of
 *         a union type.
 *
 * _dictionary
 *     Dictionary type, which indicates that the object is a dictionary type.
 */

/*
 * IrLed
 */

_t.SuccessCallback = _t.Function;
_t.ErrorCallback   = _t.Function;

/*
 * Motion
 */

_t.MotionInfoSuccessCallback = _t.Function;

/*
 * SAP
 */

_t.SAAgentSuccessCallback = _t.Function;
_t.SADeviceStatusCallback = _t.Function;
_t.SAAuthenticatePeerAgentSuccessCallback = _t.Function;
_t.SADataReceiveCallback = _t.Function;
_t.SASocketStatusCallback = _t.Function;

_t.ServiceConnectionCallback = {
    onrequest: _t.Callback,
    onconnect: _t.Callback,
    onerror:   _t.Callback
};

_t.SAPeerAgentFindCallback = {
    onpeeragentfound:   _t.Callback,
    onpeeragentupdated: _t.Callback,
    onerror:            _t.Callback
};

_t.SAPeerAccessory = {
    deviceAddress: _t.DOMString,
    deviceName:    _t.DOMString,
    productId:     _t.DOMString,
    transportType: _t.TransportType,
    vendorId:      _t.DOMString
};

_t.SAPeerAgent = {
    peerAccessory:      _t.SAPeerAccessory,
    appName:            _t.DOMString,
    maxAllowedDataSize: _t.long,
    peerId:             _t.DOMString,
    profileVersion:     _t.DOMString
};

_t.SAFileSendCallback = {
    onprogress: _t.Callback,
    oncomplete: _t.Callback,
    onerror:    _t.Callback
};

_t.SAFileReceiveCallback = {
    onreceive:  _t.Callback,
    onprogress: _t.Callback,
    oncomplete: _t.Callback,
    onerror:    _t.Callback
};

/*
 * Constructor list definition
 */

/*
 * Generic constructor
 *     Construct a prototype of constructor. A fake array of arguments type is
 *     specified for constructor.
 *
 * Overloaded constructors
 *     Construct an array of prototype of constructor. Each array element is
 *     specified for one of constructors. The constructor with extra arguments
 *     are recommended to be defined ahead of the one with fewer same arguments
 *     for exact match.
 */

_c = {};

/*
 * Interface prototype definition
 */

_i = {
    // IrLed
    IrLedManager:    {},

    // Motion
    MotionManager:   {},

    // SAP
    SAManager:       {},
    SAAgent:         {},
    SASocket:        {},
    SAFileTransfer:  {}
};

// IrLed
_i.IrLedManager.send = {
    0: _t.DOMString,
    1: _t.SuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        // nullable
        1: true,
        2: true
    }
};

// Motion
_i.MotionManager.getMotionInfo = {
    0: _t.MotionType,
    1: _t.MotionInfoSuccessCallback,
    2: _t.ErrorCallback,

    _optional: {
        // nullable
        2: true
    }
};

_i.MotionManager.start = {
    0: _t.MotionType,
    1: _t.MotionInfoSuccessCallback,

    _optional: {
        // nullable
        1: true
    }
};

_i.MotionManager.stop = {
    0: _t.MotionType
};

/*
 * SAP
 */

// SAManager
_i.SAManager.requestSAAgent = {
    0: _t.SAAgentSuccessCallback,
    1: _t.ErrorCallback,

    _optional: {
        // nullable
        1: true
    }
};

_i.SAManager.setDeviceStatusListener = {
    0: _t.SADeviceStatusCallback
};

// SAAgent
_i.SAAgent.requestServiceConnection = {
    0: _t.SAPeerAgent
};

_i.SAAgent.setServiceConnectionListener = {
    0: _t.ServiceConnectionCallback
};

_i.SAAgent.authenticatePeerAgent = {
    0: _t.SAPeerAgent,
    1: _t.SAAuthenticatePeerAgentSuccessCallback,
};

_i.SAAgent.acceptServiceConnectionRequest = {
    0: _t.SAPeerAgent
};

_i.SAAgent.rejectServiceConnectionRequest = {
    0: _t.SAPeerAgent
};

_i.SAAgent.findPeerAgents = null;

_i.SAAgent.setPeerAgentFindListener = {
    0: _t.SAPeerAgentFindCallback
};

_i.SAAgent.getSAFileTransfer = null;

// SASocket
_i.SASocket.close = null;

_i.SASocket.isConnected = null;

_i.SASocket.sendData = {
    0: _t.long,
    1: _t.DOMString
};

_i.SASocket.sendSecureData = {
    0: _t.long,
    1: _t.DOMString
};

_i.SASocket.setDataReceiveListener = {
    0: _t.SADataReceiveCallback
};

_i.SASocket.setSocketStatusListener = {
    0: _t.SASocketStatusCallback
};

// SAFileTransfer
_i.SAFileTransfer.sendFile = {
    0: _t.SAPeerAgent,
    1: _t.DOMString
};

_i.SAFileTransfer.setFileSendListener = {
    0: _t.SAFileSendCallback
};

_i.SAFileTransfer.setFileReceiveListener = {
    0: _t.SAFileReceiveCallback
};

_i.SAFileTransfer.receiveFile = {
    0: _t.long,
    1: _t.DOMString
};

_i.SAFileTransfer.cancelFile = {
    0: _t.long
};

_i.SAFileTransfer.rejectFile = {
    0: _t.long
};

// Exports
_t.constructor = _c;
_t.interface   = _i;

module.exports = _t;

});
define('ripple/platform/web/default/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
window.addEventListener("load", function () {
    var event = require('ripple/event');

    event.on("HardwareKey", function (key) {
        event.trigger("HardwareKeyDefault", [key]);
    });

    //HACK: Remove this guy from namespace since we are just hacking this in as a bootstrapper
    delete window.device;
});

});
define('ripple/platform/web/default/spec/ui', function (require, exports, module) {
module.exports = {
    plugins: [
        "accelerometer",
        "geoView"
    ]
};

});
define('ripple/platform/web/default/spec', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */

module.exports = {

    id: "web",
    version: "default",
    name: "Mobile Web",

    ui: require('ripple/platform/web/default/spec/ui'),
    device: {},

    persistencePrefix: "tinyhippos-",

    initialize: function () {},

    objects: {
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        navigator: {
            path: "w3c/1.0/navigator",
            children: {
                geolocation: {
                    path: "w3c/1.0/geolocation"
                }
            }
        },
        device: {
            path: "web/default/device"
        }
    },
};

});
define('ripple/platform/webworks.bb10/1.0.0/app', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    app = require('ripple/app'),
    notifications = require('ripple/notifications'),
    _uri = "blackberry/app/",
    _self;

_self = {
    exit: function () {
        notifications.openNotification("normal", "blackberry.app.exit() was called, in the real world your app will exit, here... you get this notification");
    }
};

_self.__defineGetter__("author", function () {
    return app.getInfo().author;
});

_self.__defineGetter__("authorEmail", function () {
    return app.getInfo().authorEmail;
});

_self.__defineGetter__("authorURL", function () {
    return app.getInfo().authorURL;
});

_self.__defineGetter__("copyright", function () {
    return app.getInfo().copyright;
});

_self.__defineGetter__("description", function () {
    return app.getInfo().description;
});

_self.__defineGetter__("id", function () {
    return app.getInfo().id;
});

_self.__defineGetter__("license", function () {
    return app.getInfo().license;
});

_self.__defineGetter__("licenseURL", function () {
    return app.getInfo().licenseURL;
});

_self.__defineGetter__("name", function () {
    return app.getInfo().name;
});

_self.__defineGetter__("version", function () {
    return app.getInfo().version;
});

module.exports = _self;

});
define('ripple/platform/webworks.bb10/1.0.0/connection', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 deviceSettings = require('ripple/deviceSettings'),
    _self = {};

_self.__defineGetter__("type", function () {
    return deviceSettings.retrieve("NetworkStatus.connectionType");
});

_self.__defineGetter__("UNKNOWN", function () { return "unknown"; });
_self.__defineGetter__("ETHERNET", function () { return "ethernet"; });
_self.__defineGetter__("WIFI", function () { return "wifi"; });
_self.__defineGetter__("BLUETOOTH_DUN", function () { return "bluetooth_dun"; });
_self.__defineGetter__("USB", function () { return "usb"; });
_self.__defineGetter__("VPN", function () { return "vpn"; });
_self.__defineGetter__("BB", function () { return "rim-bb"; });
_self.__defineGetter__("CELL_2G", function () { return "2g"; });
_self.__defineGetter__("CELL_3G", function () { return "3g"; });
_self.__defineGetter__("CELL_4G", function () { return "4g"; });
_self.__defineGetter__("NONE", function () { return "none"; });

module.exports = _self;

});
define('ripple/platform/webworks.bb10/1.0.0/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 devices = require('ripple/devices'),
    _self = {};

_self.__defineGetter__("softwareVersion", function () {
    return devices.getCurrentDevice().osVersion;
});

_self.__defineGetter__("hardwareId", function () {
    return devices.getCurrentDevice().hardwareId;
});
module.exports = _self;

});
define('ripple/platform/webworks.bb10/1.0.0/dialog', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    ui = require('ripple/ui'),
    event = require('ripple/event'),
    isDialogVisible = false,
    visibleDialogArgs,
    utils = require('ripple/utils');

function getButtonsForDialogType(dialogType) {
    switch (dialogType) {
    case _self.D_OK:
        return ["Ok"];
    case _self.D_SAVE:
        return ["Save", "Discard"];
    case _self.D_DELETE:
        return ["Delete", "Cancel"];
    case _self.D_YES_NO:
        return ["Yes", "No"];
    case _self.D_OK_CANCEL:
        return ["Ok", "Cancel"];
    default:
        throw new Error("Invalid dialog type: " + dialogType);
    }
}

event.on("LayoutChanged", function () {
    if (isDialogVisible) {
        closeDialog();
        //Used to resize dialog on orientation change
        _self.ask(visibleDialogArgs);
    }
});

function closeDialog() {
    var buttonsDiv = document.getElementById("dialog-buttons"),
        messageDiv = document.getElementById("dialog-message");

    ui.hideOverlay("dialog-window", function (dialog) {
        buttonsDiv.innerHTML = "";
        messageDiv.innerHTML = "";
        isDialogVisible = false;
    });
}

function ask(args, callback) {
    if (!args) {
        throw ("No arguments provided");
    } else if (!args.buttons || !args.message) {
        throw ("Invalid arguments");
    }
    visibleDialogArgs = args;

    ui.showOverlay("dialog-window", function (dialog) {
        var container = document.getElementById("viewport-container"),
            height = window.getComputedStyle(container, null).getPropertyValue("height"),
            width = window.getComputedStyle(container, null).getPropertyValue("width"),
            sizeDiv = document.getElementById("dialog-wrapper"),
            positionDiv = document.getElementById("dialog-window"),
            titleDiv = document.getElementById("dialog-title"),
            buttonsDiv = document.getElementById("dialog-buttons"),
            messageDiv = document.getElementById("dialog-message"),
            position, size;

        if (!messageDiv || !buttonsDiv) {
            return;
        }

        dialog.setAttribute("style", "display:-webkit-box;height:" + height + "; width:" + width + ";");

        position = "overlay-dialog";
        size = "overlay-dialog-wrapper";

        if (args.settings && args.settings.position) {
            position += " overlay-dialog-" + args.settings.position;
        }

        if (args.settings && args.settings.size) {
            size += " overlay-dialog-wrapper-" + args.settings.size;
        }

        positionDiv.setAttribute("class", position);
        sizeDiv.setAttribute("class", size);

        titleDiv.innerHTML = args.settings && args.settings.title ? args.settings.title : "";
        messageDiv.innerHTML = args.message;
        isDialogVisible = true;

        args.buttons.forEach(function (button) {
            var buttonElement = utils.createElement("input", {
                "type": "button",
                "value": button
            });
            buttonElement.addEventListener("click", function () {
                var buttonIndex = args.buttons.indexOf(button);
                closeDialog();
                callback(buttonIndex);
            });
            buttonsDiv.appendChild(buttonElement);
        });
    }, true);
}

_self = {
    customAskAsync: function (message, choices, callback, settings) {
        ask({
            message: message,
            buttons: choices,
            settings: settings
        }, function (response) {
            if (callback) {
                callback(response);
            }
        });
    },

    standardAskAsync: function (message, type, callback, settings) {
        var choices = getButtonsForDialogType(type);
        ask({ 
            message: message, 
            buttons: choices, 
            settings: settings
        }, function (response) {
            if (callback) {
                callback(response);
            }
        });
    }
};

_self.__defineGetter__("D_OK", function () {
    return 0;
});

_self.__defineGetter__("D_SAVE", function () {
    return 1;
});

_self.__defineGetter__("D_DELETE", function () {
    return 2;
});

_self.__defineGetter__("D_YES_NO", function () {
    return 3;
});

_self.__defineGetter__("D_OK_CANCEL", function () {
    return 4;
});

_self.__defineGetter__("BOTTOM", function () {
    return "bottomCenter";
});

_self.__defineGetter__("CENTER", function () {
    return "middleCenter";
});

_self.__defineGetter__("TOP", function () {
    return "topCenter";
});

_self.__defineGetter__("SIZE_FULL", function () {
    return "full";
});

_self.__defineGetter__("SIZE_LARGE", function () {
    return "large";
});

_self.__defineGetter__("SIZE_MEDIUM", function () {
    return "medium";
});

_self.__defineGetter__("SIZE_SMALL", function () {
    return "small";
});

_self.__defineGetter__("SIZE_TALL", function () {
    return "tall";
});

module.exports = _self;

});
define('ripple/platform/webworks.bb10/1.0.0/event', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    settings = require('ripple/deviceSettings'),
    app = require('ripple/app'),
    cons = require('ripple/console'),
    utils = require('ripple/utils'),
    events = {
        batterystatus: {
            callbacks: [],
            feature: 'blackberry.system' 
        },
        batterylow: {
            callbacks: [],
            feature: 'blackberry.system'
        },
        batterycritical: {
            callbacks: [],
            feature: 'blackberry.system'
        },
        connectionchange: {
            callbacks: [],
            feature: 'blackberry.connection'
        },
        invoked: {
            callbacks: [],
            feature: 'blackberry.invoked'
        },
        swipedown: {
            callbacks: [],
            feature: 'blackberry.app'
        },
        resume: {
            callbacks: [],
            feature: 'blackberry.app'
        },
        pause: {
            callbacks: [],
            feature: 'blackberry.app'
        },
        languagechange: {
            callbacks: [],
            feature: "blackberry.system"
        },
        regionchange: {
            callbacks: [],
            feature: "blackberry.system"
        }
    };

function _apply(eventName, args) {
    events[eventName].callbacks.forEach(function (cb) {
        cb.apply(null, args);
    });
}

event.on('DeviceBatteryStateChanged', function (charging) {
    var info = {
        isPlugged: charging,
        level: parseInt(settings.retrieve('battery.level'), 10)
    };

    _apply('batterystatus', [info]);
});

event.on('DeviceBatteryLevelChanged', function (level) {
    var info = {
        isPlugged: settings.retrieve('battery.state'),
        level: parseInt(level, 10)
    };

    _apply('batterystatus', [info]);
    
    if (level === '14') {
        _apply('batterylow', [info]);
    }

    if (level === '4') {
        _apply('batterycritical', [info]);
    }
});

event.on('DeviceConnectionChanged', function (info) {
    _apply('connectionchange', [info]);
});

event.on("LanguageChanged", function (lang) {
    _apply("languagechange", [lang]);
});

event.on("RegionChanged", function (lang) {
    _apply("regionchange", [lang]);
});

event.on("AppInvoke", function (invokeInfo) {
    var invokeTargets = app.getInfo().invokeTargets;

    if (!invokeTargets) {
        cons.log("The application cannot be invoked, please add a rim:invoke-target node in config.xml");
        return;
    }

    if (invokeTargets.some(function (target) {
        return target.filter.some(function (filter) {
            return (
                (!filter.property ||
                (filter.property && filter.property[0]["@attributes"].var === "exts" && filter.property[0]["@attributes"].value.split(",").some(function (value) {
                    return invokeInfo.extension.match(value);
                })) ||
                (filter.property && filter.property[0]["@attributes"].var === "uris" && filter.property[0]["@attributes"].value.split(",").some(function (value) {
                    return invokeInfo.uri.match(value);
                }))) &&
                filter.action.some(function (action) {
                    return invokeInfo.action.match(action["#text"][0].replace("*", ""));
                }) &&
                filter["mime-type"].some(function (type) {
                    return invokeInfo.type.match(type["#text"][0].replace("*", ""));
                })
            );
        });
    })) {
        _apply('invoked', [invokeInfo]);
    }
    else {
        cons.log("Cannot invoke application, values enter to not match values in rim:invoke-target in config.xml");
    }
});

event.on('AppSwipeDown', function () {
    _apply('swipedown');
});

event.on('AppResume', function () {
    _apply('resume');
});

event.on('AppPause', function () {
    _apply('pause');
});

module.exports = {
    addEventListener: function (type, func) {
        this.removeEventListener(type, func);

        if (!app.getInfo().features || app.getInfo().features[events[type].feature]) {
            events[type].callbacks.push(func);
        }
        else {
            throw ("Cannot register a hanlder for the " + type + " event. Please add the '" + 
                  events[type].feature + "' to your config.xml.");
        }
    },

    removeEventListener: function (type, func) {
        var idx = events[type].callbacks.indexOf(func);
        if (idx >= 0) {
            delete events[type].callbacks[idx];
        }
    }
};

});
define('ripple/platform/webworks.bb10/1.0.0/identity', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 deviceSettings = require('ripple/deviceSettings'),
    _self = {};

_self.__defineGetter__("uuid", function () {
    return deviceSettings.retrieve("identity.uuid");
});

module.exports = _self;

});
define('ripple/platform/webworks.bb10/1.0.0/invoke', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 notifications = require('ripple/notifications'),
    utils = require('ripple/utils'),
    _self = {};

function _fail(onError) {
    if (onError && typeof onError === "function") {
        onError("invalid invocation request");
    }
}

_self.invoke = function (request, onSuccess, onError) {
    var argsString = "";

    if (!request) { // is this check even needed?
        _fail(onError);
        return;
    } else {
        if (request) {
            utils.forEach(request, function (arg, key) {
                argsString += key + " = " + arg + "</br>";
            });

            notifications.openNotification("normal", "Requested to invoke external application with the following arguments:</br> " +
                                           argsString + "</br>");
        }
        else {
            _fail(onError);
            return;
        }
    }
};

_self.__defineGetter__("ACTION_OPEN", function () {
    return "bb.action.OPEN";
});
_self.__defineGetter__("ACTION_VIEW", function () { 
    return "bb.action.VIEW"; 
});
_self.__defineGetter__("ACTION_SHARE", function () {
    return "bb.action.SHARE";
});

module.exports = _self;

});
define('ripple/platform/webworks.bb10/1.0.0/navigator', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 nav = require('ripple/platform/w3c/1.0/navigator'),
    utils = require('ripple/utils'),
    deviceSettings = require('ripple/deviceSettings'),
    _self = {};

utils.mixin(nav, _self);

_self.__defineGetter__("language", function () {
    return deviceSettings.retrieve("system.language");
});

module.exports = _self;

});
define('ripple/platform/webworks.bb10/1.0.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (config) {
        return true;
    },
    extractInfo: function (config) {
        if (!config) {
            return null;
        }

        var widgetInfo = {},
            widgetFeatures = config.widget.children.feature.validationResult,
            accessUrls = config.widget.children.access.validationResult,
            invokeTargets = config.rawJSON.widget[0]["rim:invoke-target"],
            accessFeatures = config.widget.children.access.children.feature.validationResult,
            toFeature = function (validationResult) {
                return {
                    id: validationResult.attributes.id.value,
                    required: !validationResult.attributes.required || validationResult.attributes.required.value,
                    URIs: []
                };
            };

        widgetInfo.id = config.widget.validationResult[0].attributes.id.value;
        widgetInfo.name = config.widget.children.name.validationResult[0].value;
        widgetInfo.icon = config.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = config.widget.validationResult[0].attributes.version.value;
        widgetInfo.author = config.widget.children.author.validationResult[0].value;
        widgetInfo.authorEmail = config.widget.children.author.validationResult[0].attributes.email.value;
        widgetInfo.authorURL = config.widget.children.author.validationResult[0].attributes.href.value;
        widgetInfo.copyright = config.widget.children.author.validationResult[0].attributes["rim:copyright"].value;
        widgetInfo.description = config.widget.children.description.validationResult[0].value;
        widgetInfo.invokeTargets = invokeTargets;
        if (config.widget.children.license.validationResult[0]) {
            widgetInfo.license = config.widget.children.license.validationResult[0].value;
            widgetInfo.licenseURL = config.widget.children.license.validationResult[0].attributes.href.value;
        }

        widgetInfo.features = widgetFeatures.reduce(function (features, validationResult) {
            if (validationResult.valid) {
                var feature = toFeature(validationResult);
                feature.URIs.push({
                    value: utils.location().href,
                    subdomains: true
                });
                features = features || {};
                features[feature.id] = feature;
            }
            return features;
        }, {});

        widgetInfo.features = accessUrls.map(function (access) {
            return {
                uri: access.attributes.uri.value,
                subdomains: access.attributes.subdomains.value,
                features: accessFeatures ? accessFeatures.filter(function (f) {
                    return f.node && f.node.parentNode && f.node.parentNode.attributes.uri.value === access.attributes.uri.value;
                }) : null
            };
        }).reduce(function (result, access) {
            return access.features ? access.features.reduce(function (features, validationResult) {
                var feature = features[validationResult.attributes.id.value] || toFeature(validationResult);
                feature.URIs.push({
                    value: access.uri,
                    subdomains: access.subdomains
                });
                features[feature.id] = feature;
                return features;
            }, result) : result;
        }, widgetInfo.features);

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xmlns:rim": {
                    attributeName: "xmlns:rim",
                    required: true,
                    type: "list",
                    listValues: ["http://www.blackberry.com/ns/widgets"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                },
                id: {
                    attributeName: "id",
                    required: false,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    required: false,
                    type: "string"
                },
                "rim:header": {
                    attributeName: "rim:header",
                    required: false,
                    type: "string"
                },
                "rim:backButton": {
                    attributeName: "rim:backButton",
                    required: false,
                    type: "string"
                }
            },
            children: {
                name: {
                    nodeName: "name",
                    required: true,
                    occurrence: 1,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        "its:dir": {
                            attributeName: "its:dir",
                            required: false,
                            type: "list",
                            listValues: ["rtl", "ltr", "lro", "rlo"]
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        "its:dir": {
                            attributeName: "its:dir",
                            required: false,
                            type: "list",
                            listValues: ["rtl", "ltr", "lro", "rlo"]
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        src: {
                            attributeName: "src",
                            type: "string",
                            required: true
                        },
                        "rim:hover": {
                            attributeName: "rim:hover",
                            type: "boolean",
                            required: false
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        href: {
                            attributeName: "href",
                            type: "string",
                            required: false
                        },
                        "rim:copyright": {
                            attributeName: "rim:copyright",
                            type: "string",
                            required: false
                        },
                        email: {
                            attributeName: "email",
                            type: "string",
                            required: false
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        "its:dir": {
                            attributeName: "its:dir",
                            required: false,
                            type: "list",
                            listValues: ["rtl", "ltr", "lro", "rlo"]
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 1,
                    attributes : {
                        href: {
                            attributeName: "href",
                            type: "string",
                            required: false
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        "its:dir": {
                            attributeName: "its:dir",
                            required: false,
                            type: "list",
                            listValues: ["rtl", "ltr", "lro", "rlo"]
                        }
                    }
                },
                "rim:cache": {
                    nodeName: "rim:cache",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        disableAllCache: {
                            attributeName: "disableAllCache",
                            required: false,
                            type: "boolean"
                        },
                        aggressiveCacheAge: {
                            attributeName: "aggressiveCacheAge",
                            required: false,
                            type: "number"
                        },
                        maxCacheSizeTotal: {
                            attributeName: "maxCacheSizeTotal",
                            required: false,
                            type: "number"
                        },
                        maxCacheSizeItem: {
                            attributeName: "maxCacheSizeItem",
                            required: false,
                            type: "number"
                        }
                    }
                },
                access: {
                    nodeName: "access",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        uri: {
                            attributeName: "uri",
                            required: true,
                            type: "string"
                        },
                        subdomains: {
                            attributeName: "subdomains",
                            required: false,
                            type: "boolean"
                        }
                    },
                    children: {
                        feature: {
                            nodeName: "feature",
                            required: false,
                            occurrence: 0,
                            attributes: {
                                id: {
                                    attributeName: "id",
                                    required: true,
                                    //TODO: this should be a list
                                    type: "string"
                                },
                                required: {
                                    attributeName: "required",
                                    required: false,
                                    type: "boolean"
                                },
                                version: {
                                    attributeName: "version",
                                    required: false,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                feature: {
                    nodeName: "feature",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            //TODO: this should be a list
                            type: "string"
                        },
                        required: {
                            attributeName: "required",
                            required: false,
                            type: "boolean"
                        },
                        version: {
                            attributeName: "version",
                            required: false,
                            type: "string"
                        }
                    }
                },
                "rim:loadingScreen": {
                    nodeName: "rim:loadingScreen",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        backgroundColor: {
                            attributeName: "backgroundColor",
                            required: false,
                            type: "string"
                        },
                        backgroundImage: {
                            attributeName: "backgroundImage",
                            required: false,
                            type: "string"
                        },
                        foregroundImage: {
                            attributeName: "foregroundImage",
                            required: false,
                            type: "string"
                        },
                        onRemotePageLoad: {
                            attributeName: "onRemotePageLoad",
                            required: false,
                            type: "boolean"
                        },
                        onLocalPageLoad: {
                            attributeName: "onLocalPageLoad",
                            required : false,
                            type: "boolean"
                        },
                        onFirstLaunch: {
                            attributeName: "onFirstLaunch",
                            required: false,
                            type: "boolean"
                        }
                    },
                    children: {
                        "rim:transitionEffect": {
                            nodeName: "rim:transitionEffect",
                            required: false,
                            occurrence: 1,
                            attributes: {
                                "type": {
                                    attributeName: "type",
                                    required: true,
                                    type: "list",
                                    listValues: ["slidePush", "slideOver", "fadeIn", "fadeOut", "wipeIn", "wipeOut", "zoomIn", "zoomOut"]
                                },
                                duration: {
                                    attributeName: "duration",
                                    required: false,
                                    type: "number"
                                },
                                direction: {
                                    attributeName: "direction",
                                    required: false,
                                    type: "list",
                                    listValues: ["left", "right", "up", "down"]
                                }
                            }
                        }
                    }
                },
                "rim:invoke-target": {
                    nodeName: "rim:invoke-target",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            type: "string"
                        }
                    },
                    children: {
                        "type": {
                            nodeName: "type",
                            required: true,
                            occurrence: 1
                        },
                        "require-source-permissions": {
                            nodeName: "require-source-permissions",
                            required: false,
                            occurence: 0
                        },
                        "filter": {
                            nodeName: "filter",
                            required: false,
                            occurence: 0,
                            children: {
                                "action": {
                                    nodeName: "action",
                                    required: true,
                                    occurence: 0
                                },
                                "mime-type": {
                                    nodeName: "mime-type",
                                    required: true,
                                    occurence: 0
                                },
                                "property": {
                                    nodeName: "property",
                                    required: false,
                                    occurenc: 0,
                                    attributes: {
                                        "var": {
                                            attributeName: "var",
                                            required: false,
                                            type: "string"
                                        },
                                        "value": {
                                            attributeName: "value",
                                            required: false,
                                            type: "string"
                                        }
                                    }
                                }
                            },
                        }
                    }
                },
                "rim:connection": {
                    nodeName: "rim:connection",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        timeout: {
                            attributeName: "timeout",
                            required: false,
                            type: "number"
                        }
                    },
                    children: {
                        id: {
                            nodeName: "id",
                            required: false,
                            occurrence: 0
                        }
                    }
                },
                "rim:navigation": {
                    nodeName: "rim:navigation",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        mode: {
                            attributeName: "mode",
                            required: false,
                            type: "list",
                            listValues: ["focus"]
                        }
                    }
                },
                "content": {
                    nodeName: "content",
                    required: true,
                    occurrence: 1,
                    attributes: {
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        type: {
                            attributeName: "type",
                            required: false,
                            type: "string"
                        },
                        charset: {
                            attributeName: "charset",
                            required: false,
                            type: "string"
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/webworks.bb10/1.0.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event');

module.exports = {
    "NetworkStatus": {
        "connectionType": {
            "name": "Connection Type",
            "control": {
                "type": "select",
                "value": "ethernet"
            },
            "options": {
                "unknown": "UNKNOWN",
                "ethernet": "ETHERNET",
                "wifi": "WIFI",
                "bluetooth_dun": "BLUETOOTH_DUN",
                "usb": "USB",
                "vpn": "VPN",
                "rim-bb": "BB",
                "2g": "CELL_2G",
                "3g": "CELL_3G",
                "4g": "CELL_4G",
                "none": "NONE"
            },
            "callback": function (setting, oldSetting) {
                event.trigger("DeviceConnectionChanged", [{oldType: oldSetting, newType: setting}]);
            }
        }
    },
    "identity": {
        "uuid": {
            "name": "uuid",
            "control": {
                "type": "text",
                "value": "43A8C489"
            }
        }
    },
    "system": {
        "language": {
            "name": "language",
            "control": {
                "type": "text",
                "value": "en_US"
            },
            "callback": function (setting) {
                event.trigger("LanguageChanged", [setting]);
            }
        },
        "region": {
            "name": "region",
            "control": {
                "type": "text",
                "value": "en_CA"
            },
            "callback": function (setting) {
                event.trigger("RegionChanged", [setting]);
            }
        }
    },
    "battery": {
        "state": {
            "name": "Handset is Charging",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("DeviceBatteryStateChanged", [setting]);
            }
        },
        "level":  {
            "name": "Charge Level (% remaining)",
            "control": {
                "type": "select",
                "value": 100
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 100; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }()),
            "callback": function (setting) {
                event.trigger("DeviceBatteryLevelChanged", [setting]);
            }
        }
    },
    "Perimeters": {
        "perimeter": {
            "name": "Perimeter",
            "control": {
                "type": "select",
                "value": "Consumer"
            },
            "options": {
                "Enterprise": "Enterprise",
                "Consumer": "Consumer"
            }
        }
    }
};

});
define('ripple/platform/webworks.bb10/1.0.0/spec/events', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    event = require('ripple/event');

module.exports = {
    "blackberry.event.swipedown": {
        callback: function () {
            event.trigger("AppSwipeDown");
        }
    },
    "blackberry.event.resume": {
        callback: function () {
            event.trigger("AppResume");
        }
    },
    "blackberry.event.pause": {
        callback: function () {
            event.trigger("AppPause");
        }
    }
};

});
define('ripple/platform/webworks.bb10/1.0.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "accelerometer",
        "deviceSettings",
        "geoView",
        "platformEvents",
        "widgetConfig",
        "build",
        "invoke"
    ]
};

});
define('ripple/platform/webworks.bb10/1.0.0/spec', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    id: "webworks.bb10",
    version: "1.0.0",
    name: "BlackBerry 10 WebWorks",

    persistencePrefix: "rim-bb10-",

    ui: require('ripple/platform/webworks.bb10/1.0.0/spec/ui'),
    device: require('ripple/platform/webworks.bb10/1.0.0/spec/device'),
    config: require('ripple/platform/webworks.bb10/1.0.0/spec/config'),
    events: require('ripple/platform/webworks.bb10/1.0.0/spec/events'),

    initialize: function () {
        var event = require('ripple/event'),
            _console = require('ripple/console'),
            emulatorBridge = require('ripple/emulatorBridge');

        event.on("TinyHipposLoaded", function () {
            var doc = emulatorBridge.document(),
                evt = doc.createEvent("Events");
            evt.initEvent("webworksready", true, true);
            doc.dispatchEvent(evt);
            _console.log("fired webworksready event!");
        });
    },

    objects: {
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        navigator: {
            path: "webworks.bb10/1.0.0/navigator",
            children: {
                geolocation: {
                    path: "w3c/1.0/geolocation"
                }
            }
        },
        blackberry: {
            children: {
                event: {
                    path: "webworks.bb10/1.0.0/event"
                },
                app: {
                    path: "webworks.bb10/1.0.0/app",
                    feature: "blackberry.app"
                },
                invoke: {
                    path: "webworks.bb10/1.0.0/invoke",
                    feature: "blackberry.invoke"
                },
                identity: {
                    path: "webworks.bb10/1.0.0/identity",
                    feature: "blackberry.identity"
                },
                system: {
                    path: "webworks.bb10/1.0.0/system"
                },
                connection: {
                    path: "webworks.bb10/1.0.0/connection"
                },
                ui: {
                    children: {
                        dialog: {
                            path: "webworks.bb10/1.0.0/dialog",
                            feature: "blackberry.ui.dialog"
                        }
                    }
                },
            }
        }
    }
};

});
define('ripple/platform/webworks.bb10/1.0.0/system', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 deviceSettings = require('ripple/deviceSettings'),
    devices = require('ripple/devices'),
    app = require('ripple/app'),
    utils = require('ripple/utils'),
    _self;

function _is(feature) {
    return {
        allowedFor: function (location) {
            return feature && feature.URIs.some(function (uri) {
                return uri.value === location ||
                      (location.indexOf(uri.value) >= 0 && uri.subdomains);
            });
        }
    };
}

_self = {
    hasCapability: function (capability) {
        var capabilities = devices.getCurrentDevice().capabilities;
        return capabilities ? capabilities.some(function (type) {
                return type === capability;
            }) : false;
    },
    hasPermission: function (desiredModule) {
        var info = app.getInfo(),
            feature = info.features ? info.features[desiredModule] : null;

        return feature === null || _is(feature).allowedFor(utils.location().href) ? _self.ALLOW : _self.DENY;
    }
};

_self.__defineGetter__("ALLOW", function () {
    return 0;
});

_self.__defineGetter__("DENY", function () {
    return 1;
});

_self.__defineGetter__("softwareVersion", function () {
    return devices.getCurrentDevice().osVersion;
});

_self.__defineGetter__("hardwareId", function () {
    return devices.getCurrentDevice().hardwareId;
});

_self.__defineGetter__("language", function () {
    return deviceSettings.retrieve("system.language");
});

_self.__defineGetter__("region", function () {
    return deviceSettings.retrieve("system.region");
});

module.exports = _self;

});
define('ripple/platform/webworks.core/2.0.0/XMLHttpRequest', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    create: function (server) {
        var XHR = window.XMLHttpRequest,
            webworks = require(server);

        return function () {
            var _url,
                _async,
                xhr = new XHR(),
                origMethods = {
                    open: xhr.open,
                    send: xhr.send,
                    setRequestHeader: xhr.setRequestHeader
                };

            function onreadystatechange() {
                if (typeof xhr.onreadystatechange === "function") {
                    xhr.onreadystatechange();
                }
            }

            function statemachine(getResult) {
                var state = 0,
                    incState = function (prev, baton) {
                        state++;
                        if (_async) {
                            baton.take();
                            window.setTimeout(baton.pass, 1);
                        }
                    },
                    setResponse = function (result) {
                        xhr.__defineGetter__("status", function () {
                            return 200;
                        });

                        xhr.__defineGetter__("responseText", function () {
                            return result !== null && result !== undefined ?
                                JSON.stringify(result) : null;
                        });
                    };

                xhr.__defineGetter__("readyState", function () {
                    return state;
                });

                jWorkflow.order(incState)
                         .andThen(onreadystatechange)
                         .andThen(incState)
                         .andThen(onreadystatechange)
                         .andThen(incState)
                         .andThen(onreadystatechange)
                         .andThen(getResult)
                         .andThen(setResponse)
                         .andThen(incState)
                         .andThen(onreadystatechange)
                         .start();
            }

            xhr.setRequestHeader = function (header, value) {
                if (!_url.match(/^webworks:\/\//)) {
                    origMethods.setRequestHeader.apply(xhr, Array.prototype.slice.call(arguments));
                }
            };

            xhr.open = function (method, url, async, user, password) {
                _url = url;
                _async = async;

                if (!_url.match(/^webworks:\/\//)) {
                    origMethods.open.apply(xhr, Array.prototype.slice.call(arguments));
                }
            };

            xhr.send = function (post) {
                if (!_url.match(/^webworks:\/\//)) {
                    origMethods.send.apply(xhr, Array.prototype.slice.call(arguments));
                    return;
                }

                var params = _url.match(/\?(.*)$/),
                    objPath = _url.match(/^webworks:\/\/([^\?]*)/)[1].split("/"),
                    apiMethod = objPath.reduce(function (obj, name) {
                        return obj[name];
                    }, webworks),
                    postParams = {},
                    get = {};

                if (params) {
                    params[1].split("&").forEach(function (param) {
                            var pair = param.split("="),
                                key = decodeURIComponent(pair[0]),
                                value = decodeURIComponent(pair[1]);
                            // parsing undefied with JSON throws exception
                            get[key] = value === "undefined" ? undefined : JSON.parse(value);
                        });
                }

                if (post) {
                    post.split("&").forEach(function (param) {
                            var pair = param.split("="),
                                value;
                            try {
                                value = JSON.parse(decodeURIComponent(pair[1]));
                            } catch (e) {
                                value = pair[1] === "undefined" ? undefined : pair[1];
                            }

                            postParams[pair[0]] = value;
                        });
                }

                statemachine(function (prev, baton) {
                    return apiMethod(get, postParams, baton);
                });
            };

            return xhr;
        };
    }
};

});
define('ripple/platform/webworks.core/2.0.0/client/FileProperties', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function FileProperties(props) {
    props = props || {};

    function _get(val) {
        return function () {
            return props[val];
        };
    }

    this.__defineGetter__("dateCreated", _get("dateCreated")); //tablet only
    this.__defineGetter__("dateModified", _get("dateModified"));
    this.__defineGetter__("directory", _get("directory"));
    this.__defineGetter__("fileExtension", _get("fileExtension"));
    this.__defineGetter__("isHidden", _get("isHidden"));
    this.__defineGetter__("isReadonly", _get("isReadonly")); //handset only
    this.__defineGetter__("mimeType", _get("mimeType")); //handset only
    this.__defineGetter__("size", _get("size"));
}

module.exports = FileProperties;

});
define('ripple/platform/webworks.core/2.0.0/client/dialog', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/ui/dialog/",
    _self;

function getButtonsForDialogType(dialogType) {
    switch (dialogType) {
    case _self.D_OK:
        return ["Ok"];
    case _self.D_SAVE:
        return ["Save", "Discard"];
    case _self.D_DELETE:
        return ["Delete", "Cancel"];
    case _self.D_YES_NO:
        return ["Yes", "No"];
    case _self.D_OK_CANCEL:
        return ["Ok", "Cancel"];
    default:
        throw new Error("Invalid dialog type: " + dialogType);
    }
}

_self = {
    customAskAsync: function (message, choices, callback, settings) {
        return transport.call(_uri + "ask", {
            async: true,
            get: {
                message: message,
                buttons: choices,
                settings: settings
            }
        }, function (response) {
            if (callback) {
                callback(response);
            }
        });
    },

    standardAskAsync: function (message, type, callback, settings) {
        var choices = getButtonsForDialogType(type);
        return transport.call(_uri + "ask", {
            async: true,
            get: {
                message: message,
                buttons: choices,
                settings: settings
            }
        }, function (response) {
            if (callback) {
                callback(response);
            }
        });
    }
};

_self.__defineGetter__("D_OK", function () {
    return 0;
});

_self.__defineGetter__("D_SAVE", function () {
    return 1;
});

_self.__defineGetter__("D_DELETE", function () {
    return 2;
});

_self.__defineGetter__("D_YES_NO", function () {
    return 3;
});

_self.__defineGetter__("D_OK_CANCEL", function () {
    return 4;
});

_self.__defineGetter__("BOTTOM", function () {
    return "bottomCenter";
});

_self.__defineGetter__("CENTER", function () {
    return "middleCenter";
});

_self.__defineGetter__("TOP", function () {
    return "topCenter";
});

_self.__defineGetter__("SIZE_FULL", function () {
    return "full";
});

_self.__defineGetter__("SIZE_LARGE", function () {
    return "large";
});

_self.__defineGetter__("SIZE_MEDIUM", function () {
    return "medium";
});

_self.__defineGetter__("SIZE_SMALL", function () {
    return "small";
});

_self.__defineGetter__("SIZE_TALL", function () {
    return "tall";
});

module.exports = _self;

});
define('ripple/platform/webworks.core/2.0.0/client/events', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 _handlers = [],
    _self;

_self = {
    eventsMap: {
        getHandlerById: function (handlerId) {
            return _handlers[handlerId];
        },
        addHandler: function (handler) {
            _handlers.push(handler);
            return _handlers.length - 1;
        },
        removeHandler: function (handlerId) {
            if (handlerId > -1 && handlerId < _handlers.length) {
                delete _handlers[handlerId]; //cannot splice because all published IDs would refer to the wrong handler
            }
        }
    },

    registerEventHandler : function (eventName, eventCallback, eventParams) {
        return _self.eventsMap.addHandler(eventCallback);
    },

    getEventHandler : function (handlerId) {
        return _self.eventsMap.getHandlerById(handlerId);
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.core/2.0.0/client/io/dir', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/io/dir/",
    FILE = "file://";

function _prunePrefix(path) {
    return path.replace(new RegExp("^" + FILE), '');
}

function _addPrefix(path) {
    return FILE + path;
}

module.exports = {
    createNewDir: function (path) {
        transport.call(_uri + "createNewDir", {
            post: {path: _prunePrefix(path)}
        });
    },
    deleteDirectory: function (path, recursive) {
        transport.call(_uri + "deleteDirectory", {
            post: {path: _prunePrefix(path), recursive: recursive}
        });
    },
    exists: function (path) {
        return transport.call(_uri + "exists", {
            post: {path: _prunePrefix(path)}
        });
    },
    getParentDirectory: function (path) {
        return _addPrefix(transport.call(_uri + "getParentDirectory", {
            post: {path: _prunePrefix(path)}
        }));
    },
    listDirectories: function (path) {
        return transport.call(_uri + "listDirectories", {
            post: {path: _prunePrefix(path)}
        });
    },
    listFiles: function (path) {
        return transport.call(_uri + "listFiles", {
            post: {path: _prunePrefix(path)}
        });
    },
    rename: function (path, newName) {
        transport.call(_uri + "rename", {
            post: {path: _prunePrefix(path), newName: newName}
        });
    }
};

});
define('ripple/platform/webworks.core/2.0.0/client/io/file', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/io/file/",
    FILE = "file://",
    _onFileOpened;

function _prunePrefix(path) {
    return path.replace(new RegExp("^" + FILE), '');
}

module.exports = {
    copy: function (from, to) {
        transport.call(_uri + "copy", {
            post: {from: _prunePrefix(from), to: _prunePrefix(to)}
        });
    },
    deleteFile: function (path) {
        transport.call(_uri + "deleteFile", {
            post: {path: _prunePrefix(path)}
        });
    },
    exists: function (path) {
        return transport.call(_uri + "exists", {
            post: {path: _prunePrefix(path)}
        });
    },
    getFileProperties: function (path) {
        var properties = transport.call(_uri + "getFileProperties", {
            post: {path: _prunePrefix(path)}
        });
        properties.directory = FILE + properties.directory;
        return properties;
    },
    open: function (path, newName) {
        transport.call(_uri + "open", {
            post: {path: _prunePrefix(path)}
        });
    },
    readFile: function (path, onFileOpened, async) {
        async = async === false ? false : true;

        var uri = _uri + "readFile",
            args = {
                post: {path: _prunePrefix(path), async: async}
            },
            callResult;

        _onFileOpened = onFileOpened;

        if (async) {
            transport.poll(uri, args, function (data, res) {
                if (_onFileOpened) {
                    _onFileOpened(FILE + data.fullPath, data.blobData);
                }
                return false;
            });
        } else {
            callResult = transport.call(uri, args);
            _onFileOpened(FILE + callResult.fullPath, callResult.blobData);
        }
    },
    rename: function (path, newName) {
        transport.call(_uri + "rename", {
            post: {path: _prunePrefix(path), newName: newName}
        });
    },
    saveFile: function (path, blob) {
        transport.call(_uri + "saveFile", {
            post: {path: _prunePrefix(path), blob: blob}
        });
    }
};

});
define('ripple/platform/webworks.core/2.0.0/client/system', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/system/",
    _self;

_self = {
    hasCapability: function (capability) {
        return transport.call(_uri + "hasCapability", {
            get: {capability: capability}
        });
    },

    hasDataCoverage: function () {
        return transport.call(_uri + "hasDataCoverage");
    },

    hasPermission: function (desiredModule) {
        return transport.call(_uri + "hasPermission", {
            get: {desiredModule: desiredModule}
        });
    },

    isMassStorageActive: function () {
        return transport.call(_uri + "isMassStorageActive");
    }
};

_self.__defineGetter__("model", function () {
    return transport.call(_uri + "model");
});
_self.__defineGetter__("scriptApiVersion", function () {
    return transport.call(_uri + "scriptApiVersion");
});
_self.__defineGetter__("softwareVersion", function () {
    return transport.call(_uri + "softwareVersion");
});

_self.__defineGetter__("ALLOW", function () {
    return 0;
});
_self.__defineGetter__("DENY", function () {
    return 1;
});
_self.__defineGetter__("PROMPT", function () {
    return 2;
});
_self.__defineGetter__("NOT_SET", function () {
    return 3;
});

module.exports = _self;

});
define('ripple/platform/webworks.core/2.0.0/client/transport', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 _self;

function RemoteFunctionCall(functionUri) {
    var params = {},
        postString = "",
        postParams = {};

    function composeUri() {
        var uri = "webworks://" + functionUri,
            paramCount = 1,
            param;

        for (param in params) {
            if (params.hasOwnProperty(param)) {
                if (paramCount === 1) {
                    uri += "?";
                } else {
                    uri += "&";
                }
                uri += param + "=" + params[param];
                paramCount++;
            }

            uri = uri.replace(/\&$/, "");
        }

        return uri;
    }

    function createXhrRequest(uri, isAsync) {
        var request = new XMLHttpRequest(),
            paramCount = 1,
            param;

        for (param in postParams) {
            if (postParams.hasOwnProperty(param)) {
                postString += param + "=" + postParams[param] + "&";
                paramCount++;
            }
        }

        postString = postString.replace(/\&$/, "");

        // TODO: make get/post
        request.open("POST", uri, isAsync);
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        return request;
    }

    this.addParam = function (name, value) {
        params[name] = encodeURIComponent(JSON.stringify(value));
    };

    this.addPostParam = function (name, value) {
        postParams[name] = encodeURIComponent(JSON.stringify(value));
    };

    this.makeSyncCall = function (success, error) {
        var requestUri = composeUri(),
            request = createXhrRequest(requestUri, false),
            response, errored, cb, data;

        request.send(postString);

        response = JSON.parse(request.responseText || "null");
        errored = response.code < 0;
        cb = errored ? error : success;
        data = errored ? response.msg : response.data;

        if (cb) {
            cb(data, response);
        }
        else if (errored) {
            throw data;
        }

        return data;
    };

    this.makeAsyncCall = function (success, error) {
        var requestUri = composeUri(),
            request = createXhrRequest(requestUri, true);

        request.onreadystatechange = function () {
            if (request.readyState === 4 && request.status === 200) {
                var response = JSON.parse(request.responseText || "null"),
                    cb = response.code < 0 ? error : success,
                    data = response.code < 0 ? response.msg : response.data;

                return cb && cb(data, response);
            }
        };

        request.send(postString);
    };
}

_self = {
    call: function (url, opts, success, error) {
        var request = new RemoteFunctionCall(url),
            name;

        opts = opts || {};

        if (opts.get) {
            for (name in opts.get) {
                if (Object.hasOwnProperty.call(opts.get, name)) {
                    request.addParam(name, opts.get[name]);
                }
            }
        }

        if (opts.post) {
            for (name in opts.post) {
                if (Object.hasOwnProperty.call(opts.post, name)) {
                    request.addPostParam(name, opts.post[name]);
                }
            }
        }

        return opts.async ? request.makeAsyncCall(success, error) : request.makeSyncCall(success, error);
    },

    poll: function (url, opts, callback) {
        opts = opts || {};
        opts.async = true;

        _self.call(url, opts, function (data, response) {
            if (callback(data, response)) {
                _self.poll(url, opts, callback);
            }
        });
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.core/2.0.0/client/utils', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 _blobs = {};

function _blobBuilder() {
    var BlobBuilder = BlobBuilder || WebKitBlobBuilder;
    return new BlobBuilder();
}

module.exports = {
    parseURL: function (theUrl) {
        /********START IDEA BORROWING*******/
        // parseUri 1.2.2
        // (c) Steven Levithan <stevenlevithan.com>
        // MIT License

        function parseUri(str) {
            var	o   = parseUri.options,
                m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
                uri = {},
                i   = 14;

            while (i--) {
                uri[o.key[i]] = m[i] || "";
            }

            uri[o.q.name] = {};
            uri[o.q.arrayName] = [];
            uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
                if ($1) {
                    uri[o.q.name][$1] = $2;
                    uri[o.q.arrayName].push($2);
                }
            });

            return uri;
        }

        parseUri.options = {
                strictMode: false,
                key: ["source", "protocol", "authority", "userInfo", "user", "password", "host", "port", "relative", "path", "directory", "file", "query", "anchor"],
                q:   {
                    name:   "queryKey",
                    arrayName:   "queryArray",
                    parser: /(?:^|&)([^&=]*)=?([^&]*)/g
                },
                parser: {
                    strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
                    loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
                }
            };
        /********END IDEA BORROWING*******/

        parseUri.strictMode = "strict";
        var uri = parseUri(theUrl),
            retVal = {
                getURLParameter : function (key) {
                    return uri.queryKey[key];
                },

                getURLParameterByIndex : function (index) {
                    return uri.queryArray[index];
                }
            };

        //Add default values for the http/https port if they weren't specified in the URL. The above parser returns undefined. We need the values
        //to be compatible with the BB version of API.
        if (uri["port"] === "") {
            if (uri["protocol"] === "http") {
                uri["port"] = "80";
            }
            else if (uri["protocol"] === "https") {
                uri["port"] = "443";
            }
            else {
                uri["port"] = "0";
            }
        }

        retVal.__defineGetter__("host", function () {
            return uri["host"];
        });
        retVal.__defineGetter__("port", function () {
            return parseInt(uri["port"], 10);
        });

        return retVal;
    },

    generateUniqueId: function () {
        return Math.floor(Math.random() * Number.MAX_VALUE);
    },

    blobToString: function (blob, encoding) {
        return _blobs[blob.id];
    },

    stringToBlob: function (string, encoding) {
        var id = Math.uuid(undefined, 16),
            blob = _blobBuilder(),
            finalBlob;

        _blobs[id] = string;
        blob.append(string);

        finalBlob = blob.getBlob();
        finalBlob.id = id;
        finalBlob.length = finalBlob.size;

        return finalBlob;
    }
};

});
define('ripple/platform/webworks.core/2.0.0/fsCache', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 fs = require('ripple/dbfs'),
    utils = require('ripple/utils'),
    _console = require('ripple/console'),
    constants = require('ripple/constants'),
    event = require('ripple/event'),
    bbUtils = require('ripple/platform/webworks.core/2.0.0/client/utils'),
    FileProperties = require('ripple/platform/webworks.core/2.0.0/client/FileProperties'),
    _cache = {},
    _self;

function _createPath(path) {
    var parts = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
        workflow = jWorkflow.order();

    parts.forEach(function (part, index) {
        var dir = "/" + utils.copy(parts).splice(0, index + 1).join("/");

        workflow.andThen(function (prev, baton) {
            baton.take();
            fs.mkdir(dir, baton.pass, baton.pass);
        });
    });

    workflow.start(_self.refresh);
}
event.on("FileSystemInitialized", function () {
    _createPath("/SDCard");
    _createPath("/store/home/user/music");
    _createPath("/store/home/user/pictures");
    _createPath("/store/home/user/videos");
    _createPath("/store/home/user/videos");
    _createPath("/accounts/1000/appdata/emulatedapp/data");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/bookmarks");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/books");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/camera");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/documents");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/downloads");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/misc");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/music");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/photos");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/print");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/videos");
    _createPath("/accounts/1000/appdata/emulatedapp/shared/voice");
});

function _fsError(e) {
    _self.refresh();
    if (e.code !== 1) { // suppress file not found error
        _console.error("FileSystem error (code " + e.code + ")");
    }
}

function _walk(path, parent) {
    fs.ls(path, function (entries) {
        parent.children = parent.children || {};

        entries.forEach(function (entry) {
            parent.children[entry.name] = entry;
            parent.children[entry.name].properties = {};

            if (entry.isDirectory) {
                _walk(entry.fullPath, entry);
            } else {
                entry.file(function (file) {
                    utils.mixin(file, parent.children[entry.name].properties);
                });
                fs.read(entry.fullPath, function (data) {
                    parent.children[entry.name].data = data;
                }, function (e) {
                    console.error(e);
                });
            }
        });
    }, function (e) {
        console.error(e);
    });
}

function _get(path) {
    return path.replace(/^\//, '').split("/").reduce(function (obj, token) {
        return token === "" ? obj : (obj && obj.children ? obj.children[token] || null : null);
    }, _cache);
}

function _getInfo(path) {
    var parent = ("/" + path.replace(/^\//, '').replace(/\/$/, '')).split("/"),
        name = parent.splice(parent.length - 1, 1).join(""),
        ext = name.split(".");

    return {
        name: name,
        extension: ext.length > 1 ? ext[ext.length - 1] : "",
        hidden: (name.length > 0 && name[0] === ".") || false,
        parent: parent.join("/") || "/"
    };
}

function _set(path, obj) {
    var parent = _cache,
        tokens = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
        child = tokens.splice(tokens.length - 1, 1).join("");

    tokens.forEach(function (token) {
        parent = parent.children[token];
    });

    parent.children = parent.children || {};
    obj.properties = obj.properties || {};
    parent.children[child] = obj;
}

function _delete(path) {
    var parent = _cache,
        tokens = path.replace(/^\//, '').replace(/\/$/, '').split("/"),
        child = tokens.splice(tokens.length - 1, 1).join("");

    tokens.forEach(function (token) {
        parent = parent.children[token];
    });

    delete parent.children[child];
}

// TODO: handle exceptions so that any respective fs command can error out
// TODO: dateCreated is always dateModified

_self = {
    refresh: function () {
        _cache = {};
        _walk("/", _cache);
    },
    file: {
        exists: function (path) {
            var entry = _get(path);
            return !!(entry && !entry.isDirectory);
        },

        deleteFile: function (path) {
            _delete(path);
            fs.rm(path, function () {}, _fsError);
        },

        copy: function (from, to) {
            var fromEntry = _get(from);

            _set(to, {
                fullPath: to,
                properties: fromEntry.properties,
                data: fromEntry.data
            });

            fs.cp(from, to, function (entry) {
                entry.file(function (file) {
                    entry.properties = entry.properties || {};
                    utils.mixin(file, entry.properties);
                    _set(to, entry);
                });
            }, _fsError);
        },

        getFileProperties: function (path) {
            var entry = _get(path),
                info = _getInfo(path);

            fs.stat(path, function () {}, _fsError);

            return new FileProperties({
                //HACK: not sure where these should come from so check both for now.
                dateCreated: entry.properties.lastModifiedDate || entry.lastModifiedDate,
                dateModified: entry.properties.lastModifiedDate || entry.lastModifiedDate,
                directory: info.parent,
                fileExtension: info.extension,
                isHidden: info.hidden,
                isReadonly: false,
                mimeType: entry.properties.type,
                size: entry.properties.size
            });
        },

        rename: function (path, newName) {
            _self.dir.rename(path, newName);
        },

        readFile: function (path, success, async) {
            var entry = _get(path);

            async = async === false ? async : true;

            if (!async) {
                success(bbUtils.stringToBlob(entry.data));
            }
            else {
                fs.read(path, function (data) {
                    var blob = bbUtils.stringToBlob(data);
                    if (async) {
                        success(blob);
                    }
                    entry.data = data;
                    _set(path, entry);
                }, _fsError);
            }
        },

        saveFile: function (path, blob) {
            var data = bbUtils.blobToString(blob);

            _set(path, {
                lastModifiedDate: new Date(),
                fullPath: path,
                isDirectory: false,
                properties: {
                    type: "",
                    size: blob.size
                },
                data: data
            });

            fs.write(path, data, function (entry) {
                entry.data = data;
                entry.file(function (file) {
                    entry.properties = entry.properties || {};
                    utils.mixin(file, entry.properties);
                    _set(path, entry);
                });
            }, _fsError);
        }
    },
    dir: {
        createNewDir: function (path) {
            var entry = _get(path),
                info = _getInfo(path);

            if (!entry) {
                _set(path, {
                    name: info.name,
                    isDirectory: true,
                    fullPath: path
                });
            }

            fs.mkdir(path, function (entry) {
                _set(path, entry);
            }, _fsError);
        },

        deleteDirectory: function (path, recursive) {
            _delete(path);
            if (recursive) {
                fs.rm(path, function () {}, _fsError, {recursive: recursive});
            } else {
                fs.rmdir(path, function () {}, _fsError);
            }
        },

        exists: function (path) {
            var entry = _get(path);
            return !!(entry && entry.isDirectory);
        },

        getFreeSpaceForRoot: function (path) {
            function _du(obj, size) {
                utils.forEach(obj, function (child, key) {
                    if (child.isDirectory && child.children) {
                        size += _du(child.children, size);
                    } else if (child.properties && child.properties.size) {
                        size += child.properties.size;
                    }
                });
                return size;
            }

            return constants.FS_SIZE - _du(_cache.children, 0);
        },

        getParentDirectory: function (path) {
            path = "/" + path.replace(/^\//, '').replace(/\/$/, '');

            var entry = _get(path),
                array = path.split("/");

            return entry ? array.splice(0, array.length - 1).join("/") || "/" : null;
        },

        listDirectories: function (path) {
            var dir = _get(path),
                directories = [];

            utils.forEach(dir.children, function (item) {
                if (item.isDirectory) {
                    directories.push(item.name);
                }
            });

            fs.ls(path, function () {}, _fsError);

            return directories;
        },

        listFiles: function (path) {
            var dir = _get(path),
                files = [];

            if (dir) {
                utils.forEach(dir.children, function (item) {
                    if (!item.isDirectory) {
                        files.push(item.name);
                    }
                });
            }

            fs.ls(path, function () {}, _fsError);

            return files;
        },

        rename: function (path, newName) {
            var info = _getInfo(path),
                parent = info.parent,
                oldName = info.name,
                from = (parent === "/" ? "" : parent) + "/" + oldName,
                to =  (parent === "/" ? "" : parent) + "/" + newName;

            _delete(from);
            _set(to, {
                name: info.name,
                fullPath: path
            });

            fs.mv(from, to, function (entry) {
                _set(to, entry);
            }, _fsError);
        },

        getRootDirs: function () {
            return _self.dir.listDirectories("/");
        }
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.core/2.0.0/select', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    _select,
    _predicates = {
        "==": function (left, right) {
            return left === right;
        },
        "!=": function (left, right) {
            return left !== right;
        },
        "<": function (left, right) {
            return left < right;
        },
        ">": function (left, right) {
            return left > right;
        },
        "<=": function (left, right) {
            return left <= right;
        },
        ">=": function (left, right) {
            return left >= right;
        },
        "REGEX": function (left, right) {
            return left && left.match(new RegExp(right));
        },
        "CONTAINS": function (left, right) {
            return left.indexOf(right) >= 0;
        }
    };

function isFilter(field) {
    return field && field.operator !== undefined && field.operator !== null;
}

function extractValue(item, field) {
    return field.split(".").reduce(function (value, prop) {
        return value[prop];
    }, item);
}

function copy(items) {
    //use a reduce to ensure that we always just return an array
    //not the most performant but will whitewash the result
    return utils.reduce(items, function (array, item) {
        array.push(item);
        return array;
    }, []);
}

_select = {
    ops: {
        find: {
            0: "!=",
            1: "==",
            2: "<",
            3: "<=",
            4: ">",
            5: ">=",
            8: "REGEX",
            16: "AND",
            32: "OR",
            64: "CONTAINS"
        },
        phone: {
            0: "!=",
            1: "==",
            2: "<",
            3: "<=",
            4: ">",
            5: ">=",
            8: "AND",
            16: "OR",
            32: "CONTAINS"
        }
    },
    from: function (items) {
        var _getPredicate = function (filter, operators) {

                var noOp = function () {
                        return false;
                    },
                    operator = (function () {
                        var result = operators[filter.operator] || filter.operator,
                            exists = function (op) {
                                return result === op;
                            };

                        return utils.some(operators, exists) ? result : "";
                    }());

                return function (item) {
                    var left = extractValue(item, filter.leftField),
                        right = filter.rightField,
                        predicate = _predicates[operator] || noOp;

                    return filter.negate ? !predicate(left, right) : predicate(left, right);
                };

            },
            _applyFilter = function (filter, operators) {
                var result = [],
                    left,
                    right,
                    op;

                if (isFilter(filter.leftField) && isFilter(filter.rightField)) {

                    left = _select.from(items).where(filter.leftField);
                    right = _select.from(items).where(filter.rightField);
                    op = operators[filter.operator] || filter.operator;

                    switch (op) {
                    case "AND":
                        result = left.filter(function (item) {
                            return right.indexOf(item) >= 0;
                        });
                        break;
                    case "OR":
                        result = left.concat(right.filter(function (item) {
                            return left.indexOf(item) < 0;
                        }));
                        break;
                    }

                    if (filter.negate) {
                        //reverse the result set.
                        result = utils.filter(items, function (item) {
                            return result.indexOf(item) < 0;
                        });
                    }
                }
                else {
                    result = utils.filter(items, _getPredicate(filter, operators));
                }

                return result;
            },
            _orderBy,
            _max,
            _direction,
            _self = {
                orderBy: function (prop, dir) {
                    _orderBy = prop;
                    _direction = dir || "asc";
                    return _self;
                },
                max: function (max) {
                    _max = max;
                    return _self;
                },
                where: function (filter, ops) {
                    var result = isFilter(filter) ? _applyFilter(filter, ops || _select.ops.find) : copy(items);

                    result.sort(function (a, b) {
                        if (a[_orderBy] < b[_orderBy]) {
                            return _direction === "asc" ? -1 : 1;
                        }
                        else if (a[_orderBy] > b[_orderBy]) {
                            return _direction === "asc" ? 1: -1;
                        }
                        return 0;
                    });

                    return result.slice(0, _max === null || _max === -1 ? undefined : _max); // slice in V8 returns empty array if null
                }
            };

        return _self;
    }
};

module.exports = _select;

});
define('ripple/platform/webworks.core/2.0.0/server/dialog', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    devices = require('ripple/devices'),
    ui = require('ripple/ui'),
    utils = require('ripple/utils'),
    isDialogVisible = false,
    visibleDialogArgs,
    _self;

function closeDialog() {
    var buttonsDiv = document.getElementById("dialog-buttons"),
        messageDiv = document.getElementById("dialog-message");

    ui.hideOverlay("dialog-window", function (dialog) {
        buttonsDiv.innerHTML = "";
        messageDiv.innerHTML = "";
        isDialogVisible = false;
    });
}

event.on("LayoutChanged", function () {
    if (isDialogVisible) {
        closeDialog();
        //Used to resize dialog on orientation change
        _self.ask(visibleDialogArgs);
    }
});

_self = {

    ask: function (args, post, baton) {
        if (!args) {
            throw ("No arguments provided");
        } else if (!args.buttons || !args.message) {
            throw ("Invalid arguments");
        }
        baton.take();
        visibleDialogArgs = args;

        ui.showOverlay("dialog-window", function (dialog) {
            var container = document.getElementById("viewport-container"),
                height = window.getComputedStyle(container, null).getPropertyValue("height"),
                width = window.getComputedStyle(container, null).getPropertyValue("width"),
                sizeDiv = document.getElementById("dialog-wrapper"),
                positionDiv = document.getElementById("dialog-window"),
                titleDiv = document.getElementById("dialog-title"),
                buttonsDiv = document.getElementById("dialog-buttons"),
                messageDiv = document.getElementById("dialog-message"),
                position, size;

            if (!messageDiv || !buttonsDiv) {
                return;
            }

            dialog.setAttribute("style", "display:-webkit-box;height:" + height + "; width:" + width + ";");

            position = "overlay-dialog";
            size = "overlay-dialog-wrapper";

            if (args.settings && args.settings.position) {
                position += " overlay-dialog-" + args.settings.position;
            }

            if (args.settings && args.settings.size) {
                size += " overlay-dialog-wrapper-" + args.settings.size;
            }

            positionDiv.setAttribute("class", position);
            sizeDiv.setAttribute("class", size);

            titleDiv.innerHTML = args.settings && args.settings.title ? args.settings.title : "";
            messageDiv.innerHTML = args.message;
            isDialogVisible = true;

            args.buttons.forEach(function (button) {
                var buttonElement = utils.createElement("input", {
                    "type": "button",
                    "value": button
                });
                buttonElement.addEventListener("click", function () {
                    var buttonIndex = args.buttons.indexOf(button);
                    closeDialog();
                    baton.pass({code: 1, data: buttonIndex});
                });
                buttonsDiv.appendChild(buttonElement);
            });
        }, true);
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.core/2.0.0/server/io/dir', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 cache = require('ripple/platform/webworks.core/2.0.0/fsCache');

function _packet(data) {
    return {
        code: 1,
        data: data
    };
}

module.exports = {
    createNewDir: function (get, post, baton) {
        cache.dir.createNewDir(post.path);
        return _packet();
    },
    deleteDirectory: function (get, post, baton) {
        cache.dir.deleteDirectory(post.path, post.recursive);
        return _packet();
    },
    exists: function (get, post, baton) {
        return _packet(cache.dir.exists(post.path));
    },
    getParentDirectory: function (get, post, baton) {
        return _packet(cache.dir.getParentDirectory(post.path));
    },
    listDirectories: function (get, post, baton) {
        return _packet(cache.dir.listDirectories(post.path));
    },
    listFiles: function (get, post, baton) {
        return _packet(cache.dir.listFiles(post.path));
    },
    rename: function (get, post, baton) {
        cache.dir.rename(post.path, post.newName);
        return _packet();
    }
};

});
define('ripple/platform/webworks.core/2.0.0/server/io/file', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 cache = require('ripple/platform/webworks.core/2.0.0/fsCache'),
    constants = require('ripple/constants'),
    notifications = require('ripple/notifications');

function _packet(data) {
    return {
        code: 1,
        data: data
    };
}

module.exports = {
    copy: function (get, post, baton) {
        cache.file.copy(post.from, post.to);
        return _packet();
    },
    deleteFile: function (get, post, baton) {
        cache.file.deleteFile(post.path);
        return _packet();
    },
    exists: function (get, post, baton) {
        return _packet(cache.file.exists(post.path));
    },
    getFileProperties: function (get, post, baton) {
        return _packet(cache.file.getFileProperties(post.path));
    },
    open: function (get, post, baton) {
        var msg = "Attempting to open file: " + post.path;
        notifications.openNotification("normal", msg);
        return _packet(cache.file.exists(post.path));
    },
    readFile: function (get, post, baton) {
        var val;

        if (post.async) {
            baton.take();
        }

        cache.file.readFile(post.path, function (data) {
            if (post.async) {
                baton.pass(_packet({
                    fullPath: post.path,
                    blobData: data
                }));
            } else {
                val = data;
            }
        }, post.async);

        if (!post.async) {
            return _packet({
                fullPath: post.path,
                blobData: val
            });
        }
    },
    rename: function (get, post, baton) {
        cache.file.rename(post.path, post.newName);
        return _packet();
    },
    saveFile: function (get, post, baton) {
        cache.file.saveFile(post.path, post.blob);
        return _packet();
    }
};

});
define('ripple/platform/webworks.core/2.0.0/server/system', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 deviceSettings = require('ripple/deviceSettings'),
    devices = require('ripple/devices'),
    app = require('ripple/app'),
    client = require('ripple/platform/webworks.core/2.0.0/client/system'),
    utils = require('ripple/utils'),
    notifications = require('ripple/notifications'),
    constants = require('ripple/constants'),
    platform = require('ripple/platform'),
    _self;

function _is(feature) {
    return {
        allowedFor: function (location) {
            return feature && feature.URIs.some(function (uri) {
                return uri.value === location ||
                      (location.indexOf(uri.value) >= 0 && uri.subdomains);
            });
        }
    };
}

_self = {
    hasCapability: function (args) {
        var capabilities = devices.getCurrentDevice().capabilities;
        return {
            code: 1,
            data: capabilities ? capabilities.some(function (type) {
                return type === args.capability;
            }) : false
        };
    },
    isMassStorageActive: function () {
        return {code: 1, data: deviceSettings.retrieveAsBoolean("system.isMassStorageActive")};
    },
    hasDataCoverage: function () {
        return {code: 1, data: deviceSettings.retrieveAsBoolean("system.hasDataCoverage")};
    },
    softwareVersion: function () {
        return {code: 1, data: devices.getCurrentDevice().osVersion};
    },
    model: function () {
        return {code: 1, data: devices.getCurrentDevice().model};
    },
    scriptApiVersion: function () {
        return {code: 1, data: platform.current().version};
    },
    setHomeScreenBackground: function (args) {
        var path = args.filePath,
            msg = "Set home screen background to " + path + ".";
        notifications.openNotification("normal", msg);
        return {code: 1};
    },
    hasPermission: function (args) {
        var info = app.getInfo(),
            feature = info.features ? info.features[args.desiredModule] : null;

        return {code: 1, data: feature === null || _is(feature).allowedFor(utils.location().href) ? client.ALLOW : client.DENY};
    },
    network: function () {
        return {code: 1, data: deviceSettings.retrieve("system.network")};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.core/2.0.0/spec/config', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils');

module.exports = {
    fileName: "config.xml",
    validateVersion: function (config) {
        return true;
    },
    extractInfo: function (config) {
        if (!config) {
            return null;
        }

        var widgetInfo = {},
            widgetFeatures = config.widget.children.feature.validationResult,
            accessUrls = config.widget.children.access.validationResult,
            accessFeatures = config.widget.children.access.children.feature.validationResult,
            toFeature = function (validationResult) {
                return {
                    id: validationResult.attributes.id.value,
                    required: !validationResult.attributes.required || validationResult.attributes.required.value,
                    URIs: []
                };
            };

        widgetInfo.id = config.widget.validationResult[0].attributes.id.value;
        widgetInfo.name = config.widget.children.name.validationResult[0].value;
        widgetInfo.icon = config.widget.children.icon.validationResult[0].attributes.src.value;
        widgetInfo.version = config.widget.validationResult[0].attributes.version.value;
        widgetInfo.author = config.widget.children.author.validationResult[0].value;
        widgetInfo.authorEmail = config.widget.children.author.validationResult[0].attributes.email.value;
        widgetInfo.authorURL = config.widget.children.author.validationResult[0].attributes.href.value;
        widgetInfo.copyright = config.widget.children.author.validationResult[0].attributes["rim:copyright"].value;
        widgetInfo.description = config.widget.children.description.validationResult[0].value;
        if (config.widget.children.license.validationResult[0]) {
            widgetInfo.license = config.widget.children.license.validationResult[0].value;
            widgetInfo.licenseURL = config.widget.children.license.validationResult[0].attributes.href.value;
        }

        widgetInfo.features = widgetFeatures.reduce(function (features, validationResult) {
            if (validationResult.valid) {
                var feature = toFeature(validationResult);
                feature.URIs.push({
                    value: utils.location().href,
                    subdomains: true
                });
                features = features || {};
                features[feature.id] = feature;
            }
            return features;
        }, {});

        widgetInfo.features = accessUrls.map(function (access) {
            return {
                uri: access.attributes.uri.value,
                subdomains: access.attributes.subdomains.value,
                features: accessFeatures ? accessFeatures.filter(function (f) {
                    return f.node && f.node.parentNode && f.node.parentNode.attributes.uri.value === access.attributes.uri.value;
                }) : null
            };
        }).reduce(function (result, access) {
            return access.features ? access.features.reduce(function (features, validationResult) {
                var feature = features[validationResult.attributes.id.value] || toFeature(validationResult);
                feature.URIs.push({
                    value: access.uri,
                    subdomains: access.subdomains
                });
                features[feature.id] = feature;
                return features;
            }, result) : result;
        }, widgetInfo.features);

        return widgetInfo;
    },
    schema: {
        rootElement: "widget",
        widget: {
            nodeName: "widget",
            required: true,
            occurrence: 1,
            attributes: {
                xmlns: {
                    attributeName: "xmlns",
                    required: true,
                    type: "list",
                    listValues: ["http://www.w3.org/ns/widgets"]
                },
                "xmlns:rim": {
                    attributeName: "xmlns:rim",
                    required: true,
                    type: "list",
                    listValues: ["http://www.blackberry.com/ns/widgets"]
                },
                "xml:lang": {
                    attributeName: "xml:lang",
                    required: false,
                    type: "iso-language"
                },
                id: {
                    attributeName: "id",
                    required: false,
                    type: "string"
                },
                version: {
                    attributeName: "version",
                    required: false,
                    type: "string"
                },
                "rim:header": {
                    attributeName: "rim:header",
                    required: false,
                    type: "string"
                },
                "rim:backButton": {
                    attributeName: "rim:backButton",
                    required: false,
                    type: "string"
                }
            },
            children: {
                name: {
                    nodeName: "name",
                    required: true,
                    occurrence: 1,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        "its:dir": {
                            attributeName: "its:dir",
                            required: false,
                            type: "list",
                            listValues: ["rtl", "ltr", "lro", "rlo"]
                        }
                    }
                },
                description: {
                    nodeName: "description",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        "its:dir": {
                            attributeName: "its:dir",
                            required: false,
                            type: "list",
                            listValues: ["rtl", "ltr", "lro", "rlo"]
                        }
                    }
                },
                icon: {
                    nodeName: "icon",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        src: {
                            attributeName: "src",
                            type: "string",
                            required: true
                        },
                        "rim:hover": {
                            attributeName: "rim:hover",
                            type: "boolean",
                            required: false
                        }
                    }
                },
                author: {
                    nodeName: "author",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        href: {
                            attributeName: "href",
                            type: "string",
                            required: false
                        },
                        "rim:copyright": {
                            attributeName: "rim:copyright",
                            type: "string",
                            required: false
                        },
                        email: {
                            attributeName: "email",
                            type: "string",
                            required: false
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        "its:dir": {
                            attributeName: "its:dir",
                            required: false,
                            type: "list",
                            listValues: ["rtl", "ltr", "lro", "rlo"]
                        }
                    }
                },
                license: {
                    nodeName: "license",
                    required: false,
                    occurrence: 1,
                    attributes : {
                        href: {
                            attributeName: "href",
                            type: "string",
                            required: false
                        },
                        "xml:lang": {
                            attributeName: "xml:lang",
                            required: false,
                            type: "iso-language"
                        },
                        "its:dir": {
                            attributeName: "its:dir",
                            required: false,
                            type: "list",
                            listValues: ["rtl", "ltr", "lro", "rlo"]
                        }
                    }
                },
                "rim:cache": {
                    nodeName: "rim:cache",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        disableAllCache: {
                            attributeName: "disableAllCache",
                            required: false,
                            type: "boolean"
                        },
                        aggressiveCacheAge: {
                            attributeName: "aggressiveCacheAge",
                            required: false,
                            type: "number"
                        },
                        maxCacheSizeTotal: {
                            attributeName: "maxCacheSizeTotal",
                            required: false,
                            type: "number"
                        },
                        maxCacheSizeItem: {
                            attributeName: "maxCacheSizeItem",
                            required: false,
                            type: "number"
                        }
                    }
                },
                access: {
                    nodeName: "access",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        uri: {
                            attributeName: "uri",
                            required: true,
                            type: "string"
                        },
                        subdomains: {
                            attributeName: "subdomains",
                            required: false,
                            type: "boolean"
                        }
                    },
                    children: {
                        feature: {
                            nodeName: "feature",
                            required: false,
                            occurrence: 0,
                            attributes: {
                                id: {
                                    attributeName: "id",
                                    required: true,
                                    //TODO: this should be a list
                                    type: "string"
                                },
                                required: {
                                    attributeName: "required",
                                    required: false,
                                    type: "boolean"
                                },
                                version: {
                                    attributeName: "version",
                                    required: false,
                                    type: "string"
                                }
                            }
                        }
                    }
                },
                feature: {
                    nodeName: "feature",
                    required: false,
                    occurrence: 0,
                    attributes: {
                        id: {
                            attributeName: "id",
                            required: true,
                            //TODO: this should be a list
                            type: "string"
                        },
                        required: {
                            attributeName: "required",
                            required: false,
                            type: "boolean"
                        },
                        version: {
                            attributeName: "version",
                            required: false,
                            type: "string"
                        }
                    }
                },
                "rim:loadingScreen": {
                    nodeName: "rim:loadingScreen",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        backgroundColor: {
                            attributeName: "backgroundColor",
                            required: false,
                            type: "string"
                        },
                        backgroundImage: {
                            attributeName: "backgroundImage",
                            required: false,
                            type: "string"
                        },
                        foregroundImage: {
                            attributeName: "foregroundImage",
                            required: false,
                            type: "string"
                        },
                        onRemotePageLoad: {
                            attributeName: "onRemotePageLoad",
                            required: false,
                            type: "boolean"
                        },
                        onLocalPageLoad: {
                            attributeName: "onLocalPageLoad",
                            required : false,
                            type: "boolean"
                        },
                        onFirstLaunch: {
                            attributeName: "onFirstLaunch",
                            required: false,
                            type: "boolean"
                        }
                    },
                    children: {
                        "rim:transitionEffect": {
                            nodeName: "rim:transitionEffect",
                            required: false,
                            occurrence: 1,
                            attributes: {
                                "type": {
                                    attributeName: "type",
                                    required: true,
                                    type: "list",
                                    listValues: ["slidePush", "slideOver", "fadeIn", "fadeOut", "wipeIn", "wipeOut", "zoomIn", "zoomOut"]
                                },
                                duration: {
                                    attributeName: "duration",
                                    required: false,
                                    type: "number"
                                },
                                direction: {
                                    attributeName: "direction",
                                    required: false,
                                    type: "list",
                                    listValues: ["left", "right", "up", "down"]
                                }
                            }
                        }
                    }
                },
                "rim:connection": {
                    nodeName: "rim:connection",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        timeout: {
                            attributeName: "timeout",
                            required: false,
                            type: "number"
                        }
                    },
                    children: {
                        id: {
                            nodeName: "id",
                            required: false,
                            occurrence: 0
                        }
                    }
                },
                "rim:navigation": {
                    nodeName: "rim:navigation",
                    required: false,
                    occurrence: 1,
                    attributes: {
                        mode: {
                            attributeName: "mode",
                            required: false,
                            type: "list",
                            listValues: ["focus"]
                        }
                    }
                },
                "content": {
                    nodeName: "content",
                    required: true,
                    occurrence: 1,
                    attributes: {
                        src: {
                            attributeName: "src",
                            required: true,
                            type: "string"
                        },
                        type: {
                            attributeName: "type",
                            required: false,
                            type: "string"
                        },
                        charset: {
                            attributeName: "charset",
                            required: false,
                            type: "string"
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/webworks.core/2.0.0/spec/events', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event');

module.exports = {
    "app.event.onBackground": {
        callback: function () {
            event.trigger("AppRequestBackground");
        }
    },
    "app.event.onForeground": {
        callback: function () {
            event.trigger("AppRequestForeground");
        }
    }
};

});
define('ripple/platform/webworks.handset/2.0.0/XMLHttpRequest', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 xhr = require("ripple/platform/webworks.core/2.0.0/XMLHttpRequest");
module.exports = xhr.create("ripple/platform/webworks.handset/2.0.0/server");

});
define('ripple/platform/webworks.handset/2.0.0/client/Address', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function Address() {
    return {
        //readwrite  property  String   address1
        //readwrite  property  String   address2
        //readwrite  property  String   city
        //readwrite  property  String   country
        //readwrite  property  String   stateProvince
        //readwrite  property  String   zipPostal

        address1: null,
        address2: null,
        city: null,
        country: null,
        stateProvince: null,
        zipPostal: null
    };
}

module.exports = Address;

});
define('ripple/platform/webworks.handset/2.0.0/client/AddressBookArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.AddressBookArguments ( [contact : blackberry.pim.Contact ] )
var _self = function (contact) {
    return {
        contact: contact,
        //readwrite  property  Number   view
        view: 0
    };
};

//const Number  VIEW_NEW  = 0
_self.__defineGetter__("VIEW_NEW", function () {
    return 0;
});
//const Number  VIEW_COMPOSE  = 1
_self.__defineGetter__("VIEW_COMPOSE", function () {
    return 1;
});
//const Number  VIEW_DISPLAY  = 2
_self.__defineGetter__("VIEW_DISPLAY", function () {
    return 2;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/Appointment', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    utils = require('ripple/utils'),
    _uri = "blackberry/pim/appointment/";

function Appointment(service) {
    var _self = {
        allDay: false,
        attendees: [],
        end: null,
        freeBusy: null,
        location: null,
        note: null,
        recurrence: null,
        reminder: null,
        start: null,
        summary: null,
        uid: null,
        remove: function () {
            transport.call(_uri + "remove", {get: {uid: _self.uid}});
        },
        save: function () {
            if (_self.uid === null) {
                _self.uid  = Number(Math.uuid(8, 10));
            }
            transport.call(_uri + "save", {post: {appointment: _self}});
        }
    };

    return _self;
}

function _massage(property, name) {
    if (name === "recurrence" && property) {
        if (property.end) {
            property.end = new Date(property.end);
        }
    }
    if (name === "reminder" && property) {
        if (property.date) {
            property.date = new Date(property.date);
        }
    }
    if ((name === "end" || name === "start") && property) {
        property = new Date(property);
    }
    return property;
}

Appointment.find = function (filter, orderBy, maxReturn, service, isAscending) {
    var opts = {
        post: {
            filter: filter,
            orderBy: orderBy,
            maxReturn: maxReturn,
            service: service,
            isAscending: isAscending
        }
    };

    return transport.call(_uri + "find", opts).map(function (obj) {
        var appt = new Appointment();
        appt.allDay = obj.allDay;
        appt.attendees = obj.attendees;
        appt.end = _massage(obj.end, "end");
        appt.freeBusy = obj.freeBusy;
        appt.location = obj.location;
        appt.note = obj.note;
        appt.recurrence = _massage(obj.recurrence, "recurrence");
        appt.reminder = _massage(obj.reminder, "reminder");
        appt.start = _massage(obj.start, "start");
        appt.summary = obj.summary;
        appt.uid = obj.uid;
        return appt;
    });
};

Appointment.__defineGetter__("FREE", function () {
    return 0;
});
Appointment.__defineGetter__("TENTATIVE", function () {
    return 1;
});
Appointment.__defineGetter__("BUSY", function () {
    return 2;
});
Appointment.__defineGetter__("OUT_OF_OFFICE", function () {
    return 3;
});

module.exports = Appointment;

});
define('ripple/platform/webworks.handset/2.0.0/client/Attendee', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function Attendee() {
    return {
        //readwrite  property  String   address
        //readwrite  property  Number   type

        address: null,
        type: null
    };
}

Attendee.__defineGetter__("ORGANIZER", function () {
    return 0;
});

Attendee.__defineGetter__("INVITED", function () {
    return 1;
});

Attendee.__defineGetter__("ACCEPTED", function () {
    return 2;
});

Attendee.__defineGetter__("DECLINED", function () {
    return 3;
});

Attendee.__defineGetter__("TENTATIVE", function () {
    return 4;
});

module.exports =  Attendee;

});
define('ripple/platform/webworks.handset/2.0.0/client/AudioPlayer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/audio/player/";

function Player(locator, type, async) {
    //we can't use the async prop since we need the ID before we can do anything else.
    var _id = transport.call(_uri + "create", {
            get: {locator: locator, type: type},
            async: false
        }),
        _listener,
        _closed,
        _self,
        _poll = function (path) {
            transport.poll(_uri + path, {
                get: {id: _id}
            }, function (response) {
                if (_listener) {
                    _listener(_self, response.event, response.eventData);
                }

                return !!_listener;
            });
        };

    _self = {
        addPlayerListener: function (callback) {
            if (!_closed && callback) {
                _listener = callback;
                _poll("onStart");
                _poll("onStopped");
                _poll("onBufferingStarted");
                _poll("onBufferingStopped");
                _poll("onDurationUpdated");
                _poll("onEnd");
                _poll("onError");
                _poll("onVolumeChange");
                _poll("onClose");
            }
            else {
                _listener = null;
            }

            return !_closed;
        },

        close: function () {
            _listener = null;
            _closed = true;
            return transport.call(_uri + "close", {get: {id: _id}});
        },

        pause: function () {
            return transport.call(_uri + "pause", {get: {id: _id}});
        },

        play: function () {
            return transport.call(_uri + "play", {get: {id: _id}});
        }
    };

    _self.__defineGetter__("duration", function () {
        return transport.call(_uri + "getDuration", {get: {id: _id}});
    });

    _self.__defineGetter__("mediaTime", function () {
        return transport.call(_uri + "getMediaTime", {get: {id: _id}});
    });

    _self.__defineSetter__("mediaTime", function (val) {
        transport.call(_uri + "setMediaTime", {get: {id: _id, value: val}});
    });

    _self.__defineGetter__("state", function () {
        return transport.call(_uri + "getState", {get: {id: _id}});
    });

    _self.__defineGetter__("volumeLevel", function () {
        return transport.call(_uri + "getVolumeLevel", {get: {id: _id}});
    });

    _self.__defineSetter__("volumeLevel", function (val) {
        transport.call(_uri + "setVolumeLevel", {get: {id: _id, value: val}});
    });

    _self.__defineGetter__("EVENT_BUFFERING_STARTED", function () {
        return "EVENT_BUFFERING_STARTED";
    });
    _self.__defineGetter__("EVENT_BUFFERING_STOPPED", function () {
        return "EVENT_BUFFERING_STOPPED";
    });
    _self.__defineGetter__("EVENT_CLOSED", function () {
        return "EVENT_CLOSED";
    });
    _self.__defineGetter__("EVENT_DEVICE_AVAILABLE", function () {
        return "EVENT_DEVICE_AVAILABLE";
    });
    _self.__defineGetter__("EVENT_DEVICE_UNAVAILABLE", function () {
        return "EVENT_DEVICE_UNAVAILABLE";
    });
    _self.__defineGetter__("EVENT_DURATION_UPDATED", function () {
        return "EVENT_DURATION_UPDATED";
    });
    _self.__defineGetter__("EVENT_END_OF_MEDIA", function () {
        return "EVENT_END_OF_MEDIA";
    });
    _self.__defineGetter__("EVENT_ERROR", function () {
        return "EVENT_ERROR";
    });
    _self.__defineGetter__("EVENT_RECORD_ERROR", function () {
        return "EVENT_ERROR";
    });
    _self.__defineGetter__("EVENT_RECORD_STARTED", function () {
        return "EVENT_RECORD_STARTED";
    });
    _self.__defineGetter__("EVENT_RECORD_STOPPED", function () {
        return "EVENT_RECORD_STOPPED";
    });
    _self.__defineGetter__("EVENT_SIZE_CHANGED", function () {
        return "EVENT_SIZE_CHANGED";
    });
    _self.__defineGetter__("EVENT_STARTED", function () {
        return "EVENT_STARTED";
    });
    _self.__defineGetter__("EVENT_STOPPED", function () {
        return "EVENT_STOPPED";
    });
    _self.__defineGetter__("EVENT_STOPPED_AT_TIME", function () {
        return "EVENT_STOPPED_AT_TIME";
    });
    _self.__defineGetter__("EVENT_VOLUME_CHANGED", function () {
        return "EVENT_VOLUME_CHANGED";
    });

    return _self;
}

Player.__defineGetter__("TIME_UNKNOWN", function () {
    return -1;
});
Player.__defineGetter__("CLOSED", function () {
    return 0;
});
Player.__defineGetter__("UNREALIZED", function () {
    return 100;
});
Player.__defineGetter__("REALIZED", function () {
    return 200;
});
Player.__defineGetter__("PREFETCHED", function () {
    return 300;
});
Player.__defineGetter__("STARTED", function () {
    return 400;
});

module.exports = Player;

});
define('ripple/platform/webworks.handset/2.0.0/client/BrowserArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.BrowserArguments ( url : String ,  [transport : blackberry.identity.Transport ] )
module.exports = function (url, transport) {
    return {
        url: url
    };
};

});
define('ripple/platform/webworks.handset/2.0.0/client/CalendarArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.CalendarArguments ( )
//blackberry.invoke.CalendarArguments ( date : Date )
//blackberry.invoke.CalendarArguments ( appointment : blackberry.pim.Appointment )
var _self = function () {
    //readonly  property  Appointment   appointment
    //readonly  property  Date   date
    //readwrite  property  Number   view
    return {
        appointment: undefined,
        date: undefined,
        view: 0
    };
};

//const Number  VIEW_NEW  = 0
_self.__defineGetter__("VIEW_NEW", function () {
    return 0;
});
//const Number  VIEW_VIEW  = 1
_self.__defineGetter__("VIEW_VIEW", function () {
    return 1;
});
//const Number  VIEW_AGENDA  = 2
_self.__defineGetter__("VIEW_AGENDA", function () {
    return 2;
});
//const Number  VIEW_DAY  = 3
_self.__defineGetter__("VIEW_DAY", function () {
    return 3;
});
//const Number  VIEW_DEFAULT  = 4
_self.__defineGetter__("VIEW_DEFAULT", function () {
    return 4;
});
//const Number  VIEW_MONTH  = 5
_self.__defineGetter__("VIEW_MONTH", function () {
    return 5;
});
//const Number  VIEW_WEEK  = 6
_self.__defineGetter__("VIEW_WEEK", function () {
    return 6;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/CallLog', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function CallLog() {
    // readwrite  property  String   addressBookNumber
    // readwrite  property  String   addressBookType
    // readwrite  property  Date   date
    // readwrite  property  Number   duration
    // readwrite  property  String   name
    // readwrite  property  String   notes
    // readwrite  property  String   number
    // readwrite  property  Number   status
    // readwrite  property  Number   type
    this.addressBookNumber = null;
    this.addressBookType = null;
    this.date = null;
    this.duration = null;
    this.name = null;
    this.notes = null;
    this.number = null;
    this.status = null;
    this.type = null;
}

function _get(val) {
    return function () {
        return val;
    };
}

CallLog.__defineGetter__("STATUS_NORMAL", _get(0));
CallLog.__defineGetter__("STATUS_BUSY", _get(1));
CallLog.__defineGetter__("STATUS_CONGESTION", _get(2));
CallLog.__defineGetter__("STATUS_PATH_UNAVAILABLE", _get(3));
CallLog.__defineGetter__("STATUS_NUMBER_UNOBTAINABLE", _get(4));
CallLog.__defineGetter__("STATUS_AUTHENTICATION_FAILURE", _get(5));
CallLog.__defineGetter__("STATUS_EMERGENCY_CALLS_ONLY", _get(6));
CallLog.__defineGetter__("STATUS_HOLD_ERROR", _get(7));
CallLog.__defineGetter__("STATUS_OUTGOING_CALLS_BARRED", _get(8));
CallLog.__defineGetter__("STATUS_GENERAL_ERROR", _get(9));
CallLog.__defineGetter__("STATUS_MAINTENANCE_REQUIRED", _get(10));
CallLog.__defineGetter__("STATUS_SERVICE_NOT_AVAILABLE", _get(11));
CallLog.__defineGetter__("STATUS_CALL_FAIL_DUE_TO_FADING", _get(12));
CallLog.__defineGetter__("STATUS_CALL_LOST_DUE_TO_FADING", _get(13));
CallLog.__defineGetter__("STATUS_CALL_FAILED_TRY_AGAIN", _get(14));
CallLog.__defineGetter__("STATUS_FDN_MISMATCH", _get(15));
CallLog.__defineGetter__("STATUS_CONNECTION_DENIED", _get(16));
CallLog.__defineGetter__("STATUS_INCOMING_CALL_BARRED", _get(17));
CallLog.__defineGetter__("TYPE_RECEIVED_CALL", _get(0));
CallLog.__defineGetter__("TYPE_PLACED_CALL", _get(1));
CallLog.__defineGetter__("TYPE_MISSED_CALL_UNOPENED", _get(2));
CallLog.__defineGetter__("TYPE_MISSED_CALL_OPENED", _get(3));

module.exports = CallLog;

});
define('ripple/platform/webworks.handset/2.0.0/client/CameraArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.CameraArguments ( )
var _self = function () {
    return {
        //readwrite  property  Number   view
        view: 0
    };
};

//const Number  VIEW_CAMERA  = 0
_self.__defineGetter__("VIEW_CAMERA", function () {
    return 0;
});
//const Number  VIEW_RECORDER  = 1
_self.__defineGetter__("VIEW_RECORDER", function () {
    return 1;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/Contact', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/pim/contact/";

function Contact(service) {
    var _self = {
        anniversary: null,
        birthday: null,
        categories: [],
        company: null,
        email1: "",
        email2: "",
        email3: "",
        faxPhone: null,
        firstName: null,
        homeAddress: null,
        homePhone: null,
        homePhone2: null,
        jobTitle: null,
        lastName: null,
        mobilePhone: null,
        note: null,
        otherPhone: null,
        pagerPhone: null,
        picture: null,
        pin: null,
        title: null,
        uid: null,
        user1: null,
        user2: null,
        user3: null,
        user4: null,
        webpage: null,
        workAddress: null,
        workPhone: null,
        workPhone2: null,
        remove: function () {
            if (!_self.uid) {
                throw "task has not yet been saved (has no uid)";
            }
            transport.call(_uri + "remove", {
                get: { id: _self.uid }
            });
        },
        save: function () {
            if (!_self.uid) {
                _self.uid = Math.uuid(null, 16);
            }
            transport.call(_uri + "save", {
                post: { contact: _self }
            });
        },
        setPicture: function (picture) {
            throw "not implemented";
        }
    };

    return _self;
}

function _massage(property, name) {
    if ((name === "anniversary" || name === "birthday") && property) {
        return new Date(property);
    }
    return property;
}

Contact.find = function (fieldFilter, orderBy, maxReturn, service, isAscending) {
    return transport.call(_uri + "find", {
        post: {
            fieldFilter: fieldFilter,
            orderBy: orderBy,
            maxReturn: maxReturn,
            service: service,
            isAscending: isAscending
        }
    }).map(function (properties) {
        var contact = new Contact(),
            key;
        for (key in properties) {
            if (contact.hasOwnProperty(key)) {
                contact[key] = _massage(properties[key], key);
            }
        }
        return contact;
    });
};

module.exports = Contact;

});
define('ripple/platform/webworks.handset/2.0.0/client/FilterExpression', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.find.FilterExpression ( leftField  : object ,  operator  : object ,  rightField : object ,  [negate : Boolean ] )
var FilterExpression = function (leftField, operator, rightField, negate) {
    this.__defineGetter__("leftField", function () {
        return leftField;
    });

    this.__defineGetter__("operator", function () {
        return operator;
    });

    this.__defineGetter__("rightField", function () {
        return rightField;
    });

    this.__defineGetter__("negate", function () {
        return negate ? true : false;
    });
};

module.exports = FilterExpression;

});
define('ripple/platform/webworks.handset/2.0.0/client/JavaArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.JavaArguments ( uri : String ,  [params : String [ ] ] )
var _self = function (uri, params) {
    return {
        uri: uri,
        params: params,
        args: arguments
    };
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/MapsArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.MapsArguments ( )
//blackberry.invoke.MapsArguments ( latitude : Number ,  longitude : Number )
//blackberry.invoke.MapsArguments ( locationDocument : Document ) - Supported in 5.0.0 only
//blackberry.invoke.MapsArguments ( locationDocument : String ) - Supported in 6.0.0 only
//blackberry.invoke.MapsArguments ( address : blackberry.pim.Address )
var _self = function () {
    return {};
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/Memo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/pim/memo/";

function Memo() {
    var _self = {
        categories: [],
        note: null,
        title: null,
        uid: null,
        remove: function () {
            transport.call(_uri + "remove", {
                get: {uid: _self.uid}
            });
        },
        save: function () {
            if (_self.uid  === null) {
                _self.uid  = Number(Math.uuid(8, 10));
            }
            transport.call(_uri + "save", {
                post: {memo: _self}
            });
        }
    };

    return _self;
}

Memo.find = function (filter, orderBy, maxReturn, service, isAscending) {
    var opts = {
        post: {
            filter: filter,
            orderBy: orderBy,
            maxReturn: maxReturn,
            isAscending: isAscending,
            service: service
        }
    };

    return transport.call(_uri + "find", opts).map(function (obj) {
        var memo = new Memo();
        memo.uid = obj.uid;
        memo.categories = obj.categories || [];
        memo.note = obj.note;
        memo.title = obj.title;
        return memo;
    });
};

module.exports = Memo;

});
define('ripple/platform/webworks.handset/2.0.0/client/MemoArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.MemoArguments ( [memo : blackberry.pim.Memo ] )
var _self = function (memo) {
    return {
        memo: memo,
        view: 0
    };
};

//const Number  VIEW_NEW  = 0
_self.__defineGetter__("VIEW_NEW", function () {
    return 0;
});
//const Number  VIEW_EDIT  = 1
_self.__defineGetter__("VIEW_EDIT", function () {
    return 1;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/MenuItem', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    event = require('ripple/event');

function MenuItem(isSeparator, ordinal, caption, callback) {
    var _isDefault = false,
	id = Math.uuid();

    if (ordinal < 0) {
        throw "Ordinal cannot be less than 0";
    } else if (isSeparator) {
        if (caption !== undefined) {
            throw "caption must not be supplied";
        } else if (callback !== undefined) {
            throw "callback must not be supplied";
        }
    } else if (!isSeparator) {
        if (caption === undefined) {
            throw "caption must be supplied";
        }
    }

    this.callback = callback;

    this.__defineSetter__("id", function (i) {
        id = i;
    });

    this.__defineGetter__("id", function () {
        return id;
    });

    this.__defineSetter__("caption", function (c) {
        caption = c;
        event.trigger("MenuItemChanged", [this]);
    });

    this.__defineGetter__("caption", function () {
        return caption;
    });

    this.__defineSetter__("ordinal", function (o) {
        ordinal = o;
        event.trigger("MenuItemChanged", [this]);
    });

    this.__defineGetter__("ordinal", function () {
        return ordinal;
    });

    this.__defineGetter__("isSeparator", function () {
        return isSeparator;
    });

    this.__defineSetter__("isDefault", function (d) {
        _isDefault = d;
        event.trigger("MenuItemChanged", [this]);
    });

    this.__defineGetter__("isDefault", function () {
        return _isDefault;
    });

    this.__defineGetter__("id", function () {
        return id;
    });
}

module.exports = MenuItem;

});
define('ripple/platform/webworks.handset/2.0.0/client/Message', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/platform/webworks.core/2.0.0/client/utils'),
    identity = require('ripple/platform/webworks.handset/2.0.0/client/identity'),
    transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    Service = require('ripple/platform/webworks.handset/2.0.0/client/identity/Service'),
    select = require('ripple/platform/webworks.core/2.0.0/select'),
    _uri = "blackberry/message/message/";

function Message(service) {
    var _service = service,
        _msg = {
            uid: 0,
            status: Message.STATUS_DRAFT,
            from: "",
            folder: Message.FOLDER_DRAFT,
            replyTo: "",
            bccRecipients: "",
            body: "",
            ccRecipients: "",
            priority: Message.PRIORITY_MEDIUM, //default to med priority
            subject: "",
            toRecipients: "",

            remove: function () {
                _msg.folder = Message.FOLDER_DELETED;
                transport.call(_uri + "remove", {
                    get: {uid: _msg.uid}
                });
            },

            save: function () {
                if (_msg.uid === 0) {
                    _msg.uid = Number(Math.uuid(8, 10));
                }

                _msg.replyTo  = _msg.from = _service.emailAddress;
                _msg.status =  Message.STATUS_SAVED;
                transport.call(_uri + "save", {
                    post: {message: _msg}
                });
            },

            send: function () {
                if (_msg.toRecipients) {
                    if (_msg.uid === 0) {
                        _msg.uid = Number(Math.uuid(8, 10));
                    }

                    _msg.folder = Message.FOLDER_DRAFT;
                    _msg.status = Message.STATUS_UNKNOWN;
                    transport.call(_uri + "send", {
                        get: {message: _msg}
                    });
                } else {
                    throw "message has no recipients";
                }
            }
        };

    if (!_service) {
        _service = identity.getDefaultService().reduce(function (email, service) {
            return service.type === Service.TYPE_EMAIL ? service : email;
        }, null);
    }

    return _msg;
}

Message.find = function (filter, maxReturn, service) {
    var opts = {
        post: {
            filter: filter,
            maxReturn: maxReturn,
            service: service
        }
    };

    return transport.call(_uri + "find", opts).map(function (obj) {
        var msg = new Message();

        msg.uid = obj.uid;
        msg.status = obj.status;
        msg.from = obj.from;
        msg.folder = obj.folder;
        msg.replyTo = obj.replyTo;
        msg.bccRecipients = obj.bccRecipients;
        msg.body = obj.body;
        msg.ccRecipients = obj.ccRecipients;
        msg.priority = obj.priority;
        msg.subject = obj.subject;
        msg.toRecipients = obj.toRecipients;

        return msg;
    });
};


Message.__defineGetter__("STATUS_UNKNOWN", function () {
    return -1;
});
Message.__defineGetter__("STATUS_SAVED", function () {
    return 0;
});
Message.__defineGetter__("STATUS_DRAFT", function () {
    return 1;
});
Message.__defineGetter__("STATUS_SENT", function () {
    return 2;
});
Message.__defineGetter__("STATUS_ERROR_OCCURED", function () {
    return 3;
});
Message.__defineGetter__("PRIORITY_HIGH", function () {
    return 0;
});
Message.__defineGetter__("PRIORITY_MEDIUM", function () {
    return 1;
});
Message.__defineGetter__("PRIORITY_LOW", function () {
    return 2;
});
Message.__defineGetter__("FOLDER_INBOX", function () {
    return 0;
});
Message.__defineGetter__("FOLDER_SENT", function () {
    return 1;
});
Message.__defineGetter__("FOLDER_DRAFT", function () {
    return 2;
});
Message.__defineGetter__("FOLDER_OUTBOX", function () {
    return 3;
});
Message.__defineGetter__("FOLDER_DELETED", function () {
    return 4;
});
Message.__defineGetter__("FOLDER_OTHER", function () {
    return 5;
});

module.exports = Message;

});
define('ripple/platform/webworks.handset/2.0.0/client/MessageArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.MessageArguments ( )
//blackberry.invoke.MessageArguments ( message : blackberry.message.Message )
//blackberry.invoke.MessageArguments ( to : String ,  subject : String ,  body : String )
var _self = function () {
    return {
        view: 1
    };
};

//const Number  VIEW_NEW  = 0
_self.__defineGetter__("VIEW_NEW", function () {
    return 0;
});
//const Number  VIEW_DEFAULT  = 1
_self.__defineGetter__("VIEW_DEFAULT", function () {
    return 1;
});
//const Number  VIEW_SAVED  = 2
_self.__defineGetter__("VIEW_SAVED", function () {
    return 2;
});
//const Number  VIEW_SEARCH  = 3
_self.__defineGetter__("VIEW_SEARCH", function () {
    return 3;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/Phone', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/phone/",
    _listeners = {},
    _self;

_self = {
    activeCalls: function () {
        return transport.call(_uri + "activeCalls");
    },

    addPhoneListener: function (callback, eventType) {
        var assigned = false;

        if (callback && typeof eventType === "number") {
            _listeners[eventType] = callback;
            assigned = true;
        } else if (eventType && callback === null) {
            delete _listeners[eventType];
        } else {
            _listeners = {};
        }

        transport.poll(_uri + "onPhoneEvent", {
            get: {eventType: eventType}
        }, function (response) {
            var func = _listeners[eventType];

            if (func) {
                func(response.callId, response.error);
            }

            return !!func;
        });

        // hackish (return true that event was assigned, this is a disconnect between transport poll api and server)
        return assigned;
    },

    inActiveCall: function () {
        return transport.call(_uri + "inActiveCall");
    }
};

_self.__defineGetter__("CB_CALL_INITIATED", function () {
    return 0;
});
_self.__defineGetter__("CB_CALL_WAITING", function () {
    return 1;
});
_self.__defineGetter__("CB_CALL_INCOMING", function () {
    return 2;
});
_self.__defineGetter__("CB_CALL_ANSWERED", function () {
    return 3;
});
_self.__defineGetter__("CB_CALL_CONNECTED", function () {
    return 4;
});
_self.__defineGetter__("CB_CALL_CONFERENCECALL_ESTABLISHED", function () {
    return 5;
});
_self.__defineGetter__("CB_CONFERENCECALL_DISCONNECTED", function () {
    return 6;
});
_self.__defineGetter__("CB_CALL_DISCONNECTED", function () {
    return 7;
});
_self.__defineGetter__("CB_CALL_DIRECTCONNECT_CONNECTED", function () {
    return 8;
});
_self.__defineGetter__("CB_CALL_DIRECTCONNECT_DISCONNECTED", function () {
    return 9;
});
_self.__defineGetter__("CB_CALL_ENDED_BYUSER", function () {
    return 10;
});
_self.__defineGetter__("CB_CALL_FAILED", function () {
    return 11;
});
_self.__defineGetter__("CB_CALL_RESUMED", function () {
    return 12;
});
_self.__defineGetter__("CB_CALL_HELD", function () {
    return 13;
});
_self.__defineGetter__("CB_CALL_ADDED", function () {
    return 14;
});
_self.__defineGetter__("CB_CALL_REMOVED", function () {
    return 15;
});
_self.__defineGetter__("CALL_ERROR_SUBSCRIBER_BUSY", function () {
    return 1;
});
_self.__defineGetter__("CALL_ERROR_CONGESTION", function () {
    return 2;
});
_self.__defineGetter__("CALL_ERROR_RADIO_PATH_UNAVAILABLE", function () {
    return 3;
});
_self.__defineGetter__("CALL_ERROR_NUMBER_UNOBTAINABLE", function () {
    return 4;
});
_self.__defineGetter__("CALL_ERROR_AUTHORIZATION_FAILURE", function () {
    return 5;
});
_self.__defineGetter__("CALL_ERROR_EMERGENCY_CALLS_ONLY", function () {
    return 6;
});
_self.__defineGetter__("CALL_ERROR_HOLD_ERROR", function () {
    return 7;
});
_self.__defineGetter__("CALL_ERROR_OUTGOING_CALLS_BARRED", function () {
    return 8;
});
_self.__defineGetter__("CALL_ERROR_GENERAL", function () {
    return 9;
});
_self.__defineGetter__("CALL_ERROR_MAINTENANCE_REQUIRED", function () {
    return 10;
});
_self.__defineGetter__("CALL_ERROR_SERVICE_NOT_AVAILABLE", function () {
    return 11;
});
_self.__defineGetter__("CALL_ERROR_DUE_TO_FADING", function () {
    return 12;
});
_self.__defineGetter__("CALL_ERROR_LOST_DUE_TO_FADING", function () {
    return 13;
});
_self.__defineGetter__("CALL_ERROR_TRY_AGAIN", function () {
    return 14;
});
_self.__defineGetter__("CALL_ERROR_FDN_MISMATCH", function () {
    return 15;
});
_self.__defineGetter__("CALL_ERROR_CONNECTION_DENIED_BY_NETWORK", function () {
    return 16;
});
_self.__defineGetter__("CALL_ERROR_NUMBER_NOT_IN_SERVICE", function () {
    return 17;
});
_self.__defineGetter__("CALL_ERROR_PLEASE_TRY_LATER", function () {
    return 18;
});
_self.__defineGetter__("CALL_ERROR_SERVICE_CONFLICT", function () {
    return 19;
});
_self.__defineGetter__("CALL_ERROR_SYSTEM_BUSY_TRY_LATER", function () {
    return 20;
});
_self.__defineGetter__("CALL_ERROR_USER_BUSY_IN_PRIVATE", function () {
    return 21;
});
_self.__defineGetter__("CALL_ERROR_USER_BUSY_IN_DATA", function () {
    return 22;
});
_self.__defineGetter__("CALL_ERROR_USER_NOT_AUTHORIZED", function () {
    return 23;
});
_self.__defineGetter__("CALL_ERROR_USER_NOT_AVAILABLE", function () {
    return 24;
});
_self.__defineGetter__("CALL_ERROR_USER_UNKNOWN", function () {
    return 25;
});
_self.__defineGetter__("CALL_ERROR_USER_NOT_REACHABLE", function () {
    return 26;
});
_self.__defineGetter__("CALL_ERROR_INCOMING_CALL_BARRED", function () {
    return 27;
});
_self.__defineGetter__("CALL_ERROR_CALL_REPLACED_BY_STK", function () {
    return 28;
});
_self.__defineGetter__("CALL_ERROR_STK_CALL_NOT_ALLOWED", function () {
    return 29;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/PhoneArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.PhoneArguments ( [dialString : String ] ,  [smartDialing : Boolean ] ,  [lineId : Number ] )
var _self = function (dialString, smartDialing, lineId) {
    return {
        dialString: dialString,
        smartDialing: smartDialing,
        lineId: (lineId ? lineId : -1),
        view: 0
    };
};

//const Number  VIEW_NEW  = 0
_self.__defineGetter__("VIEW_CALL", function () {
    return 0;
});
//const Number  VIEW_DEFAULT  = 1
_self.__defineGetter__("VIEW_VOICEMAIL", function () {
    return 1;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/PhoneCall', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function PhoneCall(onhold) {
    return {
        //Boolean   isOnHold ( )
        //readonly  property  Boolean   outgoing
        //readonly  property  String   recipientName
        //readonly  property  String   recipientNumber

        outgoing: false,
        recipientName: null,
        recipientNumber: null,

        isOnHold: function () {
            return onhold;
        }
    };
}

module.exports = PhoneCall;

});
define('ripple/platform/webworks.handset/2.0.0/client/PhoneLogs', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    CallLog = require('ripple/platform/webworks.handset/2.0.0/client/CallLog'),
    utils = require('ripple/utils'),
    _onCallLog = {
        Added: null,
        Removed: null,
        Updated: null,
        Reset: null,
    },
    _uri = "blackberry/phone/logs/",
    _self;

function _massage(property, name) {
    if (name === "date" && property) {
        return new Date(property);
    }
    return property;
}

function _toCallLog(log) {
    var callLog = new CallLog(),
        prop;
    for (prop in log) {
        if (log.hasOwnProperty(prop)) {
            callLog[prop] = _massage(log[prop], prop);
        }
    }
    return callLog;
}

function handle(evt) {
    return function (response) {
        var func = _onCallLog[evt], args;

        if (func) {
            args = utils.map(response, function (value) {
                return _toCallLog(value);
            });
            func.apply(null, args);
        }

        return !!func;
    };
}

function poll(path) {
    transport.poll(_uri + path, {}, handle(path.replace("onCallLog", "")));
}

_self = {
    addPhoneLogListener: function (onCallLogAdded, onCallLogRemoved, onCallLogUpdated, onCallLogReset) {
        _onCallLog.Added = onCallLogAdded;
        _onCallLog.Removed = onCallLogRemoved;
        _onCallLog.Updated = onCallLogUpdated;
        _onCallLog.Reset = onCallLogReset;

        if (onCallLogAdded) {
            poll("onCallLogAdded");
        }

        if (onCallLogRemoved) {
            poll("onCallLogRemoved");
        }

        if (onCallLogUpdated) {
            poll("onCallLogUpdated");
        }

        if (onCallLogReset) {
            poll("onCallLogReset");
        }

        return !!(onCallLogAdded || onCallLogRemoved ||
                  onCallLogUpdated || onCallLogRemoved);
    },

    callAt: function (index, folderID) {
        var log = transport.call(_uri + "callAt", {
            get: {
                index: index,
                folderID: folderID
            }
        });

        if (log && log.date) {
            log.date = new Date(log.date);
        }

        return log;
    },

    deleteCallAt: function (index, folderID) {
        return transport.call(_uri + "deleteCallAt", {
            get: {
                index: index,
                folderID: folderID
            }
        });
    },

    find: function (filter, folderID, orderBy, maxReturn, isAscending) {
        return transport.call(_uri + "find", {
            post: {
                filter: filter,
                folderID: folderID,
                orderBy: orderBy,
                maxReturn: maxReturn,
                isAscending: isAscending
            }
        }).map(_toCallLog);
    },

    numberOfCalls: function (folderID) {
        return transport.call(_uri + "numberOfCalls", {
            get: {
                folderID: folderID
            }
        });
    }
};

_self.__defineGetter__("FOLDER_MISSED_CALLS", function () {
    return 0;
});

_self.__defineGetter__("FOLDER_NORMAL_CALLS", function () {
    return 1;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/PushData', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function PushData(data, port) {
    this.port = port;
    this.data = data;

    this.getHeaderField = function (field) {
        if (field === undefined || field === null) {
            throw "no field specified";
        }
        else if (!(typeof field === 'number' && field >= 0) && typeof field !== 'string') {
            throw "field is not valid";
        }

        return data.headerField[field];
    };

    this.getRequestURI =  function () {
        return data.requestURI;
    };

    this.getSource = function () {
        return data.source;
    };

    this.isChannelEncrypted = data.isChannelEncrypted;

    this.payload = data.payload;

    this.__defineGetter__("ACCEPT", function () {
        return 0;
    });
    this.__defineGetter__("DECLINE_USERDCR", function () {
        return 1;
    });
    this.__defineGetter__("DECLINE_USERDCU", function () {
        return 2;
    });
    this.__defineGetter__("DECLINE_USERPND", function () {
        return 3;
    });
    this.__defineGetter__("DECLINE_USERREQ", function () {
        return 4;
    });
    this.__defineGetter__("DECLINE_USERRFS", function () {
        return 5;
    });
}

module.exports = PushData;

});
define('ripple/platform/webworks.handset/2.0.0/client/Recurrence', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function Recurrence() {
    return {
        //readwrite  property  Number   count
        //readwrite  property  Number   dayInMonth
        //readwrite  property  Number   dayInWeek
        //readwrite  property  Number   dayInYear
        //readwrite  property  Date   end
        //readwrite  property  Number   frequency
        //readwrite  property  Number   interval
        //readwrite  property  Number   monthInYear
        //readwrite  property  Number   weekInMonth

        count: null,
        dayInMonth: null,
        dayInWeek: null,
        dayInYear: null,
        end: null,
        frequency: null,
        interval: null,
        monthInYear: null,
        weekInMonth: null
    };
}

Recurrence.__defineGetter__("NO_REPEAT", function () {
    return 0;
});
Recurrence.__defineGetter__("DAILY", function () {
    return 1;
});
Recurrence.__defineGetter__("WEEKLY", function () {
    return 2;
});
Recurrence.__defineGetter__("MONTHLY", function () {
    return 3;
});
Recurrence.__defineGetter__("YEARLY", function () {
    return 4;
});
Recurrence.__defineGetter__("JANUARY", function () {
    return 0x20000;
});
Recurrence.__defineGetter__("FEBRUARY", function () {
    return 0x40000;
});
Recurrence.__defineGetter__("MARCH", function () {
    return 0x80000;
});
Recurrence.__defineGetter__("APRIL", function () {
    return 0x100000;
});
Recurrence.__defineGetter__("MAY", function () {
    return 0x200000;
});
Recurrence.__defineGetter__("JUNE", function () {
    return 0x400000;
});
Recurrence.__defineGetter__("JULY", function () {
    return 0x800000;
});
Recurrence.__defineGetter__("AUGUST", function () {
    return 0x1000000;
});
Recurrence.__defineGetter__("SEPTEMBER", function () {
    return 0x2000000;
});
Recurrence.__defineGetter__("OCTOBER", function () {
    return 0x4000000;
});
Recurrence.__defineGetter__("NOVEMBER", function () {
    return 0x8000000;
});
Recurrence.__defineGetter__("DECEMBER", function () {
    return 0x10000000;
});
Recurrence.__defineGetter__("FIRST", function () {
    return 0x1;
});
Recurrence.__defineGetter__("SECOND", function () {
    return 0x2;
});
Recurrence.__defineGetter__("THIRD", function () {
    return 0x4;
});
Recurrence.__defineGetter__("FOURTH", function () {
    return 0x8;
});
Recurrence.__defineGetter__("FIFTH", function () {
    return 0x10;
});
Recurrence.__defineGetter__("LAST", function () {
    return 0x20;
});
Recurrence.__defineGetter__("SECONDLAST", function () {
    return 0x40;
});
Recurrence.__defineGetter__("THIRDLAST", function () {
    return 0x80;
});
Recurrence.__defineGetter__("FOURTHLAST", function () {
    return 0x100;
});
Recurrence.__defineGetter__("FIFTHLAST", function () {
    return 0x200;
});
Recurrence.__defineGetter__("SUNDAY", function () {
    return 0x10000;
});
Recurrence.__defineGetter__("MONDAY", function () {
    return 0x8000;
});
Recurrence.__defineGetter__("TUESDAY", function () {
    return 0x4000;
});
Recurrence.__defineGetter__("WEDNESDAY", function () {
    return 0x2000;
});
Recurrence.__defineGetter__("THURSDAY", function () {
    return 0x1000;
});
Recurrence.__defineGetter__("FRIDAY", function () {
    return 0x800;
});
Recurrence.__defineGetter__("SATURDAY", function () {
    return 0x400;
});

module.exports = Recurrence;

});
define('ripple/platform/webworks.handset/2.0.0/client/Reminder', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 Reminder = function () {

    return {
        //readwrite  property  Date   date
        //readwrite  property  Number   relativeHours
        //readwrite  property  Number   type

        date: null,
        relativeHours: null,
        type: null

    };

};

Reminder.__defineGetter__("DATE", function () {
    return 0;
});

Reminder.__defineGetter__("RELATIVE", function () {
    return 1;
});

module.exports = Reminder;

});
define('ripple/platform/webworks.handset/2.0.0/client/SearchArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.SearchArguments ( )
//blackberry.invoke.SearchArguments ( text : String ,  name : String )
var _self = function (text, name) {

    return {
        text: text,
        name: name
    };

};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/Task', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/pim/Task/";

function Task() {
    var _self = {
        save: function () {
            if (!_self.uid) {
                _self.uid = Math.uuid(null, 16);
            }
            transport.call(_uri + "save",  {
                post: {
                    task: _self
                }
            });
        },
        remove: function () {
            if (!_self.uid) {
                throw "task has not yet been saved (has no uid)";
            }
            transport.call(_uri + "remove", {
                get: {
                    id: _self.uid
                }
            });
        },
        uid: null,
        categories: [],
        due: null,
        note: "",
        priority: Task.PRIORITY_NORMAL,
        recurrence: null,
        reminder: null,
        status: Task.NOT_STARTED,
        summary: ""
    };

    return _self;
}

function _massage(property, name) {
    if (name === "recurrence" && property) {
        if (property.end) {
            property.end = new Date(property.end);
        }
    }
    if (name === "reminder" && property) {
        if (property.date) {
            property.date = new Date(property.date);
        }
    }
    if (name === "due" && property) {
        property = new Date(property);
    }
    return property;
}

Task.find = function (filter, orderBy, maxReturn, isAscending) {
    return transport.call(_uri + "find", {
        post: {
            filter: filter,
            orderBy: orderBy,
            maxReturn: maxReturn,
            isAscending: isAscending
        }
    }).map(function (properties) {
        var task = new Task(),
            key;
        for (key in properties) {
            if (task.hasOwnProperty(key)) {
                task[key] = _massage(properties[key], key);
            }
        }
        return task;
    });
};

Task.__defineGetter__("NOT_STARTED", function () {
    return 0;
});

Task.__defineGetter__("IN_PROGRESS", function () {
    return 1;
});

Task.__defineGetter__("COMPLETED", function () {
    return 2;
});

Task.__defineGetter__("WAITING", function () {
    return 3;
});

Task.__defineGetter__("DEFERRED", function () {
    return 4;
});

Task.__defineGetter__("PRIORITY_HIGH", function () {
    return 0;
});

Task.__defineGetter__("PRIORITY_NORMAL", function () {
    return 1;
});

Task.__defineGetter__("PRIORITY_LOW", function () {
    return 2;
});

module.exports = Task;

});
define('ripple/platform/webworks.handset/2.0.0/client/TaskArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.TaskArguments ( [task : blackberry.pim.Task ] )
var _self = function (task) {
    return {
        view: 0,
        task: task
    };
};

//const Number  VIEW_NEW  = 0
_self.__defineGetter__("VIEW_NEW", function () {
    return 0;
});
//const Number  VIEW_EDIT  = 1
_self.__defineGetter__("VIEW_EDIT", function () {
    return 1;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/app', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/app/",
    _self;

_self = {
    exit: function () {
        transport.call(_uri + "exit", {async: true});
    },

    setHomeScreenIcon: function (uri, hover) {
        transport.call(_uri + "setHomeScreenIcon", {
            get: {
                uri: uri,
                hover: hover
            },
            async: true
        });

        return true;
    },

    setHomeScreenName: function (text) {
        transport.call(_uri + "setHomeScreenName", {
            get: {text: text},
            async: true
        });

        return true;
    },

    requestForeground: function () {
        transport.call(_uri + "requestForeground", {async: true});
    },

    requestBackground: function () {
        transport.call(_uri + "requestBackground", {async: true});
    },

    removeBannerIndicator: function () {
        transport.call(_uri + "removeBannerIndicator", {async: true});
    },

    showBannerIndicator: function (icon, count) {
        transport.call(_uri + "showBannerIndicator", {
            get: {
                icon: icon,
                count: count
            },
            async: true
        });
    },
};

_self.__defineGetter__("author", function () {
    return transport.call(_uri + "author");
});

_self.__defineGetter__("authorEmail", function () {
    return transport.call(_uri + "authorEmail");
});

_self.__defineGetter__("authorURL", function () {
    return transport.call(_uri + "authorURL");
});

_self.__defineGetter__("copyright", function () {
    return transport.call(_uri + "copyright");
});

_self.__defineGetter__("description", function () {
    return transport.call(_uri + "description");
});

_self.__defineGetter__("id", function () {
    return transport.call(_uri + "id");
});

_self.__defineGetter__("isForeground", function () {
    return transport.call(_uri + "isForeground");
});

_self.__defineGetter__("license", function () {
    return transport.call(_uri + "license");
});

_self.__defineGetter__("licenseURL", function () {
    return transport.call(_uri + "licenseURL");
});

_self.__defineGetter__("name", function () {
    return transport.call(_uri + "name");
});

_self.__defineGetter__("version", function () {
    return transport.call(_uri + "version");
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/appEvent', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _callbacks = {},
    _self;

function _poll(evt, handler) {
    _callbacks[evt] = handler;

    transport.poll("blackberry/app/event/" + evt, {}, function () {
        var func = _callbacks[evt];

        if (func) {
            func();
        }

        return !!func;
    });
}

_self = {
    onBackground: function (handler) {
        _poll("onBackground", handler);
    },

    onForeground: function (handler) {
        _poll("onForeground", handler);
    },

    onExit: function (handler) {
        _poll("onExit", handler);
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/audio', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    supportedContentTypes: function (protocol) {
        return protocol === 'rtsp' ?
            ['audio/amr', 'audio/mp4', 'audio/aac'] :
            ['audio/midi', 'mpeg', 'x-wav', 'amr', 'basic', 'x-gsm', 'mp4', 'aac', 'x-ms-wma', 'flac', 'ogg'];
    },
    supportedProtocols: function (contentType) {
        return ['http', 'file', 'rtsp'];
    }
};

});
define('ripple/platform/webworks.handset/2.0.0/client/blackberry', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 blackberry = {},
    transport = require('ripple/platform/webworks.core/2.0.0/client/transport');

blackberry.__defineGetter__("network", function () {
    return transport.call("blackberry/system/network");
});

module.exports = blackberry;

});
define('ripple/platform/webworks.handset/2.0.0/client/category', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/pim/category/",
    _self;

_self = {
    addCategory: function (categoryName) {
        transport.call(_uri + "addCategory", {
            get: {categoryName: categoryName}
        });
    },
    deleteCategory: function (categoryName) {
        transport.call(_uri + "deleteCategory", {
            get: {categoryName: categoryName}
        });
    },
    getCategories: function () {
        return transport.call(_uri + "getCategories");
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/identity/Service', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function Service() {
    return {
        emailAddress: null,
        isDefault: null,
        name: null,
        type: null
    };
}

Service.__defineGetter__("TYPE_EMAIL", function () {
    return 0;
});

Service.__defineGetter__("TYPE_CALENDAR", function () {
    return 1;
});

Service.__defineGetter__("TYPE_CONTACT", function () {
    return 2;
});

module.exports = Service;

});
define('ripple/platform/webworks.handset/2.0.0/client/identity/Transport', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
function Transport(name, type) {
    this.__defineGetter__("name", function () {
        return name || "";
    });
    this.__defineGetter__("type", function () {
        return type || "";
    });
}

module.exports = Transport;

});
define('ripple/platform/webworks.handset/2.0.0/client/identity/phone', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/identity/phone/",
    _self;

_self = {
    getLineIds: function () {
        return transport.call(_uri + "getLineIds");
    },
    getLineLabel: function (id) {
        return transport.call(_uri + "getLineLabel", {get: {id: id}});
    },
    getLineNumber: function (id) {
        return transport.call(_uri + "getLineNumber", {get: {id: id}});
    },
    getLineType: function (id) {
        return transport.call(_uri + "getLineType", {get: {id: id}});
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/identity', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/identity/",
    _self;

_self = {
    getDefaultService: function () {
        return transport.call(_uri + "getDefaultService");
    },
    getServiceList: function () {
        return transport.call(_uri + "getServiceList");
    },
    getTransportList: function () {
        return transport.call(_uri + "getTransportList");
    }
};

_self.__defineGetter__("IMEI", function () {
    return transport.call(_uri + "IMEI");
});

_self.__defineGetter__("IMSI", function () {
    return transport.call(_uri + "IMSI");
});

_self.__defineGetter__("PIN", function () {
    return transport.call(_uri + "PIN");
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/invoke', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _uri = "blackberry/invoke/invoke",
    APP_URL_CAMERA = "camera://",
    APP_URL_CAMERA_VIDEO = "camera://video",
    APP_URL_MAP = "map://",
    APP_URL_MUSIC = "music://",
    APP_URL_PHOTOS = "photos://",
    APP_URL_VIDEOS = "videos://",
    APP_URL_APPWORLD = "appworld://",
    APP_URL_UPDATE = "update://",
    APP_BROWSER_ERROR = "Protocol specified in the url is not supported.",
    APP_ADDRESSBOOK_ERROR = "Invalid arguments specified",
    transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _self;

_self = {
    invoke: function (appType, args) {
        var get = {};

        switch (appType) {

        //AddressBook
        case 0:
            if (args) {
                if (args.view === 1 && args.contact) {
                    throw APP_ADDRESSBOOK_ERROR; //contact cannot be used with this view
                }
                else if (args.view === 2 && !args.contact) {
                    throw APP_ADDRESSBOOK_ERROR; //need contact for this view
                }
            }

            get.appType = appType;
            break;

        //Bluetooth Config
        case 1:
            get.appType = appType;
            break;

        //Calculator
        case 2:
            get.appType = appType;
            break;

        //Calendar
        case 3:
            get.appType = appType;
            break;

        //Camera
        case 4:
            if (!args || args.view === 1) {
                get.appType = APP_URL_CAMERA_VIDEO;
            } else {
                get.appType = APP_URL_CAMERA;
            }
            break;

        //Maps
        case 5:
            get.appType = APP_URL_MAP;
            break;

        //Memopad
        case 6:
            get.appType = appType;
            break;

        //Messages
        case 7:
            get.appType = appType;
            break;

        //Phone
        case 8:
            get.appType = appType;
            break;

        //Search
        case 9:
            get.appType = appType;
            break;

        //Tasks
        case 10:
            get.appType = appType;
            break;

        //Browser
        case 11:

            if (!args) {
                get.appType = "http://";
            } else {
                if (args.url && !args.url.match(/^https?:\/\//)) {
                    throw APP_BROWSER_ERROR;
                }
                get.appType = args.url;
            }

            break;

        //Java
        case 12:
            get.appType = appType;
            break;

        default:
            throw "appType not supported";
        }

        transport.call(_uri, {
            get: get,
            async: true
        });
    }
};

_self.__defineGetter__("APP_ADDRESSBOOK", function () {
    return 0;
});
_self.__defineGetter__("APP_BLUETOOTH_CONFIG", function () {
    return 1;
});
_self.__defineGetter__("APP_CALCULATOR", function () {
    return 2;
});
_self.__defineGetter__("APP_CALENDAR", function () {
    return 3;
});
_self.__defineGetter__("APP_CAMERA", function () {
    return 4;
});
_self.__defineGetter__("APP_MAPS", function () {
    return 5;
});
_self.__defineGetter__("APP_MEMOPAD", function () {
    return 6;
});
_self.__defineGetter__("APP_MESSAGES", function () {
    return 7;
});
_self.__defineGetter__("APP_PHONE", function () {
    return 8;
});
_self.__defineGetter__("APP_SEARCH", function () {
    return 9;
});
_self.__defineGetter__("APP_TASKS", function () {
    return 10;
});
_self.__defineGetter__("APP_BROWSER", function () {
    return 11;
});
_self.__defineGetter__("APP_JAVA", function () {
    return 12;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/io/dir', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    dir = require('ripple/platform/webworks.core/2.0.0/client/io/dir'),
    utils = require('ripple/utils'),
    _uri = "blackberry/io/dir/",
    FILE = "file://",
    _self = {};

function _prunePrefix(path) {
    return path.replace(new RegExp("^" + FILE), '');
}

utils.mixin({
    getFreeSpaceForRoot: function (path) {
        return transport.call(_uri + "getFreeSpaceForRoot", {
            post: {path: _prunePrefix(path)}
        });
    },
    getRootDirs: function () {
        return transport.call(_uri + "getRootDirs", {}).map(function (dir) {
            return FILE + dir;
        });
    }
}, _self);

utils.mixin(dir, _self);

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/menu', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    MenuItem = require('ripple/platform/webworks.handset/2.0.0/client/MenuItem'),
    utils = require('ripple/utils'),
    onSelect,
    _items = {},
    _uri = "blackberry/ui/menu/",
    _self;

_self = {
    addMenuItem: function (menuItem) {
        _items[menuItem.id] = menuItem;

        transport.call(_uri + "addMenuItem", {
            get: {"item": menuItem}
        });

        if (utils.count(_items) === 1) {
            transport.poll(_uri + "onSelect", {}, function (response) {
                var item = _items[response];

                if (item && item.callback) {
                    item.callback();
                }

                return !!utils.count(_items);
            });
        }
    },

    clearMenuItems: function () {
        _items = {};
        transport.call(_uri + "clearMenuItems");
    },

    getMenuItems: function () {
        return utils.map(_items, function (item) {
            var menuItem = new MenuItem(item.isSeparator, item.ordinal, item.caption, item.callback);
            menuItem.id = item.id;
            menuItem.isDefault = item.isDefault;
            return menuItem;
        });
    },

    hasMenuItem: function (menuItem) {
        return !!_items[menuItem.id];
    },

    open: function () {
        transport.call(_uri + "open", {async: true});
    },

    removeMenuItem: function (menuItem) {
        delete _items[menuItem.id];
        transport.call(_uri + "removeMenuItem", {
            get: {item: menuItem}
        });
    },

    setDefaultMenuItem: function (menuItem) {
        utils.forEach(_items, function (item) {
            item.isDefault = false;
        });

        _items[menuItem.id].isDefault = true;

        transport.call(_uri + "setDefaultMenuItem", {
            get: {id: menuItem.id}
        });
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/messaging', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {};

});
define('ripple/platform/webworks.handset/2.0.0/client/pim', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {};

});
define('ripple/platform/webworks.handset/2.0.0/client/push', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _self,
    _uri = "blackberry/push/onPush",
    callbacks = {},
    PushData = require('ripple/platform/webworks.handset/2.0.0/client/PushData');

_self = {
    openPushListener: function (callback, port, bbTransport, maxQueueCap) {
        callbacks["onPush" + port] = callback;

        transport.poll(_uri, {
            get: {
                port: port,
                bbTransport: bbTransport,
                maxQueueCap: maxQueueCap
            }
        }, function (response) {
            var func = callbacks["onPush" + port];

            if (func) {
                func(new PushData(response, port));
            }

            return !!func;
        });
    },

    closePushListener: function (port) {
        delete callbacks["onPush" + port];
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/sms', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/message/sms/",
    onReceive,
    _self;

_self = {
    addReceiveListener: function (callback) {
        onReceive = callback;
        transport.poll(_uri + "onReceive", {}, function (response) {
            if (onReceive) {
                onReceive(response.body, response.from, response.time);
            }
            return !!onReceive;
        });
    },

    removeReceiveListener: function () {
        if (onReceive) {
            onReceive = null;
            return true;
        }

        return false;
    },

    send: function (message, address) {
        transport.call(_uri + "send", {
            get: {
                message: message,
                address: address
            },
            async: true
        });
    }
};

_self.__defineGetter__("isListeningForMessage", function () {
    return transport.call(_uri + "isListeningForMessage", {async: false});
});

_self.__defineSetter__("isListeningForMessage", function (value) {
    transport.call(_uri + "isListeningForMessage", {
        async: false,
        get: {isListeningForMessage: value}
    });
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/system', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    system = require('ripple/platform/webworks.core/2.0.0/client/system'),
    _uri = "blackberry/system/",
    _self;

_self = {
    setHomeScreenBackground: function (filePath) {
        transport.call(_uri + "setHomeScreenBackground", {
            get: {filePath: filePath},
            async: true
        });
    },
};

(function () {
    // HACK: can't type check if system[key] is a function, sets off getters
    // also can't use utils.mixin or forEach for the same reason
    function get(i) {
        return function () {
            return system[i];
        };
    }

    for (var key in system) {
        if (system.hasOwnProperty(key)) {
            _self.__defineGetter__(key, get(key));
        }
    }
}());

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/client/systemEvent', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    utils = require('ripple/utils'),
    _self,
	_callbacks = {};

function _poll(evt, args, callback) {
    _callbacks[evt + args.key] = callback;

    transport.poll("blackberry/system/event/" + evt, {get: args}, function () {
        var func = _callbacks[evt + args.key];

        if (func) {
            func();
        }

        return !!func;
    });
}

_self = {
    onCoverageChange: function (callback) {
        _poll("onCoverageChange", {}, callback);
    },

    onHardwareKey: function (key, callback) {
        _poll("onHardwareKey", {key: key}, callback);
    }
};

_self.__defineGetter__("KEY_BACK", function () {
    return 0;
});
_self.__defineGetter__("KEY_MENU", function () {
    return 1;
});
_self.__defineGetter__("KEY_CONVENIENCE_1", function () {
    return 2;
});
_self.__defineGetter__("KEY_CONVENIENCE_2", function () {
    return 3;
});
_self.__defineGetter__("KEY_STARTCALL", function () {
    return 4;
});
_self.__defineGetter__("KEY_ENDCALL", function () {
    return 5;
});
_self.__defineGetter__("KEY_VOLUMEDOWN", function () {
    return 6;
});
_self.__defineGetter__("KEY_VOLUMEUP", function () {
    return 7;
});

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/Task', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 select = require('ripple/platform/webworks.core/2.0.0/select'),
    db = require('ripple/db'),
    utils = require('ripple/utils'),
    _KEY = "blackberry-pim-task",
    _self;

function _get() {
    return db.retrieveObject(_KEY) || {};
}

function _save(tasks) {
    db.saveObject(_KEY, tasks);
}

_self = {
    save: function (get, post) {
        var tasks = _get(),
            properties = post.task,
            id = properties.uid;

        if (tasks[id]) {
            utils.mixin(properties, tasks[id]);
        } else {
            tasks[id] = properties;
        }

        _save(tasks);

        return {code: 1};
    },

    remove: function (get, post) {
        var tasks = _get(),
            id = get.id;

        delete tasks[id];

        _save(tasks);

        return {code: 1};
    },

    find: function (get, post) {
        var tasks = _get(),
            match = select.from(tasks);

        if (post.orderBy) {
            match.orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc");
        }

        if (post.maxReturn) {
            match.max(post.maxReturn);
        }

        return {code: 1, data: match.where(post.filter)};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/app', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    app = require('ripple/app'),
    notifications = require('ripple/notifications'),
    constants = require('ripple/constants'),
    ui = require('ripple/ui'),
    _isForeground = true,
    _self;

_self = {
    event: require('ripple/platform/webworks.handset/2.0.0/server/appEvent'),

    exit: function () {
        event.trigger("AppExit");
        return {code: 1};
    },

    author: function () {
        return {code: 1, data: app.getInfo().author};
    },

    authorEmail: function () {
        return {code: 1, data: app.getInfo().authorEmail};
    },

    authorURL: function () {
        return {code: 1, data: app.getInfo().authorURL};
    },

    copyright: function () {
        return {code: 1, data: app.getInfo().copyright};
    },

    description: function () {
        return {code: 1, data: app.getInfo().description};
    },

    isForeground: function () {
        return {code: 1, data: _isForeground};
    },

    id: function () {
        return {code: 1, data: app.getInfo().id};
    },

    license: function () {
        return {code: 1, data: app.getInfo().license};
    },

    licenseURL: function () {
        return {code: 1, data: app.getInfo().licenseURL};
    },

    name: function () {
        return {code: 1, data: app.getInfo().name};
    },

    version: function () {
        return {code: 1, data: app.getInfo().version};
    },

    requestBackground: function () {
        ui.showOverlay("background-window", function (background) {
            var button = background.children["background-return"];

            if (button) {
                button.addEventListener("click", _self.requestForeground);
            }
            _isForeground = false;
            event.trigger("AppRequestBackground");
        });

        return {code: 1};
    },

    requestForeground: function () {
        ui.hideOverlay("background-window", function (background) {
            var button = background.children["background-return"];

            if (button) {
                button.removeEventListener("click", _self.requestForeground);
            }
            _isForeground = true;
            event.trigger("AppRequestForeground");
        });

        return {code: 1};
    },

    setHomeScreenIcon: function (args) {
        if (args.uri) {
            var msg = "The application set the home screen" +
               (args.hover ? " hover " : " ") +
               "icon to " + args.uri;

            notifications.openNotification("normal", msg);
            return {code: 1};
        }
        else {
            return {code: 0};
        }
    },

    setHomeScreenName: function (args) {
        if (args.text) {
            var msg = "The application set the home screen name to " + args.text;
            notifications.openNotification("normal", msg);
            return {code: 1};
        }
        else {
            return {code: 1};
        }
    },

    removeBannerIndicator: function () {
        event.trigger("BannerUpdated", ["", 0]);
        return {code: 1};
    },

    showBannerIndicator: function (args) {
        event.trigger("BannerUpdated", [args.icon, args.count]);
        return {code: 1};
    },

};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/appEvent', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    notifications = require('ripple/notifications'),
    _bg,
    _fg,
    _exit;

event.on("AppRequestBackground", function () {
    var baton = _bg;
    _bg = null;
    return baton && baton.pass({code: 1});
});

event.on("AppRequestForeground", function () {
    var baton = _fg;
    _fg = null;
    return baton && baton.pass({code: 1});
});

event.on("AppExit", function () {
    var baton = _exit;
    _exit = null;
    notifications.openNotification("normal", "blackberry.app.exit() as called, in the real world your app will exit, here... you get this notification");
    return baton && baton.pass({code: 1});
});

module.exports = {
    onBackground: function (get, post, baton) {
        baton.take();
        _bg = baton;
        return {code: 1};
    },

    onForeground: function (get, post, baton) {
        baton.take();
        _fg = baton;
        return {code: 1};
    },

    onExit: function (get, post, baton) {
        baton.take();
        _exit = baton;
        return {code: 1};
    }
};

});
define('ripple/platform/webworks.handset/2.0.0/server/appointment', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    select = require('ripple/platform/webworks.core/2.0.0/select'),
    _self;

function _get() {
    return db.retrieveObject("webworks-pim-appointment-list") || {};
}

function _do(func) {
    var appointments = _get();
    func(appointments);
    db.saveObject("webworks-pim-appointment-list", appointments);
}

_self = {
    find: function (get, post) {
        var appointments = _get(),
            data = select.from(appointments)
                    .orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc")
                    .max(post.maxReturn)
                    .where(post.filter);

        return {code: 1, data: data};
    },

    remove: function (get) {
        _do(function (appointments) {
            if (!appointments[get.uid]) {
                throw "attempting to delete a non existant appointment with uid: " + get.uid;
            }
            delete appointments[get.uid];
        });

        return {code: 1};
    },

    save: function (get, post) {
        _do(function (appointments) {
            appointments[post.appointment.uid] = post.appointment;
        });

        return {code: 1};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/audioPlayer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//create my dom collection node in UI

var utils = require('ripple/utils'),
    constants = require('ripple/constants'),
    notifications = require('ripple/notifications'),
    Player = require('ripple/platform/webworks.handset/2.0.0/client/AudioPlayer'),
    _handlers = {
        loadstart: {},
        canplaythrough: {},
        durationchange: {},
        ended: {},
        error: {},
        play: {},
        pause: {},
        volumechange: {},
        close: {}
    },
    extract = {
        time: function (audio) {
            return audio.currentTime;
        },
        duration: function (audio) {
            return audio.duration;
        },
        error: function (audio) {
            return audio.error;
        },
        nothing: function (audio) {
            return null;
        }
    },
    container;

container = utils.createElement("section", {
    id: "webworks-audio-players"
});

document.getElementById("ui").appendChild(container);

function _errClosed(method) {
    notifications.openNotification("error",
       "attempted to call " + method + " on a player that is already closed. This is a very bad thing to do :)");
    return false;
}

function _removeHandler(type, id) {
    var audio = document.getElementById(id);

    if (audio && _handlers[type][id]) {
        audio.removeEventListener(type, _handlers[type][id]);
        delete _handlers[type][id];
    }
}

function _addHandler(type, id, callback) {
    var audio = document.getElementById(id);

    if (audio) {
        _removeHandler(type, id);
        audio.addEventListener(type, callback);
        _handlers[type][id] = callback;
    }
}

function proxyEvent(from, map) {
    var audio = document.getElementById(map.id);

    if (audio) {
        map.baton.take();
        _addHandler(from, map.id, function () {
            _removeHandler(from, map.id);
            map.baton.pass({code: 1, data: {
                event: map.target,
                eventData: map.data(this)
            }});
        });
    }
    else {
        return {code: -1, data: {event: "EVENT_ERROR", eventData: 5}};
    }
}

module.exports = {

    create: function (args) {
        var id = Math.uuid(),
            audio = utils.createElement("audio", {
                id: id
            });

        audio.setAttribute("src", args.locator);

        if (args.type) {
            audio.setAttribute("type", args.type);
        }

        container.appendChild(audio);
        audio.load();

        if (audio.error) {
            throw "there was a problem opening the audio file";
        }

        return {code: 1, data: id};
    },

    play: function (args) {
        var audio = document.getElementById(args.id),
            playing;

        if (audio) {
            audio.play();
            audio.rimState = Player.STARTED;
            playing = !!!audio.error;
        }
        else {
            playing = _errClosed("play");
        }

        return {code: 1, data: playing};
    },

    pause: function (args) {
        var audio = document.getElementById(args.id),
            paused;

        if (audio) {
            audio.pause();
            paused = !!!audio.error;
        } else {
            paused = _errClosed("pause");
        }

        return {code: 1, data: paused};
    },

    close: function (args) {
        var audio = document.getElementById(args.id),
            callback = _handlers["close"][args.id],
            closed = true;

        if (audio) {
            if (callback) {
                callback();
            }
            container.removeChild(audio);
        }
        else {
            closed = _errClosed("close");
        }

        return {code: 1, data: closed};
    },

    onStart: function (args, post, baton) {
        return proxyEvent("play", {
            id: args.id,
            baton: baton,
            target: "EVENT_START",
            data: extract.time
        });
    },

    onStopped: function (args, post, baton) {
        return proxyEvent("pause", {
            id: args.id,
            baton: baton,
            target: "EVENT_STOPPED",
            data: extract.time
        });
    },

    onBufferingStarted: function (args, post, baton) {
        return proxyEvent("loadstart", {
            id: args.id,
            baton: baton,
            target: "EVENT_BUFFERING_STARTED",
            data: extract.time
        });
    },

    onBufferingStopped: function (args, post, baton) {
        return proxyEvent("canplaythrough", {
            id: args.id,
            baton: baton,
            target: "EVENT_BUFFERING_STOPPED",
            data: extract.time
        });
    },

    onDurationUpdated: function (args, post, baton) {
        return proxyEvent("durationchange", {
            id: args.id,
            baton: baton,
            target: "EVENT_DURATION_UPDATED",
            data: extract.duration
        });
    },

    onEnd: function (args, post, baton) {
        return proxyEvent("ended", {
            id: args.id,
            baton: baton,
            target: "EVENT_END_OF_MEDIA",
            data: extract.duration
        });
    },

    onError: function (args, post, baton) {
        return proxyEvent("error", {
            id: args.id,
            baton: baton,
            target: "EVENT_ERROR",
            data: extract.error
        });
    },

    onVolumeChange: function (args, post, baton) {
        return proxyEvent("volumechange", {
            id: args.id,
            baton: baton,
            target: "EVENT_VOLUME_CHANGED",
            data: extract.nothing
        });
    },

    onClose: function (args, post, baton) {
        return proxyEvent("close", {
            id: args.id,
            baton: baton,
            target: "EVENT_CLOSED",
            data: extract.nothing
        });
    },

    getDuration: function (args) {
        var audio = document.getElementById(args.id),
            duration;

        if (audio) {
            duration = audio.duration;
        }
        else {
            _errClosed("getDuration");
            duration = -1;
        }

        return {code: 1, data: duration};
    },

    getMediaTime: function (args) {
        var audio = document.getElementById(args.id),
            time;

        if (audio) {
            time = audio.currentTime;
        }
        else {
            _errClosed("getMediaTime");
            time = -1;
        }

        return {code: 1, data: time};
    },

    setMediaTime: function (args) {
        var audio = document.getElementById(args.id);

        if (audio) {
            audio.currentTime = args.value;
        }
        else {
            _errClosed("setMediaTime");
        }

        return {code: 1};
    },

    getVolumeLevel: function (args) {
        var audio = document.getElementById(args.id),
            level;

        if (audio) {
            level = audio.volume * 100;
        }
        else {
            _errClosed("getVolumeLevel");
            level = -1;
        }

        return {code: 1, data: level};
    },

    setVolumeLevel: function (args) {
        var audio = document.getElementById(args.id);

        if (audio) {
            audio.volume = args.value / 100;
        }
        else {
            _errClosed("setVolumeLevel");
        }

        return {code: 1};
    },

    getState: function (args) {
        var audio = document.getElementById(args.id),
            state = audio ? audio.rimState || Player.PREFETCHED : Player.CLOSED;
        return {code: 1, data: state};
    }
};

});
define('ripple/platform/webworks.handset/2.0.0/server/category', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    _KEY = "blackberry-pim-category",
    _self;

function _get() {
    return db.retrieveObject(_KEY) || [];
}

function _save(category) {
    var categories = _get();
    if (!categories.some(function (item) {
        return item === category;
    })) {
        categories.push(category);
        db.saveObject(_KEY, categories);
    }
}

function _remove(category) {
    var categories = _get(),
        index = categories.indexOf(category);

    if (index >= 0) {
        categories.splice(index, 1);
        db.saveObject(_KEY, categories);
    }
}

_self = {
    addCategory: function (args) {
        _save(args.categoryName);
        return {code: 1};
    },
    deleteCategory: function (args) {
        _remove(args.categoryName);
        return {code: 1};
    },
    getCategories: function () {
        return {code: 1, data: _get()};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/contact', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 select = require('ripple/platform/webworks.core/2.0.0/select'),
    db = require('ripple/db'),
    utils = require('ripple/utils'),
    _KEY = "blackberry-pim-contacts",
    _self;

function _defaultContacts() {
    var id1 = Math.uuid(null, 16),
        id2 = Math.uuid(null, 16),
        id3 = Math.uuid(null, 16),
        id4 = Math.uuid(null, 16),
        contacts = {};

    contacts[id1] = {
        uuid: id1,
        firstName: "Leonardo",
        homePhone: "4567892345",
        email1: "leo@underground.com"
    };
    contacts[id2] = {
        uuid: id2,
        firstName: "Raphael",
        homePhone: "4563457890",
        email1: "raph@underground.com"
    };
    contacts[id3] = {
        uuid: id3,
        firstName: "Michelangelo",
        homePhone: "4563453425",
        email1: "mike@underground.com"
    };
    contacts[id4] = {
        uuid: id4,
        firstName: "Donatello",
        homePhone: "4563453425",
        email1: "don@undergound.com"
    };

    return contacts;
}

function _get() {
    return db.retrieveObject(_KEY) || _defaultContacts();
}

function _save(contacts) {
    db.saveObject(_KEY, contacts);
}

_self = {
    save: function (get, post) {
        var contacts = _get();

        contacts[post.contact.uid] = post.contact;
        _save(contacts);
        return {code: 1};
    },
    remove: function (get, post) {
        var contacts = _get(),
            id = get.id;

        delete contacts[id];
        _save(contacts);
        return {code: 1};
    },
    find: function (get, post) {
        var contacts = _get(),
            match = select.from(contacts);

        if (post.orderBy) {
            match.orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc");
        }

        if (post.maxReturn) {
            match.max(post.maxReturn);
        }

        return {code: 1, data: match.where(post.fieldFilter)};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/identity/phone', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _lines = [
        {id: 1, number: 12345678910, label: "rogers", type: 1},
        {id: 2, number: 10987654321, label: "mystery", type: 0}
    ],
    _self;

function _filterLines(args) {

    var result = _lines;

    if (args && typeof args.id === "number") {
        result = _lines.filter(function (line) {
            return line.id === args.id;
        });

        if (result.length === 0) {
            throw "invalid line id: " + args.id;
        }
    }

    return result;
}

_self = {
    getLineIds: function () {
        var lines = _lines.map(function (line) {
            return line.id;
        });
        return {
            code: 1,
            data: lines
        };
    },
    getLineLabel: function (args) {
        return {
            code: 1,
            data: _filterLines(args)[0].label
        };
    },
    getLineNumber: function (args) {
        return {
            code: 1,
            data: _filterLines(args)[0].number
        };
    },
    getLineType: function (args) {
        return {
            code: 1,
            data: _filterLines(args)[0].type
        };
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/identity', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    Service = require('ripple/platform/webworks.handset/2.0.0/client/identity/Service'),
    Transport = require('ripple/platform/webworks.handset/2.0.0/client/identity/Transport'),
    utils = require('ripple/utils'),
    platform = require('ripple/platform'),
    deviceSettings = require('ripple/deviceSettings'),
    _transportTypes = [
        {name: "TCP Cellular", type: "TCP Cellular"},
        {name: "Wap", type: "Wap"},
        {name: "Wap 2.0", type: "Wap 2.0"},
        {name: "MDS", type: "MDS"},
        {name: "BIS B", type: "Bis B"},
        {name: "Unite!", type: "Unite!"},
        {name: "TCP Wifi", type: "TCP Wifi"},
    ],
    _services = [
        new Service(),
        new Service()
    ];

function _isTransportAvailable(transport) {
    return deviceSettings.retrieveAsBoolean("transports." + transport.type);
}

utils.mixin({
    name: "Super Dave Osborne",
    emailAddress: "dave@stunt.com",
    isDefault: true,
    type: Service.TYPE_EMAIL
}, _services[0]);

utils.mixin({
    name: "Fred Penner",
    emailAddress: "fred@fredpenner.com",
    isDefault: false,
    type: Service.TYPE_CONTACT
}, _services[1]);

_self = {
    getDefaultService: function () {
        var serices = _services.filter(function (service) {
            return service.isDefault === true;
        });
        return {code: 1, data: serices};
    },
    getServiceList: function () {
        return {code: 1, data: _services};
    },
    getTransportList: function () {
        var transports = _transportTypes.filter(function (transport) {
            return _isTransportAvailable(transport);
        }).map(function (transport) {
            return new Transport(transport.name, transport.type);
        });
        return {code: 1, data: transports};
    },
    IMEI: function () {
        return {code: 1, data: deviceSettings.retrieve("identity.IMEI")};
    },
    IMSI: function () {
        return {code: 1, data: deviceSettings.retrieve("identity.IMSI")};
    },
    PIN: function () {
        return {code: 1, data: deviceSettings.retrieve("identity.PIN")};
    },
    phone: require('ripple/platform/webworks.handset/2.0.0/server/identity/phone')
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/invoke', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 notifications = require('ripple/notifications'),
    constants = require('ripple/constants'),
    type = "normal",
    name = {
        "0": "Address Book",
        "1": "Bluetooth Config",
        "2": "Calculator",
        "3": "Calendar",
        "camera://": "Camera",
        "camera://video": "Video Camera",
        "map://": "Maps",
        "6": "Memopad",
        "7": "Messages",
        "8": "Phone",
        "9": "Search",
        "10": "Tasks",
        "11": "Browser",
        "http://": "Browser",
        "12": "Java",
    };

module.exports = {
    invoke: function (opts) {
        var app = name[opts.appType];
        if (app === undefined && opts.appType && opts.appType.match(/^http/i)) {
            app = "Browser";
        }

        notifications.openNotification(type,
           "Requested to launch: " + app + " application.");
        return {code: 1};
    }
};

});
define('ripple/platform/webworks.handset/2.0.0/server/io/dir', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 cache = require('ripple/platform/webworks.core/2.0.0/fsCache'),
    dir = require('ripple/platform/webworks.core/2.0.0/server/io/dir'),
    utils = require('ripple/utils'),
    _self = {};

function _packet(data) {
    return {
        code: 1,
        data: data
    };
}

utils.mixin({
    getFreeSpaceForRoot: function (get, post, baton) {
        return _packet(cache.dir.getFreeSpaceForRoot(post.path));
    },
    getRootDirs: function (get, post, baton) {
        return _packet(cache.dir.getRootDirs());
    }
}, _self);

utils.mixin(dir, _self);

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/memo', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    select = require('ripple/platform/webworks.core/2.0.0/select'),
    _self;

function _get() {
    return db.retrieveObject("webworks-pim-memo-list") || {};
}

function _do(func) {
    var memos = _get();
    func(memos);
    db.saveObject("webworks-pim-memo-list", memos);
}

_self = {
    find: function (get, post) {
        var memos = select.from(_get())
                    .orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc")
                    .max(post.maxReturn)
                    .where(post.filter);
        return {code: 1, data: memos};
    },
    remove: function (get, post) {
        _do(function (memos) {
            if (!memos[get.uid]) {
                throw "attempting to delete a non existant memo with uid: " + get.uid;
            }
            delete memos[get.uid];
        });
        return {code: 1};
    },
    save: function (get, post) {
        _do(function (memos) {
            memos[post.memo.uid] = post.memo;
        });
        return {code: 1};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/menu', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _menuItems = {},
    event = require('ripple/event'),
    events = require('ripple/platform/webworks.core/2.0.0/client/events'),
    ui = require('ripple/ui'),
    devices = require('ripple/devices'),
    utils = require('ripple/utils'),
    tooltip = require('ripple/ui/plugins/tooltip'),
    _self,
    isMenuOpen = false,
    _baton,
    menuWindow = document ? document.getElementById("menu-window") : undefined;

if (menuWindow) {
    menuWindow.addEventListener("click", function () {
        _self.close();
    });
}

event.on("LayoutChanged", function () {
    if (isMenuOpen) {
        _self.close();
        //Used to resize menu on orientation change
        _self.open();
    }
});

event.on("HardwareKeyDefault", function (key) {
    if (key === 1 || key === "1") { //menu button key
        if (isMenuOpen) {
            _self.close();
        }
        else {
            _self.open();
        }
    }
});

event.on("MenuItemSelected", function (menuItem) {
    var baton = _baton;
    _baton = null;
    return baton && baton.pass({code: 1, data: menuItem});
});

event.on("MenuItemChanged", function (menuItem) {
    _menuItems[menuItem.id] = menuItem;
});

_self = {

    onSelect : function (args, post, baton) {
        baton.take();
        _baton = baton;
    },

    addMenuItem: function (args) {
        if (!args) {
            throw "item not found";
        }
        _menuItems[args.item.id] = args.item;
        event.trigger("MenuChanged", [_menuItems]);
        return {code: 1};
    },

    clearMenuItems: function () {
        _menuItems = {};
        event.trigger("MenuChanged", [utils.copy(_menuItems)]);
        return {code: 1};
    },

    open: function () {
        function _return() {
            return {code: 1};
        }

        if (utils.count(_menuItems) === 0) {
            _return();
        }

        ui.showOverlay("menu-window", function (menu) {
            var container = document.getElementById("viewport-container"),
                height = window.getComputedStyle(container, null).getPropertyValue("height"),
                width = window.getComputedStyle(container, null).getPropertyValue("width"),
                menuButtons = document.getElementById("menu-buttons"),
                sorted,
                menuItem;

            if (!menuButtons) {
                _return();
            }

            menu.setAttribute("style", "display:block;height:" + height + "; width:" + width + ";");
            isMenuOpen = true;

            sorted = utils.map(_menuItems, function (item) {
                return item;
            }).sort(function (a, b) {
                return a.ordinal - b.ordinal;
            });

            menuButtons.innerHTML = "";
            sorted.forEach(function (item) {
                if (!item.isSeparator) {
                    if (item.isDefault) {
                        menuItem = utils.createElement("div", {
                            "class": "overlay-menu-item-default",
                            "id": "default-menu-item"
                        });
                    }
                    else {
                        menuItem = utils.createElement("div", {
                            "class": "overlay-menu-item"
                        });
                    }
                    menuItem.innerHTML = item.caption;

                    menuItem.addEventListener("click", function () {
                        _baton.pass({code: 1, data: item.id});
                    });
                }
                else {
                    menuItem = utils.createElement("hr", {});
                }
                menuButtons.appendChild(menuItem);
                tooltip.create("#default-menu-item", "Default Item");
            });
        }, true);

        event.trigger("MenuOpened", []);

        _return();
    },

    close: function () {
        ui.hideOverlay("menu-window", function (menu) {
            var menuButtons = document.getElementById("menu-buttons");
            menuButtons.innerHTML = "";
            isMenuOpen = false;
            menu.setAttribute("style", "display:none;");

        });
        return {code: 1};
    },

    removeMenuItem: function (args) {
        delete _menuItems[args.item.id];
        event.trigger("MenuChanged", [_menuItems]);
        return {code: 1};
    },

    setDefaultMenuItem: function (args) {

        utils.forEach(_menuItems, function (item) {
            item.isDefault = false;
        });

        _menuItems[args.id].isDefault = true;

        event.trigger("DefaultItemChanged", [_menuItems[args.id]]);
        return {code: 1};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/message', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    select = require('ripple/platform/webworks.core/2.0.0/select'),
    Message = require('ripple/platform/webworks.handset/2.0.0/client/Message'),
    _self;

function _get() {
    return db.retrieveObject("webworks-message-list") || {};
}

function _do(func) {
    var messages = _get();
    func(messages);
    db.saveObject("webworks-message-list", messages);
}

_self = {
    find: function (get, post) {
        var data = select
                .from(_get())
                .max(post.maxReturn)
                .where(post.filter);
        return {code: 1, data: data};
    },

    remove: function (get, post) {
        _do(function (messages) {
            if (!messages[get.uid]) {
                throw "attempting to delete a non existant message with uid: " + get.uid;
            }
            delete messages[get.uid];
        });
        return {code: 1};
    },

    save: function (get, post) {
        _do(function (messages) {
            var orig = messages[post.message.uid],
                updated = utils.copy(post.message);

            updated.folder = orig ? orig.folder : Message.FOLDER_DRAFT;
            updated.status = orig ? orig.status : Message.STATUS_DRAFT;

            messages[post.message.uid] = updated;
        });
        return {code: 1};
    },

    send: function (get, post) {
        _do(function (messages) {
            var updated = utils.copy(get.message);

            updated.folder = Message.FOLDER_SENT;
            updated.status = Message.STATUS_SENT;

            messages[updated.uid] = updated;
        });
        return {code: 1};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/phone', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 PhoneCall = require('ripple/platform/webworks.handset/2.0.0/client/PhoneCall'),
    PhoneLogs = require('ripple/platform/webworks.handset/2.0.0/client/PhoneLogs'),
    CallLog = require('ripple/platform/webworks.handset/2.0.0/client/CallLog'),
    select = require('ripple/platform/webworks.core/2.0.0/select'),
    event = require('ripple/event'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    _KEY = "blackberry-phone-logs",
    _onPhoneEventListeners = {},
    _activeCalls = {},
    _onCallLogAdded,
    _onCallLogRemoved,
    _onCallLogUpdated,
    _onCallLogReset,
    _self;

function _defaultLogs() {
    var n1 = new CallLog(),
        n2 = new CallLog(),
        m1 = new CallLog(),
        m2 = new CallLog();

    n1.number = "12344567";
    n1.name = "larry";
    n1.type = CallLog.TYPE_PLACED_CALL;
    n1.status = CallLog.STATUS_NORMAL;

    n2.number = "14567890";
    n2.name = "curly";
    n2.type = CallLog.TYPE_RECEIVED_CALL;
    n2.status = CallLog.STATUS_NORMAL;

    m1.number = "17659800";
    m1.name = "moe";
    m1.type = CallLog.TYPE_MISSED_CALL_UNOPENED;
    m1.status = CallLog.STATUS_NORMAL;

    m2.number = "14567896";
    m2.name = "snarf";
    m2.type = CallLog.TYPE_MISSED_CALL_OPENED;
    m2.status = CallLog.STATUS_NORMAL;

    return {
        normal: [n1, n2],
        missed: [m1, m2]
    };
}

function _getLogs(folderID) {
    var logs = db.retrieveObject(_KEY) || _defaultLogs();
    return folderID === undefined || folderID === null ?
        logs : logs[folderID !== PhoneLogs.FOLDER_NORMAL_CALLS ? "missed" : "normal"];
}

function _saveLogs(logs) {
    db.saveObject(_KEY, logs);
}

function _isMissedCall(log) {
    return (log.type === CallLog.TYPE_MISSED_CALL_UNOPENED ||
            log.type === CallLog.TYPE_MISSED_CALL_OPENED) ? true : false;
}

function _isNormalCall(log) {
    return (log.type === CallLog.TYPE_RECEIVED_CALL ||
            log.type === CallLog.TYPE_PLACED_CALL) ? true : false;
}

event.on("PhoneEvent", function (type, callId, error) {
    var baton = _onPhoneEventListeners[type];
    delete _onPhoneEventListeners[type];

    return baton && baton.pass({code: 1, data: {callId: callId, error: error}});
});

event.on("PhoneCallLogAdded", function (log) {
    var logs = _getLogs(),
        baton = _onCallLogAdded;

    logs[_isMissedCall(log) ? "missed" : "normal"].push(log);
    _saveLogs(logs);

    _onCallLogAdded = null;
    return baton && baton.pass({code: 1, data: {log: log}});
});

event.on("PhoneCallLogRemoved", function (log) {
    // TODO: make this be the only one responsible for deletion (instead of triggering internally)
    var baton = _onCallLogRemoved;
    _onCallLogRemoved = null;
    return baton && baton.pass({code: 1, data: {log: log}});
});

event.on("PhoneCallLogUpdated", function (newLog, oldLog) {
    // TODO: implement way to update with just this event
    var baton = _onCallLogUpdated;
    _onCallLogUpdated = null;
    return baton && baton.pass({code: 1, data: {
        newLog: newLog,
        oldLog: oldLog
    }});
});

event.on("PhoneCallLogReset", function () {
    _saveLogs(_defaultLogs());
    var baton = _onCallLogReset;
    _onCallLogReset = null;
    return baton && baton.pass({code: 1});
});

event.on("PhoneCallInitiated", function (call) {
    _activeCalls[call.id] = call;
});

event.on("PhoneCallEnded", function (call) {
    delete _activeCalls[call.id];
});

_self = {
    logs: {
        onCallLogAdded: function (get, post, baton) {
            baton.take();
            _onCallLogAdded = baton;
        },

        onCallLogRemoved: function (get, post, baton) {
            baton.take();
            _onCallLogRemoved = baton;
        },

        onCallLogUpdated: function (get, post, baton) {
            baton.take();
            _onCallLogUpdated = baton;
        },

        onCallLogReset: function (get, post, baton) {
            baton.take();
            _onCallLogReset = baton;
        },

        callAt: function (get) {
            var logs = _getLogs(get.folderID !== null && get.folderID !== undefined ?
                                        get.folderID : PhoneLogs.FOLDER_MISSED_CALLS);
            return {code: 1, data: logs.length > get.index ? logs[get.index] : null};
        },

        deleteCallAt: function (get) {
            var logs = _getLogs(),
                subLog = _getLogs(get.folderID),
                deleted = false,
                type, log;

            if (subLog.length > get.index &&
               (type = _isNormalCall(subLog[get.index]) ? "normal" : "missed") &&
               (log = logs[type].splice(get.index, 1))) {
                event.trigger("PhoneCallLogRemoved", [log]);
                _saveLogs(logs);
                deleted = true;
            }

            return {code: 1, data: deleted};
        },

        find: function (get, post) {
            var data = select.from(_getLogs(post.folderID !== null && post.folderID !== undefined ?
                                        post.folderID : PhoneLogs.FOLDER_MISSED_CALLS))
                    .orderBy(post.orderBy, post.isAscending === false ? "desc" : "asc")
                    .max(post.maxReturn)
                    .where(post.filter, select.ops.phone);
            return {code: 1, data: data};
        },

        numberOfCalls: function (get) {
            return {code: 1, data: _getLogs(get.folderID !== null && get.folderID !== undefined ?
                                        get.folderID : PhoneLogs.FOLDER_MISSED_CALLS).length};
        }
    },

    onPhoneEvent: function (get, post, baton) {
        baton.take();
        _onPhoneEventListeners[get.eventType] = baton;
    },

    activeCalls: function () {
        var data = utils.map(_activeCalls, function (callItem) {
            var call = new PhoneCall(callItem.onhold);
            call.outgoing = callItem.outgoing;
            call.recipientName = callItem.recipient.name;
            call.recipientNumber = callItem.recipient.number;
            return call;
        });
        return {code: 1, data: data};
    },

    inActiveCall: function () {
        return {code: 1, data: utils.count(_activeCalls) > 0 ? true : false};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/push', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    _handlers = {},
    _self;

function listenersChanged() {
    var ports = utils.map(_handlers, function (handler) {
        return handler.port;
    });
    event.trigger("PushListenersChanged", [ports]);
}

event.on("Push", function (data, port) {
    var handler = _handlers["port_" + port];
    delete _handlers["port_" + port];
    window.setTimeout(function () {
        if (!_handlers["port_" + port]) {
            //doesn't look like they are coming back ;)
            listenersChanged();
        }
    }, 100);
    return handler && handler.baton.pass({code: 1, data: data});
});

_self = {

    onPush: function (args, post, baton) {
        if (!args.port) {
            throw "no port specified";
        }
        else if (typeof args.port !== 'number') {
            throw "port is not a number";
        }
        baton.take();
        _handlers["port_" + args.port] = {
            port: args.port,
            baton: baton
        };
        listenersChanged();
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/sms', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _listener,
    _isListening = false,
    notifications = require('ripple/notifications'),
    constants = require('ripple/constants'),
    event = require('ripple/event'),
    _console = require('ripple/console'),
    _onReceive,
    _self;

event.on("MessageReceived", function (message) {
    if (!_isListening || message.type !== 'sms') {
        return;
    }

    var baton = _onReceive;
    _onReceive = null;
    _isListening = false;
    return baton && baton.pass({code: 1, data: message});
});

_self = {
    onReceive: function (args, post, baton) {
        baton.take();
        _onReceive = baton;
        _isListening = !!_onReceive;
    },

    send: function (args) {
        var msg = "To " + args.address + ": " + args.message;
        notifications.openNotification("normal", msg);
        _console.log(msg);
        return {code: 1};
    },

    isListeningForMessage: function (get, post, baton) {
        if (get && typeof get.isListeningForMessage === "boolean") {
            _isListening = get.isListeningForMessage;
        }

        return {code: 1, data: _isListening};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/server/systemEvent', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    _onCoverageChange,
    _onHardwareKey = {};

event.on("CoverageChange", function () {
    var baton = _onCoverageChange;
    _onCoverageChange = null;
    return baton && baton.pass({code: 1});
});

event.on("HardwareKey", function (key) {
    var baton = _onHardwareKey["key_" + key];
    delete _onHardwareKey["key_" + key];

    if (baton) {
        baton.pass({code: 1});
    }
    else {
        event.trigger("HardwareKeyDefault", [key]);
    }
});

module.exports = {
    onCoverageChange: function (args, post, baton) {
        baton.take();
        _onCoverageChange = baton;
    },

    onHardwareKey: function (args, post, baton) {
        baton.take();
        _onHardwareKey["key_" + args.key] = baton;
    }
};

});
define('ripple/platform/webworks.handset/2.0.0/server', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    platform = "ripple/platform/webworks.handset/2.0.0/server/",
    core = "ripple/platform/webworks.core/2.0.0/server/",
    systemEvent = require(platform + 'systemEvent'),
    system = {};

// ugh, thanks to the spec...
system.event = systemEvent;
utils.mixin(require(core + "system"), system);

module.exports = {
    blackberry: {
        invoke: require(platform + "invoke"),
        system: system,
        app: require(platform + "app"),
        identity: require(platform + "identity"),
        message: {
            sms: require(platform + "sms"),
            message: require(platform + "message")
        },
        push: require(platform + "push"),
        pim: {
            Task: require(platform + "Task"),
            category: require(platform + "category"),
            memo: require(platform + "memo"),
            appointment: require(platform + "appointment"),
            contact: require(platform + "contact")
        },
        audio: {
            player: require(platform + "audioPlayer")
        },
        ui: {
            menu: require(platform + "menu"),
            dialog: require(core + "dialog")
        },
        phone: require(platform + "phone"),
        io: {
            dir: require(platform + "io/dir"),
            file: require(core + "io/file")
        }
    }
};

});
define('ripple/platform/webworks.handset/2.0.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event');

module.exports = {
    "transports": {
        "TCP Cellular": {
            "name": "Cellular TCP",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "Wap": {
            "name": "WAP",
            "control": {
                "type": "checkbox",
                "value": false
            }
        },
        "Wap 2.0": {
            "name": "WAP 2.0",
            "control": {
                "type": "checkbox",
                "value": false
            }
        },
        "MDS": {
            "name": "MDS",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "Bis B": {
            "name": "BIS B",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "Unite!": {
            "name": "Unite",
            "control": {
                "type": "checkbox",
                "value": false
            }
        },
        "TCP Wifi": {
            "name": "Wifi TCP",
            "control": {
                "type": "checkbox",
                "value": true
            }
        }
    },
    "identity": {
        "IMEI": {
            "name": "IMEI",
            "control": {
                "type": "text",
                "value": "123456786543210"
            }
        },
        "IMSI": {
            "name": "IMSI",
            "control": {
                "type": "text",
                "value": "310150123456789"
            }
        },
        "PIN": {
            "name": "PIN",
            "control": {
                "type": "text",
                "value": "43A8C489"
            }
        }
    },
    "system": {
        "isMassStorageActive": {
            "name": "Mass Storage Is Connected",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "hasDataCoverage": {
            "name": "Has Data Coverage",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("CoverageChange");
                require('ripple/bus').send("network", setting);
            }
        },
        "lag": {
            "name": "Lag the network",
            "control": {
                type: "checkbox",
                value: false
            },
            "callback": function (setting) {
                require('ripple/bus').send("lag", setting);
            }
        },
        "network": {
            "name": "Data Network",
            "control": {
                "type": "select",
                "value": "3GPP"
            },
            "options": {
                "3GPP" : "3GPP",
                "CDMA": "CDMA",
                "iDEN": "iDEN",
                "Wi-Fi": "Wi-Fi"
            },
            "callback": function (setting) {
                event.trigger("CoverageChange");
            }
        }
    }
};

});
define('ripple/platform/webworks.handset/2.0.0/spec/events', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    events = require('ripple/platform/webworks.core/2.0.0/spec/events');

_self = {
    "system.event.onExit": {
        callback: function () {
            event.trigger("AppExit");
        }
    },
    "system.event.onCoverageChange": {
        callback: function () {
            event.trigger("CoverageChange");
        }
    },
    "system.event.onHardwareKey": {
        args: [
            "Back",
            "Menu",
            "Convenience 1",
            "Convenience 2",
            "Start Call",
            "End Call",
            "Volume Down",
            "Volume Up"
        ],
        callback: function (key) {
            event.trigger("HardwareKey", [key]);
        }
    }
};

utils.mixin(events, _self);

module.exports = _self;

});
define('ripple/platform/webworks.handset/2.0.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "accelerometer",
        "deviceSettings",
        "geoView",
        "platformEvents",
        "widgetConfig",
        "messaging",
        "push",
        "phone",
        "build"
    ]
};

});
define('ripple/platform/webworks.handset/2.0.0/spec', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    id: "webworks.handset",
    version: "2.0.0",
    name: "WebWorks",

    persistencePrefix: "rim-handset-",

    ui: require('ripple/platform/webworks.handset/2.0.0/spec/ui'),
    device: require('ripple/platform/webworks.handset/2.0.0/spec/device'),
    config: require('ripple/platform/webworks.core/2.0.0/spec/config'),
    events: require('ripple/platform/webworks.handset/2.0.0/spec/events'),

    initialize: function () {},

    objects: {
        XMLHttpRequest: {
            path: "webworks.handset/2.0.0/XMLHttpRequest"
        },
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        navigator: {
            path: "w3c/1.0/navigator",
            children: {
                geolocation: {
                    path: "w3c/1.0/geolocation"
                }
            }
        },
        blackberry: {
            path: "webworks.handset/2.0.0/client/blackberry",
            children: {
                pim: {
                    path: "webworks.handset/2.0.0/client/pim",
                    feature: "blackberry.pim.category|blackberry.pim.Task|blackberry.pim.Recurrence|blackberry.pim.Reminder|blackberry.pim.Appointment|blackberry.pim.Address|blackberry.pim.Attendee|blackberry.pim.Memo|blackberry.pim.Contact",
                    children: {
                        category: {
                            path: "webworks.handset/2.0.0/client/category",
                            feature: "blackberry.pim.category"
                        },
                        Task: {
                            path: "webworks.handset/2.0.0/client/Task",
                            feature: "blackberry.pim.Task"
                        },
                        Recurrence: {
                            path: "webworks.handset/2.0.0/client/Recurrence",
                            feature: "blackberry.pim.Recurrence"
                        },
                        Reminder: {
                            path: "webworks.handset/2.0.0/client/Reminder",
                            feature: "blackberry.pim.Reminder"
                        },
                        Appointment: {
                            path: "webworks.handset/2.0.0/client/Appointment",
                            feature: "blackberry.pim.Appointment"
                        },
                        Address: {
                            path: "webworks.handset/2.0.0/client/Address",
                            feature: "blackberry.pim.Address"
                        },
                        Attendee: {
                            path: "webworks.handset/2.0.0/client/Attendee",
                            feature: "blackberry.pim.Attendee"
                        },
                        Memo: {
                            path: "webworks.handset/2.0.0/client/Memo",
                            feature: "blackberry.pim.Memo"
                        },
                        Contact: {
                            path: "webworks.handset/2.0.0/client/Contact",
                            feature: "blackberry.pim.Contact"
                        }
                    }
                },
                phone: {
                    children: {
                        Phone: {
                            path: "webworks.handset/2.0.0/client/Phone",
                            feature: "blackberry.phone.Phone"
                        },
                        PhoneLogs: {
                            path: "webworks.handset/2.0.0/client/PhoneLogs",
                            feature: "blackberry.phone.PhoneLogs|blackberry.phone.Find",
                            children: {
                                CallLog: {
                                    path: "webworks.handset/2.0.0/client/CallLog"
                                }
                            }
                        },
                        Find: {
                            children: {
                                FilterExpression: {
                                    path: "webworks.handset/2.0.0/client/FilterExpression",
                                    feature: "blackberry.phone.Find"
                                }
                            }
                        }
                    }
                },
                message: {
                    path: "webworks.handset/2.0.0/client/messaging",
                    feature: "blackberry.message.sms|blackberry.message",
                    children: {
                        sms: {
                            path: "webworks.handset/2.0.0/client/sms",
                            feature: "blackberry.message.sms"
                        },
                        Message: {
                            path: "webworks.handset/2.0.0/client/Message",
                            feature: "blackberry.message"
                        }
                    }
                },
                transport: {
                    path: "webworks.core/2.0.0/client/transport"
                },
                events: {
                    path: "webworks.core/2.0.0/client/events"
                },
                app: {
                    path: "webworks.handset/2.0.0/client/app",
                    feature: "blackberry.app",
                    children: {
                        event: {
                            path: "webworks.handset/2.0.0/client/appEvent",
                            feature: "blackberry.app.event"
                        }
                    }
                },
                invoke: {
                    path: "webworks.handset/2.0.0/client/invoke",
                    feature: "blackberry.invoke",
                    children: {
                        AddressBookArguments: {
                            path: "webworks.handset/2.0.0/client/AddressBookArguments",
                            feature: "blackberry.invoke.AddressBookArguments"
                        },
                        BrowserArguments: {
                            path: "webworks.handset/2.0.0/client/BrowserArguments",
                            feature: "blackberry.invoke.BrowserArguments"
                        },
                        CameraArguments: {
                            path: "webworks.handset/2.0.0/client/CameraArguments",
                            feature: "blackberry.invoke.CameraArguments"
                        },
                        CalendarArguments: {
                            path: "webworks.handset/2.0.0/client/CalendarArguments",
                            feature: "blackberry.invoke.CalendarArguments"
                        },
                        JavaArguments: {
                            path: "webworks.handset/2.0.0/client/JavaArguments",
                            feature: "blackberry.invoke.JavaArguments"
                        },
                        MapsArguments: {
                            path: "webworks.handset/2.0.0/client/MapsArguments",
                            feature: "blackberry.invoke.MapsArguments"
                        },
                        MemoArguments: {
                            path: "webworks.handset/2.0.0/client/MemoArguments",
                            feature: "blackberry.invoke.MemoArguments"
                        },
                        MessageArguments: {
                            path: "webworks.handset/2.0.0/client/MessageArguments",
                            feature: "blackberry.invoke.MessageArguments"
                        },
                        PhoneArguments: {
                            path: "webworks.handset/2.0.0/client/PhoneArguments",
                            feature: "blackberry.invoke.PhoneArguments"
                        },
                        SearchArguments: {
                            path: "webworks.handset/2.0.0/client/SearchArguments",
                            feature: "blackberry.invoke.SearchArguments"
                        },
                        TaskArguments: {
                            path: "webworks.handset/2.0.0/client/TaskArguments",
                            feature: "blackberry.invoke.TaskArguments"
                        }
                    }
                },
                identity: {
                    path: "webworks.handset/2.0.0/client/identity",
                    feature: "blackberry.identity",
                    children: {
                        Transport: {
                            path: "webworks.handset/2.0.0/client/identity/Transport",
                            feature: "blackberry.identity"
                        },
                        Service: {
                            path: "webworks.handset/2.0.0/client/identity/Service",
                            feature: "blackberry.identity"
                        },
                        phone: {
                            path: "webworks.handset/2.0.0/client/identity/phone",
                            feature: "blackberry.identity.phone"
                        }
                    }
                },
                system: {
                    path: "webworks.handset/2.0.0/client/system",
                    feature: "blackberry.system",
                    children: {
                        event: {
                            path: "webworks.handset/2.0.0/client/systemEvent",
                            feature: "blackberry.system.event"
                        }
                    }
                },
                ui: {
                    children: {
                        dialog: {
                            path: "webworks.core/2.0.0/client/dialog",
                            feature: "blackberry.ui.dialog"
                        },
                        menu: {
                            path: "webworks.handset/2.0.0/client/menu",
                            children: {
                                MenuItem: {
                                    path: "webworks.handset/2.0.0/client/MenuItem"
                                }
                            }
                        }
                    }
                },
                utils: {
                    path: "webworks.core/2.0.0/client/utils",
                    feature: "blackberry.utils"
                },
                find: {
                    feature: "blackberry.find",
                    children: {
                        FilterExpression: {
                            path: "webworks.handset/2.0.0/client/FilterExpression",
                            feature: "blackberry.find"
                        }
                    }
                },
                push: {
                    path: "webworks.handset/2.0.0/client/push",
                    feature: "blackberry.push"
                },
                audio: {
                    path: "webworks.handset/2.0.0/client/audio",
                    feature: "blackberry.audio",
                    children: {
                        Player: {
                            path: "webworks.handset/2.0.0/client/AudioPlayer",
                            feature: "blackberry.audio.Player"
                        }
                    }
                },
                io: {
                    children: {
                        dir: {
                            path: "webworks.handset/2.0.0/client/io/dir",
                            feature: "blackberry.io.dir"
                        },
                        file: {
                            path: "webworks.core/2.0.0/client/io/file",
                            feature: "blackberry.io.file"
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform/webworks.tablet/2.0.0/XMLHttpRequest', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 xhr = require("ripple/platform/webworks.core/2.0.0/XMLHttpRequest");
module.exports = xhr.create("ripple/platform/webworks.tablet/2.0.0/server");

});
define('ripple/platform/webworks.tablet/2.0.0/client/BrowserArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.BrowserArguments ( url : String ,  [transport : blackberry.identity.Transport ] )
module.exports = function (url, transport) {
    return {
        url: url
    };
};

});
define('ripple/platform/webworks.tablet/2.0.0/client/CameraArguments', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//blackberry.invoke.CameraArguments ( )
var _self = function () {
    return {
        //readwrite  property  Number   view
        view: 0
    };
};

//const Number  VIEW_CAMERA  = 0
_self.__defineGetter__("VIEW_CAMERA", function () {
    return 0;
});
//const Number  VIEW_RECORDER  = 1
_self.__defineGetter__("VIEW_RECORDER", function () {
    return 1;
});

module.exports = _self;

});
define('ripple/platform/webworks.tablet/2.0.0/client/app', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/app/",
    _self;

_self = {
    exit: function () {
        transport.call(_uri + "exit", {async: true});
    }
};

_self.__defineGetter__("author", function () {
    return transport.call(_uri + "author");
});

_self.__defineGetter__("authorEmail", function () {
    return transport.call(_uri + "authorEmail");
});

_self.__defineGetter__("authorURL", function () {
    return transport.call(_uri + "authorURL");
});

_self.__defineGetter__("copyright", function () {
    return transport.call(_uri + "copyright");
});

_self.__defineGetter__("description", function () {
    return transport.call(_uri + "description");
});

_self.__defineGetter__("id", function () {
    return transport.call(_uri + "id");
});

_self.__defineGetter__("license", function () {
    return transport.call(_uri + "license");
});

_self.__defineGetter__("licenseURL", function () {
    return transport.call(_uri + "licenseURL");
});

_self.__defineGetter__("name", function () {
    return transport.call(_uri + "name");
});

_self.__defineGetter__("version", function () {
    return transport.call(_uri + "version");
});

module.exports = _self;

});
define('ripple/platform/webworks.tablet/2.0.0/client/appEvent', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _callbacks = {},
    _self;

function _poll(evt, handler) {
    _callbacks[evt] = handler;

    transport.poll("blackberry/app/event/" + evt, {}, function () {
        var func = _callbacks[evt];

        if (func) {
            func();
        }

        return !!func;
    });
}

_self = {
    onBackground: function (handler) {
        _poll("onBackground", handler);
    },

    onForeground: function (handler) {
        _poll("onForeground", handler);
    },

    onSwipeDown: function (handler) {
        _poll("onSwipeDown", handler);
    },

    onSwipeStart: function (handler) {
        _poll("onSwipeStart", handler);
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.tablet/2.0.0/client/identity', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _uri = "blackberry/identity/",
    _self = {};

_self.__defineGetter__("PIN", function () {
    return transport.call(_uri + "PIN");
});

module.exports = _self;

});
define('ripple/platform/webworks.tablet/2.0.0/client/invoke', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _uri = "blackberry/invoke/invoke",
    APP_TYPE = "appType",
    APP_URL_CAMERA = "camera://",
    APP_URL_CAMERA_VIDEO = "camera://video",
    APP_URL_MAP = "map://",
    APP_URL_MUSIC = "music://",
    APP_URL_PHOTOS = "photos://",
    APP_URL_VIDEOS = "videos://",
    APP_URL_APPWORLD = "appworld://",
    APP_URL_UPDATE = "update://",
    APP_TYPE_ERROR = "appType not supported",
    APP_BROWSER_ERROR = "Protocol specified in the url is not supported.",
    transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    _self;

_self = {
    invoke: function (appType, args) {
        var get = {};

        switch (appType) {

        //Camera
        case 4:
            if (!args || args.view === 1) {
                get.appType = APP_URL_CAMERA_VIDEO;
            } else {
                get.appType = APP_URL_CAMERA;
            }
            break;

        //Maps
        case 5:
            get.appType = APP_URL_MAP;
            break;

        //Browser
        case 11:

            if (!args) {
                get.appType = "http://";
            }
            else {
                get.appType = args.url.split("://");

                if (get.appType.length === 1) {
                    get.appType = "http://" + get.appType[0];
                }
                else if (get.appType.length === 2) {
                    if (get.appType[0].indexOf("http") !== 0) {
                        throw APP_BROWSER_ERROR;
                    }
                    else {
                        get.appType = args.url;
                    }
                }
            }
            break;

        //Music
        case 13:
            get.appType = APP_URL_MUSIC;
            break;

        //Photos
        case 14:
            get.appType = APP_URL_PHOTOS;
            break;

        //Videos
        case 15:
            get.appType = APP_URL_VIDEOS;
            break;

        //AppWorld
        case 16:
            get.appType = APP_URL_APPWORLD;
            break;

        //Update
        case 17:
            get.appType = APP_URL_UPDATE;
            break;

        default:
            throw APP_TYPE_ERROR;
        }

        transport.call(_uri, {
            get: get,
            async: true
        });
    }
};

_self.__defineGetter__("APP_CAMERA", function () {
    return 4;
});
_self.__defineGetter__("APP_MAPS", function () {
    return 5;
});
_self.__defineGetter__("APP_BROWSER", function () {
    return 11;
});
_self.__defineGetter__("APP_MUSIC", function () {
    return 13;
});
_self.__defineGetter__("APP_PHOTOS", function () {
    return 14;
});
_self.__defineGetter__("APP_VIDEOS", function () {
    return 15;
});
_self.__defineGetter__("APP_APPWORLD", function () {
    return 16;
});

module.exports = _self;

});
define('ripple/platform/webworks.tablet/2.0.0/client/io/dir', function (require, exports, module) {
/*
 * Copyright 2011 Research In Motion Limited.
 *
 * 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 dir = require('ripple/platform/webworks.core/2.0.0/client/io/dir'),
    utils = require('ripple/utils'),
    _self = {};

utils.mixin({
    appDirs: {
        "app": {
            "storage" : {
                "path" : "file:///accounts/1000/appdata/emulatedapp/data"
            }
        },
        "shared": {
            "bookmarks": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/bookmarks"
            },
            "books": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/books"
            },
            "camera": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/camera"
            },
            "documents": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/documents"
            },
            "downloads": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/downloads"
            },
            "misc": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/misc"
            },
            "music": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/music"
            },
            "photos": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/photos"
            },
            "print": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/print"
            },
            "videos": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/videos"
            },
            "voice": {
                "path" : "file:///accounts/1000/appdata/emulatedapp/shared/voice"
            }
        }
    }
}, _self);

utils.mixin(dir, _self);

module.exports = _self;

});
define('ripple/platform/webworks.tablet/2.0.0/client/system', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    system = require('ripple/platform/webworks.core/2.0.0/client/system'),
    _uri = "blackberry/system/";

system.__defineGetter__("scriptApiVersion", function () {
    return transport.call(_uri + "softwareVersion");
});


module.exports = system;

});
define('ripple/platform/webworks.tablet/2.0.0/client/systemEvent', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 transport = require('ripple/platform/webworks.core/2.0.0/client/transport'),
    api = "blackberry/system/event/";

function _poll(evt, handler) {
    transport.poll(api + evt, {}, function (data, response) {
        if (handler) {
            handler(data);
        }
        return !!handler;
    });
}

module.exports = {
    deviceBatteryLevelChange: function (handler) {
        _poll("deviceBatteryLevelChange", handler);
    },
    deviceBatteryStateChange: function (handler) {
        _poll("deviceBatteryStateChange", handler);
    }
};

});
define('ripple/platform/webworks.tablet/2.0.0/server/app', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    app = require('ripple/app'),
    _self;

_self = {
    event: require('ripple/platform/webworks.tablet/2.0.0/server/appEvent'),

    exit: function () {
        event.trigger("AppExit");
        return {code: 1};
    },

    author: function () {
        return {code: 1, data: app.getInfo().author};
    },

    authorEmail: function () {
        return {code: 1, data: app.getInfo().authorEmail};
    },

    authorURL: function () {
        return {code: 1, data: app.getInfo().authorURL};
    },

    copyright: function () {
        return {code: 1, data: app.getInfo().copyright};
    },

    description: function () {
        return {code: 1, data: app.getInfo().description};
    },

    id: function () {
        return {code: 1, data: app.getInfo().id};
    },

    license: function () {
        return {code: 1, data: app.getInfo().license};
    },

    licenseURL: function () {
        return {code: 1, data: app.getInfo().licenseURL};
    },

    name: function () {
        return {code: 1, data: app.getInfo().name};
    },

    version: function () {
        return {code: 1, data: app.getInfo().version};
    }
};

module.exports = _self;

});
define('ripple/platform/webworks.tablet/2.0.0/server/appEvent', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    notifications = require('ripple/notifications'),
    _bg,
    _fg,
    _swipeDown,
    _swipeStart,
    _exit;

event.on("AppExit", function () {
    var baton = _exit;
    _exit = null;
    notifications.openNotification("normal", "blackberry.app.exit() as called, in the real world your app will exit, here... you get this notification");
    return baton && baton.pass({code: 1});
});

event.on("AppRequestBackground", function () {
    var baton = _bg;
    _bg = null;
    return baton && baton.pass({code: 1});
});

event.on("AppRequestForeground", function () {
    var baton = _fg;
    _fg = null;
    return baton && baton.pass({code: 1});
});

event.on("AppSwipeDown", function () {
    var baton = _swipeDown;
    _swipeDown = null;
    return baton && baton.pass({code: 1});
});

event.on("AppSwipeStart", function () {
    var baton = _swipeStart;
    _swipeStart = null;
    return baton && baton.pass({code: 1});
});

module.exports = {
    onBackground: function (get, post, baton) {
        baton.take();
        _bg = baton;
        return {code: 1};
    },

    onForeground: function (get, post, baton) {
        baton.take();
        _fg = baton;
        return {code: 1};
    },

    onSwipeDown: function (get, post, baton) {
        baton.take();
        _swipeDown = baton;
        return {code: 1};
    },

    onSwipeStart: function (get, post, baton) {
        baton.take();
        _swipeStart = baton;
        return {code: 1};
    }
};

});
define('ripple/platform/webworks.tablet/2.0.0/server/identity', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 deviceSettings = require('ripple/deviceSettings');

module.exports = {
    PIN: function () {
        return {code: 1, data: deviceSettings.retrieve("identity.PIN")};
    }
};

});
define('ripple/platform/webworks.tablet/2.0.0/server/invoke', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 notifications = require('ripple/notifications'),
    constants = require('ripple/constants'),
    type = "normal",
    name = {
        "camera://": "Camera",
        "camera://video": "Video Camera",
        "map://": "Maps",
        "http://": "Browser",
        "music://": "Music",
        "photos://": "Photos",
        "videos://": "Videos",
        "appworld://": "App World",
        "update://": "Update"
    };

module.exports = {
    invoke: function (opts) {
        var app = name[opts.appType];
        if (app === undefined && opts.appType && opts.appType.match(/^http/i)) {
            app = "Browser";
        }

        notifications.openNotification(type,
           "Requested to launch: " + app + " application.");
        return {code: 1};
    }
};

});
define('ripple/platform/webworks.tablet/2.0.0/server/systemEvent', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    _onBatteryStateChange,
    _onBatteryLevelChange,
    _states = {
        UNKNOWN: 0,
        FULL: 1,
        CHARGING: 2,
        UNPLUGGED: 3
    },
    _battery = {
        state: _states.UNKNOWN,
        charging: null,
        level: null
    };

function _getState() {
    return _battery.level === 100 ? _states.FULL :
           _battery.charging ? _states.CHARGING : _states.UNPLUGGED;
}

function _pass(baton, data) {
    if (baton) {
        baton.pass({code: 1, data: data});
    }
}

event.on("DeviceBatteryStateChanged", function (charging) {
    _battery.charging = charging;
    _battery.state = _getState();
    _pass(_onBatteryStateChange, _battery.state);
});

event.on("DeviceBatteryLevelChanged", function (level) {
    level = parseInt(level, 10);

    _battery.level = level;
    _pass(_onBatteryLevelChange, level);

    if (level === 100) {
        _battery.state = _getState();
        _pass(_onBatteryStateChange, _battery.state);
    }
});

module.exports = {
    deviceBatteryLevelChange: function (get, post, baton) {
        baton.take();
        _onBatteryLevelChange = baton;
    },
    deviceBatteryStateChange: function (get, post, baton) {
        baton.take();
        _onBatteryStateChange = baton;
    }
};

});
define('ripple/platform/webworks.tablet/2.0.0/server', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    platform = "ripple/platform/webworks.tablet/2.0.0/server/",
    core = "ripple/platform/webworks.core/2.0.0/server/",
    systemEvent = require(platform + 'systemEvent'),
    system = {};

// ugh, thanks to the spec...
system.event = systemEvent;
utils.mixin(require(core + "system"), system);

module.exports = {
    blackberry: {
        identity: require(platform + "identity"),
        app: require(platform + "app"),
        invoke: require(platform + "invoke"),
        system: system,
        ui: {
            dialog: require(core + "dialog")
        },
        io: {
            dir: require(core + "io/dir"),
            file: require(core + "io/file")
        }
    }
};

});
define('ripple/platform/webworks.tablet/2.0.0/spec/device', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event');

module.exports = {
    "transports": {
        "TCPCellular": {
            "name": "Cellular TCP",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "WAP": {
            "name": "WAP",
            "control": {
                "type": "checkbox",
                "value": false
            }
        },
        "WAP2": {
            "name": "WAP 2.0",
            "control": {
                "type": "checkbox",
                "value": false
            }
        },
        "MDS": {
            "name": "MDS",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "BISB": {
            "name": "BIS B",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "Unite": {
            "name": "Unite!",
            "control": {
                "type": "checkbox",
                "value": false
            }
        },
        "TCPWifi": {
            "name": "Wifi TCP",
            "control": {
                "type": "checkbox",
                "value": true
            }
        }
    },
    "identity": {
        "PIN": {
            "name": "PIN",
            "control": {
                "type": "text",
                "value": "43A8C489"
            }
        }
    },
    "battery": {
        "state": {
            "name": "Handset is Charging",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("DeviceBatteryStateChanged", [setting]);
            }
        },
        "level":  {
            "name": "Charge Level (% remaining)",
            "control": {
                "type": "select",
                "value": 100
            },
            "options": (function () {
                var i,
                    optionList = {};

                for (i = 0; i <= 100; i++) {
                    optionList[i] = i;
                }

                return optionList;
            }()),
            "callback": function (setting) {
                event.trigger("DeviceBatteryLevelChanged", [setting]);
            }
        }
    },
    "system": {
        "isMassStorageActive": {
            "name": "Mass Storage Is Connected",
            "control": {
                "type": "checkbox",
                "value": true
            }
        },
        "hasDataCoverage": {
            "name": "Has Data Coverage",
            "control": {
                "type": "checkbox",
                "value": true
            },
            "callback": function (setting) {
                event.trigger("CoverageChange");
                require('ripple/bus').send("network", setting);
            }
        },
        "lag": {
            "name": "Lag the network",
            "control": {
                type: "checkbox",
                value: false
            },
            "callback": function (setting) {
                require('ripple/bus').send("lag", setting);
            }
        },
        "network": {
            "name": "Data Network",
            "control": {
                "type": "select",
                "value": "3GPP"
            },
            "options": {
                "3GPP" : "3GPP",
                "CDMA": "CDMA",
                "iDEN": "iDEN",
                "Wi-Fi": "Wi-Fi"
            },
            "callback": function (setting) {
                event.trigger("CoverageChange");
            }
        }
    }
};

});
define('ripple/platform/webworks.tablet/2.0.0/spec/events', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    events = require('ripple/platform/webworks.core/2.0.0/spec/events');

_self = {
    "app.event.onSwipeDown": {
        callback: function () {
            event.trigger("AppSwipeDown");
        }
    },
    "app.event.onSwipeStart": {
        callback: function () {
            event.trigger("AppSwipeStart");
        }
    }
};

utils.mixin(events, _self);

module.exports = _self;

});
define('ripple/platform/webworks.tablet/2.0.0/spec/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {
    plugins: [
        "accelerometer",
        "deviceSettings",
        "geoView",
        "platformEvents",
        "widgetConfig",
        "build"
    ]
};

});
define('ripple/platform/webworks.tablet/2.0.0/spec', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
module.exports = {

    id: "webworks.tablet",
    version: "2.0.0",
    name: "WebWorks-TabletOS",

    persistencePrefix: "rim-tablet-",

    ui: require('ripple/platform/webworks.tablet/2.0.0/spec/ui'),
    device: require('ripple/platform/webworks.tablet/2.0.0/spec/device'),
    config: require('ripple/platform/webworks.core/2.0.0/spec/config'),
    events: require('ripple/platform/webworks.tablet/2.0.0/spec/events'),

    initialize: function () {},

    objects: {
        XMLHttpRequest: {
            path: "webworks.tablet/2.0.0/XMLHttpRequest"
        },
        Coordinates: {
            path: "w3c/1.0/Coordinates"
        },
        Position: {
            path: "w3c/1.0/Position"
        },
        PositionError: {
            path: "w3c/1.0/PositionError"
        },
        navigator: {
            path: "w3c/1.0/navigator",
            children: {
                geolocation: {
                    path: "w3c/1.0/geolocation"
                }
            }
        },
        blackberry: {
            children: {
                transport: {
                    path: "webworks.core/2.0.0/client/transport"
                },
                events: {
                    path: "webworks.core/2.0.0/client/events"
                },
                app: {
                    path: "webworks.tablet/2.0.0/client/app",
                    feature: "blackberry.app",
                    children: {
                        event: {
                            path: "webworks.tablet/2.0.0/client/appEvent",
                            feature: "blackberry.app.event"
                        }
                    }
                },
                invoke: {
                    path: "webworks.tablet/2.0.0/client/invoke",
                    feature: "blackberry.invoke",
                    children: {
                        BrowserArguments: {
                            path: "webworks.tablet/2.0.0/client/BrowserArguments",
                            feature: "blackberry.invoke.BrowserArguments"
                        },
                        CameraArguments: {
                            path: "webworks.tablet/2.0.0/client/CameraArguments",
                            feature: "blackberry.invoke.CameraArguments"
                        }
                    }
                },
                identity: {
                    path: "webworks.tablet/2.0.0/client/identity",
                    feature: "blackberry.identity"
                },
                system: {
                    path: "webworks.tablet/2.0.0/client/system",
                    children: {
                        event: {
                            path: "webworks.tablet/2.0.0/client/systemEvent"
                        }
                    }
                },
                ui: {
                    children: {
                        dialog: {
                            path: "webworks.core/2.0.0/client/dialog",
                            feature: "blackberry.ui.dialog"
                        }
                    }
                },
                utils: {
                    path: "webworks.core/2.0.0/client/utils",
                    feature: "blackberry.utils"
                },
                io: {
                    children: {
                        dir: {
                            path: "webworks.tablet/2.0.0/client/io/dir",
                            feature: "blackberry.io.dir"
                        },
                        file: {
                            path: "webworks.core/2.0.0/client/io/file",
                            feature: "blackberry.io.file"
                        }
                    }
                }
            }
        }
    }
};

});
define('ripple/platform', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _current,
    db = require('ripple/db'),
    utils = require('ripple/utils'),
    _console = require('ripple/console'),
    app = require('ripple/app'),
    event = require('ripple/event'),
    spec = require('ripple/platform/spec'),
    _self;

function _getRequestedPlatform() {
    var requestedPlatform = null,
        enableRippleArg = utils.queryString().enableripple,
        platform;

    if (enableRippleArg) {
        enableRippleArg = enableRippleArg.split('-');
        platform = spec.get(enableRippleArg[0], enableRippleArg[1]);
        if (platform) {
            requestedPlatform = { name: platform.id, version: platform.version };
        }
    }

    return requestedPlatform;
}

function _validatePlatform(platform, defaultPlatform) {
    if (!platform ||
        !spec[platform.name] ||
        !spec[platform.name][platform.version] ||
        (spec[platform.name][platform.version] && !spec[platform.name][platform.version].objects)) {
        return defaultPlatform;
    }
    return platform;
}

function _getPlatform() {
    return require('ripple/platform/' + _current.name + "/" + _current.version + "/spec");
}

function _getCurrentPlatform() {
    var uriParams, platform = {};

    uriParams = utils.getURIParams(document.documentURI);
    if (uriParams && uriParams.platform) {
        var platformName = uriParams.platform.split("-")[0], platformVersion;

        if (platformName === "ivi") {
            platformName = "ivi";
            platformVersion = "3.0";
        }
        else if (platformName === "wearable") {
            platformName = "wearable";
            platformVersion = "2.0";
        }
        else if (platformName === "tv") {
            platformName = "tv";
            platformVersion = "1.0";
        }
        else {
            platformName = "tizen";
            platformVersion = "2.0";
        }
        platform.name = platformName;
        platform.version = platformVersion;

        return platform;
    }

    return undefined;
}

_self = {
    initialize: function () {
        var firstAvailablePlatform = utils.map(this.getList(), function (platform) {
            return utils.map(platform, function (details, version) {
                return {name: details.id, version: version};
            })[0];
        })[0];

        _current = _getRequestedPlatform() || _getCurrentPlatform() ||
                db.retrieveObject("api-key") || firstAvailablePlatform;
        _current = _validatePlatform(_current, firstAvailablePlatform);

        db.saveObject("api-key", _current);

        _console.prefix = _current.name;
    },

    getList: function () {
        var platformList = {};
        utils.forEach(spec, function (platform, platformKey) {
            utils.forEach(platform, function (version, versionKey) {
                platformList[platformKey] = platformList[platformKey] || {};
                platformList[platformKey][versionKey] = {
                    "id": version.id,
                    "name": version.name,
                    "type": version.type,
                    "text": require('ripple/platform/' + platformKey + "/" + versionKey + "/spec").version
                };
            });
        });

        return platformList;
    },

    getPersistencePrefix: function (id) {
        return _getPlatform().persistencePrefix + (id || app.getInfo().id) + "-";
    },

    current: function () {
        return _getPlatform();
    },

    changeEnvironment: function (platform, deviceId, callback) {
        var save = jWorkflow.order(function (prev, baton) {
                baton.take();
                db.saveObject("api-key", platform, null, baton.pass);
            }).andThen(function (prev, baton) {
                baton.take();
                db.save("device-key", deviceId, null, baton.pass);
            }).andThen(function (prev, baton) {
                //remove the persisted value for the layout
                baton.take();
                db.save("layout", null, null, baton.pass);
            }).andThen(function () {
                event.trigger("PlatformChangedEvent", [], true);
                _console.prefix = null;
                _console.log("Emulator :: loading platform " + platform.name);
            });

        save.start(callback);
    }
};

module.exports = _self;

});
define('ripple/resizer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    exception = require('ripple/exception'),
    utils = require('ripple/utils'),
    devices = require('ripple/devices'),
    constants = require('ripple/constants'),
    event = require('ripple/event'),
    _win,
    _doc,
    _self;

function _validateLayoutType(layoutType) {
    return (layoutType === "landscape" || layoutType === "portrait");
}

function _validateOrientation(orientation) {
    return (orientation === "landscape" || orientation === "portrait");
}

function _getContainers() {
    return {
        device: {
            div: document.getElementById("device-container"),
            containerClass: document.getElementById("device-container").getAttribute("class") || ""
        },
        viewport: {
            div: document.getElementById("viewport-container"),
            containerClass: document.getElementById("viewport-container").getAttribute("class") || ""
        },
        "menu-button": {
            div: document.getElementById(constants.COMMON.MENU_BUTTON),
            containerClass: document.getElementById(constants.COMMON.MENU_BUTTON).getAttribute("class") || ""
        },
        "back-button": {
            div: document.getElementById(constants.COMMON.BACK_BUTTON),
            containerClass: document.getElementById(constants.COMMON.BACK_BUTTON).getAttribute("class") || ""
        }
    };
}

function _setContainers(containers, device, orientation) {
    var suffix = {
            portrait:  "-wrapper" + (device.skin ? "-" + device.skin : ""),
            landscape: "-wrapper-landscape" + (device.skin ? "-" + device.skin : "")
        };

    utils.forEach(containers, function (container, key) {
        container.div.setAttribute("class", container.containerClass.replace(/\s.*$/, "") + " " + key + suffix[orientation]);
    });
}

function _getDimensions(device, orientation) {
    return {
        deviceWidth: orientation === "portrait" ? device.screen.width : device.screen.height,
        deviceHeight: orientation === "portrait" ? device.screen.height : device.screen.width,
        paddingLeft: device.viewPort[orientation].paddingLeft,
        paddingTop: device.viewPort[orientation].paddingTop,
        viewPort: {
            width: device.viewPort[orientation].width,
            height: device.viewPort[orientation].height
        }
    };
}

function _formatSkin(containers, dimensions) {
    var currentDeviceKey = devices.getCurrentDevice().id;
    var scaleFactor = dimensions.deviceWidth / dimensions.viewPort.width,
    scaleString = "scale(" + scaleFactor + ")";

	containers.device.div.style.width = (dimensions.deviceWidth + 4) + "px";
	containers.device.div.style.height = (dimensions.deviceHeight + 4) + "px";
    containers.viewport.div.style.width = dimensions.viewPort.width + "px";
    containers.viewport.div.style.height = dimensions.viewPort.height + "px";
    containers.viewport.div.style.padding = "0";

    jQuery('#viewport-container').css('-webkit-transform', scaleString);
    jQuery('#viewport-container').css('-webkit-transform-origin', 'left top');
}

function _setOrientation(layout) {
    _win.orientation = window.orientation = layout === "portrait" ? 0 : 90;
}

function _upDateHWKeyPanelPosition(orientation, scaleFactor) {
    var left = 0;

    if (orientation === 'portrait') {
        if (db.retrieve("layout") === "portrait") {
            left = 350 + $('#device-layout').width()*scaleFactor;
        } else {
            left = 470 + $('#device-layout').height()*scaleFactor;
        }
    } else {
        if (db.retrieve("layout") === "portrait") {
            left = 490 + $('#device-layout').height()*scaleFactor;
        } else {
            left = 350 + $('#device-layout').width()*scaleFactor;
        }
    }

    $("#hwkeys-panel").css("top", "40px");
    $("#hwkeys-panel").css("left", left+"px");
}

function _getTransformString(orientation, scaleFactor) {
    var transformString = "",
    offset;

    if (orientation === "landscape") {
        if (db.retrieve("layout") === "portrait") {
            offset = devices.getCurrentDevice().screen.height * scaleFactor + 170;
            transformString = "translate("+ offset + "px, 0px) rotate(90deg) scale("+ scaleFactor +")";
        } else {
            transformString = "translate(0px,0px) rotate(0deg) scale("+ scaleFactor +")";
        }
    } else {
        if (db.retrieve("layout") === "portrait") {
            transformString = "translate(0px,0px) rotate(0deg) scale("+ scaleFactor +")";
        } else {
            offset = devices.getCurrentDevice().screen.width * scaleFactor + 150;
            transformString = "translate("+ offset + "px, 0px) rotate(90deg) scale("+ scaleFactor +")";
        }
    }

    return transformString;
}


_self = {
    init: function (win, doc) {
        _win = win;
        _doc = doc;

        var layout = db.retrieve("layout") || "portrait";

        _setOrientation(layout);

        _win.onorientationchange = undefined;

        $(".middle").scroll(function () {
            if (this.scrollLeft > 0) {
                this.scrollLeft = 0;
            }
        });
    },
    // TODO: redo/refactor this in general, seems bloated, also devices REQUIRE viewport schemas which they shouldnt
    resize: function (device) {
        var layout = db.retrieve("layout"),
            orientation = "portrait",
            containers, dimensions;

        if (layout && layout === "landscape" && device.viewPort.landscape) {
            orientation = "landscape";
        }

        containers = _getContainers();
        _setContainers(containers, device, orientation);

        dimensions = _getDimensions(device, orientation);
        if (!device.skin) {
            _formatSkin(containers, dimensions);
        }

        event.trigger("ScreenChangeDimensions", [dimensions.viewPort.width, dimensions.viewPort.height]);
    },

    changeLayoutType: function (layoutType) {
        var orientation = db.retrieve("deviceOrientation") || "portrait";
        if (!_validateLayoutType(layoutType)) {
            exception.raise(exception.types.LayoutType, "unknown layout type requested!");
        }

        db.save("layout", layoutType);
        _self.resize(devices.getCurrentDevice());
        _self.rotateDevice(orientation);

        if (!_win) return;
        _setOrientation(layoutType);
    },

    scaleDevice: function (scaleFactor) {
        var orientation = db.retrieve("deviceOrientation") || "portrait",
        transformString = _getTransformString(orientation, scaleFactor);
        _upDateHWKeyPanelPosition(orientation, scaleFactor);
        db.save("deviceScaleFactor", scaleFactor);
        jQuery('#device-layout').css('-webkit-transform-origin', '0% 0%');
        jQuery('#device-layout').css('-webkit-transform',  transformString);
    },

    rotateDevice: function (orientation) {
        if (!_validateOrientation(orientation)) {
            exception.raise(exception.types.OrientationType, "unknown orientation type requested!");
        }

        db.save("deviceOrientation", orientation);
        jQuery('#device-layout').css('-webkit-transform-origin', '0% 0%');
        jQuery('#device-layout').css('-webkit-transform',
                _getTransformString(orientation, db.retrieve("deviceScaleFactor")));
        _upDateHWKeyPanelPosition(orientation, db.retrieve("deviceScaleFactor"))
        if (!_win) return;
        if (_win.onorientationchange) {
            _win.onorientationchange();
        }

        var evt = _doc.createEvent("Event");
        evt.initEvent("orientationchange", true, true);
        _win.dispatchEvent(evt);
    }
};

module.exports = _self;

});
define('ripple/sensorSettings', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 _PERSISTENCE_KEY = "sensorsettings",
    db = require('ripple/db'),
    platform = require('ripple/platform'),
    _currentSensorSettings = {},
    _self;

function _default(key) {
    var keys = key.split("."),
        defaults = platform.current().sensor;

    if (keys.length === 1)
        return defaults[key];

    return keys.length === 2 &&
           defaults[keys[0]] &&
           defaults[keys[0]][keys[1]] &&
           defaults[keys[0]][keys[1]].control ?
           defaults[keys[0]][keys[1]].control.value : undefined;
}

_self = {
    initialize: function () {
        _currentSensorSettings = db.retrieveObject(_PERSISTENCE_KEY) || {};
    },
    register: function (key, obj) {
        _currentSensorSettings[key] = obj;
    },

    persist: function (key, obj) {
        if (key) {
            _currentSensorSettings[key] = obj;
        }

        db.saveObject(_PERSISTENCE_KEY, _currentSensorSettings);
    },

    retrieve: function (key) {
        return _currentSensorSettings.hasOwnProperty(key) ?
               _currentSensorSettings[key] : _default(key);
    },

    retrieveAsInt: function (key) {
        return parseInt(_self.retrieve(key), 10);
    },

    retrieveAsBoolean: function (key) {
        return !!_self.retrieve(key);
    }
};

module.exports = _self;

});
define('ripple/touchEventEmulator', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 emulatorBridge = require('ripple/emulatorBridge'),
    utils = require('ripple/utils'),
    _isMouseDown, self;

// NOTE: missing view, detail, touches, targetTouches, scale and rotation
function _initTouchEvent(type, canBubble, cancelable, eventData) {
    var touchEvent = emulatorBridge.document().createEvent("Event");
    touchEvent.initEvent(type, canBubble, cancelable);
    utils.mixin(eventData, touchEvent);
    return touchEvent;
}

function _raiseTouchEvent(mouseEvent) {
    var type = "",
        simulatedEvent,
        touchObj,
        eventData;

    switch (mouseEvent.type) {
    case "mousedown":
        type = "touchstart";
        _isMouseDown = true;
        break;
    case "mousemove":
        if (!_isMouseDown) {
            return;
        }
        type = "touchmove";
        break;
    case "mouseup":
        type = "touchend";
        _isMouseDown = false;
        break;
    default:
        return;
    }

    touchObj = {
        clientX: mouseEvent.pageX,
        clientY: mouseEvent.pageY,
        identifier: "",
        pageX: mouseEvent.pageX,
        pageY: mouseEvent.pageY,
        screenX: mouseEvent.pageX,
        screenY: mouseEvent.pageY,
        target: mouseEvent.target
    };

    eventData = {
        altKey: mouseEvent.altKey,
        ctrlKey: mouseEvent.ctrlKey,
        shiftKey: mouseEvent.shiftKey,
        metaKey: mouseEvent.metaKey,
        changedTouches: [touchObj],
        targetTouches: [touchObj],
        touches: [touchObj]
    };

    utils.mixin(touchObj, eventData);

    simulatedEvent = _initTouchEvent(type, true, true, eventData);

    mouseEvent.target.dispatchEvent(simulatedEvent);

    if (typeof mouseEvent.target["on" + type] === "function") {
        mouseEvent.target["on" + type].apply(mouseEvent.target, [simulatedEvent]);
    }
}

function _marshalEvents(win, doc) {
    utils.forEach(["mousedown", "mousemove", "mouseup"],
        function (event) {
            win.addEventListener(event, _raiseTouchEvent, true);
        });

    //win.Node.prototype.ontouchstart = null;
    //win.Node.prototype.ontouchend = null;
    //win.Node.prototype.ontouchmove = null;
}

self = module.exports = {
    mask: function (win, doc) {
        _marshalEvents(win, doc);
    }
};

});

define('ripple/ui/plugins/HWKeys', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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 db = require('ripple/db'),
    event = require('ripple/event'),
    emulatorBridge = require('ripple/emulatorBridge'),
    devices = require('ripple/devices');

function initHWKey() {
    var left = 0,
	currentDeviceKey = devices.getCurrentDevice().id,
        orientation = db.retrieve('deviceOrientation'),
        scaleFactor = db.retrieve('deviceScaleFactor');

    if (orientation === 'portrait') {
        if (db.retrieve("layout") === "portrait") {
            left = 350 + $('#device-layout').width()*scaleFactor;
        } else {
            left = 470 + $('#device-layout').height()*scaleFactor;
        }
    } else {
        if (db.retrieve("layout") === "portrait") {
            left = 490 + $('#device-layout').height()*scaleFactor;
        } else {
            left = 350 + $('#device-layout').width()*scaleFactor;
        }
    }

    $("#hwkeys-panel").css("top", "40px");
    $("#hwkeys-panel").css("left", left+"px");
    $("#hwkeys-panel").draggable({ cursor: 'move', containment: [0, 52, 1480, 800]});

    jQuery("#hwkey-menu-btn").bind("click", function () {
        event.trigger("tizenhwkeyEvent", ["menu"], true);
    });
    jQuery("#hwkey-back-btn").bind("click", function () {
        event.trigger("tizenhwkeyEvent", ["back"], true);
    });
}

module.exports = {
    initialize: function () {
        initHWKey();
    }
};

});
define('ripple/ui/plugins/about-dialog', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 bus = require('ripple/bus');

module.exports = {
    initialize: function () {
        $("#about-dialog").dialog({
            resizable: false,
            draggable: false,
            modal: true,
            autoOpen: false,
            position: 'center',
            minWidth: '464',
            minHeight: '262'
        });
    },
    show: function () {
        //TODO: Restore this line once framework issue is resolved
        //var port =  window.stagewebview ? stagewebview.serverPort : "9900";
        var port = "9910";

        bus.send("version", null, function (resp) {
            $("#about-dialog-ripple-ui-version").html("(v" + resp + ")");
        });

        bus.ajax(
            "GET",
            "http://127.0.0.1:" + port + "/ripple/about",
            null,
            function (resp) {
                $("#about-dialog-ripple-build-deploy-version").html("(v" + resp.data.version + ")");
            },
            function (error) {
                var version = error.data;
                
                if (error.code === 0 || error.code === 404) {
                    version = "The service is not running";
                }
                $("#about-dialog-ripple-build-deploy-version").html("(" + version + ")");
            }
        );

        $("#about-dialog").dialog("open");
    }
};

});
define('ripple/ui/plugins/accelerometer', function (require, exports, module) {
/*
 * Copyright (c) 2010 Epic Train Hack
 * Copyright (c) 2011 Research In Motion Limited
 * Contributors: Wolfram Kriesing, Dan Silivestru, Brent Lintner
 *
 * 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 ui = require('ripple/ui'),
    goodVibrations = require('ripple/ui/plugins/goodVibrations'),
    accelerometer = require('ripple/accelerometer'),
    event = require('ripple/event'),
    Rotation = require('ripple/platform/w3c/1.0/Rotation'),
    Acceleration = require('ripple/platform/w3c/1.0/Acceleration'),
    _mouseDown,
    _shiftKeyDown,
    _offsets = {
        x: 0,
        y: 0,
        z: -9.81,
    },
    _oldX,
    _oldY,
    _oldAlphaX,
    _shape =
        //
        // The front side
        //
        // x, y, z      x, y, z         x, y, z
        // for some strange reason for y -100 is top, 100 is bottom
        "-30,30,10,     30,30,10,       30,60,10,       100,100,100,-1,0;" + // top left, top right, bottom right - of the right triangle
        "-30,30,10,     30,60,10,       -30,60,10,      100,100,100,-1,0;" + // top left, right bottom, left bottom - of the left triangle
        // front side "the phone display"
        "-20,-50,11,    20,-50,11,      20,20,11,       100,100,100,-1,0;" +
        "-20,-50,11,    20,20,11,       -20,20,11,      100,100,100,-1,0;" +
        // below the display
        "-30,30,10,     30,20,10,       30,30,10,       0,0,0,-1,0;" +
        "-30,30,10,     -30,20,10,      30,20,10,       0,0,0,-1,0;" +
        // above the display
        "-30,-60,10,    30,-60,10,      30,-50,10,      0,0,0,-1,0;" +
        "-30,-60,10,    30,-50,10,      -30,-50,10,     0,0,0,-1,0;" +
        // left of the display
        "-30,-50,10,    -20,-50,10,     -20,20,10,      0,0,0,-1,0;" +
        "-30,-50,10,    -20,20,10,      -30,20,10,      0,0,0,-1,0;" +
        // right of the display
        "20,-50,10,     30,-50,10,      30,20,10,       0,0,0,-1,0;" +
        "20,-50,10,     30,20,10,       20,20,10,       0,0,0,-1,0;" +


        // back side, opposite side to the above one
        "-30,-60,-10,   30,60,-10,      30,-60,-10,     0,0,0,-1,0;" +
        "-30,-60,-10,   -30,60,-10,     30,60,-10,      0,00,-1,0;" +
        // right side
        "30,-60,-10,    30,60,-10,      30,60,10,       50,50,80,-1,0;" +
        "30,-60,-10,    30,60,10,       30,-60,10,      50,50,80,-1,0;" +
        // left side
        "-30,-60,-10,   -30,60,10,      -30,60,-10,     50,50,80,-1,0;" +
        "-30,-60,-10,   -30,-60,10,     -30,60,10,      50,50,80,-1,0;" +

        // top
        "30,-60,-10,    -30,-60,10, -30,-60,-10,    50,80,50,-1,0;" +
        "30,-60,-10,    30,-60,10,      -30,-60,10, 50,80,50,-1,0;" +
        // bottom
        "30,60,-10, -30,60,-10,     -30,60,10,      80,50,50,-1,0;" +
        "30,60,-10, -30,60,10,      30,60,10,       80,50,50,-1,0";

function _shakeDevice() {
    window.setTimeout(goodVibrations.shakeDevice(8), 1);
    accelerometer.shake();
}

function _updateAccelerometerPanel(motion) {
    jQuery("#accelerometer-x").html(Math.round(motion.accelerationIncludingGravity.x * 100) / 100);
    jQuery("#accelerometer-y").html(Math.round(motion.accelerationIncludingGravity.y * 100) / 100);
    jQuery("#accelerometer-z").html(Math.round(motion.accelerationIncludingGravity.z * 100) / 100);
    jQuery("#accelerometer-alpha").html(Math.round(motion.orientation.alpha));
    jQuery("#accelerometer-beta").html(Math.round(motion.orientation.beta));
    jQuery("#accelerometer-gamma").html(Math.round(motion.orientation.gamma));
}

function _updateCanvas(a, b, g) {
    ThreeDee.loadMesh(_shape);
    g = g || 0;
    ThreeDee.rotate(0, g, 0);
    ThreeDee.rotate(b, 0, a);
    ThreeDee.backface();
    ThreeDee.shade();
    ThreeDee.zSort();
    Draw.initialize(document.querySelector("#accelerometer-canvas"));
    Draw.clear(0, 0, 480, 300);
    Draw.drawScene(ThreeDee.getTranslation(), 3);
}

function _createCanvas() {
    var node = document.querySelector("#accelerometer-canvas"),
        x = 0, y = 0, z = -9.81,
        alpha = 0, beta = 0, gamma = 0,
        cosX, sinX, cosY, sinY,
        deltaAlpha = 360;

    ThreeDee.setCenter(150, 100);
    ThreeDee.setLight(-300, -300, 800);

    node.addEventListener("mousemove", function (e) {
        if (!_mouseDown)
            return;

        if (!_shiftKeyDown) {
            _offsets.x = (_offsets.x + _oldX - e.offsetX) % 360;
            _offsets.y = (_offsets.y + _oldY - e.offsetY) % 360;

            alpha = alpha || 0;

            // enforce gamma in [-90,90] as per w3c spec
            gamma = -_offsets.x;
            if (gamma < -90) {
                gamma = -90;
            }
            if (gamma > 90) {
                gamma = 90;
            }

            // enforce beta in [-180,180] as per w3c spec
            beta = -_offsets.y % 360;
            if (beta < -180) {
                beta += 360;
            }
            else if (beta >= 180) {
                beta -= 360;
            }

            cosX = Math.cos((gamma) * (Math.PI / 180));
            sinX = Math.sin((gamma) * (Math.PI / 180));
            cosY = Math.cos((beta) * (Math.PI / 180));
            sinY = Math.sin((beta) * (Math.PI / 180));
            x = 9.81 * cosY * sinX;
            y = -9.81 * sinY;
            z = -9.81 * cosY * cosX;

        }
        else {
            deltaAlpha = (deltaAlpha - (_oldAlphaX - e.offsetX) * 2.5) % 360;
            alpha = (360 - deltaAlpha) % 360;
        }

        _oldX = e.offsetX;
        _oldY = e.offsetY;
        _oldAlphaX = e.offsetX;

        _updateCanvas(deltaAlpha, -beta, gamma);
        accelerometer.setInfo({
            x: x,
            y: y,
            z: z,
            alpha: alpha,
            beta: beta,
            gamma: gamma
        });

    });

    node.addEventListener("mousedown", function (e) {
        _oldX = e.offsetX;
        _oldY = e.offsetY;
        if (_shiftKeyDown) {
            _oldAlphaX = _oldX;
        }
        _mouseDown = true;
    });

    node.addEventListener("mouseup", function (e) {
        _mouseDown = false;
    });

    node.addEventListener("dblclick", function (e) {   
        x = 0;
        y = 0;
        z = -9.81;
        alpha = 0;
        beta = 0;
        gamma = 0;
        deltaAlpha = 360;
        _resetAccelerometer();
    });

    document.addEventListener("mouseup", function (e) {
        //Catch mouseup events that fire when outside canvas bounds
        _mouseDown = false;
    });

    document.addEventListener("keydown", function (e) {
        if (e.keyCode === 16) { // Shift Key            
            _shiftKeyDown = true;
        }
    });

    document.addEventListener("keyup", function (e) {
        if (e.keyCode === 16) { // Shift Key
            _shiftKeyDown = false;
        }
    });    
}

function _resetAccelerometer() {    
    _updateCanvas(0, 0);
    _oldX = 0;
    _oldY = 0;
    _oldAlphaX = 0;
    _offsets = {
        x: 0,
        y: 0,
        z: -9.81,
    };
    accelerometer.setInfo({
        acceleration: new Acceleration(0, 0, 0),
        accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
        rotationRate: new Rotation(0, 0, 0),
        orientation: new Rotation(0, 0, 0),
        timestamp: new Date().getTime()
    });
}

module.exports = {
    panel: {
        domId: "accelerometer-container",
        collapsed: true,
        pane: "left",
        titleName: "Accelerometer",
        display: true
    },
    initialize: function () {
        _createCanvas();
        
        _resetAccelerometer();

        _updateAccelerometerPanel(accelerometer.getInfo());

        jQuery("#accelerometer-shake").click(_shakeDevice);

        event.on("AccelerometerInfoChangedEvent", _updateAccelerometerPanel, this);
    }
};

});
define('ripple/ui/plugins/application', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    dbinit = require('ripple/platform/tizen/2.0/dbinit'),
    DB_APPLICATION_KEY = "tizen1-db-application",
    _data = {
        appList: {},
        installedAppList: {}
    },
    _appInstalledTemplate,
    _apps,
    _installedAppList;

function _get() {
    _data = db.retrieveObject(DB_APPLICATION_KEY);
    if (_data === undefined) {
        _data = {
            appList: _apps,
            installedAppList: _installedAppList
        };
    }
}

function _save() {
    db.saveObject(DB_APPLICATION_KEY, _data);
}

function _loadInstalledAppList() {
    var html = "";
    jQuery("#application-installed-box").empty();
    utils.forEach(_data.installedAppList, function (item) {
        html += _appInstalledTemplate.replace(/#Name/g, item.name)
            .replace(/#ID/g, item.id)
            .replace(/#IconPath/, item.iconPath)
            .replace(/#Version/, item.version)
            .replace(/#Show/, item.show)
            .replace(/#Categories/, item.categories.join("<br>"))
            .replace(/#InstallDate/, item.installDate)
            .replace(/#Size/, item.size)
            .replace(/#PackageID/, item.packageId)
            .replace(/#SharedURI/, item.sharedURI)
            .replace(/#Operation/, item.operation)
            .replace(/#URI/, item.appControl.uri)
            .replace(/#MIME/, item.appControl.mime)
            .replace(/#category/, item.appControl.category)
            .replace(/#Data/, item.appControl.data);
    });
    jQuery("#application-installed-box").accordion("destroy");
    jQuery("#application-installed-box").html(html).accordion({
        active: false,
        collapsible: true,
        autoHeight: false
    });
}

function _displayInfo(text) {
    var html = "<b>" + text + "</b>";
    document.getElementById("application-error").innerHTML = html;
}

function _programChanged(status, id) {
    event.trigger("programChanged", [status, id]);
}

function updateApp(id, updateFlag) {
    var item = _data.appList[id];
    if (!item) {
        return;
    }
    _data.installedAppList[id] = {
        id: item.id,
        name: item.name,
        iconPath: item.iconPath,
        version: item.version,
        show: item.show,
        categories: item.categories,
        installDate: new Date(),
        size: item.size,
        packageId: item.packageId,
        sharedURI: item.sharedURI,
        operation: item.operation,
        appControl: {
            uri: item.appControl.uri,
            mime: item.appControl.mime,
            category: item.appControl.category,
            data: item.appControl.data
        },
        type: item.type,
        value: item.value
    };
    _save();
    if (updateFlag) {
        _programChanged("updated", id);
    } else {
        _programChanged("installed", id);
    }
    _loadInstalledAppList();
}

function removeApp(id) {
    delete _data.installedAppList[id];
    _save();
    _programChanged("uninstalled", id);
    _loadInstalledAppList();
}

event.on("install-current-app", function (item) {
    _data.installedAppList[item.id] = {
        id: item.id,
        name: item.name,
        iconPath: item.iconPath,
        version: item.version,
        show: item.show,
        categories: item.categories,
        installDate: item.installDate,
        size: item.size,
        packageId: item.packageId,
        sharedURI: item.sharedURI,
        operation: item.operation,
        appControl: {
            uri: item.appControl.uri,
            mime: item.appControl.mime,
            category: item.appControl.category,
            data: item.appControl.data
        },
        type: item.type,
        value: item.value
    };
    _loadInstalledAppList();
});

event.on("appServiceReplied", function () {
    _displayInfo("The application has been launched successfully");
});

event.on("install-apps", function (ids) {
    utils.forEach(ids, function (id) {
        updateApp(id, false);
    });
});

event.on("update-apps", function (ids) {
    utils.forEach(ids, function (id) {
        updateApp(id, true);
    });
});

event.on("remove-apps", function (ids) {
    utils.forEach(ids, function (id) {
        removeApp(id);
    });
});

module.exports = {
    initialize: function () {
        _apps = dbinit.Application.apps;
        _installedAppList = dbinit.Application.installedAppList;
        _appInstalledTemplate = jQuery("#application-installed-template").html();
        _get();
        _save();
        _loadInstalledAppList();
    }
};

});
define('ripple/ui/plugins/audioPlayer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    constants = require('ripple/constants'),
    audioObj = document.getElementById("multimedia-audio"),
    audioProgress = document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_PROGRESS_ID);

module.exports = {
    initialize: function () {
        var audioObj = document.getElementById("multimedia-audio"),
            audioProgress = document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_PROGRESS_ID);

        if (audioObj) {
            event.on("MultimediaVolumeChanged", function (volume) {
                audioObj.volume = parseFloat(volume / 10);
            });

            audioObj.addEventListener("timeupdate", function () {
                var s = parseInt(audioObj.currentTime % 60, 10),
                    m = parseInt((audioObj.currentTime / 60) % 60, 10);

                audioProgress.innerText = ((m > 9) ? m  : "0" + m) + ':' + ((s > 9) ? s  : "0" + s);
            }, false);

            event.on("MultimediaAudioStateChanged", function (state) {
                document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_STATE_FIELD_ID).innerText = state;
                document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_FILE_FIELD_ID).innerText = audioObj.getAttribute("src");
            });
        }
    }
};

});
define('ripple/ui/plugins/build', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 tooltip = require('ripple/ui/plugins/tooltip'),
    settings = require('ripple/ui/plugins/settings-dialog'),
    bus = require('ripple/bus');

function handleBuild() {
    var node = $(this),
        action = node.attr('id').split("-")[2];

    if (node.hasClass("not-ready")) {
        return;
    }

    if (!settings.can(action)) {
        settings.show(action);
    }
    else {
        settings.perform(action);
    }
}

function areServicesRunning(success, fail) {
    bus.ajax(
        "GET",
        "http://127.0.0.1:9910/ripple/about",
        null,
        function () {
            success();
        },
        function (error) {
            fail();
        }
    );
}

function manageServices(action, callBack) {
    bus.send("services", action, function () {
        if (typeof callBack === "function") {
            callBack();
        }
    });
}

module.exports = {
    panel: {
        domId: "build-container",
        collapsed: true,
        pane: "right"
    },

    initialize: function () {
        $("#options-menu-build").click(handleBuild);
        $("#options-menu-sign").click(handleBuild);
        $("#options-menu-launch").click(handleBuild);

        $('#options-menu-start-service').click(function () {
            manageServices("start", function (result) {
                $('#options-menu-services-stop').show();
                $('#options-menu-services-start').hide();
            });
        });

        $('#options-menu-stop-service').click(function () {
            manageServices("stop", function (result) {
                $('#options-menu-services-stop').hide();
                $('#options-menu-services-start').show();
            });
        });

        $("#options-menu-settings").click(function () {
            settings.show(); 
        });

        if (settings.value("remoteInspector")) {
            $("#options-menu-build-warning").show();
            tooltip.create("#options-menu-build-warning", "Remote Web Inspector should be disabled when packaging for App World release");
        }

        areServicesRunning(
            function () {
                $('#options-menu-services-stop').show();
                $('#options-menu-services-start').hide();
            }, 
            function () {
                $('#options-menu-services-stop').hide();
                $('#options-menu-services-start').show();
            }
        );
    }
};

});
define('ripple/ui/plugins/call', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    _exception = {
        "unknown":           "Unknown",
        "network":           "Network",
        "unreachable":       "Unreachable",
        "no-answer":         "No Answer",
        "bad-number":        "Bad Number",
        "number-not-in-use": "Number Not In Use",
        "media":             "Media",
        "no-sim":            "No Sim Card",
        "account-down":      "Account Down",
        "credit-down":       "Credit Down",
        "barred":            "Barred",
        "network-busy":      "Network Busy",
        "network-down":      "Network Down"
    },
    _status = {
        IDLE:       0,
        DIALED:     1,
        PLACED:     2,
        INPROGRESS: 3,
    },
    _statusInfo = [
        "Waiting...;Waiting",                                   // IDLE
        "Calling... ;Incomming call from simulator",               // DIALED
        "Incomming call from ;Calling simulator",                // PLACED
        "In conversation with ;In conversation with simulator"   // INPROGRESS
    ],
    _data = {
        status: _status.IDLE,
        isInException: false,
        isAutoAccept: false,
        autoAcceptTimerId: null,
        conversationStartTime: null
    },
    _contactMap = {
        "861012345678": "Guest"
    },
    _CONTACT_KEY = "tizen1-contact",
    _RECORDING_KEY = "tizen1-call-recording",
    _RECORDING_PATH = "music/",
    _record = {},
    _conversationSeconds = 0,
    _conversationTimer,
    _callingEffectTimer;

function _initContacts() {
    var data = db.retrieveObject(_CONTACT_KEY),
        contactsSelect = document.getElementById("call-local-phone-number"),
        displayName = null, number = null, index = 0, i;
        
    contactsSelect.innerHTML = "";

    utils.forEach(data, function (addrBook) {
        utils.forEach(addrBook._contacts, function (contact) {
            if (contact.name && contact.name && contact.phoneNumbers &&
                contact.phoneNumbers.length > 0) {
                displayName = contact.name.firstName + ' ' + contact.name.lastName;
                number = contact.phoneNumbers[0].number;
                _contactMap[number] = displayName;

                contactsSelect.appendChild(utils.createElement("option", {
                    "innerText": displayName + ':' + number,
                    "value": index
                }));
                index++;
            }
        });
    });

    if (displayName === null && number === null) {
        for (i in _contactMap) {
            displayName = _contactMap[i];
            number = i;
            contactsSelect.appendChild(utils.createElement("option", {
                "innerText": displayName + ':' + number,
                "value": index
            }));
        }
    }
}

function _initEventWatchers() {
    event.on("DialerLaunched", function (remoteParty) {
        var localContact = document.getElementById("call-local-phone-number");

        if (_data.status !== _status.IDLE) {
            return;
        }

        localContact.appendChild(utils.createElement("option", {
            "innerText": remoteParty.displayName,
            "value": remoteParty.remoteParty,
            "selected": "selected"
        }));
        _localCall();
    });
}

function _initExceptionTypes() {
    utils.forEach(_exception, function (value, key) {
        document.getElementById("call-exception-type").appendChild(utils.createElement("option", {
            "innerText": value,
            "value": key
        }));
    });
}

function _initRecord() {
    var localPartString = jQuery("#call-local-phone-number option:selected").text() || "",
        localPartStringList = localPartString.split(":"),
        displayName;

    if (localPartStringList.length > 1) {
        displayName = localPartStringList[0];
    }
    else {
        displayName = localPartString;
    }

    _record = {};
    _record.serviceId = (new Date()).getTime() || 0;
    _record.callParticipants = [{
        id: localPartString + ':' + displayName,
        displayName: displayName,
        contactRef: null
    }];
    _record.forwardedFrom = null;
    _record.startTime = new Date();
    _record.recording = [];
}


function updateConvTime() {
    var timeObj = new Date(1970, 0, 1),
    timeString;

    timeObj.setSeconds(_conversationSeconds);
    timeString = timeObj.toTimeString().substr(0, 8);
    jQuery("#ConvTimeString").text(timeString);
    jQuery("#ConvTimeString2").text(timeString);
    _conversationSeconds = _conversationSeconds + 1;
}


function CallingEffect() {
    var color = jQuery("#callingString").css('color');
    if (color === "rgb(255, 255, 255)") {
        jQuery("#callingString").css('color', "black");
        jQuery("#callingString2").css('color', "black");
    }
    else {
        jQuery("#callingString").css('color', "white");
        jQuery("#callingString2").css('color', "white");
    }
}


function _transferStatus() {
    var statusStringList = _statusInfo[_data.status].split(";"),
        localPartString = jQuery("#call-local-phone-number option:selected").text() || "",
        localPartStringList = localPartString.split(":"),
        localNumber = localPartStringList[0],
        localName = _contactMap[localNumber] || localNumber;
    jQuery("#status-text").show();
    jQuery("#remote-status-text").show();
    jQuery("#call-status").show();
    jQuery("#remote-call-status").show();
    jQuery("#remotePartyName").html(localName);
    jQuery("#call-local-call").show();
    window.clearInterval(_callingEffectTimer);

    switch (_data.status) {
    case _status.DIALED:      // local call
        jQuery("#call-remote-text").html("Accept");
        jQuery("#end-remote-text").html("Reject");
        jQuery("#call-status").html("<span style='font-size: 22px;'>" + localName + "</span><br>" + 
                        "<span id='callingString' style='font-size: 14px;'>&nbsp;" + statusStringList[0] + 
                        "</span><br><br><br><button id='call-local-end-d' class='ui-corner-all' style='padding:2px;" +
                        " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
        jQuery("#call-local-end-d").bind("click", _localEnd);
        jQuery("#remote-call-status").html("<span style='font-size: 20px;'>Simulator Bot</span><br>" + 
                        "<span id='callingString2' style='font-size: 12px;'>&nbsp;Incoming call...</span>" +
                        "<br><br><br><button id='call-remote-decline-d' class='ui-corner-all' style='padding:2px;" +
                        " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:48%;'>Decline</button>&nbsp;&nbsp;" +
                        "<button id='call-remote-answer-d' class='ui-corner-all' style='padding:2px; border-width:1px; background-color:green; color:white; font-size:14px; font-weight:bold; width:48%;'>Answer</button>");
        jQuery("#call-remote-answer-d").bind("click", _remoteCall);
        jQuery("#call-remote-decline-d").bind("click", _remoteEnd);
        _callingEffectTimer = window.setInterval(CallingEffect, 800);
        break;
    case _status.PLACED:      // Remote Call
        jQuery("#call-local-text").html("Accept");
        jQuery("#end-local-text").html("Reject");
        jQuery("#call-status").html(statusStringList[0] + localName);
        jQuery("#remote-call-status").html(statusStringList[1]);
        jQuery("#remote-call-status").html("<span style='font-size: 22px;'>Simulator Bot</span><br>" + 
                        "<span id='callingString' style='font-size: 14px;'>&nbsp;Calling..." + 
                        "</span><br><br><br><button id='call-remote-end-d' class='ui-corner-all' style='padding:2px;" +
                        " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
        jQuery("#call-remote-end-d").bind("click", _remoteEnd);
        jQuery("#call-status").html("<span style='font-size: 22px;'>" + localName + "</span><br>" + 
                        "<span id='callingString2' style='font-size: 14px;'>&nbsp;Incoming call...</span>" +
                        "<br><br><br><button id='call-local-decline-d' class='ui-corner-all' style='padding:2px;" +
                        " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:48%;'>Decline</button>&nbsp;&nbsp;" +
                        "<button id='call-local-answer-d' class='ui-corner-all' style='padding:2px; border-width:1px;" +
                        " background-color:green; color:white; font-size:14px; font-weight:bold; width:48%;'>Answer</button>");
        jQuery("#call-local-answer-d").bind("click", _localCall);
        jQuery("#call-local-decline-d").bind("click", _localEnd);
        _callingEffectTimer = window.setInterval(CallingEffect, 800);
        break;
    case _status.INPROGRESS:
        jQuery("#call-status").html("<span style='font-size: 22px;'>" + localName + "</span><br>" + 
                        "<span id='ConvTimeString' style='font-size: 14px;'>" + "00:00:00" + 
                        "</span><br><br><br><button id='call-local-end-d-c' class='ui-corner-all' style='padding:2px;" +
                        " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
        jQuery("#remote-call-status").html("<span style='font-size: 22px;'>Simulator Robot</span><br>" + 
                        "<span id='ConvTimeString2' style='font-size: 14px;'>" + "00:00:00" + 
                        "</span><br><br><br><button id='call-remote-end-d-c' class='ui-corner-all' style='padding:2px;" +
                        " border-width:1px; background-color:red; color:white; font-size:14px; font-weight:bold; width:100%;'>End call</button>");
        jQuery("#call-local-end-d-c").bind("click", _localEnd);
        jQuery("#call-remote-end-d-c").bind("click", _remoteEnd);
        _conversationTimer = window.setInterval(updateConvTime, 1000);
        jQuery("#call-remote-text").html("Call");
        jQuery("#end-remote-text").html("End");
        jQuery("#call-local-text").html("Call");
        jQuery("#end-local-text").html("End");
        break;
    default:
        jQuery("#call-status").html(statusStringList[0]);
        jQuery("#call-status").html("default");
        jQuery("#remote-call-status").html(statusStringList[1]);
        jQuery("#remote-call-status").html("default");
        jQuery("#call-remote-text").html("Call");
        jQuery("#end-remote-text").html("End");
        jQuery("#call-local-text").html("Call");
        jQuery("#end-local-text").html("End");
        return;
    }
}

function _startCall() {
    _data.conversationStartTime = new Date();
    event.trigger("CallInProgress", [true]);
    _data.status = _status.INPROGRESS;
    //_transferStatus();
}

function _endCall(callEndReason) {
    if (_data.autoAcceptTimerId) {
        var path = _RECORDING_PATH + _record.serviceId + ".mp3";

        _record.recording.push(path);
        db.saveObject(_RECORDING_KEY, path);

        clearTimeout(_data.autoAcceptTimerId);
        _data.autoAcceptTimerId = null;
    }

    _record.duration = _data.conversationStartTime ? ((new Date()) - _data.conversationStartTime) : 0;
    _data.conversationStartTime = null;
    
    _record.endReason = callEndReason;

    if (_data.status === _status.PLACED) {
        _record.direction = "missed-new";
    }

    event.trigger("CallRecorded", [_record]);
    event.trigger("CallInProgress", [false]);

    _data.status = _status.IDLE;
    _transferStatus();
    _record = {};

    _conversationSeconds = 0;
    window.clearInterval(_conversationTimer);
    jQuery("#call-status").hide();
    jQuery("#remote-call-status").hide();

    jQuery("#status-text").hide();
    jQuery("#remote-status-text").hide();
}

function _localCall() {
    if (_data.isInException) {
        return;
    }

    switch (_data.status) {
    case _status.IDLE:    //local call
        _data.status = _status.DIALED;
        _initRecord();
        _record.direction = "dialed";
        break;
    case _status.PLACED:
        _data.status = _status.INPROGRESS;
        _record.direction = "received";
        if (_data.autoAcceptTimerId) {
            clearTimeout(_data.autoAcceptTimerId);
            _data.autoAcceptTimerId = null;
        }
        _startCall();
        break;
    default:
        return;
    }

    _transferStatus();

    if (_data.isInException) {
        _endCall(document.getElementById("call-exception-type").value);
    }
}

function _localEnd() {
    switch (_data.status) {
    case _status.DIALED:     // Local Cancel
    case _status.INPROGRESS: // Local End
        _endCall("local");
        break;
    case _status.PLACED:
        _record.direction = "missed-new";
        _endCall("local");
        break;
    default:
        return;
    }
}

function _remoteCall() {
    if (_data.isInException) {
        return;
    }

    switch (_data.status) {
    case _status.IDLE:      // Remote Call
        _data.status = _status.PLACED; 
        _initRecord();
        if (_data.isAutoAccept) {
            _data.autoAcceptTimerId = setTimeout(_localCall, 2000);
        }
        break;
    case _status.DIALED:    // Remote Answer
        _startCall();
        break;
    default:
        return;
    }

    _transferStatus();

    if (_data.isInException) {
        _endCall(document.getElementById("call-exception-type").value);
    }
}

function _remoteEnd() {
    switch (_data.status) {
    case _status.DIALED:     // Remote Reject
        _endCall("rejected");
        break;
    case _status.INPROGRESS: // Remote End
        _endCall("remote");
        break;
    case _status.PLACED:    // Remote Cancel
        _record.direction = "missed-new";
        _endCall("remote");
        break;
    default:
        return;
    }
}

function _leaveMessage() {
    if (!this.checked && _data.autoAcceptTimerId) {
        clearTimeout(_data.autoAcceptTimerId);
        _data.autoAcceptTimerId = null;
    }
    _data.isAutoAccept = this.checked;
}

function _exceptionStatus() {
    _data.isInException = this.checked;
    if (_data.isInException && (_data.status !== _status.IDLE)) {
        if (_data.status === _status.RECEIVED) {   // Remote Cancel
            _record.direction = "missed-new";
            _record.duration = 0;
        }
        _endCall(document.getElementById("call-exception-type").value);
    }
}


function _updateRemotePartyName() {
    jQuery("#remotePartyName").text(jQuery("#call-local-phone-number option:selected").text());
}


module.exports = {
    panel: {
        domId: "call-container",
        collapsed: true,
        pane: "left",
        titleName: "Call",
        display: true
    },
    initialize: function () {
        jQuery("#call-local-call").bind("click", _localCall);
        jQuery("#call-local-end").bind("click", _localEnd);
        jQuery("#call-remote-call").bind("click", _remoteCall);
        jQuery("#call-remote-end").bind("click", _remoteEnd);
        jQuery("#recording-status").bind("click", _leaveMessage);
        jQuery("#call-exception-status").bind("click", _exceptionStatus);
        jQuery("#call-exception-type").bind("click", null);

        _initEventWatchers();
        _initContacts();
        jQuery("#remotePartyName").text(jQuery("#call-local-phone-number option:selected").text());
        jQuery("#call-local-phone-number").bind("change", _updateRemotePartyName);
        _initExceptionTypes();
    }
};

});
define('ripple/ui/plugins/camera', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 ui = require('ripple/ui'),
    event = require('ripple/event'),
    video = document.getElementById('camera-video'),
    upload = document.getElementById('picture-upload'),
    select = document.getElementById('select-file'),
    take = document.getElementById('take-file'),
    pic = document.getElementById("camera-image");


select.addEventListener('click', function () {
    upload.click();
});

upload.addEventListener('change', function () {
    pic.src = window.webkitURL.createObjectURL(upload.files[0]);
    take.style.display = "inline";
});

take.addEventListener('click', function () {
    console.log("captured-image: " + pic.src);
    event.trigger('captured-image', [pic.src, upload.files[0]]);
    module.exports.hide();
});

module.exports = {
    show: function () {
        ui.showOverlay("camera-window");
        if (pic.src) {
            take.style.display = "inline";
        }
        else {
            take.style.display = "none";
        }
    },
    hide: function () {
        ui.hideOverlay("camera-window");
    }
};

});
define('ripple/ui/plugins/communication', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 ui = require('ripple/ui'),
    event = require('ripple/event'),
    deviceSettings = require('ripple/deviceSettings'),
    db = require('ripple/db'),
    utils = require('ripple/utils'),
    _messageType = {
        sms: "SMS",
        mms: "MMS",
        email: "E-mail"
    },
    _attachments = [],
/*
    _exception = {
        "":                  "Connection Issue",
        "unknown":           "Unknown",
        "network":           "Network",
        "unreachable":       "Unreachable",
        "no-answer":         "No Answer",
        "bad-number":        "Bad Number",
        "number-not-in-use": "Number Not In Use",
        "media":             "Media",
        "no-sim":            "No Sim Card",
        "account-down":      "Account Down",
        "credit-down":       "Credit Down",
        "barred":            "Barred",
        "network-busy":      "Network Busy",
        "network-down":      "Network Down"
    },
*/
    _status = {
        IDLE:       0,
        DIALED:     1,
        INPROGRESS: 2,
    },
    _data = {
        status: _status.IDLE,
//        isInException: false,
        conversationStartTime: null
    },
    _contactNameArr = [],
    _contactNumArr = [],
    _CONTACT_KEY = "tizen1-contact",
    _record = {},
    _conversationSeconds = 0,
    _conversationTimer,
    _msgTimer,
    _audioPlayersStatus = [];

function _showMsg() {
    var messageName = jQuery("#communication-senderName").val(),
        messageContent = jQuery("#communication-messageContent").val(),
        disMsgName = jQuery(".communication-messageContainer tr:first-child td"),
        disMsgContent = jQuery(".communication-messageContainer tr:nth-child(2) td textarea");

    ui.showOverlay("communication-window");

    disMsgName.text(messageName ? messageName : "Unknown name");
    disMsgContent.val(messageContent ? messageContent : "");

    jQuery("#communication-viewport").css("height", jQuery("#viewport-container").css("height"))
                                     .show("slide", {direction: "up"}, "fast");
    jQuery(".communication-callContainer").hide();
    jQuery(".communication-messageContainer").show();
}

function _msgEventInitialize() {
    jQuery("#communication-messageRadioStatus").hide();
    jQuery("#communication-sendMessage").unbind("click").click(function () {
        var messageItem,
            number = jQuery("#communication-senderName").val(),
            text = jQuery("#communication-messageContent").val(),
            type = jQuery("#communication-msgType").val(),
            message = {
                type: type,
                body: text,
                from: number,
                time: new Date(),
                attachments: _attachments
            };

        if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === false &&
            (type === 'sms' || type === 'mms')) {
            jQuery("#communication-messageRadioStatus").html('cellular radio is off<br \>Turn it on from Network Management Panel.');
            jQuery("#communication-messageRadioStatus").show();
            setTimeout(function () {
                jQuery("#communication-messageRadioStatus").hide();
            }, 3000);
            return;
        }
        if (deviceSettings.retrieve("WIFI_NETWORK.status") === false &&
            type === 'email') {
            jQuery("#communication-messageRadioStatus").html('wifi radio is off<br \>Turn it on from Network Management Panel.');
            jQuery("#communication-messageRadioStatus").show();
            setTimeout(function () {
                jQuery("#communication-messageRadioStatus").hide();
            }, 3000);
            return;
        }

        event.trigger("MessageReceived", [message]);
        _attachments = [];
        event.trigger("CommWinShow", [true]);
        _showMsg();

        jQuery(".communication-messageContainer textarea").attr("disabled", "disabled");
        jQuery("#communication-messageOut td:nth-child(3)").text(jQuery("#communication-messageContent").val());
        messageItem = jQuery("#communication-messageOut").html();
        jQuery("#communication-messageDisplay").append(messageItem);

        clearTimeout(_msgTimer);
        _msgTimer = setTimeout(function () {
            if (_data.status === _status.IDLE) {
                ui.hideOverlay("communication-window");
                event.trigger("CommWinShow", [false]);
            } else {
                _showCall();
            }
        }, 5000);
    });

    jQuery("#communication-clearMessage").unbind("click").click(function () {
            jQuery("#communication-messageDisplay").empty();
        });

    event.on("LayoutChanged", function () {
        jQuery("#communication-viewport").css("height", jQuery("#viewport-container").css("height"));

    });
    event.on("OutsideMessageReceived", function (message) {
        var i = 0,
            recipients = [],
            recipientsStatus = {},
            messageItem;

        recipientsStatus.id = message.id;
        recipientsStatus.msg = message.msg;
        for (i in message.to) {
            recipientsStatus[message.to[i]] = true;
            recipients.push(message.to[i]);
        }
        for (i in message.cc) {
            recipientsStatus[message.cc[i]] = true;
            recipients.push(message.cc[i]);
        }
        for (i in message.bcc) {
            recipientsStatus[message.bcc[i]] = true;
            recipients.push(message.bcc[i]);
        }

        event.trigger("MessageSent", [recipientsStatus]);
        jQuery("#communication-messageIn td:nth-child(1)").text(message.body);
        messageItem = jQuery("#communication-messageIn").html();
        jQuery("#communication-messageDisplay").append(messageItem);
    });

    jQuery("#communication-ok").unbind("click").click(function () {
        if (_data.status === _status.IDLE) {
            ui.hideOverlay("communication-window");
            event.trigger("CommWinShow", [false]);
        } else {
            _showCall();
        }
        clearTimeout(_msgTimer);
    });
}

function _msgInitialize() {
    _msgEventInitialize();

    utils.forEach(_messageType, function (msgTypeText, msgType) {
        var typeNode = utils.createElement("option", {
                "innerText": msgTypeText,
                "value": msgType
            });

        jQuery("#communication-msgType").append(typeNode);
    });
}

function pauseAllAudioPlayer() {
    var audios = $("#document").contents().find("audio"),
        index;
    for (var index = 0; index < audios.length; index++) {
        if (audios[index].paused) {
            _audioPlayersStatus[index] = 0;
        }
        else {
            _audioPlayersStatus[index] = 1;
            audios[index].pause();
        }
    }
}

function playAllAudioPlayer() {
    var audios = $("#document").contents().find("audio"),
        index;
    for (var index = 0; index < audios.length; index++) {
        if (_audioPlayersStatus[index] === 1) {
            audios[index].play();
        }
    }
    _audioPlayersStatus = [];
}

function _showCall() {
    var callName = jQuery("#communication-callerName").val(),
        callNum = jQuery("#communication-callNum").val(),
        disCallName = jQuery(".communication-callContainer tr:first-child td"),
        disCallNum = jQuery(".communication-callContainer tr:nth-child(2) td");

    ui.showOverlay("communication-window");
    event.trigger("CommWinShow", [true]);

    disCallName.text(callName ? callName : "Unknown Name");
    disCallNum.text(callNum ? callNum : "Unknown Number");

    jQuery("#communication-viewport").css("height", jQuery("#viewport-container").css("height"))
                                     .show("slide", {direction: "up"}, "fast");
    jQuery(".communication-callContainer").show();
    jQuery(".communication-messageContainer").hide();
    pauseAllAudioPlayer();
}

function _initRecord() {
    var callerName = jQuery("#communication-callerName").val(),
        callerNum = jQuery("#communication-callNum").val(),
        displayName = callerName ? callerName : "Unknown",
        displayNum = callerNum ? callerNum : "Unknown";

    _record = {};
    _record.type = "TEL";
    if ($("#is-videoCall").prop("checked") === true) {
        _record.features = ["CALL", "VIDEOCALL"];
    } else {
        _record.features = ["CALL", "VOICECALL"];
    }
    _record.remoteParties = [{
        remoteParty: displayNum,
        personId: displayName,
    }];
    _record.startTime = new Date();
}

function _endCall(callEndReason) {
    _record.duration = _data.conversationStartTime ? _conversationSeconds : 0;

    _data.conversationStartTime = null;

    switch (callEndReason) {
    case 'rejected':
        _record.direction = "REJECTED";
        break;
    case 'remote':
        _record.direction = "RECEIVED";
        break;
    case 'local':
        _record.direction = "MISSEDNEW";
        break; 
    }

    event.trigger("CallRecorded", [_record]);
    event.trigger("CallInProgress", [false]);

    _data.status = _status.IDLE;
    _record = {};

    _conversationSeconds = 0;
    window.clearInterval(_conversationTimer);
    ui.hideOverlay("communication-window");
    event.trigger("CommWinShow", [false]);
    playAllAudioPlayer();
}

function _callEventInitialize() {
    jQuery("#communication-cellularStatus").hide();
    jQuery("#communication-callStart").unbind('click').click(
        function () {
            if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === false) {
                jQuery("#communication-cellularStatus").show();
                setTimeout(function () {
                    jQuery("#communication-cellularStatus").hide();
                }, 3000);

                return;
            }
            if (_data.status === _status.IDLE) {
                _data.status = _status.DIALED;
                _initRecord();
                _showCall();
                jQuery("#callSettings tr:last-child td").text("Calling...");
                jQuery("#communication-callStart > span").text("End Call");
                jQuery("#callSettings input").attr("disabled", "disabled");
            } else {
                _endCall("local");

                jQuery("#callSettings tr:last-child td").text("");
                jQuery("#communication-callStart > span").text("Call");
                jQuery(".communication-callContainer tr:nth-child(3)").show();
                jQuery(".communication-callContainer tr:last-child").hide();
                jQuery("#callSettings input").removeAttr("disabled");
            }

        }
    );

    event.on("ApplicationLoad", function () {
        switch (_data.status) {
        case _status.INPROGRESS:
            jQuery("#communication-callStart").click();
            break;
        case _status.DIALED:
            jQuery("#communication-ignore").click();
            break;
        default:
            break;
        }
    });

    jQuery("#communication-ignore").unbind('click').click(function () {
        _endCall("rejected");

        jQuery("#callSettings tr:last-child td").text("");
        jQuery("#communication-callStart > span").text("Call");
        jQuery("#communication-callStart").removeData();
        jQuery("#callSettings input").removeAttr("disabled");
    });

    jQuery("#communication-answer").unbind('click').click(function () {
        _data.conversationStartTime = new Date();
        event.trigger("CallInProgress", [true]);
        _data.status = _status.INPROGRESS;

        _conversationTimer = setInterval(function () {
            var timeObj = new Date(1970, 0, 1),
                timeString;

            timeObj.setSeconds(_conversationSeconds);
            timeString = timeObj.toTimeString().substr(0, 8);
            jQuery("#callSettings tr:last-child td").text(timeString);
            _conversationSeconds = _conversationSeconds + 1;
        }, 1000);

        jQuery(".communication-callContainer tr:nth-child(3)").hide();
        jQuery(".communication-callContainer tr:last-child").show();
    });

    jQuery("#communication-end").unbind('click').click(function () {
        _endCall("remote");

        jQuery("#callSettings tr:last-child td").text("");
        jQuery("#communication-callStart > span").text("Call");
        jQuery("#communication-callStart").removeData();
        jQuery(".communication-callContainer tr:nth-child(3)").show();
        jQuery(".communication-callContainer tr:last-child").hide();
        jQuery("#callSettings input").removeAttr("disabled");
    });
/*
    jQuery("#communication-callEndReason").unbind("change").change(function () {
        if (!jQuery("#communication-callEndReason").val()) {
            _data.isInException = false;
        } else {
            _data.isInException = true;
            if (_data.isInException && (_data.status !== _status.IDLE)) {
                _endCall(jQuery("#communication-callEndReason").val());
            }
        }

        jQuery("#callSettings tr:last-child td").text("");
        jQuery("#communication-callStart > span").text("Call");
        jQuery("#communication-callStart").removeData();
        jQuery(".communication-callContainer tr:nth-child(3)").show();
        jQuery(".communication-callContainer tr:last-child").hide();
        jQuery("#callSettings input").removeAttr("disabled");
    });
*/
}

function _contactInitialize() {
    var data = db.retrieveObject(_CONTACT_KEY),
        displayName = null, number = null, index = 0;

    _contactNameArr = [];
    _contactNumArr = [];

    utils.forEach(data, function (addrBook) {
        utils.forEach(addrBook._contacts, function (contact) {
            if (contact.name && contact.name && contact.phoneNumbers && contact.phoneNumbers.length > 0) {
                displayName = contact.name.firstName + ' ' + contact.name.lastName;
                number = contact.phoneNumbers[0].number;
                _contactNameArr.push(displayName);
                _contactNumArr[displayName] = number;
                index++;
            }
        });
    });

    jQuery("#communication-callerName").autocomplete({
        source: _contactNameArr,
        select: function (event, ui) {
            jQuery("#communication-callNum").val(_contactNumArr[ui.item.value]);
        }
    });
    jQuery("#communication-senderName").autocomplete({
        source: _contactNameArr
    });
}

function _callInitialize() {
    _callEventInitialize();

    _contactInitialize();
/*
    utils.forEach(_exception, function (value, key) {
        var typeNode = utils.createElement("option", {
                "innerText": value,
                "value": key
            });

        jQuery("#communication-callEndReason").append(typeNode);
    });
*/
}

function _pushEventInitialize() {
    function register(appService) {
        appService.registrationId = Math.uuid(null, 16);

        window.setTimeout(function () {
            var appLabel;

            if ($("#communication-push-" + appService.appId).length !== 0) {
                $("#" + appService.appId).click();
                $("#communication-push-status-" + appService.appId).html("||");
                $("#communication-push-status-" + appService.appId).css("color", "#ff0000");

                return;
            }

            if (!$("#communication-push-app > tbody").html()) {
                $("#communication-push-header").show();
                $("#communication-push-submit").removeAttr("disabled");
            }

            appLabel = appService.appControl.uri || appService.appId;

            $("#communication-push-app").append(
                "<tr id='communication-push-" + appService.appId + "'>" +
                "<td style='width: 90%'><input type='radio' name='communication-push-list' id='" +
                appService.appId + "' style='margin: 5px' checked='checked' />" +
                "<label for='" + appService.appId + "'>" + appLabel + "</label></td>" +
                "<td id='communication-push-status-" + appService.appId + "'>||</td>" +
                "</tr>");

            $("label[for='" + appService.appId + "']").css({
                "display": "inline-block",
                "width": "220px",
                "white-space": "nowrap",
                "overflow": "hidden",
                "text-overflow": "ellipsis"
            });

            $("#communication-push-status-" + appService.appId).css({
                "width": "10%",
                "color": "#ff0000",
                "text-align": "center",
                "font-weight": "bold",
                "font-size": "14px"
            });

            $("#communication-push-app tr:even").css("background-color", "white");
            $("#communication-push-app tr:odd").css("background-color", "whitesmoke");
        }, 1);
    }

    function unregister(appId) {
        if ($("#communication-push-" + appId).length === 0)
            return;

        $("tr[id='communication-push-" + appId + "']").remove();

        if (!$("#communication-push-app > tbody").html()) {
            $("#communication-push-header").hide();
            $("#communication-push-submit").attr("disabled", "disabled");

            return;
        }

        if ($("input[name='communication-push-list']:checked").length === 0) {
            $("#communication-push-app input:first").click();
        }

        $("#communication-push-app tr:even").css("background-color", "white");
        $("#communication-push-app tr:odd").css("background-color", "whitesmoke");
    }

    function connect(appId) {
        $("#communication-push-status-" + appId).html("<=>");
        $("#communication-push-status-" + appId).css("color", "#32cd32");
    }

    function disconnect(appId) {
        $("#communication-push-status-" + appId).html("||");
        $("#communication-push-status-" + appId).css("color", "#ff0000");
    }

    event.on("PushRequest", function (command, cmdData) {
        switch (command) {
        case "REGISTER":
            register(cmdData);
            break;

        case "UNREGISTER":
            unregister(cmdData);
            break;

        case "CONNECT":
            connect(cmdData);
            break;

        case "DISCONNECT":
            disconnect(cmdData);
            break;
        }
    });
}

function _pushElementInitialize() {
    $("#communication-push-submit").attr("disabled", "disabled");
    $("#communication-push-submit").unbind('click').click(function () {
        var appId, pushMessage;

        appId = $("#communication-push-app :checked").attr("id");
        if (!appId)
            return;

        pushMessage = {
            appData:      $("#communication-push-data").val(),
            alertMessage: $("#communication-push-msg").val(),
            date:         new Date()
        };

        if (!pushMessage.appData || !pushMessage.alertMessage)
            return;

        event.trigger("PushNotified", [appId, pushMessage]);
    });

    $("#communication-push-clear").unbind('click').click(function () {
        $("#communication-push-msg").val("");
        $("#communication-push-data").val("");
    });
}

function _pushInitialize() {
    _pushEventInitialize();
    _pushElementInitialize();
}

module.exports = {
    panel: {
        domId: "communication-container",
        collapsed: true,
        pane: "left",
        titleName: "Communications",
        display: true
    },
    initialize: function () {
        jQuery("#communication-select").tabs();
        _callInitialize();
        _msgInitialize();
        _pushInitialize();
    }
};

});
define('ripple/ui/plugins/configWindow', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    tooltip = require('ripple/ui/plugins/tooltip'),
    platform = require('ripple/platform'),
    items = [{name: "DEVICE", id: "device-conf-panel"},
             {name: "SYSTEM SETTINGS", id: "system-settings-conf-panel"},
             {name: "NETWORK", id: "network-conf-panel"}
            ],
    _KEY = "tizen-configuration-window-setting",
    _PERSISTENCE_KEY = "devicesettings",
    _DEVICESETTING_SAVE_KEY = "tizen-configuration-window-device-setting",
    _DB_APPLICATION_KEY = "tizen1-db-application",
    _DB_APPLICATION_SAVE_KEY = "tizen-configuration-window-application-key";

function reload() {
    window.tinyHipposReload = true;
    location.reload();
}

function _hideConfigWindow() {
    $("#configure-window-popup").hide("slide", {direction: "up"}, "slow");
    $("#overlayBackground").hide("fade", "slow");
}

function _cancelConfig() {
    $("#platform-select").val(platform.current().id);
    $("#platform-select").trigger("change");

    _hideConfigWindow();
}

function checkResolutionValue(val) {
    var ret = false;
    if (val >= 200 && val <= 2000) {
        ret = true;
    }
    return ret;
}

function _showConfigWindow() {
    var position_x;
    $("#item_container").empty();
    items.forEach(function (item) {
        $("#item_container").append('<div class="configuration-window-item">' + item.name + '</div>');
        $("#" + item.id).hide();
    });

    $("#content_container").show();
    $("#" + items[0].id).show("fast");

    $(".configuration-window-item:eq(0)").css("background-color", "#003399");
    $(".configuration-window-item:eq(0)").css("color", "#ffffff");

    $(".configuration-window-item").unbind('click');
    $(".configuration-window-item").bind("click", function () {
        $(".configuration-window-item").css("background-color", "#eeeeee");
        $(".configuration-window-item").css("color", "#333333");

        $(this).css("background-color", "#003399");
        $(this).css("color", "#ffffff");

        items.forEach(function (item) {
            $("#" + item.id).hide();
        });
        $("#" + items[$(this).index()].id).show("fast");
    });

    if ($("#configure-window-popup").is(":visible")) {
        $("#configure-window-popup").hide("slide", {direction: "up"}, "slow");
        $("#overlayBackground").hide("fade", "slow");
        return;
    }

    position_x = (($(window).width() - 800) / 2)  < 0 ? 0 : ($(window).width() - 800) / 2;
    $("#configure-window-popup").css("top", 80);
    $("#configure-window-popup").css("left", position_x);

    position_x = (($(window).width() - 400) / 2)  < 0 ? 0 : ($(window).width() - 400) / 2;
    $("#configure-window-done-popup").css("top", 80);
    $("#configure-window-done-popup").css("left", position_x);

    $("#overlayBackground").css("width", $(window).width());
    $("#overlayBackground").css("height", $(window).height());
    $("#overlayBackground").show("fade", "slow");
    $("#configure-window-popup").show("slide", {direction: "up"}, "slow");

    $("#configuration-window-done-btn").unbind('click');
    $("#configuration-window-done-btn").bind("click", function () {
        var platformId, version, device, type, width, height, url;

        // device & resolution setting
        platformId = jQuery("#platform-select").val();
        version = jQuery("#version-select").val();
        device = jQuery("#device-select").val();
        width = jQuery("#resolution-custom-width").val();
        height = jQuery("#resolution-custom-height").val();
        type = jQuery('input:radio[name="resolution-type"]:checked').val();

        if (type === "custom") {
            device = "custom";
            if (!checkResolutionValue(width) || !checkResolutionValue(height)) {
                return;
            }
        }

        if (platformId === "ivi") {
            platformId = "ivi";
            version = "3.0";
        }
        else if (platformId === "wearable") {
            platformId = "wearable";
            version = "2.0";
        }
        else if (platformId === "tv") {
            platformId = "tv";
            version = "1.0";
        }
        else {
            platformId = "tizen";
            version = "2.0";
        }

        platform.changeEnvironment({
            "name": platformId,
            "version": version
        }, device, function () {
            _hideConfigWindow();
            window.tinyHipposReload = true;
            url = location.href.replace(/&platform=(.+?)-(.+?)$/, "&platform=" + platformId + "-" + version);
            location.href = url;
            //reload();
        });
    });

    $("#configuration-window-close-btn").unbind('click');
    $("#configuration-window-close-btn").bind("click", function () {
        if ($("#configure-window-popup").is(":visible")) {
            _cancelConfig();
            return;
        }
    });
    tooltip.create("#configuration-window-save-btn", "Save Configuration");
    $("#configuration-window-save-btn").unbind('click');
    $("#configuration-window-save-btn").bind("click", function () {
        var _type, _device, _custom_width = 0, _custom_height = 0, programs, deviceInfo, _settings;

        deviceInfo = db.retrieveObject(_PERSISTENCE_KEY);
        db.saveObject(_DEVICESETTING_SAVE_KEY, deviceInfo);

        _device = jQuery("#device-select").val();
        _type = jQuery('input:radio[name="resolution-type"]:checked').val();
        if (_type === "custom") {
            _device = "custom";
            _custom_width = jQuery("#resolution-custom-width").val();
            _custom_height = jQuery("#resolution-custom-height").val();
        }
        _settings = {
            platformId : jQuery("#platform-select").val(),
            version : jQuery("#version-select").val(),
            device : _device,
            type : _type,
            custom_width : _custom_width,
            custom_height : _custom_height
        };
        db.saveObject(_KEY, _settings);
        programs = db.retrieveObject(_DB_APPLICATION_KEY);
        db.saveObject(_DB_APPLICATION_SAVE_KEY, programs);
    });
    tooltip.create("#configuration-window-load-btn", "Load Configuration");
    $("#configuration-window-load-btn").unbind('click');
    $("#configuration-window-load-btn").bind("click", function () {
        var platformList,
            deviceInfo,
            _settings,
            versionSelect = document.getElementById("version-select");
        if (db.retrieveObject(_DEVICESETTING_SAVE_KEY) === undefined) {
            //Never saving data exist
            return;
        }
        //reload system & network setting
        deviceInfo = db.retrieveObject(_DEVICESETTING_SAVE_KEY);
        db.saveObject("devicesettings", deviceInfo);
        jQuery("#devicesettings-content-container").empty();
        jQuery("#networksettings-content-container").empty();
        require('ripple/deviceSettings').initialize();
        require('ripple/ui/plugins/deviceSettings').terminate();
        require('ripple/ui/plugins/deviceSettings').initialize();

        //reload device setting
        jQuery(versionSelect).empty();
        _settings = db.retrieveObject(_KEY);
        jQuery("#platform-select").val(_settings.platformId);
        jQuery("#device-select").val(_settings.device);
        if (_settings.type === "custom") {
            $('input:radio[name="resolution-type"][value="custom"]').click();
            jQuery("#resolution-custom-width").val(parseInt(_settings.custom_width, 10));
            jQuery("#resolution-custom-height").val(parseInt(_settings.custom_height, 10));
        } else {
            $('input:radio[name="resolution-type"][value="predefined"]').click();
        }

        platformList = platform.getList();
        utils.forEach(platformList, function (platform) {
            utils.forEach(platform, function (version, versionNumber) {
                if (_settings.platformId === version.id) {
                    versionSelect.appendChild(utils.createElement("option", {
                        "innerText": versionNumber,
                        "value":  versionNumber
                    }));
                }
            });
        });
        jQuery("#version-select").val(_settings.version);
    });

    $(window).bind('resize', function () {
        var position_x = 0;
        $("#configure-window-popup").css("top", 80);
        position_x = (($(window).width() - 800) / 2)  < 0 ? 0 : ($(window).width() - 800) / 2;
        $("#configure-window-popup").css("left", position_x);

        $("#configure-window-done-popup").css("top", 180);
        position_x = (($(window).width() - 400) / 2)  < 0 ? 0 : ($(window).width() - 400) / 2;
        $("#configure-window-done-popup").css("left", position_x);

        $("#overlayBackground").css("width", $(window).width());
        $("#overlayBackground").css("height", $(window).height());
    });

    if (jQuery("#platform-select").val() === "ivi" ||
            jQuery("#platform-select").val() === "wearable" ||
            jQuery("#platform-select").val() === "tv") {
        jQuery("#configuration-window-save-btn").hide();
        jQuery("#configuration-window-load-btn").hide();

        jQuery("#item_container :nth-child(2)").hide();
        jQuery("#item_container :nth-child(3)").hide();

        //jQuery("#hwkeys-panel").hide();
    }
    else {
        jQuery("#configuration-window-save-btn").show();
        jQuery("#configuration-window-load-btn").show();

        jQuery("#item_container :nth-child(2)").show();
        jQuery("#item_container :nth-child(3)").show();

        //jQuery("#hwkeys-panel").show();
    }
}

module.exports = {
    initialize: function () {
        if (platform.current().id === "cordova") {
            items.splice(1, 1);
        }
        $("#options-button-config-window").bind("click", function ()  {
            _showConfigWindow();
        });
    }
};

});
define('ripple/ui/plugins/deviceSettings', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    constants = require('ripple/constants'),
    deviceSettings = require('ripple/deviceSettings'),
    utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    platform = require('ripple/platform'),
    db = require('ripple/db'),
    _CONST = {
        "CONTENT_CONTAINER_ID": "devicesettings-content-container",
        "UKNOWN_CONTROL_MESSAGE": "Unknown device control type"
    },
    _contentContainer,
    _network_contentContainer,
    DBNETWORKSETTING_KEY = "tizen2-preFlightModeNetworksetting",
    _CONTAINER_ID = _CONST.CONTENT_CONTAINER_ID;

function _retrieveDeviceInfo(key) {
    var layout, rtn, deviceInfo = require('ripple/devices').getCurrentDevice();

    switch (key) {
    case "Device.model":
        return deviceInfo.model;
    case "Device.version":
        return deviceInfo.firmware;
    case "Device.vendor":
        return deviceInfo.manufacturer;
    case "DISPLAY.resolutionHeight":
        return deviceInfo.screen.height;
    case "DISPLAY.resolutionWidth":
        return deviceInfo.screen.width;
    case "DISPLAY.pixelAspectRatio":
        return (deviceInfo.screen.width / deviceInfo.screen.height).toFixed(2);

    case "DISPLAY.physicalWidth":
        return Number((deviceInfo.screen.width / deviceInfo.ppi).toFixed(2));
    case "DISPLAY.physicalHeight":
        return Number((deviceInfo.screen.height / deviceInfo.ppi).toFixed(2));
    case "DISPLAY.dpiY":
    case "DISPLAY.dotsPerInchHeight":
        return deviceInfo.ppi;
    case "DISPLAY.dpiX":
    case "DISPLAY.dotsPerInchWidth":
        return deviceInfo.ppi;
    case "OperatingSystem.version":
        return deviceInfo.osVersion;
    case "OperatingSystem.name":
        return deviceInfo.osName;
    case "OperatingSystem.vendor":
        return deviceInfo.manufacturer;
    case "DEVICE_ORIENTATION.status":
        layout = db.retrieve("layout");
        if (layout === null || layout === undefined) {
            layout = deviceInfo.defaultOrientation || "portrait";
        }
        if (layout === "portrait") {
            return "PORTRAIT_PRIMARY";
        } else {
            return "LANDSCAPE_PRIMARY";
        }
        break;
    case "WIFI_NETWORK.status":
    case "CELLULAR_NETWORK.status":
        rtn = deviceSettings.retrieve(key);
        if (rtn === true) {
            return "ON";
        } else {
            return "OFF";
        }
        break;
    case "CPU.load":
        rtn = deviceSettings.retrieve(key);
        if (rtn > 1) {
            rtn = 1;
            deviceSettings.persist(key, rtn);
        }
        if (rtn < 0) {
            rtn = 0;
            deviceSettings.persist(key, rtn);
        }
        return rtn;
    case "DISPLAY.brightness":
        rtn = deviceSettings.retrieve(key);
        if (rtn > 1) {
            rtn = 1;
            deviceSettings.persist("DISPLAY.brightness", rtn);
        }
        if (rtn < 0) {
            rtn = 0;
            deviceSettings.persist("DISPLAY.brightness", rtn);
        }
        return rtn;
    case "BUILD.manufacturer":
        return deviceInfo.manufacturer;
    default:
        return deviceSettings.retrieve(key);
    }
}

function _retrieveSettingName(type) {

    switch (type) {
    case "CellularHardware":
        return "Cellular Hardware";
    case "CellularNetwork":
        return "Cellular Network";
    case "MemoryUnit":
        return "Memory Unit";
    case "OperatingSystem":
        return "Operating System";
    case "WebRuntime":
        return "Web Runtime";
    case "WiFiHardware":
        return "WiFi Hardware";
    case "WiFiNetwork":
        return "WiFi Network";
    default:
        return type;
    }
}

function _appendSettingNode(labelNode, inputNode, label) {
    var frag = document.createDocumentFragment(),
        rowNode = frag.appendChild(utils.createElement("tr")),
        tempTdNode;

    rowNode.appendChild(utils.createElement("td"))
           .appendChild(labelNode);

    tempTdNode = rowNode.appendChild(utils.createElement("td"));

    if (label) {
        tempTdNode.appendChild(label);
    }

    tempTdNode.appendChild(inputNode);

    return frag;
}

function _getCurrentSetting(setting, settingType, key) {
    var ret, savedSetting, fullKey;
    fullKey = settingType + "." + key;
    savedSetting = _retrieveDeviceInfo(fullKey);
    if (fullKey === "WIFI_NETWORK.status" || fullKey === "CELLULAR_NETWORK.status") {
        if (savedSetting === "ON") {
            savedSetting = true;
        } else {
            savedSetting = false;
        }
    }
    ret = (savedSetting || savedSetting === false || savedSetting === "" || savedSetting === 0) ? savedSetting : setting.control.value;
    return ret;
}

function _buildDOMNode(setting, settingType, key) {
    var settingsNode, tagName, jNode,
        fullKey = settingType + "." + key,
        savedSetting = _retrieveDeviceInfo(fullKey),
        // TODO: move this into Utils (isSet method)
        currentSetting,
        domNode,
        domNodeLabel = null;

    if (fullKey === "WIFI_NETWORK.status" || fullKey === "CELLULAR_NETWORK.status") {
        if (savedSetting === "ON") {
            savedSetting = true;
        } else {
            savedSetting = false;
        }
    }
    currentSetting = (savedSetting || savedSetting === false || savedSetting === "" || savedSetting === 0) ? savedSetting : setting.control.value;

    switch (setting.control.type) {
    case "text":
    case "number":
    case "range":
    case "checkbox":
        tagName = "input";
        break;
    case "textarea":
        tagName = "textarea";
        break;
    case "select":
        tagName = "select";
        break;
    case "label":
        tagName = "label";
        break;
    default:
        exception.raise(exception.types.Application, _CONST.UKNOWN_CONTROL_MESSAGE);
    }

    settingsNode = utils.createElement(tagName, setting.control.type === "select" ? null : setting.control);
    settingsNode.setAttribute("id", "device-settings-" + settingType + "-" + key);

    // TODO: this should really be part of utils.createControl? add element of type "range" with label?
    if (setting.control.type === "range") {
        domNodeLabel = utils.createElement("label", {
            "class": constants.UI.LEFT_RANGE_LABEL_CLASS
        });
    }

    domNode = _appendSettingNode(utils.createElement("span", {"innerText": setting.name, "class": "configure-window-text-label"}), settingsNode, domNodeLabel);

    jNode = jQuery(settingsNode);
    if (tagName !== "label") {
        jNode.addClass(constants.UI.JQUERY_UI_INPUT_CLASSES);
    }

    switch (setting.control.type) {
    case "checkbox":
        jNode.bind("click", function () {
            var checked = this.checked ? true : false;
            deviceSettings.persist(fullKey, checked);
            if (typeof setting.callback === "function") {
                setting.callback(checked);
            }
        });

        if (currentSetting === true) {
            jNode.attr("checked", "checked");
        }

        break;

    case "text":
    case "textarea":
    case "number":
        jNode.val(currentSetting);
        utils.bindAutoSaveEvent(jNode, function () {
            if (setting.control.type === "number") {
                deviceSettings.persist(fullKey, Number(jNode.val()));
            } else {
                deviceSettings.persist(fullKey, jNode.val());
            }

            if (typeof setting.callback === "function") {
                setting.callback(jNode.val());
            }
        });
        break;

    case "label":
        jNode.text(currentSetting);
        break;

    case "select":
    case "range":
        if (setting.control.type === "select") {
            utils.forEach(setting.options,  function (value, option) {
                jNode.append(utils.createElement("option", {
                    "value": option,
                    "innerText": value
                }));
            });
        }
        else {
            if (domNodeLabel) {
                domNodeLabel.innerText = currentSetting;
            }
        }

        jNode.val(currentSetting)
             .bind("change", function () {
                if (setting.control.type === "range" && domNodeLabel) {
                    domNodeLabel.innerText = jQuery(this).val();
                }
                deviceSettings.persist(fullKey, jQuery(this).val());

                if (typeof setting.callback === "function") {
                    setting.callback(jQuery(this).val(), currentSetting);
                }
            }
        );
    }

    // TODO: Brent, do in DeviceSettings on load instead?
    if (currentSetting !== setting.control.value) {
        deviceSettings.register(fullKey, currentSetting);
    }

    return domNode;
}

function displayBrightnessCB(value) {
    if (value > 1) value = 1;
    if (value < 0) value = 0;
    if (document.getElementById("device-settings-DISPLAY-brightness").value === value) {
        return;
    }
    deviceSettings.persist("DISPLAY.brightness", Number(value));
    document.getElementById("device-settings-DISPLAY-brightness").value = value;
}

function cpuLoadCB(value) {
    if (value > 1) value = 1;
    if (value < 0) value = 0;
    if (document.getElementById("device-settings-CPU-load").value === value) {
        return;
    }
    deviceSettings.persist("CPU.load", Number(value));
    document.getElementById("device-settings-CPU-load").value = value;
}

function availCapacityCB(value) {
    var capacity = deviceSettings.retrieve("STORAGE.capacity");
    if (Number(value) > Number(capacity)) value = capacity;
    if (Number(value) < 0) value = 0;
    deviceSettings.persist("STORAGE.availableCapacity", Number(value));
    document.getElementById("device-settings-STORAGE-availableCapacity").value = Number(value);
}

function wiFiNetworkStatusCB(value) {
    document.getElementById("device-settings-WIFI_NETWORK-status").checked = value;
}

function flightModeChangedCB(value) {
    var networkSettings = {};
    if (value === true) {
        networkSettings['wifiSetting'] = deviceSettings.retrieve("WIFI_NETWORK.status");
        networkSettings['cellularSetting'] = deviceSettings.retrieve("CELLULAR_NETWORK.status");
        //networkSettings['bluetoothSetting'] = deviceSettings.retrieve("CELLULAR_NETWORK.status");
        //networkSettings['nfcSetting'] = deviceSettings.retrieve("CELLULAR_NETWORK.status");
        db.saveObject(DBNETWORKSETTING_KEY, networkSettings);

        deviceSettings.persist("CELLULAR_NETWORK.status", false);
        deviceSettings.persist("WIFI_NETWORK.status", false);
        event.trigger("nfc-power-setting", [false]);
        event.trigger("bt-power-setting", [false]);

        document.getElementById("device-settings-WIFI_NETWORK-status").checked = false;
        document.getElementById("device-settings-CELLULAR_NETWORK-status").checked = false;
        $("#device-settings-CELLULAR_NETWORK-status").parent().append("<span id='config_flight_mode_notice' style='color:#555555;'>  (Disabled for Flight Mode)</span>");
        document.getElementById("device-settings-CELLULAR_NETWORK-status").disabled = true;

    } else {
        networkSettings = db.retrieveObject(DBNETWORKSETTING_KEY)||{"wifiSetting": true, "cellularSetting": true};
        deviceSettings.persist("WIFI_NETWORK.status", networkSettings['wifiSetting']);
        deviceSettings.persist("CELLULAR_NETWORK.status", networkSettings['cellularSetting']);
        document.getElementById("device-settings-WIFI_NETWORK-status").checked = networkSettings['wifiSetting'];
        document.getElementById("device-settings-CELLULAR_NETWORK-status").checked = networkSettings['cellularSetting'];
        $("#config_flight_mode_notice").remove();
        document.getElementById("device-settings-CELLULAR_NETWORK-status").disabled = false;
    }
}

function cellularNetworkStatusCB(value) {
    document.getElementById("device-settings-CELLULAR_NETWORK-status").checked = value;
}

function layoutCB(value) {
    if (value === 'portrait') {
        deviceSettings.register("DEVICE_ORIENTATION.status", "PORTRAIT_PRIMARY");
        document.getElementById("device-settings-DEVICE_ORIENTATION-status").innerText = "PORTRAIT_PRIMARY";
    } else {
        deviceSettings.register("DEVICE_ORIENTATION.status", "LANDSCAPE_PRIMARY");
        document.getElementById("device-settings-DEVICE_ORIENTATION-status").innerText = "LANDSCAPE_PRIMARY";
    }
}

// goes through current platforms device settings
// adds nodes to panel and binds respective events
// talks to DeviceSettings for persistence
module.exports = {
    initialize: function () {
        var settings, value;
        _contentContainer = document.getElementById(_CONTAINER_ID);
        _network_contentContainer = document.getElementById("networksettings-content-container");

        settings = platform.current().device;
        utils.forEach(settings, function (settingSection, settingType) {

            var currentTableNode, currentTableNode2, settingNameNode, settingName = _retrieveSettingName(settingType);

            settingNameNode = utils.createElement("h3", { "innerText": settingName });
            settingNameNode.setAttribute("class", "configure-window-session-title");

            if (settingType === 'NETWORK' || settingType === 'WIFI_NETWORK' || settingType === 'CELLULAR_NETWORK' || settingType === 'SIM') {
                _network_contentContainer.appendChild(settingNameNode);
                currentTableNode2 = utils.createElement("table", {
                    "class": constants.UI.PANEL_TABLE_CLASS
                });
                currentTableNode2.setAttribute("class", "configure-window-panel-table");
                _network_contentContainer.appendChild(currentTableNode2);
            }
            else {
                _contentContainer.appendChild(settingNameNode);
                currentTableNode = utils.createElement("table", {
                    "class": constants.UI.PANEL_TABLE_CLASS
                });
                currentTableNode.setAttribute("class", "configure-window-panel-table");
                _contentContainer.appendChild(currentTableNode);
            }

            utils.forEach(settingSection, function (setting, key) {
                if (settingType === 'NETWORK' || settingType === 'WIFI_NETWORK' || settingType === 'CELLULAR_NETWORK' || settingType === 'SIM') {
                    currentTableNode2.appendChild(_buildDOMNode(setting, settingType, key));
                }
                else {
                    currentTableNode.appendChild(_buildDOMNode(setting, settingType, key));
                }
                value = _getCurrentSetting(setting, settingType, key);
                if (setting.callback) {
                    setting.callback(value);
                }
            });
        });

        if (deviceSettings.retrieve("CELLULAR_NETWORK.isFlightMode") === true) {
            $("#device-settings-CELLULAR_NETWORK-status").parent().append("<span id='config_flight_mode_notice' style='color:#555555;'>  (Disabled for Flight Mode)</span>");
            document.getElementById("device-settings-CELLULAR_NETWORK-status").disabled = true;
        }

        event.on("DisplayBrightnessChanged", displayBrightnessCB);
        event.on("DisplayBrightnessChangedByPower", displayBrightnessCB);
        event.on("CpuLoadChanged", cpuLoadCB);
        event.on("AvailCapacityChanged", availCapacityCB);
        event.on("CpuLoadChangedByPower", cpuLoadCB);
        event.on("FlightModeChanged", flightModeChangedCB);
        event.on("WiFiNetworkStatusChanged", wiFiNetworkStatusCB);
        event.on("CellularNetworkStatusChanged", cellularNetworkStatusCB);
        event.on("LayoutChanged", layoutCB);
    },
    terminate: function () {
        event.deleteEventHandler("DisplayBrightnessChanged", displayBrightnessCB);
        event.deleteEventHandler("DisplayBrightnessChangedByPower", displayBrightnessCB);
        event.deleteEventHandler("CpuLoadChanged", cpuLoadCB);
        event.deleteEventHandler("AvailCapacityChanged", availCapacityCB);
        event.deleteEventHandler("FlightModeChanged", flightModeChangedCB);
        event.deleteEventHandler("CpuLoadChangedByPower", cpuLoadCB);
        event.deleteEventHandler("WiFiNetworkStatusChanged", wiFiNetworkStatusCB);
        event.deleteEventHandler("CellularNetworkStatusChanged", cellularNetworkStatusCB);
        event.deleteEventHandler("LayoutChanged", layoutCB);
    }
};

});
define('ripple/ui/plugins/devices', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    db = require('ripple/db'),
    resizer = require('ripple/resizer');

function _getTextZooming(zooming) {
    return zooming + '%';
}

module.exports = {
    panel: {
        domId: "devices-container",
        collapsed: true,
        pane: "left",
        titleName: "Orientation and Zooming",
        display: true
    },

    initialize: function () {
        var zooming = document.getElementById(constants.ENCAPSULATOR.ZOOMING);
        function updateZoomingValues() {
            var zoomingText, scaleFactor;

            zoomingText = _getTextZooming(zooming.value);
            jQuery('#screen-zooming-label').html(zoomingText);

            // Zooming device skin
            scaleFactor = zooming.value / 100;
            resizer.scaleDevice(scaleFactor);
        }

        function initializeValues() {
            var zoomingValue =  db.retrieve(constants.ENCAPSULATOR.ZOOMING);

            if (!zoomingValue) {
                zoomingValue = 50;
            }
            jQuery("#" + constants.ENCAPSULATOR.ZOOMING).val(zoomingValue);
            updateZoomingValues();
        }

        jQuery("#" + constants.ENCAPSULATOR.ZOOMING).bind("change", function () {
            updateZoomingValues();
            db.save(constants.ENCAPSULATOR.ZOOMING, zooming.value);
        });

        initializeValues();
    }
};


});
define('ripple/ui/plugins/download', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    event = require('ripple/event'),
    utils = require('ripple/utils'),
    _data = {
        DB_DOWNLOAD_KEY : "tizen1-db-download",
        resources : []
    },
    _cleanInputs, intervalId,
    _downloads;

function _get() {
    _downloads = [
        {id: "0001", url : "http://tizen.org/small_file.zip", size : "5", speed : "1.0", estimatedTime : "5", MIMEType : "application/zip"},
        {id: "0002", url : "http://tizen.org/big_file.zip", size : "20", speed : "1.0", estimatedTime : "20", MIMEType : "application/zip"},
        {id: "0003", url : "http://download.tizen.org/tct/2_1/webapi-tizen-download-test-image-hq.png", size : "3937596", speed : "1968798", estimatedTime : "2", MIMEType : "image/png"},
        {id: "0004", url : "http://download.tizen.org/tct/2_1/webapi-tizen-download-test-image-lq.png", size : "589", speed : "589", estimatedTime : "1", MIMEType : "image/png"}
    ];
    _data.resources = db.retrieveObject(_data.DB_DOWNLOAD_KEY) || _downloads;
    if (db.retrieveObject(_data.DB_DOWNLOAD_KEY) && db.retrieveObject(_data.DB_DOWNLOAD_KEY).length === 0) {
        _data.resources = _downloads;
    } else {
        _data.resources = db.retrieveObject(_data.DB_DOWNLOAD_KEY) || _downloads;
    }
    _save();
}

function _save() {
    db.saveObject(_data.DB_DOWNLOAD_KEY, _data.resources);
    event.trigger('downloadResourceChanged');
}

function checkURL(url) {
    var rg = new RegExp("((^http)|(^https)|(^ftp)):\/\/()+");
    return rg.test(url);
}

function loadResources() {
    var installed = document.getElementById("download-resource"), node, i;
    installed.innerHTML = "";
    for (i in _data.resources) {
        node = utils.createElement("option", {
            "innerText": _data.resources[i].url,
            "value": _data.resources[i].id
        });
        installed.appendChild(node);
    }
    _cleanInputs();
}

function _displayInfo(text) {
    var info = document.getElementById("download-error");
    info.innerHTML = text;
    if (intervalId) {
        clearTimeout(intervalId);
    }
    intervalId = setTimeout(clearDisplayInfo, 5000);
}

function clearDisplayInfo() {
    document.getElementById('download-error').innerHTML = '';
}

function _cleanInputs() {
    document.getElementById("download-url").value = "";
    document.getElementById("download-size").value = "";
    document.getElementById("download-speed").value = "";
    document.getElementById("download-time").innerText = "0";
    document.getElementById("download-MIMEType").value = "";
}

function checkProperties(optionType, url, size, speed, time, MIMEType) {
    var back = true;
    if (url === "" || size === "" ||  speed === "" || time === "" || MIMEType === "") {
        _displayInfo(optionType + " failed, empty input.");
        back = false;
    }
    if (!checkURL(url)) {
        _displayInfo(optionType + " failed, 'URL' is invalid.");
        back = false;
    }
    if (size <= 0 ||  speed <= 0) {
        _displayInfo(optionType + " failed, invalid input.");
        back = false;
    }
    return back;
}

function showUpdateNotification() {
    var url     = document.getElementById("download-url").value,
        size    = document.getElementById("download-size").value,
        speed   = document.getElementById("download-speed").value,
        MIMEType = document.getElementById("download-MIMEType").value,
        isValid = true;
    if (url === "" || size === "" ||  speed === "" || MIMEType === "" || !checkURL(url) || size <= 0 ||  speed <= 0) {
        isValid = false;
    }
    if (isValid) {
        _displayInfo("Resource changed, please Add or Update the content.");
    }
}

function _adding() {
    var id, time, url, size, speed, MIMEType, object, i, isValid;
    url     = document.getElementById("download-url").value;
    size    = document.getElementById("download-size").value;
    speed   = document.getElementById("download-speed").value;
    MIMEType = document.getElementById("download-MIMEType").value;
    time    = size / speed;
    id      = Math.uuid(null, 16);

    isValid = checkProperties("Add", url, size, speed, time, MIMEType);
    if (!isValid)
        return;
    if (_data.resources.length !== 0) {
        for (i in _data.resources) {
            if (url === _data.resources[i].url) {
                _displayInfo("Add failed, the download resource is already available.");
                return;
            }
        }
    }
    document.getElementById("download-time").innerText = Math.round(time * 100) / 100;
    object = {'id': id, 'url': url, 'size': size, 'speed': speed, 'estimatedTime': time, MIMEType: MIMEType};
    _data.resources.push(object);
    _save();
    loadResources();
}

function _update() {
    var id, time, url, size, speed, MIMEType, i, isExist = false, isValid;

    id    = document.getElementById("download-resource").value;
    url   = document.getElementById("download-url").value;
    size  = document.getElementById("download-size").value;
    speed = document.getElementById("download-speed").value;
    MIMEType = document.getElementById("download-MIMEType").value;
    time  = size / speed;

    if (_data.resources.length === 0) {
        _displayInfo("Update failed, there is no download resource now.");
        return;
    }
    isValid = checkProperties("Update", url, size, speed, time, MIMEType);
    if (!isValid)
        return;
    for (i in _data.resources) {
        if (_data.resources[i].url === url) {
            isExist = true;
            _data.resources[i] = {id: id, url : url, size : size, speed : speed, estimatedTime: time, MIMEType: MIMEType};
            loadResources();
            _save();
            break;
        }
    }
    if (!isExist)
        _displayInfo("Update failed, the download resource doesn't exist.");
}

function _delete() {
    var i, id;
    id = document.getElementById("download-resource").value;
    if (id) {
        for (i in _data.resources) {
            if (_data.resources[i].id === id) {
                _data.resources.splice(i, 1);
                _save();
                loadResources();
            }
        }
    }
}

function _showAppDetail(id) {
    var i;
    for (i in _data.resources) {
        if (id === _data.resources[i].id) {
            document.getElementById("download-time").innerText = Math.round(_data.resources[i].estimatedTime * 100) / 100;
            jQuery("#download-url").val(_data.resources[i].url);
            jQuery("#download-size").val(_data.resources[i].size);
            jQuery("#download-speed").val(_data.resources[i].speed);
            jQuery("#download-MIMEType").val(_data.resources[i].MIMEType);
        }
    }
}

function _changeAppData() {
    var id = jQuery("#download-resource").val();
    _showAppDetail(id);
}
function changeValue() {
    var size  = document.getElementById("download-size").value,
        speed = document.getElementById("download-speed").value;
    if (size > 0 && speed > 0) {
        document.getElementById("download-time").innerText = Math.round(size / speed * 100) / 100;
    } else {
        document.getElementById("download-time").innerText  = "";
    }
}
function checkInputValue(input) {
    if (input.value === "" || input.value <= 0) {
        input.style['border-color'] = 'red';
        _displayInfo("Invalided value.");
    } else {
        if (input.style['border-color']) {
            input.style.removeProperty('border-color');
        }
        changeValue();
        //showUpdateNotification();
    }
}
module.exports = {
    panel: {
        domId: "download-container",
        collapsed: true,
        pane: "left",
        titleName: "Download",
        display: true
    },
    initialize: function () {
        _get();
        loadResources();

        document.getElementById("download-add").addEventListener("click", _adding, false);
        document.getElementById("download-update").addEventListener("click", _update, false);
        document.getElementById("download-delete").addEventListener("click", _delete, false);

        jQuery("#download-resource").bind("focus change", function () {
            var url = document.getElementById("download-url"),
                size = document.getElementById("download-size"),
                speed = document.getElementById("download-speed"),
                MIMEType = document.getElementById("download-MIMEType");
            if (url.style['border-color']) {
                url.style.removeProperty('border-color');
            }
            if (MIMEType.style['border-color']) {
                MIMEType.style.removeProperty('border-color');
            }
            if (size.value > 0 && size.style['border-color']) {
                size.style.removeProperty('border-color');
            }
            if (speed.value > 0 && speed.style['border-color']) {
                speed.style.removeProperty('border-color');
            }
            _changeAppData();
        });
        jQuery("#download-speed").bind("blur", function () {
            changeValue();
        });
        jQuery("#download-size").bind("blur", function () {
            changeValue();
        });
        jQuery("#download-speed").bind("change", function () {
            checkInputValue(this);
        });
        jQuery("#download-size").bind("change", function () {
            checkInputValue(this);
        });
        jQuery("#download-speed").bind("change", function () {
            checkInputValue(this);
        });
        jQuery("#download-url").bind("change", function () {
            if (this.style['border-color']) {
                this.style.removeProperty('border-color');
            }
            if (this.value && checkURL(this.value)) {
                //showUpdateNotification();
            } else  {
                _displayInfo("Invalided URL.");
                this.style['border-color'] = 'red';
            }
        });
    }
};

});
define('ripple/ui/plugins/eulaCheck', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    bus = require('ripple/bus');

function _initializeEulaCheck() {
    var width = jQuery(document).width(),
        p = (width / 2) - 277;


    $(".eula-window").show();
    $(".eula-dialog").show().css({left: p + "px"});

    $("#eula-accept").click(function () {
        bus.send("acceptEula", null, function (result) {
            $(".eula-window").hide();
            $(".eula-dialog").hide();
        });
    });

    $("#eula-decline").click(function () {
        bus.send("disable", null, null);
    });
}

module.exports = {
    initialize: function () {
        //HACK: there has to be a better way!!!
        if ($("#extension-url").val().match(/geelfhphabnejjhdalkjhgipohgpdnoc/)) {
            // do nothing, extension was installed from the Chrome Store
            return;
        }

        bus.send("checkEula", null, function (response) {
            console.log("eula response: ", response);
            if (response === false) {
                _initializeEulaCheck();
            }
        });
    }
};

});
define('ripple/ui/plugins/exec-dialog', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function exec(func) {
    return function () {
        var val = $("#exec-response").val();

        //TODO: handle multiple args
        func.apply(null, val ? [JSON.parse(val)] : []);
        $("#exec-dialog").dialog("close");
    };
}

module.exports = {
    initialize: function () {
        $("#exec-dialog").dialog({
            autoOpen: false,
            modal: true,
            title: "I Haz Cheeseburger?!?!",
            width: 500,
            position: 'center'
        }).hide();

        $("#exec-success").button();
        $("#exec-fail").button();
    },

    show: function (service, action, success, fail) {
        console.log(service);
        console.log(action);
        $("#exec-service").text(service);
        $("#exec-action").text(action);
        $("#exec-dialog").dialog("open");
        $("#exec-success").unbind().bind('click', exec(success));
        $("#exec-fail").unbind().bind('click', exec(fail));
    }
};

});
define('ripple/ui/plugins/fileSystem', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    constants = require('ripple/constants'),
    fileSystem = require('ripple/fileSystem'),
    fileSystemPaths = fileSystem.getFileSystemPaths();

module.exports = {
    panel: {
        domId: "filsystem-container",
        collapsed: true,
        pane: "left"
    },
    initialize: function () {
        var fileSystemPaths = fileSystem.getFileSystemPaths();

        utils.forEach(fileSystemPaths, function (value, key) {
            utils.bindAutoSaveEvent(jQuery(constants.FILESYSTEM.INPUT_PREFIX_ID + key).val(value.uri), function () {
                value.uri = jQuery(constants.FILESYSTEM.INPUT_PREFIX_ID + key).val();
                fileSystem.updateFileSystemPaths(fileSystemPaths);
            });
        });
    }
};

});
define('ripple/ui/plugins/firstRunCheck', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    _platform = require('ripple/platform'),
    db = require('ripple/db');

function _handleFirstRunResponse(platform, version) {
    var device = jQuery("#device-select").val(),
        api = {
            name: platform.id,
            version: version
        };


    _platform.changeEnvironment(api, device, function () {
        window.tinyHipposReload = true;
        location.reload();
    });
}

function _addPlatformButton(platform, version) {
    var section = jQuery(".platform-select-buttons"),
        buttonID = "platform-" + platform.id,
        button = utils.createElement("button", {
            "id": buttonID,
            "class": "ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only"
        });

    button.appendChild(utils.createElement("span", {
        "class": "ui-button-text",
        "innertext" : platform.name
    }));

    section.append(button);

    document.getElementById(buttonID).addEventListener("click", function () {
        _handleFirstRunResponse(platform, version);
    });
}

function _initializeFirstRunCheck() {
    var savedPlatform = db.retrieveObject("api-key"),
        firstRunOverlayNode, firstRunOptionsNode,
        width, p;

    if (!savedPlatform) {
        width = jQuery(document).width();
        p = (width / 2) - 277;

        firstRunOverlayNode = jQuery(".first-run-window").css({display: 'block'});
        firstRunOptionsNode = jQuery(".platform-select-dialog").css({display: 'block', left: p + "px"});

        utils.forEach(_platform.getList(), function (platform) {
            utils.forEach(platform, function (details, version) {
                _addPlatformButton(details, version);
            });
        });
    }
}

module.exports = {
    initialize: function () {
        if (utils.map(_platform.getList(), function (platform) {
            return platform;
        }).length > 1) {
            _initializeFirstRunCheck();
        }
    }
};

});
define('ripple/ui/plugins/geoDB', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    lbs = require('ripple/platform/tizen/2.0/lbs_utils'),
    _GEO_OBJECTS = "tizen1.0-geocode-objects",
    _geoList, _currentGeo, _saveID, _showGeoDetail;

function _getGeo() {
    var geoList = [],
        data = db.retrieveObject(_GEO_OBJECTS);

    utils.forEach(data, function (geo) {
        geoList.push(geo);
    });
    return geoList;
}

function _saveGeo() {
    db.saveObject(_GEO_OBJECTS, _geoList);
}

function GeoEntry(addr, coord) {
    var _self;
    _self = {
        address : addr || null,
        coordinate : coord || null
    };
    return _self;
}

function _updateGeoDBSelect() {
    var geoDBSelect = document.getElementById("geo-select"),
        geoNode, i;

    geoDBSelect.innerHTML = "";
    for (i = 0; i < _geoList.length; i++) {
        geoNode = utils.createElement("option", {
            "innerText": "(" + _geoList[i].coordinate.latitude + ", " + _geoList[i].coordinate.longitude + ")",
            "value": i
        });
        if (_currentGeo === Number(geoNode.value)) {
            geoNode.selected = true;
            _showGeoDetail(_geoList[_currentGeo].coordinate, _geoList[_currentGeo].address);
        }
        geoDBSelect.appendChild(geoNode);
    }
}

function _showGeoDetail(coord, addr) {
    jQuery("#geoDB-latitude").val(coord.latitude);
    jQuery("#geoDB-longitude").val(coord.longitude);
    jQuery("#geoDB-altitude").val(coord.altitude);
    jQuery("#geoDB-accuracy").val(coord.accuracy);
    jQuery("#geoDB-altitudeAccuracy").val(coord.altitudeAccuracy);
    jQuery("#geoDB-heading").val(coord.heading);
    jQuery("#geoDB-speed").val(coord.speed);

    jQuery("#geoDB-country").val(addr.country);
    jQuery("#geoDB-region").val(addr.region);
    jQuery("#geoDB-county").val(addr.county);
    jQuery("#geoDB-city").val(addr.city);
    jQuery("#geoDB-street").val(addr.street);
    jQuery("#geoDB-streetNumber").val(addr.streetNumber);
    jQuery("#geoDB-premises").val(addr.premises);
    jQuery("#geoDB-additionalInformation").val(addr.additionalInformation);
    jQuery("#geoDB-postalCode").val(addr.postalCode);
}

function _changeGeoData() {
    var id = Number(jQuery("#geo-select").val());
    _currentGeo = id;
    _showGeoDetail(_geoList[id].coordinate, _geoList[id].address);
}

function _triggerReadOnly(on) {
    if (on === true) {
        jQuery("#geoDB-table input").attr("readonly", "readonly");
        jQuery("#geoDB-add").show();
        jQuery("#geoDB-modify").show();
        jQuery("#geoDB-delete").show();
        jQuery("#geo-select").removeAttr("disabled");
        jQuery("#geoDB-save").hide();
        jQuery("#geoDB-cancel").hide();
    } else {
        jQuery("#geoDB-table input").removeAttr("readonly");
        jQuery("#geoDB-add").hide();
        jQuery("#geoDB-modify").hide();
        jQuery("#geoDB-delete").hide();
        jQuery("#geo-select").attr("disabled", "disabled");
        jQuery("#geoDB-save").show();
        jQuery("#geoDB-cancel").show();
    }
}

function _addGeoData() {
    _triggerReadOnly(false);
    jQuery("#geoDB-table input").val("");
    _saveID = _geoList.length;
    jQuery("#geo-select").val("");
}
function _modifyGeoData() {
    _triggerReadOnly(false);
    _saveID = _currentGeo;
}
function _deleteGeoData() {
    _geoList.splice(_currentGeo, 1);
    _saveGeo();
    _currentGeo = 0;
    _updateGeoDBSelect();
}
function _saveGeoData() {
    var entry;
    entry = new GeoEntry(new lbs.StructuredAddress({
        country: jQuery("#geoDB-country").val(),
        region: jQuery("#geoDB-region").val(),
        county: jQuery("#geoDB-county").val(),
        city: jQuery("#geoDB-city").val(),
        street: jQuery("#geoDB-street").val(),
        streetNumber: jQuery("#geoDB-streetNumber").val(),
        premises: jQuery("#geoDB-premises").val(),
        additionalInformation: jQuery("#geoDB-additionalInformation").val(),
        postalCode: jQuery("#geoDB-postalCode").val()
    }),
        new lbs.GeoCoordinates({
        latitude: parseFloat(jQuery("#geoDB-latitude").val()),
        longitude: parseFloat(jQuery("#geoDB-longitude").val()),
        altitude: parseFloat(jQuery("#geoDB-altitude").val()),
        accuracy: parseFloat(jQuery("#geoDB-accuracy").val()),
        altitudeAccuracy: parseFloat(jQuery("#geoDB-altitudeAccuracy").val()),
        heading: parseFloat(jQuery("#geoDB-heading").val()),
        speed: parseFloat(jQuery("#geoDB-speed").val())
    }));
    if (_saveID === _geoList.length)
        _geoList.push(entry);
    else
        _geoList[_saveID] = entry;
    
    _saveGeo();
    _currentGeo = _saveID;
    _updateGeoDBSelect();
    _triggerReadOnly(true);
}

function _cancelGeoData() {
    _triggerReadOnly(true);
    _updateGeoDBSelect();
}

module.exports = {
    panel: {
        domId: "geoDB-container",
        collapsed: true,
        pane: "right"
    },

    initialize: function () {
        _currentGeo = 0; // set _geoList[0] as default value
        _geoList = _getGeo();
        _updateGeoDBSelect();
        _triggerReadOnly(true);

        jQuery("#geo-select").bind("change", function () {
            _changeGeoData();
        });
        jQuery("#geoDB-add").bind("click", function () {
            _addGeoData();
        });
        jQuery("#geoDB-modify").bind("click", function () {
            _modifyGeoData();
        });
        jQuery("#geoDB-delete").bind("click", function () {
            _deleteGeoData();
        });
        jQuery("#geoDB-save").bind("click", function () {
            _saveGeoData();
        });
        jQuery("#geoDB-cancel").bind("click", function () {
            _cancelGeoData();
        });
    }
};

});
define('ripple/ui/plugins/geoView', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    geo = require('ripple/geo'),
    db = require('ripple/db'),
    event = require('ripple/event'),
    utils = require('ripple/utils'),
    platform = require('ripple/platform'),
    markers,
    _gpsMapZoomLevel,
    _routePoints = [],
    _routes = [],
    _routeMarkers,
    _lineLayer,
    _drawLineTimeout,
    _playFrequency = 0,
    _originalNavigator = window.navigator,
    _locationSharing = false;
    _playState = {'play': false, 'replay': false};

function _initTimeZone() {
    var allTZ, dbTZ, node = jQuery("#time-locale-select"),
        timezone = require('ripple/platform/tizen/2.0/timezone_info'),
        alarms, time;

    function triggerAlarm() {
        time = new Date();
        alarms = db.retrieveObject("tizen1.0-db-alarms");
        if (alarms !== null) {
            utils.forEach(alarms, function (obj) {
                if (obj.id !== undefined) {
                    event.trigger("CheckAlarm", [obj.id]);
                }
            });
        }
    }
    window.setInterval(triggerAlarm, 1000);

    allTZ = timezone.getAllTimezone();
    utils.forEach(allTZ, function (tz) {
        node.append(utils.createElement("option", {
            "value": tz,
            "innerHTML": tz + " - " + timezone.getTimezoneAbbr(tz) + "(" + timezone.getTimezoneDiff(tz) + ")"
        }));
    });
    dbTZ = db.retrieve("tizen-timezone");
    if (timezone.isValidTimezone(dbTZ)) {
        node.val(dbTZ);
    } else {
        db.save("tizen-timezone", node.val());
    }
    node.bind("change", function () {
        db.save("tizen-timezone", node.val());
    });
}

function _updateGpsMap() {
    var positionInfo = geo.getPositionInfo(),
        mapContainer = document.getElementById(constants.GEO.OPTIONS.MAP_CONTAINER);

    if (mapContainer && jQuery(mapContainer).is(':visible')) {
        geo.map.setCenter(new OpenLayers.LonLat(positionInfo.longitude, positionInfo.latitude).transform(
            new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel, true);
    }

    if (_lineLayer) {
        geo.map.removeLayer(_lineLayer);
        geo.map.addLayer(_lineLayer);
    }
}

function _updateGpsMapZoom(goUp) {
    if (goUp && _gpsMapZoomLevel < constants.GEO.MAP_ZOOM_MAX) {
        _gpsMapZoomLevel++;
    }
    else if (!goUp && _gpsMapZoomLevel > constants.GEO.MAP_ZOOM_MIN) {
        _gpsMapZoomLevel--;
    }

    _updateGpsMap();
    db.save(constants.GEO.MAP_ZOOM_KEY, _gpsMapZoomLevel);
}

function _getTextHeading(heading) {
    if (heading >= 337.5 || (heading >= 0 && heading <= 22.5)) {
        return 'N';
    }

    if (heading >= 22.5 && heading <= 67.5) {
        return 'NE';
    }

    if (heading >= 67.5 && heading <= 112.5) {
        return 'E';
    }
    if (heading >= 112.5 && heading <= 157.5) {
        return 'SE';
    }

    if (heading >= 157.5 && heading <= 202.5) {
        return 'S';
    }

    if (heading >= 202.5 && heading <= 247.5) {
        return 'SW';
    }

    if (heading >= 247.5 && heading <= 292.5) {
        return 'W';
    }

    if (heading >= 292.5 && heading <= 337.5) {
        return 'NW';
    }
}

function _updateRoutes() {
    var i, j, k, lon_step, lat_step;
    _routes = [];

    for (i = 0; i < _routePoints.length - 1; i++) {
        lon_step = (_routePoints[i + 1].lonlat.lon - _routePoints[i].lonlat.lon) / 50;
        lat_step = (_routePoints[i + 1].lonlat.lat - _routePoints[i].lonlat.lat) / 50;

        _routes.push(new OpenLayers.LonLat(_routePoints[i].lonlat.lon, _routePoints[i].lonlat.lat));
        for (j = 1, k = _routes.length; j < 50; j++, k++) {
            _routes.push(new OpenLayers.LonLat(_routes[k - 1].lon + lon_step, _routes[k - 1].lat + lat_step));
        }
    }
    _routes.push(new OpenLayers.LonLat(
        _routePoints[_routePoints.length - 1].lonlat.lon,
        _routePoints[_routePoints.length - 1].lonlat.lat)
    );
}

function _drawLine(array) {
    var GEO_OPTIONS = constants.GEO.OPTIONS,
        latitude = document.getElementById(GEO_OPTIONS.LATITUDE),
        longitude = document.getElementById(GEO_OPTIONS.LONGITUDE),
        lonlat = new OpenLayers.LonLat(array[0].lon, array[0].lat).transform(
            new OpenLayers.Projection("EPSG:900913"),
            new OpenLayers.Projection("EPSG:4326")
        ),
        points = new Array(
            new OpenLayers.Geometry.Point(array[0].lon, array[0].lat),
            new OpenLayers.Geometry.Point(array[1].lon, array[1].lat)
        ),
        line = new OpenLayers.Geometry.LineString(points),
        style = {
            strokeColor: '#0000ff',
            strokeOpacity: 1,
            strokeWidth: 3
        },
        lineFeature = new OpenLayers.Feature.Vector(line, null, style);

    if (!_lineLayer) {
        _lineLayer = new OpenLayers.Layer.Vector("Line Layer");
        geo.map.addLayer(_lineLayer);
    }

    _lineLayer.addFeatures([lineFeature]);
    longitude.value = lonlat.lon;
    latitude.value = lonlat.lat;

    if (_playFrequency % 10 === 0) {
        geo.map.panTo(new OpenLayers.LonLat(array[0].lon, array[0].lat), _gpsMapZoomLevel);
    }
    _playFrequency++;
}

function clearRoute() {
    if (!_playState.play) {
        _routePoints.forEach(function (item) {
            _routeMarkers.removeMarker(item.marker);
        });
        _routePoints = [];
        _routes = [];
        _lineLayer.removeFeatures(_lineLayer.features);
    }
}

function setRoute() {
    var clickHandler = new OpenLayers.Handler.Click(
        this,
        {
            click: function (e) {
                if (geo.map.calculateBounds(null, 1) === null) {
                    geo.map.zoomTo(geo.map.zoom);
                }
                var location = geo.map.getLonLatFromViewPortPx(e.xy),
                    size = new OpenLayers.Size(21, 25),
                    offset = new OpenLayers.Pixel(-(size.w / 2), -size.h),
                    icon = new OpenLayers.Icon('images/map_marker.png', size, offset),
                    marker = new OpenLayers.Marker(new OpenLayers.LonLat(location.lon, location.lat), icon);

                geo.map.addLayer(_routeMarkers);
                _routeMarkers.addMarker(marker);
                _routePoints.push({
                    lonlat : location,
                    marker : marker
                });
            }
        },
        {double: true}
    );
    clickHandler.dblclick = function () {
        _updateRoutes();
        this.deactivate();
    };

    if (!_playState.play) {
        clickHandler.setMap(geo.map);
        clickHandler.activate();
    }
}

function playRoute() {
    var speed = document.getElementById("play-route-speed"),
        getPlaySpeed = function () {
            return 20 / speed.value * 1000 / 50;
        },
        draw = function () {
            if (_routes.length <= 1) {
                window.clearTimeout(_drawLineTimeout);
                geo.map.panTo(new OpenLayers.LonLat(
                    _routePoints[_routePoints.length - 1].lonlat.lon,
                    _routePoints[_routePoints.length - 1].lonlat.lat),
                    _gpsMapZoomLevel);
                _playState.play = false;
                _playState.replay = true;
                document.getElementById('play-btn-icon').src = "images/play.png";
            } else {
                _drawLine(_routes);
                _routes.splice(0, 1);
                _drawLineTimeout = window.setTimeout(draw, getPlaySpeed());
            }
        };

    if (!_playState.play && _routes.length !== 0) {
        if (_lineLayer && _playState.replay) {
            _lineLayer.removeFeatures(_lineLayer.features);
            _updateRoutes();
        }
        draw();
        _playState.play = true;
        document.getElementById('play-btn-icon').src = "images/pause.png";
    } else if (_playState.play) {
        window.clearTimeout(_drawLineTimeout);
        _playState.play = false;
        _playState.replay = false;
        document.getElementById('play-btn-icon').src = "images/play.png";
    }
}

function skipTo(position) {
    if (_routes.length !== 0) {
        var index = (position === 'start' ? 0 : _routePoints.length - 1);
        window.clearTimeout(_drawLineTimeout);
        _lineLayer.removeFeatures(_lineLayer.features);
        geo.map.panTo(new OpenLayers.LonLat(_routePoints[index].lonlat.lon, _routePoints[index].lonlat.lat), _gpsMapZoomLevel);
        _routes = [];
        _updateRoutes();
        _playFrequency = 0;
        _playState.play = false;
        _playState.replay = false;
        document.getElementById('play-btn-icon').src = "images/play.png";
    }
}

module.exports = {
    panel: {
        domId: "gps-container",
        collapsed: true,
        pane: "left",
        titleName: "Geolocation",
        display: true
    },
    initialize: function () {
        var GEO_OPTIONS = constants.GEO.OPTIONS,
            positionInfo = geo.getPositionInfo(),
            positionEvent = "PositionInfoUpdatedEvent",
            latitude = document.getElementById(GEO_OPTIONS.LATITUDE),
            longitude = document.getElementById(GEO_OPTIONS.LONGITUDE),
            altitude = document.getElementById(GEO_OPTIONS.ALTITUDE),
            accuracy = document.getElementById(GEO_OPTIONS.ACCURACY),
            altitudeAccuracy = document.getElementById(GEO_OPTIONS.ALTITUDE_ACCURACY),
            heading = document.getElementById(GEO_OPTIONS.HEADING),
            speed = document.getElementById(GEO_OPTIONS.SPEED),
            cellID = document.getElementById(GEO_OPTIONS.CELL_ID),
            delay = document.getElementById(GEO_OPTIONS.DELAY),
            delayLabel = document.getElementById(GEO_OPTIONS.DELAY_LABEL),
            headingLabel = document.getElementById(GEO_OPTIONS.HEADING_LABEL),
            headingMapLabel = document.getElementById(GEO_OPTIONS.HEADING_MAP_LABEL),
            timeout = document.getElementById(GEO_OPTIONS.TIMEOUT),
            gpxMultiplier = document.getElementById(GEO_OPTIONS.GPXMULTIPLIER),
            gpxReplayStatus = document.getElementById(GEO_OPTIONS.GPXREPLAYSTATUS),
            gpxGo = $(document.getElementById(GEO_OPTIONS.GPXGO)).find("span")[0],
            mapContainer = document.getElementById(GEO_OPTIONS.MAP_CONTAINER),
            map = null,
            track = [],
            _replayingGpxFile = false,
            _haltGpxReplay = false;

        function updateGeo() {
            if (parseFloat(latitude.value) > 90)
                latitude.value = 90;
            else if (parseFloat(latitude.value) < -90)
                latitude.value = -90;

            if (parseFloat(longitude.value) > 180)
                longitude.value = 180;
            else if (parseFloat(longitude.value) < -180)
                longitude.value = -180;

            geo.updatePositionInfo({
                latitude: parseFloat(latitude.value),
                longitude: parseFloat(longitude.value),
                altitude: parseInt(altitude.value, 10),
                accuracy: parseInt(accuracy.value, 10),
                altitudeAccuracy: parseInt(altitudeAccuracy.value, 10),
                heading: heading.value ? parseFloat(heading.value) : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
                speed: speed.value ? parseInt(speed.value, 10) : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
                cellID: cellID.value,
                timeStamp: new Date()
            },
            delay.value,
            timeout.checked);
        }

        function updateHeadingValues() {
            var headingDeg = parseFloat(heading.value),
                headingText = _getTextHeading(parseFloat(heading.value));

            headingLabel.innerText = headingText;
            headingMapLabel.innerHTML = headingText + "</br>" + headingDeg + "&deg;";
        }

        function updateValsFromMap() {
            var center = geo.map.getCenter().transform(
                new OpenLayers.Projection("EPSG:900913"),
                new OpenLayers.Projection("EPSG:4326"));
            longitude.value = center.lon;
            latitude.value = center.lat;
            updateGeo();
        }

        function initializeValues() {
            latitude.value =          positionInfo.latitude;
            longitude.value =         positionInfo.longitude;
            altitude.value =          positionInfo.altitude;
            accuracy.value =          positionInfo.accuracy;
            altitudeAccuracy.value =  positionInfo.altitudeAccuracy;
            cellID.value =            positionInfo.cellID;
            delay.value = document.getElementById(GEO_OPTIONS.DELAY_LABEL).innerText = geo.delay || 0;
            if (geo.timeout) {
                timeout.checked = true;
            }
            updateHeadingValues();
        }

        function initMap() {
            var marker, clickHandler;
            // override image location so we don't have to include image assets
            OpenLayers.ImgPath = 'http://openlayers.org/api/img/';

            // init map
            geo.map = new OpenLayers.Map(mapContainer, { controls: [] });

            // add controls and OSM map layer
            geo.map.addLayer(new OpenLayers.Layer.OSM());
            geo.map.addControl(new OpenLayers.Control.Navigation());

            // override behaviour of click to pan and double click to zoom in
            clickHandler = new OpenLayers.Handler.Click(
                this,
                {
                    click: function (e) {
                        if (geo.map.calculateBounds(null, 1) === null) {
                            geo.map.zoomTo(geo.map.zoom);
                        }
                        var location = geo.map.getLonLatFromViewPortPx(e.xy);
                        geo.map.panTo(new OpenLayers.LonLat(location.lon, location.lat), _gpsMapZoomLevel);
                    },

                    dblclick: function () {
                        _updateGpsMapZoom(true);
                    }
                },
                {double: true}
            );

            // add click handler to map
            clickHandler.setMap(geo.map);
            clickHandler.activate();

            // update long and lat when map is panned
            geo.map.events.register("moveend", map, function () {
                updateValsFromMap();
            });
            geo.map.events.register("zoomend", map, function (obj) {
                if ((obj.object.zoom > _gpsMapZoomLevel && _gpsMapZoomLevel < constants.GEO.MAP_ZOOM_MAX) ||
                    (obj.object.zoom < _gpsMapZoomLevel && _gpsMapZoomLevel > constants.GEO.MAP_ZOOM_MIN)) {
                    _gpsMapZoomLevel = obj.object.zoom;
                }
            });

            markers = new OpenLayers.Layer.Markers("markers");
            _routeMarkers = new OpenLayers.Layer.Markers("markers");
            geo.map.addLayer(markers);

            event.on("ApplicationState", function (obj) {
                if (obj && obj[0].id === 'gps-container' && obj.hasClass('ui-box-open')) {
                    _updateGpsMap();

                    // Update the position if user accept location sharing
                    if (_locationSharing === false) {
                        _originalNavigator.geolocation.getCurrentPosition(function(geoPosition) {
                            geo.map.panTo(new OpenLayers.LonLat(geoPosition.coords.longitude, geoPosition.coords.latitude).transform(
                                new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel);
                            _locationSharing = true;
                        });
                    }

                    // Simulator is loaded with geo panel folded, now it's the first time it's unfolded
                    if (!marker) {
                        // Only when the geo panel is unfolded, getCenter() will go well
                        marker = new OpenLayers.Marker(geo.map.getCenter(),
                            new OpenLayers.Icon("images/arrow.png", new OpenLayers.Size(22, 30), new OpenLayers.Pixel(-11, -15)));
                        markers.addMarker(marker);

                        navigator.geolocation.getCurrentPosition(function (geoPosition) {
                            geo.map.panTo(new OpenLayers.LonLat(geoPosition.coords.longitude, geoPosition.coords.latitude).transform(
                                new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel);
                        });
                    }
                }
            });
            _updateGpsMap();

            // Simulator is loaded with geo panel unfolded
            if (mapContainer && jQuery(mapContainer).is(':visible')) {
                marker = new OpenLayers.Marker(geo.map.getCenter(),
                    new OpenLayers.Icon("images/arrow.png", new OpenLayers.Size(22, 30), new OpenLayers.Pixel(-11, -15)));
                markers.addMarker(marker);

                navigator.geolocation.getCurrentPosition(function (geoPosition) {
                    geo.map.panTo(new OpenLayers.LonLat(geoPosition.coords.longitude, geoPosition.coords.latitude).transform(
                        new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")), _gpsMapZoomLevel);
                    _locationSharing = true;
                });
            }

            geo.map.events.register("move", map, function () {
                markers.clearMarkers();
                marker = new OpenLayers.Marker(geo.map.getCenter(),
                        new OpenLayers.Icon("images/arrow.png", new OpenLayers.Size(22, 30), new OpenLayers.Pixel(-11, -15)));
                markers.addMarker(marker);
            });
        }

        function loadGpxFile(win, fail, args) {
            var reader = new FileReader(),
                file = args[0],
                _xml,
                t,
                att,
                lastAtt,
                _ele,
                _timestamp,
                _lastTimestamp,
                _useTimestamp = new Date().getTime(),
                _tempTimestamp,
                _tempPosition,
                _lastPosition,
                _useLastTimestamp,
                _heading = 0,
                _speed = 0,
                _dist = 0,
                navUtils = new utils.navHelper();

            reader.onload = function (e) {
                _xml = e.target.result;
                t = $(_xml).find('trkpt');

                track = [];

                utils.forEach(t, function (p, i) {
                    if (!isNaN(i)) {
                        att = t[i].attributes;
                        lastAtt = t[i - 1] ? t[i - 1].attributes : {};
                        _ele = $(t[i]).find("ele")[0];
                        _timestamp = $(t[i]).find("time")[0];
                        _lastTimestamp = $(t[i - 1]).find("time")[0];

                        if (_timestamp) {
                            //files recorded with endomondo and others have timestamps, this is not a route plan but a record of a track
                            _useTimestamp = new Date(_timestamp.innerText).getTime();
                        }

                        if (t[i - 1]) {
                            _dist = navUtils.getDistance(att["lat"].value, att["lon"].value, lastAtt["lat"].value, lastAtt["lon"].value);

                            if (_lastTimestamp) {
                                _useLastTimestamp = new Date(_lastTimestamp.innerText).getTime();
                            }
                            else {
                                //routes from YOURS come in as tracks (rather than routes under the GPX schema), but with no timestamps.  This is a route.
                                _useLastTimestamp = _useTimestamp;
                                _useTimestamp += Math.round(_dist / 22.2222 * 1000);  //80km/h in m/s
                            }

                            _heading = navUtils.getHeading(lastAtt["lat"].value, lastAtt["lon"].value, att["lat"].value, att["lon"].value);
                            _speed = (_dist / ((_useTimestamp - _useLastTimestamp) / 1000)).toFixed(2);

                            if (!_lastTimestamp) {
                                //on YOURS routes, make sure we have at least one update a second
                                _tempTimestamp = _useLastTimestamp;

                                while (_useTimestamp - _tempTimestamp > 1000) {
                                    _tempTimestamp += 1000;
                                    _lastPosition = track[track.length - 1].coords;
                                    _tempPosition = navUtils.simulateTravel(_lastPosition.latitude, _lastPosition.longitude, _heading, _speed);
                                    track.push({
                                        coords: {
                                            latitude: _tempPosition.latitude,
                                            longitude: _tempPosition.longitude,
                                            altitude: _ele ? _ele.innerText : 0,
                                            accuracy: 150,
                                            altitudeAccuracy: 80,
                                            heading: _heading,
                                            speed: _speed
                                        },
                                        timestamp: _tempTimestamp
                                    });
                                }
                            }
                        }

                        track.push({
                            coords: {
                                latitude: att["lat"].value,
                                longitude: att["lon"].value,
                                altitude: _ele ? _ele.innerText : 0,
                                accuracy: 150,
                                altitudeAccuracy: 80,
                                heading: _heading,
                                speed: _speed
                            },
                            timestamp: _useTimestamp
                        });
                    }
                });
            };
            reader.onerror = function (e) {
                fail(e);
            };
            reader.readAsText(file.target.files[0], "UTF-8");
        }

        function replayGpxTrack() {
            if (_replayingGpxFile) {
                _haltGpxReplay = true;
                gpxGo.innerText = constants.GEO.GPXGO_LABELS.GO;
            }
            else {
                if (track.length > 0) {
                    _haltGpxReplay = false;
                    gpxGo.innerText = constants.GEO.GPXGO_LABELS.STOP;

                    latitude.value = track[0].coords.latitude;
                    longitude.value = track[0].coords.longitude;
                    altitude.value = track[0].coords.altitude;
                    accuracy.value = track[0].coords.accuracy;
                    altitudeAccuracy.value = track[0].coords.altitudeAccuracy;
                    heading.value = track[0].coords.heading;
                    speed.value = track[0].coords.speed;

                    updateGeo();
                    updateHeadingValues();
                    _triggerEvent();

                    moveNextGpxTrack(1);
                }
            }
        }

        function moveNextGpxTrack(i)
        {
            if (_haltGpxReplay) {
                _replayingGpxFile = false;
                _haltGpxReplay = false;
                console.log("Ripple :: User interrupted replay of GPX file (Aye Captain, answers All Stop.)");
            }
            else {
                _replayingGpxFile = true;
                var _timeMultiplier = !isNaN(gpxMultiplier.value) ? gpxMultiplier.value : 1,
                _step = 0,
                _interval = 0;

                while (_interval < 250) {
                    _step++;
                    if ((i + _step) >= track.length) { break; }
                    _interval = (track[i + _step].timestamp - track[i].timestamp) / _timeMultiplier;
                }

                gpxReplayStatus.textContent = (_interval / 1000).toFixed(2) + "s (" + (_interval / 1000 * _timeMultiplier).toFixed(2) + "s realtime), " + (i + 1) + " of " + track.length + " (stepping " + _step + " at " + _timeMultiplier + "x)";

                setTimeout(function () {
                    latitude.value = track[i].coords.latitude;
                    longitude.value = track[i].coords.longitude;
                    altitude.value = track[i].coords.altitude;
                    accuracy.value = track[i].coords.accuracy;
                    altitudeAccuracy.value = track[i].coords.altitudeAccuracy;
                    heading.value = track[i].coords.heading;
                    speed.value = track[i].coords.speed;

                    updateGeo();
                    updateHeadingValues();
                    _triggerEvent();

                    if (track[i + _step]) {
                        moveNextGpxTrack(i + _step);
                    }
                    else {
                        if (i < track.length - 1) {
                            moveNextGpxTrack(track.length - 1);
                        }
                        else {
                            _replayingGpxFile = false;
                            gpxGo.innerText = constants.GEO.GPXGO_LABELS.GO;
                            console.log("Ripple :: Finished replaying GPX file (Arriving at our destination, assuming standard orbit Captain.)");
                        }
                    }
                }, _interval);
            }
        }

        // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847 (double HACK!!!)
        if (platform.current().id === 'phonegap' ||
            platform.current().id === 'webworks' ||
            platform.current().id === 'cordova') {
            // make the fields visible
            jQuery("#geo-cellid-container").hide();
            jQuery("#geo-heading-container").show();
            jQuery("#geo-speed-container").show();
        }
        else {
            jQuery("#geo-cellid-container").show();
            jQuery("#geo-heading-container").hide();
            jQuery("#geo-speed-container").hide();
        }

        _gpsMapZoomLevel = db.retrieve(constants.GEO.MAP_ZOOM_KEY) || 14;

        jQuery("#geo-map-zoom-decrease").bind("click", function () {
            _updateGpsMapZoom(false);
        });

        jQuery("#geo-map-zoom-increase").bind("click", function () {
            _updateGpsMapZoom(true);
        });

        utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.LATITUDE), updateGeo);
        utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.LONGITUDE), updateGeo);
        utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.ALTITUDE), updateGeo);
        utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.ACCURACY), updateGeo);
        utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.ALTITUDE_ACCURACY), updateGeo);
        utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.CELL_ID), updateGeo);

        jQuery("#play-route-speed-label").html(jQuery("#play-route-speed").val() + 'x');
        jQuery("#play-route-speed").bind("change", function () {
            jQuery("#play-route-speed-label").html(jQuery("#play-route-speed").val() + 'x');
        });
        jQuery("#clear-route-btn").bind("click", function () {
            clearRoute();
        });
        jQuery("#set-route-btn").bind("click", function () {
            setRoute();
        });
        jQuery("#play-route-btn").bind("click", function () {
            playRoute();
        });
        jQuery("#back-route-btn").bind("click", function () {
            skipTo("start");
        });
        jQuery("#forward-route-btn").bind("click", function () {
            skipTo("end");
        });

        jQuery("#" + GEO_OPTIONS.DELAY).bind("change", function () {
            updateGeo();
            delayLabel.innerText = delay.value;
        });
        jQuery("#" + GEO_OPTIONS.TIMEOUT).bind("click", function () {
            updateGeo();
        });
        jQuery("#" + GEO_OPTIONS.GPXFILE).bind("change", function (a) {
            loadGpxFile(null, null, [a]);
        });
        jQuery("#" + GEO_OPTIONS.GPXGO).bind("click", function () {
            replayGpxTrack();
        });

        // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847 (double HACK!!!)
        if (platform.current().id === 'phonegap' || platform.current().id === 'webworks' || platform.current().id === 'cordova') {
            jQuery("#" + GEO_OPTIONS.HEADING).bind("change", function () {
                updateGeo();
                updateHeadingValues();
            });

            utils.bindAutoSaveEvent(jQuery("#" + GEO_OPTIONS.SPEED), updateGeo);
            heading.value =       positionInfo.heading;
            speed.value =         positionInfo.speed;
        }

        initMap();
        if (navigator.onLine === false) {
            jQuery("#disable_geo_panel").show();
        }
        jQuery(window).bind("online", function () {
            jQuery("#disable_geo_panel").hide();
            console.log("ONLINE");
        });
        jQuery(window).bind("offline", function () {
            jQuery("#disable_geo_panel").show();
            console.log("OFFLINE");
        });

        initializeValues();
        _initTimeZone();

        event.on(positionEvent, function () {
            _updateGpsMap();
        });

        _triggerEvent();

        function _triggerEvent() {
            event.trigger(positionEvent, [{
                latitude: latitude.value,
                longitude: longitude.value,
                altitude: altitude.value,
                accuracy: accuracy.value,
                altitudeAccuracy: altitudeAccuracy.value,
                heading: heading ? heading.value : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
                speed: speed ? speed.value : 0, // HACK: see techdebt http://www.pivotaltracker.com/story/show/5478847
                cellID: cellID.value,
                timeStamp: new Date()
            }]);
        }
    }
};

});
define('ripple/ui/plugins/goodVibrations', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants');

module.exports = {
    vibrateDevice: function (milliseconds) {
        var node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
            x, times;

        times = Math.floor(milliseconds / 100);

        for (x = 1; x <= times; x++) {
            node.animate({ left: -10 }, 5)
            .animate({ left: 0 }, 1)
            .animate({ left: 10 }, 5)
            .animate({ left: 0 }, 1);

            node.animate({ top: -10 }, 5)
            .animate({ top: 0 }, 1)
            .animate({ top: 10 }, 5)
            .animate({ top: 0 }, 1);
        }
    },
    shakeDevice: function (times) {
        var node = jQuery("#" + constants.COMMON.DEVICE_CONTAINER),
            x;

        for (x = 1; x <= times; x++) {
            node.animate({ left: -25 }, 50)
            .animate({ left: 0 }, 30)
            .animate({ left: 25 }, 50)
            .animate({ left: 0 }, 30);
        }
    }
};

});
define('ripple/ui/plugins/information', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    devices = require('ripple/devices'),
    event = require('ripple/event'),
    platform = require('ripple/platform'),
    utils = require('ripple/utils'),
    app = require('ripple/app'),
    tooltip = require('ripple/ui/plugins/tooltip'),
    db = require('ripple/db');

function _updateInformationView() {
    var infoPane = document.getElementById(constants.COMMON.INFO_SECTION),
        infoList = [],
        device = devices.getCurrentDevice(),
        tempString = "",
        widgetInfo = app.getInfo(),
        layout = db.retrieve("layout") || "portrait",
        _systemSettings = db.retrieveObject("tizen2-systemsetting") || {"HOME_SCREEN": "", "LOCK_SCREEN": "", "INCOMING_CALL": "", "NOTIFICATION_EMAIL": ""};

    //TODO: refactor this stuff to grab info from API, do this in a loop rather then hardcoded. Better DOM injection approach. This is legacy code

    infoList.push('<section id=\"information-banner\" style=\"display:none\"><img id=\"information-banner-icon\" width=\"16px\" height=\"16px\"/> <span id=\"information-banner-count\"></span></section>');

    if (widgetInfo.icon) {
        infoList.push('<section style="position: absolute; left: 260px;"  class="information-widgeticon"><img class="ui-corner-all" width="64" src="' + utils.appLocation() + widgetInfo.icon + '" alt="widget icon"/></section>');
    }
    if (widgetInfo.name) {
        infoList.push("<section><div id=\"systemSummaryAppNameContainer\" style=\"width:240px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">App Name: </label><span class=\"text-is-selectable\">" + widgetInfo.name + "</span></div></section>");
        //Update Title
        document.title = "Web Simulator - " + widgetInfo.name;
    }

    infoList.push('<table class="tf_panel-table" style="border-spacing: 0px;">');
   
    if (widgetInfo.version) {
        infoList.push('<section class="information-widgetversion"><label class=\"ui-text-label\">Version: </label><span class="text-is-selectable">' + widgetInfo.version + '</span></section>');
    }
    infoList.push("<section><label class=\"ui-text-label\">Platform: </label><span class=\"text-is-selectable\">" + platform.current().name + "</span></section>");
    infoList.push("<section><label class=\"ui-text-label\">Device: </label><span class=\"text-is-selectable\">" + device.name + "</span></section>");
    infoList.push("<section><label class=\"ui-text-label\">OS: </label><span class=\"text-is-selectable\">" + device.osName + " " + device.osVersion + "</span></section>");
    infoList.push("<section><label class=\"ui-text-label\">Manufacturer: </label><span class=\"text-is-selectable\">" + device.manufacturer + "</span></section>");
    infoList.push("<section><label class=\"ui-text-label\">Screen: </label><span class=\"text-is-selectable\">" + device.screen.width + "x" + device.screen.height + "</span></section>");
    infoList.push("<section><label class=\"ui-text-label\">Viewport: </label><span class=\"text-is-selectable\">" + device.viewPort[layout].width.toFixed(0) + "x" + device.viewPort[layout].height.toFixed(0) + "</span></section>");
    infoList.push("<section><label class=\"ui-text-label\">Density: </label><span class=\"text-is-selectable\">" + device.ppi + " PPI</span></section>");
    infoList.push("<section><label class=\"ui-text-label\" style=\"float:left; padding-top: 0px; \">User Agent: </label>" +
                    "<div class=\"text-is-selectable\" style=\"padding-left: 80px\">" + device.userAgent + "</div></section>");

    if (device.notes) {
        utils.forEach(device.notes, function (note) {
            tempString += "<li class=\"text-is-selectable\">" + note + "</li>";
        });
        infoList.push("<section><div style=\"clear:both;\"></div><label class=\"ui-text-label\">Notes: </label><ul>" + tempString + "</ul></section>");
    }

    infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryHomeScreenContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Home Screen Image: </label><span>" + _systemSettings["HOME_SCREEN"] + "</span></div></section>");
    infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryLockScreenContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Lock Screen Image: </label><span>" + _systemSettings["LOCK_SCREEN"] + "</span></div></section>");
    infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryInComingCallContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Incoming Call Number: </label><span>" + _systemSettings["INCOMING_CALL"] + "</span></div></section>");
    infoList.push("<section><div style=\"clear:both;\"></div><div id=\"systemSummaryNotiEMailContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">Notification Email: </label><span>" + _systemSettings["NOTIFICATION_EMAIL"] + "</span></div></section>");
    infoList.push("<section><div style=\"clear:both;\"></div><div id=\"NFCExclusiveModeContainer\" style=\"width:320px; height:20px; overflow:hidden; white-space: nowrap; text-overflow: ellipsis;\" ><label class=\"ui-text-label\">NFC Exclusive Mode: </label><span id=\"NFCExclusiveModeValue\">false</span></div></section>");
    infoPane.innerHTML = infoList.join("");

    // Make tooltip if it needed
    if ((jQuery("#systemSummaryAppNameContainer").children("label").width() + jQuery("#systemSummaryAppNameContainer").children("span").width()) > 240) {
        tooltip.create("#systemSummaryAppNameContainer", jQuery("#systemSummaryAppNameContainer").children("span").text());
    }
    if ((jQuery("#systemSummaryHomeScreenContainer").children("label").width() + jQuery("#systemSummaryHomeScreenContainer").children("span").width()) > 320) {
        tooltip.create("#systemSummaryHomeScreenContainer", jQuery("#systemSummaryHomeScreenContainer").children("span").text());
    }
    if ((jQuery("#systemSummaryLockScreenContainer").children("label").width() + jQuery("#systemSummaryLockScreenContainer").children("span").width()) > 320) {
        tooltip.create("#systemSummaryLockScreenContainer", jQuery("#systemSummaryLockScreenContainer").children("span").text());
    }
    if ((jQuery("#systemSummaryInComingCallContainer").children("label").width() + jQuery("#systemSummaryInComingCallContainer").children("span").width()) > 320) {
        tooltip.create("#systemSummaryInComingCallContainer", jQuery("#systemSummaryInComingCallContainer").children("span").text());
    }
    if ((jQuery("#systemSummaryNotiEMailContainer").children("label").width() + jQuery("#systemSummaryNotiEMailContainer").children("span").width()) > 320) {
        tooltip.create("#systemSummaryNotiEMailContainer", jQuery("#systemSummaryNotiEMailContainer").children("span").text());
    }
}

function _updateBanner(icon, count) {
    var bannerSection = document.getElementById("information-banner"),
        iconImg  = document.getElementById("information-banner-icon"),
        countSpan = document.getElementById("information-banner-count");

    if (icon && (count === undefined || count !== 0)) {
        count = count || "";
        jQuery("#" + constants.COMMON.INFO_SECTION).show();
        jQuery(bannerSection).fadeToggle(1000);
        jQuery(bannerSection).fadeIn(1000);
    }
    else {
        jQuery(bannerSection).fadeOut(1000);
    }

    iconImg.src = utils.appLocation() + icon;
    if (icon.indexOf("http") === 0) {
        iconImg.src = icon;
    }

    countSpan.innerHTML = count > 99 ? "99+" : count;
}

module.exports = {
    panel: {
        domId: "information-container",
        collapsed: false,
        pane: "left",
        titleName: "System Summary",
        display: true
    },
    initialize: function () {
        event.on("BannerUpdated", function (icon, count) {
            _updateBanner(icon, count);
        });

        event.on("PlatformChangedEvent", function () {
            _updateInformationView();
        });

        event.on("WidgetInformationUpdated", function () {
            _updateInformationView();
        });
        
        event.on("SystemSettingChanged", function () {
            _updateInformationView();
        });

        event.on("ScreenChangeDimensions", function() {
            _updateInformationView();
        });
        _updateInformationView();
    }
};

});
define('ripple/ui/plugins/invoke', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    event = require('ripple/event');

module.exports = {
    panel: {
        domId: "invoke-container",
        collapsed: true,
        pane: "left"
    },
    initialize: function () {
        document.getElementById("invoke-send")
            .addEventListener("click", function () {
                var invokeInfo = {};

                invokeInfo.uri = document.getElementById("invoke-uri-text").value;
                invokeInfo.source = document.getElementById("invoke-source-text").value;
                invokeInfo.target = document.getElementById("invoke-target-text").value;
                invokeInfo.action = document.getElementById("invoke-action-text").value;
                invokeInfo.type = document.getElementById("invoke-mime-type-text").value;
                invokeInfo.extension = document.getElementById("invoke-extension-text").value;
                invokeInfo.data = document.getElementById("invoke-data-text").value;
                if (invokeInfo.data) {
                    invokeInfo.data = window.btoa(invokeInfo.data);
                }

                event.trigger("AppInvoke", [invokeInfo]);
            }, false);
    }
};

});
define('ripple/ui/plugins/layout', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    db = require('ripple/db'),
    resizer = require('ripple/resizer'),
    devices = require('ripple/devices'),
    event = require('ripple/event');

function _initializeLayout(prev, baton) {
    var layout = db.retrieve("layout"),
        orientation = db.retrieve("deviceOrientation") || "portrait",
        layoutLandscape = document.getElementById(constants.COMMON.ORIENTATION_SELECT_LANDSCAPE_ID),
        layoutPortrait = document.getElementById(constants.COMMON.ORIENTATION_SELECT_PORTRAIT_ID),
        currentDevice = devices.getCurrentDevice(),
        defaultOrientation =  currentDevice ? currentDevice.defaultOrientation : null,
        layoutTypeChanged = false;

    jQuery("#" + constants.COMMON.ORIENTATION_SELECT_LANDSCAPE_ID).bind("click", function () {
        layoutLandscape.setAttribute("class", "layout-selected");
        layoutPortrait.setAttribute("class", "layout-not-selected");
        resizer.rotateDevice("landscape");
        event.trigger("OrientationChanged", ["landscape"], true);
    });

    jQuery("#" + constants.COMMON.ORIENTATION_SELECT_PORTRAIT_ID).bind("click", function () {
        layoutLandscape.setAttribute("class", "layout-not-selected");
        layoutPortrait.setAttribute("class", "layout-selected");
        resizer.rotateDevice("portrait");
        event.trigger("OrientationChanged", ["portrait"], true);
    });

    jQuery("#" + constants.COMMON.MENU_BUTTON).bind("click", function () {
        event.trigger("HardwareKey", [1]);
    });

    jQuery("#" + constants.COMMON.BACK_BUTTON).bind("click", function () {
        event.trigger("HardwareKey", [0]);
    });

    if (!layout) {
        layout = defaultOrientation || "portrait";
        layoutTypeChanged = true;
        resizer.changeLayoutType(layout);
    }

    //Hide the orientation buttons that we don't need for this device
    if (!currentDevice.viewPort.landscape) {
        layoutLandscape.setAttribute("style", "display:none");
    }

    if (!currentDevice.viewPort.portrait) {
        layoutPortrait.setAttribute("style", "display:none");
    }

    if (layout && layout === "portrait") {
        layoutLandscape.setAttribute("class", "layout-not-selected");
        layoutPortrait.setAttribute("class", "layout-selected");
    }
    else if (layout && layout === "landscape") {
        layoutLandscape.setAttribute("class", "layout-selected");
        layoutPortrait.setAttribute("class", "layout-not-selected");
    }

    if (!layoutTypeChanged) {
        resizer.resize(currentDevice);
    }

    if (orientation === "portrait") {
        layoutLandscape.setAttribute("class", "layout-not-selected");
        layoutPortrait.setAttribute("class", "layout-selected");
    } else {
        layoutLandscape.setAttribute("class", "layout-selected");
        layoutPortrait.setAttribute("class", "layout-not-selected");
    }
    resizer.rotateDevice(orientation);
}

module.exports = {
    initialize: _initializeLayout
};

});
define('ripple/ui/plugins/messaging', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    utils = require('ripple/utils'),
    _type = {
        sms: "SMS",
        mms: "MMS",
        email: "E-mail"
    },
    _filename_suffix = 0,
    _attachments = [];

function _getAttachmentFileName() {
    return "attach" + _filename_suffix + ".txt";
}

module.exports = {
    panel: {
        domId: "messaging-container",
        collapsed: true,
        pane: "left",
        titleName: "Messaging",
        display: true
    },
    initialize: function () {
        document.getElementById("messaging-send")
            .addEventListener("click", function () {
                var number = document.getElementById("messaging-sms-number").value,
                    text = document.getElementById("messaging-text").value,
                    type = document.getElementById("messaging-type").value,
                    message = {
                        type: type,
                        body: text,
                        from: number,
                        time: new Date(),
                        attachments: _attachments
                    };

                event.trigger("MessageReceived", [message]);
                
                _attachments = [];
/* TODO: add back when attachment is finished
                document.getElementById("messaging-attachments").innerHTML = "";
*/
                _filename_suffix = 0;
            }, false);

/* TODO: add back when attachment is finished
        document.getElementById("messaging-attach")
            .addEventListener("click", function () {
                var attachedFile, attachedFileCheckbox, attachedFileName;
                if (_filename_suffix > 0)
                    return;
                _attachments.push({filename: _getAttachmentFileName(), content: document.getElementById("messaging-attachment-content").value});

                attachedFile = document.getElementById("messaging-attachments").insertRow(0);
                attachedFileName = attachedFile.insertCell(0);
                attachedFileCheckbox = attachedFile.insertCell(1);
                attachedFileName.innerHTML = _attachments[_filename_suffix].filename;
//                attachedFileCheckbox.innerHTML = '<input type="checkbox" value="' + _filename_suffix + '">';

                document.getElementById("messaging-attachment-content").value = "";
                _filename_suffix++;
            }, false);

        document.getElementById("messaging-detach")
            .addEventListener("click", function () {
                _attachments = [];
                document.getElementById("messaging-attachments").innerHTML = "";
                _filename_suffix = 0;
            }, false);
*/
        event.on("OutsideMessageReceived", function (message) {
            var numRecipients = 0,
                i = 0,
                recipients = [],
                recipientsStatus = {},
                strRecipients = document.getElementById("messaging-recipients").value;

            recipientsStatus.id = message.id;
            recipientsStatus.msg = message.msg;
            for (i in message.to) {
                recipientsStatus[message.to[i]] = true;
                recipients.push(message.to[i]);
            }
            for (i in message.cc) {
                recipientsStatus[message.cc[i]] = true;
                recipients.push(message.cc[i]);
            }
            for (i in message.bcc) {
                recipientsStatus[message.bcc[i]] = true;
                recipients.push(message.bcc[i]);
            }
            numRecipients = recipients.length;
            strRecipients = recipients.join(",");
            event.trigger("MessageSent", [recipientsStatus]);
            document.getElementById("messaging-received").innerHTML = "" + numRecipients + " recipient(s)" + " delivered";
            document.getElementById("messaging-recipients").value = strRecipients;
            document.getElementById("received-message-box").value = message.body;
        });
        
        document.getElementById("messaging-clear")
            .addEventListener("click", function () {
                document.getElementById("received-message-box").value = "";
                document.getElementById("messaging-received").innerHTML = "";
            }, false);
        
        utils.forEach(_type, function (msgTypeText, msgType) {
            var typeNode = utils.createElement("option", {
                    "innerText": msgTypeText,
                    "value": msgType
                });

            document.getElementById("messaging-type").appendChild(typeNode);
        });
    }
};

});
define('ripple/ui/plugins/multimedia', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    event = require('ripple/event'),
    volumeField = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_FIELD_ID),
    volume = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_SLIDER_ID);

module.exports = {
    panel: {
        domId: "multimedia-container",
        collapsed: true,
        pane: "left"
    },
    initialize: function () {
        var volumeField = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_FIELD_ID),
            volume = document.getElementById(constants.COMMON.MULTIMEDIA_VOLUME_SLIDER_ID);

        event.on("MultimediaVolumeChanged", function (volume) {
            volumeField.innerText = volume > 9 ? volume : "0" + volume;
            if (volume.value !== volume) {
                volume.value = volume;
            }
        });

        volume.addEventListener('change', function () {
            event.trigger("MultimediaVolumeChanged", [this.value], true);
        }, false);

        event.on("MultimediaAudioStateChanged", function updateIsAudioPlaying(state) {
            document.getElementById(constants.COMMON.MULTIMEDIA_AUDIO_PLAYING_FIELD_ID).innerHTML = state === constants.MULTIMEDIA.AUDIO_STATES.PLAYING;
        });
    }
};

});
define('ripple/ui/plugins/network', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    deviceSettings = require('ripple/deviceSettings'),
    dbinit = require('ripple/platform/tizen/2.0/dbinit'),
    _NFC_TAG = "tizen1.0-nfc-tag",
    _NFC_PEER = "tizen1.0-nfc-peer",
    _NFC_OUTPUT_MESSAGE = "tizen1.0-nfc-output-message",
    _powered = false,
    _isConnected = false,
    _tagNDEF,
    _tagRaw,
    _peerNDEF,
    btNodes,
    _btDeviceTemplate = "",
    _btSimulatedDevs = {},
    _btBluetoothDB;

String.prototype.toCharCode = function () {
    return this.split("").map(function(char) {
        return char.charCodeAt(0);
    });
};

function elementEnableDisableSetting(prop) {
    jQuery("#nfc-attach-msg").text("\xa0");
    jQuery("#nfc-peer-send-msg").text("\xa0");
    if (prop && prop.power !== undefined && prop.power !== null) {
        if (!prop.power) {
            $("#nfc-type").removeAttr("disabled");
        }
    }
    if (prop && prop.connectedState !== undefined && prop.connectedState !== null) {
        if (prop.connectedState) {
            $("#nfc-type").attr("disabled", "disabled");
            $("#nfc-tag-type-text").text($("#nfc-tag-type option:selected").text());
            $("#nfc-tag-type").hide();
            $("#nfc-tag-type-text").show();
            $("#nfc-tag-NDEF-support-text").text($("#nfc-tag-NDEF-support option:selected").text());
            $("#nfc-tag-NDEF-support").hide();
            $("#nfc-tag-NDEF-support-text").show();
            $("#nfc-raw-data").attr("disabled", "disabled");
        } else {
            $("#nfc-type").removeAttr("disabled");
            $("#nfc-tag-type").show();
            $("#nfc-tag-type-text").hide();
            $("#nfc-tag-NDEF-support").show();
            $("#nfc-tag-NDEF-support-text").hide();
            $("#nfc-raw-data").removeAttr("disabled");
        }
    }
}

function _initializeDB() {
    _tagNDEF = {
        type: "GENERIC_TARGET",
        isSupportedNDEF: true,
        ndefSize: 3,
        ndefs: [{
            recordCount: 2,
            records: [{
                tnf: 1,
                type: "TypeA".toCharCode(),
                id: "ID001".toCharCode(),
                payload: "This is 1st payload".toCharCode()
            }, {
                tnf: 1,
                type: "TypeA".toCharCode(),
                id: "ID002".toCharCode(),
                payload: "This is 2nd payload".toCharCode()
            }]
        },
        {
            recordCount: 2,
            records: [{
                tnf: 1,
                type: "TypeA".toCharCode(),
                id: "ID003".toCharCode(),
                payload: "This is 1st payload".toCharCode()
            }, {
                tnf: 1,
                type: "TypeA".toCharCode(),
                id: "ID004".toCharCode(),
                payload: "This is 2nd payload".toCharCode()
            }]
        },
        {
            recordCount: 2,
            records: [{
                tnf: 1,
                type: "TypeA".toCharCode(),
                id: "ID005".toCharCode(),
                payload: "This is 1st payload".toCharCode()
            }, {
                tnf: 1,
                type: "TypeA".toCharCode(),
                id: "ID006".toCharCode(),
                payload: "This is 2nd payload".toCharCode()
            }]
        }]
    };

    _tagRaw = {
        type: "GENERIC_TARGET",
        isSupportedNDEF: false,
        rawData : ""
    };

    _peerNDEF = {
        ndef: {
            recordCount: 2,
            records: [{
                tnf: 1,
                type: "TypeA".toCharCode(),
                id: "ID001".toCharCode(),
                payload: "This is 1st payload".toCharCode()
            }, {
                tnf: 1,
                type: "TypeA".toCharCode(),
                id: "ID002".toCharCode(),
                payload: "This is 2nd payload".toCharCode()
            }]
        }
    };
}

function _initializeElements() {
    jQuery(function () {
        var stop = false,
        wifiRadio = $("#wifi-radio"),
        isSupportNDEF, type;

        // initialize main menus
        wifiRadio.buttonset();

        $("#cellular-radio").buttonset();
        $("#nfc-radio").buttonset();
        $("#bluetooth-radio").buttonset();
        $("#bearer-radio").buttonset();

        $("#wifi-radio1").prop('checked', false);
        $("#wifi-radio2").prop('checked', false);
        if (deviceSettings.retrieve("WIFI_NETWORK.status") === true) {
            $("#wifi-radio1").prop('checked', true);
            $("#wifi-radio1-label").css({'color': '#000000'});
            $("#wifi-radio2-label").css({'color': '#bbbbbb'});
        }
        else {
            $("#wifi-radio2").prop('checked', true);
            $("#wifi-radio1-label").css({'color': '#bbbbbb'});
            $("#wifi-radio2-label").css({'color': '#222222'});
        }
        $("#wifi-radio1").button("refresh");
        $("#wifi-radio2").button("refresh");

        $("#cellular-radio1").prop('checked', false);
        $("#cellular-radio2").prop('checked', false);
        if (deviceSettings.retrieve("CELLULAR_NETWORK.status") === true) {
            $("#cellular-radio1").prop('checked', true);
            $("#cellular-radio1-label").css({'color': '#000000'});
            $("#cellular-radio2-label").css({'color': '#bbbbbb'});
        }
        else {
            $("#cellular-radio2").prop('checked', true);
            $("#cellular-radio1-label").css({'color': '#bbbbbb'});
            $("#cellular-radio2-label").css({'color': '#222222'});
        }

        if (deviceSettings.retrieve("CELLULAR_NETWORK.isFlightMode") === true) {
            $("#cellular-radio1").prop('disabled', true);
            $("#cellular-radio2").prop('disabled', true);
            $("#panel_flight_mode_notice").show();
        }
        else {
            $("#cellular-radio1").prop('disabled', false);
            $("#cellular-radio2").prop('disabled', false);
            $("#panel_flight_mode_notice").hide();
        }

        $("#cellular-radio1").button("refresh");
        $("#cellular-radio2").button("refresh");

        $("#bearer-radio2").prop('checked', true);
        $("#bearer-radio2").button("refresh");

        $("#wifi-radio1").click(function () {
            $("#wifi-radio1-label").css({'color': '#000000'});
            $("#wifi-radio2-label").css({'color': '#bbbbbb'});
            deviceSettings.persist("WIFI_NETWORK.status", true);
            event.trigger("WiFiNetworkStatusChanged", [true]);
        });

        $("#wifi-radio2").click(function () {
            $("#wifi-radio1-label").css({'color': '#bbbbbb'});
            $("#wifi-radio2-label").css({'color': '#222222'});
            deviceSettings.persist("WIFI_NETWORK.status", false);
            event.trigger("WiFiNetworkStatusChanged", [false]);
        });

        $("#cellular-radio1").click(function () {
            $("#cellular-radio1-label").css({'color': '#000000'});
            $("#cellular-radio2-label").css({'color': '#bbbbbb'});
            deviceSettings.persist("CELLULAR_NETWORK.status", true);
            event.trigger("CellularNetworkStatusChanged", [true]);
        });

        $("#cellular-radio2").click(function () {
            $("#cellular-radio1-label").css({'color': '#bbbbbb'});
            $("#cellular-radio2-label").css({'color': '#222222'});
            deviceSettings.persist("CELLULAR_NETWORK.status", false);
            event.trigger("CellularNetworkStatusChanged", [false]);
        });

        $("#nfc-radio1-label").css({'color': '#bbbbbb'});
        $("#nfc-radio2-label").css({'color': '#222222'});

        $("#bluetooth-radio1-label").css({'color': '#bbbbbb'});
        $("#bluetooth-radio2-label").css({'color': '#222222'});

        $("#bearer-radio1-label").css({'color': '#bbbbbb'});
        $("#bearer-radio2-label").css({'color': '#222222'});

        $("#nfc-radio1").click(function () {
            $("#nfc-radio2-label").css({'color': '#bbbbbb'});
            $("#nfc-radio1-label").css({'color': '#222222'});
            $("#nfc-main-container").show();
        });

        $("#nfc-radio2").click(function () {
            $("#nfc-radio1-label").css({'color': '#bbbbbb'});
            $("#nfc-radio2-label").css({'color': '#222222'});
            $("#nfc-main-container").hide();
        });

        $("#bluetooth-radio1").click(function () {
            $("#bluetooth-radio2-label").css({'color': '#bbbbbb'});
            $("#bluetooth-radio1-label").css({'color': '#222222'});
            $("#bluetooth-main-container").show();
        });

        $("#bluetooth-radio2").click(function () {
            $("#bluetooth-radio1-label").css({'color': '#bbbbbb'});
            $("#bluetooth-radio2-label").css({'color': '#222222'});
            $("#bluetooth-main-container").hide();
        });

        $("#bearer-radio1").click(function () {
            $("#bearer-radio2-label").css({'color': '#bbbbbb'});
            $("#bearer-radio1-label").css({'color': '#222222'});
            $("#bearer-main-container").show();
        });

        $("#bearer-radio2").click(function () {
            $("#bearer-radio1-label").css({'color': '#bbbbbb'});
            $("#bearer-radio2-label").css({'color': '#222222'});
            $("#bearer-main-container").hide();
        });

        // initialize nfc
        jQuery("nfc-tag-ndef-container h3").click(function (event) {
            if (stop) {
                event.stopImmediatePropagation();
                event.preventDefault();
                stop = false;
            }
        });
        jQuery("#nfc-tag-ndef-container").accordion("destroy").accordion({
            header: "> div > h3",
            autoHeight: false
        });
        jQuery("nfc-nfcpeer h3").click(function (event) {
            if (stop) {
                event.stopImmediatePropagation();
                event.preventDefault();
                stop = false;
            }
        });
        jQuery("#nfc-nfcpeer").accordion("destroy").accordion({
            header: "> div > h3",
            autoHeight: false
        });
        jQuery("#nfc-tag-NDEF-support").bind("change", function () {
            isSupportNDEF = jQuery("#nfc-tag-NDEF-support").val();
            if (isSupportNDEF === "Yes") {
                jQuery("#nfc-tag-ndef-container").fadeIn();
                jQuery("#nfc-tag-raw-container").hide();
            } else {
                jQuery("#nfc-tag-ndef-container").hide();
                jQuery("#nfc-tag-raw-container").fadeIn();
            }
        });
        jQuery("#nfc-type").bind("change", function () {
            type = jQuery("#nfc-type").val();
            if (type === "Tag") {
                jQuery("#nfc-nfctag").fadeIn();
                jQuery("#nfc-nfcpeer").hide();
            } else {
                jQuery("#nfc-nfctag").hide();
                jQuery("#nfc-nfcpeer").fadeIn();
            }
            elementEnableDisableSetting();
        });
        jQuery("#nfc-power").bind("change", function () {
            var status;
            status = jQuery("#nfc-power").val() === "On" ? true : false;
            if (status)
                jQuery("#nfc").show();
            event.trigger("nfc-power-setting", [status]);
        });
        jQuery("#nfc-attach").bind("click", function () {
            var type, isAttached;
            isAttached = jQuery("#nfc-attach").children().text() === "Attach" ? true : false;
            jQuery("#nfc-attach-msg").text("\xa0");

            if (!_powered && isAttached) {
                jQuery("#nfc-attach-msg").text("Power:Off, attach won't work");
                return;
            }
            type = jQuery("#nfc-type").val();
            event.trigger("nfc-attach-setting", [type, isAttached]);
        });
        jQuery("#nfc-peer-send").bind("click", function () {
            jQuery("#nfc-peer-send-msg").text("\xa0");
            if (!_isConnected) {
                jQuery("#nfc-peer-send-msg").text("Disconnected. Send won't work");
                return;
            }
            db.saveObject(_NFC_PEER, _peerNDEF);
            event.trigger("nfc-peer-sending-ndef", []);
        });

        // Initialize network bearer selection
        $("#bearer-cellular-radio1").prop('checked', true);
        $("#bearer-unknown-radio2").prop('checked', true);
        $("#bearer-cellular-radio1").button("refresh");
        $("#bearer-unknown-radio2").button("refresh");

        $("#bearer-cellular-radio2").click(function () {
            $("#bearer-cellular button").click();
        });

        $("#bearer-unknown-radio2").click(function () {
            $("#bearer-unknown button").click();
        });
    });
}

function _btRender() {
    var devicesHTML, btHtmlContent = "";

    utils.forEach(_btSimulatedDevs, function (item) {
        var uuidsHTML = "", firstService = null;

        utils.forEach(item.services, function (s, index) {
            if (!firstService) {
                firstService = s;
            }
            uuidsHTML += '<option value="' + index + '">' + s.name + '</option>';
        });

        devicesHTML = _btDeviceTemplate.replace(/#name/g, item.name)
        .replace(/#address/g, item.address)
        .replace(/#class-major/, item.deviceClass.majorName)
        .replace(/#class-minor/, item.deviceClass.minorName)
        .replace(/#class-service/, item.deviceClass.servicesName.join(","))
        .replace(/#bonded/, "No")
        .replace(/#trusted/, item.isTrusted ? "Yes" : "No")
        .replace(/#connected/, "No")
        .replace(/#uuids/, uuidsHTML)
        .replace(/#service-uuid/, firstService.uuid)
        .replace(/#service-protocol/, firstService.protocol)
        .replace(/#service-state/, firstService.state || "CLOSED")
        .replace(/#id/g, item.address.replace(/:/g, ""));

        btHtmlContent += devicesHTML;
    });

    $("#network-bt-box").accordion("destroy");
    $("#network-bt-box").html(btHtmlContent).accordion({
        active : false,
        collapsible : true,
        autoHeight : false
    });
}

function _btRemove(index) {
    delete _btSimulatedDevs[index];
    db.saveObject("bt-simulated-devices", _btSimulatedDevs);
    event.trigger("bt-simulated-devices-changed", []);
    _btRender();
}

function _bearerRelease(type, idBearer, evNetworkDisconnected) {
    if ($("#bearer-row-" + idBearer).length > 0) {
        $("tr[id='bearer-row-" + idBearer + "']").remove();
    }

    event.trigger(evNetworkDisconnected);

    $("#bearer-" + type + " tr:even").css("background-color", "white");
    $("#bearer-" + type + " tr:odd").css("background-color", "whitesmoke");
}

module.exports = {
    panel: {
        domId: "network-container",
        collapsed: true,
        pane: "left",
        titleName: "Network Management",
        display: true
    },
    initialize: function () {
        _initializeDB();
        _initializeElements();

        // Events for nfc module
        event.on("nfc-power-changed", function (status) {
            _powered = status;
            if (_powered === true) {
                $("#nfc-power").val("On");
            } else {
                $("#nfc-power").val("Off");
            }
            elementEnableDisableSetting({power: status});
        });
        event.on("nfc-connectedState-changed", function (state) {
            var i, type, isSupportedNDEF, str, bytes = [];
            _isConnected = state;
            elementEnableDisableSetting({connectedState: state});
            type = jQuery("#nfc-type").val();
            if (state) {
                jQuery("#nfc-attach").children().text("Detach");
                jQuery("#nfc-tag-connection").text("Connected");
                jQuery("#nfc-peer-connection").text("Connected");
                if (type === "Tag") {
                    isSupportedNDEF = jQuery("#nfc-tag-NDEF-support").val() === "Yes" ? true : false;
                    if (isSupportedNDEF) {
                        _tagNDEF.type = jQuery("#nfc-tag-type").val();
                        db.saveObject(_NFC_TAG, _tagNDEF);
                    } else {
                        _tagRaw.type = jQuery("#nfc-tag-type").val();
                        str = jQuery("#nfc-raw-data").val();
                        for (i = 0; i < str.length; i++) {
                            bytes.push(str.charCodeAt(i));
                        }
                        _tagRaw.rawData = bytes;
                        db.saveObject(_NFC_TAG, _tagRaw);
                    }
                    event.trigger("nfc-tag-send", [true]);
                } else {
                    event.trigger("nfc-peer-send", [true]);
                }
            } else {
                jQuery("#nfc-attach").children().text("Attach");
                jQuery("#nfc-tag-connection").text("Disconnected");
                jQuery("#nfc-peer-connection").text("Disconnected");
                jQuery("#nfc-output").text("");
                jQuery("#nfc-output-table").hide();
                if (type === "Tag") {
                    event.trigger("nfc-tag-send", [false]);
                } else {
                    event.trigger("nfc-peer-send", [false]);
                }
            }
        });
        event.on("nfc-output-msg", function () {
            var msg;
            msg = db.retrieve(_NFC_OUTPUT_MESSAGE);
            jQuery("#nfc-output").text(msg);
            jQuery("#nfc-output-table").show();
        });

        // Events for bluetooth module
        event.on("bluetoothPowerState", function (state) {
            if (state) {
                $("#bluetooth-radio1").click();
            } else {
                $("#bluetooth-radio2").click();
            }
        });
        event.on("bt-adapter-name-changed", function (name) {
            $("#bt-adapter-name").text(name);
        });
        event.on("bt-adapter-power-changed", function (state) {
            if (state) {
                $("#bt-adapter-power").text("On");
            } else {
                $("#bt-adapter-power").text("Off");
            }
        });
        event.on("bt-adapter-visible-changed", function (state) {
            if (state) {
                $("#bt-adapter-visible").text("On");
            } else {
                $("#bt-adapter-visible").text("Off");
            }
        });
        event.on("bt-device-bonded-changed", function (addr, isBonded) {
            var str = "No";
            if (isBonded) {
                str = "Yes";
            }
            jQuery("#bonded-" + addr.replace(/:/g, "")).html(str);
        });
        event.on("bt-device-connected-changed", function (addr, isConnected) {
            var str = "No";
            if (isConnected) {
                str = "Yes";
            }
            jQuery("#connected-" + addr.replace(/:/g, "")).html(str);
        });
        event.on("bt-service-state-changed", function (addr, uuid, state) {
            var str = "CLOSED";
            if (state) {
                str = "OPEN";
            }
            _btSimulatedDevs[addr].services[uuid].state = str;
            jQuery("#service-state-" + addr.replace(/:/g, "")).html(str);
        });
        event.on("bt-service-write-msg", function (addr, uuid, data) {
            var msg = "", uuidNow;
            utils.forEach(data, function (char) {
                msg += String.fromCharCode(char);
            });
            uuidNow = jQuery("#network-bt-uuid-" + addr.replace(/:/g, "")).html();
            if (uuidNow === uuid) {
                jQuery("#service-receive-textarea-" + addr.replace(/:/g, "")).html(msg);
            }
        });

        // Event for network bearer selection module
        event.on("NetworkRequest", function (networkType, domainName) {
            var type = networkType.toLowerCase(), name, idBearer,
                evNetworkOpened       = "NO_" + networkType + "_" + domainName,
                evNetworkDisconnected = "ND_" + networkType + "_" + domainName;

            if (!$("#bearer-" + type + "-radio1").prop("checked")) {
                event.trigger(evNetworkOpened, [false]);
                event.trigger(evNetworkDisconnected);

                return;
            }

            name = domainName.replace(/\./, "");
            idBearer = type + '-' + name;

            if ($("#bearer-row-" + idBearer).length <= 0) {
                $("#bearer-" + type).append("<tr id='bearer-row-" + idBearer + "'>" +
                     "<td>&nbsp<lable class='ui-text-label'>" + domainName + "</label></td>" +
                     "<td><button id='bearer-btn-" + idBearer + "'>X</button>&nbsp&nbsp</td>" +
                     "</tr>");

                $("#bearer-btn-" + idBearer).click(function () {
                    _bearerRelease(type, idBearer, evNetworkDisconnected);
                });

                $("#bearer-" + type + " tr:even").css("background-color", "white");
                $("#bearer-" + type + " tr:odd").css("background-color", "whitesmoke");
            }

            event.trigger(evNetworkOpened, [true]);
        });

        event.on("NetworkRelease", function (networkType, domainName) {
            var type = networkType.toLowerCase(),
                name = domainName.replace(/\./, ""),
                idBearer = type + '-' + name,
                evNetworkDisconnected = "ND_" + networkType + "_" + domainName;

            _bearerRelease(type, idBearer, evNetworkDisconnected);
        });

        // Update UI for Flight Mode changing
        event.on("FlightModeChanged", function (value) {
            if (value === true) {
                $("#cellular-radio1").prop('disabled', true);
                $("#cellular-radio2").prop('disabled', true);
                $("#panel_flight_mode_notice").show();
            }
            else {
                $("#cellular-radio1").prop('disabled', false);
                $("#cellular-radio2").prop('disabled', false);
                $("#panel_flight_mode_notice").hide();
            }

            $("#cellular-radio1").button("refresh");
            $("#cellular-radio2").button("refresh");
        });

        $("#bt-adapter-name").text(db.retrieveObject("tizen1-db-bluetooth_adapter-name") || "Tizen BT Adapter");
        _btDeviceTemplate = $("#network-bt-template").html();
        $("#network-bt-box").empty();
        btNodes = jQuery("#network-bt-device-select");
        btNodes.html("");

        _btBluetoothDB = dbinit.Bluetooth;
        utils.forEach(_btBluetoothDB, function (item, index) {
            btNodes.append(utils.createElement("option", {
                "value": index,
                "innerText": item.name
            }));
        });

        jQuery("#network-bt-nearby-btn").click(function () {
            var index;
            index = jQuery("#network-bt-device-select").val();
            if (_btSimulatedDevs[index]) {
                return;
            }
            _btSimulatedDevs[index] = _btBluetoothDB[index];
            db.saveObject("bt-simulated-devices", _btSimulatedDevs);
            event.trigger("bt-simulated-devices-changed", []);
            _btRender();
        });
        $(".network-bt-remove-btn").live("click", function () {
            _btRemove(this.id);
        });
        $(".network-bt-send-btn").live("click", function () {
            var msg = jQuery("#service-transfer-textarea-" + this.id.replace(/:/g, "")).val(),
            uuid = jQuery("#network-bt-uuid-" + this.id.replace(/:/g, "")).html();
            event.trigger("bt-service-rawdata-received", [this.id, uuid, msg]);
        });
        $(".network-bt-service-select").live("change", function () {
            var uuid = this.children[this.selectedIndex].value,
            index = this.id,
            addr,
            service;
            addr = index.replace(/:/g, "");
            service = _btSimulatedDevs[index].services[uuid];
            jQuery("#network-bt-uuid-" + index.replace(/:/g, "")).html(service.uuid);
            jQuery("#network-bt-protocol-" + index.replace(/:/g, "")).html(service.protocol);
            jQuery("#service-state-" + index.replace(/:/g, "")).html(service.state || "CLOSED");
            jQuery("#service-transfer-textarea-" + addr).val("");
            jQuery("#service-receive-textarea-" + addr).html("");
        });

        //Default "Tizen Phone" is nearby
        //_btSimulatedDevs["00:02:60:00:05:63"] = _btBluetoothDB["00:02:60:00:05:63"];
        _btSimulatedDevs = db.retrieveObject("bt-simulated-devices") || {};
        if (Object.keys(_btSimulatedDevs).length === 0) {
            for (var address in _btBluetoothDB) {
                _btSimulatedDevs[address] = _btBluetoothDB[address];
                break;
            }

            db.saveObject("bt-simulated-devices", _btSimulatedDevs);
        }

        _btRender();
    }
};

});
define('ripple/ui/plugins/notifications', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    _notificationUIStack,
    _notificationTemplate = "";

function _remove(id) {
    delete _notificationUIStack[id];
    db.saveObject("posted-notifications", _notificationUIStack);
    event.trigger("refreshNotificationStack", [], true);
    _render();
}

function _removeAll() {
    _notificationUIStack = {};
    db.saveObject("posted-notifications", _notificationUIStack);
    event.trigger("refreshNotificationStack", [], true);
    $("#notification-box").empty();
    $("#notification-box").append('<div style="color:#666666;">(Empty notification.)</div>');
    $("#remove-all-notifications-btn").hide();
}

function _render() {
    var notificationHTML = "",
        htmlContent = "";

    utils.forEach(_notificationUIStack, function (item) {
        notificationHTML = _notificationTemplate.replace(/#id/g, item.id)
            .replace(/#title/g, item.title)
            .replace(/#content/, item.content ? item.content : "")
            .replace(/#type/, item.type)
            .replace(/#statusType/, item.statusType)
            .replace(/#postedTime/, item.postedTime)
            .replace(/#iconPath/, item.iconPath ? item.iconPath : "")
            .replace(/#subIconPath/, item.subIconPath ? item.subIconPath : "")
            .replace(/#number/, item.number ? item.number : "")
            .replace(/#detailInfo/, item.detailInfo ? item.detailInfo.join() : "")
            .replace(/#backgroundImagePath/, item.backgroundImagePath ? item.backgroundImagePath : "")
            .replace(/#thumbnails/, item.thumbnails ? item.thumbnails.join() : "")
            .replace(/#soundPath/, item.soundPath ? item.soundPath : "")
            .replace(/#vibration/, item.vibration !== undefined ? (item.vibration === true ? "true" : "false") : "")
            .replace(/#appControl/, item.appControl ? item.appControl : "")
            .replace(/#appId/, item.appId ? item.appId : "")
            .replace(/#progressType/g, item.progressType ? item.progressType: "")
            .replace(/#progressValue/, (item.statusType === "PROGRESS" && item.progressType === "PERCENTAGE" && item.progressValue) ? item.progressValue.toString() + "%" : "")
            .replace(/#progressBarValue/, (item.statusType === "PROGRESS" && item.progressType === "PERCENTAGE" && item.progressValue) ? item.progressValue : 0)
            .replace(/#progress2Value/, (item.statusType === "PROGRESS" && item.progressType === "BYTE" && item.progressValue) ? item.progressValue.toString() + " byte(s)" : "")
            .replace(/#displayBar/g, (item.statusType !== "PROGRESS" || item.progressType !== "PERCENTAGE") ? "none" : "")
            .replace(/#display2Bar/g, (item.statusType !== "PROGRESS" || item.progressType !== "BYTE") ? "none" : "");
        htmlContent += notificationHTML;
    });

    $("#notification-box").accordion("destroy");
    $("#notification-box").html(htmlContent).accordion({
        active : false,
        collapsible : true,
        autoHeight : false
    });

    $("#notification-box .progress-bar").each(function (index, item) {
        $(item).width(this.id);
    });
    if (utils.count(_notificationUIStack) !== 0) {
        $("#remove-all-notifications-btn").show();
    } else {
        $("#remove-all-notifications-btn").hide();
    }
    $("." + "remove-notification-btn").bind("click", function () {
        _remove(this.id);
    });
}

module.exports = {
    panel: {
        domId: "notification-container",
        collapsed: true,
        pane: "left",
        titleName: "Notification",
        display: true
    },
    initialize: function () {
        _notificationTemplate = $("#notification-template").html();
        $("#notification-box").empty();
        _notificationUIStack = db.retrieveObject("posted-notifications") || {};
        if (utils.count(_notificationUIStack) === 0) {
            $("#notification-box").append('<div style="color:#666666;">(Empty notification.)</div>');
        }
        else
            _render();
        $("#remove-all-notifications-btn").bind("click", _removeAll);

        event.on("refreshNotificationUI", function () {
            _notificationUIStack = db.retrieveObject("posted-notifications");
            _render();
        });
    }
};

});
define('ripple/ui/plugins/omnibar', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 emulatorBridge = require('ripple/emulatorBridge'),
    platform = require('ripple/platform'),
    db = require('ripple/db'),
    utils = require('ripple/utils'),
    devices = require('ripple/devices'),
    constants = require('ripple/constants'),
    _event = require('ripple/event'),
    tooltip = require('ripple/ui/plugins/tooltip'),
    histories = [];

function _omnibar() {
    return document.querySelector(".omni-bar input");
}

function _persist(url) {
    db.save("current-url", url);
}

function _persistRoot(url) {
    db.save("root-url", url);
}

function _currentURL() {
    return db.retrieve("current-url") || "about:blank";
}

function _rootURL() {
    return db.retrieve("root-url") || "about:blank";
}

function _reload() {
    _event.trigger("ApplicationLoad", null);
    emulatorBridge.window().location.reload();
}

function _loadApplication() {
    var omnibar = _omnibar(),
            xhr;
    if (omnibar.value.trim() !== "") {
        if (_currentURL().match(/^file:/) && omnibar.value.match(/^file:/)) { // Use ajax to know whether that file exists
            xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.responseText !== '') {
                        _persist(omnibar.value);
                        _persistRoot(omnibar.value);
                        emulatorBridge.window().location.assign(omnibar.value);
                    } else {
                        alert("File doesn't exist!");
                        return;
                    }
                }
            };
            xhr.open('GET', omnibar.value, true);
            xhr.send(null);
        } else {
            omnibar.value = omnibar.value.indexOf("://") < 0 ? "http://" + omnibar.value : omnibar.value;
            _persist(omnibar.value);
            _persistRoot(omnibar.value);
            emulatorBridge.window().location.assign(omnibar.value);
        }
        _addHistory(omnibar.value);
    }
    _event.trigger("ApplicationLoad", null);
}

function _hideHistory() {
    $("#app-launching-history").hide("slide", {direction: "up"}, "fast");
    $("#overlayBackground-transparent").hide();
}

function _makeHistoryItems() {
    histories = db.retrieveObject(constants.LAUNCHING_HISTORY);
    if (histories === undefined) {
        histories = [];
    }
    $("#app-launching-history").empty();
    histories.reverse();
    histories.forEach(function (item) {
        $("#app-launching-history").append('<div class="app-launching-history-item">' + item + '</div>');
    });

    if (histories.length === 0) {
        $("#app-launching-history").append('<div class="app-launching-history-item-empty">History empty</div>');
    }

    $(".app-launching-history-item").unbind('click');
    $(".app-launching-history-item").bind("click", function () {
        $(".omni-bar input").val(histories[$(this).index()]);
        _loadApplication();
        _hideHistory();
    });
}


function _showHistory() {
    _makeHistoryItems();
    $("#app-launching-history").css("width", $(".omni-bar input").width() + 20);
    $("#app-launching-history").show("slide", {direction: "up"}, "fast");
    $(window).bind('resize', function () {
        $("#app-launching-history").css("width", $(".omni-bar input").width() + 20);
        $("#overlayBackground-transparent").css("width", $(window).width());
        $("#overlayBackground-transparent").css("height", $(window).height());
    });

    $("#history-background-overlay").show();
    $("#overlayBackground-transparent").css("width", $(window).width());
    $("#overlayBackground-transparent").css("height", $(window).height());
    $("#overlayBackground-transparent").show();
    $("#overlayBackground-transparent").unbind('click');
    $("#overlayBackground-transparent").bind("click", function () {
        _hideHistory();
    });
}


function _addHistory(uri) {
    var i = 0, thehistories = db.retrieveObject(constants.LAUNCHING_HISTORY);
    if (thehistories !== undefined) {
        for (i; i < thehistories.length; i++) {
            if (uri === thehistories[i]) {
                return;
            }
        }
        if (thehistories.length >= 20) {
            thehistories.reverse();
            thehistories.pop();
            thehistories.reverse();
        }
    } else {
        thehistories = [];
    }
    thehistories.push(uri);
    db.saveObject(constants.LAUNCHING_HISTORY, thehistories);
}

_event.on("FrameHistoryChange", function (url) {
    _omnibar().value = url;
    _persist(url);
    _persistRoot(url);
});

module.exports = {
    initialize: function () {
        var omnibar = _omnibar(), loc, tmp,
            url, filename, matching, deviceId,
            xhr, uriParams, platformName, platformVersion, newUrl;

        jQuery(".logo, .beta, .left, .right, .left-panel-collapse, .right-panel-collapse").css({
            "marginTop": "35px"
        });

        jQuery("#settings-xhr-proxy").parent().parent().hide();

        $(".omni-bar").show();

        uriParams = utils.getURIParams(document.documentURI);
        if (uriParams.url !== undefined) {
            url = uriParams.url;
            if (url.match(/^\.[\.]?/) !== null) {
                loc = document.location;
                filename = loc.pathname.replace(/^.*[\\\/]/, '');
                matching = new RegExp(filename, "g");
                tmp = loc.protocol + "//" + loc.hostname + loc.pathname.replace(matching, "") + url;
                url = tmp;
            }
            _persist(url);
            _persistRoot(url);
            require('ripple/widgetConfig').initialize();
            require('ripple/ui/plugins/widgetConfig').initialize();
        }

        omnibar.value = _currentURL();

        omnibar.addEventListener("keydown", function (event) {
            if (event.keyCode === '13' || event.keyCode === 13 || event.keyCode === '0' || event.keyCode === 0) { // enter or return
                if (omnibar.value.trim() !== "") {
                    if (_currentURL().match(/^file:/) && omnibar.value.match(/^file:/)) { // Use ajax to know whether that file exists
                        xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4) {
                                if (xhr.responseText !== '') {
                                    _persist(omnibar.value);
                                    _persistRoot(omnibar.value);
                                    emulatorBridge.window().location.assign(omnibar.value);
                                } else {
                                    alert("File doesn't exist!");
                                    return;
                                }
                            }
                        };
                        xhr.open('GET', omnibar.value, true);
                        xhr.send(null);
                    } else {
                        //default the protocal if not provided
                        omnibar.value = omnibar.value.indexOf("://") < 0 ? "http://" + omnibar.value : omnibar.value;
                        _persist(omnibar.value);
                        _persistRoot(omnibar.value);
                        emulatorBridge.window().location.assign(omnibar.value);
                    }
                    _event.trigger("ApplicationLoad", null);
                    _addHistory(omnibar.value);
                }
            }
        });

        window.addEventListener("keydown", function (event) {
            var hasMetaOrAltPressed = (event.metaKey || event.ctrlKey),
                key = parseInt(event.keyCode, 10);

            if (key === 82 && hasMetaOrAltPressed) { // cmd/ctrl + r
                event.preventDefault();
                _reload();
            }

            if (key === 116) { // F5
                event.preventDefault();
                _reload();
            }
        });

        document.getElementById("history-reload").addEventListener("click", _reload);
        $("#options-button-history").bind("click", function () {
            _showHistory();
        });
        tooltip.create("#history-reload", "Reload Application");
        tooltip.create("#options-button-history", "History");
        tooltip.create("#options-button-config-window", "Configuration");
        tooltip.create("#options-button-preview-window", "Preview");
        tooltip.create("#options-button-panels", "Panel Settings");
        tooltip.create("#options-button-about", "About");
    },
    currentURL: function () {
        return _currentURL();
    },
    rootURL: function () {
        return _rootURL();
    }
};

});
define('ripple/ui/plugins/options', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 about = require('ripple/ui/plugins/about-dialog'),
    settings = require('ripple/ui/plugins/settings-dialog'),
    tooltip = require('ripple/ui/plugins/tooltip'),
    hide,
    show;

show = function () {
    if (settings.value("remoteInspector")) {
        $("#options-menu-build-warning").show();
        tooltip.create("#options-menu-build-warning", "Remote Web Inspector should be disabled when packaging for App World release");
    }
    else {
        $("#options-menu-build-warning").hide();
    }

    $("#options-window").show();
    $("#options-menu").show();
};

hide = function () {
    $("#options-window").hide();
    $("#options-menu").effect("fade", {}, 300);
};

module.exports = {
    initialize: function () {
        $("#options-menu").menu().hide();
        $("#options-menu").bind("click", function (event) {
            var target = $("#" + event.target.parentElement.id),
                action;

            if (target.hasClass("not-ready")) {
                return;
            }

            switch (target.attr("id")) {
            case "options-menu-build":
            case "options-menu-launch":
            case "options-menu-sign":
                action = target.attr("id").split("-")[2];
                if (!settings.can(action)) {
                    settings.show(action);
                }
                else {
                    settings.perform(action);
                }
                break;
            case "options-menu-about":
                about.show();
                break;
            case "options-menu-settings":
                settings.show();
                break;
            default:
                break;
            }
            hide();
        });

        $("#options-window").click(hide);
        
        $("#options-button-about").bind("click", function (event) {
            about.show();
        });
        
        hide();
    }
};

});
define('ripple/ui/plugins/package', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    event = require('ripple/event'),
    dbinit = require('ripple/platform/tizen/2.0/dbinit'),
    PackageInformation = require('ripple/platform/tizen/2.0/PackageInformation'),
    DB_PACKAGE_KEY = "tizen-db-package",
    _data = {
        packageList: {},
        installedList: {}
    },
    _currentPackageId = null,
    _packages,
    _installedList,
    _packageListTemplate,
    _packageInstalledTemplate;

function _get() {
    _data = db.retrieveObject(DB_PACKAGE_KEY);
    if (_data === undefined) {
        _data = {
            packageList: _packages,
            installedList: _installedList
        };
    }
    utils.forEach(_data.installedList, function (item) {
        item.lastModified = new Date(item.lastModified);
    });
}

function _save() {
    db.saveObject(DB_PACKAGE_KEY, _data);
}

function loadPackageList() {
    var nodes = jQuery("#package-list-select");
    nodes.html("");
    utils.forEach(_data.packageList, function (item, index) {
        nodes.append(utils.createElement("option", {
            "value": index,
            "innerText": item.name
        }));
    });
    renderPackageListBox($("#package-list-select option:selected").val());
}

function loadInstalledList() {
    var html = "";
    jQuery("#package-installed-box").empty();
    utils.forEach(_data.installedList, function (item) {
        html += _packageInstalledTemplate.replace(/#Name/g, item.name)
            .replace(/#ID/g, item.id)
            .replace(/#IconPath/, item.iconPath)
            .replace(/#Version/, item.version)
            .replace(/#TotalSize/, item.totalSize)
            .replace(/#DataSize/, item.dataSize)
            .replace(/#LastModified/, item.lastModified)
            .replace(/#Author/, item.author)
            .replace(/#Description/, item.description)
            .replace(/#APPIDs/, item.appIds.join("<br>"));
    });
    $("#package-installed-box").accordion("destroy");
    $("#package-installed-box").html(html).accordion({
        active: false,
        collapsible: true,
        autoHeight: false
    });
    $("." + "package-remove-btn").bind("click", function () {
        var id = this.id;
        if (id === _currentPackageId) {
            $("#msg-" + id).html("Can't Uninstall:<br> Package including running app");
            setTimeout(function () {
                $("#msg-" + id).text("");
            }, 5000);
            return;
        }
        utils.forEach(_data.packageList, function (item) {
            if (item.id === id) {
                event.trigger("remove-apps", [item.appIds]);
            }
        });
        delete _data.installedList[this.id];
        _save();
        loadPackageList();
        loadInstalledList();
        event.trigger("uninstall-package", [this.id]);
    });
}

function renderPackageListBox(path) {
    var item, html;
    jQuery("#package-list-box").empty();
    item = _data.packageList[path];
    html = _packageListTemplate.replace(/#Path/, path)
        .replace(/#ID/, item.id)
        .replace(/#Name/, item.name)
        .replace(/#IconPath/, item.iconPath)
        .replace(/#Version/, item.version)
        .replace(/#TotalSize/, item.totalSize)
        .replace(/#DataSize/, item.dataSize)
        .replace(/#Author/, item.author)
        .replace(/#Description/, item.description)
        .replace(/#APPList/, item.appIds.join("<br>"));
    jQuery("#package-list-box").html(html);
    if (_data.installedList[item.id]) {
        jQuery("#package-update-btn").show();
    } else {
        jQuery("#package-install-btn").show();
    }
}

function addPackage(path, type) {
    var item;
    if (!_data.packageList[path]) {
        return;
    }
    item = _data.packageList[path];
    _data.installedList[item.id] = new PackageInformation(
        item.id, item.name, item.iconPath, item.version,
        item.totalSize, item.dataSize, new Date(),
        item.author, item.description, item.appIds
    );
    if (type === "install") {
        event.trigger("install-apps", [item.appIds]);
    } else {
        event.trigger("update-apps", [item.appIds]);
    }
    _save();
}

module.exports = {
    panel: {
        domId: "package-container",
        collapsed: true,
        pane: "left",
        titleName: "Packages and Applications",
        display: true
    },
    initialize: function () {
        _packages = dbinit.Package.packages;
        _installedList = dbinit.Package.installedList;
        _packageListTemplate = jQuery("#package-list-template").html();
        _packageInstalledTemplate = jQuery("#package-installed-template").html();

        _get();
        _save();
        loadPackageList();
        loadInstalledList();
        jQuery("#package-list-select").bind("focus change", function () {
            var path = $("#package-list-select option:selected").val();
            renderPackageListBox(path);
        });
        jQuery("#package-install-btn").live("click", function () {
            var path = $("#package-list-select option:selected").val();
            addPackage(path, "install");
            _get();
            loadPackageList();
            loadInstalledList();
            event.trigger("install-packge", [path]);
        });
        jQuery("#package-update-btn").live("click", function () {
            var path = $("#package-list-select option:selected").val();
            addPackage(path, "update");
            loadPackageList();
            loadInstalledList();
            event.trigger("update-package", [path]);
        });
        jQuery("#package-select").tabs();
        event.on("installedList-updated", function () {
            _get();
            loadPackageList();
            loadInstalledList();
        });
        event.on("install-current-package", function (item) {
            _data.installedList[item.id] = new PackageInformation(
                item.id, item.name, item.iconPath, item.version,
                item.totalSize, item.dataSize, item.lastModified,
                item.author, item.description, item.appIds);
            _currentPackageId = item.id;
            loadInstalledList();
        });
    }
};

});
define('ripple/ui/plugins/panelCollapse', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
// TODO: could use a bit of refactoring sugar
var db = require('ripple/db'),
    constants = require('ripple/constants'),
    _LEFT_PANEL_COLLAPSE = ".left-panel-collapse",
    _RIGHT_PANEL_COLLAPSE = ".right-panel-collapse",
    _LEFT_PANEL = ".left",
    _RIGHT_PANEL = ".right",
    _SAVE_KEY = "panel-collapsed",
    platform = require('ripple/platform'),
    devices = require('ripple/devices'),
    _leftEngaged, _rightEngaged, _store;


$(function () { 
    $(window).resize(function () {
        var windowHeight = $(window).height();
        jQuery(".PanelCollapseBar").css("top", windowHeight - 56);
        jQuery("#left_div").css("height", $(window).height() - 21);
        if (_store["left"] === true) {
            jQuery("#middle_div").css("width", $(window).width());
        } else {
            jQuery("#middle_div").css("width", $(window).width());
        }
    });
});


function _persist() {
    db.saveObject(_SAVE_KEY, _store);
}


function updateZoomingValues(value, origin) {
    var scaleFactor = value / 100, scaleString;
    scaleString = "scale(" + scaleFactor + ")";
    jQuery('#device-layout').css('-webkit-transform', scaleString);
    if (origin === "center") {
        jQuery('#device-layout').css('-webkit-transform-origin', 'center top');
    } else {
        jQuery('#device-layout').css('-webkit-transform-origin', 'left top');
    }
}


function _process(collapseNode, panelNode, side, callback) {
    var jNode = collapseNode.children("span"),
        jPanelNode = jQuery(panelNode),
        properties = {},
        collapseProperties = {},
        options = {
            duration: 600,
            complete: callback
        },
        oldIcon, newIcon,
        zoomingValue =  db.retrieve(constants.ENCAPSULATOR.ZOOMING);

    if (_store[side] === true) {
        _store[side] = false;
        
        if (side === "left") {
            jQuery('#left_div').show("fast");
            collapseNode.removeClass("PanelCollapseBarCollapsed");
            collapseNode.addClass("PanelCollapseBar");
            collapseNode.children().remove();
            collapseNode.append('<img src="images/sideCollapseIconLeftSide.png" style="margin-left:330px; margin-top: 6px;"/>');
            collapseNode.css("top", $(window).height() - 56);
            collapseNode.css("left", 0);
            jQuery("#middle_div").css("width", $(window).width());
            updateZoomingValues(zoomingValue, "left");
        }
        oldIcon = (side === "left" ? "ui-icon-arrowthick-1-e" : "ui-icon-arrowthick-1-w");
        newIcon = (side === "left" ? "ui-icon-arrowthick-1-w" : "ui-icon-arrowthick-1-e");

        properties[side] = "0px";
        collapseProperties[side] = "345px";
        properties.opacity = "1";

        if (jQuery("#device-layout").position().left < 290 ) {
            jQuery("#device-layout").animate({left: "350px"}, 200 );
        }
    } else {
        _store[side] = true;
        
        if (side === "left") {
            collapseNode.removeClass("PanelCollapseBar");
            collapseNode.addClass("PanelCollapseBarCollapsed");
            collapseNode.children().remove();
            collapseNode.append('<img src="images/sideCollapseIconRightSide.png" style="position: absolute; margin-left:5px; margin-top:48%;"/>');
            collapseNode.css("top", 10);
            collapseNode.css("left", 0);
            collapseNode.css("margin-left", 0);
            jQuery('#left_div').hide("slow");
            jQuery("#middle_div").css("width", $(window).width());
            updateZoomingValues(zoomingValue, "left");
        }

        oldIcon = (side === "left" ? "ui-icon-arrowthick-1-w" : "ui-icon-arrowthick-1-e");
        newIcon = (side === "left" ? "ui-icon-arrowthick-1-e" : "ui-icon-arrowthick-1-w");

        properties[side] = "-340px";
        collapseProperties[side] = "5px";
        properties.opacity = "0.1";
    }

    jNode.removeClass(oldIcon).addClass(newIcon);

    jPanelNode.animate(properties, options);
    _persist();
}

module.exports = {
    initialize: function () {
        var rightCollapseNode = jQuery(_RIGHT_PANEL_COLLAPSE),
            leftCollapseNode = jQuery(_LEFT_PANEL_COLLAPSE),
            device = devices.getCurrentDevice(),
            zoomingValue =  db.retrieve(constants.ENCAPSULATOR.ZOOMING),
            deviceNode = jQuery("#device-layout");
           
        _store = db.retrieveObject(_SAVE_KEY) || {
            left: false,
            right: false
        };

        jQuery("#left_div").css("height", $(window).height() - 21);
        jQuery("#middle_div").css("width", $(window).width());

        jQuery("#device-container").bind("mousedown", function () {
            jQuery("#device-maskmask").show();
        });

        jQuery("#device-container").bind("mouseup", function () {
            jQuery("#device-maskmask").hide();
        });

        jQuery("#deviceTitleBar").bind("mousedown", function () {
            jQuery("#device-maskmask").show();
        });

        jQuery("#deviceTitleBar").bind("mouseup", function () {
            jQuery("#device-maskmask").hide();
        });

        deviceNode.draggable({ cursor: 'move', handle: "#deviceTitleBar", containment: [0, 52, 1280, 800]});
        jQuery("#deviceTitle").text(device.name);
        if (_store.left === true) {
            jQuery(_LEFT_PANEL).css({
                left: "-340px",
                opacity: "0.1"
            });

            leftCollapseNode.removeClass("PanelCollapseBar");
            leftCollapseNode.addClass("PanelCollapseBarCollapsed");
            leftCollapseNode.children().remove();
            leftCollapseNode.append('<img src="images/sideCollapseIconRightSide.png" style="position: absolute; margin-left:5px; margin-top:48%;"/>');
            leftCollapseNode.css("top", 10);
            leftCollapseNode.css("left", 0);
            leftCollapseNode.css("margin-left", 0);
            jQuery('#left_div').hide();
            jQuery("#device-layout").css("left", "21px");
            updateZoomingValues(zoomingValue, "left");
        } else {
            jQuery('#left_div').show("fast");
            leftCollapseNode.removeClass("PanelCollapseBarCollapsed");
            leftCollapseNode.addClass("PanelCollapseBar");
            leftCollapseNode.children().remove();
            leftCollapseNode.append('<img src="images/sideCollapseIconLeftSide.png" style="margin-left:330px; margin-top: 6px;"/>');
            leftCollapseNode.css("top", $(window).height() - 56);
            leftCollapseNode.css("left", 0);
            jQuery("#device-layout").css("left", "350px");
            updateZoomingValues(zoomingValue, "left");
        }   

        if (_store.right === true) {
            jQuery(_RIGHT_PANEL).css({
                right: "-340px",
                opacity: "0.1"
            });

            rightCollapseNode.css({
                right: "5px"
            }).children("span").removeClass("ui-icon-arrowthick-1-e").addClass("ui-icon-arrowthick-1-w");
        }

        leftCollapseNode.bind("click", function () {
            if (!_leftEngaged) {
                _leftEngaged = true;
                _process(leftCollapseNode, _LEFT_PANEL, "left", function () {
                    _leftEngaged = false;
                });
            }
        });

        rightCollapseNode.bind("click", function () {
            if (!_rightEngaged) {
                _rightEngaged = true;
                _process(rightCollapseNode, _RIGHT_PANEL, "right", function () {
                    _rightEngaged = false;
                });
            }
        });
    }
};

});
define('ripple/ui/plugins/phone', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    Phone = require('ripple/platform/webworks.handset/2.0.0/client/Phone'),
    CallLog = require('ripple/platform/webworks.handset/2.0.0/client/CallLog'),
    event = require('ripple/event'),
    _console = require('ripple/console'),
    eventSelect = document.getElementById("phone-event-types"),
    eventErrorContainer = document.getElementById("phone-event-error-container"),
    eventErrorSelect = document.getElementById("phone-event-error-types");

function _firePhoneLogEvents(type, number, error) {
    if (type === Phone.CB_CALL_INITIATED ||
        type === Phone.CB_CALL_ANSWERED) {
        event.trigger("PhoneCallLogAdded", [{
            date: new Date(),
            number: number,
            status: CallLog.STATUS_NORMAL,
            type: CallLog.TYPE_RECEIVED_CALL
        }], true);
    } else if (type === Phone.CB_CALL_ENDED_BYUSER ||
                type === Phone.CB_CALL_FAILED) {
        event.trigger("PhoneCallLogAdded", [{
            date: new Date(),
            number: number,
            status: CallLog.STATUS_NORMAL,
            type: CallLog.TYPE_PLACED_CALL
        }], true);
    }
}

function _updateActiveCalls(type, number, error) {
    if (type === Phone.CB_CALL_INITIATED ||
        type === Phone.CB_CALL_CONNECTED ||
        type === Phone.CB_CALL_CONFERENCECALL_ESTABLISHED ||
        type === Phone.CB_CALL_DIRECTCONNECT_CONNECTED ||
        type === Phone.CB_CALL_ANSWERED) {
        event.trigger("PhoneCallInitiated", [{
            id: number,
            onhold: false,
            outgoing: false,
            recipient: {
                name: "",
                number: String(number)
            }
        }], true);
    } else if (type === Phone.CB_CALL_ENDED_BYUSER ||
                type === Phone.CB_CALL_FAILED ||
                type === Phone.CB_CALL_DISCONNECTED ||
                type === Phone.CB_CONFERENCECALL_DISCONNECTED ||
                type === Phone.CB_CALL_DIRECTCONNECT_DISCONNECTED) {
        event.trigger("PhoneCallEnded", [{
            id: number
        }], true);
    }
}

module.exports = {
    panel: {
        domId: "phone-container",
        collapsed: true,
        pane: "right"
    },
    initialize: function (prev, baton) {
        utils.forEach(Phone, function (value, prop) {
            if (prop.match(/^CB_/)) {
                eventSelect.appendChild(utils.createElement("option", {
                    value: value,
                    innerHTML: prop.replace(/^CB_(CALL_)?/, "")
                }));
            }

            if (prop.match(/^CALL_ERROR_/)) {
                eventErrorSelect.appendChild(utils.createElement("option", {
                    value: value,
                    innerHTML: prop.replace(/^CALL_ERROR_/, "")
                }));
            }
        });

        document.getElementById("phone-event-types").addEventListener("change", function () {
            eventErrorContainer.setAttribute("style", parseInt(eventSelect.value, 10) === Phone.CB_CALL_FAILED ? "" : "display: none");
        });

        document.getElementById("phone-logs-clear").addEventListener("click", function () {
            event.trigger("PhoneCallLogReset");
        });

        document.getElementById("phone-event-send").addEventListener("click", function () {
            var type = parseInt(eventSelect.value, 10),
                error = type === Phone.CB_CALL_FAILED ? eventErrorSelect.value : undefined,
                callId = document.getElementById("phone-call-id").value;

            _firePhoneLogEvents(type, callId, error);
            _updateActiveCalls(type, callId, error);

            event.trigger("PhoneEvent", [type, callId, error]);

            _console.log("Fired PhoneEvent (type " + type +  ") CallID: " +
                         callId + (error ? (" (error type " + error + ")") : ""));
        }, false);
    }
};

});
define('ripple/ui/plugins/platform', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    utils = require('ripple/utils'),
    devices = require('ripple/devices'),
    deviceSettings = require('ripple/deviceSettings'),
    platform = require('ripple/platform'),
    db = require('ripple/db');

function _updatePlatformDeviceSelect(platformID, currentDeviceKey) {
    var devicesSelect = document.getElementById(constants.COMMON.DEVICE_SELECT_ID),
        listOfSortedDevices = devices.getDevicesForPlatform(platformID)
                                        .sort(function (a, b) {
                                            return (a.screen.width * a.screen.height) < (b.screen.width * b.screen.height) ? -1 : ((a.screen.width * a.screen.height) > (b.screen.width * b.screen.height) ? 1 : 0);
                                        });
	var main_devicesSelect = document.getElementById(constants.COMMON.DEV_SELECT),
        listOfSortedDevices = devices.getDevicesForPlatform(platformID)
                                        .sort(function (a, b) {
                                            return (a.screen.width * a.screen.height) < (b.screen.width * b.screen.height) ? -1 : ((a.screen.width * a.screen.height) > (b.screen.width * b.screen.height) ? 1 : 0);
                                        });
    db.remove("viewport_width");
    db.remove("viewport_height");
    db.remove("viewportTag");

    devicesSelect.innerHTML = "";
	main_devicesSelect.innerHTML = "";
    listOfSortedDevices.forEach(function (dev) {
        var deviceNode = utils.createElement("option", {
            "innerText": dev.name,
            "value": dev.id
        });

        if (currentDeviceKey && deviceNode.value === currentDeviceKey) {
            deviceNode.selected = true;
        }

        devicesSelect.appendChild(deviceNode);
    });

    listOfSortedDevices.forEach(function (dev) {
        var deviceNode = utils.createElement("option", {
            "innerText": dev.name,
            "value": dev.id
        });

        if (currentDeviceKey && deviceNode.value === currentDeviceKey) {
            deviceNode.selected = true;
        }

        main_devicesSelect.appendChild(deviceNode);
    });

    if (platformID === "ivi" || platformID === "wearable" || platformID === "tv") {
        jQuery("#configuration-window-save-btn").hide();
        jQuery("#configuration-window-load-btn").hide();

        jQuery("#item_container :nth-child(2)").hide();
        jQuery("#item_container :nth-child(3)").hide();

        _unlockScreen();
        //jQuery("#hwkeys-panel").hide();
    }
    else {
        jQuery("#configuration-window-save-btn").show();
        jQuery("#configuration-window-load-btn").show();

        jQuery("#item_container :nth-child(2)").show();
        jQuery("#item_container :nth-child(3)").show();

        //jQuery("#hwkeys-panel").show();
    }

    if (currentDeviceKey === "CUSTOM") {
		jQuery("#dev-select").hide();
    }
}

function _unlockScreen() {
    if (!deviceSettings.retrieve("Config.lockScreen"))
        return;

    if ($("#device-settings-Config-lockScreen").length === 0) {
        deviceSettings.persist("Config.lockScreen", false);
    } else {
        $("#device-settings-Config-lockScreen")[0].click();
    }
}

function checkResolutionSize(evt) {
	var query_str, id_str, len;
	query_str = "#resolution-custom-" + evt.data.msg;
	id_str = "custom_" + evt.data.msg;
	len = jQuery(query_str).val();
	if (len >= 200 && len <= 2000) {
		db.save(id_str, len);
	} else {
		jQuery(query_str).val(db.retrieve(id_str));
	}
}

function changePlatformOrDevice() {
    	var platformId = jQuery("#platform-select").val(),
        version = jQuery("#version-select").val(),
        device = jQuery("#dev-select").val();

	platform.changeEnvironment({
        "name": platformId,
        "version": version
    }, device, function () {
        var original = utils.queryString().enableripple,
            updated = platformId + "-" + version + "-" + device;

        if (original) {
            location.href = location.href.replace(new RegExp(original, "i"), updated);
        }
        else { window.tinyHipposReload=true; location.reload(true); }
    });
}

module.exports = {
    initialize: function () {
        var currentPlatform = platform.current().id,
            currentVersion = platform.current().version,
            platformList = platform.getList(),
            platformSelect = document.getElementById(constants.COMMON.PLATFORM_SELECT_ID),
            versionSelect = document.getElementById("version-select"),
            currentDeviceKey = devices.getCurrentDevice().id,
            platformNode, versionNode;

        jQuery("#platform-select").bind("change", function () {
            var newPlatform = jQuery(this).val(),
                newDevice = jQuery("#device-select").val();

            jQuery(versionSelect).children("option").remove();
            utils.forEach(platformList, function (platform) {
                utils.forEach(platform, function (version, versionNumber) {
                    if (newPlatform === version.id) {
                        versionSelect.appendChild(utils.createElement("option", {
                            "innerText": version.text,
                            "value":  versionNumber
                        }));
                    }
                });
            });
            _updatePlatformDeviceSelect(newPlatform, newDevice);
        });

        jQuery("#device-select").bind("focus", function () {
            $('input:radio[name="resolution-type"][value="predefined"]').click();
        });
        jQuery("#resolution-custom-width").bind("focus", function () {
            $('input:radio[name="resolution-type"][value="custom"]').click();
        });
        jQuery("#resolution-custom-height").bind("focus", function () {
            $('input:radio[name="resolution-type"][value="custom"]').click();
        });
        jQuery("#resolution-custom-width").bind("change", {msg: "width"}, checkResolutionSize);
        jQuery("#resolution-custom-height").bind("change", {msg: "height"}, checkResolutionSize);

		jQuery("#dev-select").bind("change", changePlatformOrDevice);
        utils.forEach(platformList, function (platform, platformKey) {
            platformNode = utils.createElement("option", {
                "innerText": platformKey === "tizen" ? "mobile": platformKey,
                "value":  platformKey
            });

            utils.forEach(platform, function (version, versionNumber) {
                versionNode = utils.createElement("option", {
                    "innerText": version.text,
                    "value":  versionNumber
                });

                if (currentPlatform && version.id === currentPlatform) {
                    versionSelect.appendChild(versionNode);
                    if (currentVersion && currentVersion === versionNumber) {
                        platformNode.selected = true;
                        versionNode.selected = true;
                    }
                }
            });
            platformSelect.appendChild(platformNode);
        });

        _updatePlatformDeviceSelect(currentPlatform, currentDeviceKey);
    }
};

});
define('ripple/ui/plugins/platformEvents', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _console = require('ripple/console'),
    platform = require('ripple/platform'),
    event = require('ripple/event'),
    exception = require('ripple/exception'),
    utils = require('ripple/utils');

module.exports = {
    panel: {
        domId: "platform-events-container",
        collapsed: true,
        pane: "right",
        titleName: "Platform Events",
        display: true
    },
    initialize: function () {
        var eventSelect = document.getElementById("platform-events-select"),
            spec = platform.current();

        if (!spec.events) {
            return;
        }

        utils.forEach(spec.events, function (method, name) {
            eventSelect.appendChild(utils.createElement("option", {
                "innerText": name,
                "value": name
            }));
        });

        jQuery("#platform-events-fire").click(function () {
            var eventName = document.getElementById("platform-events-select").value,
                args = spec.events[eventName].args ? document.getElementById("platform-events-args").value : null,
                callback = spec.events[eventName].callback;

            _console.log("fired event => " + eventName);

            try {
                callback(args);
            } catch (e) {
                exception.throwMaskedException(e);
            }
        });

        jQuery(eventSelect).change(function () {
            var argsSelect = jQuery("#platform-events-args"),
                args = spec.events[this.value].args;

            argsSelect.empty();

            if (args) {
                utils.forEach(spec.events[this.value].args, function (arg, index) {
                    argsSelect.append(utils.createElement("option", {
                        innerText: arg,
                        value: index
                    }));
                });

                argsSelect.show();
            } else {
                argsSelect.hide();
            }
        });
    }
};

});
define('ripple/ui/plugins/power', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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 db = require('ripple/db'),
    event = require('ripple/event'),
    constants = require('ripple/constants'),
    _volume  = document.getElementById(constants.BATTERY.VOLUME),
    _volumeLabel  = document.getElementById(constants.BATTERY.VOLUME + "-label"),
    _charging = document.getElementById(constants.BATTERY.CHARGING),
    _battery = {
        volume: 600,
        level:  1.0,
        timerId: null,
        charge: function (isStart, isCharge, callback) {
            var currentVolume,
                checkValue = function () {
                    if (_battery.level < 0 || _battery.level > 1.0 || !isStart) {
                        clearInterval(_battery.timerId);
                        _battery.timerId = null;
                        if (_battery.level < 0)
                            _battery.level = 0;
                        else if (_battery.level > 1.0)
                            _battery.level = 1.0;
                    }
                };

            if (isStart && !_battery.timerId) {
                _battery.timerId = setInterval(function () {
                    currentVolume = isCharge ? _battery.level * _battery.volume + 1 : _battery.level * _battery.volume - 1;
                    _battery.level = currentVolume / _battery.volume;
                    checkValue();
                    return callback && callback();
                }, 1000);
            }
            checkValue();
            return callback && callback();
        }
    };

function _triggerEvent(chargingStatus, chargingTime, dischargingTime, level, type) {
    var status = {
        charging: chargingStatus,
        chargingTime: chargingTime,
        dischargingTime: dischargingTime,
        level: level,
        type: type
    };
    event.trigger("BatteryEvent", [status]); // for w3c battery api
    // for tizen systeminfo api
    if (type === "levelchange") {
        event.trigger("BatteryLevelChanged", [level]);
    }
    if (type === "chargingchange") {
        event.trigger("BatteryChargingChanged", [status]);
    }
}

function _updateLevelIcons() {
    var colors = ["black", "black", "black", "black", "black", "black", "#404040", "#606060", "#808080", "#b0b0b0", "#ffffff", "#ffffff", "#ffffff", "#ffffff", "#ffffff", "#ffffff"],
        colorIndex = 10 - Math.round(_battery.level * 10),
        index;

    //map the battery level to the color range
    for (index = 0 ; index <= 5 ; index++) {
        $("#block" + index).css("backgroundColor", colors[colorIndex]);
        colorIndex++;
    }
}

function _setVolumeReadOnly(flag) {
    if (flag) {
        $("#" + constants.BATTERY.VOLUME).hide();
        $("#" + constants.BATTERY.VOLUME + "-label").show();
    } else {
        $("#" + constants.BATTERY.VOLUME).show();
        $("#" + constants.BATTERY.VOLUME + "-label").hide();
    }
}

function _startDischarging() {
    var remainVolume = 0;

    if ($("#simulate-low-battery #low-battery-remain-time").val() <= 0) {
        $("#simulate-low-battery #low-battery-remain-time").val(0);
    }
    remainVolume = Number($("#simulate-low-battery #low-battery-remain-time").val());
    if ($("#simulate-low-battery #low-battery-start-at").val() > 100) {
        $("#simulate-low-battery #low-battery-start-at").val(100);
    }
    if ($("#simulate-low-battery #low-battery-start-at").val() <= 0) {
        $("#simulate-low-battery #low-battery-start-at").val(0);
    }
    _battery.level = $("#simulate-low-battery #low-battery-start-at").val() / 100.0;
    if (_battery.level === 0 || remainVolume === 0) {
        $("#simulate-low-battery").dialog("close");
        _stopDischarging();
        return;
    }
    _setVolumeReadOnly(true);
    if (_charging.checked) {
        _charging.checked = false;
        _battery.charge(false);
    }

    _charging.disabled = true;
    $("#remaining-time-label").html("Remaining Time to empty (seconds)");
    $("#charging-state").html("Plugged in?");

    $("#remain-time").show();
    _battery.volume = remainVolume / _battery.level;
    _volumeLabel.innerText = (_battery.level * 100).toFixed(2);
    _battery.charge(true, false, function () {
        _volumeLabel.innerText = (_battery.level * 100).toFixed(2);
        _volume.value = (_battery.level * 100).toFixed(2);
        changeBatteryVolume();
        $("#remain-time").html(Math.round(_battery.volume * _battery.level) + " Seconds");
        _updateLevelIcons();
        if (_battery.level <= 0.0) {
            _stopDischarging();
        }
    });
    $("#simulate-low-battery").dialog("close");
    $("#simulate-low-battery-btn").hide();
    $("#stop-btn").show();
    _triggerEvent(false, Infinity, Math.round(_battery.volume * _battery.level), _battery.level, "chargingtimechange");
}

function _stopDischarging() {
    _charging.disabled = false;
    _battery.level = _volume.value / 100.0;
    $("#remain-time").hide();
    $("#remain-time").html("");
    $("#remaining-time-label").html("Remaining Time (seconds)");
    _setVolumeReadOnly(false);
    _battery.charge(false);
    $("#simulate-low-battery-btn").show();
    $("#stop-btn").hide();
    _updateLevelIcons();
}

function _setCharging() {
    // update the UI parts
    if (_charging.checked) {
        _battery.volume = 600;
        _battery.level = _volume.value / 100;
        _setVolumeReadOnly(true);
        $("#remain-time").show();
        $("#remaining-time-label").html("Remaining Time to fully charged (seconds)");
        $("#charging-state").html("Plugged in - charging rate 0.17%/second");
        _triggerEvent(true, Math.round(_battery.volume * (1 - _battery.level)), Infinity, _battery.level, "chargingchange");
    } else {
        _battery.level = _volume.value / 100.0;
        _updateLevelIcons();
        $("#remain-time").hide();
        $("#remain-time").html("");
        _setVolumeReadOnly(false);
        $("#remaining-time-label").html("Remaining Time (seconds)");
        $("#charging-state").html("Plugged in?");
        _triggerEvent(false, Infinity, Math.round(_battery.volume * _battery.level), _battery.level, "chargingchange");
    }
    // if it's unchecked, the timer will stop in this function call, the UI update blow it
    _battery.charge(_charging.checked, true, function () {
        _volumeLabel.innerText = (_battery.level * 100).toFixed(2);
        _volume.value = (_battery.level * 100).toFixed(2);
        changeBatteryVolume();
        $("#remain-time").html(Math.round(_battery.volume * (1 - _battery.level)) + " Seconds");    //show current remain time
        _updateLevelIcons();
    });
}

function changeBatteryVolume() {
    if (_volume.value < 0)
        _volume.value = 0;
    else if (_volume.value > 100)
        _volume.value = 100;

    _battery.level = _volume.value / 100.0;
    if (_charging.checked === true) {
        _triggerEvent(true, Math.round(_battery.volume * (1 - _battery.level)), Infinity, _battery.level, "levelchange");
    } else {
        _triggerEvent(false, Infinity, Math.round(_battery.volume * _battery.level), _battery.level, "levelchange");
    }
    db.save(constants.BATTERY.VOLUME, _volume.value);
    _updateLevelIcons();
}

function initBattery() {
    $("#" + constants.BATTERY.CHARGING).bind("change", _setCharging);

    $("#simulate-low-battery-btn").bind("click", function () {
        $("#simulate-low-battery").dialog("open");
    });

    $("#simulate-low-battery-cancel").bind("click", function () {
        $("#low-battery-start-at").val = 20;  //UI initialize
        $("#low-battery-remain-time").val = 1200;
        $("#simulate-low-battery").dialog("close");
    });

    $("#simulate-low-battery-start").bind("click", _startDischarging);
    $("#stop-btn").bind("click", _stopDischarging);

    $("#" + constants.BATTERY.VOLUME).bind("change", function () {
        changeBatteryVolume();
    });

    _charging.checked = false;
    _battery.level = db.retrieve(constants.BATTERY.VOLUME) / 100.0;
    if (isNaN(_battery.level)) {
        _battery.level = 1;
    }
    _volume.value = (_battery.level * 100).toFixed(2);
    _updateLevelIcons();
    $("#simulate-low-battery").dialog({
        resizable: false,
        draggable: true,
        modal: true,
        autoOpen: false,
        position: 'center',
        minWidth: '460',
        minHeight: '240'
    });
}

module.exports = {
    panel: {
        domId: "power-container",
        collapsed: true,
        pane: "left",
        titleName: "Power Manager",
        display: true
    },

    initialize: function () {
        initBattery();
    }
};

});
define('ripple/ui/plugins/previewWindow', function (require, exports, module) {
/*
 *  Copyright 2014 Intel Corporation.
 *
 * 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 platform = require("ripple/platform"),
    devices = require("ripple/devices"),
    LIMIT_SIZE = 230, ROW_COUNT = 3, ROW_TOP = 40,
    previewSource, deviceResolutions,
    oldContainer, oldLeft, oldTop, oldScale,
    previewContainer, prevLeft,
    rowIndex, rowNum, currentRowIndex, containerArr;

function getAbsoluteURI(base, relative) {
    var stack = base.split("/"),
        parts = relative.split("/"),
        i;

    stack.pop();
    for (i = 0; i < parts.length; i++) {
        if (parts[i] === ".")
            continue;
        if (parts[i] === "..")
            stack.pop();
        else
            stack.push(parts[i]);
    }

    return stack.join("/");
}

function _readPreviewSourceHtml() {
    var resource = document.getElementById("document"),
        links, linkHref,
        images, imgSrc,
        sources, sourceSrc,
        scripts, i, src;

    previewSource = resource.contentDocument.cloneNode(true);
    src = previewSource.documentURI;
    links = previewSource.getElementsByTagName("link");
    images = previewSource.getElementsByTagName("img");
    sources = previewSource.getElementsByTagName("source");
    scripts = previewSource.getElementsByTagName("script");
    for (i = 0; i < links.length; i++) {
        linkHref = links[i].getAttribute("href");
        if (!linkHref)
            continue;
        if (linkHref.indexOf("file://") === 0 ||
                linkHref.indexOf("http://") === 0)
            continue;
        previewSource.getElementsByTagName("link")[i].setAttribute("href",
            getAbsoluteURI(src, linkHref));
    }
    for (i = 0; i < images.length; i++) {
        imgSrc = images[i].getAttribute("src");
        if (!imgSrc)
            continue;
        if (imgSrc.indexOf("file://") === 0 ||
                imgSrc.indexOf("http://") === 0 ||
                imgSrc.indexOf("data:") === 0)
            continue;
        previewSource.getElementsByTagName("img")[i].setAttribute("src",
            getAbsoluteURI(src, imgSrc));
    }
    for (i = 0; i < sources.length; i++) {
        sourceSrc = sources[i].getAttribute("src");
        if (!sourceSrc)
            continue;
        if (sourceSrc.indexOf("file://") === 0 ||
                sourceSrc.indexOf("http://") === 0)
            continue;
        previewSource.getElementsByTagName("source")[i].setAttribute("src",
            getAbsoluteURI(src, sourceSrc));
    }
    while (scripts.length > 0) {
        previewSource.getElementsByTagName("script")[0].remove();
    }
}

function _createPreviewLayout(container, width, height) {
    var frameId = container.id.replace("container", "preview"),
        frame = document.createElement("iframe"),
        frameContent;

    container.appendChild(frame);
    frame.setAttribute("id", frameId);
    //frame.setAttribute("src", previewSource.documentURI);
    frame.setAttribute("src", "");
    $(frame).css("width", width + "px");
    $(frame).css("height", height + "px");

    frameContent = frame.contentDocument;
    frameContent.open();
    frameContent.writeln(previewSource.documentElement.outerHTML);
    frameContent.close();
}

function _showPreviewField(container, width, height, title) {
    var suffix = title.replace(/\s/g, "").replace("(", "").replace(")", ""),
        containerId = "table" + suffix,
        containerField = $("<table></table>"),
        containerLeft = prevLeft,
        containerTop = ROW_TOP,
        containerScale = 1,
        template = '<tr><td>' +
            '<div style="background-color: #dddddd; height: 25px; width: 100%; border: 1px solid #888888;">' +
            '<span style="margin-top:3px; margin-left:20px;">#TITLE</span></div>' +
            '</td></tr><tr><td>' +
            '<div id="container#SUFFIX" style="margin: 0; border: 10px solid #000000;"></div>' +
            '<input type="hidden" id="scale#SUFFIX" value="#SCALE" />' +
            '<input type="hidden" id="left#SUFFIX" value="#LEFT" />' +
            '<input type="hidden" id="top#SUFFIX" value="#TOP" />' +
            '<div class="preview-window-table-layout" style="position: absolute; width: 100%; height: 100%; left: 0; top: 18px; opacity: 0.5;"></div>' +
            '</td></tr>',
        iframeContainer;

    containerScale = (width > LIMIT_SIZE) ? Math.floor((LIMIT_SIZE / width) * 100) / 100 : 1;
    previewContainer.append(containerField);
    containerField.html(template.replace(/#SUFFIX/g, suffix)
        .replace(/#TITLE/g, title)
        .replace(/#SCALE/g, containerScale)
        .replace(/#LEFT/g, containerLeft)
        .replace(/#TOP/g, containerTop));
    containerField.attr("id", containerId);
    containerField.css({
        "left": containerLeft + "px",
        "top": containerTop + "px",
        '-webkit-transform-origin':  '0% 0%',
        '-webkit-transform':  "translate(0px, 0px) rotate(0deg) scale(" + containerScale + ")"
    });

    containerArr.push(containerId);
    if (rowIndex > 2) {
        containerField.css({"display": "none"});
        currentRowIndex = 0;
    }

    rowIndex++;
    if (rowIndex % ROW_COUNT === 0) {
        prevLeft = 20;
    }
    else {
        prevLeft = containerLeft + LIMIT_SIZE + 20;
    }

    iframeContainer = document.getElementById("container" + suffix);
    _createPreviewLayout(iframeContainer, width, height);
}

function _showPreviewLayouts() {
    var deviceName,
        container = document.getElementById("preview-window-container-div");

    for (deviceName in deviceResolutions) {
        _showPreviewField(container, deviceResolutions[deviceName].width,
                deviceResolutions[deviceName].height, deviceName);
    }
}

function _initializeDeviceResolutions() {
    var platforms = platform.getList(),
        platformId,
        platformDevices,
        i, count = 0;

    deviceResolutions = {};
    for (platformId in platforms) {
        platformDevices = devices.getDevicesForPlatform(platformId);
        for (i = 0; i < platformDevices.length; i++) {
            count++;
            deviceResolutions[platformDevices[i].name] = {
                width: platformDevices[i].viewPort.portrait.width,
                height: platformDevices[i].viewPort.portrait.height
            };
        }
    }
    rowNum = Math.ceil(count / ROW_COUNT);
}

function _bindEventsForPreviewWindow() {
    $("#preview-window-close-btn").unbind("click");
    $("#preview-window-close-btn").bind("click", function (event) {
        $("#preview-window-popup").hide("slide", {direction: "up"}, "slow" ,function () {
            previewContainer.html("");
            $("#overlayBackground").hide();
        });

        event.preventDefault();
    });

    $("#preview-window-container-div table").unbind("click");
    $("#preview-window-container-div table").bind("click", function (event) {
        var containers = $("#preview-window-container-div table"),
            container = $(this),
            containerId = container.attr("id"),
            scaleId = containerId.replace("table", "scale"),
            leftId = containerId.replace("table", "left"),
            topId = containerId.replace("table", "top");

        oldLeft = container.find("#" + leftId).val();
        oldTop = container.find("#" + topId).val();
        oldScale = container.find("#" + scaleId).val();
        oldContainer = containerId;
        containers.find(".preview-window-table-layout").css("background", "");
        container.find(".preview-window-table-layout").css("background", "#000000");

        event.preventDefault();
    });

    $("#preview-window-preview-btn").unbind("click");
    $("#preview-window-preview-btn").bind("click", function (event) {
        var containerId = oldContainer;
        if (!containerId)
            return;

        $("#preview-window-container-div table").hide();

        $("#" + containerId).css('left', '0px');
        $("#" + containerId).css('top', '0px');
        $("#" + containerId).find(".preview-window-table-layout").css("background", "");
        $("#" + containerId).css('-webkit-transform-origin', '0% 0%');
        $("#" + containerId).css('-webkit-transform',  "translate(0px, 0px) rotate(0deg) scale(1)");
        $("#" + containerId).show();

        $("#preview-window-preview-btn").hide();
        $("#preview-window-container-bar").hide();
        $("#preview-window-back-btn").show();
        $("#preview-window-scale-range").show();
        $("#preview-window-scale-range").val(100);
        $("#preview-window-popup .preview-window-scale-num").show();
        $("#preview-window-popup .preview-window-scale-num").text("100%");

        event.preventDefault();
    });

    $("#preview-window-scale-range").unbind("change");
    $("#preview-window-scale-range").bind("change", function (event) {
        var containerId = oldContainer,
            nScale = Number($(this).val());

        $("#" + containerId).css('-webkit-transform',  "translate(0px, 0px) rotate(0deg) scale(" + nScale / 100 + ")");
        $("#preview-window-popup .preview-window-scale-num").text(nScale + "%");

        event.preventDefault();
    });

    $("#preview-window-back-btn").unbind("click");
    $("#preview-window-back-btn").bind("click", function (event) {
        var containerId = oldContainer, i;

        $("#" + containerId).css('left', oldLeft + "px");
        $("#" + containerId).css('top', oldTop + "px");
        $("#" + containerId).find(".preview-window-table-layout").css("background", "#000000");
        $("#" + containerId).css('-webkit-transform-origin', '0% 0%');
        $("#" + containerId).css('-webkit-transform',  "translate(0px, 0px) rotate(0deg) scale(" + oldScale + ")");

        $("#preview-window-container-div table").hide();
        for (i = 0; i < ROW_COUNT; i++) {
            if (containerArr.length >= i) {
                $("#" + containerArr[currentRowIndex * ROW_COUNT + i]).show();
            }
        }

        $("#preview-window-preview-btn").show();
        $("#preview-window-container-bar").show();
        $("#preview-window-back-btn").hide();
        $("#preview-window-scale-range").hide();
        $("#preview-window-popup .preview-window-scale-num").hide();

        event.preventDefault();
    });

    $("#preview-window-container-bar").slider({
        orientation: "vertical",
        min: 0,
        max: 100,
        value: 100,
        slide: function(event, ui) {
            var rangeSize = 100 / rowNum, start, end, i;

            for (i = 0; i < rowNum; i++) {
                start = 100 - i * rangeSize;
                end = (i + 1 < rowNum) ? (100 - (i + 1) * rangeSize) : 0;
                if (start >= ui.value && end < ui.value) {
                    currentRowIndex = i;
                }
            }
            $("#preview-window-container-div table").hide();
            for (i = 0; i < ROW_COUNT; i++) {
                if (containerArr.length >= i) {
                    $("#" + containerArr[currentRowIndex * ROW_COUNT + i]).show();
                }
            }
        }
    });
}

function _showPreviewWindow() {
    var position_x;

    position_x = (($(window).width() - 800) / 2) < 0 ? 0 : ($(window).width() - 800) / 2;
    $("#preview-window-popup").css("top", 80);
    $("#preview-window-popup").css("left", position_x);
    $("#preview-window-popup").show("slide", {direction: "up"}, "slow" ,function () {
        $("#overlayBackground").css("width", $(window).width());
        $("#overlayBackground").css("height", $(window).height());
        $("#overlayBackground").show("fade", "slow");
        _showPreviewLayouts();
        _bindEventsForPreviewWindow();
        $("#preview-window-container-div table:first-child").trigger("click");
    });
}

module.exports = {
    initialize : function() {
        previewContainer = $("#preview-window-container-div");
        $("#options-button-preview-window").bind("click", function () {
            previewContainer.html("");
            $("#preview-window-preview-btn").show();
            $("#preview-window-container-bar").show();
            $("#preview-window-back-btn").hide();
            $("#preview-window-scale-range").hide();
            $("#preview-window-popup .preview-window-scale-num").hide();

            prevLeft = 20;

            oldLeft = oldTop = 0;
            oldScale = 1;
            oldContainer = null;

            rowIndex = 0;
            currentRowIndex = 0;
            containerArr = [];

            _initializeDeviceResolutions();
            _readPreviewSourceHtml();
            _showPreviewWindow();
        });
    }
};

});
define('ripple/ui/plugins/push', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    event = require('ripple/event'),
    utils = require('ripple/utils'),
    db = require('ripple/db'),
    PUSH_OPTIONS = constants.PUSH.OPTIONS;

function _updatePushPanel(ports) {
    var portsSelect = document.getElementById("port-select"),
        currentPort = portsSelect.value;

    portsSelect.innerHTML = "";

    ports.forEach(function (port) {
        portsSelect.appendChild(utils.createElement("option", {
            innerText: port,
            value: port,
            selected: currentPort === port
        }));
    });
}

module.exports = {
    panel: {
        domId: "push-container",
        collapsed: true,
        pane: "left"
    },
    initialize: function () {
        event.on("PushListenersChanged", function (listeners) {
            _updatePushPanel(listeners);
            jQuery("#port-select").effect("highlight", {color: "#62B4C8"}, 1000);
        });

        _updatePushPanel([]);

        document.getElementById("push-send")
            .addEventListener("click", function () {
                var port = document.getElementById("port-select").value,
                    text = document.getElementById(PUSH_OPTIONS.PAYLOAD).value,
                    pushData = {
                        headerField: ["21f39092"],
                        requestURI: "/",
                        source: "ripple",
                        isChannelEncrypted: false,
                        payload: text
                    };

                event.trigger("Push", [pushData, port], true);
            }, false);

        utils.bindAutoSaveEvent(jQuery("#" + PUSH_OPTIONS.PAYLOAD), function () {
            db.save(PUSH_OPTIONS.PAYLOAD, document.getElementById(PUSH_OPTIONS.PAYLOAD).value);
        });

        document.getElementById(PUSH_OPTIONS.PAYLOAD).value = db.retrieve(PUSH_OPTIONS.PAYLOAD) || "My payload data";
    }
};

});
define('ripple/ui/plugins/sensorSettings', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * 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 constants = require('ripple/constants'),
    sensorSettings = require('ripple/sensorSettings'),
    utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    platform = require('ripple/platform'),
    _CONST = {
        "CONTENT_CONTAINER_ID": "sensorsettings-content-container",
        "UKNOWN_CONTROL_MESSAGE": "Unknown sensor control type"
    },
    _contentContainer,
    _CONTAINER_ID = _CONST.CONTENT_CONTAINER_ID;

function _appendSettingNode(labelNode, inputNode, label) {
    var frag = document.createDocumentFragment(),
        rowNode = frag.appendChild(utils.createElement("tr")),
        tempTdNode;

    rowNode.appendChild(utils.createElement("td"))
           .appendChild(labelNode);

    tempTdNode = rowNode.appendChild(utils.createElement("td"));

    if (label) {
        tempTdNode.appendChild(label);
    }

    tempTdNode.appendChild(inputNode);

    return frag;
}

function _buildDOMNode(setting, settingType, key) {
    var settingsNode, tagName, jNode,
        fullKey = settingType + "." + key,
        savedSetting = sensorSettings.retrieve(fullKey),
        // TODO: move this into Utils (isSet method)
        currentSetting = (savedSetting || savedSetting === false || savedSetting === "" || savedSetting === 0) ? savedSetting : setting.control.value,
        domNode,
        domNodeLabel = null;

    switch (setting.control.type) {
    case "text":
    case "number":
    case "range":
    case "checkbox":
        tagName = "input";
        break;
    case "textarea":
        tagName = "textarea";
        break;
    case "select":
        tagName = "select";
        break;
    default:
        exception.raise(exception.types.Application, _CONST.UKNOWN_CONTROL_MESSAGE);
    }

    settingsNode = utils.createElement(tagName, setting.control.type === "select" ? null : setting.control);

    // TODO: this should really be part of utils.createControl? add element of type "range" with label?
    if (setting.control.type === "range") {
        domNodeLabel = utils.createElement("label", {
            "class": constants.UI.LEFT_RANGE_LABEL_CLASS
        });
    }

    domNode = _appendSettingNode(utils.createElement("span", {"innerText": setting.name, "class": constants.UI.TEXT_LABEL_CLASS}), settingsNode, domNodeLabel);

    jNode = jQuery(settingsNode);
    jNode.addClass(constants.UI.JQUERY_UI_INPUT_CLASSES);

    switch (setting.control.type) {
    case "checkbox":
        jNode.bind("click", function () {
            var checked = this.checked ? true : false;
            sensorSettings.persist(fullKey, checked);
            if (typeof setting.callback === "function") {
                setting.callback(checked);
            }
        });

        if (currentSetting === true) {
            jNode.attr("checked", "checked");
        }

        break;

    case "text":
    case "textarea":
    case "number":
        jNode.val(currentSetting);
        utils.bindAutoSaveEvent(jNode, function () {
            sensorSettings.persist(fullKey, jNode.val());
            if (typeof setting.callback === "function") {
                setting.callback(jNode.val());
            }
        });
        break;

    case "select":
    case "range":
        if (setting.control.type === "select") {
            utils.forEach(setting.options,  function (value, option) {
                jNode.append(utils.createElement("option", {
                    "value": option,
                    "innerText": value
                }));
            });
        }
        else {
            if (domNodeLabel) {
                domNodeLabel.innerText = currentSetting;
            }
        }

        jNode.val(currentSetting)
             .bind("change", function () {
                if (setting.control.type === "range" && domNodeLabel) {
                    domNodeLabel.innerText = jQuery(this).val();
                }
                sensorSettings.persist(fullKey, jQuery(this).val());

                if (typeof setting.callback === "function") {
                    setting.callback(jQuery(this).val());
                }
            }
        );
    }

    // TODO: Brent, do in DeviceSettings on load instead?
    if (currentSetting !== setting.control.value) {
        sensorSettings.register(fullKey, currentSetting);
    }

    return domNode;
}

// goes through current platforms sensor settings
// adds nodes to panel and binds respective events
// talks to SensorSettings for persistence
module.exports = {
    panel: {
        domId: "sensors-panel-container",
        collapsed: true,
        pane: "right",
        titleName: "Sensors",
        display: true
    },
    initialize: function () {
        var settings;

        _contentContainer = document.getElementById(_CONTAINER_ID);

        settings = platform.current().sensor;

        utils.forEach(settings, function (settingSection, settingType) {

            var currentTableNode, flag = false;
            
            utils.forEach(settingSection, function (setting, key) {
                if (typeof setting === "object") {
                    flag = true;
                    return;
                }
            });

            if (flag) {
                _contentContainer.appendChild(utils.createElement("h3", { "innerText": settingType }));
            }

            currentTableNode = utils.createElement("table", {
                "class": constants.UI.PANEL_TABLE_CLASS
            });

            _contentContainer.appendChild(currentTableNode);

            utils.forEach(settingSection, function (setting, key) {
                if (typeof setting === "object") {
                    currentTableNode.appendChild(_buildDOMNode(setting, settingType, key));
                }

            });
        });
    }
};

});
define('ripple/ui/plugins/sensors', function (require, exports, module) {
/*
 * Copyright (c) 2010 Epic Train Hack
 * Copyright (c) 2011 Research In Motion Limited
 * Contributors: Wolfram Kriesing, Dan Silivestru, Brent Lintner
 *
 * 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 event = require('ripple/event'),
    accelerometer = require('ripple/accelerometer'),
    deviceSettings = require('ripple/deviceSettings'),
    Acceleration = require('ripple/platform/w3c/1.0/Acceleration'),
    Rotation = require('ripple/platform/w3c/1.0/Rotation'),
    sensorSettings = require('ripple/sensorSettings'),
	platform = require('ripple/platform'),
    _oldX, _oldY, _oldAlphaX,
    _camera, _scene, _renderer, _mesh, _params = {},
    _offsets = {
        x: 0,
        y: 0,
        z: -9.81,
    },
    _flag, // whether the browser supports webGL
    _shape =
        //
        // The front side
        //
        // x, y, z      x, y, z         x, y, z
        // for some strange reason for y -100 is top, 100 is bottom
        "-30,30,10,     30,30,10,       30,60,10,       100,100,100,-1,0;" + // top left, top right, bottom right - of the right triangle
        "-30,30,10,     30,60,10,       -30,60,10,      100,100,100,-1,0;" + // top left, right bottom, left bottom - of the left triangle
        // front side "the phone display"
        "-20,-50,11,    20,-50,11,      20,20,11,       100,100,100,-1,0;" +
        "-20,-50,11,    20,20,11,       -20,20,11,      100,100,100,-1,0;" +
        // below the display
        "-30,30,10,     30,20,10,       30,30,10,       0,0,0,-1,0;" +
        "-30,30,10,     -30,20,10,      30,20,10,       0,0,0,-1,0;" +
        // above the display
        "-30,-60,10,    30,-60,10,      30,-50,10,      0,0,0,-1,0;" +
        "-30,-60,10,    30,-50,10,      -30,-50,10,     0,0,0,-1,0;" +
        // left of the display
        "-30,-50,10,    -20,-50,10,     -20,20,10,      0,0,0,-1,0;" +
        "-30,-50,10,    -20,20,10,      -30,20,10,      0,0,0,-1,0;" +
        // right of the display
        "20,-50,10,     30,-50,10,      30,20,10,       0,0,0,-1,0;" +
        "20,-50,10,     30,20,10,       20,20,10,       0,0,0,-1,0;" +


        // back side, opposite side to the above one
        "-30,-60,-10,   30,60,-10,      30,-60,-10,     0,0,0,-1,0;" +
        "-30,-60,-10,   -30,60,-10,     30,60,-10,      0,00,-1,0;" +
        // right side
        "30,-60,-10,    30,60,-10,      30,60,10,       50,50,80,-1,0;" +
        "30,-60,-10,    30,60,10,       30,-60,10,      50,50,80,-1,0;" +
        // left side
        "-30,-60,-10,   -30,60,10,      -30,60,-10,     50,50,80,-1,0;" +
        "-30,-60,-10,   -30,-60,10,     -30,60,10,      50,50,80,-1,0;" +

        // top
        "30,-60,-10,    -30,-60,10, -30,-60,-10,    50,80,50,-1,0;" +
        "30,-60,-10,    30,-60,10,      -30,-60,10, 50,80,50,-1,0;" +
        // bottom
        "30,60,-10, -30,60,-10,     -30,60,10,      80,50,50,-1,0;" +
        "30,60,-10, -30,60,10,      30,60,10,       80,50,50,-1,0";

function _createThreeDModel() {
    var node,
        shader,
        hemiLight,
        dirLight,
        material,
        uniforms,
        container,
        loader,
        directionalLight,
        isDiffuseTextureLoaded,
        isNormalTextureLoaded,
        shiftKeyDown,
        mouseDown,
        ctrlKeyDown = false;

	
	window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(string, key, value) {
    	_params[key] = value;
    });

    if (_flag) {
        // create a 3D phone model with three.js if webGL is supported
        node = document.getElementById("accelerometer-div");
        container = document.createElement("div");
        $("#accelerometer-div").append(container);

        _camera = new THREE.PerspectiveCamera(50, 1.5, 0.1, 100);
        _camera.position.set(4.32823, 3.74714, 2.62985);
        _scene = new THREE.Scene();
        _scene.add(new THREE.AmbientLight(0xffffff));
        directionalLight = new THREE.DirectionalLight(0xffffff, 1);
        directionalLight.position.set(1, 1, 1).normalize();
        _scene.add(directionalLight);
        hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
        hemiLight.color.setHSV(0.6, 0.75, 1);
        hemiLight.groundColor.setHSV(0.095, 0.5, 1);
        hemiLight.position.set(0, 500, 0);
        _scene.add(hemiLight);
        dirLight = new THREE.DirectionalLight(0xffffff, 1);
        dirLight.color.setHSV(0.1, 0.1, 1);
        dirLight.position.set(-1, 1.75, 1);
        dirLight.position.multiplyScalar(50);
        _scene.add(dirLight);
        shader = THREE.ShaderSkin["skin"];
        uniforms = THREE.UniformsUtils.clone(shader.uniforms);
        uniforms["tNormal"].value = THREE.ImageUtils.loadTexture("images/phoneMap_tNormal.png", {}, function () {
            isNormalTextureLoaded = true;
            if (isDiffuseTextureLoaded) {
                _renderer.clear();
                _renderer.render(_scene, _camera);
            }
        });
        uniforms["uNormalScale"].value = 0.75;

		if(_params.platform === "wearable-2.0"){
		    uniforms["tDiffuse"].value = THREE.ImageUtils.loadTexture("images/phoneMap_tDiffuse_wearable.png", {}, function () {
		        isDiffuseTextureLoaded = true;
		        if (isNormalTextureLoaded) {
		            _renderer.clear();
		            _renderer.render(_scene, _camera);
		        }
		    });
		} else {
		    uniforms["tDiffuse"].value = THREE.ImageUtils.loadTexture("images/phoneMap_tDiffuse.png", {}, function () {
		        isDiffuseTextureLoaded = true;
		        if (isNormalTextureLoaded) {
		            _renderer.clear();
		            _renderer.render(_scene, _camera);
		        }
		    });
		}			
        uniforms["uDiffuseColor"].value.setHex(0xbbbbbb);
        uniforms["uSpecularColor"].value.setHex(0x070707);
        uniforms["uAmbientColor"].value.setHex(0x111111);
        uniforms["uRoughness"].value = 0.185;
        uniforms["uSpecularBrightness"].value = 0.8;
        material = new THREE.ShaderMaterial({ fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true });
        loader = new THREE.JSONLoader(true);
        document.body.appendChild(loader.statusDomElement);

        loader.load("phoneModel.js", function (geometry) {
            loader.statusDomElement.style.display = "none";
            geometry.computeTangents();
            _mesh = new THREE.Mesh(geometry, material);
            _mesh.position.set(7, 2, -50);
            _mesh.scale.set(18, 12, 18);
            _scene.add(_mesh);
            _renderer.clear();
            _renderer.render(_scene, _camera);
        });

        _renderer = new THREE.WebGLRenderer({antialias: false});
        _renderer.setSize(300, 280);
        _renderer.setClearColorHex(0xffffff, 1);
        _renderer.autoClear = false;

        container.appendChild(_renderer.domElement);
    } else { // create the model with 3d.js
        node = document.querySelector("#accelerometer-canvas");

        jQuery("#accelerometer-div").css("display", "none");
        jQuery("#accelerometer-canvas").css("display", "block");
        ThreeDee.setCenter(150, 100);
        ThreeDee.setLight(-300, -300, 800);
        _updateCanvas(0, 0);
    }

    //change accelerometer and phone by moving the mouse and the key "shift"
    node.addEventListener("mousemove", function (event) {
        var cosX, sinX, cosY, sinY,
            alpha = accelerometer.getInfo().orientation.alpha,
            beta = accelerometer.getInfo().orientation.beta,
            gamma = accelerometer.getInfo().orientation.gamma,
            x = accelerometer.getInfo().acceleration.x,
            y = accelerometer.getInfo().acceleration.y,
            z = accelerometer.getInfo().acceleration.z;

        if (!mouseDown) {
            return;
        }

        // if the shift key is pressed down, only the alpha value will be chagned
        if (!shiftKeyDown) {
            _offsets.x = (_offsets.x + _oldX - event.offsetX) % 360;
            _offsets.y = (_offsets.y + _oldY - event.offsetY) % 360;

            alpha = alpha || 0;

            // enforce gamma in [-90,90] as per w3c spec
            gamma = -_offsets.x;
            if (gamma < -90) {
                gamma = -90;
            }
            if (gamma > 90) {
                gamma = 90;
            }

            // enforce beta in [-180,180] as per w3c spec
            beta = -_offsets.y % 360;
            if (beta < -180) {
                beta += 360;
            }
            else if (beta >= 180) {
                beta -= 360;
            }

            cosX = Math.cos(gamma * (Math.PI / 180));
            sinX = Math.sin(gamma * (Math.PI / 180));
            cosY = Math.cos(beta * (Math.PI / 180));
            sinY = Math.sin(beta * (Math.PI / 180));
            x = 9.81 * cosY * sinX;
            y = -9.81 * sinY;
            z = -9.81 * cosY * cosX;

        } else {
            alpha = (alpha - (_oldAlphaX - event.offsetX) * 2.5) % 360;
        }
        _oldX = event.offsetX;
        _oldY = event.offsetY;
        _oldAlphaX = event.offsetX;
        if (_flag)
            _updatePhoneModel(alpha, beta, gamma);
        else
            _updateCanvas(alpha, -beta, gamma);
        accelerometer.setInfo({
            x: x,
            y: y,
            z: z,
            alpha: alpha,
            beta: beta,
            gamma: gamma
        });
    }, false);

    node.addEventListener("mousedown", function (e) {
        mouseDown = true;
        _oldX = e.offsetX;
        _oldY = e.offsetY;
        if (shiftKeyDown) {
            _oldAlphaX = _oldX;
        }
    });

    node.addEventListener("mouseup", function () {
        mouseDown = false;
    });

    document.addEventListener("mouseup", function () {
        //Catch mouseup events that fire when outside canvas bounds
        mouseDown = false;
    });

    document.addEventListener("keydown", function (e) {
        switch (e.keyCode) {
        case 16:                // Shift Key
            shiftKeyDown = true;
            break;
        case 17:                // Ctrl Key
            ctrlKeyDown = true;
            break;
        case 74:                // J Key
            if (shiftKeyDown && ctrlKeyDown) { //if shift+ctrl+j keydown in the meantime, console comes up rather than shift key down
                shiftKeyDown = false;
                ctrlKeyDown = false;
            }
            break;
        }
    });

    document.addEventListener("keyup", function (e) {
        if (e.keyCode === 16) { // Shift Key
            shiftKeyDown = false;
        }
    });
}

// update the 3d model created by 3d.js
function _updateCanvas(a, b, g) {
    ThreeDee.loadMesh(_shape);
    g = g || 0;
    ThreeDee.rotate(0, g, 0);
    ThreeDee.rotate(b, 0, a);
    ThreeDee.backface();
    ThreeDee.shade();
    ThreeDee.zSort();
    Draw.initialize(document.querySelector("#accelerometer-canvas"));
    Draw.clear(0, 0, 480, 300);
    Draw.drawScene(ThreeDee.getTranslation(), 3);
}

// update the 3d model created by three.js
function _updatePhoneModel(a, b, g) {
    _mesh.rotation.x = b / 90 * 1.5;
    _mesh.rotation.y = g / 90 * 1.5;
    _mesh.rotation.z = a / 90 * 1.5;
    _renderer.clear();
    _renderer.render(_scene, _camera);
}

function _resetAccelerometer() {
    _oldX = 0;
    _oldY = 0;
    _oldAlphaX = 0;
    _offsets = {
        x: 0,
        y: 0,
        z: -9.81
    };
    if (_flag) {
        _mesh.rotation.x = 0;
        _mesh.rotation.y = 0;
        _mesh.rotation.z = 0;
        _renderer.clear();
        _renderer.render(_scene, _camera);
    } else {
        _updateCanvas(0, 0);
    }

    accelerometer.setInfo({
        acceleration: new Acceleration(0, 0, 0),
        accelerationIncludingGravity: new Acceleration(0, 0, -9.81),
        rotationRate: new Rotation(0, 0, 0),
        orientation: new Rotation(0, 0, 0),
        timestamp: new Date().getTime()
    });
    accelerometer.triggerEvent();
}

function _resetMagneticField() {
    jQuery("#magnetic-x").val("100");
    jQuery("#magnetic-y").val("100");
    jQuery("#magnetic-z").val("100");
}

function _resetLightLevel() {
    $("#display-state").children().each(function() {
        if ($(this).val() === "OFF") {
            $(this).attr("selected", "true");
            this.selected = true;
        }
        else {
            $(this).attr("selected", "false");
            this.selected = false;
        }
    });
}


// set a typical mode for accelerometer simulation, when the phone drops,
// x will become to be 0, y will become to be -9.81 and z will become to be 0
function _setDrop() {
    //duration = 20 * 50 = 1000ms. 20 is ths number of steps and 50 is the duration of steps.
    var alpha = Number(accelerometer.getInfo().orientation.alpha),
        beta = Number(accelerometer.getInfo().orientation.beta),
        gamma = Number(accelerometer.getInfo().orientation.gamma),
        cosX, cosY, sinX, sinY, x, y, z,
        alphaStep = Math.abs(alpha) / 20,
        betaStep = Math.abs(beta - 90) / 20,
        gammaStep = Math.abs(gamma) / 20,
        counts = 0, dropTimeout,
        drop = function () {
            if (counts >= 20) {
                window.clearTimeout(dropTimeout);
                // to avoid showing "-0" or "-0.00"
                if (_flag)
                    _updatePhoneModel(0, 90, 0);
                else
                    _updateCanvas(0, -90, 0);
                accelerometer.setInfo({
                    x: 0,
                    y: -9.81,
                    z: 0,
                    alpha: 0,
                    beta: 90,
                    gamma: 0
                });
            } else {
                dropTimeout = setTimeout(drop, 50);
                step();
                counts++;
            }
        },
        step = function () {
            var _beta;

            alpha = alpha > 0 ? alpha - alphaStep : alpha + alphaStep;
            beta = beta > 90 ? beta - betaStep : beta + betaStep;
            gamma = gamma > 0 ? gamma - gammaStep : gamma + gammaStep;
            _beta = _flag ? beta + betaStep : -(beta + betaStep);
            if (_flag)
                _updatePhoneModel(alpha, _beta, gamma);
            else
                _updateCanvas(alpha, _beta, gamma);

            cosX = Math.cos(gamma * (Math.PI / 180));
            sinX = Math.sin(gamma * (Math.PI / 180));
            cosY = Number(Math.cos(beta * (Math.PI / 180)).toFixed(6));
            sinY = Math.sin(beta * (Math.PI / 180));
            x = 9.81 * cosY * sinX;
            y = -9.81 * sinY;
            z = -9.81 * cosY * cosX;
            accelerometer.setInfo({
                x: x,
                y: y,
                z: z,
                alpha: alpha,
                beta: beta,
                gamma: gamma
            });
            _offsets.x = -gamma;
            _offsets.y = -beta;
        };

    drop();
}

function _initializeSensorSettings() {
    var sensorsInputID = ["accelerometer-alpha", "accelerometer-beta", "accelerometer-gamma", "magnetic-x", "magnetic-y", "magnetic-z"],
        magneticEvent = ["MagneticField-xChanged", "MagneticField-yChanged", "MagneticField-zChanged"],
         magneticData = ["MagneticField.x", "MagneticField.y", "MagneticField.z"],
        oldValue, oldInputX,
        inputMouseDown,
        triggerFunction,
        selectedInputID = null;

    triggerFunction = function (val, index) {
        var cosX, cosY, sinX, sinY, x, y, z,
            alpha = accelerometer.getInfo().orientation.alpha,
            beta = accelerometer.getInfo().orientation.beta,
            gamma = accelerometer.getInfo().orientation.gamma;

        //choose which value to change according to index
        switch (index) {
        case 0:
            alpha = val;
            break;
        case 1:
            beta = val;
            break;
        case 2:
            gamma = val;
            break;
        default:
            sensorSettings.persist(magneticData[index - 3], val);
            event.trigger(magneticEvent[index - 3], [val]);
        }

        //change the phone model and values of other inputs when changing a value of input
        if (_flag)
            _updatePhoneModel(alpha, beta, gamma);
        else
            _updateCanvas(alpha, -beta, gamma);
        cosX = Math.cos(gamma * (Math.PI / 180));
        sinX = Math.sin(gamma * (Math.PI / 180));
        cosY = Math.cos(beta * (Math.PI / 180));
        sinY = Math.sin(beta * (Math.PI / 180));
        x = 9.81 * cosY * sinX;
        y = -9.81 * sinY;
        z = -9.81 * cosY * cosX;
        accelerometer.setInfo({
            x: x,
            y: y,
            z: z,
            alpha: alpha,
            beta: beta,
            gamma: gamma
        });
        _offsets.x = -gamma;
        _offsets.y = -beta;
    };

    // make the input elements more powful: drag mouse to left to decrease the value and right to increase it;
    // also change the value with arrow keys.


    sensorsInputID.forEach(function (id, index) {
        jQuery("#" + id).mousedown(function (e) {
            selectedInputID = id;
            oldValue = parseInt(this.value, 10);
            oldInputX = e.offsetX;
            inputMouseDown = true;
        });

        jQuery("#" + id).mousemove(function (e) {
            if (inputMouseDown && (selectedInputID !== null)) {
                jQuery("#" + selectedInputID).val(parseInt(oldValue + (e.offsetX - oldInputX) / 2, 10));
                if (parseInt(this.value, 10) <= parseInt(jQuery(this).attr("minValue"), 10)) {
                    this.value = jQuery(this).attr("minValue");
                }
                if (parseInt(this.value, 10) >= parseInt(jQuery(this).attr("maxValue"), 10)) {
                    this.value = jQuery(this).attr("maxValue");
                }
                triggerFunction(this.value, index);
            }
        });

        jQuery("#" + id).mouseup(function () {
            selectedInputID = null;
            inputMouseDown = false;
        });
        jQuery(document).mouseup(function () {
            selectedInputID = null;
            inputMouseDown = false;
        });

        jQuery("#" + id).click(function () {
            this.select();
        });

        jQuery("#" + id).blur(function () {
            if (isNaN(this.value)) {
                this.value = 0;
            }
            else if (parseInt(this.value, 10) > parseInt(jQuery(this).attr("maxValue"), 10))
                this.value = jQuery(this).attr("maxValue");
            else if (parseInt(this.value, 10) < parseInt(jQuery(this).attr("minValue"), 10))
                this.value = jQuery(this).attr("minValue");
            else
                this.value = parseInt(this.value, 10);
            triggerFunction(this.value, index);
        });

        jQuery("#" + id).keydown(function (e) {
            switch (e.keyCode) {
            case 38:
                if (parseInt(this.value, 10) < parseInt(jQuery(this).attr("maxValue"), 10)) {
                    this.value = parseInt(this.value, 10) + 1;
                    triggerFunction(this.value, index);
                }
                break;
            case 40:
                if (parseInt(this.value, 10) > parseInt(jQuery(this).attr("minValue"), 10)) {
                    this.value = parseInt(this.value, 10) - 1;
                    triggerFunction(this.value, index);
                }
                break;
            default:
                return;
            }
        });
    });
}

/*
//initialize light settings
function _initializeLightSettings() {
    var displayObj = document.getElementById("display-state"),
        DISPLAY_STATE  = require('ripple/constants').POWER_RESOURCE.SCREEN.STATE,
        brightness;

    displayObj.addEventListener("change", function () {
        var state = displayObj.value, value;
        value = DISPLAY_STATE[state].VALUE;
        deviceSettings.persist("Display.brightness", value);
        event.trigger("DisplayBrightnessChanged", [value]);
    });

    brightness = deviceSettings.retrieve("Display.brightness");
    if (brightness ===  DISPLAY_STATE.SCREEN_OFF.MAX) {
        displayObj.options[0].selected = true;
    } else if (brightness <= DISPLAY_STATE.SCREEN_DIM.MAX) {
        displayObj.options[1].selected = true;
    } else if (brightness <= DISPLAY_STATE.SCREEN_NORMAL.MAX) {
        displayObj.options[2].selected = true;
    } else {
        displayObj.options[3].selected = true;
    }
}
*/

module.exports = {
    panel: {
        domId: "sensors-container",
        collapsed: true,
        pane: "left",
        titleName: "Sensors",
        display: true
    },
    initialize: function () {
        var gl,
            testCanvas = document.getElementById("accelerometer-canvas");

        try { // check whether the browser supports webGL, returns null if not support
            gl = testCanvas.getContext("experimental-webgl");
            gl.viewport(0, 0, testCanvas.width, testCanvas.height);
        } catch (e) {
            console.log("unsupport webgl");
        }

        _flag = gl ? true : false;

        accelerometer.init();
        _createThreeDModel();
        _initializeSensorSettings();
        //_initializeLightSettings();

        jQuery("#accelerometer-shake").click(function () {
            window.setTimeout(require('ripple/ui/plugins/goodVibrations').shakeDevice(8), 1);
            accelerometer.shake();
        });

        jQuery("#sensor-reset-all").click(function () {
            _resetAccelerometer();
            _resetMagneticField();
            _resetLightLevel();
        });

        jQuery("#accelerometer-drop").click(_setDrop);

        event.on("AccelerometerInfoChangedEvent", function (motion) {
            jQuery("#accelerometer-x").html(motion.accelerationIncludingGravity.x.toFixed(2));
            jQuery("#accelerometer-y").html(motion.accelerationIncludingGravity.y.toFixed(2));
            jQuery("#accelerometer-z").html(motion.accelerationIncludingGravity.z.toFixed(2));
            jQuery("#accelerometer-alpha").val(Number(motion.orientation.alpha).toFixed(2));
            jQuery("#accelerometer-beta").val(Number(motion.orientation.beta).toFixed(2));
            jQuery("#accelerometer-gamma").val(Number(motion.orientation.gamma).toFixed(2));
        }, this);
    }
};

});
define('ripple/ui/plugins/settings-dialog', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    utils = require('ripple/utils'),
    platform = require('ripple/platform'),
    notifications = require('ripple/notifications'),
    tooltip = require('ripple/ui/plugins/tooltip'),
    bus = require('ripple/bus'),
    required = {
        build: {
            "webworks.tablet": ["sdk", "projectPath", "outputPath", "projectName"],
            "webworks.bb10": ["sdk", "projectPath", "outputPath", "projectName"],
            "webworks.handset": ["sdk", "projectPath", "outputPath", "projectName"]
        },
        sign: {
            "webworks.tablet": ["sdk", "projectPath", "outputPath", "projectName", "csk_password", "p12_password", "bundle_number"],
            "webworks.bb10": ["sdk", "projectPath", "outputPath", "projectName", "signingPassword", "bundle_number"],
            "webworks.handset": ["sdk", "projectPath", "outputPath", "projectName", "signingPassword"]
        },
        launch: {
            "webworks.tablet": ["sdk", "projectPath", "outputPath", "projectName", "device"],
            "webworks.bb10": ["sdk", "projectPath", "outputPath", "projectName", "device"],
            "webworks.handset": ["sdk", "projectPath", "outputPath", "projectName", "simulator"]
        }
    },
    _settings = {
        get: function () {
            var settings = db.retrieveObject("build-settings", platform.getPersistencePrefix()) || {};
            settings.debug = !!settings["remoteInspector"];

            return settings;
        },
        save: function (settings) {
            db.saveObject("build-settings", settings, platform.getPersistencePrefix());
        }
    },
    port = "9910",
    host = "http://127.0.0.1:" + port + "/ripple",
    progressContainer = jQuery("#options-progress"),
    progressInterval,
    _passwordFields = [
        "signingPassword",
        "devicePassword",
        "csk_password",
        "p12_password"
    ],
    _checkboxFields = [
        "remoteInspector"
    ],
    _passwords = {},
    _self;

function missing(settings, action) {
    return required[action][platform.current().id].filter(function (field) {
        return !settings.hasOwnProperty(field);
    });
}

function _isPasswordField(id) {
    var match = typeof id === "string" && new RegExp("^" + id + "$", "i");
    return match && utils.some(_passwordFields, function (name) {
        return match.test(name);
    });
}

function _isCheckboxField(id) {
    var match = typeof id === "string" && new RegExp("^" + id + "$", "i");
    return match && utils.some(_checkboxFields, function (name) {
        return match.test(name);
    });
}

function table(action) {
    var _table = $("<table class='panel-table'>"),
        _row = {
            row: function (item, desc, opts) {
                var id = "settings-field-" + item.toLowerCase(),
                    input = "",
                    save = function () {
                        var s = _settings.get(),
                            v = $("#" + id).val(),
                            val = opts.type === "number" ? parseInt(v, 10) : v;

                        if (_isCheckboxField(item)) {
                            s[item] = $("#" + id).prop("checked");
                        }
                        else if (val) {
                            (_isPasswordField(item) ? _passwords : s)[item] = val;
                        }
                        else {
                            delete s[item];
                        }
                        _settings.save(s);

                        if (opts.onChanged) {
                            opts.onChanged(s[item]);
                        }
                    },
                    row;

                opts = opts || { type: "text" };

                switch (opts.type) {
                case "select":
                    input = "<select id='" + id + "' class='ui-state-default ui-corner-all' style='width:100%'/>";
                    break;
                case "span":
                    input = "<span id = '" + id + "'>" + opts.text + "</span>";
                    break;
                default:
                    input = "<input id='" + id + "' type='" + opts.type + "' class='ui-state-default ui-corner-all' style='width:90%' />";
                    break;
                }

                row = $("<tr>" +
                    "<td><label for='" + id + "' class='ui-text-label'>" + desc + "</label></td>" +
                    "<td>" + input + "</td>" +
                "</tr>");

                row.appendTo(_table);

                //bind save handlers to the row
                utils.bindAutoSaveEvent(row.find("#" + id).change(save), save);

                return _row;
            },
            appendTo: function (id) {
                var fs = $("<fieldset class='main'><legend class='cap-text'>" + action + "</legend></fieldset>");

                $(_table).appendTo(fs);
                fs.appendTo($(id));
            }
        };

    return _row;
}

function create() {
    var build = table('build'),
        sign = table('sign'),
        launch = table('launch');

    build
        .row("sdk", "SDK Path")
        .row("projectPath", "Project Root")
        .row("projectName", "Archive Name")
        .row("outputPath", "Output Folder")
        .row("remoteInspector", "Enable Remote Web Inspector", {
            type: "checkbox",
            onChanged: function (enabled) {
                if (enabled) {
                    $("#options-menu-build-warning").show();
                    tooltip.create("#options-menu-build-warning", "Remote Web Inspector should be disabled when packaging for App World release");
                }
                else {
                    $("#options-menu-build-warning").hide();
                }
            }
        })
        .appendTo("#settings-tabs-build");

    switch (platform.current().id) {
    case "webworks.handset":
        sign.row("signingPassword", "Password", {
            type: "password"
        });

        launch.row("simulator", "Simulator", {
            type: "select"
        });

        launch.row("simulatorstatus", "Simulator", {
            type: "span",
            text: "Searching for simulators ..."
        });
        
        break;

    case "webworks.tablet":
        sign.row("csk_password", "CSK Password", {
            type: "password"
        });
        sign.row("p12_password", "P12 Password", {
            type: "password"
        });
        sign.row("bundle_number", "Bundle Number", {
            type: "number"
        });

        launch.row("device", "Playbook IP");
        launch.row("devicePassword", "Playbook Password", {
            type: "password"
        });

        break;

    case "webworks.bb10":
        sign.row("signingPassword", "Signing Password", {
            type: "password"
        });
        sign.row("bundle_number", "Bundle Number", {
            type: "number"
        });

        launch.row("device", "Device IP");
        launch.row("devicePassword", "Device Password", {
            type: "password"
        });

        break;
    }

    sign.appendTo("#settings-tabs-build");
    launch.appendTo("#settings-tabs-build");

    $("#settings-field-simulator").parent().parent().hide();
}

function populate(settings) {
    var fill = function (action, prop) {
        var element = $("#settings-field-" + prop.toLowerCase());

        if (_isPasswordField(prop)) {
            element.val(_passwords[prop]);
        }
        else if (_isCheckboxField(prop)) {
            element.prop("checked", settings[prop]);
        }
        else {
            element.val(settings[prop]);
        }
    };

    fill("build", "sdk");
    fill("build", "projectPath");
    fill("build", "outputPath");
    fill("build", "projectName");
    fill("build", "remoteInspector");

    fill("sign", "signingPassword");
    fill("sign", "csk_password");
    fill("sign", "p12_password");
    fill("sign", "bundle_number");

    fill("launch", "simulator");
    fill("launch", "device");
    fill("launch", "devicePassword");
}

function url(action) {
    var target = "";

    switch (platform.current().id) {
    case "webworks.bb10":
        target = "bb10";
        break;
    case "webworks.tablet":
        target = "tablet";
        break;
    case "webworks.handset":
        target = "smartphone";
        break;
    }

    return host + "/" + action + "/" + target;
}

function enable(action) {
    $("#options-menu-" + action).removeClass("not-ready");
    if (action === "launch") {
        $("#settings-field-simulatorstatus").parent().parent().hide();
        $("#settings-field-simulator").parent().parent().show();
    }
}

function disable(action) {
    $("#options-menu-" + action).addClass("not-ready");
    if (action === "launch") {
        $("#settings-field-simulatorstatus").parent().parent().show();
        $("#settings-field-simulator").parent().parent().hide();
    }
}

function getSimulators() {
    if (!_settings.get().sdk) {
        $("#settings-field-simulatorstatus").text("");
        disable("launch");
        return;
    }

    bus.ajax(
        "POST",
        host + "/simulators",
        _settings.get(),
        function (resp) {
            var sims = resp.data.simulators;

            $("#settings-field-simulator").empty();
            if (sims.length > 0) {
                $(resp.data.simulators.map(function (sim) {
                    return "<option value='" + sim + "'>" + sim + "</option>";
                }).join()).appendTo("#settings-field-simulator");

                enable("launch");
            }
            else {
                disable("launch");
                $("#settings-field-simulatorstatus").text("No simulators found :(");
            }
        },
        function () {
            disable("launch");
            $("#settings-field-simulatorstatus").text("Error attempting to get simulators :(");
        }
    );
}

function _startProgress() {
    if (progressInterval) {
        window.clearInterval(progressInterval);
    }
    progressInterval = window.setInterval(function () {
        if (progressContainer.html().length === 5) {
            progressContainer.html(".");
        }
        else {
            progressContainer.html(progressContainer.html() + ".");
        }
    }, 250);
}

function _endProgress() {
    window.clearInterval(progressInterval);
    progressInterval = null;
    progressContainer.html("");
}


_self = {
    initialize: function () {
        $("#settings-dialog").dialog({
            autoOpen: false,
            modal: true,
            width: 700,
            title: "Settings",
            position: 'center'
        }).hide();

        $("#settings-tabs").tabs();
        $("#settings-action").button();

        create();

        if (platform.current().id === "webworks.handset") {
            enable("build");
            enable("sign");
            enable("settings");

            getSimulators();
            $("#settings-field-sdk").change(getSimulators);
        }
        else if (platform.current().id === "webworks.tablet") {
            enable("build");
            enable("sign");
            enable("launch");
            enable("settings");
        }
        else if (platform.current().id === "webworks.bb10") {
            enable("build");
            enable("sign");
            enable("launch");
            enable("settings");
        }
    },

    can: function (action) {
        var settings = {};

        utils.mixin(_settings.get(), settings);
        utils.mixin(_passwords, settings);

        return action && missing(settings, action).length === 0;
    },

    value: function (prop) {
        var settings = {};

        utils.mixin(_settings.get(), settings);
        return settings[prop];
    },

    show: function (action) {
        var settings = {};

        utils.mixin(_settings.get(), settings);
        utils.mixin(_passwords, settings);

        populate(settings);

        $("#settings-dialog").dialog("open");
        $("#settings-action").button("option", "label", action || "Close")[action ? "show" : "hide"]();

        if (action) {
            missing(settings, action).forEach(function (field) {
                $("#settings-field-" + field.toLowerCase()).effect("highlight", {color: "red"}, 1500);
            });

            $("#settings-action").unbind("click").click(function () {
                if (_self.can(action)) {
                    _self.perform(action);
                    $("#settings-dialog").dialog("close");
                }
                else {
                    _self.show(action);
                }
            });
        }
    },

    perform: function (action) {
        var settings = _settings.get(),
            data = {},
            poll = function (resp) {
                var notifications = require("ripple/notifications");

                if (resp && resp.code !== 0) {
                    notifications.openNotification("error", "Build request failed with message: " + resp.msg);
                    _endProgress();
                }
                else {
                    if (resp && resp.data.status === "building") {
                        setTimeout(function () {
                            bus.ajax(
                                "GET",
                                host + "/build_status/" + resp.data.id,
                                null,
                                poll,
                                function (error) {
                                    notifications.openNotification("error", "Build request failed with message: " + JSON.stringify(error));
                                    _endProgress();
                                }
                            );
                        }, 500);
                    }
                    else {
                        if (action.match(/sign/)) {
                            settings["bundle_number"] = $("#settings-field-bundle_number").val(parseInt($("#settings-field-bundle_number").val(), 10) + 1).val();
                            _settings.save(settings);
                        }
                        notifications.openNotification("normal", "Build succeeded!");
                        _endProgress();
                    }
                }
            };

        utils.mixin(settings, data);
        utils.mixin(_passwords, data);

        bus.ajax(
            "POST",
            url(action),
            data,
            function (resp) {
                _startProgress();
                poll(resp);
            },
            function (error) {
                var message = "Build request failded with message: " + error.data;

                if (error.code === 0 || error.code === 404) {
                    message += "<br>This could be due to the Build and Deploy services not running or not being installed";
                }

                notifications.openNotification("error", message);
            }
        );
    }
};

module.exports = _self;

});
define('ripple/ui/plugins/settings-menu', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    constants = require('ripple/constants'),
    platform = require('ripple/platform'),
    db = require('ripple/db'),
    _applicationStateId
    ;


function reload() {
    window.tinyHipposReload = true;
    location.reload();
}

function _showSettingMenu() {
    var contentTable = "",
    settings = [],
    _applicationState = [],
    _applicationStateTmp = [],
    unselectedNum = 0,
    i = 0;

    if ($("#settings-menu-popup").is(":visible")) {
        $("#settings-menu-popup").hide("slide", {direction: "up"}, "slow");
        $("#overlayBackground").hide("fade", "slow");
        return;
    }

    _applicationStateId = constants.COMMON.APPLICATION_STATE + platform.current().id;

    _applicationStateTmp = db.retrieveObject(_applicationStateId) || [];

    utils.forEach(_applicationStateTmp, function (obj) {
        if (obj.display)
            _applicationState.push(obj);
    });

    utils.forEach(_applicationStateTmp, function (obj) {
        if (!obj.display)
            _applicationState.push(obj);
    });

    $("#settings-menu-content-panel-table").remove();

    contentTable = '<table id="settings-menu-content-panel-table" class="settings-menu-content-table">';
    utils.forEach(_applicationState, function (obj) {
        var checked = obj.display ? 'checked="yes"':"";
        contentTable += '<tr><td><input name="panel-display-setting" type="checkbox" class="settings-menu-checkbox "' +
                        checked + '></input>' +
                        obj.titleName + '</td></tr>\n';
    });
    contentTable += "</table>";

    $("#settings-menu-container-div").append(contentTable);
    $("#settings-menu-popup").css("top", 50);
    $("#settings-menu-popup").css("left", $(window).width() - 340);

    $("#overlayBackground").css("width", $(window).width());
    $("#overlayBackground").css("height", $(window).height());
    $("#overlayBackground").show("fade", "slow");
    $("#settings-menu-popup").show("slide", {direction: "up"}, "slow");

    $("#settings-menu-save-btn").unbind('click');
    $("#settings-menu-save-btn").bind("click", function (event) {
        $("input[name='panel-display-setting']").each(function (i, a) {
            settings.push(a.checked);
        });

        utils.forEach(_applicationState, function (obj) {
            if (!settings[i])
                obj.collapsed = true;
            obj.display = settings[i];
            i++;
        }, this);
  
        db.saveObject(_applicationStateId, _applicationState);
        _applicationStateTmp = db.retrieveObject(_applicationStateId) || [];

        $("#settings-menu-popup").hide("slide", {direction: "up"}, "slow");
        $("#overlayBackground").hide("fade", "slow");
        setTimeout(reload, 500);
    });

    $(".settings-menu-content-table td").unbind('click');
    $(".settings-menu-content-table td").bind("click", function (event) {
        var checkbox;
        if (($(event.target).children().length === 0)) {
            return;
        } else {
            checkbox = $(event.target).children();
        }
        
        if (checkbox.is(':checked')) {
            checkbox.prop('checked', false);
        }
        else
            checkbox.prop('checked', true);
    });

    $("#settings-menu-close-btn").unbind('click');
    $("#settings-menu-close-btn").bind("click", function (event) {
        if ($("#settings-menu-popup").is(":visible")) {
            $("#settings-menu-popup").hide("slide", {direction: "up"}, "slow");
            $("#overlayBackground").hide("fade", "slow");
            return;
        }
    });

    $(window).bind('resize', function () {
        $("#settings-menu-popup").css("top", 50);
        $("#settings-menu-popup").css("left", $(window).width() - 340);
        $("#overlayBackground").css("width", $(window).width());
        $("#overlayBackground").css("height", $(window).height());
    });

    $(".settings-menu-checkbox").each(function (i, a) {
        if (a.checked === false) {
            unselectedNum++;
        }
    });

    if (unselectedNum === 0) {
        $("#select_unselect_text").text("Unselect All");
        $("#panelSettingSelectAll").prop('checked', true);
    }

    $("#panelSettingSelectAll").unbind('click');
    $("#panelSettingSelectAll").bind("click", function (event) {
        if ($("#panelSettingSelectAll").is(':checked')) {
            $("#select_unselect_text").text("Unselect All");
            $(".settings-menu-checkbox").prop('checked', true);
        }
        else {
            $("#select_unselect_text").text("Select All");
            $(".settings-menu-checkbox").prop('checked', false);
        }
    });
}

module.exports = {
    initialize: function () {
        $("#options-button-panels").bind("click", function (event) {
            _showSettingMenu();
        });
    }
};

});
define('ripple/ui/plugins/settings', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 db = require('ripple/db'),
    constants = require('ripple/constants'),
    KEY = constants.XHR.PROXY_DISABLED_BUTTON; // TODO: one settings object for all

function _saveAndReload(key, value) {
    jWorkflow.order(function (prev, baton) {
        baton.take();
        db.save(key, value, null, baton.pass);
    }).start(function () {
        window.tinyHipposReload = true;
        location.reload();
    });
}

function _initialize(prev, baton) {
    var select = document.getElementById("settings-xhr-proxy"),
        about = require('ripple/ui/plugins/about-dialog');

    select.value = String(db.retrieve(KEY));
    select.addEventListener("change", function () {
        _saveAndReload(KEY, this.value);
    }, false);
    
    $("#options-menu-about").click(function () {
        about.show();
    });
    // TODO: reload here?
}

module.exports = {
    panel: {
        domId: "settings-container",
        collapsed: true,
        pane: "right"
    },
    initialize: _initialize
};

});
define('ripple/ui/plugins/storage', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    event = require('ripple/event'),
    platform = require('ripple/platform'),
    utils = require('ripple/utils'),
    app = require('ripple/app'),
    db = require('ripple/db');

function _updatePreferencesView() {
    var node = document.getElementById(constants.COMMON.STORAGE_TABLE_BODY_CLASS),
        countTitle = document.getElementById(constants.COMMON.STORAGE_COUNT_CONTAINER_ID);

    // TODO: convert to appendChild
    if (node) {
        db.retrieveAll(platform.getPersistencePrefix(), function (results) {
            var str = "",
                counter = 0;

            utils.forEach(results, function (value, key) {
                // TODO: based of current platform
                if (app.isPreferenceReadOnly(key)) {
                    str += '<tr class="ui-text-highlight">';
                } else {
                    str += '<tr>';
                }
                str += '<td>' + key + '</td><td>' + value + "</td></tr>";
                counter ++;
            });

            node.innerHTML = str;
            countTitle.innerHTML = counter.toString();

            if (counter === 0) {
                jQuery("#" + constants.COMMON.STORAGE_CLEAR_BUTTON_ID).addClass(constants.CSS_PREFIX.IRRELEVANT);
            }
            else {
                jQuery("#" + constants.COMMON.STORAGE_CLEAR_BUTTON_ID).removeClass(constants.CSS_PREFIX.IRRELEVANT);
            }
        });
    }
}

module.exports = {
    panel: {
        domId: "preferences",
        collapsed: true,
        pane: "left"
    },
    initialize: function () {
        jQuery("#preferences-clear-button").bind("click", function () {
            db.removeAll(platform.getPersistencePrefix());
        });

        event.on("StorageUpdatedEvent", function () {
            _updatePreferencesView();
        });

        _updatePreferencesView();
    }
};

});
define('ripple/ui/plugins/themeSwitcher', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    db = require('ripple/db'),
    THEME_KEY = "ui-theme",
    THEME_SELECTOR = "#theme-select",
    _currentTheme;

function _saveAndReload(key, value) {
    jWorkflow.order(function (prev, baton) {
                baton.take();
                db.save(key, value, null, baton.pass);
            }).start(function () {
                window.tinyHipposReload = true;
                location.reload();
            });
}

module.exports = {
    initialize: function () {
        var themeToSet = db.retrieve(THEME_KEY);

	// Hide the theme switcher and always set the theme to light
        jQuery(".theme-switcher").hide();
		if (themeToSet !== "light") {
            _saveAndReload(THEME_KEY, "light");
		}
		return;
    }
};

});
define('ripple/ui/plugins/time', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function _init() {
    var db = require('ripple/db'),
        utils = require('ripple/utils'),
        allTZ, dbTZ, node = jQuery("#time-locale-select"),
        timezone = require('ripple/platform/tizen/2.0/timezone_info'),
        event = require('ripple/event'),
        alarms, time;

    function triggerAlarm() {
        time = new Date();
        alarms = db.retrieveObject("tizen1.0-db-alarms");
        if (alarms !== null) {
            utils.forEach(alarms, function (obj) {
                if (obj.id !== undefined) {
                    event.trigger("CheckAlarm", [obj.id]);
                }
            });
        }
    }
    window.setInterval(triggerAlarm, 1000);

    allTZ = timezone.getAllTimezone();
    utils.forEach(allTZ, function (tz) {
        node.append(utils.createElement("option", {
            "value": tz,
            "innerHTML": tz + " - " + timezone.getTimezoneAbbr(tz) + "(" + timezone.getTimezoneDiff(tz) + ")"
        }));
    });
    dbTZ = db.retrieve("tizen-timezone");
    if (timezone.isValidTimezone(dbTZ)) {
        node.val(dbTZ);
    } else {
        db.save("tizen-timezone", node.val());
    }
    node.bind("change", function () {
        db.save("tizen-timezone", node.val());
    });
/* FIXME: Node "trigger-alarm-id" will be removed from Time panel
 *        due to "time" panel will changed to "time zone" panel(PTSDK-875)

    event.on("SendTriggerAppId", function (applicationId) {
        if (timeId !== undefined)
            clearTimeout(timeId);
        triggerNode.empty();
        triggerNode.append(utils.createElement("p", {
            "innerHTML": applicationId + " is triggered"
        }));
        triggerNode.show();
        timeId = setTimeout("jQuery('#trigger-alarm-id').empty();", 10000);// Comments will disappear after 10s
    });
*/
}

module.exports = {
    panel: {
        domId: "time-container",
        collapsed: true,
        pane: "right",
        titleName: "Time",
        display: true
    },
    initialize: _init
};

});
define('ripple/ui/plugins/tooltip', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 utils = require('ripple/utils'),
    _options = {
        track: true,
        delay: 0,
        showURL: false,
        fade: 250,
        extraClass: "ui-state-highlight ui-corner-all"
    };

module.exports = {
    create: function (element, message) {
        var options = utils.copy(_options);

        options.bodyHandler = function () {
            return message;
        };

        return jQuery(element).tooltip(options);
    },

    toggle: function () {
        jQuery.tooltip.block();
        return this.isOff();
    },

    isOff: function () {
        return jQuery.tooltip.blocked;
    }
};

});
define('ripple/ui/plugins/tooltips', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
// Class: UI.Tooltips
// Purpose: build tooltips for UI
// See here for Tooltip Options
// http://jquery.bassistance.de/tooltip/demo/
var utils = require('ripple/utils'),
    tooltip = require('ripple/ui/plugins/tooltip'),
    constants = require('ripple/constants'),
    db = require('ripple/db'),
    utils = require('ripple/utils');

function _updateButtonText() {
    document.querySelector("#settings-toggletooltips > span")
            .innerHTML = "Turn " + (tooltip.isOff() ? "On" : "Off");
}

module.exports = {
    initialize: function () {
        var saved = db.retrieve(constants.SETTINGS.TOOLTIPS_KEY);

        // blarg, tooltips are always enabled so if its saved to false disable it
        if (!tooltip.isOff() && (saved === "false" || saved === false)) {
            tooltip.toggle();
        }

        _updateButtonText();

        jQuery(constants.SETTINGS.TOOLTIPS_TOGGLE_DIV).click(function () {
            db.save(constants.SETTINGS.TOOLTIPS_KEY, !tooltip.toggle());
            _updateButtonText();
        });
    }
};

});
define('ripple/ui/plugins/touchEvent', function (require, exports, module) {
/*
 *  Copyright 2012 Intel Corporation
 *
 * 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 event = require('ripple/event'),
    db = require('ripple/db'),
    constants = require('ripple/constants'),
    colors  = ["red", "green", "magenta", "blue", "yellow"],
    Point,
    intervalId,
    moveEvents  = {},
    currentIndex = 0,
    enlargeRatio = 4;

function _exec(operation) {
    var canvas = document.getElementById(constants.TOUCHEVENT.CANVAS),
        cxt = canvas.getContext("2d"),
        altKey = document.getElementById(constants.TOUCHEVENT.ALTKEY),
        metaKey = document.getElementById(constants.TOUCHEVENT.METAKEY),
        ctrlKey = document.getElementById(constants.TOUCHEVENT.CTRLKEY),
        shiftKey = document.getElementById(constants.TOUCHEVENT.SHIFTKEY),
        key, eventType;

    if (operation === "start") {
        altKey.disabled = 'disabled';
        metaKey.disabled = 'disabled';
        ctrlKey.disabled = 'disabled';
        shiftKey.disabled = 'disabled';
        clearInterval(intervalId);
        currentIndex = 0;
        eventType = "touchEvent";
    } else if (operation === "cancel") {
        altKey.disabled = '';
        metaKey.disabled = '';
        ctrlKey.disabled = '';
        shiftKey.disabled = '';
        altKey.checked = false;
        metaKey.checked = false;
        ctrlKey.checked = false;
        shiftKey.checked = false;
        cxt.clearRect(0, 0, canvas.width, canvas.height);
        moveEvents = {};
        eventType = "touchCancel";
    }

    event.trigger(eventType, [{
        data : moveEvents,
        keys : [altKey.checked, metaKey.checked, ctrlKey.checked, shiftKey.checked]
    }]);
}

Point = function (x, y, color, isDragging) {
    var _self = {};

    _self.x = x;
    _self.y = y;
    _self.color = color;
    _self.isDragging = isDragging;

    return _self;
};

module.exports = {
    panel: {
        domId: "touchEvent-container",
        collapsed: true,
        pane: "left",
        titleName: "Touch Event",
        display: true
    },

    initialize: function () {
        var deviceInfo = require('ripple/devices').getCurrentDevice(),
            canvas = document.getElementById(constants.TOUCHEVENT.CANVAS),
            button = document.getElementById(constants.TOUCHEVENT.OPTION),
            cxt = canvas.getContext("2d"),
            points = [],
            paint = false,
            currentPoint = {};

        function drawPoints() {
            var key, index, points = [], point;

            for (key in moveEvents) {
                points = moveEvents[key];
                cxt.fillStyle = colors[key];

                for (index = 0; index < points.length; index++) {
                    point = points[index];
                    cxt.beginPath();
                    cxt.arc(point.offsetX, point.offsetY, 5, 0, 2 * Math.PI, 1);
                    cxt.fill();
                }
            }
        }

        function endDraw(event) {
            if (paint) {
                paint = false;
                clearInterval(intervalId);
                moveEvents[currentIndex].push(event);
                drawPoints();

                currentIndex++;
                if (currentIndex === 5)
                    currentIndex = 0;
            }
        }

        canvas.addEventListener("mousedown", function (event) {
            if (button.value === "Touch Cancel") {
                button.value = "Touch Start";
                _exec("cancel");
            }
            moveEvents[currentIndex] = [];
            currentPoint = event;
            moveEvents[currentIndex].push(event);
            paint = true;
            drawPoints();
            intervalId = setInterval(function () {
                moveEvents[currentIndex].push(currentPoint);
            }, 100);
        });

        canvas.addEventListener("mousemove", function (event) {
            if (paint) {
                currentPoint = event;
                drawPoints();
            }
        });

        canvas.addEventListener("mouseup", endDraw);
        canvas.addEventListener("mouseout", endDraw);
        canvas.addEventListener("mouseleave", endDraw);

        document.getElementById(constants.TOUCHEVENT.OPTION).addEventListener("click", function () {
            if (!moveEvents[0])
                return;

            if (this.value === "Touch Start") {
                this.value = "Touch Cancel";
                _exec("start");
            } else if (this.value === "Touch Cancel") {
                this.value = "Touch Start";
                _exec("cancel");
            }
        }, false);

        canvas.width = deviceInfo.screen.width / enlargeRatio;
        canvas.height = deviceInfo.screen.height / enlargeRatio;
    }
};

});
define('ripple/ui/plugins/vehicle', function (require, exports, module) {
/*
 *  Copyright 2013 Research In Motion Limited.
 *
 * 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 event = require('ripple/event'),
    exception = require('ripple/exception'),
    vehiclePanelEngine = require('ripple/platform/ivi/3.0/VehiclePanelEngine').VehiclePanelEngine,
    _vehicleGlobalVars = {
        currentAutoStatus: false,
        currentDataIndex: 0,
        timeFlag: null,
        timeInterval: 1000, //ms
        timeCurrent: 0,
        timeHistoryArray: [],
        timeHistoryLimit: 60 * 60,
        registerListeners: {},
        vehicleCache: {},
        history: {},
        notShowProperties: [
            "timeStamp"
        ]
    };

function _interceptString (str, length) {
    return str.length > length ? str.substring(0, length) + "...": str;
}

function _setVehicleConfigurationSel (configuration) {
    var selContainer = jQuery("#vehicle-container #vehicle-configuration-types"),
        html = "", i = 0;

    for (var value in configuration) {
        html += '<option value="' + value + '">' +
            'Car ' + i +
            '</option>';

        i++;
    }

    selContainer.html(html);
}

function _setVehicleConfiguration (configuration, currentType) {
    var container = jQuery("#vehicle-container #vehicle-configuration-show"),
        selContainer = jQuery("#vehicle-container #vehicle-configuration-types"),
        current, property, propertyList, item, unit, html = "", i,
        enums, showValue;

    if (currentType !== selContainer.val()) {
        for (i = 0; i < selContainer[0].options.length; i++) {
            if (selContainer[0].options[i].value === currentType) {
                selContainer[0].selectedIndex = i;
                break;
            }
        }
        if (i >= selContainer[0].options.length ) {
            throw "undefined configuration: " + currentType + ".";
        }
    }

    current = configuration[currentType];
    if (!current) {
        throw "undefined configuration: " + currentType + ".";
    }

    for (property in current) {
        html += '<tr><td colspan="2" class="vehicle-property-header">' + property + '</td></tr>';

        propertyList = current[property];
        for (item in propertyList) {
            showValue = propertyList[item];
            unit = vehiclePanelEngine.getPropertyUnit(property, item);
            enums = vehiclePanelEngine.getPropertyConstant(property, item);
            if (enums) {
                showValue = enums["val" + showValue];
            }

            html += '<tr class="vehicle-property-content">' +
                '<td class="vehicle-property-label"> ' + item + unit + '</td>' +
                '<td class="vehicle-property-value" id="' + property + '-' + item + '-show">' + showValue + '</td>' +
                '<td style="display: none;">' +
                '<input id="' + property + '-' + item + '-set" type="hidden" ' + 'value="' + propertyList[item] + '" />' +
                '</td></tr>';
        }
    }

    container.html(html);
    return;
}

function _setVehicleSupported (properties, supported) {
    var hideContainer = jQuery("#vehicle-container #vehicle-supported-hide"),
        showContainer = jQuery("#vehicle-container #vehicle-supported-show"),
        hideHtml = "", showHtml = "", tempHtml, column = 0, columnNum = 3, className,
        i, property, propertyAbbr;

    for (i = 0; i < properties.length; i++) {
        property = properties[i];
        propertyAbbr = _interceptString(property, 12);

        if (supported.indexOf(property) > -1) {
            className = "vehicle-property-supported";
            hideHtml += '<input type="checkbox" id="' + property + '-supported" value="' + property + '" checked="checked" />';
        }
        else {
            className = "vehicle-property-unsupported";
            hideHtml += '<input type="checkbox" id="' + property + '-supported" value="' + property + '" />';
        }

        tempHtml = '<td id="' + property + '-supported-show" ' + 'class="' + className + '" title="' + property + '">' + propertyAbbr + '</td>';

        if (column % columnNum === 0) {
            showHtml += '<tr>' + tempHtml;
        }
        else if (column % columnNum === (columnNum - 1)){
            showHtml += tempHtml + '</tr>';
        }
        else {
            showHtml += tempHtml;
        }
        column++;
    }

    hideContainer.html(hideHtml);
    showContainer.html(showHtml);
}

function _setVehicleSetting (settings) {
    var settingContainer = jQuery("#vehicle-container #vehicle-setting-show"),
        property, propertyItems, item, html = "", unit, range,
        optionHtml = "", i, optionName, option, options;

    for (property in settings) {
        html += '<tr><td colspan="2" class="vehicle-property-header">' + property + '</td></tr>';

        propertyItems = settings[property];
        for (item in propertyItems) {
            unit = vehiclePanelEngine.getPropertyUnit(property, item);

            if (propertyItems[item].type === "radio" || propertyItems[item].type === "select") {
                optionHtml = "";
                options = propertyItems[item].options;
                for (i = 0; i < options.length; i++) {
                    option = options[i];
                    for (optionName in option) {
                        if (option[optionName].toString() === propertyItems[item].value.toString()) {
                            optionHtml += '<option value="' + option[optionName] + '" selected>' +
                                optionName + '</option>';
                        }
                        else {
                            optionHtml += '<option value="' + option[optionName] + '">' +
                                optionName + '</option>';
                        }
                        break;
                    }
                }
                html += '<tr class="vehicle-property-content">' +
                    '<td class="vehicle-property-label" title="' + item + unit  + '">' + _interceptString(item + unit, 18)  + '</td>' +
                    '<td class="vehicle-property-value">' +
                    '<select id="' + property + '-' + item + '-set">' + optionHtml + '</select>' +
                    '</td></tr>';
            }
            else if (propertyItems[item].type === "range") {
                range = vehiclePanelEngine.getPropertyRange(property, item);

                html += '<tr class="vehicle-property-content">' +
                    '<td class="vehicle-property-label" title="' + item + unit  + '">' + _interceptString(item + unit, 18)  + '</td>' +
                    '<td class="vehicle-property-value">' +
                    '<label id="' + property + '-' + item + '-num">' + propertyItems[item].value + '</label>' +
                    '<input id="' + property + '-' + item + '-set" type="range" value="' + propertyItems[item].value + '"' +
                        ' min="' + range[0] + '" max="' + range[1] + '" step="' + range[2] + '" class="vehicle-property-range" />' +
                    '</td></tr>';
            }
            else if (propertyItems[item].type === "text") {
                html += '<tr class="vehicle-property-content">' +
                    '<td class="vehicle-property-label" title="' + item + unit  + '">' + _interceptString(item + unit, 18)  + '</td>' +
                    '<td class="vehicle-property-value">' +
                    '<input id="' + property + '-' + item + '-set" type="text" value="' + propertyItems[item].value + '" />' +
                    '</td></tr>';
            }
        }
    }

    settingContainer.html(html);
}

function _addArrayValueEnter (property, item, value) {
    var itemValue, html = "", i,
        id = property + '-' + item + "-set";

    itemValue = value.split(",");

    if (jQuery("#" + id + "Array") && jQuery("#" + id + "Array").length === 1) {
        html += '<td colspan="3">';
    }
    else {
        html += '<tr id="'+ id + 'Array" class="vehicle-property-array">' +
            '<td colspan="3">';
    }

    if (itemValue.length === 0) {
        html += '<div class="vehicle-property-arrayItem">' +
            '<button>add</button>' +
            '<input type="text" value="0" />' +
            '<button>del</button>' +
            '</div>';
    }
    else {
        for (i = 0; i < itemValue.length; i++) {
            if (i === itemValue.length - 1) {
                html += '<div class="vehicle-property-arrayItem">' +
                    '<button style="margin-left: -60px;">add</button>' +
                    '<input type="text" value="' + itemValue[i] + '" />' +
                    '<button >del</button>' +
                    '</div>';
            }
            else {
                html += '<div class="vehicle-property-arrayItem">' +
                    '<button style="display: none;">add</button>' +
                    '<input type="text" value="' + itemValue[i] + '" />' +
                    '<button >del</button>' +
                    '</div>';
            }
        }
    }

    if (jQuery("#" + id + "Array") && jQuery("#" + id + "Array").length === 1) {
        html += '</td>';

        jQuery("#" + id + "Array").html(html);
    }
    else {
        html += '</td></tr>';

        html += '<tr id="'+ id + 'OK" class="vehicle-property-array">' +
            '<td colspan="3">';
        html += '<button class="vehicle-property-arrayOk">OK</button>';
        html += '</td></tr>';
    }

    return html;
}

function _setVehicleAutoRunning (autoRunning, isFill) {
    var autoContainer = jQuery("#vehicle-container #vehicle-running-show"),
        timeStamp, html = "", unit,  range, property, propertyItem, value, data,
        showContainer, setContainer, valueField, options, option, optionName, i,
        enums, showValue;

    timeStamp = (new Date()).getTime();
    data = autoRunning["auto" + _vehicleGlobalVars.currentDataIndex];
    if (!data) {
        _vehicleGlobalVars.currentDataIndex = 0;
        data = autoRunning["auto0"];
    }
    _vehicleGlobalVars.timeCurrent = timeStamp;

    if (!isFill) {
        html += '<tr class="vehicle-property-content">' +
            '<td class="vehicle-property-label">time</td>' +
            '<td class="vehicle-property-value" id="vehicle-time-show">' + timeStamp + '</td></tr>';

        for (property in data) {
            html += '<tr><td colspan="2" class="vehicle-property-header">' + property + '</td></tr>';

            for (propertyItem in data[property]) {
                value = data[property][propertyItem].value;
                unit = vehiclePanelEngine.getPropertyUnit(property, propertyItem);

                if (Object.prototype.toString.call(value) === '[object Array]') {
                    value = value.join(",");
                }

                if (data[property][propertyItem].type === "radio" || data[property][propertyItem].type === "select") {
                    valueField = "";
                    options = data[property][propertyItem].options;
                    for (i = 0; i < options.length; i++) {
                        option = options[i];
                        for (optionName in option) {
                            if (option[optionName].toString() === data[property][propertyItem].value) {
                                valueField += '<option value="' + option[optionName] + '" selected>' +
                                    optionName + '</option>';
                            }
                            else {
                                valueField += '<option value="' + option[optionName] + '">' +
                                    optionName + '</option>';
                            }
                            break;
                        }
                    }

                    valueField = '<select id="' + property + '-' + propertyItem + '-set">' + valueField + '</select>';
                }
                else if (data[property][propertyItem].type === "range") {
                    range = vehiclePanelEngine.getPropertyRange(property, propertyItem);

                    valueField = '<label id="' + property + '-' + propertyItem + '-num">' + value + '</label>' +
                        '<input id="' + property + '-' + propertyItem + '-set" type="range" value="' + value + '"' +
                        ' min="' + range[0] + '" max="' + range[1] + '" step="' + range[2] + '" class="vehicle-property-range" />';
                }
                else if (data[property][propertyItem].type === "text") {
                    valueField = '<input type="text" value="' + value +'" id="' + property + '-' + propertyItem + '-set" disabled />';
                }

                enums = vehiclePanelEngine.getPropertyConstant(property, propertyItem);
                if (enums) {
                    showValue = enums["val" + value];
                }

                html += '<tr class="vehicle-property-content">' +
                    '<td class="vehicle-property-label" title="' + propertyItem + unit  + '">' + _interceptString(propertyItem + unit, 18) + '</td>' +
                    '<td class="vehicle-property-value vehicle-property-value-auto" id="' + property + '-' + propertyItem + '-show">' + showValue + '</td>' +
                    '<td class="vehicle-property-value vehicle-property-value-manual">' +
                    valueField +
                    '</td></tr>';

                if (data[property][propertyItem].type === "text") {
                    html += _addArrayValueEnter(property, propertyItem, value);
                }

                if (_vehicleGlobalVars.registerListeners[property]) {
                    event.trigger("vehicle-subscribe-request", [property, false, 0]);
                }
            }
        }

        autoContainer.html(html);
        _switchAutoManual(false);
    }
    else {
        if (_vehicleGlobalVars.currentAutoStatus) {
            for (property in data) {

                for (propertyItem in data[property]) {
                    value = data[property][propertyItem].value;

                    showContainer = jQuery("#vehicle-container #vehicle-running-show #" + property + '-' + propertyItem + "-show");
                    setContainer = jQuery("#vehicle-container #vehicle-running-show #" + property + '-' + propertyItem + "-set");

                    if (Object.prototype.toString.call(value) === '[object Array]') {
                        value = value.join(",");
                    }

                    if (data[property][propertyItem].type === "text") {
                        _addArrayValueEnter(property, propertyItem, value);
                    }

                    if (showContainer && setContainer) {
                        showContainer.html(value);
                        setContainer.val(value);
                    }
                }
            }
        }
        else {
        }
        jQuery("#vehicle-container #vehicle-running-show #vehicle-time-show").html(timeStamp);
    }

    for (property in _vehicleGlobalVars.registerListeners) {
        event.trigger("vehicle-subscribe-request", [property, false, 0]);
    }

    _saveVehicleData();
    _vehicleGlobalVars.currentDataIndex++;
}

function _formatHistory (historyData, timeStamp) {
    var format = {}, property, name, item, value;

    for (property in historyData) {
        name = property.split("-")[0];
        item = property.split("-")[1];

        if (!format[name]) {
            format[name] = {};
            format[name].timeStamp = timeStamp;
        }

        value = historyData[property];
        if (value.indexOf(",") > -1) {
            value = value.split(",");
        }
        if (value === "true") value = true;
        if (value === "false") value = false;

        format[name][item] = value;
    }

    return format;
}

function _saveVehicleData () {
    var configurationContainer = jQuery("#vehicle-container #vehicle-configuration-show *[id$='-set']"),
        currentConfigContainer = jQuery("#vehicle-container #vehicle-configuration-types"),
        settingContainer = jQuery("#vehicle-container #vehicle-setting-show  *[id$='-set']"),
        autoContainer = jQuery("#vehicle-container #vehicle-running-show  *[id$='-set']"),
        supportedContainer = jQuery("#vehicle-container #vehicle-supported-hide  *[id$='-supported']:checked"),
        supported = [], currentConfig, configuration = [], setting = [], autoRunning = [],
        history = {}, itemKey, format, delTime, timeStamp;

    supportedContainer.each(function (index, item) {
        supported.push(item.value);
    });

    currentConfig = currentConfigContainer.val().replace("configuration", "");

    configurationContainer.each(function (index, item) {
        itemKey = item.id.replace("-set", "");
        history[itemKey] = item.value;

        configuration.push(item.value);
    });

    settingContainer.each(function (index, item) {
        itemKey = item.id.replace("-set", "");
        history[itemKey] = item.value;

        setting.push(item.value);
    });

    autoContainer.each(function (index, item) {
        var value;

        value = item.value;
        if (item.id.indexOf("TripMeter") > -1) {
            value = item.value.split(",");
        }

        itemKey = item.id.replace("-set", "");
        history[itemKey] = value;

        autoRunning.push(value);
    });

    _vehicleGlobalVars.timeHistoryArray.push(_vehicleGlobalVars.timeCurrent);
    if (_vehicleGlobalVars.timeHistoryArray.length > _vehicleGlobalVars.timeHistoryLimit) {
        delTime = _vehicleGlobalVars.timeHistoryArray.shift();
        delete _vehicleGlobalVars.history[delTime];
    }

    timeStamp = _vehicleGlobalVars.timeCurrent;
    format = _formatHistory(history, timeStamp);
    _vehicleGlobalVars.history[_vehicleGlobalVars.timeCurrent] = format;
    event.trigger("vehicle-cache-refresh", [supported, format]);
    _setVehicleHistory();

    vehiclePanelEngine.saveData(supported, currentConfig, configuration, setting, autoRunning);
}

function _switchAutoManual (isAuto) {
    var autoContainer = jQuery("#vehicle-container #vehicle-running-show .vehicle-property-value-auto"),
        manualContainer = jQuery("#vehicle-container #vehicle-running-show .vehicle-property-value-manual"),
        arrayContainer = jQuery("#vehicle-container #vehicle-running-show .vehicle-property-array"),
        autoBtnContainer = jQuery("#vehicle-container #vehicle-running-auto");

    if (isAuto) {
        autoBtnContainer.addClass("vehicle-property-supported");
        autoBtnContainer.removeClass("vehicle-property-unsupported");
        autoContainer.show();
        manualContainer.hide();
        arrayContainer.hide();
    }
    else {
        autoBtnContainer.addClass("vehicle-property-unsupported");
        autoBtnContainer.removeClass("vehicle-property-supported");
        autoContainer.hide();
        manualContainer.show();
        arrayContainer.show();
    }
}

function _addVehicleDomEventListener () {
    var configSelection = jQuery("#vehicle-container #vehicle-configuration-types"),
        supportedSelection = jQuery("#vehicle-container #vehicle-supported-show td"),
        autoSelection = jQuery("#vehicle-container #vehicle-running-auto"),
        arraySelection = jQuery("#vehicle-container .vehicle-property-array"),
        arrayOKSelection = jQuery("#vehicle-container .vehicle-property-arrayOk"),
        rangeSelection = jQuery("#vehicle-container input[type='range']");

    arraySelection.delegate("button", "click", function () {
        var els = jQuery(this), appHtml;

        appHtml = '<div class="vehicle-property-arrayItem">' +
            '<button style="margin-left: -60px;">add</button>' +
            '<input type="text" value="0" />' +
            '<button >del</button>' +
            '</div>';

        if (els.html() === "add") {
            jQuery(appHtml).insertAfter(els.parent());
            els.hide();
        }
        else if (els.html() === "del") {
            if (els.parent().prev().length === 0 && els.parent().next().length === 0)
                return;
            els.parent().prev().find("button")[0].style.marginLeft = "-60px";
            els.parent().prev().find("button")[0].style.display = "";
            els.parent().remove();
        }
    });

    arrayOKSelection.click("click", function () {
        var els = jQuery(this), inputEls, i, trEls,
            setElsId, value = [];

        trEls = els.parent().parent();
        setElsId = trEls.attr("id").replace("OK", "");

        inputEls = trEls.prev().find("input");
        for (i = 0; i < inputEls.length; i++)  {
            value.push(inputEls[i].value);
        }

        jQuery("#vehicle-container #" + setElsId).val(value.join(","));
    });

    rangeSelection.bind("change", function () {
        var domJQuery = jQuery(this);

        domJQuery.prev().html(domJQuery.val());
    });

    configSelection.bind("change", function () {
        var configuration, current,
            domJQuery = jQuery(this);

        configuration = _vehicleGlobalVars.vehicleCache.configurationData;
        current = domJQuery.val();
        _setVehicleConfiguration(configuration, current);
    });

    //add vehicle supported click event
    supportedSelection.bind("click", function () {
        var domJQuery = jQuery(this), vehicleChecked,
            propertiesSelector = "#vehicle-container #vehicle-supported-hide",
            content, supportedId, inputJQuery;

        content = domJQuery.html();
        supportedId = content + "-supported";
        inputJQuery = jQuery(propertiesSelector + " #" + supportedId);
        if (domJQuery.hasClass("vehicle-property-unsupported")) {
            inputJQuery.attr("checked", "checked");
            domJQuery.removeClass("vehicle-property-unsupported");
            domJQuery.addClass("vehicle-property-supported");
        }
        else {
            inputJQuery.removeAttr("checked");
            domJQuery.removeClass("vehicle-property-supported");
            domJQuery.addClass("vehicle-property-unsupported");
        }

        vehicleChecked = jQuery("#vehicle-container #vehicle-supported-hide input:checked");
        _vehicleGlobalVars.vehicleCache.supported.length = 0;
        vehicleChecked.each(function (index, els) {
            _vehicleGlobalVars.vehicleCache.supported.push(els.value);
        });
    });

    //add vehicle auto click event
    autoSelection.bind("click", function () {
        if (_vehicleGlobalVars.currentAutoStatus) {
            _vehicleGlobalVars.currentAutoStatus = false;
            jQuery("#vehicle-container #vehicle-configuration-noOperation").hide();
            jQuery("#vehicle-container #vehicle-supported-noOperation").hide();
        }
        else {
            _vehicleGlobalVars.currentAutoStatus = true;
            jQuery("#vehicle-container #vehicle-configuration-noOperation").show();
            jQuery("#vehicle-container #vehicle-supported-noOperation").show();
        }
        _switchAutoManual(_vehicleGlobalVars.currentAutoStatus);

        _vehicleGlobalVars.timeFlag = setInterval(function () {
            _setVehicleAutoRunning(_vehicleGlobalVars.vehicleCache.autoRunningData, true);
        }, _vehicleGlobalVars.timeInterval);
    });
}

function _addVehicleEventListener () {
    event.once("vehicle-cache-request", function (data) {
        data.supported = _vehicleGlobalVars.vehicleCache.supported;
        data.data = _vehicleGlobalVars.history[_vehicleGlobalVars.timeCurrent];
    });

    event.on("vehicle-subscribe-request", function (property, isRegister, zone) {
        if (isRegister) {
            _vehicleGlobalVars.registerListeners[property] = true;
            return;
        }

        var value, status, timeStamp, history,
            propertyObj = {};

        if (_vehicleGlobalVars.vehicleCache.supported.indexOf(property) === -1) {
            propertyObj.val = null;
            propertyObj.supported = false;
            propertyObj.type = property;
        }
        else {
            history = _vehicleGlobalVars.history;
            timeStamp = _vehicleGlobalVars.timeCurrent;

            value = history[timeStamp][property];
            value.timeStamp = timeStamp;
            status = true;

            propertyObj.val = value;
            propertyObj.supported = status;
            propertyObj.type = property;
        }

        event.trigger("vehicle-subscribe-response", [propertyObj]);
    });

    event.on("vehicle-set-request", function (property, value) {
        var enums, showID, showValue, showContainer, item,
            enterID, enterContainer;

        for (item in value) {
            enterID = property + "-" + item + "-set";
            showID = property + "-" + item + "-show";
            enterContainer = jQuery("#vehicle-container #" + enterID);
            showContainer = jQuery("#vehicle-container #" + showID);

            if (Object.prototype.toString.call(value[item]) === '[object Array]') {
                enterContainer.val(value[item].join(","));
            }
            else {
                enterContainer.val(value[item].toString());
            }
            if (showContainer) {
                enums = vehiclePanelEngine.getPropertyConstant(property, item);
                showValue = value[item];
                if (enums) {
                    showValue = enums["val" + value[item]];
                }
                showContainer.html(showValue);
            }
        }
    });
}

function _setVehicleHistory() {
    var history = [], obj, timeStamp;

        for (timeStamp in _vehicleGlobalVars.history) {
            obj = _vehicleGlobalVars.history[timeStamp];
            obj.timeStamp = timeStamp;
            history.push(obj);
        }

        event.trigger("vehicle-history-response", [history]);
}

function _initializeVehiclePanel () {
    try {
        var stop = false,
            configuration, current, properties, supported, settings,
            autoRunning;

        _vehicleGlobalVars.timeHistoryArray = [];

        configuration = vehiclePanelEngine.getConfiguration();
        current = vehiclePanelEngine.getCurrentConfiguration();
        _setVehicleConfigurationSel(configuration);
        _vehicleGlobalVars.vehicleCache.configurationData = configuration;
        _vehicleGlobalVars.vehicleCache.currentConfiguration = current;
        _setVehicleConfiguration(configuration, current);

        properties = vehiclePanelEngine.getProperties();
        supported = vehiclePanelEngine.getSupported();
        _vehicleGlobalVars.vehicleCache.properties = properties;
        _vehicleGlobalVars.vehicleCache.supported = supported;
        _setVehicleSupported(properties, supported);

        settings = vehiclePanelEngine.getSettings();
        _vehicleGlobalVars.vehicleCache.settingData = settings;
        _setVehicleSetting(settings);

        autoRunning = vehiclePanelEngine.getAutoRunning();
        _vehicleGlobalVars.vehicleCache.autoRunningData = autoRunning;
        _setVehicleAutoRunning(autoRunning, false);
        _vehicleGlobalVars.currentDataIndex = 0;

        _vehicleGlobalVars.timeFlag = setInterval(function () {
            _setVehicleAutoRunning(_vehicleGlobalVars.vehicleCache.autoRunningData, true);
        }, _vehicleGlobalVars.timeInterval);

        _addVehicleDomEventListener();

        _addVehicleEventListener();

        jQuery("#vehicle-properties h3").click(function (event) {
            if (stop) {
                event.stopImmediatePropagation();
                event.preventDefault();
                stop = false;
            }
        });
        jQuery("#vehicle-properties").accordion("destroy").accordion({
            header: "> div > h3",
            autoHeight: false
        });
    } catch (e) {
        exception.handle(e, true);
    }
}

module.exports = {
    panel: {
        domId: "vehicle-container",
        collapsed: true,
        pane: "right",
        titleName: "Vehicle Information",
        display: true
    },
    initialize: function () {
        _initializeVehiclePanel();
    }
};

});
define('ripple/ui/plugins/videoPlayer', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    event = require('ripple/event');

module.exports = {
    initialize: function () {
        var videoObj,
            videoProgress = document.getElementById(constants.COMMON.MULTIMEDIA_VIDEO_PROGRESS_ID);

        event.on("MultimediaAppVideoPlayerCreated", function (videoDOMObj) {
            videoObj = videoDOMObj;

            videoObj.addEventListener("timeupdate", function () {
                var s = parseInt(videoObj.currentTime % 60, 10),
                    m = parseInt((videoObj.currentTime / 60) % 60, 10);

                videoProgress.innerText = ((m > 9) ? m  : "0" + m) + ':' + ((s > 9) ? s  : "0" + s);
            }, false);
        });

        event.on("MultimediaVolumeChanged", function (volume) {
            if (videoObj) {
                videoObj.volume = parseFloat(volume / 10);
            }
        });

        event.on("MultimediaVideoStateChanged", function (state) {
            document.getElementById(constants.COMMON.MULTIMEDIA_VIDEO_STATE_FIELD_ID).innerText = state;
            document.getElementById(constants.COMMON.MULTIMEDIA_VIDEO_FILE_FIELD_ID).innerText = videoObj.getAttribute("src");
        });
    }
};

});
define('ripple/ui/plugins/widgetConfig', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    event = require('ripple/event'),
    utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    tooltip = require('ripple/ui/plugins/tooltip'),
    platform = require('ripple/platform'),
    widgetConfig = require('ripple/widgetConfig');

function _buildConfigAccordionNode(node, accordionContainer, counter) {
    var nodeDiv, nodeTitleH3, nodeContentDiv, tableString, attribute, child, result,
        tableClass, nameClass, attributeNameClass, messageClass, nameId, messageId, attributeName, attributeValue, attributeMessage,
        helpText = {},
        nodeCounter = 0,
        attributeCounter = 0,
        moreNodes = node.validationResult,
        createTooltip = function (value, index) {
            tooltip.create("#" +  index, value);
        };

    while (moreNodes) {
        result = node.validationResult[nodeCounter];

        if (!result) {
            // this should never happen
            return;
        }

        // the container of the entire accordion block
        nodeDiv = utils.createElement("div", {
            "id": "config-accordion-node-content-" + counter + "-" + nodeCounter,
            "class": "ui-corner-all"
        });

        // the header bar of the accordion block
        nodeTitleH3 = utils.createElement("h3", {
            "id": "config-accordion-node-title-" + counter + "-" + nodeCounter,
            "class": "config-accordion-node-title"
        });

        nodeTitleH3.appendChild(utils.createElement("a", {
            href: "#",
            innerText: node.nodeName,
            "class": constants.CONFIG.SUCCESS_CSS[(result.valid === undefined) ? "missing" : result.valid.toString()]
        }));
        nodeDiv.appendChild(nodeTitleH3);

        if (node.helpText) {
            helpText[nodeTitleH3.id] = node.helpText;
        }

        nodeContentDiv = utils.createElement("div");

        // display node value (add tool tip if exists)
        if (node.type || (!node.type && result && result.value)) {
            nodeContentDiv.appendChild(utils.createElement("div", {
                "id": "config-accordion-node-content-value-" + counter + "-" + nodeCounter,
                "class": "config-accordion-node-content-value",
                "innerHTML": "<span>Value:</span>" + (result.value || "")
            }));

            if (node.helpValueText) {
                helpText["config-accordion-node-content-value-" + counter + "-" + nodeCounter] = node.helpValueText;
            }
        }

        // display node message if failed validation
        if (result && result.message) {
            nodeContentDiv.appendChild(utils.createElement("div", {
                "id": "config-accordion-node-content-value-message-" + counter + "-" + nodeCounter,
                "class": "config-accordion-node-content-value-message ui-text-fail",
                "innerHTML": "<span>Message:</span>" + result.message
            }));
        }

        // display node attributes with name, value, message if failed validation
        if (result.attributes) {
            nodeContentDiv.appendChild(utils.createElement("div", {
                "id": "config-accordion-node-content-attributes-title-" + counter + "-" + nodeCounter,
                "class": "config-accordion-node-content-attributes-title",
                "innerHTML": "Attributes..."
            }));

            tableClass = "preferences-table";
            nameClass = "config-attributes-name-value";
            attributeNameClass = "ui-text-label";
            messageClass = "config-attributes-message";

            tableString = '<table class="' + tableClass + ' ui-widget-content">';
            for (attribute in result.attributes) {
                if (result.attributes.hasOwnProperty(attribute)) {
                    nameId = "config-accordion-node-content-attributes-table-name-" + counter + "-" + nodeCounter + "-" + attributeCounter;
                    messageId = "config-accordion-node-content-attributes-table-message-" + counter + "-" + nodeCounter + "-" + attributeCounter;
                    attributeName = result.attributes[attribute].attributeName;
                    attributeValue = result.attributes[attribute].value || "&nbsp;";
                    attributeMessage = result.attributes[attribute].message || null;

                    tableString += '<tr class="' + nameClass + '" id="' + nameId + '">' +
                            '<td class="' + attributeNameClass + '">' + attributeName + '</td>' +
                            '<td>' + attributeValue + '</td></tr>';

                    if (node.attributes[attributeName].helpText) {
                        helpText[nameId] = node.attributes[attributeName].helpText;
                    }

                    if (attributeMessage !== null) {
                        tableString += "<tr class=" + messageClass + " id=" + messageId + "><td colspan=\"2\">" +
                                attributeMessage + "</td></tr>";
                    }
                    attributeCounter++;
                }
            }
            tableString += "</table>";

            nodeContentDiv.innerHTML += tableString;
        }


        nodeDiv.appendChild(nodeContentDiv);
        accordionContainer.appendChild(nodeDiv);

        utils.forEach(helpText, createTooltip);

        nodeCounter ++;

        if (!node.validationResult[nodeCounter]) {
            nodeCounter = 0;
            moreNodes = false;
        }
    }

    if (node.children) {
        for (child in node.children) {
            if (node.children.hasOwnProperty(child)) {
                counter ++;
                _buildConfigAccordionNode(node.children[child], accordionContainer, counter);
            }
        }
    }
}

function _initializeConfigResultsView(results) {
    try {
        var rootNode,
            accordionContainer = document.getElementById("widget-config");

        accordionContainer.innerHTML = "";
        if (!results) {
            accordionContainer.appendChild(utils.createElement("div", {
                "class": "config-accordion-node-title " + constants.CONFIG.SUCCESS_CSS["false"],
                "innerHTML": "Expected to find a configuration file for your application, but none is present. Please create" +
                        " a configuration file with the following name in the root directory of your application: " +
                        platform.current().fileName
            }));
            return;
        }

        rootNode = results[results.rootElement];

        _buildConfigAccordionNode(rootNode, accordionContainer, 0);

        jQuery(function () {
            var stop = false;
            jQuery("#widget-config h3").click(function (event) {
                if (stop) {
                    event.stopImmediatePropagation();
                    event.preventDefault();
                    stop = false;
                }
            });
            jQuery("#widget-config").accordion("destroy").accordion({
                header: "> div > h3",
                autoHeight: false
            });
        });
    } catch (e) {
        exception.handle(e, true);
    }
}

event.on("FrameHistoryChange", function () {
    module.exports.initialize();
});

module.exports = {
    panel: {
        domId: "config-container",
        collapsed: true,
        pane: "right",
        titleName: "Application Configuration",
        display: true
    },
    initialize: function () {
        var results = widgetConfig.getValidationResults();
        _initializeConfigResultsView(results);
    }
};

});
define('ripple/ui/themes', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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.
 */
//module.exports = ["dark", "light"];
module.exports = ["light"];

});
define('ripple/ui', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 _self,
    db = require('ripple/db'),
    platform = require('ripple/platform'),
    constants = require('ripple/constants'),
    utils = require('ripple/utils'),
    exception = require('ripple/exception'),
    event = require('ripple/event'),
    themes = require('ripple/ui/themes'),
    _applicationStateId,
    _applicationState,
    _availablePanels,
    _applicationStateTmp,
    _systemPlugins = [
        "options",
        "about-dialog",
        "settings-dialog",
        "exec-dialog",
        "firstRunCheck",
        "eulaCheck",
        "devices",
        "goodVibrations",
        "panelCollapse",
        "platform",
        "information",
        "layout",
        "themeSwitcher",
        "settings-menu",
        "configWindow",
        "previewWindow",
        "HWKeys"
        //"launchingHistory"
    ],
    _overlay = {
        getOrCreate: function (id) {
            var _container = document.getElementById(constants.COMMON.HTML_CONTAINER),
                _overlays = document.getElementById("overlay-views"),
                _overlay = _overlays.children[id],
                _hide = function (node) {
                    node.setAttribute("style", "display: none");
                },
                _show = function (node) {
                    node.setAttribute("style", "display: block");
                },
                _trigger = function (callback) {
                    if (callback) {
                        callback.apply(null, [_overlay]);
                    }
                };


            if (!_overlay) {
                _overlay = utils.createElement("section", {id: id, "class": "overlay"});
                _overlays.appendChild(_overlay);
            }

            return {
                hide: function (callback) {
                    _hide(_overlay);
                    _show(_container);
                    _trigger(callback);
                },
                show: function (callback, showContainer) {
                    _show(_overlay);
                    if (!showContainer) {
                        _hide(_container);
                    }
                    _trigger(callback);
                }
            };
        }
    };

function _addUIPaneItemsToApplicationState(arrayObj, pane) {
    utils.forEach(arrayObj, function (domId) {
        var collapsed = jQuery("#" + domId + " .info")[0];
        collapsed = (collapsed.style && collapsed.style.display === "none") ? true : false;
        utils.forEach(_applicationStateTmp, function (obj) {
            if (obj.domId === domId) {
                _applicationState.push({
                    "domId": domId,
                    "collapsed": collapsed,
                    "pane": pane,
                    "titleName" : obj.titleName,
                    "display" : obj.display
                });
                _applicationStateTmp.splice(_applicationStateTmp.indexOf(obj), 1);
                return;
            }
        }, this);
    }, this);

    utils.forEach(_applicationStateTmp, function (obj) {
        _applicationState.push({
            "domId": obj.domId,
            "collapsed": obj.collapsed,
            "pane": obj.pane,
            "titleName" : obj.titleName,
            "display" : obj.display
        });
    });
}

function _currentlyEnabledTheme() {
    var qsSet = utils.queryString().theme,
        current = db.retrieve("ui-theme") || themes[0];

    function matches(something) {
        return function (item) {
            return something === item;
        };
    }

    if (qsSet && themes.some(matches(qsSet))) {
        current = qsSet;
        db.save("ui-theme", qsSet);
    }

    return current;
}

function _insertStyleSheets() {
    var uiTheme = db.retrieve("ui-theme") || require('ripple/ui/themes')[0],
        extensionURL = jQuery("#extension-url").text(),
        uiThemeURL = extensionURL + "themes/" + uiTheme + "/theme.css",
        head = document.getElementsByTagName('head')[0];

    function stylesheet(src) {
        var scriptElement = document.createElement("link");
        scriptElement.setAttribute("href", src);
        scriptElement.setAttribute("type", "text/css");
        scriptElement.setAttribute("rel", "stylesheet");
        return scriptElement;
    }

    head.appendChild(stylesheet(uiThemeURL));
}

function _collapsePannels(side) {
    var collapseNode = [],
        event = document.createEvent("UIEvent");

    collapseNode = side === "left" ? document.getElementsByClassName("left-panel-collapse") : 
                                     document.getElementsByClassName("right-panel-collapse");
    
    if (collapseNode.length > 0) {
        event.initEvent("click", true, true);
        collapseNode[0].dispatchEvent(event);    
    }
}

function _initializeUI() {
    _applicationStateId = constants.COMMON.APPLICATION_STATE + platform.current().id;
    _applicationState = db.retrieveObject(_applicationStateId) || [];
    _insertStyleSheets();

    var leftPanelSection = jQuery(".left"),
        uiBoxToggleEngaged = false;

    //clean up
    db.remove("ui-application-state");
    utils.forEach(_availablePanels, function (obj) {
        var matchingDomId = function (panel) {
            return panel.domId === obj.domId;
        };
        if (!utils.some(_applicationState, matchingDomId)) {
            _applicationState.push({
                "domId": obj.domId,
                "collapsed": obj.collapsed,
                "pane": obj.pane,
                "titleName" : obj.titleName,
                "display" : obj.display
            });
        }
    });

    utils.forEach(_applicationState, function (obj) {
        var node = jQuery("#" + obj.domId),
            imgNode = node.find(".ui-box-TitleImage"),
            matchingDomId = function (panel) {
                return panel.domId === obj.domId;
            };

        if (node.length > 0) {
            if (!utils.some(_availablePanels, matchingDomId)) {
                node.parent()[0].removeChild(node[0]);
            }
            else {
                if (obj.display !== false) {
                    leftPanelSection.append(node.parent()[0].removeChild(node[0]));
                    if (!obj.collapsed) {
                        node.find(".info")
                            .css({
                            "display": "block"
                        })
                        .end()
                        .addClass("ui-box-open");
                        imgNode.addClass("ui-box-TitleImageOpen");
                    }
                }
            }
        }
    });

    db.saveObject(_applicationStateId, _applicationState);

    event.on("ApplicationState", function () {
        try {
            var leftArray = jQuery(".left").sortable('toArray');
            _applicationStateTmp = [];
            _applicationStateTmp = utils.copy(_applicationState);
            _applicationState = [];
            _addUIPaneItemsToApplicationState(leftArray, "left");

            if (leftArray.length === 0) {
                _collapsePannels("left");
            }

            db.saveObject(_applicationStateId, _applicationState);
        }
        catch (e) {
            exception.handle(e);
        }
    });

    jQuery(".left").sortable({
        handle: ".drag-handle",
        revert: true,
        placeholder: 'ui-sortable-highlight ui-corner-all',
        connectWith: [".left"],
        scroll: true,
        update: function (uiEvent, ui) {
            event.trigger("ApplicationState");
        }
    });

    jQuery(".left").sortable({ axis: 'y' });

    jQuery(".collapse-handle").bind("click", function () {
        if (!uiBoxToggleEngaged) {

            uiBoxToggleEngaged = true;

            var jNode = jQuery(this).parentsUntil(".ui-box"),
                    pNode = jNode.parent(),
                    isOpen = pNode.hasClass("ui-box-open"),
                    imgNode = jQuery(this).find(".ui-box-TitleImage");

            if (!isOpen) {
                pNode.addClass("ui-box-open");
                imgNode.removeClass("ui-box-TitleImageClosed");
                imgNode.addClass("ui-box-TitleImageOpen");
            }

            jQuery(this).parent().next().toggle("blind", {}, 300, function () {
                if (isOpen) {
                    pNode.removeClass("ui-box-open");
                    imgNode.removeClass("ui-box-TitleImageOpen");
                    imgNode.addClass("ui-box-TitleImageClosed");
                }
                event.trigger("ApplicationState", [pNode]);
                uiBoxToggleEngaged = false;
            });
        }
    });
}

function _db_upgrade_for_release() {
    var version = db.retrieve(constants.RELEASE_VERSION);

    // version: 20121115 is the first release version
    if (version === null || version === undefined || Number(version) < 20130722) {
        db.remove(constants.COMMON.APPLICATION_STATE + "tizen");
        db.remove(constants.COMMON.APPLICATION_STATE + "cordova");
        db.remove("tizen1-db-application");
        db.remove("tizen-db-package");
        version = 20130722;
        db.save(constants.RELEASE_VERSION, version);
    }
}

_self = module.exports = {
    initialize: function () {
        var plugins = _systemPlugins.concat(platform.current().ui.plugins || []).map(function (name) {
                return require('ripple/ui/plugins/' + name);
            }),
            boot = jWorkflow.order(_initializeUI);

        _db_upgrade_for_release();
        _availablePanels = [];

        plugins.forEach(function (plugin) {
            if (plugin.initialize) {
                boot.andThen(plugin.initialize);
            }

            if (plugin.panel) {
                _availablePanels.push(plugin.panel);
            }
        });

        boot.start();
    },

    getSystemPlugins: function () {
        return utils.copy(_systemPlugins);
    },

    register: function (plugin) {
        _systemPlugins.push(plugin);
    },

    registered: function (plugin) {
        return _systemPlugins.indexOf(plugin) >= 0;
    },

    getExtensionURL: function () {
        return jQuery("#" + constants.COMMON.EXTENSION_URL_CONTAINER).text();
    },

    showOverlay: function (id, callback, showContainer) {
        _overlay.getOrCreate(id).show(callback, showContainer);
    },

    hideOverlay: function (id, callback) {
        _overlay.getOrCreate(id).hide(callback);
    }
};

});
define('ripple/utils', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 self,
    exception = require('ripple/exception'),
    constants = require('ripple/constants'),
    _HtmlElements = ['header', 'footer', 'section', 'aside', 'nav', 'article'];

self = module.exports = {
    validateNumberOfArguments: function (lowerBound, upperBound, numberOfArguments, customExceptionType, customExceptionMessage, customExceptionObject) {

        customExceptionMessage = customExceptionMessage || "";

        if (arguments.length < 3 || arguments.length > 6) {
            exception.raise(exception.types.Argument, "Wrong number of arguments when calling: validateNumberOfArguments()");
        }

        if (isNaN(lowerBound) && isNaN(upperBound) && isNaN(numberOfArguments)) {
            exception.raise(exception.types.ArgumentType, "(validateNumberOfArguments) Arguments are not numbers");
        }

        lowerBound = parseInt(lowerBound, 10);
        upperBound = parseInt(upperBound, 10);
        numberOfArguments = parseInt(numberOfArguments, 10);

        if (numberOfArguments < lowerBound || numberOfArguments > upperBound) {
            exception.raise((customExceptionType || exception.types.ArgumentLength), (customExceptionMessage + "\n\nWrong number of arguments"), customExceptionObject);
        }

    },

    validateArgumentType: function (arg, argType, customExceptionType, customExceptionMessage, customExceptionObject) {
        var invalidArg = false,
            msg;

        switch (argType) {
        case "array":
            if (!arg instanceof Array) {
                invalidArg = true;
            }
            break;
        case "date":
            if (!arg instanceof Date) {
                invalidArg = true;
            }
            break;
        case "integer":
            if (typeof arg === "number") {
                if (arg !== Math.floor(arg)) {
                    invalidArg = true;
                }
            }
            else {
                invalidArg = true;
            }
            break;
        default:
            if (typeof arg !== argType) {
                invalidArg = true;
            }
            break;
        }

        if (invalidArg) {
            msg = customExceptionMessage +  ("\n\nInvalid Argument type. argument: " + arg + " ==> was expected to be of type: " + argType);
            exception.raise((customExceptionType || exception.types.ArgumentType), msg, customExceptionObject);
        }
    },

    validateMultipleArgumentTypes: function (argArray, argTypeArray, customExceptionType, customExceptionMessage, customExceptionObject) {
        for (var i = 0; i < argArray.length; i++) {
            this.validateArgumentType(argArray[i], argTypeArray[i], customExceptionType, customExceptionMessage, customExceptionObject);
        }
    },

    createElement: function (elementType, attributes) {
        var d = document.createElement(elementType);

        if (attributes) {
            this.forEach(attributes, function (attributeValue, attributeName) {

                switch (attributeName.toLowerCase()) {

                case "innerhtml":
                    d.innerHTML = attributeValue;
                    break;

                case "innertext":
                    d.innerText = attributeValue;
                    break;

                default:
                    d.setAttribute(attributeName, attributeValue);
                }

            });
        }

        return d;
    },


    loadHTMLElements: function () {
        for (var i = 0; i < _HtmlElements.length; i += 1) {
            document.createElement(_HtmlElements[i]);
        }
    },

    getAllStylesheetRules: function getAllStylesheetRules(title) {
        this.validateNumberOfArguments(1, 1, arguments.length);

        var i, x, sheet, rules, styles_array = [];

        // get style sheet according to title
        for (i = 0; i < document.styleSheets.length; i += 1) {

            sheet = document.styleSheets[i];
            rules = sheet.cssRules;

            if (rules) {
                for (x = 0; x < rules.length; x += 1) {
                    if (rules[x].selectorText && rules[x].selectorText === (title.toString())) {
                        styles_array.push(rules[x]);
                    }
                }
            }
        }

        return (styles_array);
    },

    location: function () {
        return window.location;
    },

    queryString: function () {
        // trim the leading ? and split each name=value
        var args = this.location().search.replace(/^\?/, '').split('&');

        return args.reduce(function (obj, value) {
            if (value) {
                value = value.toLowerCase().split("=");
                obj[value[0]] = value[1];
            }
            return obj;
        }, {});
    },

    extensionUrl: function () {
        return document.getElementById("extension-url").innerText;
    },

    appLocation: function () {
        if (require('ripple/ui').registered("omnibar")) {
            /* rootURL can only get url saved from 'FrameHistoryChange' event
               it causes trouble when navigating directory through online 
               version as index.html is automatically loaded.
               Need a way to get more updated URL */

            var path = require('ripple/ui/plugins/omnibar').rootURL(),
                parts;

            if ((parts = path.match(/^((http[s]?|ftp|file):\/\/)(.+\/)?([^\/].+)$/i)) !== null && parts.length === 5) {
                // this is a path already.
                if (path.search(/\/$/, "") !== -1) {
                    return path;
                }
                if (parts[4] === "about:blank") {
                    path = "";
                }
                else if (parts[3]) {
                    path = parts[1] + parts[3];
                    if (parts[4].indexOf(".") === -1) {
                        path += parts[4] + "/";
                    }
                }
                else {
                    path = parts[1] + parts[4] + "/";
                }
            }
            else {
                path = "";
            }
            return path;
        }
        return self.rippleLocation();
    },

    rippleLocation: function () {
        var loc = self.location(),
            parts = loc.pathname.replace(/\/$/, "").split("/"),
            base = "",
            port = loc.port ? ":" + loc.port : "";

        if (parts[parts.length - 1].indexOf(".") !== -1) {
            parts = parts.splice(0, parts.length - 1);
        }
        base = parts.join("/");

        return loc.protocol + "//" + loc.hostname + port + base + "/";
    },

    arrayContains: function (array, obj) {
        var i = array.length;
        while (i--) {
            if (array[i] === obj) {
                return true;
            }
        }
        return false;
    },

    some: function (obj, predicate, scope) {
        if (obj instanceof Array) {
            return obj.some(predicate, scope);
        }
        else {
            var values = self.map(obj, predicate, scope);

            return self.reduce(values, function (some, value) {
                return value ? value : some;
            }, false);
        }
    },

    count: function (obj) {
        return self.sum(obj, function (total) {
            return 1;
        });
    },

    sum: function (obj, selector, scope) {
        var values = self.map(obj, selector, scope);
        return self.reduce(values, function (total, value) {
            return total + value;
        });
    },

    max: function (obj, selector, scope) {
        var values = self.map(obj, selector, scope);
        return self.reduce(values, function (max, value) {
            return max < value ? value : max;
        }, Number.MIN_VALUE);
    },

    min: function (obj, selector, scope) {
        var values = self.map(obj, selector, scope);
        return self.reduce(values, function (min, value) {
            return min > value ? value : min;
        }, Number.MAX_VALUE);
    },

    forEach: function (obj, action, scope) {
        if (obj instanceof Array) {
            return obj.forEach(action, scope);
        }
        else {
            self.map(obj, action, scope);
        }
    },

    filter: function (obj, predicate, scope) {
        if (obj instanceof Array) {
            return obj.filter(predicate, scope);
        }
        else {
            var result = [];
            self.forEach(obj, function (value, index) {
                if (predicate.apply(scope, [value, index])) {
                    result.push(value);
                }

            }, scope);

            return result;
        }
    },

    reduce: function (obj, func, init, scope) {
        var i,
            initial = init === undefined ? 0 : init,
            result = initial;


        if (obj instanceof Array) {
            return obj.reduce(func, initial);
        }
        else if (obj instanceof NamedNodeMap) {
            for (i = 0; i < obj.length; i++) {
                result = func.apply(scope, [result, obj[i], i]);
            }
        }
        else {
            for (i in obj) {
                if (obj.hasOwnProperty(i)) {
                    result = func.apply(scope, [result, obj[i], i]);
                }
            }
        }

        return result;

    },

    map: function (obj, func, scope) {
        var i,
            returnVal = null,
            result = [];

        if (obj instanceof Array) {
            return obj.map(func, scope);
        }
        else if (obj instanceof NamedNodeMap) {
            for (i = 0; i < obj.length; i++) {
                returnVal = func.apply(scope, [obj[i], i]);
                result.push(returnVal);
            }
        }
        else {
            for (i in obj) {
                if (obj.hasOwnProperty(i)) {
                    returnVal = func.apply(scope, [obj[i], i]);
                    result.push(returnVal);
                }
            }
        }

        return result;
    },

    regexSanitize: function (regexString) {
        return regexString.replace("^", "\\^")
                    .replace("$", "\\$")
                    .replace("(", "\\(")
                    .replace(")", "\\)")
                    .replace("<", "\\<")
                    .replace("[", "\\[")
                    .replace("{", "\\{")
                    .replace(/\\/, "\\\\")
                    .replace("|", "\\|")
                    .replace(">", "\\>")
                    .replace(".", "\\.")
                    .replace("*", "\\*")
                    .replace("+", "\\+")
                    .replace("?", "\\?");
    },

    bindAutoSaveEvent: function (node, saveCallback) {
        var oldSetTimeoutId,
            jNode = jQuery(node);

        jNode.bind("keyup", function (event) {
            if (event.keyCode !== 9) {
                clearTimeout(oldSetTimeoutId);
                oldSetTimeoutId = window.setTimeout(function () {
                    saveCallback();
                }, 500);
            }
        });
    },

    find: function (comparison, collection, startInx, endInx, callback) {
        var results = [],
            compare = function (s, pattern) {

                if (typeof(s) !== "string" || pattern === null) {
                    return s === pattern;
                }

                var regex = pattern.replace(/\./g, "\\.")
                                   .replace(/\^/g, "\\^")
                                   .replace(/\*/g, ".*")
                                   .replace(/\\\.\*/g, "\\*");

                regex = "^".concat(regex, "$");

                return !!s.match(new RegExp(regex, "i"));
            };

        self.forEach(collection, function (c) {
            var match,
                fail = false;

            self.forEach(comparison, function (value, key) {
                if (!fail && value !== undefined) {

                    if (compare(c[key], value)) {
                        match = c;
                    }
                    else {
                        fail = true;
                        match = null;
                    }
                }
            });

            if (match) {
                results.push(match);
            }
        });

        if (callback) {
            if (startInx === undefined) {
                startInx = 0;
            }
            if (endInx === undefined) {
                endInx = results.length;
            }
            if (startInx === endInx) {
                endInx = startInx + 1;
            }

            callback.apply(null, [results.slice(startInx, endInx)]);
        }
    },

    mixin: function (mixin, to) {
        for (var prop in mixin) {
            if (Object.hasOwnProperty.call(mixin, prop)) {
                to[prop] = mixin[prop];
            }
        }
        return to;
    },

    copy: function (obj) {
        var i,
            newObj = jQuery.isArray(obj) ? [] : {};

        if (typeof obj === 'number' ||
            typeof obj === 'string' ||
            typeof obj === 'boolean' ||
            obj === null ||
            obj === undefined) {
            return obj;
        }

        if (obj instanceof Date) {
            return new Date(obj);
        }

        if (obj instanceof RegExp) {
            return new RegExp(obj);
        }

        for (i in obj) {
            if (obj.hasOwnProperty(i)) {
                if (obj[i] && typeof obj[i] === "object") {
                    if (obj[i] instanceof Date) {
                        newObj[i] = obj[i];
                    }
                    else {
                        newObj[i] = self.copy(obj[i]);
                    }
                }
                else {
                    newObj[i] = obj[i];
                }
            }
        }

        return newObj;
    },

    navHelper: function () {
        return {
            getHeading: function (lat1, lon1, lat2, lon2) {
                var dLon = this.rad(lon2 - lon1),
                    llat1 = this.rad(lat1),
                    llat2 = this.rad(lat2),
                    y = Math.sin(dLon) * Math.cos(llat2),
                    x = Math.cos(llat1) * Math.sin(llat2) - Math.sin(llat1) * Math.cos(llat2) * Math.cos(dLon);
                return (this.deg(Math.atan2(y, x)) + 360) % 360;
            },

            getDistance: function (lat1, lon1, lat2, lon2) {
                var dLat = this.rad(lat2 - lat1),
                    dLon = this.rad(lon2 - lon1),
                    a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.rad(lat1)) * Math.cos(this.rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2),
                    c = 2 * Math.asin(Math.sqrt(a)),
                    d = 6378100 * c;
                return d;
            },

            simulateTravel: function (lat, lon, hdg, dist) {
                var lat1 = this.rad(lat),
                    lon1 = this.rad(lon),
                    brng = this.rad(hdg),
                    angularDistance = dist / 6378100,
                    lat2 = Math.asin(Math.sin(lat1) * Math.cos(angularDistance) + Math.cos(lat1) * Math.sin(angularDistance) * Math.cos(brng)),
                    lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(angularDistance) * Math.cos(lat1), Math.cos(angularDistance) - Math.sin(lat1) * Math.sin(lat2));
                lon2 = (lon2 + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // Normalise to -180..+180

                return {
                    latitude: this.deg(lat2),
                    longitude: this.deg(lon2)
                };
            },

            deg: function (num) {
                return num * 180 / Math.PI;
            },

            rad: function (num) {
                return num * Math.PI / 180;
            }
        };
    },

    getURIParams: function (uriString) {
        var params = {};

        uriString.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) {
            params[key] = value;
        });

        return params;
    }
};

});
define('ripple/widgetConfig', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 exception = require('ripple/exception'),
    event = require('ripple/event'),
    app = require('ripple/app'),
    _console = require('ripple/console'),
    utils = require('ripple/utils'),
    platform = require('ripple/platform'),
    _validationResult = {
        valid: false,
        message: "",
        value: null
    },
    _configValidationResults = null;

function _failNodeValidation(schemaNode, message, value, node) {
    var validationResult = utils.copy(_validationResult);

    if (!schemaNode.validationResult) {
        schemaNode.validationResult = [];
    }
    validationResult.valid = false;
    if (value) {
        validationResult.value = value;
    }
    else {
        delete(validationResult.value);
    }
    validationResult.message = schemaNode.nodeName + message;
    validationResult.node = node;

    schemaNode.validationResult.push(validationResult);
}

function _createEmptyNodeValidation(node) {

    var validationResult = utils.copy(_validationResult),
        attributeValidationResult, attribute;

    if (!node.validationResult) {
        node.validationResult = [];
    }

    validationResult.value = "";
    delete(validationResult.valid);
    delete(validationResult.message);

    if (node.attributes) {
        for (attribute in node.attributes) {
            if (node.attributes.hasOwnProperty(attribute)) {
                if (!validationResult.attributes) {
                    validationResult.attributes = {};
                }

                attributeValidationResult = utils.copy(_validationResult);

                attributeValidationResult.attributeName = node.attributes[attribute].attributeName;
                delete(attributeValidationResult.value);
                delete(attributeValidationResult.valid);
                delete(attributeValidationResult.message);

                validationResult.attributes[attributeValidationResult.attributeName] = attributeValidationResult;
            }
        }
    }

    node.validationResult.push(validationResult);
}

function _validateValue(valueToTest, schemaNode) {
    var failMessage = "",
        nodeValue,
        numbers,
        numberRangeIndex,
        numberRange,
        range1,
        range2;

    switch (schemaNode.type) {
    case "string":
        if (typeof valueToTest !== "string") {
            failMessage = " value was expected to be of type string but was typeof: " + typeof(valueToTest);
        }
        break;
    case "number":
        nodeValue = parseFloat(valueToTest);
        if (isNaN(nodeValue)) {
            failMessage = " value was expected to be of type number but was typeof: " + typeof(valueToTest);
        }
        break;
    case "integer":
        nodeValue = parseInt(valueToTest, 10);
        if (isNaN(nodeValue)) {
            failMessage = " value was expected to be of type number but was typeof: " + typeof(valueToTest);
        }
        break;
    case "boolean":
        if (valueToTest !== "false" && valueToTest !== "true") {
            failMessage = " value was expected to be of type boolean (i.e. 'true' or 'false' but was: " + valueToTest;
        }
        break;
    case "list":
        if (!utils.arrayContains(schemaNode.listValues, valueToTest)) {
            failMessage = " value is not recognized as being valid, it was:<br/><br/><span class=\"ui-text-fail\">" + valueToTest +
                    "</span><br/><br/>Valid values are:<p class=\"ui-text-pass\">" + schemaNode.listValues.join(" <br/> ") + "</p>";
        }
        break;
    case "listBoolean":
    case "listDefault":
        if (!utils.arrayContains(schemaNode.listValues, valueToTest)) {
            failMessage = " value is not recognized as being valid, it was:<br/><br/><span class=\"ui-text-fail\">" + valueToTest +
                    "</span><br/><br/>The framework will assume the value to be:<p class=\"ui-text-pass\">" + schemaNode.defaultValue + "</p>";
        }
        break;
    case "listNumbers":
        numbers = valueToTest.split(",");

        for (numberRangeIndex = 0; numberRangeIndex < numbers.length; numberRangeIndex++) {
            numberRange = valueToTest.split("-");
            if (numberRange.length > 1) {
                range1 = parseInt(numberRange[0], 10);
                range2 = parseInt(numberRange[1], 10);
                if (isNaN(range1) || isNaN(range2)) {
                    failMessage = " range values where not recognized as being valid, they was: " + range1 +
                            " and " + range2 + " :: valid values should be of type 'integer'";
                    break;
                }
            }
            else if (numberRange.length === 1) {
                range1 = parseInt(numberRange[0], 10);
                if (isNaN(range1)) {
                    failMessage = " value was not recognized as being valid, it was: " + range1 +
                            " :: valid values should be of type 'integer'";
                    break;
                }
            }
        }
        break;
    case "regex":
        if (!valueToTest.match(schemaNode.regex)) {
            failMessage = " value does not match expected format. Value should pass this regular expression validation: " + schemaNode.regex;
        }
        break;
    case "iso-language":
        break;
    default:
        exception.raise(exception.types.Application, "Schema node with value type of: " + schemaNode.type + " is not known");
    }

    return failMessage;
}

function _passNodeValidation(schemaNode, value, node) {
    var validationResult = utils.copy(_validationResult);

    if (!schemaNode.validationResult) {
        schemaNode.validationResult = [];
    }
    validationResult.valid = true;
    validationResult.node = node;
    if (value) {
        validationResult.value = value;
    }
    else {
        delete(validationResult.value);
    }
    delete(validationResult.message);

    schemaNode.validationResult.push(validationResult);
}

function _validateNodeValue(schemaNode, node) {
    var failMessage,
        valueToTest = node && node.nodeValue ? node.nodeValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : null;

    if (schemaNode.type && valueToTest) {

        failMessage = _validateValue(valueToTest, schemaNode);

        if (failMessage !== "") {
            _failNodeValidation(schemaNode, failMessage, valueToTest, node);
            return;
        }
    }
    _passNodeValidation(schemaNode, valueToTest, node);
}

function _failNodeAttributeValidation(node, attribute, message, value) {
    var nodeValidationResult = node.validationResult ? node.validationResult.pop() : utils.copy(_validationResult),
        attributeValidationResult = utils.copy(_validationResult);

    if (!nodeValidationResult.attributes) {
        nodeValidationResult.attributes = {};
    }

    nodeValidationResult.valid = false;
    nodeValidationResult.message = "One or more attributes failed validation";

    attributeValidationResult.attributeName = attribute.attributeName;
    attributeValidationResult.valid = false;
    if (value) {
        attributeValidationResult.value = value;
    }
    else {
        delete(attributeValidationResult.value);
    }
    attributeValidationResult.message = node.nodeName + "." + attribute.attributeName + message;

    nodeValidationResult.attributes[attribute.attributeName] = attributeValidationResult;
    node.validationResult.push(nodeValidationResult);
}

function _passNodeAttributeValidation(node, attribute, value) {
    var nodeValidationResult = node.validationResult ? node.validationResult.pop() : utils.copy(_validationResult),
        attributeValidationResult = utils.copy(_validationResult);

    if (!nodeValidationResult.attributes) {
        nodeValidationResult.attributes = {};
    }

    attributeValidationResult.attributeName = attribute.attributeName;
    attributeValidationResult.valid = true;
    if (value) {
        attributeValidationResult.value = value;
    }
    else {
        delete(attributeValidationResult.value);
    }
    delete(attributeValidationResult.message);

    nodeValidationResult.attributes[attribute.attributeName] = attributeValidationResult;
    node.validationResult.push(nodeValidationResult);
}

function _validateNodeAttributeValue(schemaNode, schemaNodeAttribute, attribute) {
    var failMessage,
        valueToTest = attribute ? attribute.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : null;

    if (schemaNodeAttribute.type && valueToTest) {

        failMessage = _validateValue(valueToTest, schemaNodeAttribute);

        if (failMessage !== "") {
            _failNodeAttributeValidation(schemaNode, schemaNodeAttribute, failMessage, valueToTest);
            return;
        }
    }
    _passNodeAttributeValidation(schemaNode, schemaNodeAttribute, valueToTest);
}

function _validateNodeAttributes(schemaNode, node, children) {

    var siblings = utils.filter(children, function (child) {
            return child !== node;
        }),
        attributeConverter = function (attribute) {
            var _self = {
                toValue: function (n) {
                    var obj = _self.toNode(n);
                    return obj ? obj.value : null;
                },
                toNode: function (n) {
                    return n.attributes.getNamedItem(attribute.attributeName);
                }
            };

            return _self;
        };

    utils.forEach(schemaNode.attributes, function (attribute) {

        var convert = attributeConverter(attribute),
            dupe = false;

        if (attribute.unique) {
            // this means we need to check and see if there are other node with the same name
            // and ensure that they have a different value for this attributes, if not... fail

            dupe = siblings.some(function (sibling) {
                return convert.toValue(sibling) === convert.toValue(node);
            });

            if (dupe) {
                _failNodeAttributeValidation(schemaNode,
                        attribute,
                        " node is allowed to appear multiple times, however it must be unique based on this attribute and in this case another node with an identical attribute vale was found",
                        convert.toValue(node));
                return;
            }
        }

        if (attribute.required && !convert.toValue(node)) {
            _failNodeAttributeValidation(schemaNode, attribute, " attribute was expected but not found", null);
        }
        else {
            _validateNodeAttributeValue(schemaNode, attribute, convert.toNode(node));
        }
    });
}


function _validateNode(schemaNode, parentNode) {
    var children = utils.filter(parentNode.childNodes, function (child) {
        return child && child.nodeName === schemaNode.nodeName;
    });

    if (children.length === 0) {
        if (schemaNode.required) {
            _failNodeValidation(schemaNode, " node expected, but not found", null, null);
        }
    }

    utils.forEach(children, function (child) {
        if (schemaNode.occurrence !== 0 && schemaNode.occurrence < children.length) {
            _failNodeValidation(schemaNode, " node: more then " + schemaNode.occurrence + " node(s) found", null, child);
        }
        else {
            _validateNodeValue(schemaNode, child.childNodes[0] || child);

            _validateNodeAttributes(schemaNode, child, children);
        }

        utils.forEach(schemaNode.children, function (schema) {
            _validateNode(schema, child);
        });
    });
}

function _validateAgainstSchemaNode(configSchema, configXML) {
    var results = utils.copy(configSchema);
    try {
        _validateNode(results[configSchema.rootElement], configXML);
    }
    catch (e) {
        exception.handle(e, true);
    }

    return results;
}

function _validate(configXML) {
    // traverse the config schema JSON object
    // TODO: update to get platform.getPlatformConfigSpec().schema
    return _validateAgainstSchemaNode(platform.current().config.schema, configXML);
}

function _process(results) {
    // Check to make sure that widget is the correct version (i.e. config.xml needs to match selected platform)
    var validVersion = app.validateVersion(results);

    if (!validVersion) {
        _console.warn("Your application does not appear to match" +
                " the platform you have selected. The version number in your configuration might not " +
                "match the selected platform version or your configuration file has errors in it.");
    }

    // save widget info
    app.saveInfo(results);
    event.trigger("WidgetInformationUpdated");

    // Check for readonly preferences (WAC only?)

    if (app.getInfo().preferences !== {}) {
        event.trigger("StorageUpdatedEvent");
    }
}

function _xmlToJson(xml) {
    var obj = {};

    if (xml.nodeType === 1) { // element
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            utils.forEach(xml.attributes, function (attribute) {
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            });
        }
    } 
    else if (xml.nodeType === 3) { // text node
        obj = xml.nodeValue;
    }

    if (xml.hasChildNodes && xml.hasChildNodes()) {
        utils.forEach(xml.childNodes, function (child) {
            if (!child.nodeName) {
                return;
            }
            if (!obj[child.nodeName]) {
                obj[child.nodeName] = [];
            }
            obj[child.nodeName].push(_xmlToJson(child));
        });
    }

    return obj;
}

module.exports = {

    validate: function (configXML) {
        utils.validateNumberOfArguments(1, 1, arguments.length);
        return _validate(configXML);
    },

    initialize: function (previous, baton) {
        var xmlHttp = new XMLHttpRequest(),
            config = platform.current().config,
            fileName = config ? config.fileName : null,
            results;

        if (!fileName) {
            return;
        }

        try {
            xmlHttp.open("GET", utils.appLocation() + fileName, false);
            xmlHttp.send();
            if (xmlHttp.responseXML) {
                results = _validate(xmlHttp.responseXML);
                results.rawJSON = _xmlToJson(xmlHttp.responseXML);
                _process(results);
                _configValidationResults = results;
            }
            else {
                _process();
                _configValidationResults = null;
                require('ripple/ui/plugins/widgetConfig').initialize();
            }
        }
        catch (e) {
            exception.handle(e);
        }
    },

    getValidationResults: function () {
        return _configValidationResults;
    }
};

});
define('ripple/xhr/base', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 XHR = window.XMLHttpRequest;

function _handle(object, key) {
    return function () {
        return object[key].apply(object, Array.prototype.slice.call(arguments));
    };
}

function _getter(object, key) {
    return function () {
        return object[key];
    };
}

function _setter(object, key) {
    return function (val) {
        object[key] = val;
    };
}

function _writeable(obj) {
    var newObj = {},
        key;

    // need prototypes
    for (key in obj) {
        //HACK: don't even know what to say bout this, resonseBlob can go fly a kite: related to this issue:
        //https://github.com/blackberry/Ripple-UI/issues/394
        if (key !== "responseBlob" && typeof obj[key] === "function") {
            newObj[key] = _handle(obj, key);
        } else {
            newObj.__defineGetter__(key, _getter(obj, key));
            newObj.__defineSetter__(key, _setter(obj, key));
        }
    }

    return newObj;
}

function _XMLHttpRequest() {
    var Xhr = require('ripple/emulatorBridge').xhr() || XHR;
    return _writeable(new Xhr());
}

module.exports = _XMLHttpRequest;

});
define('ripple/xhr/cors', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 helpers = require('ripple/xhr/helpers'),
    constants = require('ripple/constants'),
    XHR = require('ripple/xhr/base');

function _XMLHttpRequest() {
    var xhr = new XHR(),
        origMethods = {
            setRequestHeader: xhr.setRequestHeader,
            open: xhr.open
        };

    xhr.setRequestHeader = function (header, value) {
        // This is done to get around jQuery 1.3.2 setting a header that it shouldn't
        if (header && header.toUpperCase() !== "X-REQUESTED-WITH") {
            origMethods.setRequestHeader.apply(xhr, Array.prototype.slice.call(arguments));
        }
    };

    xhr.open = function (method, url, async, user, password) {
        if (!helpers.isLocalRequest(url)) {
            url = constants.API_URL + "/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=" + escape(url);
        }

        origMethods.open.apply(xhr, Array.prototype.slice.call(arguments));
    };

    return xhr;
}

module.exports = _XMLHttpRequest;

});
define('ripple/xhr/helpers', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    db = require('ripple/db');

module.exports = {
    isLocalRequest: function (url) {
        return (!!(url.match(constants.REGEX.LOCAL_URI)) || !url.match(constants.REGEX.EXTERNAL_URI)) || 
                !!(location.host && url.match(location.host));
    },

    proxyEnabled: function () {
        var isDisabled = db.retrieve(constants.XHR.PROXY_DISABLED_BUTTON);
        return !isDisabled || isDisabled === "false" ? true : false;
    }
};

});
define('ripple/xhr/jsonp', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    exception = require('ripple/exception'),
    utils = require('ripple/utils'),
    helpers = require('ripple/xhr/helpers'),
    _console = require('ripple/console'),
    XHR = require('ripple/xhr/base');

function _XMLHttpRequest() {
    var xhr = new XHR(),
        origMethods = {
            setRequestHeader: xhr.setRequestHeader,
            getResponseHeader: xhr.getResponseHeader,
            getAllResponseHeaders: xhr.getAllResponseHeaders,
            open: xhr.open,
            send: xhr.send,
            abort: xhr.abort
        },
        _jxhr = new window.jXHR(),
        _sendFlag = false,
        _headers = [],
        _errorFlag = false,
        _url,
        _async;

    function _localURI() {
        return _url && helpers.isLocalRequest(_url);
    }

    function _set(prop, value) {
        xhr.__defineGetter__(prop, function () {
            return value;
        });
    }

    function _reset() {
        _set("response", "");
        _set("responseText", "");
        _set("responseXML", null);
    }

    xhr.setRequestHeader = function (header, value) {
        if (_localURI()) {
            origMethods.setRequestHeader.apply(xhr, Array.prototype.slice.call(arguments));
        } else {
            _console.error("XMLHttpRequest :: setRequestHeader does not work with JSONP.");
        }
    };

    xhr.getResponseHeader = function (header) {
        return _localURI() ?
                origMethods.getAllResponseHeaders.apply(xhr, [header]) :
                _headers[header] || null;
    };

    xhr.getAllResponseHeaders = function () {
        return _localURI() ?
                origMethods.getAllResponseHeaders.apply(xhr) :
                utils.reduce(_headers, function (str, value, key) {
                    return str + key + ": " + value + '\n';
                }, "").replace(/\n$/, '');
    };

    xhr.open = function (method, url, async) {
        _url = url;
        _async = async !== false ? true : false;

        if (_localURI()) {
            origMethods.open.apply(xhr, Array.prototype.slice.call(arguments));
        } else {
            _reset();
            method = method.toUpperCase();

            if (method === "POST") {
                //HACK: Switch the method to get for now to simulate post
                method = "GET";
            }

            if (method !== "GET") {
                exception.raise(exception.types.MethodNotImplemented, "Method: " + method + " not supported!");
            }

            _jxhr.onreadystatechange = function (data) {
                var response;

                try {
                    _set("readyState", _jxhr.readyState);

                    if (xhr.readyState === xhr.DONE) {
                        _sendFlag = false;
                        _set("status", data.status);
                        _set("statusText", data.statusText);
                        _headers = data.headers;

                        if (data.responseXML) {
                            response = new DOMParser().parseFromString(unescape(data.responseXML), "text/xml");
                            _set("responseXML", response);
                        } else {
                            response = unescape(data.responseText);
                            _set("responseText", response);
                        }

                        _set("response", response);
                    }

                    if (typeof xhr.onreadystatechange === "function") {
                        xhr.onreadystatechange.apply(xhr);
                    }
                } catch (e) {
                    exception.handle(e);
                }
            };

            _jxhr.onerror = xhr.onerror;
            _jxhr.open(method, constants.API_URL + "/jsonp_xhr_proxy?callback=?&tinyhippos_apikey=ABC&tinyhippos_rurl=" + escape(url));
        }
    };

    xhr.send = function (data) {
        if (_localURI()) {
            origMethods.send(data);
            return;
        }

        if (!_async) {
            exception.raise(exception.types.MethodNotImplemented, "Synchronous not supported.");
        }

        if (xhr.readyState !== xhr.OPENED || _sendFlag === true) {
            exception.raise(exception.types.InvalidState, "Ready state should be OPENED (1)");
        }

        _errorFlag = false;
        _sendFlag = true;
        data = null;

        _jxhr.send();
    };

    xhr.abort = function () {
        if (_localURI()) {
            origMethods.abort();
            return;
        }

        _reset();

        _errorFlag = true;

        if (xhr.readyState === xhr.UNSENT ||
                (xhr.readyState === xhr.OPENED && _sendFlag === false) ||
                xhr.readyState === xhr.DONE) {
            _set("readyState", xhr.UNSENT);
        } else {
            _set("readyState", xhr.DONE);
            _sendFlag = false;

            if (typeof xhr.onreadystatechange === "function") {
                xhr.onreadystatechange.apply(xhr);
            }
        }

        _jxhr.onreadystatechange = null;

        if (xhr.onabort) {
            xhr.onabort.apply(xhr, arguments);
        }
    };

    return xhr;
}

module.exports = _XMLHttpRequest;

});
define('ripple/xhr', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 constants = require('ripple/constants'),
    utils = require('ripple/utils'),
    ui = require('ripple/ui'),
    helpers = require('ripple/xhr/helpers'),
    XHR = window.XMLHttpRequest;

module.exports = {
    initialize: function (previous, baton) {
        window.XMLHttpRequest = require('ripple/xhr/base');

        if (helpers.proxyEnabled() && !ui.registered("omnibar")) {
            var isFileScheme = utils.location().protocol.match(/^file:/);
            window.XMLHttpRequest = require(isFileScheme ? 'ripple/xhr/jsonp' : 'ripple/xhr/cors');
        }
    }
};

});
define('ripple', function (require, exports, module) {
/*
 *  Copyright 2011 Research In Motion Limited.
 *
 * 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 omgwtf = require('ripple/omgwtf'),
    db = require('ripple/db'),
    xhr = require('ripple/xhr'),
    geo = require('ripple/geo'),
    fileSystem = require('ripple/fileSystem'),
    fs = require('ripple/dbfs'),
    platform = require('ripple/platform'),
    emulatorBridge = require('ripple/emulatorBridge'),
    devices = require('ripple/devices'),
    widgetConfig = require('ripple/widgetConfig'),
    deviceSettings = require('ripple/deviceSettings'),
    sensorSettings = require('ripple/sensorSettings'),
    ui = require('ripple/ui'),
    appcache = require('ripple/appcache'),
    _self = {
        boot: function (booted) {
            // techdebt (event registration timing)
            // require('ripple/platform/webworks.core/2.0.0/fsCache');

            window.addEventListener("keydown", function (event) {
                var hasMetaOrAltPressed = (event.metaKey || event.ctrlKey),
                    key = parseInt(event.keyCode, 10);

                if (key === 37 && hasMetaOrAltPressed) { // cmd/ctrl + left arrow
                    event.preventDefault();
                    emulatorBridge.window().history.back();
                }

                if (key === 39 && hasMetaOrAltPressed) { // cmd/ctrl + right arrow
                    event.preventDefault();
                    emulatorBridge.window().history.forward();
                }

                if (key === 82 && hasMetaOrAltPressed) { // cmd/ctrl + r
                    event.preventDefault();
                    window.tinyHipposReload = true;
                    emulatorBridge.window().location.reload();
                }

                if (key === 116) { // F5
                    event.preventDefault();
                    window.tinyHipposReload = true;
                    emulatorBridge.window().location.reload();
                }
            });

            window.onbeforeunload = function () { 
                if (!window.tinyHipposReload) {
                    return "Tizen Web Simulator";
                }
            };

            jWorkflow.order(omgwtf.initialize, omgwtf)
                 .andThen(appcache.initialize, appcache)
                 .andThen(db.initialize, db)
                 .andThen(xhr.initialize, xhr)
                 .andThen(geo.initialize, geo)
                 .andThen(fileSystem.initialize, fileSystem)
                 .andThen(fs.initialize, fs)
                 .andThen(platform.initialize, platform)
                 .andThen(devices.initialize, devices)
                 .andThen(widgetConfig.initialize, widgetConfig)
                 .andThen(deviceSettings.initialize, deviceSettings)
                 .andThen(ui.initialize, ui)
                 .start(booted);
        }
    };

module.exports = _self;

});
require('ripple/ui').register('omnibar');require('ripple/bootstrap').bootstrap();
