From ed85c305fa08306bfb185a41a0125fb199c7a7b8 Mon Sep 17 00:00:00 2001 From: Pure Krome Date: Mon, 30 Jul 2018 17:45:49 +1000 Subject: [PATCH] :space_invader: Number 5 is alive! --- .gitattributes | 1 + .gitignore | 56 + CODE_OF_CONDUCT.md | 46 + CONTRIBUTING.md | 53 + LICENSE.txt | 12 + README.md | 13 + YUICompressor.NET.MSBuild.sln | 31 + appveyor.yml | 62 + .../ActionType.cs | 9 + .../CompressorTask.cs | 60 + .../CompressorTaskEngine.cs | 428 ++ .../CssCompressorTask.cs | 24 + src/Yahoo.Yui.Compressor.MsBuild/FileSpec.cs | 27 + src/Yahoo.Yui.Compressor.MsBuild/ILog.cs | 17 + .../JavaScriptCompressorTask.cs | 129 + .../MsBuildLogAdapter.cs | 41 + .../Yahoo.Yui.Compressor.MsBuild.csproj | 34 + .../SampleStylesheet1.css | 476 ++ .../Cascading Style Sheet Files/bug9527.css | 5 + .../CssCompressorTaskTests.cs | 189 + .../CustomDictionary.xml | 8 + .../JavaScriptCompressorTaskTests.cs | 235 + .../Javascript Files/Accents.Expected.min.js | 1 + .../Javascript Files/Accents.js | 6 + .../Javascript Files/Issue9719.js | 8 + .../Javascript Files/SampleJavaScript1.js | 246 + .../Javascript Files/SampleJavaScript2.js | 6336 +++++++++++++++++ .../TestHelpers/BuildEngine.cs | 55 + .../TestHelpers/BuildEngineStub.cs | 63 + .../Yahoo.Yui.Compressor.MsBuild.Tests.csproj | 44 + 30 files changed, 8715 insertions(+) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.txt create mode 100644 README.md create mode 100644 YUICompressor.NET.MSBuild.sln create mode 100644 appveyor.yml create mode 100644 src/Yahoo.Yui.Compressor.MsBuild/ActionType.cs create mode 100644 src/Yahoo.Yui.Compressor.MsBuild/CompressorTask.cs create mode 100644 src/Yahoo.Yui.Compressor.MsBuild/CompressorTaskEngine.cs create mode 100644 src/Yahoo.Yui.Compressor.MsBuild/CssCompressorTask.cs create mode 100644 src/Yahoo.Yui.Compressor.MsBuild/FileSpec.cs create mode 100644 src/Yahoo.Yui.Compressor.MsBuild/ILog.cs create mode 100644 src/Yahoo.Yui.Compressor.MsBuild/JavaScriptCompressorTask.cs create mode 100644 src/Yahoo.Yui.Compressor.MsBuild/MsBuildLogAdapter.cs create mode 100644 src/Yahoo.Yui.Compressor.MsBuild/Yahoo.Yui.Compressor.MsBuild.csproj create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/Cascading Style Sheet Files/SampleStylesheet1.css create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/Cascading Style Sheet Files/bug9527.css create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/CssCompressorTaskTests.cs create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/CustomDictionary.xml create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/JavaScriptCompressorTaskTests.cs create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Accents.Expected.min.js create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Accents.js create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Issue9719.js create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/SampleJavaScript1.js create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/SampleJavaScript2.js create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/TestHelpers/BuildEngine.cs create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/TestHelpers/BuildEngineStub.cs create mode 100644 tests/Yahoo.Yui.Compressor.MsBuild.Tests/Yahoo.Yui.Compressor.MsBuild.Tests.csproj diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..5378fe0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* -text \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ab065ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,56 @@ +*.obj +*.pdb +*.user +*.aps +*.pch +*.vspscc +*.vssscc +*_i.c +*_p.c +*.ncb +*.suo +*.tlb +*.tlh +*.bak +*.cache +*.ilk +*.log +*.lib +*.sbr +*.scc +*.tmp +[Bb]in/ +[Dd]ebug/ +obj/ +[Rr]elease/ +[Tt]humbs.db +[Tt]est[Rr]esult* +[Bb]uild[Ll]og.* +*.[Pp]ublish.xml +*.log.* +[Ll]ogs/ +[Dd]ata/ +[Pp]ackages/ +*nlog*.csv +nlog-404s.csv +imagecache/ +[Aa]ssemblies/ +[Rr]aven/ +.vs/ + +# Windows Azure +csx/ +rcf/ + +# Windows Azure Publish Settings contain security keys for accessing your Windows Azure account +.publishsettings + +# Resharper Ignores +_ReSharper.*/ +*.resharper.user + +.sass-cache/ + +# Ignore build stuff +[Bb]uild/Artifacts/ +[Ss]cripts-[Bb]uild/ \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..d8112a5 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at openrealestate@world-domination.com.au. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..5a43a13 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,53 @@ +# How to contribute + +One of the easiest ways to contribute is to participate in discussions and discuss issues. You can also contribute by submitting pull requests with code changes. + +## Filing issues +- Don't be afraid to ask any question about the project, including suggestions to change how things currently are. +- Keep the conversation polite and respectful. This way, all parties will take an interest in your question and will be more proactive into helping. +- For bugs, the best way to get your bug fixed is to be as detailed as you can be about the problem. Providing a minimal project with steps to reproduce the problem is ideal. Even though this might be painful, it will speed up the resolution to the problem. + +GitHub supports [markdown](https://help.github.com/articles/github-flavored-markdown/), so when filing bugs make sure you check the formatting before clicking submit. + +## Contributing code and content + +**Identifying the scale** + +If you would like to contribute to one of our repositories, first identify the scale of what you would like to contribute. If it is small (grammar/spelling or a bug fix) feel free to start working on a fix. If you are submitting a feature or substantial code contribution, please discuss it with the team. + +You can also read these two blogs posts on contributing code: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza and [Don't "Push" Your Pull Requests](https://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik. Note that all code submissions will be reviewed and tested by team members. Of course (where appropriate), tests will be required. + +**Obtaining the source code** + +If you are an outside contributer, please fork the appropriate repository you would like to contribute to. See the GitHub documentation on [forking a repo](https://help.github.com/articles/fork-a-repo/) if you have any questions about this. + +**Building our Repositories** + +All repositories are designed to be simple to get started. Once you have pulled down your own fork, just open up the solution file (`.sln` for .NET) and then compile the solution. + +**Submitting a Pull Request** + +If you don't know what a pull request is read this article: https://help.github.com/articles/using-pull-requests. Make sure the repository can build and all tests pass. Familiarize yourself with the project workflow and our coding conventions. + +Pull requests should all be done to the `master` branch. + +When a pull request is accepted, squashed and merged (by the repo Administrators), we then manually create a Git tag, which will then be the trigger point to creating a new NuGet package. As such, we don't always create new NuGet packages on every Pull Request ... which is why this is a manual step. + +**Commit/Pull Request Format** + +``` +Summary of the changes (Less than 80 chars) + - Detail 1 + - Detail 2 + +Addresses #bugnumber (in this specific format) +``` + +**Tests** + +- Tests need to be provided for every bug/feature that is completed. +- Tests only need to be present for issues that need to be verified by QA (e.g. not tasks) +- If there is a scenario that is far too hard to test there does not need to be a test for it. + - "Too hard" is determined by the team as a whole. + +--- \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..0a35d44 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) 2008 - 2012, Pure Krome +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 World Domination Technologies 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 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. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..ddedc1e --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +## Project Description +This is an MSBuild Task for helping minify and/or combine JS and CSS using the YUICompressor.NET library. + +![CI Status via AppVeyor](https://ci.appveyor.com/api/projects/status/na9m20sc8dr8qg2r) ![NuGet](https://img.shields.io/nuget/dt/yuicompressor.net.msbuild.svg?syle=flat-square) + +## Available via NuGet + +[![NuGet Command with MSBuild Task](https://i.imgur.com/aqKIj.png)](https://nuget.org/packages/YUICompressor.NET.MSBuild) + +Package Name: `YUICompressor.NET.MSBuild` +CLI: `install-package YUICompressor.NET.MSBuild` + +--- diff --git a/YUICompressor.NET.MSBuild.sln b/YUICompressor.NET.MSBuild.sln new file mode 100644 index 0000000..e243e4c --- /dev/null +++ b/YUICompressor.NET.MSBuild.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2042 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yahoo.Yui.Compressor.MsBuild", "src\Yahoo.Yui.Compressor.MsBuild\Yahoo.Yui.Compressor.MsBuild.csproj", "{FC51E4A2-EB87-462D-8945-92DD5A4F4624}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Yahoo.Yui.Compressor.MsBuild.Tests", "tests\Yahoo.Yui.Compressor.MsBuild.Tests\Yahoo.Yui.Compressor.MsBuild.Tests.csproj", "{CEBF623F-AA1D-4694-988C-B9DDEC91F0A9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FC51E4A2-EB87-462D-8945-92DD5A4F4624}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FC51E4A2-EB87-462D-8945-92DD5A4F4624}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FC51E4A2-EB87-462D-8945-92DD5A4F4624}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FC51E4A2-EB87-462D-8945-92DD5A4F4624}.Release|Any CPU.Build.0 = Release|Any CPU + {CEBF623F-AA1D-4694-988C-B9DDEC91F0A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CEBF623F-AA1D-4694-988C-B9DDEC91F0A9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CEBF623F-AA1D-4694-988C-B9DDEC91F0A9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CEBF623F-AA1D-4694-988C-B9DDEC91F0A9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {244388D8-E74A-46E6-B529-C91A484327EE} + EndGlobalSection +EndGlobal diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000..596a399 --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,62 @@ + +version: '{build}.0.0-dev' +configuration: Release +os: Visual Studio 2017 +pull_requests: + do_not_increment_build_number: true + +environment: + nuget_apiKey: + secure: jfcUvHZhgnUboplqTBDWr8mG5PIlrgBv5TA2fhhop4ZSiDxskyy+RtYyeHoduJFR + myget_apiKey: + secure: AguzfXNvHBkkDebTyWHK7o9OC5YL3eszT6u7PnzGq2G7ozdUypDlGGpcFsTRYHEc + +# Override the 'version' if this is a GH-tag-commit -or- this is a custom branch (i.e not 'master'). +init: + - ps: | + if ($env:APPVEYOR_REPO_TAG -eq $TRUE -and $env:APPVEYOR_REPO_BRANCH -eq 'master') + { + Write-Host " !! Commit is Tagged and branch is 'master' - forcing build version to tag-value." -ForegroundColor Red; + Update-AppveyorBuild -Version "$env:APPVEYOR_REPO_TAG_NAME" + } + iex ((new-object net.webclient).DownloadString('https://gist.githubusercontent.com/PureKrome/0f79e25693d574807939/raw/f5b40256fc2ca77d49f1c7773d28406152544c1e/appveyor-build-info.ps')) + + +before_build: + # Display .NET Core version + - cmd: dotnet --info + # Display minimal restore text + - cmd: dotnet restore --verbosity quiet + +build_script: + - dotnet build -c %CONFIGURATION% -v minimal /p:Version=%APPVEYOR_BUILD_VERSION% --no-restore + +test_script: + - dotnet test tests\Yahoo.Yui.Compressor.MsBuild.Tests -c %CONFIGURATION% -v minimal --no-restore --no-build + - dotnet pack -c %CONFIGURATION% /p:Version=%APPVEYOR_BUILD_VERSION% --no-restore --no-build + +artifacts: + - path: '**\*.nupkg' + name: packaged-nugets + type: NuGetPackage + +deploy: + - provider: NuGet + server: https://www.myget.org/F/pk-development/api/v2/package + api_key: + secure: AguzfXNvHBkkDebTyWHK7o9OC5YL3eszT6u7PnzGq2G7ozdUypDlGGpcFsTRYHEc + skip_symbols: true + artifact: packaged-nugets + on: + appveyor_repo_tag: false + - provider: NuGet + api_key: + secure: jfcUvHZhgnUboplqTBDWr8mG5PIlrgBv5TA2fhhop4ZSiDxskyy+RtYyeHoduJFR + skip_symbols: true + artifact: packaged-nugets + on: + branch: master + appveyor_repo_tag: true + +cache: + - packages -> **\packages.config \ No newline at end of file diff --git a/src/Yahoo.Yui.Compressor.MsBuild/ActionType.cs b/src/Yahoo.Yui.Compressor.MsBuild/ActionType.cs new file mode 100644 index 0000000..807d939 --- /dev/null +++ b/src/Yahoo.Yui.Compressor.MsBuild/ActionType.cs @@ -0,0 +1,9 @@ +namespace Yahoo.Yui.Compressor.MsBuild +{ + public enum ActionType + { + Unknown, + Css, + JavaScript + } +} \ No newline at end of file diff --git a/src/Yahoo.Yui.Compressor.MsBuild/CompressorTask.cs b/src/Yahoo.Yui.Compressor.MsBuild/CompressorTask.cs new file mode 100644 index 0000000..ac12cba --- /dev/null +++ b/src/Yahoo.Yui.Compressor.MsBuild/CompressorTask.cs @@ -0,0 +1,60 @@ +using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; + +namespace Yahoo.Yui.Compressor.MsBuild +{ + using System.Collections.Generic; + + public abstract class CompressorTask : Task + { + protected readonly CompressorTaskEngine TaskEngine; + + public string LoggingType { get; set; } + + [Required] + public ITaskItem[] SourceFiles { get; set; } + + [Required] + public string OutputFile { get; set; } + + public string CompressionType { get; set; } + + public string EncodingType { get; set; } + + public bool DeleteSourceFiles { get; set; } + + public int LineBreakPosition { get; set; } + + protected CompressorTask(ICompressor compressor) + { + TaskEngine = new CompressorTaskEngine(new MsBuildLogAdapter(Log), compressor) { SetTaskEngineParameters = this.SetTaskEngineParameters }; + DeleteSourceFiles = false; + LineBreakPosition = -1; + } + + public override bool Execute() + { + return this.TaskEngine.Execute(); + } + + protected virtual void SetTaskEngineParameters() + { + this.TaskEngine.CompressionType = this.CompressionType; + this.TaskEngine.DeleteSourceFiles = this.DeleteSourceFiles; + this.TaskEngine.EncodingType = this.EncodingType; + this.TaskEngine.LineBreakPosition = this.LineBreakPosition; + this.TaskEngine.LoggingType = this.LoggingType; + this.TaskEngine.OutputFile = this.OutputFile; + var fileSpecs = new List(); + if (SourceFiles == null) + { + return; + } + foreach (var sourceFile in SourceFiles) + { + fileSpecs.Add(new FileSpec(sourceFile.ItemSpec, sourceFile.GetMetadata("CompressionType"))); + } + this.TaskEngine.SourceFiles = fileSpecs.ToArray(); + } + } +} \ No newline at end of file diff --git a/src/Yahoo.Yui.Compressor.MsBuild/CompressorTaskEngine.cs b/src/Yahoo.Yui.Compressor.MsBuild/CompressorTaskEngine.cs new file mode 100644 index 0000000..b331964 --- /dev/null +++ b/src/Yahoo.Yui.Compressor.MsBuild/CompressorTaskEngine.cs @@ -0,0 +1,428 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Reflection; +using System.Text; +using System.Threading; + +namespace Yahoo.Yui.Compressor.MsBuild +{ + public class CompressorTaskEngine + { + private CompressionType _compressionType; + + public LoggingType LogType; + + public Encoding Encoding; + + private readonly ICompressor _compressor; + + public string LoggingType { get; set; } + + public FileSpec[] SourceFiles { get; set; } + + public string OutputFile { get; set; } + + public string CompressionType { get; set; } + + public string EncodingType { get; set; } + + public bool DeleteSourceFiles { get; set; } + + public int LineBreakPosition { get; set; } + + public ILog Log { get; private set; } + + public Action SetTaskEngineParameters; + + public Action ParseAdditionalTaskParameters; + + public Action LogAdditionalTaskParameters; + + public Action SetCompressorParameters; + + public delegate void Action(); + + public CompressorTaskEngine(ILog log, ICompressor compressor) + { + Log = log; + _compressor = compressor; + Encoding = Encoding.Default; + DeleteSourceFiles = false; + LineBreakPosition = -1; + } + + public bool Execute() + { + try + { + if (SetTaskEngineParameters != null) + { + SetTaskEngineParameters(); + } + ParseTaskParameters(); + if (SetCompressorParameters != null) + { + SetCompressorParameters(); + } + } + catch (Exception ex) + { + Log.LogErrorFromException(ex); + return false; + } + + // Check to make sure we have the bare minimum arguments supplied to the task. + if (SourceFiles == null || SourceFiles.Length == 0) + { + Log.LogError("At least one file is required to be compressed / minified."); + return false; + } + + if (string.IsNullOrEmpty(OutputFile)) + { + Log.LogError("The outfile is required if one or more css input files have been defined."); + return false; + } + + foreach (var sourceFile in SourceFiles) + { + if (string.Compare(sourceFile.FileName, OutputFile, StringComparison.InvariantCultureIgnoreCase) == 0) + { + Log.LogError("Output file cannot be the same as source file(s)."); + return false; + } + } + + if (LogType == Yui.Compressor.LoggingType.Debug) + { + LogTaskParameters(); + if (LogAdditionalTaskParameters != null) + { + LogAdditionalTaskParameters(); + } + } + + Log.LogMessage("Starting Compression..."); + + // Determine and log the Assembly version. + var assembly = Assembly.GetExecutingAssembly(); + var fileVersionAttributes = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false); + var assemblyFileVersion = fileVersionAttributes.Length > 0 + ? ((AssemblyFileVersionAttribute)fileVersionAttributes[0]).Version + : "Unknown File Version"; + + var assemblyTitleAttributes = assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false); + var assemblyTitle = assemblyTitleAttributes.Length > 0 + ? ((AssemblyTitleAttribute)assemblyTitleAttributes[0]).Title + : "Unknown Title"; + + Log.LogMessage(string.Format("Using version {0} of {1}.", assemblyFileVersion, assemblyTitle)); + + // What is the current thread culture? + Log.LogMessage( + string.Format( + "Current thread culture / UI culture (before modifying, if requested): {0}/{1}", + Thread.CurrentThread.CurrentCulture.EnglishName, + Thread.CurrentThread.CurrentUICulture.EnglishName)); + + Log.LogMessage(string.Empty); // This, in effect, is a new line. + + var startTime = DateTime.Now; + var errorFound = false; + var compressedText = CompressFiles(out errorFound); + + if (errorFound) + { + Log.LogMessage("Error found during compression - see log."); + return false; + } + + // Save this css to the output file, if we have some result text. + if (!SaveCompressedText(compressedText)) + { + Log.LogMessage("Failed to finish compression - terminating prematurely."); + return false; + } + + Log.LogMessage("Finished compression."); + Log.LogMessage( + string.Format( + CultureInfo.InvariantCulture, "Total time to execute task: {0}", (DateTime.Now - startTime))); + Log.LogMessage("8< --------------------------------- ( o Y o ) --------------------------------- >8"); + Log.LogMessage(string.Empty); // This, in effect, is a new line. + + return true; + } + + public void ParseTaskParameters() + { + ParseLoggingType(); + if (string.IsNullOrEmpty(CompressionType)) + { + LogMessage("No Compression type defined. Defaulting to 'Standard'."); + _compressionType = ParseCompressionType("Standard"); + } + else + { + _compressionType = ParseCompressionType(CompressionType); + } + ParseEncoding(); + if (ParseAdditionalTaskParameters != null) + { + ParseAdditionalTaskParameters(); + } + } + + protected void LogMessage(string message, bool isIndented = false) + { + if (LogType != Yui.Compressor.LoggingType.None) + { + Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "{0}{1}", isIndented ? " " : string.Empty, message)); + } + } + + private void ParseLoggingType() + { + if (string.IsNullOrEmpty(LoggingType)) + { + LogType = Yui.Compressor.LoggingType.Info; + LogMessage("No logging argument defined. Defaulting to 'Info'."); + return; + } + + switch (LoggingType.ToLowerInvariant()) + { + case "none": + LogType = Yui.Compressor.LoggingType.None; + break; + case "debug": + LogType = Yui.Compressor.LoggingType.Debug; + break; + case "info": + LogType = Yui.Compressor.LoggingType.Info; + break; + default: + throw new ArgumentException("Logging Type: " + LoggingType + " is invalid.", "LoggingType"); + } + } + + private void ParseEncoding() + { + if (string.IsNullOrEmpty(EncodingType)) + { + Encoding = Encoding.Default; + return; + } + + switch (EncodingType.ToLowerInvariant()) + { + case "ascii": + Encoding = Encoding.ASCII; + break; + case "bigendianunicode": + Encoding = Encoding.BigEndianUnicode; + break; + case "unicode": + Encoding = Encoding.Unicode; + break; + case "utf32": + case "utf-32": + Encoding = Encoding.UTF32; + break; + case "utf7": + case "utf-7": + Encoding = Encoding.UTF7; + break; + case "utf8": + case "utf-8": + Encoding = Encoding.UTF8; + break; + case "default": + Encoding = Encoding.Default; + break; + default: + throw new ArgumentException("Encoding: " + EncodingType + " is invalid.", "EncodingType"); + } + } + + protected virtual void LogTaskParameters() + { + LogMessage("CompressionType: " + CompressionType); + LogMessage("DeleteSourceFiles: " + DeleteSourceFiles); + LogMessage("EncodingType: " + EncodingType); + LogMessage("LoggingType: " + LoggingType); + } + + private CompressionType ParseCompressionType(string type) + { + switch (type.ToLowerInvariant()) + { + case "none": + return Yui.Compressor.CompressionType.None; + case "standard": + return Yui.Compressor.CompressionType.Standard; + default: + throw new ArgumentException("Compression Type: " + type + " is invalid.", "type"); + } + } + + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + private StringBuilder CompressFiles(out bool errorFound) + { + errorFound = false; + int totalOriginalContentLength = 0; + StringBuilder finalContent = null; + + if (SourceFiles != null) + { + LogMessage(string.Format(CultureInfo.InvariantCulture, "# {0} file{1} requested.", SourceFiles.Length, Extensions.ToPluralString(SourceFiles.Length))); + + // Now compress each file. + foreach (var file in SourceFiles) + { + var message = "=> " + file.FileName; + + // Load up the file. + try + { + var originalContent = File.ReadAllText(file.FileName, Encoding); + totalOriginalContentLength += originalContent.Length; + + if (string.IsNullOrEmpty(originalContent)) + { + errorFound = true; + LogMessage(message, true); + Log.LogError(string.Format(CultureInfo.InvariantCulture, "There is no data in the file [{0}]. Please check that this is the file you want to compress.", file.FileName)); + } + + var compressedContent = Compress(file, originalContent); + + if (!string.IsNullOrEmpty(compressedContent)) + { + if (finalContent == null) + { + finalContent = new StringBuilder(); + } + finalContent.Append(compressedContent); + } + + // Try and remove this file, if the user requests to do + try + { + if (DeleteSourceFiles) + { + if (LogType == Yui.Compressor.LoggingType.Debug) + { + Log.LogMessage("Deleting source file: " + file.FileName); + } + File.Delete(file.FileName); + } + } + catch (Exception exception) + { + errorFound = true; + Log.LogError( + string.Format(CultureInfo.InvariantCulture, + "Failed to delete the path/file [{0}]. It's possible the file is locked?", + file.FileName)); + Log.LogErrorFromException(exception, false); + } + } + catch (Exception exception) + { + errorFound = true; + if (exception is FileNotFoundException) + { + Log.LogError(string.Format(CultureInfo.InvariantCulture, "ERROR reading file or path [{0}].", file.FileName)); + } + else + { + // FFS :( Something bad happened. + Log.LogError(string.Format(CultureInfo.InvariantCulture, "Failed to read/parse data in file [{0}].", file.FileName)); + } + Log.LogErrorFromException(exception, false); + } + } + + LogMessage( + string.Format(CultureInfo.InvariantCulture, + "Finished compressing all {0} file{1}.", + SourceFiles.Length, + Extensions.ToPluralString(SourceFiles.Length)), + true); + + int finalContentLength = finalContent == null ? 0 : finalContent.ToString().Length; + + LogMessage( + string.Format(CultureInfo.InvariantCulture, + "Total original file size: {0}. After compression: {1}. Compressed down to {2}% of original size.", + totalOriginalContentLength, + finalContentLength, + 100 - (totalOriginalContentLength - (float)finalContentLength) / totalOriginalContentLength * 100)); + + LogMessage(string.Format(CultureInfo.InvariantCulture, "Compression Type: {0}.", _compressionType)); + } + + return finalContent; + } + + protected internal virtual string Compress(FileSpec file, string originalContent) + { + _compressor.CompressionType = GetCompressionTypeFor(file); + _compressor.LineBreakPosition = LineBreakPosition; + return _compressor.Compress(originalContent); + } + + private CompressionType GetCompressionTypeFor(FileSpec file) + { + var message = "=> " + file.FileName; + var actualCompressionType = _compressionType; + var overrideType = file.CompressionType; + if (!string.IsNullOrEmpty(overrideType)) + { + actualCompressionType = ParseCompressionType(overrideType); + if (actualCompressionType != _compressionType) + { + message += string.Format(" (CompressionType: {0})", actualCompressionType.ToString()); + } + } + LogMessage(message, true); + return actualCompressionType; + } + + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] + private bool SaveCompressedText(StringBuilder compressedText) + { + // Note: compressedText CAN be null or empty, so no check. + + var outputDirectory = Path.GetDirectoryName(Path.GetFullPath(OutputFile)); + if (!Directory.Exists(outputDirectory)) + { + Log.LogMessage(string.Format("Creating output directory {0}", outputDirectory)); + Directory.CreateDirectory(outputDirectory); + } + + try + { + File.WriteAllText(OutputFile, compressedText == null ? string.Empty : compressedText.ToString(), Encoding); + Log.LogMessage(string.Format(CultureInfo.InvariantCulture, "Compressed content saved to file [{0}].{1}", + OutputFile, Environment.NewLine)); + } + catch (Exception exception) + { + // Most likely cause of this exception would be that the user failed to provide the correct path/file + // or the file is read only, unable to be written, etc.. + Log.LogError(string.Format(CultureInfo.InvariantCulture, + "Failed to save the compressed text into the output file [{0}]. Please check the path/file name and make sure the file isn't magically locked, read-only, etc..", + OutputFile)); + Log.LogErrorFromException(exception, false); + + return false; + } + return true; + } + } +} \ No newline at end of file diff --git a/src/Yahoo.Yui.Compressor.MsBuild/CssCompressorTask.cs b/src/Yahoo.Yui.Compressor.MsBuild/CssCompressorTask.cs new file mode 100644 index 0000000..a77581c --- /dev/null +++ b/src/Yahoo.Yui.Compressor.MsBuild/CssCompressorTask.cs @@ -0,0 +1,24 @@ +namespace Yahoo.Yui.Compressor.MsBuild +{ + public class CssCompressorTask : CompressorTask + { + private readonly ICssCompressor _compressor; + + public bool PreserveComments { get; set; } + + public CssCompressorTask() : this(new CssCompressor()) + { + } + + public CssCompressorTask(ICssCompressor compressor) : base(compressor) + { + _compressor = compressor; + } + + public override bool Execute() + { + _compressor.RemoveComments = !PreserveComments; + return base.Execute(); + } + } +} \ No newline at end of file diff --git a/src/Yahoo.Yui.Compressor.MsBuild/FileSpec.cs b/src/Yahoo.Yui.Compressor.MsBuild/FileSpec.cs new file mode 100644 index 0000000..d98e332 --- /dev/null +++ b/src/Yahoo.Yui.Compressor.MsBuild/FileSpec.cs @@ -0,0 +1,27 @@ +namespace Yahoo.Yui.Compressor.MsBuild +{ + public class FileSpec + { + private string fileName; + + public string FileName + { + get + { + return fileName; + } + set + { + fileName = value.Trim(); + } + } + + public string CompressionType { get; set; } + + public FileSpec(string fileName, string compressionType) + { + FileName = fileName; + CompressionType = compressionType; + } + } +} \ No newline at end of file diff --git a/src/Yahoo.Yui.Compressor.MsBuild/ILog.cs b/src/Yahoo.Yui.Compressor.MsBuild/ILog.cs new file mode 100644 index 0000000..874ceee --- /dev/null +++ b/src/Yahoo.Yui.Compressor.MsBuild/ILog.cs @@ -0,0 +1,17 @@ +namespace Yahoo.Yui.Compressor.MsBuild +{ + using System; + + public interface ILog + { + void LogMessage(string message); + + void LogBoolean(string name, bool value); + + void LogError(string message, params object[] messageArgs); + + void LogErrorFromException(Exception exception); + + void LogErrorFromException(Exception exception, bool showStackTrace); + } +} diff --git a/src/Yahoo.Yui.Compressor.MsBuild/JavaScriptCompressorTask.cs b/src/Yahoo.Yui.Compressor.MsBuild/JavaScriptCompressorTask.cs new file mode 100644 index 0000000..b1fcfd5 --- /dev/null +++ b/src/Yahoo.Yui.Compressor.MsBuild/JavaScriptCompressorTask.cs @@ -0,0 +1,129 @@ +using System; +using System.Globalization; + +namespace Yahoo.Yui.Compressor.MsBuild +{ + using EcmaScript.NET; + + public class JavaScriptCompressorTask : CompressorTask + { + private readonly IJavaScriptCompressor compressor; + + private CultureInfo threadCulture; + + public bool ObfuscateJavaScript { get; set; } + + public bool PreserveAllSemicolons { get; set; } + + public bool DisableOptimizations { get; set; } + + public string ThreadCulture { get; set; } + + public bool IsEvalIgnored { get; set; } + + public JavaScriptCompressorTask() : this(new JavaScriptCompressor()) + { + } + + public JavaScriptCompressorTask(IJavaScriptCompressor compressor) : base(compressor) + { + this.compressor = compressor; + ObfuscateJavaScript = true; + TaskEngine.ParseAdditionalTaskParameters = this.ParseAdditionalTaskParameters; + TaskEngine.LogAdditionalTaskParameters = this.LogAdditionalTaskParameters; + TaskEngine.SetCompressorParameters = this.SetCompressorParameters; + } + + public override bool Execute() + { + try + { + return base.Execute(); + } + catch (EcmaScriptException ecmaScriptException) + { + Log.LogError("An error occurred in parsing the Javascript file."); + if (ecmaScriptException.LineNumber == -1) + { + Log.LogError("[ERROR] {0} ********", ecmaScriptException.Message); + } + else + { + Log.LogError( + "[ERROR] {0} ******** Line: {2}. LineOffset: {3}. LineSource: \"{4}\"", + ecmaScriptException.Message, + string.IsNullOrEmpty(ecmaScriptException.SourceName) + ? string.Empty + : "Source: {1}. " + ecmaScriptException.SourceName, + ecmaScriptException.LineNumber, + ecmaScriptException.ColumnNumber, + ecmaScriptException.LineSource); + } + return false; + } + } + + private void ParseAdditionalTaskParameters() + { + ParseThreadCulture(); + } + + private void SetCompressorParameters() + { + compressor.DisableOptimizations = DisableOptimizations; + compressor.IgnoreEval = IsEvalIgnored; + compressor.ObfuscateJavascript = ObfuscateJavaScript; + compressor.PreserveAllSemicolons = PreserveAllSemicolons; + compressor.ThreadCulture = threadCulture; + compressor.Encoding = TaskEngine.Encoding; + compressor.ErrorReporter = new CustomErrorReporter(TaskEngine.LogType); + } + + private void LogAdditionalTaskParameters() + { + TaskEngine.Log.LogBoolean("Obfuscate Javascript", ObfuscateJavaScript); + TaskEngine.Log.LogBoolean("Preserve semi colons", PreserveAllSemicolons); + TaskEngine.Log.LogBoolean("Disable optimizations", DisableOptimizations); + TaskEngine.Log.LogBoolean("Is Eval Ignored", IsEvalIgnored); + TaskEngine.Log.LogMessage( + "Line break position: " + + (LineBreakPosition <= -1 ? "None" : LineBreakPosition.ToString(CultureInfo.InvariantCulture))); + TaskEngine.Log.LogMessage("Thread Culture: " + threadCulture.DisplayName); + } + + private void ParseThreadCulture() + { + if (string.IsNullOrEmpty(ThreadCulture)) + { + threadCulture = CultureInfo.InvariantCulture; + return; + } + + try + { + switch (ThreadCulture.ToLowerInvariant()) + { + case "iv": + case "ivl": + case "invariantculture": + case "invariant culture": + case "invariant language": + case "invariant language (invariant country)": + { + threadCulture = CultureInfo.InvariantCulture; + break; + } + default: + { + threadCulture = CultureInfo.CreateSpecificCulture(ThreadCulture); + break; + } + } + } + catch + { + throw new ArgumentException("Thread Culture: " + ThreadCulture + " is invalid.", "ThreadCulture"); + } + } + } +} \ No newline at end of file diff --git a/src/Yahoo.Yui.Compressor.MsBuild/MsBuildLogAdapter.cs b/src/Yahoo.Yui.Compressor.MsBuild/MsBuildLogAdapter.cs new file mode 100644 index 0000000..703003f --- /dev/null +++ b/src/Yahoo.Yui.Compressor.MsBuild/MsBuildLogAdapter.cs @@ -0,0 +1,41 @@ +namespace Yahoo.Yui.Compressor.MsBuild +{ + using System; + + using Microsoft.Build.Utilities; + + public class MsBuildLogAdapter : ILog + { + private readonly TaskLoggingHelper logger; + + public void LogMessage(string message) + { + logger.LogMessage(message); + } + + public void LogBoolean(string name, bool value) + { + LogMessage(name + ": " + (value ? "Yes" : "No")); + } + + public void LogError(string message, params object[] messageArgs) + { + logger.LogError(message, messageArgs); + } + + public void LogErrorFromException(Exception exception) + { + this.logger.LogErrorFromException(exception); + } + + public void LogErrorFromException(Exception exception, bool showStackTrace) + { + this.logger.LogErrorFromException(exception, showStackTrace); + } + + public MsBuildLogAdapter(TaskLoggingHelper logger) + { + this.logger = logger; + } + } +} \ No newline at end of file diff --git a/src/Yahoo.Yui.Compressor.MsBuild/Yahoo.Yui.Compressor.MsBuild.csproj b/src/Yahoo.Yui.Compressor.MsBuild/Yahoo.Yui.Compressor.MsBuild.csproj new file mode 100644 index 0000000..f853c30 --- /dev/null +++ b/src/Yahoo.Yui.Compressor.MsBuild/Yahoo.Yui.Compressor.MsBuild.csproj @@ -0,0 +1,34 @@ + + + + netstandard2.0;net452 + YUICompressor.NET.MSBuild + Pure Krome and freeranger + 0.0.0 + World-Domination Technologies Pty. Ltd. + YUICompressor.NET : MSBuild Task + This is an MSBuild task to help minify and/or combine JavaScript and/or Cascading Style Sheets. + 2008 + https://github.com/YUICompressor-NET/YUICompressor.NET.MSBuild/blob/master/LICENSE.txt + https://github.com/YUICompressor-NET + http://i.imgur.com/bR4Yf.jpg + https://github.com/YUICompressor-NET/YUICompressor.NET.MSBuild + C# .NET + compression compressor minification obfuscation minify bundle bundler combine javascript js CSS cascading-style-sheets msbuild + + + + + + + + + + + + + + + + + diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Cascading Style Sheet Files/SampleStylesheet1.css b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Cascading Style Sheet Files/SampleStylesheet1.css new file mode 100644 index 0000000..243e3c2 --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Cascading Style Sheet Files/SampleStylesheet1.css @@ -0,0 +1,476 @@ +/* -------------------------------------------- + Home Styles +----------------------------------------------- */ + +#home-header, +.home-info +{ + zoom: 1; +} + +#home-header:after, +.home-info:after +{ + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} + +/* Header +----------------------------------------------- */ + +#home-header +{ + padding: 15px 30px; + background: #fff; +} + +#home-header .userinfo dt a, +#home-header .userinfo .user +{ + margin-left: 8px; + margin-right: 15px; + color: #000; +} + +#home-header .userinfo strong +{ + float: left; + margin-right: 5px; + border-right: 1px solid #D7D7D7; +} + +#home-header .userinfo li +{ + padding-top: 5px; +} + +#home-header .userinfo dd +{ + padding-left: 10px; +} + +#home-header .userinfo ul +{ + float: left; +} + +#home-header .userinfo dt, +#home-header .userinfo dd +{ + display: inline; +} + +#home-header .partner +{ + float: left; +} + +/* Search +----------------------------------------------- */ + +#home-search +{ + position: relative; + height: 310px; + background: #c00 url("/image/home_bg.png") 0 100% repeat-x; + z-index: 1000; +} + +#home-search h1, +#home-search h2 +{ + padding: 30px; + color: #fff; + text-align: center; +} + +#home-search h1 img +{ + width: 409px; + height: 93px; +} + +#home-search h2 +{ + padding-top: 98px; +} + +/* Search Box +----------------------------------------------- */ + +#home-search .search +{ + position: absolute; + top: 150px; + left: 215px; + width: 551px; +} + +#home-search .searchtext +{ + padding: 6px 0 0 9px; + width: 386px; + height: 25px; + font-size: 130%; +} + +#home-search .searchbutton +{ + padding-top: 33px; + width: 130px; + background-image: url("/image/search_button_home.png"); +} + +#home-search .searchsample, +#home-search .searchregion +{ + font-size: 90%; +} + +#home-search .searchsample +{ + top: 44px; +} + +#home-search .search .sc-h +{ + background-image: url("/image/search_header_home.png"); +} + +#home-search .search .sc-b +{ + background-image: url("/image/search_body_home.png"); +} + +#home-search .search .sc-f +{ + background-image: url("/image/search_footer_home.png"); +} + +/* Info +----------------------------------------------- */ + +#content +{ + padding-top: 10px; + background: #fff url("/image/home_info_bg.png") 0 0 repeat-x; +} + +#primary +{ + padding: 15px 0 0 15px; + width: 650px; +} + +#popular, +#reviewlist, +.news +{ + padding-right: 15px; +} + +/* Featured Reviews */ + +#reviewlist +{ + clear: both; +} + +.listc > .c-b +{ + background: url("/image/item_bg2.png") 0 100% repeat-x; +} + +.listc .hreview +{ + float: left; + width: 316px; + background: none; +} + +.hreview .reviewcol2 +{ + float: none; + width: auto; +} + +.hreview .reviewdetail .c-h +{ + margin-left: 60px; + padding-bottom: 0; + /*line-height: 120%;*/ +} +/* +.hreview .reviewdetail .c-h h4 +{ + font-size: 90%; +} +*/ +.hreview .reviewdetail .c-h .street +{ + padding-top: 2px; + padding-bottom: 4px; +} + +.hreview .reviewdetail .c-b +{ + clear: left; + padding-bottom: 4px; +} + +.hreview .reviewdetail .description, +.hreview .reviewdetail .fullreview +{ + font-size: 90%; + display: inline; +} + +.overallsummary +{ + margin-left: 60px; +} + +.hreview .reviewdetail .info, +.hreview .reviewdetail .c-f +{ + display: none; +} + +.hreview .reviewdetail .street a +{ + color: #666; +} + +/* Popular cities & neighborshoods */ + +#popular ul, +#popular dl +{ + float: left; + padding-top: 8px; + width: 158px; +} + +#popular.linkc .c-b a +{ + padding: 2px 15px; + font-size: 85%; +} + +#popular.linkc .c-b dt +{ + padding: 2px 15px; + font-size: 90%; + font-weight: bold; +} + +/* Partner Services */ + +#home-partner +{ + padding-bottom: 15px; + zoom: 1; +} + +#home-partner:after +{ + content: "."; + display: block; + height: 0; + clear: both; + visibility: hidden; +} + +#home-partner .adc +{ + float: left; + margin-right: 10px; + padding: 0; + width: 205px; + text-align: left; + background: #f1f1f1; +} + +#home-partner .adc .r-h +{ + position: absolute; + width: 205px; +} + +#home-partner .adc .r-h, +#home-partner .adc .r-h div { background-image: url("/image/container1_trans.png"); } + +#home-partner .adc .r-f, +#home-partner .adc .r-f div { background-image: url("/image/container2.gif"); } + +#home-partner .adc .c-h, +#home-partner .adc .c-b +{ + border: 1px solid #d7d7d7; + border-width: 0 1px; +} + +#home-partner .adc .c-b +{ + padding: 6px 8px; + height: 120px; +} + +#home-partner .adc b +{ + display: block; + padding-bottom: 2px; + font-size: 90%; + line-height: 1.4em; +} + +#home-partner .adc p, +#home-partner .adc li +{ + font-size: 85%; +} + +#home-partner .adc p +{ + padding-bottom: 5px; +} + +#home-partner .adc ul +{ + list-style-type: disc; +} + +#home-partner .adc li +{ + margin-left: 15px; +} + +/* News */ + +.news .c-b +{ + padding-right: 15px; +/* background: url("/image/item_bg2.png") 0 100% repeat-x;*/ +} + +.newsitem a.more +{ + white-space: nowrap; +} + +/* Buzz */ + +#main +{ + padding-top: 0; +} + +#main .c-h h3 +{ + float: none; +} + +#main .c-h +{ + text-align: center; +} + +#main .c-b +{ + padding: 0 0 0 225px; +} + +#buzz ul +{ + width: 500px; +} + +#buzz li +{ + float: left; +} + +#buzz .buzz6 +{ + padding-left: 100px; +} + +#buzz a +{ + display: block; + height: 0; + overflow: hidden; + font-size: 1px; + + padding-top: 40px; + width: 100px; + background: url("/image/home_buzz.png") 0 0 no-repeat; +} + +#buzz .buzz2 a { background-position: 0 -40px; } +#buzz .buzz3 a { background-position: 0 -80px; } +#buzz .buzz4 a { background-position: 0 -120px; } +#buzz .buzz5 a { background-position: 0 -160px; } +#buzz .buzz6 a { background-position: 0 -200px; } +#buzz .buzz7 a { background-position: 0 -240px; } +#buzz .buzz8 a { background-position: 0 -280px; } + +/* Non-US/AU Sites */ + +.home-info +{ + padding: 30px 0 25px 30px; + line-height: 130%; +} + +.home-info .linkc, +.home-info .expertc, +.home-info .infoc +{ + float: left; + position: relative; + margin-right: 13px; + width: 300px; + background-image: url("/image/container_body.png"); + background-repeat: repeat-y; +} + +.home-info .c-b +{ + height: 11.2em; +} + +.home-info .linkc .c-b a +{ + white-space: nowrap; + overflow: hidden; + width: 268px; +} + +.home-info .expertc ul +{ + position: absolute; + bottom: 8px; + width: 288px; +} + +#home-ad .c-h +{ + border-bottom: 1px solid #EBEBEB; +} + +#home-ad .c-b +{ + padding: 0; + font-size: 100%; +} + +#home-ad a +{ + display: block; +} + +/* -------------------------------------------- */ \ No newline at end of file diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Cascading Style Sheet Files/bug9527.css b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Cascading Style Sheet Files/bug9527.css new file mode 100644 index 0000000..c635426 --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Cascading Style Sheet Files/bug9527.css @@ -0,0 +1,5 @@ +html >/**/ body { + color: red; + /* comment */ + /*! preserved comment */ +} diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/CssCompressorTaskTests.cs b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/CssCompressorTaskTests.cs new file mode 100644 index 0000000..55fcce7 --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/CssCompressorTaskTests.cs @@ -0,0 +1,189 @@ +using System.IO; +using System.Text; +using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; +using NUnit.Framework; +using Yahoo.Yui.Compressor.MsBuild; +using Yahoo.Yui.Compressor.MsBuild.Tests.TestHelpers; + +namespace Yahoo.Yui.Compressor.MsBuild.Tests +{ + // ReSharper disable InconsistentNaming + public abstract class CssCompressorTaskTests + { + private CssCompressorTask target; + + public class When_PreserveComments_Is_True : CssCompressorTaskTests + { + [Test] + [Description("http://yuicompressor.codeplex.com/workitem/9527")] + public void Comments_Are_Preserved() + { + // Arrange + target = GetCompressorFor("bug9527"); + target.PreserveComments = true; + + // Act + var worked = target.Execute(); + var compressedCss = File.ReadAllText(target.OutputFile); + + // Assert + Assert.That(worked, Is.True, "Task Didn't work"); + Assert.That(compressedCss, Does.Contain("/* comment */"), compressedCss); + } + } + + public class When_PreserveComments_Is_False : CssCompressorTaskTests + { + [SetUp] + public void Setup() + { + // Arrange + target = GetCompressorFor("bug9527"); + target.PreserveComments = false; + } + + [Test] + [Description("http://yuicompressor.codeplex.com/workitem/9527")] + public void Comments_Are_Removed() + { + // Act + var worked = target.Execute(); + var compressedCss = File.ReadAllText(target.OutputFile); + + // Assert + Assert.That(worked, Is.True, "Task Didn't work"); + Assert.That(compressedCss, Does.Not.Contain("/* comment */"), compressedCss); + } + + /// + /// There is a specific IE7 hack to preserve these, so just test it works ;) + /// + [Test] + public void Empty_Comments_After_Child_Selectors_Are_Not_Removed() + { + // Act. + var worked = target.Execute(); + var compressedCss = File.ReadAllText(target.OutputFile); + + // Assert. + Assert.That(worked, Is.True, "Task Didn't work"); + Assert.That(compressedCss, Does.Contain("/**/"), compressedCss); + } + + [Test] + public void Comments_Marked_To_Be_Preserved_Are_Not_Removed() + { + // Act. + var worked = target.Execute(); + var compressedCss = File.ReadAllText(target.OutputFile); + + // Assert. + Assert.That(worked, Is.True, "Task Didn't work"); + Assert.That(compressedCss, Does.Contain("/*! preserved comment */"), compressedCss); + } + } + + [TestFixture] + public class In_Testing_The_Effects_Of_The_Compression_Type_Value : CssCompressorTaskTests + { + [SetUp] + public void Setup() + { + // Arrange + target = CreateCompressorTask(); + target.SourceFiles = new ITaskItem[] + { + new TaskItem(@"Cascading Style Sheet Files\SampleStylesheet1.css"), + new TaskItem(@"Cascading Style Sheet Files\SampleStylesheet1.css") + }; + } + + [Test] + public void When_The_CompressionType_Is_None_The_Input_Files_Are_Concatenated_Unchanged() + { + // Arrange + target.CompressionType = CompressionType.None.ToString(); + target.OutputFile = "noCompression.css"; + + // Act + target.Execute(); + + // Assert + var actual = File.ReadAllText("noCompression.css"); + var sb = new StringBuilder(); + foreach (var file in target.SourceFiles) + { + sb.Append(File.ReadAllText(file.ItemSpec)); + } + Assert.That(actual, Is.EqualTo(sb.ToString())); + } + + [Test] + public void When_The_CompressionType_Is_Not_Specified_The_Input_Files_Are_Compressed() + { + // Arrange + target.OutputFile = "compressed.css"; + + // Act + target.Execute(); + + // assert + var actual = File.ReadAllText("compressed.css"); + var sb = new StringBuilder(); + foreach (var file in target.SourceFiles) + { + sb.AppendLine(File.ReadAllText(file.ItemSpec)); + } + Assert.That(actual.Length, Is.LessThan(sb.Length)); + } + + [Test] + public void When_Compressions_Type_Is_Overridden_On_An_Individual_Item_It_Takes_Precedence_Over_The_Task_Compression_Type() + { + // Arrange + target.CompressionType = CompressionType.None.ToString(); + target.SourceFiles[0].SetMetadata("CompressionType", CompressionType.Standard.ToString()); + target.OutputFile = "semicompressed.css"; + + // Act + target.Execute(); + + // Assert + var actual = File.ReadAllText("semicompressed.css"); + var sb = new StringBuilder(); + foreach (var file in target.SourceFiles) + { + sb.Append(File.ReadAllText(file.ItemSpec)); + } + Assert.That(actual.Length, Is.LessThan(sb.Length)); + } + } + + private static CssCompressorTask GetCompressorFor(string fileName) + { + var compressorTask = CreateCompressorTask(); + if (!string.IsNullOrEmpty(fileName)) + { + compressorTask.SourceFiles = new ITaskItem[] + { new TaskItem(@"Cascading Style Sheet Files\" + fileName + ".css") }; + compressorTask.OutputFile = fileName + "min.css"; + } + return compressorTask; + } + + private static CssCompressorTask CreateCompressorTask() + { + return new CssCompressorTask + { + BuildEngine = new BuildEngineStub(), + DeleteSourceFiles = false, + CompressionType = "Standard", + EncodingType = "Default", + LoggingType = "None", + PreserveComments = false + }; + } + } + // ReSharper restore InconsistentNaming +} \ No newline at end of file diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/CustomDictionary.xml b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/CustomDictionary.xml new file mode 100644 index 0000000..c56e541 --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/CustomDictionary.xml @@ -0,0 +1,8 @@ + + + + + Yui + + + \ No newline at end of file diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/JavaScriptCompressorTaskTests.cs b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/JavaScriptCompressorTaskTests.cs new file mode 100644 index 0000000..c4cd22a --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/JavaScriptCompressorTaskTests.cs @@ -0,0 +1,235 @@ +using Microsoft.Build.Framework; +using Microsoft.Build.Utilities; +using NUnit.Framework; +using System.IO; +using System.Text; +using Yahoo.Yui.Compressor.MsBuild.Tests.TestHelpers; + +namespace Yahoo.Yui.Compressor.MsBuild.Tests +{ + // ReSharper disable InconsistentNaming + [TestFixture] + public class JavaScriptCompressorTaskTests + { + [Test] + public void When_The_CompressionType_Is_None_The_Input_Files_Are_Concatenated_Unchanged() + { + // Arange + var compressor = CreateCompressorTask(); + compressor.CompressionType = "None"; + compressor.SourceFiles = new ITaskItem[] + { + new TaskItem(@"Javascript Files\SampleJavaScript1.js"), + new TaskItem(@"Javascript Files\SampleJavaScript2.js") + }; + compressor.OutputFile = "noCompression.js"; + + // Act + compressor.Execute(); + + // Assert + var actual = File.ReadAllText("noCompression.js"); + var sb = new StringBuilder(); + foreach (var file in compressor.SourceFiles) + { + sb.Append(File.ReadAllText(file.ItemSpec)); + } + Assert.That(actual, Is.EqualTo(sb.ToString())); + } + + [Test] + public void When_The_JavaScriptCompressionType_Is_Not_Specified_The_Input_Files_Are_Compressed() + { + // Arrange + var compressor = CreateCompressorTask(); + compressor.SourceFiles = new ITaskItem[] + { + new TaskItem(@"Javascript Files\SampleJavaScript1.js"), + new TaskItem(@"Javascript Files\SampleJavaScript2.js") + }; + compressor.OutputFile = "compressed.js"; + + // Act + compressor.Execute(); + + // Assert + var actual = File.ReadAllText("compressed.js"); + var sb = new StringBuilder(); + foreach (var file in compressor.SourceFiles) + { + sb.Append(File.ReadAllText(file.ItemSpec)); + } + Assert.That(actual.Length, Is.LessThan(sb.Length)); + } + + [Test] + [Description("http://yuicompressor.codeplex.com/workitem/10507")] + public void Accents_Should_Be_Retained_When_Encoded_With_UTF8() + { + // Arrange + var compressor = CreateCompressorTask(); + compressor.EncodingType = "utf-8"; + + compressor.SourceFiles = new ITaskItem[] + { + new TaskItem(@"Javascript Files\Accents.js") + }; + compressor.OutputFile = "Accents.Actual.js"; + var expected = File.ReadAllText(@"Javascript Files\Accents.Expected.min.js", Encoding.GetEncoding(compressor.EncodingType)); + + // Act + compressor.Execute(); + + // Assert + var actual = File.ReadAllText(compressor.OutputFile, Encoding.GetEncoding(compressor.EncodingType)); + Assert.That(actual, Is.EqualTo(expected)); + } + + [Test] + public void When_The_Compressions_Type_Is_Overridden_On_An_Individual_Item_It_Takes_Precedence_Over_The_Task_Compression_Type() + { + // Arrange + var compressor = CreateCompressorTask(); + compressor.CompressionType = CompressionType.None.ToString(); + + compressor.SourceFiles = new ITaskItem[] + { + new TaskItem(@"Javascript Files\SampleJavaScript1.js"), + new TaskItem(@"Javascript Files\SampleJavaScript2.js") + }; + compressor.SourceFiles[0].SetMetadata("CompressionType", CompressionType.Standard.ToString()); + compressor.OutputFile = "semicompressed.js"; + + // Act + compressor.Execute(); + + // Assert + var actual = File.ReadAllText("semicompressed.js"); + var sb = new StringBuilder(); + foreach (var file in compressor.SourceFiles) + { + sb.Append(File.ReadAllText(file.ItemSpec)); + } + Assert.That(actual.Length, Is.LessThan(sb.Length)); + } + + [Test] + public void An_Error_Is_Logged_If_The_CompressionType_Is_Not_Recognised() + { + // Arrange + var compressor = CreateCompressorTask(); + compressor.CompressionType = "invalid"; + + // Act + var result = compressor.Execute(); + + // Assert + Assert.IsFalse(result); + Assert.That(BuildEngine.ContainsError(compressor.BuildEngine, "Compression Type: invalid is invalid")); + } + + [Test] + public void An_Invalid_File_Or_Path_Results_In_An_Could_Not_File_File_Exception_Being_Logged() + { + // Arange + var compressor = GetJavascriptCompressorFor(@"DoesNotExist"); + + // Act + compressor.Execute(); + + // Assert + Assert.That(BuildEngine.ContainsError(compressor.BuildEngine, ("ERROR reading file or path"))); + } + + [Test] + [Description("http://yuicompressor.codeplex.com/workitem/9719")] + public void A_Reserved_Word_As_A_Property_In_The_Source_Should_Throw_An_Error_With_The_Correct_Error_Exposed() + { + var compressor = GetJavascriptCompressorFor("Issue9719"); + + compressor.Execute(); + Assert.That(BuildEngine.ContainsError(compressor.BuildEngine, ("invalid property id"))); + } + + [Test] + public void An_Error_Is_Logged_If_The_Output_File_Is_The_Same_As_An_Input_File() + { + // Arange + var compressor = CreateCompressorTask(); + compressor.SourceFiles = new ITaskItem[] { new TaskItem("SomeDir\\Different.js"), new TaskItem("SomeDir\\Same.js") }; + compressor.OutputFile = "SomeDir\\Same.js"; + + // Act + compressor.Execute(); + + // Assert + Assert.That(BuildEngine.ContainsError(compressor.BuildEngine, ("Output file cannot be the same as source file(s)."))); + } + + [Test] + public void An_Error_Is_Not_Logged_If_The_Output_File_Has_The_Same_Name_But_A_Different_Location_To_An_Input_File() + { + // Arange + var compressor = CreateCompressorTask(); + compressor.SourceFiles = new ITaskItem[] { new TaskItem("SomeDir\\Different.js"), new TaskItem("SomeOtherDir\\Same.js") }; + compressor.OutputFile = "SomeDir\\Same.js"; + + // Act + compressor.Execute(); + + // Assert + Assert.That(BuildEngine.DoesNotContainError(compressor.BuildEngine, ("Output file cannot be the same as source file(s)."))); + } + + [Test] + public void If_OutputFile_Directory_Does_Not_Exist_It_Is_Created() + { + try + { + // Arange + var compressor = CreateCompressorTask(); + compressor.SourceFiles = new ITaskItem[] { new TaskItem("Javascript Files\\SampleJavaScript1.js") }; + compressor.OutputFile = "NewOutputDir\\Output.js"; + + // Act + compressor.Execute(); + + // Assert + Assert.That(Directory.Exists(Path.GetFullPath("NewOutputDir"))); + } + finally + { + if (Directory.Exists(Path.GetFullPath("NewOutputDir"))) + { + Directory.Delete(Path.GetFullPath("NewOutputDir"), true); + } + } + } + + private static CompressorTask GetJavascriptCompressorFor(string fileName) + { + var compressorTask = CreateCompressorTask(); + if (!string.IsNullOrEmpty(fileName)) + { + compressorTask.SourceFiles = new ITaskItem[] { new TaskItem(@"Javascript Files\" + fileName + ".js") }; + compressorTask.OutputFile = fileName + "min.js"; + } + return compressorTask; + } + + private static JavaScriptCompressorTask CreateCompressorTask() + { + return new JavaScriptCompressorTask + { + BuildEngine = new BuildEngineStub(), + DeleteSourceFiles = false, + CompressionType = "Standard", + DisableOptimizations = false, + EncodingType = "Default", + LineBreakPosition = -1, + LoggingType = "None", + }; + } + } + // ReSharper restore InconsistentNaming +} \ No newline at end of file diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Accents.Expected.min.js b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Accents.Expected.min.js new file mode 100644 index 0000000..85673be --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Accents.Expected.min.js @@ -0,0 +1 @@ +Strings={IncorrectLogin:"Felaktigt användarnamn eller lösenord. Försök igen!",ExpandAll:"Visa allt",CollapseAll:"Minimera",ViewInNormalMode:"Tryck här för normalt läge"}; \ No newline at end of file diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Accents.js b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Accents.js new file mode 100644 index 0000000..13e980e --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Accents.js @@ -0,0 +1,6 @@ +Strings = { + IncorrectLogin: 'Felaktigt användarnamn eller lösenord. Försök igen!', + ExpandAll: 'Visa allt', + CollapseAll: 'Minimera', + ViewInNormalMode: 'Tryck här för normalt läge' +}; \ No newline at end of file diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Issue9719.js b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Issue9719.js new file mode 100644 index 0000000..926322b --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/Issue9719.js @@ -0,0 +1,8 @@ +this.element + .attr('style', '') + .css({ + top: 0, + left: 0, + position: 'relative', + float: 'left' + }); \ No newline at end of file diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/SampleJavaScript1.js b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/SampleJavaScript1.js new file mode 100644 index 0000000..20e9a72 --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/SampleJavaScript1.js @@ -0,0 +1,246 @@ +var __spinner = ''; + +/* Helpers +----------------------------------------------- */ + +function stopEvent(e) +{ + if(!e) var e = window.event; + + e.cancelBubble = true; + e.returnValue = false; + + if (e.stopPropagation) + { + e.stopPropagation(); + e.preventDefault(); + } + + return false; +} + +function formatMediaHTML(result) +{ + return String.format('{2} for {3}', + result.Url, + result.ImageUrl, + result.Title, + result.FormattedAddress); +} + +Array.getItemById = function Array$getItemById(array, id) +{ + for (var i = 0; i < array.length; i++) + { + if (array[i].Id == id) + { + return array[i]; + } + } + return null; +} + +Array.prototype.exists = function(x) +{ + for (var i = 0; i < this.length; i++) + { + if (this[i] == x) return true; + } + return false; +} + +Array.merge = function Array$merge(array) +{ + var result = array; + for (var i = 1; i < arguments.length; i++) + { + result = result.concat(arguments[i]); + } + return result; +} + +function CheckWordCount(textbox, minWords) +{ + var wordList = textbox.value.replace(/\s/g, ' ').split(' '); + var wordCount = 0; + + for (var x = 0; x < wordList.length; x++) + { + if (wordList[x].length > 0) + { + wordCount++; + } + } + return (wordCount >= minWords); +} + +function getElementsByClassName(searchClass, tag, node) +{ + var classElements = new Array(); + if (node == null) + node = document; + if (tag == null) + tag = '*'; + var els = node.getElementsByTagName(tag); + var elsLen = els.length; + var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"); + for (i = 0, j = 0; i < elsLen; i++) { + if ( pattern.test(els[i].className) ) { + classElements[j] = els[i]; + j++; + } + } + return classElements; +} + +if (typeof HTMLElement != 'undefined' && typeof HTMLElement.prototype.__defineGetter__ != 'undefined') +{ + HTMLElement.prototype.__defineGetter__('innerText', function () + { + return(this.textContent); + }); + HTMLElement.prototype.__defineSetter__('innerText', function (text) + { + this.textContent = text; + }); +} + +/* Async TinyMCE +----------------------------------------------- */ + +function tinyMCEAsync_Save() +{ + tinyMCE.triggerSave(true, true); +} + +function tinyMCEAsync_Add(sender, args) +{ + var controls = tinyMCEAsync_GetControls(args.get_panelsUpdated()); + for (var x = 0; x < controls.length; x++) + { + var instance = tinyMCE.getInstanceById(controls[x].name); + if (!instance) + { + tinyMCE.execCommand('mceAddControl', true, controls[x].name); + } + } +} + +function tinyMCEAsync_Remove(sender, args) +{ + var controls = tinyMCEAsync_GetControls(args.get_panelsUpdating()); + for (var x = 0; x < controls.length; x++) + { + tinyMCE.execCommand('mceRemoveControl', true, controls[x].name); + } +} + +// Find each tinyMCE control in the UpdatePanel. +function tinyMCEAsync_GetControls(panels) +{ + var controls = []; + for (var i = 0; i < panels.length; i++) + { + var panelControls = getElementsByClassName('editor', null, panels[i]); + for (var x = 0; x < panelControls.length; x++) + { + controls.push(panelControls[x]); + } + } + return controls; +} + +/* RevisionHistory +----------------------------------------------- */ + +function HistoryCheckboxSelected(checkbox, historyID) +{ + if(!checkbox.checked) + { + return; + } + + var selected = []; + + // Get all checkboxes in RevisionHistory control. + var elements = $get(historyID).getElementsByTagName('input'); + for (var i = 0; i < elements.length; i++) + { + if (elements[i].type.toLowerCase() == 'checkbox' && elements[i].checked) + { + selected.push(elements[i]); + } + } + + if(selected.length > 2) + { + // Too many selected, reset. + for (var i = 0; i < selected.length; i++) + { + if(selected[i] != checkbox) + { + selected[i].checked = false; + } + } + } +} + +/* Behaviours +----------------------------------------------- */ + +Sys.Application.add_init(function() +{ + Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(ReloadUserTooltip); + LoadUserTooltip(null); +}); + +function ReloadUserTooltip(sender, args) +{ + var panels = args.get_panelsUpdated(); + + for (var i = 0; i < panels.length; i++) + { + LoadUserTooltip(panels[i]); + } +} + +// Create user overview tooltips +function LoadUserTooltip(node) +{ + var users = getElementsByClassName('ut', 'a', node); + for (var i = 0; i < users.length; i++) + { + $create(Appian.Tooltip, {'Key': 'useroverview', 'Arg': users[i].title}, null, null, users[i]); + } +} + +// Toggle show and hide calender. +function toggleContainer(target, sender) +{ + if(target) + { + var theContainer = document.getElementById(target); + if(theContainer) + { + if(theContainer.style.display == "block") + { + theContainer.style.display = "none"; + sender.innerText = "show calendar"; + } + else + { + theContainer.style.display = "block"; + sender.innerText = "hide calendar"; + } + } + } +} + +/** + * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/ + * + * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License: + * http://www.opensource.org/licenses/mit-license.php + * + */ +if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="";_19+="";var _1d=this.getParams();for(var key in _1d){_19+="";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="";}_19+="";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.majorfv.major){return true;}if(this.minorfv.minor){return true;}if(this.rev=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject; \ No newline at end of file diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/SampleJavaScript2.js b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/SampleJavaScript2.js new file mode 100644 index 0000000..5918f7a --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Javascript Files/SampleJavaScript2.js @@ -0,0 +1,6336 @@ +//----------------------------------------------------------------------- +// Copyright (C) Microsoft Corporation. All rights reserved. +//----------------------------------------------------------------------- +// MicrosoftAjax.js +// Microsoft AJAX Framework. + +Function.__typeName = 'Function'; +Function.__class = true; +Function.createCallback = function Function$createCallback(method, context) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "method", type: Function}, + {name: "context", mayBeNull: true} + ]); + if (e) throw e; + return function() { + var l = arguments.length; + if (l > 0) { + var args = []; + for (var i = 0; i < l; i++) { + args[i] = arguments[i]; + } + args[l] = context; + return method.apply(this, args); + } + return method.call(this, context); + } +} +Function.createDelegate = function Function$createDelegate(instance, method) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance", mayBeNull: true}, + {name: "method", type: Function} + ]); + if (e) throw e; + return function() { + return method.apply(instance, arguments); + } +} +Function.emptyFunction = Function.emptyMethod = function Function$emptyMethod() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} +Function._validateParams = function Function$_validateParams(params, expectedParams) { + var e; + e = Function._validateParameterCount(params, expectedParams); + if (e) { + e.popStackFrame(); + return e; + } + for (var i=0; i < params.length; i++) { + var expectedParam = expectedParams[Math.min(i, expectedParams.length - 1)]; + var paramName = expectedParam.name; + if (expectedParam.parameterArray) { + paramName += "[" + (i - expectedParams.length + 1) + "]"; + } + e = Function._validateParameter(params[i], expectedParam, paramName); + if (e) { + e.popStackFrame(); + return e; + } + } + return null; +} +Function._validateParameterCount = function Function$_validateParameterCount(params, expectedParams) { + var maxParams = expectedParams.length; + var minParams = 0; + for (var i=0; i < expectedParams.length; i++) { + if (expectedParams[i].parameterArray) { + maxParams = Number.MAX_VALUE; + } + else if (!expectedParams[i].optional) { + minParams++; + } + } + if (params.length < minParams || params.length > maxParams) { + var e = Error.parameterCount(); + e.popStackFrame(); + return e; + } + return null; +} +Function._validateParameter = function Function$_validateParameter(param, expectedParam, paramName) { + var e; + var expectedType = expectedParam.type; + var expectedInteger = !!expectedParam.integer; + var expectedDomElement = !!expectedParam.domElement; + var mayBeNull = !!expectedParam.mayBeNull; + e = Function._validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName); + if (e) { + e.popStackFrame(); + return e; + } + var expectedElementType = expectedParam.elementType; + var elementMayBeNull = !!expectedParam.elementMayBeNull; + if (expectedType === Array && typeof(param) !== "undefined" && param !== null && + (expectedElementType || !elementMayBeNull)) { + var expectedElementInteger = !!expectedParam.elementInteger; + var expectedElementDomElement = !!expectedParam.elementDomElement; + for (var i=0; i < param.length; i++) { + var elem = param[i]; + e = Function._validateParameterType(elem, expectedElementType, + expectedElementInteger, expectedElementDomElement, elementMayBeNull, + paramName + "[" + i + "]"); + if (e) { + e.popStackFrame(); + return e; + } + } + } + return null; +} +Function._validateParameterType = function Function$_validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName) { + var e; + if (typeof(param) === "undefined") { + if (mayBeNull) { + return null; + } + else { + e = Error.argumentUndefined(paramName); + e.popStackFrame(); + return e; + } + } + if (param === null) { + if (mayBeNull) { + return null; + } + else { + e = Error.argumentNull(paramName); + e.popStackFrame(); + return e; + } + } + if (expectedType && expectedType.__enum) { + if (typeof(param) !== 'number') { + e = Error.argumentType(paramName, Object.getType(param), expectedType); + e.popStackFrame(); + return e; + } + if ((param % 1) === 0) { + var values = expectedType.prototype; + if (!expectedType.__flags || (param === 0)) { + for (var i in values) { + if (values[i] === param) return null; + } + } + else { + var v = param; + for (var i in values) { + var vali = values[i]; + if (vali === 0) continue; + if ((vali & param) === vali) { + v -= vali; + } + if (v === 0) return null; + } + } + } + e = Error.argumentOutOfRange(paramName, param, String.format(Sys.Res.enumInvalidValue, param, expectedType.getName())); + e.popStackFrame(); + return e; + } + if (expectedDomElement) { + var val; + if (typeof(param.nodeType) !== 'number') { + var doc = param.ownerDocument || param.document || param; + if (doc != param) { + var w = doc.defaultView || doc.parentWindow; + val = (w != param) && !(w.document && param.document && (w.document === param.document)); + } + else { + val = (typeof(doc.body) === 'undefined'); + } + } + else { + val = (param.nodeType === 3); + } + if (val) { + e = Error.argument(paramName, Sys.Res.argumentDomElement); + e.popStackFrame(); + return e; + } + } + if (expectedType && !expectedType.isInstanceOfType(param)) { + e = Error.argumentType(paramName, Object.getType(param), expectedType); + e.popStackFrame(); + return e; + } + if (expectedType === Number && expectedInteger) { + if ((param % 1) !== 0) { + e = Error.argumentOutOfRange(paramName, param, Sys.Res.argumentInteger); + e.popStackFrame(); + return e; + } + } + return null; +} + +Error.__typeName = 'Error'; +Error.__class = true; +Error.create = function Error$create(message, errorInfo) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true}, + {name: "errorInfo", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var e = new Error(message); + e.message = message; + if (errorInfo) { + for (var v in errorInfo) { + e[v] = errorInfo[v]; + } + } + e.popStackFrame(); + return e; +} +Error.argument = function Error$argument(paramName, message) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentException: " + (message ? message : Sys.Res.argument); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { name: "Sys.ArgumentException", paramName: paramName }); + e.popStackFrame(); + return e; +} +Error.argumentNull = function Error$argumentNull(paramName, message) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentNullException: " + (message ? message : Sys.Res.argumentNull); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { name: "Sys.ArgumentNullException", paramName: paramName }); + e.popStackFrame(); + return e; +} +Error.argumentOutOfRange = function Error$argumentOutOfRange(paramName, actualValue, message) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "actualValue", mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentOutOfRangeException: " + (message ? message : Sys.Res.argumentOutOfRange); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + if (typeof(actualValue) !== "undefined" && actualValue !== null) { + displayMessage += "\n" + String.format(Sys.Res.actualValue, actualValue); + } + var e = Error.create(displayMessage, { + name: "Sys.ArgumentOutOfRangeException", + paramName: paramName, + actualValue: actualValue + }); + e.popStackFrame(); + return e; +} +Error.argumentType = function Error$argumentType(paramName, actualType, expectedType, message) { + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "actualType", type: Type, mayBeNull: true, optional: true}, + {name: "expectedType", type: Type, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentTypeException: "; + if (message) { + displayMessage += message; + } + else if (actualType && expectedType) { + displayMessage += + String.format(Sys.Res.argumentTypeWithTypes, actualType.getName(), expectedType.getName()); + } + else { + displayMessage += Sys.Res.argumentType; + } + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { + name: "Sys.ArgumentTypeException", + paramName: paramName, + actualType: actualType, + expectedType: expectedType + }); + e.popStackFrame(); + return e; +} +Error.argumentUndefined = function Error$argumentUndefined(paramName, message) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "paramName", type: String, mayBeNull: true, optional: true}, + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ArgumentUndefinedException: " + (message ? message : Sys.Res.argumentUndefined); + if (paramName) { + displayMessage += "\n" + String.format(Sys.Res.paramName, paramName); + } + var e = Error.create(displayMessage, { name: "Sys.ArgumentUndefinedException", paramName: paramName }); + e.popStackFrame(); + return e; +} +Error.format = function Error$format(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.FormatException: " + (message ? message : Sys.Res.format); + var e = Error.create(displayMessage, {name: 'Sys.FormatException'}); + e.popStackFrame(); + return e; +} +Error.invalidOperation = function Error$invalidOperation(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.InvalidOperationException: " + (message ? message : Sys.Res.invalidOperation); + var e = Error.create(displayMessage, {name: 'Sys.InvalidOperationException'}); + e.popStackFrame(); + return e; +} +Error.notImplemented = function Error$notImplemented(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.NotImplementedException: " + (message ? message : Sys.Res.notImplemented); + var e = Error.create(displayMessage, {name: 'Sys.NotImplementedException'}); + e.popStackFrame(); + return e; +} +Error.parameterCount = function Error$parameterCount(message) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var displayMessage = "Sys.ParameterCountException: " + (message ? message : Sys.Res.parameterCount); + var e = Error.create(displayMessage, {name: 'Sys.ParameterCountException'}); + e.popStackFrame(); + return e; +} +Error.prototype.popStackFrame = function Error$popStackFrame() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (typeof(this.stack) === "undefined" || this.stack === null || + typeof(this.fileName) === "undefined" || this.fileName === null || + typeof(this.lineNumber) === "undefined" || this.lineNumber === null) { + return; + } + var stackFrames = this.stack.split("\n"); + var currentFrame = stackFrames[0]; + var pattern = this.fileName + ":" + this.lineNumber; + while(typeof(currentFrame) !== "undefined" && + currentFrame !== null && + currentFrame.indexOf(pattern) === -1) { + stackFrames.shift(); + currentFrame = stackFrames[0]; + } + var nextFrame = stackFrames[1]; + if (typeof(nextFrame) === "undefined" || nextFrame === null) { + return; + } + var nextFrameParts = nextFrame.match(/@(.*):(\d+)$/); + if (typeof(nextFrameParts) === "undefined" || nextFrameParts === null) { + return; + } + this.fileName = nextFrameParts[1]; + this.lineNumber = parseInt(nextFrameParts[2]); + stackFrames.shift(); + this.stack = stackFrames.join("\n"); +} + +Object.__typeName = 'Object'; +Object.__class = true; +Object.getType = function Object$getType(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"} + ]); + if (e) throw e; + var ctor = instance.constructor; + if (!ctor || (typeof(ctor) !== "function") || !ctor.__typeName || (ctor.__typeName === 'Object')) { + return Object; + } + return ctor; +} +Object.getTypeName = function Object$getTypeName(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"} + ]); + if (e) throw e; + return Object.getType(instance).getName(); +} + +String.__typeName = 'String'; +String.__class = true; +String.prototype.endsWith = function String$endsWith(suffix) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "suffix", type: String} + ]); + if (e) throw e; + return (this.substr(this.length - suffix.length) === suffix); +} +String.prototype.startsWith = function String$startsWith(prefix) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "prefix", type: String} + ]); + if (e) throw e; + return (this.substr(0, prefix.length) === prefix); +} +String.prototype.trim = function String$trim() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this.replace(/^\s+|\s+$/g, ''); +} +String.prototype.trimEnd = function String$trimEnd() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this.replace(/\s+$/, ''); +} +String.prototype.trimStart = function String$trimStart() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this.replace(/^\s+/, ''); +} +String.format = function String$format(format, args) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String}, + {name: "args", mayBeNull: true, parameterArray: true} + ]); + if (e) throw e; + return String._toFormattedString(false, arguments); +} +String.localeFormat = function String$localeFormat(format, args) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String}, + {name: "args", mayBeNull: true, parameterArray: true} + ]); + if (e) throw e; + return String._toFormattedString(true, arguments); +} +String._toFormattedString = function String$_toFormattedString(useLocale, args) { + var result = ''; + var format = args[0]; + for (var i=0;;) { + var open = format.indexOf('{', i); + var close = format.indexOf('}', i); + if ((open < 0) && (close < 0)) { + result += format.slice(i); + break; + } + if ((close > 0) && ((close < open) || (open < 0))) { + if (format.charAt(close + 1) !== '}') { + throw Error.argument('format', Sys.Res.stringFormatBraceMismatch); + } + result += format.slice(i, close + 1); + i = close + 2; + continue; + } + result += format.slice(i, open); + i = open + 1; + if (format.charAt(i) === '{') { + result += '{'; + i++; + continue; + } + if (close < 0) throw Error.argument('format', Sys.Res.stringFormatBraceMismatch); + var brace = format.substring(i, close); + var colonIndex = brace.indexOf(':'); + var argNumber = parseInt((colonIndex < 0)? brace : brace.substring(0, colonIndex), 10) + 1; + if (isNaN(argNumber)) throw Error.argument('format', Sys.Res.stringFormatInvalid); + var argFormat = (colonIndex < 0)? '' : brace.substring(colonIndex + 1); + var arg = args[argNumber]; + if (typeof(arg) === "undefined" || arg === null) { + arg = ''; + } + if (arg.toFormattedString) { + result += arg.toFormattedString(argFormat); + } + else if (useLocale && arg.localeFormat) { + result += arg.localeFormat(argFormat); + } + else if (arg.format) { + result += arg.format(argFormat); + } + else + result += arg.toString(); + i = close + 1; + } + return result; +} + +Boolean.__typeName = 'Boolean'; +Boolean.__class = true; +Boolean.parse = function Boolean$parse(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + var v = value.trim().toLowerCase(); + if (v === 'false') return false; + if (v === 'true') return true; + throw Error.argumentOutOfRange('value', value, Sys.Res.boolTrueOrFalse); +} + +Date.__typeName = 'Date'; +Date.__class = true; +Date._appendPreOrPostMatch = function Date$_appendPreOrPostMatch(preMatch, strBuilder) { + var quoteCount = 0; + var escaped = false; + for (var i = 0, il = preMatch.length; i < il; i++) { + var c = preMatch.charAt(i); + switch (c) { + case '\'': + if (escaped) strBuilder.append("'"); + else quoteCount++; + escaped = false; + break; + case '\\': + if (escaped) strBuilder.append("\\"); + escaped = !escaped; + break; + default: + strBuilder.append(c); + escaped = false; + break; + } + } + return quoteCount; +} +Date._expandFormat = function Date$_expandFormat(dtf, format) { + if (!format) { + format = "F"; + } + if (format.length === 1) { + switch (format) { + case "d": + return dtf.ShortDatePattern; + case "D": + return dtf.LongDatePattern; + case "t": + return dtf.ShortTimePattern; + case "T": + return dtf.LongTimePattern; + case "F": + return dtf.FullDateTimePattern; + case "M": case "m": + return dtf.MonthDayPattern; + case "s": + return dtf.SortableDateTimePattern; + case "Y": case "y": + return dtf.YearMonthPattern; + default: + throw Error.format(Sys.Res.formatInvalidString); + } + } + return format; +} +Date._expandYear = function Date$_expandYear(dtf, year) { + if (year < 100) { + var curr = new Date().getFullYear(); + year += curr - (curr % 100); + if (year > dtf.Calendar.TwoDigitYearMax) { + return year - 100; + } + } + return year; +} +Date._getParseRegExp = function Date$_getParseRegExp(dtf, format) { + if (!dtf._parseRegExp) { + dtf._parseRegExp = {}; + } + else if (dtf._parseRegExp[format]) { + return dtf._parseRegExp[format]; + } + var expFormat = Date._expandFormat(dtf, format); + expFormat = expFormat.replace(/([\^\$\.\*\+\?\|\[\]\(\)\{\}])/g, "\\\\$1"); + var regexp = new Sys.StringBuilder("^"); + var groups = []; + var index = 0; + var quoteCount = 0; + var tokenRegExp = Date._getTokenRegExp(); + var match; + while ((match = tokenRegExp.exec(expFormat)) !== null) { + var preMatch = expFormat.slice(index, match.index); + index = tokenRegExp.lastIndex; + quoteCount += Date._appendPreOrPostMatch(preMatch, regexp); + if ((quoteCount%2) === 1) { + regexp.append(match[0]); + continue; + } + switch (match[0]) { + case 'dddd': case 'ddd': + case 'MMMM': case 'MMM': + regexp.append("(\\D+)"); + break; + case 'tt': case 't': + regexp.append("(\\D*)"); + break; + case 'yyyy': + regexp.append("(\\d{4})"); + break; + case 'fff': + regexp.append("(\\d{3})"); + break; + case 'ff': + regexp.append("(\\d{2})"); + break; + case 'f': + regexp.append("(\\d)"); + break; + case 'dd': case 'd': + case 'MM': case 'M': + case 'yy': case 'y': + case 'HH': case 'H': + case 'hh': case 'h': + case 'mm': case 'm': + case 'ss': case 's': + regexp.append("(\\d\\d?)"); + break; + case 'zzz': + regexp.append("([+-]?\\d\\d?:\\d{2})"); + break; + case 'zz': case 'z': + regexp.append("([+-]?\\d\\d?)"); + break; + } + Array.add(groups, match[0]); + } + Date._appendPreOrPostMatch(expFormat.slice(index), regexp); + regexp.append("$"); + var regexpStr = regexp.toString().replace(/\s+/g, "\\s+"); + var parseRegExp = {'regExp': regexpStr, 'groups': groups}; + dtf._parseRegExp[format] = parseRegExp; + return parseRegExp; +} +Date._getTokenRegExp = function Date$_getTokenRegExp() { + return /dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|y|hh|h|HH|H|mm|m|ss|s|tt|t|fff|ff|f|zzz|zz|z/g; +} +Date.parseLocale = function Date$parseLocale(value, formats) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String}, + {name: "formats", mayBeNull: true, optional: true, parameterArray: true} + ]); + if (e) throw e; + return Date._parse(value, Sys.CultureInfo.CurrentCulture, arguments); +} +Date.parseInvariant = function Date$parseInvariant(value, formats) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String}, + {name: "formats", mayBeNull: true, optional: true, parameterArray: true} + ]); + if (e) throw e; + return Date._parse(value, Sys.CultureInfo.InvariantCulture, arguments); +} +Date._parse = function Date$_parse(value, cultureInfo, args) { + var custom = false; + for (var i = 1, il = args.length; i < il; i++) { + var format = args[i]; + if (format) { + custom = true; + var date = Date._parseExact(value, format, cultureInfo); + if (date) return date; + } + } + if (! custom) { + var formats = cultureInfo._getDateTimeFormats(); + for (var i = 0, il = formats.length; i < il; i++) { + var date = Date._parseExact(value, formats[i], cultureInfo); + if (date) return date; + } + } + return null; +} +Date._parseExact = function Date$_parseExact(value, format, cultureInfo) { + value = value.trim(); + var dtf = cultureInfo.dateTimeFormat; + var parseInfo = Date._getParseRegExp(dtf, format); + var match = new RegExp(parseInfo.regExp).exec(value); + if (match === null) return null; + + var groups = parseInfo.groups; + var year = null, month = null, date = null, weekDay = null; + var hour = 0, min = 0, sec = 0, msec = 0, tzMinOffset = null; + var pmHour = false; + for (var j = 0, jl = groups.length; j < jl; j++) { + var matchGroup = match[j+1]; + if (matchGroup) { + switch (groups[j]) { + case 'dd': case 'd': + date = parseInt(matchGroup, 10); + if ((date < 1) || (date > 31)) return null; + break; + case 'MMMM': + month = cultureInfo._getMonthIndex(matchGroup); + if ((month < 0) || (month > 11)) return null; + break; + case 'MMM': + month = cultureInfo._getAbbrMonthIndex(matchGroup); + if ((month < 0) || (month > 11)) return null; + break; + case 'M': case 'MM': + var month = parseInt(matchGroup, 10) - 1; + if ((month < 0) || (month > 11)) return null; + break; + case 'y': case 'yy': + year = Date._expandYear(dtf,parseInt(matchGroup, 10)); + if ((year < 0) || (year > 9999)) return null; + break; + case 'yyyy': + year = parseInt(matchGroup, 10); + if ((year < 0) || (year > 9999)) return null; + break; + case 'h': case 'hh': + hour = parseInt(matchGroup, 10); + if (hour === 12) hour = 0; + if ((hour < 0) || (hour > 11)) return null; + break; + case 'H': case 'HH': + hour = parseInt(matchGroup, 10); + if ((hour < 0) || (hour > 23)) return null; + break; + case 'm': case 'mm': + min = parseInt(matchGroup, 10); + if ((min < 0) || (min > 59)) return null; + break; + case 's': case 'ss': + sec = parseInt(matchGroup, 10); + if ((sec < 0) || (sec > 59)) return null; + break; + case 'tt': case 't': + var upperToken = matchGroup.toUpperCase(); + pmHour = (upperToken === dtf.PMDesignator.toUpperCase()); + if (!pmHour && (upperToken !== dtf.AMDesignator.toUpperCase())) return null; + break; + case 'f': + msec = parseInt(matchGroup, 10) * 100; + if ((msec < 0) || (msec > 999)) return null; + break; + case 'ff': + msec = parseInt(matchGroup, 10) * 10; + if ((msec < 0) || (msec > 999)) return null; + break; + case 'fff': + msec = parseInt(matchGroup, 10); + if ((msec < 0) || (msec > 999)) return null; + break; + case 'dddd': + weekDay = cultureInfo._getDayIndex(matchGroup); + if ((weekDay < 0) || (weekDay > 6)) return null; + break; + case 'ddd': + weekDay = cultureInfo._getAbbrDayIndex(matchGroup); + if ((weekDay < 0) || (weekDay > 6)) return null; + break; + case 'zzz': + var offsets = matchGroup.split(/:/); + if (offsets.length !== 2) return null; + var hourOffset = parseInt(offsets[0], 10); + if ((hourOffset < -12) || (hourOffset > 13)) return null; + var minOffset = parseInt(offsets[1], 10); + if ((minOffset < 0) || (minOffset > 59)) return null; + tzMinOffset = (hourOffset * 60) + (matchGroup.startsWith('-')? -minOffset : minOffset); + break; + case 'z': case 'zz': + var hourOffset = parseInt(matchGroup, 10); + if ((hourOffset < -12) || (hourOffset > 13)) return null; + tzMinOffset = hourOffset * 60; + break; + } + } + } + var result = new Date(); + if (year === null) { + year = result.getFullYear(); + } + if (month === null) { + month = result.getMonth(); + } + if (date === null) { + date = result.getDate(); + } + result.setFullYear(year, month, date); + if (result.getDate() !== date) return null; + if ((weekDay !== null) && (result.getDay() !== weekDay)) { + return null; + } + if (pmHour && (hour < 12)) { + hour += 12; + } + result.setHours(hour, min, sec, msec); + if (tzMinOffset !== null) { + var adjustedMin = result.getMinutes() - (tzMinOffset + result.getTimezoneOffset()); + result.setHours(result.getHours() + parseInt(adjustedMin/60, 10), adjustedMin%60); + } + return result; +} +Date.prototype.format = function Date$format(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.InvariantCulture); +} +Date.prototype.localeFormat = function Date$localeFormat(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.CurrentCulture); +} +Date.prototype._toFormattedString = function Date$_toFormattedString(format, cultureInfo) { + if (!format || (format.length === 0) || (format === 'i')) { + if (cultureInfo && (cultureInfo.name.length > 0)) { + return this.toLocaleString(); + } + else { + return this.toString(); + } + } + var dtf = cultureInfo.dateTimeFormat; + format = Date._expandFormat(dtf, format); + var ret = new Sys.StringBuilder(); + var hour; + function addLeadingZero(num) { + if (num < 10) { + return '0' + num; + } + return num.toString(); + } + function addLeadingZeros(num) { + if (num < 10) { + return '00' + num; + } + if (num < 100) { + return '0' + num; + } + return num.toString(); + } + var quoteCount = 0; + var tokenRegExp = Date._getTokenRegExp(); + for (;;) { + var index = tokenRegExp.lastIndex; + var ar = tokenRegExp.exec(format); + var preMatch = format.slice(index, ar ? ar.index : format.length); + quoteCount += Date._appendPreOrPostMatch(preMatch, ret); + if (!ar) break; + if ((quoteCount%2) === 1) { + ret.append(ar[0]); + continue; + } + switch (ar[0]) { + case "dddd": + ret.append(dtf.DayNames[this.getDay()]); + break; + case "ddd": + ret.append(dtf.AbbreviatedDayNames[this.getDay()]); + break; + case "dd": + ret.append(addLeadingZero(this.getDate())); + break; + case "d": + ret.append(this.getDate()); + break; + case "MMMM": + ret.append(dtf.MonthNames[this.getMonth()]); + break; + case "MMM": + ret.append(dtf.AbbreviatedMonthNames[this.getMonth()]); + break; + case "MM": + ret.append(addLeadingZero(this.getMonth() + 1)); + break; + case "M": + ret.append(this.getMonth() + 1); + break; + case "yyyy": + ret.append(this.getFullYear()); + break; + case "yy": + ret.append(addLeadingZero(this.getFullYear() % 100)); + break; + case "y": + ret.append(this.getFullYear() % 100); + break; + case "hh": + hour = this.getHours() % 12; + if (hour === 0) hour = 12; + ret.append(addLeadingZero(hour)); + break; + case "h": + hour = this.getHours() % 12; + if (hour === 0) hour = 12; + ret.append(hour); + break; + case "HH": + ret.append(addLeadingZero(this.getHours())); + break; + case "H": + ret.append(this.getHours()); + break; + case "mm": + ret.append(addLeadingZero(this.getMinutes())); + break; + case "m": + ret.append(this.getMinutes()); + break; + case "ss": + ret.append(addLeadingZero(this.getSeconds())); + break; + case "s": + ret.append(this.getSeconds()); + break; + case "tt": + ret.append((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator); + break; + case "t": + ret.append(((this.getHours() < 12) ? dtf.AMDesignator : dtf.PMDesignator).charAt(0)); + break; + case "f": + ret.append(addLeadingZeros(this.getMilliseconds()).charAt(0)); + break; + case "ff": + ret.append(addLeadingZeros(this.getMilliseconds()).substr(0, 2)); + break; + case "fff": + ret.append(addLeadingZeros(this.getMilliseconds())); + break; + case "z": + hour = this.getTimezoneOffset() / 60; + ret.append(((hour <= 0) ? '+' : '-') + Math.floor(Math.abs(hour))); + break; + case "zz": + hour = this.getTimezoneOffset() / 60; + ret.append(((hour <= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour)))); + break; + case "zzz": + hour = this.getTimezoneOffset() / 60; + ret.append(((hour <= 0) ? '+' : '-') + addLeadingZero(Math.floor(Math.abs(hour))) + + dtf.TimeSeparator + addLeadingZero(Math.abs(this.getTimezoneOffset() % 60))); + break; + } + } + return ret.toString(); +} + +Number.__typeName = 'Number'; +Number.__class = true; +Number.parseLocale = function Number$parseLocale(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + return Number._parse(value, Sys.CultureInfo.CurrentCulture); +} +Number.parseInvariant = function Number$parseInvariant(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String} + ]); + if (e) throw e; + return Number._parse(value, Sys.CultureInfo.InvariantCulture); +} +Number._parse = function Number$_parse(value, cultureInfo) { + value = value.trim(); + + if (value.match(/^[+-]?infinity$/i)) { + return parseFloat(value); + } + if (value.match(/^0x[a-f0-9]+$/i)) { + return parseInt(value); + } + var numFormat = cultureInfo.numberFormat; + var signInfo = Number._parseNumberNegativePattern(value, numFormat, numFormat.NumberNegativePattern); + var sign = signInfo[0]; + var num = signInfo[1]; + + if ((sign === '') && (numFormat.NumberNegativePattern !== 1)) { + signInfo = Number._parseNumberNegativePattern(value, numFormat, 1); + sign = signInfo[0]; + num = signInfo[1]; + } + if (sign === '') sign = '+'; + + var exponent; + var intAndFraction; + var exponentPos = num.indexOf('e'); + if (exponentPos < 0) exponentPos = num.indexOf('E'); + if (exponentPos < 0) { + intAndFraction = num; + exponent = null; + } + else { + intAndFraction = num.substr(0, exponentPos); + exponent = num.substr(exponentPos + 1); + } + + var integer; + var fraction; + var decimalPos = intAndFraction.indexOf(numFormat.NumberDecimalSeparator); + if (decimalPos < 0) { + integer = intAndFraction; + fraction = null; + } + else { + integer = intAndFraction.substr(0, decimalPos); + fraction = intAndFraction.substr(decimalPos + numFormat.NumberDecimalSeparator.length); + } + + integer = integer.split(numFormat.NumberGroupSeparator).join(''); + + var p = sign + integer; + if (fraction !== null) { + p += '.' + fraction; + } + if (exponent !== null) { + var expSignInfo = Number._parseNumberNegativePattern(exponent, numFormat, 1); + if (expSignInfo[0] === '') { + expSignInfo[0] = '+'; + } + p += 'e' + expSignInfo[0] + expSignInfo[1]; + } + if (p.match(/^[+-]?\d*\.?\d*(e[+-]?\d+)?$/)) { + return parseFloat(p); + } + return Number.NaN; +} +Number._parseNumberNegativePattern = function Number$_parseNumberNegativePattern(value, numFormat, numberNegativePattern) { + var neg = numFormat.NegativeSign; + var pos = numFormat.PositiveSign; + switch (numberNegativePattern) { + case 4: + neg = ' ' + neg; + pos = ' ' + pos; + case 3: + if (value.endsWith(neg)) { + return ['-', value.substr(0, value.length - neg.length)]; + } + else if (value.endsWith(pos)) { + return ['+', value.substr(0, value.length - pos.length)]; + } + break; + case 2: + neg += ' '; + pos += ' '; + case 1: + if (value.startsWith(neg)) { + return ['-', value.substr(neg.length)]; + } + else if (value.startsWith(pos)) { + return ['+', value.substr(pos.length)]; + } + break; + case 0: + if (value.startsWith('(') && value.endsWith(')')) { + return ['-', value.substr(1, value.length - 2)]; + } + break; + } + return ['', value]; +} +Number.prototype.format = function Number$format(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.InvariantCulture); +} +Number.prototype.localeFormat = function Number$localeFormat(format) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "format", type: String} + ]); + if (e) throw e; + return this._toFormattedString(format, Sys.CultureInfo.CurrentCulture); +} +Number.prototype._toFormattedString = function Number$_toFormattedString(format, cultureInfo) { + if (!format || (format.length === 0) || (format === 'i')) { + if (cultureInfo && (cultureInfo.name.length > 0)) { + return this.toLocaleString(); + } + else { + return this.toString(); + } + } + var _percentPositivePattern = ["n %", "n%", "%n" ]; + var _percentNegativePattern = ["-n %", "-n%", "-%n"]; + var _numberNegativePattern = ["(n)","-n","- n","n-","n -"]; + var _currencyPositivePattern = ["$n","n$","$ n","n $"]; + var _currencyNegativePattern = ["($n)","-$n","$-n","$n-","(n$)","-n$","n-$","n$-","-n $","-$ n","n $-","$ n-","$ -n","n- $","($ n)","(n $)"]; + function expandNumber(number, precision, groupSizes, sep, decimalChar) { + + var curSize = groupSizes[0]; + var curGroupIndex = 1; + var numberString = number.toString(); + var right = ""; + var exponent = ""; + var decimalSplit = numberString.split('.'); + if (decimalSplit.length > 1) { + numberString = decimalSplit[0]; + right = decimalSplit[1]; + var exponentSplit = right.split(/e/i); + if (exponentSplit.length > 1) { + right = exponentSplit[0]; + exponent = "e" + exponentSplit[1]; + } + } + if (precision > 0) { + var rightDifference = right.length - precision; + if (rightDifference > 0) { + right = right.slice(0, precision); + } else if (rightDifference < 0) { + for (var i=0; i= 0) { + if (curSize === 0 || curSize > stringIndex) { + if (ret.length > 0) + return numberString.slice(0, stringIndex + 1) + sep + ret + right; + else + return numberString.slice(0, stringIndex + 1) + right; + } + if (ret.length > 0) + ret = numberString.slice(stringIndex - curSize + 1, stringIndex+1) + sep + ret; + else + ret = numberString.slice(stringIndex - curSize + 1, stringIndex+1); + stringIndex -= curSize; + if (curGroupIndex < groupSizes.length) { + curSize = groupSizes[curGroupIndex]; + curGroupIndex++; + } + } + return numberString.slice(0, stringIndex + 1) + sep + ret + right; + } + var nf = cultureInfo.numberFormat; + var number = Math.abs(this); + if (!format) + format = "D"; + var precision = -1; + if (format.length > 1) precision = parseInt(format.slice(1), 10); + var pattern; + switch (format.charAt(0)) { + case "d": + case "D": + pattern = 'n'; + if (precision !== -1) { + var numberStr = ""+number; + var zerosToAdd = precision - numberStr.length; + if (zerosToAdd > 0) { + for (var i=0; i + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + array[array.length] = item; +} +Array.addRange = function Array$addRange(array, items) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "items", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + array.push.apply(array, items); +} +Array.clear = function Array$clear(array) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + array.length = 0; +} +Array.clone = function Array$clone(array) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + if (array.length === 1) { + return [array[0]]; + } + else { + return Array.apply(null, array); + } +} +Array.contains = function Array$contains(array, item) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + return (Array.indexOf(array, item) >= 0); +} +Array.dequeue = function Array$dequeue(array) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true} + ]); + if (e) throw e; + return array.shift(); +} +Array.forEach = function Array$forEach(array, method, instance) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "method", type: Function}, + {name: "instance", mayBeNull: true, optional: true} + ]); + if (e) throw e; + for (var i = 0, l = array.length; i < l; i++) { + var elt = array[i]; + if (typeof(elt) !== 'undefined') method.call(instance, elt, i, array); + } +} +Array.indexOf = function Array$indexOf(array, item, start) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true, optional: true}, + {name: "start", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (typeof(item) === "undefined") return -1; + var length = array.length; + if (length !== 0) { + start = start - 0; + if (isNaN(start)) { + start = 0; + } + else { + if (isFinite(start)) { + start = start - (start % 1); + } + if (start < 0) { + start = Math.max(0, length + start); + } + } + for (var i = start; i < length; i++) { + if ((typeof(array[i]) !== "undefined") && (array[i] === item)) { + return i; + } + } + } + return -1; +} +Array.insert = function Array$insert(array, index, item) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "index", mayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + array.splice(index, 0, item); +} +Array.parse = function Array$parse(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String, mayBeNull: true} + ]); + if (e) throw e; + if (!value) return []; + var v = eval(value); + if (!Array.isInstanceOfType(v)) throw Error.argument('value', Sys.Res.arrayParseBadFormat); + return v; +} +Array.remove = function Array$remove(array, item) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "item", mayBeNull: true} + ]); + if (e) throw e; + var index = Array.indexOf(array, item); + if (index >= 0) { + array.splice(index, 1); + } + return (index >= 0); +} +Array.removeAt = function Array$removeAt(array, index) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "array", type: Array, elementMayBeNull: true}, + {name: "index", mayBeNull: true} + ]); + if (e) throw e; + array.splice(index, 1); +} + +if (!window) this.window = this; +window.Type = Function; +Type.__fullyQualifiedIdentifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]([^ \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*[^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\])?$", "i"); +Type.__identifierRegExp = new RegExp("^[^.0-9 \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\][^. \\s|,;:&*=+\\-()\\[\\]{}^%#@!~\\n\\r\\t\\f\\\\]*$", "i"); +Type.prototype.callBaseMethod = function Type$callBaseMethod(instance, name, baseArguments) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"}, + {name: "name", type: String}, + {name: "baseArguments", type: Array, mayBeNull: true, optional: true, elementMayBeNull: true} + ]); + if (e) throw e; + var baseMethod = this.getBaseMethod(instance, name); + if (!baseMethod) throw Error.invalidOperation(String.format(Sys.Res.methodNotFound, name)); + if (!baseArguments) { + return baseMethod.apply(instance); + } + else { + return baseMethod.apply(instance, baseArguments); + } +} +Type.prototype.getBaseMethod = function Type$getBaseMethod(instance, name) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"}, + {name: "name", type: String} + ]); + if (e) throw e; + if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this); + var baseType = this.getBaseType(); + if (baseType) { + var baseMethod = baseType.prototype[name]; + return (baseMethod instanceof Function) ? baseMethod : null; + } + return null; +} +Type.prototype.getBaseType = function Type$getBaseType() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return (typeof(this.__baseType) === "undefined") ? null : this.__baseType; +} +Type.prototype.getInterfaces = function Type$getInterfaces() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var result = []; + var type = this; + while(type) { + var interfaces = type.__interfaces; + if (interfaces) { + for (var i = 0, l = interfaces.length; i < l; i++) { + var interfaceType = interfaces[i]; + if (!Array.contains(result, interfaceType)) { + result[result.length] = interfaceType; + } + } + } + type = type.__baseType; + } + return result; +} +Type.prototype.getName = function Type$getName() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return (typeof(this.__typeName) === "undefined") ? "" : this.__typeName; +} +Type.prototype.implementsInterface = function Type$implementsInterface(interfaceType) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "interfaceType", type: Type} + ]); + if (e) throw e; + this.resolveInheritance(); + var interfaceName = interfaceType.getName(); + var cache = this.__interfaceCache; + if (cache) { + var cacheEntry = cache[interfaceName]; + if (typeof(cacheEntry) !== 'undefined') return cacheEntry; + } + else { + cache = this.__interfaceCache = {}; + } + var baseType = this; + while (baseType) { + var interfaces = baseType.__interfaces; + if (interfaces) { + if (Array.indexOf(interfaces, interfaceType) !== -1) { + return cache[interfaceName] = true; + } + } + baseType = baseType.__baseType; + } + return cache[interfaceName] = false; +} +Type.prototype.inheritsFrom = function Type$inheritsFrom(parentType) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "parentType", type: Type} + ]); + if (e) throw e; + this.resolveInheritance(); + var baseType = this.__baseType; + while (baseType) { + if (baseType === parentType) { + return true; + } + baseType = baseType.__baseType; + } + return false; +} +Type.prototype.initializeBase = function Type$initializeBase(instance, baseArguments) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance"}, + {name: "baseArguments", type: Array, mayBeNull: true, optional: true, elementMayBeNull: true} + ]); + if (e) throw e; + if (!this.isInstanceOfType(instance)) throw Error.argumentType('instance', Object.getType(instance), this); + this.resolveInheritance(); + if (this.__baseType) { + if (!baseArguments) { + this.__baseType.apply(instance); + } + else { + this.__baseType.apply(instance, baseArguments); + } + } + return instance; +} +Type.prototype.isImplementedBy = function Type$isImplementedBy(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance", mayBeNull: true} + ]); + if (e) throw e; + if (typeof(instance) === "undefined" || instance === null) return false; + var instanceType = Object.getType(instance); + return !!(instanceType.implementsInterface && instanceType.implementsInterface(this)); +} +Type.prototype.isInstanceOfType = function Type$isInstanceOfType(instance) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "instance", mayBeNull: true} + ]); + if (e) throw e; + if (typeof(instance) === "undefined" || instance === null) return false; + if (instance instanceof this) return true; + var instanceType = Object.getType(instance); + return !!(instanceType === this) || + (instanceType.inheritsFrom && instanceType.inheritsFrom(this)) || + (instanceType.implementsInterface && instanceType.implementsInterface(this)); +} +Type.prototype.registerClass = function Type$registerClass(typeName, baseType, interfaceTypes) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "typeName", type: String}, + {name: "baseType", type: Type, mayBeNull: true, optional: true}, + {name: "interfaceTypes", type: Type, parameterArray: true} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName); + var parsedName; + try { + parsedName = eval(typeName); + } + catch(e) { + throw Error.argument('typeName', Sys.Res.argumentTypeName); + } + if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); + if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); + if ((arguments.length > 1) && (typeof(baseType) === 'undefined')) throw Error.argumentUndefined('baseType'); + if (baseType && !baseType.__class) throw Error.argument('baseType', Sys.Res.baseNotAClass); + this.prototype.constructor = this; + this.__typeName = typeName; + this.__class = true; + if (baseType) { + this.__baseType = baseType; + this.__basePrototypePending = true; + } + Sys.__upperCaseTypes[typeName.toUpperCase()] = this; + if (interfaceTypes) { + this.__interfaces = []; + this.resolveInheritance(); + for (var i = 2, l = arguments.length; i < l; i++) { + var interfaceType = arguments[i]; + if (!interfaceType.__interface) throw Error.argument('interfaceTypes[' + (i - 2) + ']', Sys.Res.notAnInterface); + for (var methodName in interfaceType.prototype) { + var method = interfaceType.prototype[methodName]; + if (!this.prototype[methodName]) { + this.prototype[methodName] = method; + } + } + this.__interfaces.push(interfaceType); + } + } + Sys.__registeredTypes[typeName] = true; + return this; +} +Type.prototype.registerInterface = function Type$registerInterface(typeName) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "typeName", type: String} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(typeName)) throw Error.argument('typeName', Sys.Res.notATypeName); + var parsedName; + try { + parsedName = eval(typeName); + } + catch(e) { + throw Error.argument('typeName', Sys.Res.argumentTypeName); + } + if (parsedName !== this) throw Error.argument('typeName', Sys.Res.badTypeName); + if (Sys.__registeredTypes[typeName]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, typeName)); + Sys.__upperCaseTypes[typeName.toUpperCase()] = this; + this.prototype.constructor = this; + this.__typeName = typeName; + this.__interface = true; + Sys.__registeredTypes[typeName] = true; + return this; +} +Type.prototype.resolveInheritance = function Type$resolveInheritance() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this.__basePrototypePending) { + var baseType = this.__baseType; + baseType.resolveInheritance(); + for (var memberName in baseType.prototype) { + var memberValue = baseType.prototype[memberName]; + if (!this.prototype[memberName]) { + this.prototype[memberName] = memberValue; + } + } + delete this.__basePrototypePending; + } +} +Type.getRootNamespaces = function Type$getRootNamespaces() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return Array.clone(Sys.__rootNamespaces); +} +Type.isClass = function Type$isClass(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__class; +} +Type.isInterface = function Type$isInterface(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__interface; +} +Type.isNamespace = function Type$isNamespace(object) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(object) === 'undefined') || (object === null)) return false; + return !!object.__namespace; +} +Type.parse = function Type$parse(typeName, ns) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "typeName", type: String, mayBeNull: true}, + {name: "ns", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var fn; + if (ns) { + fn = Sys.__upperCaseTypes[ns.getName().toUpperCase() + '.' + typeName.toUpperCase()]; + return fn || null; + } + if (!typeName) return null; + if (!Type.__htClasses) { + Type.__htClasses = {}; + } + fn = Type.__htClasses[typeName]; + if (!fn) { + fn = eval(typeName); + if (typeof(fn) !== 'function') throw Error.argument('typeName', Sys.Res.notATypeName); + Type.__htClasses[typeName] = fn; + } + return fn; +} +Type.registerNamespace = function Type$registerNamespace(namespacePath) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "namespacePath", type: String} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(namespacePath)) throw Error.argument('namespacePath', Sys.Res.invalidNameSpace); + var rootObject = window; + var namespaceParts = namespacePath.split('.'); + for (var i = 0; i < namespaceParts.length; i++) { + var currentPart = namespaceParts[i]; + var ns = rootObject[currentPart]; + if (ns && !ns.__namespace) { + throw Error.invalidOperation(String.format(Sys.Res.namespaceContainsObject, namespaceParts.splice(0, i + 1).join('.'))); + } + if (!ns) { + ns = rootObject[currentPart] = { + __namespace: true, + __typeName: namespaceParts.slice(0, i + 1).join('.') + }; + if (i === 0) { + Sys.__rootNamespaces[Sys.__rootNamespaces.length] = ns; + } + var parsedName; + try { + parsedName = eval(ns.__typeName); + } + catch(e) { + parsedName = null; + } + if (parsedName !== ns) { + delete rootObject[currentPart]; + throw Error.argument('namespacePath', Sys.Res.invalidNameSpace); + } + ns.getName = function ns$getName() {return this.__typeName;} + } + rootObject = ns; + } +} +window.Sys = { + __namespace: true, + __typeName: "Sys", + getName: function() {return "Sys";}, + __upperCaseTypes: {} +}; +Sys.__rootNamespaces = [Sys]; +Sys.__registeredTypes = {}; + +Sys.IDisposable = function Sys$IDisposable() { + throw Error.notImplemented(); +} + function Sys$IDisposable$dispose() { + throw Error.notImplemented(); + } +Sys.IDisposable.prototype = { + dispose: Sys$IDisposable$dispose +} +Sys.IDisposable.registerInterface('Sys.IDisposable'); + +Sys.StringBuilder = function Sys$StringBuilder(initialText) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "initialText", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._parts = (typeof(initialText) !== 'undefined' && initialText !== null && initialText !== '') ? + [initialText.toString()] : []; + this._value = {}; + this._len = 0; +} + function Sys$StringBuilder$append(text) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "text", mayBeNull: true} + ]); + if (e) throw e; + this._parts[this._parts.length] = text; + } + function Sys$StringBuilder$appendLine(text) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "text", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._parts[this._parts.length] = + ((typeof(text) === 'undefined') || (text === null) || (text === '')) ? + '\r\n' : text + '\r\n'; + } + function Sys$StringBuilder$clear() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._parts = []; + this._value = {}; + this._len = 0; + } + function Sys$StringBuilder$isEmpty() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._parts.length === 0) return true; + return this.toString() === ''; + } + function Sys$StringBuilder$toString(separator) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "separator", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + separator = separator || ''; + var parts = this._parts; + if (this._len !== parts.length) { + this._value = {}; + this._len = parts.length; + } + var val = this._value; + if (typeof(val[separator]) === 'undefined') { + if (separator !== '') { + for (var i = 0; i < parts.length;) { + if ((typeof(parts[i]) === 'undefined') || (parts[i] === '') || (parts[i] === null)) { + parts.splice(i, 1); + } + else { + i++; + } + } + } + val[separator] = this._parts.join(separator); + } + return val[separator]; + } +Sys.StringBuilder.prototype = { + append: Sys$StringBuilder$append, + appendLine: Sys$StringBuilder$appendLine, + clear: Sys$StringBuilder$clear, + isEmpty: Sys$StringBuilder$isEmpty, + toString: Sys$StringBuilder$toString +} +Sys.StringBuilder.registerClass('Sys.StringBuilder'); + +if (!window.XMLHttpRequest) { + window.XMLHttpRequest = function window$XMLHttpRequest() { + var progIDs = [ 'Mxsml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP' ]; + for (var i = 0, l = progIDs.length; i < l; i++) { + try { + return new ActiveXObject(progIDs[i]); + } + catch (ex) { + } + } + return null; + } +} + +Sys.Browser = {}; +Sys.Browser.InternetExplorer = {}; +Sys.Browser.Firefox = {}; +Sys.Browser.Safari = {}; +Sys.Browser.Opera = {}; +Sys.Browser.agent = null; +Sys.Browser.hasDebuggerStatement = false; +Sys.Browser.name = navigator.appName; +Sys.Browser.version = parseFloat(navigator.appVersion); +if (navigator.userAgent.indexOf(' MSIE ') > -1) { + Sys.Browser.agent = Sys.Browser.InternetExplorer; + Sys.Browser.version = parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]); + Sys.Browser.hasDebuggerStatement = true; +} +else if (navigator.userAgent.indexOf(' Firefox/') > -1) { + Sys.Browser.agent = Sys.Browser.Firefox; + Sys.Browser.version = parseFloat(navigator.userAgent.match(/ Firefox\/(\d+\.\d+)/)[1]); + Sys.Browser.name = 'Firefox'; + Sys.Browser.hasDebuggerStatement = true; +} +else if (navigator.userAgent.indexOf(' Safari/') > -1) { + Sys.Browser.agent = Sys.Browser.Safari; + Sys.Browser.version = parseFloat(navigator.userAgent.match(/ Safari\/(\d+(\.\d+)?)/)[1]); + Sys.Browser.name = 'Safari'; +} +else if (navigator.userAgent.indexOf('Opera/') > -1) { + Sys.Browser.agent = Sys.Browser.Opera; +} +Type.registerNamespace('Sys.UI'); + +Sys._Debug = function Sys$_Debug() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} + function Sys$_Debug$_appendConsole(text) { + if ((typeof(Debug) !== 'undefined') && Debug.writeln) { + Debug.writeln(text); + } + if (window.console && window.console.log) { + window.console.log(text); + } + if (window.opera) { + window.opera.postError(text); + } + if (window.debugService) { + window.debugService.trace(text); + } + } + function Sys$_Debug$_appendTrace(text) { + var traceElement = document.getElementById('TraceConsole'); + if (traceElement && (traceElement.tagName.toUpperCase() === 'TEXTAREA')) { + traceElement.value += text + '\n'; + } + } + function Sys$_Debug$assert(condition, message, displayCaller) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "condition", type: Boolean}, + {name: "message", type: String, mayBeNull: true, optional: true}, + {name: "displayCaller", type: Boolean, optional: true} + ]); + if (e) throw e; + if (!condition) { + message = (displayCaller && this.assert.caller) ? + String.format(Sys.Res.assertFailedCaller, message, this.assert.caller) : + String.format(Sys.Res.assertFailed, message); + if (confirm(String.format(Sys.Res.breakIntoDebugger, message))) { + this.fail(message); + } + } + } + function Sys$_Debug$clearTrace() { + var traceElement = document.getElementById('TraceConsole'); + if (traceElement && (traceElement.tagName.toUpperCase() === 'TEXTAREA')) { + traceElement.value = ''; + } + } + function Sys$_Debug$fail(message) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "message", type: String, mayBeNull: true} + ]); + if (e) throw e; + this._appendConsole(message); + if (Sys.Browser.hasDebuggerStatement) { + eval('debugger'); + } + } + function Sys$_Debug$trace(text) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "text"} + ]); + if (e) throw e; + this._appendConsole(text); + this._appendTrace(text); + } + function Sys$_Debug$traceDump(object, name) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", mayBeNull: true}, + {name: "name", type: String, mayBeNull: true, optional: true} + ]); + if (e) throw e; + var text = this._traceDump(object, name, true); + } + function Sys$_Debug$_traceDump(object, name, recursive, indentationPadding, loopArray) { + name = name? name : 'traceDump'; + indentationPadding = indentationPadding? indentationPadding : ''; + if (object === null) { + this.trace(indentationPadding + name + ': null'); + return; + } + switch(typeof(object)) { + case 'undefined': + this.trace(indentationPadding + name + ': Undefined'); + break; + case 'number': case 'string': case 'boolean': + this.trace(indentationPadding + name + ': ' + object); + break; + default: + if (Date.isInstanceOfType(object) || RegExp.isInstanceOfType(object)) { + this.trace(indentationPadding + name + ': ' + object.toString()); + break; + } + if (!loopArray) { + loopArray = []; + } + else if (Array.contains(loopArray, object)) { + this.trace(indentationPadding + name + ': ...'); + return; + } + Array.add(loopArray, object); + if ((object == window) || (object === document) || + (window.HTMLElement && (object instanceof HTMLElement)) || + (typeof(object.nodeName) === 'string')) { + var tag = object.tagName? object.tagName : 'DomElement'; + if (object.id) { + tag += ' - ' + object.id; + } + this.trace(indentationPadding + name + ' {' + tag + '}'); + } + else { + var typeName = Object.getTypeName(object); + this.trace(indentationPadding + name + (typeof(typeName) === 'string' ? ' {' + typeName + '}' : '')); + if ((indentationPadding === '') || recursive) { + indentationPadding += " "; + var i, length, properties, p, v; + if (Array.isInstanceOfType(object)) { + length = object.length; + for (i = 0; i < length; i++) { + this._traceDump(object[i], '[' + i + ']', recursive, indentationPadding, loopArray); + } + } + else { + for (p in object) { + v = object[p]; + if (!Function.isInstanceOfType(v)) { + this._traceDump(v, p, recursive, indentationPadding, loopArray); + } + } + } + } + } + Array.remove(loopArray, object); + } + } +Sys._Debug.prototype = { + _appendConsole: Sys$_Debug$_appendConsole, + _appendTrace: Sys$_Debug$_appendTrace, + assert: Sys$_Debug$assert, + clearTrace: Sys$_Debug$clearTrace, + fail: Sys$_Debug$fail, + trace: Sys$_Debug$trace, + traceDump: Sys$_Debug$traceDump, + _traceDump: Sys$_Debug$_traceDump +} +Sys._Debug.registerClass('Sys._Debug'); +Sys.Debug = new Sys._Debug(); + Sys.Debug.isDebug = true; + +function Sys$Enum$parse(value, ignoreCase) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", type: String}, + {name: "ignoreCase", type: Boolean, optional: true} + ]); + if (e) throw e; + var values, parsed, val; + if (ignoreCase) { + values = this.__lowerCaseValues; + if (!values) { + this.__lowerCaseValues = values = {}; + var prototype = this.prototype; + for (var name in prototype) { + values[name.toLowerCase()] = prototype[name]; + } + } + } + else { + values = this.prototype; + } + if (!this.__flags) { + val = (ignoreCase ? value.toLowerCase() : value); + parsed = values[val.trim()]; + if (typeof(parsed) !== 'number') throw Error.argument('value', String.format(Sys.Res.enumInvalidValue, value, this.__typeName)); + return parsed; + } + else { + var parts = (ignoreCase ? value.toLowerCase() : value).split(','); + var v = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var part = parts[i].trim(); + parsed = values[part]; + if (typeof(parsed) !== 'number') throw Error.argument('value', String.format(Sys.Res.enumInvalidValue, value.split(',')[i].trim(), this.__typeName)); + v |= parsed; + } + return v; + } +} +function Sys$Enum$toString(value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "value", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if ((typeof(value) === 'undefined') || (value === null)) return this.__string; + if ((typeof(value) != 'number') || ((value % 1) !== 0)) throw Error.argumentType('value', Object.getType(value), this); + var values = this.prototype; + var i; + if (!this.__flags || (value === 0)) { + for (i in values) { + if (values[i] === value) { + return i; + } + } + } + else { + var sorted = this.__sortedValues; + if (!sorted) { + sorted = []; + for (i in values) { + sorted[sorted.length] = {key: i, value: values[i]}; + } + sorted.sort(function(a, b) { + return a.value - b.value; + }); + this.__sortedValues = sorted; + } + var parts = []; + var v = value; + for (i = sorted.length - 1; i >= 0; i--) { + var kvp = sorted[i]; + var vali = kvp.value; + if (vali === 0) continue; + if ((vali & value) === vali) { + parts[parts.length] = kvp.key; + v -= vali; + if (v === 0) break; + } + } + if (parts.length && v === 0) return parts.reverse().join(', '); + } + throw Error.argumentOutOfRange('value', value, String.format(Sys.Res.enumInvalidValue, value, this.__typeName)); +} +Type.prototype.registerEnum = function Type$registerEnum(name, flags) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "name", type: String}, + {name: "flags", type: Boolean, optional: true} + ]); + if (e) throw e; + if (!Type.__fullyQualifiedIdentifierRegExp.test(name)) throw Error.argument('name', Sys.Res.notATypeName); + var parsedName; + try { + parsedName = eval(name); + } + catch(e) { + throw Error.argument('name', Sys.Res.argumentTypeName); + } + if (parsedName !== this) throw Error.argument('name', Sys.Res.badTypeName); + if (Sys.__registeredTypes[name]) throw Error.invalidOperation(String.format(Sys.Res.typeRegisteredTwice, name)); + for (var i in this.prototype) { + var val = this.prototype[i]; + if (!Type.__identifierRegExp.test(i)) throw Error.invalidOperation(String.format(Sys.Res.enumInvalidValueName, i)); + if (typeof(val) !== 'number' || (val % 1) !== 0) throw Error.invalidOperation(Sys.Res.enumValueNotInteger); + if (typeof(this[i]) !== 'undefined') throw Error.invalidOperation(String.format(Sys.Res.enumReservedName, i)); + } + Sys.__upperCaseTypes[name.toUpperCase()] = this; + for (var i in this.prototype) { + this[i] = this.prototype[i]; + } + this.__typeName = name; + this.parse = Sys$Enum$parse; + this.__string = this.toString(); + this.toString = Sys$Enum$toString; + this.__flags = flags; + this.__enum = true; + Sys.__registeredTypes[name] = true; +} +Type.isEnum = function Type$isEnum(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__enum; +} +Type.isFlags = function Type$isFlags(type) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", mayBeNull: true} + ]); + if (e) throw e; + if ((typeof(type) === 'undefined') || (type === null)) return false; + return !!type.__flags; +} + +Sys.EventHandlerList = function Sys$EventHandlerList() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._list = {}; +} + function Sys$EventHandlerList$addHandler(id, handler) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + Array.add(this._getEvent(id, true), handler); + } + function Sys$EventHandlerList$removeHandler(id, handler) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + var evt = this._getEvent(id); + if (!evt) return; + Array.remove(evt, handler); + } + function Sys$EventHandlerList$getHandler(id) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String} + ]); + if (e) throw e; + var evt = this._getEvent(id); + if (!evt || (evt.length === 0)) return null; + evt = Array.clone(evt); + return function(source, args) { + for (var i = 0, l = evt.length; i < l; i++) { + evt[i](source, args); + } + }; + } + function Sys$EventHandlerList$_getEvent(id, create) { + if (!this._list[id]) { + if (!create) return null; + this._list[id] = []; + } + return this._list[id]; + } +Sys.EventHandlerList.prototype = { + addHandler: Sys$EventHandlerList$addHandler, + removeHandler: Sys$EventHandlerList$removeHandler, + getHandler: Sys$EventHandlerList$getHandler, + _getEvent: Sys$EventHandlerList$_getEvent +} +Sys.EventHandlerList.registerClass('Sys.EventHandlerList'); + +Sys.EventArgs = function Sys$EventArgs() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} +Sys.EventArgs.registerClass('Sys.EventArgs'); +Sys.EventArgs.Empty = new Sys.EventArgs(); + +Sys.CancelEventArgs = function Sys$CancelEventArgs() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.CancelEventArgs.initializeBase(this); + this._cancel = false; +} + function Sys$CancelEventArgs$get_cancel() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._cancel; + } + function Sys$CancelEventArgs$set_cancel(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); + if (e) throw e; + this._cancel = value; + } +Sys.CancelEventArgs.prototype = { + get_cancel: Sys$CancelEventArgs$get_cancel, + set_cancel: Sys$CancelEventArgs$set_cancel +} +Sys.CancelEventArgs.registerClass('Sys.CancelEventArgs', Sys.EventArgs); + +Sys.INotifyPropertyChange = function Sys$INotifyPropertyChange() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} + function Sys$INotifyPropertyChange$add_propertyChanged(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$INotifyPropertyChange$remove_propertyChanged(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } +Sys.INotifyPropertyChange.prototype = { + add_propertyChanged: Sys$INotifyPropertyChange$add_propertyChanged, + remove_propertyChanged: Sys$INotifyPropertyChange$remove_propertyChanged +} +Sys.INotifyPropertyChange.registerInterface('Sys.INotifyPropertyChange'); + +Sys.PropertyChangedEventArgs = function Sys$PropertyChangedEventArgs(propertyName) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyName", type: String} + ]); + if (e) throw e; + Sys.PropertyChangedEventArgs.initializeBase(this); + this._propertyName = propertyName; +} + + function Sys$PropertyChangedEventArgs$get_propertyName() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._propertyName; + } +Sys.PropertyChangedEventArgs.prototype = { + get_propertyName: Sys$PropertyChangedEventArgs$get_propertyName +} +Sys.PropertyChangedEventArgs.registerClass('Sys.PropertyChangedEventArgs', Sys.EventArgs); + +Sys.INotifyDisposing = function Sys$INotifyDisposing() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} + function Sys$INotifyDisposing$add_disposing(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$INotifyDisposing$remove_disposing(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + throw Error.notImplemented(); + } +Sys.INotifyDisposing.prototype = { + add_disposing: Sys$INotifyDisposing$add_disposing, + remove_disposing: Sys$INotifyDisposing$remove_disposing +} +Sys.INotifyDisposing.registerInterface("Sys.INotifyDisposing"); + +Sys.Component = function Sys$Component() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (Sys.Application) Sys.Application.registerDisposableObject(this); +} + function Sys$Component$get_events() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._events) { + this._events = new Sys.EventHandlerList(); + } + return this._events; + } + function Sys$Component$get_id() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._id; + } + function Sys$Component$set_id(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + if (this._idSet) throw Error.invalidOperation(Sys.Res.componentCantSetIdTwice); + this._idSet = true; + var oldId = this.get_id(); + if (oldId && Sys.Application.findComponent(oldId)) throw Error.invalidOperation(Sys.Res.componentCantSetIdAfterAddedToApp); + this._id = value; + } + function Sys$Component$get_isInitialized() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._initialized; + } + function Sys$Component$get_isUpdating() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._updating; + } + function Sys$Component$add_disposing(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("disposing", handler); + } + function Sys$Component$remove_disposing(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("disposing", handler); + } + function Sys$Component$add_propertyChanged(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("propertyChanged", handler); + } + function Sys$Component$remove_propertyChanged(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("propertyChanged", handler); + } + function Sys$Component$beginUpdate() { + this._updating = true; + } + function Sys$Component$dispose() { + if (this._events) { + var handler = this._events.getHandler("disposing"); + if (handler) { + handler(this, Sys.EventArgs.Empty); + } + } + delete this._events; + Sys.Application.unregisterDisposableObject(this); + Sys.Application.removeComponent(this); + } + function Sys$Component$endUpdate() { + this._updating = false; + if (!this._initialized) this.initialize(); + this.updated(); + } + function Sys$Component$initialize() { + this._initialized = true; + } + function Sys$Component$raisePropertyChanged(propertyName) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyName", type: String} + ]); + if (e) throw e; + if (!this._events) return; + var handler = this._events.getHandler("propertyChanged"); + if (handler) { + handler(this, new Sys.PropertyChangedEventArgs(propertyName)); + } + } + function Sys$Component$updated() { + } +Sys.Component.prototype = { + _id: null, + _idSet: false, + _initialized: false, + _updating: false, + get_events: Sys$Component$get_events, + get_id: Sys$Component$get_id, + set_id: Sys$Component$set_id, + get_isInitialized: Sys$Component$get_isInitialized, + get_isUpdating: Sys$Component$get_isUpdating, + add_disposing: Sys$Component$add_disposing, + remove_disposing: Sys$Component$remove_disposing, + add_propertyChanged: Sys$Component$add_propertyChanged, + remove_propertyChanged: Sys$Component$remove_propertyChanged, + beginUpdate: Sys$Component$beginUpdate, + dispose: Sys$Component$dispose, + endUpdate: Sys$Component$endUpdate, + initialize: Sys$Component$initialize, + raisePropertyChanged: Sys$Component$raisePropertyChanged, + updated: Sys$Component$updated +} +Sys.Component.registerClass('Sys.Component', null, Sys.IDisposable, Sys.INotifyPropertyChange, Sys.INotifyDisposing); +function Sys$Component$_setProperties(target, properties) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "target"}, + {name: "properties"} + ]); + if (e) throw e; + var current; + var targetType = Object.getType(target); + var isObject = (targetType === Object) || (targetType === Sys.UI.DomElement); + var isComponent = Sys.Component.isInstanceOfType(target) && !target.get_isUpdating(); + if (isComponent) target.beginUpdate(); + for (var name in properties) { + var val = properties[name]; + var getter = isObject ? null : target["get_" + name]; + if (isObject || typeof(getter) !== 'function') { + var targetVal = target[name]; + if (!isObject && typeof(targetVal) === 'undefined') throw Error.invalidOperation(String.format(Sys.Res.propertyUndefined, name)); + if (!val || (typeof(val) !== 'object') || (isObject && !targetVal)) { + target[name] = val; + } + else { + Sys$Component$_setProperties(targetVal, val); + } + } + else { + var setter = target["set_" + name]; + if (typeof(setter) === 'function') { + setter.apply(target, [val]); + } + else if (val instanceof Array) { + current = getter.apply(target); + if (!(current instanceof Array)) throw new Error.invalidOperation(String.format(Sys.Res.propertyNotAnArray, name)); + for (var i = 0, j = current.length, l= val.length; i < l; i++, j++) { + current[j] = val[i]; + } + } + else if ((typeof(val) === 'object') && (Object.getType(val) === Object)) { + current = getter.apply(target); + if ((typeof(current) === 'undefined') || (current === null)) throw new Error.invalidOperation(String.format(Sys.Res.propertyNullOrUndefined, name)); + Sys$Component$_setProperties(current, val); + } + else { + throw new Error.invalidOperation(String.format(Sys.Res.propertyNotWritable, name)); + } + } + } + if (isComponent) target.endUpdate(); +} +function Sys$Component$_setReferences(component, references) { + for (var name in references) { + var setter = component["set_" + name]; + var reference = $find(references[name]); + if (typeof(setter) !== 'function') throw new Error.invalidOperation(String.format(Sys.Res.propertyNotWritable, name)); + if (!reference) throw Error.invalidOperation(String.format(Sys.Res.referenceNotFound, references[name])); + setter.apply(component, [reference]); + } +} +var $create = Sys.Component.create = function Sys$Component$create(type, properties, events, references, element) { + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "type", type: Type}, + {name: "properties", mayBeNull: true, optional: true}, + {name: "events", mayBeNull: true, optional: true}, + {name: "references", mayBeNull: true, optional: true}, + {name: "element", mayBeNull: true, domElement: true, optional: true} + ]); + if (e) throw e; + if (!type.inheritsFrom(Sys.Component)) { + throw Error.argument('type', String.format(Sys.Res.createNotComponent, type.getName())); + } + if (type.inheritsFrom(Sys.UI.Behavior) || type.inheritsFrom(Sys.UI.Control)) { + if (!element) throw Error.argument('element', Sys.Res.createNoDom); + } + else if (element) throw Error.argument('element', Sys.Res.createComponentOnDom); + var component = (element ? new type(element): new type()); + var app = Sys.Application; + var creatingComponents = app.get_isCreatingComponents(); + component.beginUpdate(); + if (properties) { + Sys$Component$_setProperties(component, properties); + } + if (events) { + for (var name in events) { + if (!(component["add_" + name] instanceof Function)) throw new Error.invalidOperation(String.format(Sys.Res.undefinedEvent, name)); + if (!(events[name] instanceof Function)) throw new Error.invalidOperation(Sys.Res.eventHandlerNotFunction); + component["add_" + name](events[name]); + } + } + if (component.get_id()) { + app.addComponent(component); + } + if (creatingComponents) { + app._createdComponents[app._createdComponents.length] = component; + if (references) { + app._addComponentToSecondPass(component, references); + } + else { + component.endUpdate(); + } + } + else { + if (references) { + Sys$Component$_setReferences(component, references); + } + component.endUpdate(); + } + return component; +} + +Sys.UI.MouseButton = function Sys$UI$MouseButton() { + /// + /// + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.MouseButton.prototype = { + leftButton: 0, + middleButton: 1, + rightButton: 2 +} +Sys.UI.MouseButton.registerEnum("Sys.UI.MouseButton"); + +Sys.UI.Key = function Sys$UI$Key() { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.Key.prototype = { + backspace: 8, + tab: 9, + enter: 13, + esc: 27, + space: 32, + pageUp: 33, + pageDown: 34, + end: 35, + home: 36, + left: 37, + up: 38, + right: 39, + down: 40, + del: 127 +} +Sys.UI.Key.registerEnum("Sys.UI.Key"); + +Sys.UI.Point = function Sys$UI$Point(x, y) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "x", type: Number, integer: true}, + {name: "y", type: Number, integer: true} + ]); + if (e) throw e; + this.x = x; + this.y = y; +} +Sys.UI.Point.registerClass('Sys.UI.Point'); + +Sys.UI.Bounds = function Sys$UI$Bounds(x, y, width, height) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "x", type: Number, integer: true}, + {name: "y", type: Number, integer: true}, + {name: "height", type: Number, integer: true}, + {name: "width", type: Number, integer: true} + ]); + if (e) throw e; + this.x = x; + this.y = y; + this.height = height; + this.width = width; +} +Sys.UI.Bounds.registerClass('Sys.UI.Bounds'); + +Sys.UI.DomEvent = function Sys$UI$DomEvent(eventObject) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "eventObject"} + ]); + if (e) throw e; + var e = eventObject; + this.rawEvent = e; + this.altKey = e.altKey; + if (typeof(e.button) !== 'undefined') { + this.button = (typeof(e.which) !== 'undefined') ? e.button : + (e.button === 4) ? Sys.UI.MouseButton.middleButton : + (e.button === 2) ? Sys.UI.MouseButton.rightButton : + Sys.UI.MouseButton.leftButton; + } + if (e.type === 'keypress') { + this.charCode = e.charCode || e.keyCode; + } + else if (e.keyCode && (e.keyCode === 46)) { + this.keyCode = 127; + } + else { + this.keyCode = e.keyCode; + } + this.clientX = e.clientX; + this.clientY = e.clientY; + this.ctrlKey = e.ctrlKey; + this.target = e.target ? e.target : e.srcElement; + if ((typeof(e.offsetX) !== 'undefined') && (typeof(e.offsetY) !== 'undefined')) { + this.offsetX = e.offsetX; + this.offsetY = e.offsetY; + } + else if (this.target && (this.target.nodeType !== 3) && (typeof(e.clientX) === 'number')) { + var loc = Sys.UI.DomElement.getLocation(this.target); + var w = Sys.UI.DomElement._getWindow(this.target); + this.offsetX = (w.pageXOffset || 0) + e.clientX - loc.x; + this.offsetY = (w.pageYOffset || 0) + e.clientY - loc.y; + } + this.screenX = e.screenX; + this.screenY = e.screenY; + this.shiftKey = e.shiftKey; + this.type = e.type; +} + function Sys$UI$DomEvent$preventDefault() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this.rawEvent.preventDefault) { + this.rawEvent.preventDefault(); + } + else if (window.event) { + this.rawEvent.returnValue = false; + } + } + function Sys$UI$DomEvent$stopPropagation() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this.rawEvent.stopPropagation) { + this.rawEvent.stopPropagation(); + } + else if (window.event) { + this.rawEvent.cancelBubble = true; + } + } +Sys.UI.DomEvent.prototype = { + preventDefault: Sys$UI$DomEvent$preventDefault, + stopPropagation: Sys$UI$DomEvent$stopPropagation +} +Sys.UI.DomEvent.registerClass('Sys.UI.DomEvent'); +var $addHandler = Sys.UI.DomEvent.addHandler = function Sys$UI$DomEvent$addHandler(element, eventName, handler) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"}, + {name: "eventName", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + if (eventName === "error") throw Error.invalidOperation(Sys.Res.addHandlerCantBeUsedForError); + if (!element._events) { + element._events = {}; + } + var eventCache = element._events[eventName]; + if (!eventCache) { + element._events[eventName] = eventCache = []; + } + var browserHandler; + if (element.addEventListener) { + browserHandler = function(e) { + return handler.call(element, new Sys.UI.DomEvent(e)); + } + element.addEventListener(eventName, browserHandler, false); + } + else if (element.attachEvent) { + browserHandler = function() { + var e = {}; + try {e = Sys.UI.DomElement._getWindow(element).event} catch(ex) {} + return handler.call(element, new Sys.UI.DomEvent(e)); + } + element.attachEvent('on' + eventName, browserHandler); + } + eventCache[eventCache.length] = {handler: handler, browserHandler: browserHandler}; +} +var $addHandlers = Sys.UI.DomEvent.addHandlers = function Sys$UI$DomEvent$addHandlers(element, events, handlerOwner) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"}, + {name: "events", type: Object}, + {name: "handlerOwner", optional: true} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + for (var name in events) { + var handler = events[name]; + if (typeof(handler) !== 'function') throw Error.invalidOperation(Sys.Res.cantAddNonFunctionhandler); + if (handlerOwner) { + handler = Function.createDelegate(handlerOwner, handler); + } + $addHandler(element, name, handler); + } +} +var $clearHandlers = Sys.UI.DomEvent.clearHandlers = function Sys$UI$DomEvent$clearHandlers(element) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + if (element._events) { + var cache = element._events; + for (var name in cache) { + var handlers = cache[name]; + for (var i = handlers.length - 1; i >= 0; i--) { + $removeHandler(element, name, handlers[i].handler); + } + } + element._events = null; + } +} +var $removeHandler = Sys.UI.DomEvent.removeHandler = function Sys$UI$DomEvent$removeHandler(element, eventName, handler) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element"}, + {name: "eventName", type: String}, + {name: "handler", type: Function} + ]); + if (e) throw e; + Sys.UI.DomEvent._ensureDomNode(element); + var browserHandler = null; + if ((typeof(element._events) !== 'object') || (element._events == null)) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); + var cache = element._events[eventName]; + if (!(cache instanceof Array)) throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); + for (var i = 0, l = cache.length; i < l; i++) { + if (cache[i].handler === handler) { + browserHandler = cache[i].browserHandler; + break; + } + } + if (typeof(browserHandler) !== 'function') throw Error.invalidOperation(Sys.Res.eventHandlerInvalid); + if (element.removeEventListener) { + element.removeEventListener(eventName, browserHandler, false); + } + else if (element.detachEvent) { + element.detachEvent('on' + eventName, browserHandler); + } + cache.splice(i, 1); +} +Sys.UI.DomEvent._ensureDomNode = function Sys$UI$DomEvent$_ensureDomNode(element) { + if (element.tagName && (element.tagName === "SCRIPT")) return; + + var doc = element.ownerDocument || element.document || element; + if ((typeof(element.document) !== 'object') && (element != doc) && (typeof(element.nodeType) !== 'number')) { + throw Error.argument("element", Sys.Res.argumentDomNode); + } +} + +Sys.UI.DomElement = function Sys$UI$DomElement() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.DomElement.registerClass('Sys.UI.DomElement'); +Sys.UI.DomElement.addCssClass = function Sys$UI$DomElement$addCssClass(element, className) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + if (!Sys.UI.DomElement.containsCssClass(element, className)) { + if (element.className === '') { + element.className = className; + } + else { + element.className += ' ' + className; + } + } +} +Sys.UI.DomElement.containsCssClass = function Sys$UI$DomElement$containsCssClass(element, className) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + return Array.contains(element.className.split(' '), className); +} +Sys.UI.DomElement.getBounds = function Sys$UI$DomElement$getBounds(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + var offset = Sys.UI.DomElement.getLocation(element); + return new Sys.UI.Bounds(offset.x, offset.y, element.offsetWidth || 0, element.offsetHeight || 0); +} +var $get = Sys.UI.DomElement.getElementById = function Sys$UI$DomElement$getElementById(id, element) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "element", mayBeNull: true, domElement: true, optional: true} + ]); + if (e) throw e; + if (!element) return document.getElementById(id); + if (element.getElementById) return element.getElementById(id); + var nodeQueue = []; + var childNodes = element.childNodes; + for (var i = 0; i < childNodes.length; i++) { + var node = childNodes[i]; + if (node.nodeType == 1) { + nodeQueue[nodeQueue.length] = node; + } + } + while (nodeQueue.length) { + node = nodeQueue.shift(); + if (node.id == id) { + return node; + } + childNodes = node.childNodes; + for (i = 0; i < childNodes.length; i++) { + node = childNodes[i]; + if (node.nodeType == 1) { + nodeQueue[nodeQueue.length] = node; + } + } + } + return null; +} +switch(Sys.Browser.agent) { + case Sys.Browser.InternetExplorer: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if (element.self || element.nodeType === 9) return new Sys.UI.Point(0,0); + var clientRect = element.getBoundingClientRect(); + if (!clientRect) { + return new Sys.UI.Point(0,0); + } + var documentElement = element.ownerDocument.documentElement; + var offsetX = clientRect.left - 2 + documentElement.scrollLeft, + offsetY = clientRect.top - 2 + documentElement.scrollTop; + + try { + var f = element.ownerDocument.parentWindow.frameElement || null; + if (f) { + var offset = (f.frameBorder === "0" || f.frameBorder === "no") ? 2 : 0; + offsetX += offset; + offsetY += offset; + } + } + catch(ex) { + } + + return new Sys.UI.Point(offsetX, offsetY); + } + break; + case Sys.Browser.Safari: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); + var offsetX = 0; + var offsetY = 0; + var previous = null; + var previousStyle = null; + var currentStyle; + for (var parent = element; parent; previous = parent, previousStyle = currentStyle, parent = parent.offsetParent) { + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + var tagName = parent.tagName; + if ((parent.offsetLeft || parent.offsetTop) && + ((tagName !== "BODY") || (!previousStyle || previousStyle.position !== "absolute"))) { + offsetX += parent.offsetLeft; + offsetY += parent.offsetTop; + } + } + currentStyle = Sys.UI.DomElement._getCurrentStyle(element); + var elementPosition = currentStyle ? currentStyle.position : null; + if (!elementPosition || (elementPosition !== "absolute")) { + for (var parent = element.parentNode; parent; parent = parent.parentNode) { + tagName = parent.tagName; + if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop)) { + offsetX -= (parent.scrollLeft || 0); + offsetY -= (parent.scrollTop || 0); + } + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + var parentPosition = currentStyle ? currentStyle.position : null; + if (parentPosition && (parentPosition === "absolute")) break; + } + } + return new Sys.UI.Point(offsetX, offsetY); + } + break; + case Sys.Browser.Opera: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); + var offsetX = 0; + var offsetY = 0; + var previous = null; + for (var parent = element; parent; previous = parent, parent = parent.offsetParent) { + var tagName = parent.tagName; + offsetX += parent.offsetLeft || 0; + offsetY += parent.offsetTop || 0; + } + var elementPosition = element.style.position; + var elementPositioned = elementPosition && (elementPosition !== "static"); + for (var parent = element.parentNode; parent; parent = parent.parentNode) { + tagName = parent.tagName; + if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop) && + ((elementPositioned && + ((parent.style.overflow === "scroll") || (parent.style.overflow === "auto"))))) { + offsetX -= (parent.scrollLeft || 0); + offsetY -= (parent.scrollTop || 0); + } + var parentPosition = (parent && parent.style) ? parent.style.position : null; + elementPositioned = elementPositioned || (parentPosition && (parentPosition !== "static")); + } + return new Sys.UI.Point(offsetX, offsetY); + } + break; + default: + Sys.UI.DomElement.getLocation = function Sys$UI$DomElement$getLocation(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if ((element.window && (element.window === element)) || element.nodeType === 9) return new Sys.UI.Point(0,0); + var offsetX = 0; + var offsetY = 0; + var previous = null; + var previousStyle = null; + var currentStyle = null; + for (var parent = element; parent; previous = parent, previousStyle = currentStyle, parent = parent.offsetParent) { + var tagName = parent.tagName; + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + if ((parent.offsetLeft || parent.offsetTop) && + !((tagName === "BODY") && + (!previousStyle || previousStyle.position !== "absolute"))) { + offsetX += parent.offsetLeft; + offsetY += parent.offsetTop; + } + if (previous !== null && currentStyle) { + if ((tagName !== "TABLE") && (tagName !== "TD") && (tagName !== "HTML")) { + offsetX += parseInt(currentStyle.borderLeftWidth) || 0; + offsetY += parseInt(currentStyle.borderTopWidth) || 0; + } + if (tagName === "TABLE" && + (currentStyle.position === "relative" || currentStyle.position === "absolute")) { + offsetX += parseInt(currentStyle.marginLeft) || 0; + offsetY += parseInt(currentStyle.marginTop) || 0; + } + } + } + currentStyle = Sys.UI.DomElement._getCurrentStyle(element); + var elementPosition = currentStyle ? currentStyle.position : null; + if (!elementPosition || (elementPosition !== "absolute")) { + for (var parent = element.parentNode; parent; parent = parent.parentNode) { + tagName = parent.tagName; + if ((tagName !== "BODY") && (tagName !== "HTML") && (parent.scrollLeft || parent.scrollTop)) { + offsetX -= (parent.scrollLeft || 0); + offsetY -= (parent.scrollTop || 0); + currentStyle = Sys.UI.DomElement._getCurrentStyle(parent); + if (currentStyle) { + offsetX += parseInt(currentStyle.borderLeftWidth) || 0; + offsetY += parseInt(currentStyle.borderTopWidth) || 0; + } + } + } + } + return new Sys.UI.Point(offsetX, offsetY); + } + break; +} +Sys.UI.DomElement.removeCssClass = function Sys$UI$DomElement$removeCssClass(element, className) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + var currentClassName = ' ' + element.className + ' '; + var index = currentClassName.indexOf(' ' + className + ' '); + if (index >= 0) { + element.className = (currentClassName.substr(0, index) + ' ' + + currentClassName.substring(index + className.length + 1, currentClassName.length)).trim(); + } +} +Sys.UI.DomElement.setLocation = function Sys$UI$DomElement$setLocation(element, x, y) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "x", type: Number, integer: true}, + {name: "y", type: Number, integer: true} + ]); + if (e) throw e; + var style = element.style; + style.position = 'absolute'; + style.left = x + "px"; + style.top = y + "px"; +} +Sys.UI.DomElement.toggleCssClass = function Sys$UI$DomElement$toggleCssClass(element, className) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "className", type: String} + ]); + if (e) throw e; + if (Sys.UI.DomElement.containsCssClass(element, className)) { + Sys.UI.DomElement.removeCssClass(element, className); + } + else { + Sys.UI.DomElement.addCssClass(element, className); + } +} +Sys.UI.DomElement.getVisibilityMode = function Sys$UI$DomElement$getVisibilityMode(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + return (element._visibilityMode === Sys.UI.VisibilityMode.hide) ? + Sys.UI.VisibilityMode.hide : + Sys.UI.VisibilityMode.collapse; +} +Sys.UI.DomElement.setVisibilityMode = function Sys$UI$DomElement$setVisibilityMode(element, value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "value", type: Sys.UI.VisibilityMode} + ]); + if (e) throw e; + Sys.UI.DomElement._ensureOldDisplayMode(element); + if (element._visibilityMode !== value) { + element._visibilityMode = value; + if (Sys.UI.DomElement.getVisible(element) === false) { + if (element._visibilityMode === Sys.UI.VisibilityMode.hide) { + element.style.display = element._oldDisplayMode; + } + else { + element.style.display = 'none'; + } + } + element._visibilityMode = value; + } +} +Sys.UI.DomElement.getVisible = function Sys$UI$DomElement$getVisible(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + var style = element.currentStyle || Sys.UI.DomElement._getCurrentStyle(element); + if (!style) return true; + return (style.visibility !== 'hidden') && (style.display !== 'none'); +} +Sys.UI.DomElement.setVisible = function Sys$UI$DomElement$setVisible(element, value) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "value", type: Boolean} + ]); + if (e) throw e; + if (value !== Sys.UI.DomElement.getVisible(element)) { + Sys.UI.DomElement._ensureOldDisplayMode(element); + element.style.visibility = value ? 'visible' : 'hidden'; + if (value || (element._visibilityMode === Sys.UI.VisibilityMode.hide)) { + element.style.display = element._oldDisplayMode; + } + else { + element.style.display = 'none'; + } + } +} +Sys.UI.DomElement._ensureOldDisplayMode = function Sys$UI$DomElement$_ensureOldDisplayMode(element) { + if (!element._oldDisplayMode) { + var style = element.currentStyle || Sys.UI.DomElement._getCurrentStyle(element); + element._oldDisplayMode = style ? style.display : null; + if (!element._oldDisplayMode || element._oldDisplayMode === 'none') { + switch(element.tagName.toUpperCase()) { + case 'DIV': case 'P': case 'ADDRESS': case 'BLOCKQUOTE': case 'BODY': case 'COL': + case 'COLGROUP': case 'DD': case 'DL': case 'DT': case 'FIELDSET': case 'FORM': + case 'H1': case 'H2': case 'H3': case 'H4': case 'H5': case 'H6': case 'HR': + case 'IFRAME': case 'LEGEND': case 'OL': case 'PRE': case 'TABLE': case 'TD': + case 'TH': case 'TR': case 'UL': + element._oldDisplayMode = 'block'; + break; + case 'LI': + element._oldDisplayMode = 'list-item'; + break; + default: + element._oldDisplayMode = 'inline'; + } + } + } +} +Sys.UI.DomElement._getWindow = function Sys$UI$DomElement$_getWindow(element) { + var doc = element.ownerDocument || element.document || element; + return doc.defaultView || doc.parentWindow; +} +Sys.UI.DomElement._getCurrentStyle = function Sys$UI$DomElement$_getCurrentStyle(element) { + if (element.nodeType === 3) return null; + var w = Sys.UI.DomElement._getWindow(element); + if (element.documentElement) element = element.documentElement; + var computedStyle = (w && (element !== w) && w.getComputedStyle) ? + w.getComputedStyle(element, null) : + element.currentStyle || element.style; + if (!computedStyle && (Sys.Browser.agent === Sys.Browser.Safari) && element.style) { + var oldDisplay = element.style.display; + var oldPosition = element.style.position; + element.style.position = 'absolute'; + element.style.display = 'block'; + var style = w.getComputedStyle(element, null); + element.style.display = oldDisplay; + element.style.position = oldPosition; + computedStyle = {}; + for (var n in style) { + computedStyle[n] = style[n]; + } + computedStyle.display = 'none'; + } + return computedStyle; +} + +Sys.IContainer = function Sys$IContainer() { + throw Error.notImplemented(); +} + function Sys$IContainer$addComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$IContainer$removeComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$IContainer$findComponent(id) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$IContainer$getComponents() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } +Sys.IContainer.prototype = { + addComponent: Sys$IContainer$addComponent, + removeComponent: Sys$IContainer$removeComponent, + findComponent: Sys$IContainer$findComponent, + getComponents: Sys$IContainer$getComponents +} +Sys.IContainer.registerInterface("Sys.IContainer"); + +Sys._ScriptLoader = function Sys$_ScriptLoader() { + this._scriptsToLoad = null; + this._scriptLoadedDelegate = Function.createDelegate(this, this._scriptLoadedHandler); +} + function Sys$_ScriptLoader$dispose() { + this._stopLoading(); + if(this._events) { + delete this._events; + } + this._scriptLoadedDelegate = null; + } + function Sys$_ScriptLoader$loadScripts(scriptTimeout, allScriptsLoadedCallback, scriptLoadFailedCallback, scriptLoadTimeoutCallback) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptTimeout", type: Number, integer: true}, + {name: "allScriptsLoadedCallback", type: Function, mayBeNull: true}, + {name: "scriptLoadFailedCallback", type: Function, mayBeNull: true}, + {name: "scriptLoadTimeoutCallback", type: Function, mayBeNull: true} + ]); + if (e) throw e; + if(this._loading) { + throw Error.invalidOperation(Sys.Res.scriptLoaderAlreadyLoading); + } + this._loading = true; + this._allScriptsLoadedCallback = allScriptsLoadedCallback; + this._scriptLoadFailedCallback = scriptLoadFailedCallback; + this._scriptLoadTimeoutCallback = scriptLoadTimeoutCallback; + + this._loadScriptsInternal(); + } + function Sys$_ScriptLoader$notifyScriptLoaded() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + + if(!this._loading) { + return; + } + this._currentTask._notified++; + + if(Sys.Browser.agent === Sys.Browser.Safari) { + if(this._currentTask._notified === 1) { + window.setTimeout(Function.createDelegate(this, function() { + this._scriptLoadedHandler(this._currentTask.get_scriptElement(), true); + }), 0); + } + } + } + function Sys$_ScriptLoader$queueCustomScriptTag(scriptAttributes) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptAttributes"} + ]); + if (e) throw e; + if(!this._scriptsToLoad) { + this._scriptsToLoad = []; + } + Array.add(this._scriptsToLoad, scriptAttributes); + } + function Sys$_ScriptLoader$queueScriptBlock(scriptContent) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptContent", type: String} + ]); + if (e) throw e; + if(!this._scriptsToLoad) { + this._scriptsToLoad = []; + } + Array.add(this._scriptsToLoad, {text: scriptContent}); + } + function Sys$_ScriptLoader$queueScriptReference(scriptUrl) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptUrl", type: String} + ]); + if (e) throw e; + if(!this._scriptsToLoad) { + this._scriptsToLoad = []; + } + Array.add(this._scriptsToLoad, {src: scriptUrl}); + } + function Sys$_ScriptLoader$_createScriptElement(queuedScript) { + var scriptElement = document.createElement('SCRIPT'); + scriptElement.type = 'text/javascript'; + for (var attr in queuedScript) { + scriptElement[attr] = queuedScript[attr]; + } + + return scriptElement; + } + function Sys$_ScriptLoader$_loadScriptsInternal() { + if (this._scriptsToLoad && this._scriptsToLoad.length > 0) { + var nextScript = Array.dequeue(this._scriptsToLoad); + var scriptElement = this._createScriptElement(nextScript); + + if (scriptElement.text && Sys.Browser.agent === Sys.Browser.Safari) { + scriptElement.innerHTML = scriptElement.text; + delete scriptElement.text; + } + if (typeof(nextScript.src) === "string") { + this._currentTask = new Sys._ScriptLoaderTask(scriptElement, this._scriptLoadedDelegate); + this._currentTask.execute(); + } + else { + document.getElementsByTagName('HEAD')[0].appendChild(scriptElement); + + var scriptLoader = this; + window.setTimeout(function() { + Sys._ScriptLoader._clearScript(scriptElement); + scriptLoader._loadScriptsInternal(); + }, 0); + } + } + else { + var callback = this._allScriptsLoadedCallback; + this._stopLoading(); + if(callback) { + callback(this); + } + } + } + function Sys$_ScriptLoader$_raiseError(multipleCallbacks) { + var callback = this._scriptLoadFailedCallback; + var scriptElement = this._currentTask.get_scriptElement(); + this._stopLoading(); + + if(callback) { + callback(this, scriptElement, multipleCallbacks); + } + else { + throw Sys._ScriptLoader._errorScriptLoadFailed(scriptElement.src, multipleCallbacks); + } + } + function Sys$_ScriptLoader$_scriptLoadedHandler(scriptElement, loaded) { + if(loaded && this._currentTask._notified) { + if(this._currentTask._notified > 1) { + this._raiseError(true); + } + else { + Array.add(Sys._ScriptLoader._getLoadedScripts(), scriptElement.src); + this._currentTask.dispose(); + this._currentTask = null; + this._loadScriptsInternal(); + } + } + else { + this._raiseError(false); + } + } + function Sys$_ScriptLoader$_scriptLoadTimeoutHandler() { + var callback = this._scriptLoadTimeoutCallback; + this._stopLoading(); + if(callback) { + callback(this); + } + } + function Sys$_ScriptLoader$_stopLoading() { + if(this._timeoutCookie) { + window.clearTimeout(this._timeoutCookie); + this._timeoutCookie = null; + } + if(this._currentTask) { + this._currentTask.dispose(); + this._currentTask = null; + } + this._scriptsToLoad = null; + this._loading = null; + + this._allScriptsLoadedCallback = null; + this._scriptLoadFailedCallback = null; + this._scriptLoadTimeoutCallback = null; + } +Sys._ScriptLoader.prototype = { + dispose: Sys$_ScriptLoader$dispose, + loadScripts: Sys$_ScriptLoader$loadScripts, + notifyScriptLoaded: Sys$_ScriptLoader$notifyScriptLoaded, + queueCustomScriptTag: Sys$_ScriptLoader$queueCustomScriptTag, + queueScriptBlock: Sys$_ScriptLoader$queueScriptBlock, + queueScriptReference: Sys$_ScriptLoader$queueScriptReference, + _createScriptElement: Sys$_ScriptLoader$_createScriptElement, + _loadScriptsInternal: Sys$_ScriptLoader$_loadScriptsInternal, + _raiseError: Sys$_ScriptLoader$_raiseError, + _scriptLoadedHandler: Sys$_ScriptLoader$_scriptLoadedHandler, + _scriptLoadTimeoutHandler: Sys$_ScriptLoader$_scriptLoadTimeoutHandler, + _stopLoading: Sys$_ScriptLoader$_stopLoading +} +Sys._ScriptLoader.registerClass('Sys._ScriptLoader', null, Sys.IDisposable); +Sys._ScriptLoader.getInstance = function Sys$_ScriptLoader$getInstance() { + var sl = Sys._ScriptLoader._activeInstance; + if(!sl) { + sl = Sys._ScriptLoader._activeInstance = new Sys._ScriptLoader(); + } + return sl; +} +Sys._ScriptLoader.isScriptLoaded = function Sys$_ScriptLoader$isScriptLoaded(scriptSrc) { + var dummyScript = document.createElement('script'); + dummyScript.src = scriptSrc; + return Array.contains(Sys._ScriptLoader._getLoadedScripts(), dummyScript.src); +} +Sys._ScriptLoader.readLoadedScripts = function Sys$_ScriptLoader$readLoadedScripts() { + if(!Sys._ScriptLoader._referencedScripts) { + var referencedScripts = Sys._ScriptLoader._referencedScripts = []; + var existingScripts = document.getElementsByTagName('SCRIPT'); + for (i = existingScripts.length - 1; i >= 0; i--) { + var scriptNode = existingScripts[i]; + var scriptSrc = scriptNode.src; + if (scriptSrc.length) { + if (!Array.contains(referencedScripts, scriptSrc)) { + Array.add(referencedScripts, scriptSrc); + } + } + } + } +} +Sys._ScriptLoader._clearScript = function Sys$_ScriptLoader$_clearScript(scriptElement) { + if (!Sys.Debug.isDebug) { + scriptElement.parentNode.removeChild(scriptElement); + } +} +Sys._ScriptLoader._errorScriptLoadFailed = function Sys$_ScriptLoader$_errorScriptLoadFailed(scriptUrl, multipleCallbacks) { + var errorMessage; + if(multipleCallbacks) { + errorMessage = Sys.Res.scriptLoadMultipleCallbacks; + } + else { + errorMessage = Sys.Res.scriptLoadFailedDebug; + } + var displayMessage = "Sys.ScriptLoadFailedException: " + String.format(errorMessage, scriptUrl); + var e = Error.create(displayMessage, {name: 'Sys.ScriptLoadFailedException', 'scriptUrl': scriptUrl }); + e.popStackFrame(); + return e; +} +Sys._ScriptLoader._getLoadedScripts = function Sys$_ScriptLoader$_getLoadedScripts() { + if(!Sys._ScriptLoader._referencedScripts) { + Sys._ScriptLoader._referencedScripts = []; + Sys._ScriptLoader.readLoadedScripts(); + } + return Sys._ScriptLoader._referencedScripts; +} + +Sys._ScriptLoaderTask = function Sys$_ScriptLoaderTask(scriptElement, completedCallback) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "scriptElement", domElement: true}, + {name: "completedCallback", type: Function} + ]); + if (e) throw e; + this._scriptElement = scriptElement; + this._completedCallback = completedCallback; + this._notified = 0; +} + function Sys$_ScriptLoaderTask$get_scriptElement() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._scriptElement; + } + function Sys$_ScriptLoaderTask$dispose() { + if(this._disposed) { + return; + } + this._disposed = true; + this._removeScriptElementHandlers(); + Sys._ScriptLoader._clearScript(this._scriptElement); + this._scriptElement = null; + } + function Sys$_ScriptLoaderTask$execute() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._addScriptElementHandlers(); + document.getElementsByTagName('HEAD')[0].appendChild(this._scriptElement); + } + function Sys$_ScriptLoaderTask$_addScriptElementHandlers() { + this._scriptLoadDelegate = Function.createDelegate(this, this._scriptLoadHandler); + + if (Sys.Browser.agent !== Sys.Browser.InternetExplorer) { + this._scriptElement.readyState = 'loaded'; + $addHandler(this._scriptElement, 'load', this._scriptLoadDelegate); + } + else { + $addHandler(this._scriptElement, 'readystatechange', this._scriptLoadDelegate); + } + if (this._scriptElement.addEventListener) { + this._scriptErrorDelegate = Function.createDelegate(this, this._scriptErrorHandler); + this._scriptElement.addEventListener('error', this._scriptErrorDelegate, false); + } + } + function Sys$_ScriptLoaderTask$_removeScriptElementHandlers() { + if(this._scriptLoadDelegate) { + var scriptElement = this.get_scriptElement(); + if (Sys.Browser.agent !== Sys.Browser.InternetExplorer) { + $removeHandler(scriptElement, 'load', this._scriptLoadDelegate); + } + else { + $removeHandler(scriptElement, 'readystatechange', this._scriptLoadDelegate); + } + if (this._scriptErrorDelegate) { + this._scriptElement.removeEventListener('error', this._scriptErrorDelegate, false); + this._scriptErrorDelegate = null; + } + this._scriptLoadDelegate = null; + } + } + function Sys$_ScriptLoaderTask$_scriptErrorHandler() { + if(this._disposed) { + return; + } + + this._completedCallback(this.get_scriptElement(), false); + } + function Sys$_ScriptLoaderTask$_scriptLoadHandler() { + if(this._disposed) { + return; + } + var scriptElement = this.get_scriptElement(); + if ((scriptElement.readyState !== 'loaded') && + (scriptElement.readyState !== 'complete')) { + return; + } + + var _this = this; + window.setTimeout(function() { + _this._completedCallback(scriptElement, true); + }, 0); + } +Sys._ScriptLoaderTask.prototype = { + get_scriptElement: Sys$_ScriptLoaderTask$get_scriptElement, + dispose: Sys$_ScriptLoaderTask$dispose, + execute: Sys$_ScriptLoaderTask$execute, + _addScriptElementHandlers: Sys$_ScriptLoaderTask$_addScriptElementHandlers, + _removeScriptElementHandlers: Sys$_ScriptLoaderTask$_removeScriptElementHandlers, + _scriptErrorHandler: Sys$_ScriptLoaderTask$_scriptErrorHandler, + _scriptLoadHandler: Sys$_ScriptLoaderTask$_scriptLoadHandler +} +Sys._ScriptLoaderTask.registerClass("Sys._ScriptLoaderTask", null, Sys.IDisposable); + +Sys.ApplicationLoadEventArgs = function Sys$ApplicationLoadEventArgs(components, isPartialLoad) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "components", type: Array, elementType: Sys.Component}, + {name: "isPartialLoad", type: Boolean} + ]); + if (e) throw e; + Sys.ApplicationLoadEventArgs.initializeBase(this); + this._components = components; + this._isPartialLoad = isPartialLoad; +} + + function Sys$ApplicationLoadEventArgs$get_components() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._components; + } + function Sys$ApplicationLoadEventArgs$get_isPartialLoad() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._isPartialLoad; + } +Sys.ApplicationLoadEventArgs.prototype = { + get_components: Sys$ApplicationLoadEventArgs$get_components, + get_isPartialLoad: Sys$ApplicationLoadEventArgs$get_isPartialLoad +} +Sys.ApplicationLoadEventArgs.registerClass('Sys.ApplicationLoadEventArgs', Sys.EventArgs); + +Sys._Application = function Sys$_Application() { + Sys._Application.initializeBase(this); + this._disposableObjects = []; + this._components = {}; + this._createdComponents = []; + this._secondPassComponents = []; + this._unloadHandlerDelegate = Function.createDelegate(this, this._unloadHandler); + this._loadHandlerDelegate = Function.createDelegate(this, this._loadHandler); + Sys.UI.DomEvent.addHandler(window, "unload", this._unloadHandlerDelegate); + Sys.UI.DomEvent.addHandler(window, "load", this._loadHandlerDelegate); +} + function Sys$_Application$get_isCreatingComponents() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._creatingComponents; + } + function Sys$_Application$add_load(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("load", handler); + } + function Sys$_Application$remove_load(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("load", handler); + } + function Sys$_Application$add_init(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + if (this._initialized) { + handler(this, Sys.EventArgs.Empty); + } + else { + this.get_events().addHandler("init", handler); + } + } + function Sys$_Application$remove_init(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("init", handler); + } + function Sys$_Application$add_unload(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().addHandler("unload", handler); + } + function Sys$_Application$remove_unload(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this.get_events().removeHandler("unload", handler); + } + function Sys$_Application$addComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + var id = component.get_id(); + if (!id) throw Error.invalidOperation(Sys.Res.cantAddWithoutId); + if (typeof(this._components[id]) !== 'undefined') throw Error.invalidOperation(String.format(Sys.Res.appDuplicateComponent, id)); + this._components[id] = component; + } + function Sys$_Application$beginCreateComponents() { + this._creatingComponents = true; + } + function Sys$_Application$dispose() { + if (!this._disposing) { + this._disposing = true; + if (window.pageUnload) { + window.pageUnload(this, Sys.EventArgs.Empty); + } + var unloadHandler = this.get_events().getHandler("unload"); + if (unloadHandler) { + unloadHandler(this, Sys.EventArgs.Empty); + } + var disposableObjects = Array.clone(this._disposableObjects); + for (var i = 0, l = disposableObjects.length; i < l; i++) { + disposableObjects[i].dispose(); + } + Array.clear(this._disposableObjects); + Sys.UI.DomEvent.removeHandler(window, "unload", this._unloadHandlerDelegate); + if(this._loadHandlerDelegate) { + Sys.UI.DomEvent.removeHandler(window, "load", this._loadHandlerDelegate); + this._loadHandlerDelegate = null; + } + var sl = Sys._ScriptLoader.getInstance(); + if(sl) { + sl.dispose(); + } + Sys._Application.callBaseMethod(this, 'dispose'); + } + } + function Sys$_Application$endCreateComponents() { + var components = this._secondPassComponents; + for (var i = 0, l = components.length; i < l; i++) { + var component = components[i].component; + Sys$Component$_setReferences(component, components[i].references); + component.endUpdate(); + } + this._secondPassComponents = []; + this._creatingComponents = false; + } + function Sys$_Application$findComponent(id, parent) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "id", type: String}, + {name: "parent", mayBeNull: true, optional: true} + ]); + if (e) throw e; + return (parent ? + ((Sys.IContainer.isInstanceOfType(parent)) ? + parent.findComponent(id) : + parent[id] || null) : + Sys.Application._components[id] || null); + } + function Sys$_Application$getComponents() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var res = []; + var components = this._components; + for (var name in components) { + res[res.length] = components[name]; + } + return res; + } + function Sys$_Application$initialize() { + if(!this._initialized && !this._initializing) { + this._initializing = true; + window.setTimeout(Function.createDelegate(this, this._doInitialize), 0); + } + } + function Sys$_Application$notifyScriptLoaded() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var sl = Sys._ScriptLoader.getInstance(); + if(sl) { + sl.notifyScriptLoaded(); + } + } + function Sys$_Application$registerDisposableObject(object) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", type: Sys.IDisposable} + ]); + if (e) throw e; + if (!this._disposing) { + this._disposableObjects[this._disposableObjects.length] = object; + } + } + function Sys$_Application$raiseLoad() { + var h = this.get_events().getHandler("load"); + var args = new Sys.ApplicationLoadEventArgs(Array.clone(this._createdComponents), !this._initializing); + if (h) { + h(this, args); + } + if (window.pageLoad) { + window.pageLoad(this, args); + } + this._createdComponents = []; + } + function Sys$_Application$removeComponent(component) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "component", type: Sys.Component} + ]); + if (e) throw e; + var id = component.get_id(); + if (id) delete this._components[id]; + } + function Sys$_Application$unregisterDisposableObject(object) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", type: Sys.IDisposable} + ]); + if (e) throw e; + if (!this._disposing) { + Array.remove(this._disposableObjects, object); + } + } + function Sys$_Application$_addComponentToSecondPass(component, references) { + this._secondPassComponents[this._secondPassComponents.length] = {component: component, references: references}; + } + function Sys$_Application$_doInitialize() { + Sys._Application.callBaseMethod(this, 'initialize'); + var handler = this.get_events().getHandler("init"); + if (handler) { + this.beginCreateComponents(); + handler(this, Sys.EventArgs.Empty); + this.endCreateComponents(); + } + this.raiseLoad(); + this._initializing = false; + } + function Sys$_Application$_loadHandler() { + if(this._loadHandlerDelegate) { + Sys.UI.DomEvent.removeHandler(window, "load", this._loadHandlerDelegate); + this._loadHandlerDelegate = null; + } + this.initialize(); + } + function Sys$_Application$_unloadHandler(event) { + this.dispose(); + } +Sys._Application.prototype = { + _creatingComponents: false, + _disposing: false, + get_isCreatingComponents: Sys$_Application$get_isCreatingComponents, + add_load: Sys$_Application$add_load, + remove_load: Sys$_Application$remove_load, + add_init: Sys$_Application$add_init, + remove_init: Sys$_Application$remove_init, + add_unload: Sys$_Application$add_unload, + remove_unload: Sys$_Application$remove_unload, + addComponent: Sys$_Application$addComponent, + beginCreateComponents: Sys$_Application$beginCreateComponents, + dispose: Sys$_Application$dispose, + endCreateComponents: Sys$_Application$endCreateComponents, + findComponent: Sys$_Application$findComponent, + getComponents: Sys$_Application$getComponents, + initialize: Sys$_Application$initialize, + notifyScriptLoaded: Sys$_Application$notifyScriptLoaded, + registerDisposableObject: Sys$_Application$registerDisposableObject, + raiseLoad: Sys$_Application$raiseLoad, + removeComponent: Sys$_Application$removeComponent, + unregisterDisposableObject: Sys$_Application$unregisterDisposableObject, + _addComponentToSecondPass: Sys$_Application$_addComponentToSecondPass, + _doInitialize: Sys$_Application$_doInitialize, + _loadHandler: Sys$_Application$_loadHandler, + _unloadHandler: Sys$_Application$_unloadHandler +} +Sys._Application.registerClass('Sys._Application', Sys.Component, Sys.IContainer); +Sys.Application = new Sys._Application(); +var $find = Sys.Application.findComponent; +Type.registerNamespace('Sys.Net'); + +Sys.Net.WebRequestExecutor = function Sys$Net$WebRequestExecutor() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._webRequest = null; + this._resultObject = null; +} + function Sys$Net$WebRequestExecutor$get_webRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._webRequest; + } + function Sys$Net$WebRequestExecutor$_set_webRequest(value) { + if (this.get_started()) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'set_webRequest')); + } + this._webRequest = value; + } + function Sys$Net$WebRequestExecutor$get_started() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_responseAvailable() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_timedOut() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_aborted() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_responseData() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_statusCode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_statusText() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_xml() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$get_object() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._resultObject) { + this._resultObject = Sys.Serialization.JavaScriptSerializer.deserialize(this.get_responseData()); + } + return this._resultObject; + } + function Sys$Net$WebRequestExecutor$executeRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$abort() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$getResponseHeader(header) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "header", type: String} + ]); + if (e) throw e; + throw Error.notImplemented(); + } + function Sys$Net$WebRequestExecutor$getAllResponseHeaders() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); + } +Sys.Net.WebRequestExecutor.prototype = { + get_webRequest: Sys$Net$WebRequestExecutor$get_webRequest, + _set_webRequest: Sys$Net$WebRequestExecutor$_set_webRequest, + get_started: Sys$Net$WebRequestExecutor$get_started, + get_responseAvailable: Sys$Net$WebRequestExecutor$get_responseAvailable, + get_timedOut: Sys$Net$WebRequestExecutor$get_timedOut, + get_aborted: Sys$Net$WebRequestExecutor$get_aborted, + get_responseData: Sys$Net$WebRequestExecutor$get_responseData, + get_statusCode: Sys$Net$WebRequestExecutor$get_statusCode, + get_statusText: Sys$Net$WebRequestExecutor$get_statusText, + get_xml: Sys$Net$WebRequestExecutor$get_xml, + get_object: Sys$Net$WebRequestExecutor$get_object, + executeRequest: Sys$Net$WebRequestExecutor$executeRequest, + abort: Sys$Net$WebRequestExecutor$abort, + getResponseHeader: Sys$Net$WebRequestExecutor$getResponseHeader, + getAllResponseHeaders: Sys$Net$WebRequestExecutor$getAllResponseHeaders +} +Sys.Net.WebRequestExecutor.registerClass('Sys.Net.WebRequestExecutor'); + +Sys.Net.XMLDOM = function Sys$Net$XMLDOM(markup) { + if (!window.DOMParser) { + var progIDs = [ 'Msxml2.DOMDocument.3.0', 'Msxml2.DOMDocument' ]; + for (var i = 0, l = progIDs.length; i < l; i++) { + try { + var xmlDOM = new ActiveXObject(progIDs[i]); + xmlDOM.async = false; + xmlDOM.loadXML(markup); + xmlDOM.setProperty('SelectionLanguage', 'XPath'); + return xmlDOM; + } + catch (ex) { + } + } + } + else { + try { + var domParser = new window.DOMParser(); + return domParser.parseFromString(markup, 'text/xml'); + } + catch (ex) { + } + } + return null; +} +Sys.Net.XMLHttpExecutor = function Sys$Net$XMLHttpExecutor() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Net.XMLHttpExecutor.initializeBase(this); + var _this = this; + this._xmlHttpRequest = null; + this._webRequest = null; + this._responseAvailable = false; + this._timedOut = false; + this._timer = null; + this._aborted = false; + this._started = false; + this._onReadyStateChange = function this$_onReadyStateChange() { + + if (_this._xmlHttpRequest.readyState === 4 ) { + try { + if (typeof(_this._xmlHttpRequest.status) === "undefined") { + return; + } + } + catch(ex) { + return; + } + + _this._clearTimer(); + _this._responseAvailable = true; + _this._webRequest.completed(Sys.EventArgs.Empty); + if (_this._xmlHttpRequest != null) { + _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; + _this._xmlHttpRequest = null; + } + } + } + this._clearTimer = function this$_clearTimer() { + if (_this._timer != null) { + window.clearTimeout(_this._timer); + _this._timer = null; + } + } + this._onTimeout = function this$_onTimeout() { + if (!_this._responseAvailable) { + _this._clearTimer(); + _this._timedOut = true; + _this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; + _this._xmlHttpRequest.abort(); + _this._webRequest.completed(Sys.EventArgs.Empty); + _this._xmlHttpRequest = null; + } + } +} + function Sys$Net$XMLHttpExecutor$get_timedOut() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._timedOut; + } + function Sys$Net$XMLHttpExecutor$get_started() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._started; + } + function Sys$Net$XMLHttpExecutor$get_responseAvailable() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._responseAvailable; + } + function Sys$Net$XMLHttpExecutor$get_aborted() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._aborted; + } + function Sys$Net$XMLHttpExecutor$executeRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._webRequest = this.get_webRequest(); + if (this._started) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'executeRequest')); + } + if (this._webRequest === null) { + throw Error.invalidOperation(Sys.Res.nullWebRequest); + } + var body = this._webRequest.get_body(); + var headers = this._webRequest.get_headers(); + this._xmlHttpRequest = new XMLHttpRequest(); + this._xmlHttpRequest.onreadystatechange = this._onReadyStateChange; + var verb = this._webRequest.get_httpVerb(); + this._xmlHttpRequest.open(verb, this._webRequest.getResolvedUrl(), true ); + if (headers) { + for (var header in headers) { + var val = headers[header]; + if (typeof(val) !== "function") + this._xmlHttpRequest.setRequestHeader(header, val); + } + } + if (verb.toLowerCase() === "post") { + if ((headers === null) || !headers['Content-Type']) { + this._xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8'); + } + if (!body) { + body = ""; + } + } + var timeout = this._webRequest.get_timeout(); + if (timeout > 0) { + this._timer = window.setTimeout(Function.createDelegate(this, this._onTimeout), timeout); + } + this._xmlHttpRequest.send(body); + this._started = true; + } + function Sys$Net$XMLHttpExecutor$getResponseHeader(header) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "header", type: String} + ]); + if (e) throw e; + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'getResponseHeader')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'getResponseHeader')); + } + var result; + try { + result = this._xmlHttpRequest.getResponseHeader(header); + } catch (e) { + } + if (!result) result = ""; + return result; + } + function Sys$Net$XMLHttpExecutor$getAllResponseHeaders() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'getAllResponseHeaders')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'getAllResponseHeaders')); + } + return this._xmlHttpRequest.getAllResponseHeaders(); + } + function Sys$Net$XMLHttpExecutor$get_responseData() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_responseData')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_responseData')); + } + return this._xmlHttpRequest.responseText; + } + function Sys$Net$XMLHttpExecutor$get_statusCode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusCode')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusCode')); + } + var result = 0; + try { + result = this._xmlHttpRequest.status; + } + catch(ex) { + } + return result; + } + function Sys$Net$XMLHttpExecutor$get_statusText() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusText')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusText')); + } + return this._xmlHttpRequest.statusText; + } + function Sys$Net$XMLHttpExecutor$get_xml() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._responseAvailable) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_xml')); + } + if (!this._xmlHttpRequest) { + throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_xml')); + } + var xml = this._xmlHttpRequest.responseXML; + if (!xml || !xml.documentElement) { + xml = Sys.Net.XMLDOM(this._xmlHttpRequest.responseText); + if (!xml || !xml.documentElement) + return null; + } + else if (navigator.userAgent.indexOf('MSIE') !== -1) { + xml.setProperty('SelectionLanguage', 'XPath'); + } + if (xml.documentElement.namespaceURI === "http://www.mozilla.org/newlayout/xml/parsererror.xml" && + xml.documentElement.tagName === "parsererror") { + return null; + } + + if (xml.documentElement.firstChild && xml.documentElement.firstChild.tagName === "parsererror") { + return null; + } + + return xml; + } + function Sys$Net$XMLHttpExecutor$abort() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._started) { + throw Error.invalidOperation(Sys.Res.cannotAbortBeforeStart); + } + if (this._aborted || this._responseAvailable || this._timedOut) + return; + this._aborted = true; + this._clearTimer(); + if (this._xmlHttpRequest && !this._responseAvailable) { + this._xmlHttpRequest.onreadystatechange = Function.emptyMethod; + this._xmlHttpRequest.abort(); + + this._xmlHttpRequest = null; + this._webRequest.completed(Sys.EventArgs.Empty); + } + } +Sys.Net.XMLHttpExecutor.prototype = { + get_timedOut: Sys$Net$XMLHttpExecutor$get_timedOut, + get_started: Sys$Net$XMLHttpExecutor$get_started, + get_responseAvailable: Sys$Net$XMLHttpExecutor$get_responseAvailable, + get_aborted: Sys$Net$XMLHttpExecutor$get_aborted, + executeRequest: Sys$Net$XMLHttpExecutor$executeRequest, + getResponseHeader: Sys$Net$XMLHttpExecutor$getResponseHeader, + getAllResponseHeaders: Sys$Net$XMLHttpExecutor$getAllResponseHeaders, + get_responseData: Sys$Net$XMLHttpExecutor$get_responseData, + get_statusCode: Sys$Net$XMLHttpExecutor$get_statusCode, + get_statusText: Sys$Net$XMLHttpExecutor$get_statusText, + get_xml: Sys$Net$XMLHttpExecutor$get_xml, + abort: Sys$Net$XMLHttpExecutor$abort +} +Sys.Net.XMLHttpExecutor.registerClass('Sys.Net.XMLHttpExecutor', Sys.Net.WebRequestExecutor); + +Sys.Net._WebRequestManager = function Sys$Net$_WebRequestManager() { + this._this = this; + this._defaultTimeout = 0; + this._defaultExecutorType = "Sys.Net.XMLHttpExecutor"; +} + function Sys$Net$_WebRequestManager$add_invokingRequest(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().addHandler("invokingRequest", handler); + } + function Sys$Net$_WebRequestManager$remove_invokingRequest(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().removeHandler("invokingRequest", handler); + } + function Sys$Net$_WebRequestManager$add_completedRequest(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().addHandler("completedRequest", handler); + } + function Sys$Net$_WebRequestManager$remove_completedRequest(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().removeHandler("completedRequest", handler); + } + function Sys$Net$_WebRequestManager$_get_eventHandlerList() { + if (!this._events) { + this._events = new Sys.EventHandlerList(); + } + return this._events; + } + function Sys$Net$_WebRequestManager$get_defaultTimeout() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultTimeout; + } + function Sys$Net$_WebRequestManager$set_defaultTimeout(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Number}]); + if (e) throw e; + if (value < 0) { + throw Error.argumentOutOfRange("value", value, Sys.Res.invalidTimeout); + } + this._defaultTimeout = value; + } + function Sys$Net$_WebRequestManager$get_defaultExecutorType() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultExecutorType; + } + function Sys$Net$_WebRequestManager$set_defaultExecutorType(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + this._defaultExecutorType = value; + } + function Sys$Net$_WebRequestManager$executeRequest(webRequest) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "webRequest", type: Sys.Net.WebRequest} + ]); + if (e) throw e; + var executor = webRequest.get_executor(); + if (!executor) { + var failed = false; + try { + var executorType = eval(this._defaultExecutorType); + executor = new executorType(); + } catch (e) { + failed = true; + } + if (failed || !Sys.Net.WebRequestExecutor.isInstanceOfType(executor) || !executor) { + throw Error.argument("defaultExecutorType", String.format(Sys.Res.invalidExecutorType, this._defaultExecutorType)); + } + webRequest.set_executor(executor); + } + if (executor.get_aborted()) { + return; + } + var evArgs = new Sys.Net.NetworkRequestEventArgs(webRequest); + var handler = this._get_eventHandlerList().getHandler("invokingRequest"); + if (handler) { + handler(this, evArgs); + } + if (!evArgs.get_cancel()) { + executor.executeRequest(); + } + } +Sys.Net._WebRequestManager.prototype = { + add_invokingRequest: Sys$Net$_WebRequestManager$add_invokingRequest, + remove_invokingRequest: Sys$Net$_WebRequestManager$remove_invokingRequest, + add_completedRequest: Sys$Net$_WebRequestManager$add_completedRequest, + remove_completedRequest: Sys$Net$_WebRequestManager$remove_completedRequest, + _get_eventHandlerList: Sys$Net$_WebRequestManager$_get_eventHandlerList, + get_defaultTimeout: Sys$Net$_WebRequestManager$get_defaultTimeout, + set_defaultTimeout: Sys$Net$_WebRequestManager$set_defaultTimeout, + get_defaultExecutorType: Sys$Net$_WebRequestManager$get_defaultExecutorType, + set_defaultExecutorType: Sys$Net$_WebRequestManager$set_defaultExecutorType, + executeRequest: Sys$Net$_WebRequestManager$executeRequest +} +Sys.Net._WebRequestManager.registerClass('Sys.Net._WebRequestManager'); +Sys.Net.WebRequestManager = new Sys.Net._WebRequestManager(); + +Sys.Net.NetworkRequestEventArgs = function Sys$Net$NetworkRequestEventArgs(webRequest) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "webRequest", type: Sys.Net.WebRequest} + ]); + if (e) throw e; + Sys.Net.NetworkRequestEventArgs.initializeBase(this); + this._webRequest = webRequest; +} + function Sys$Net$NetworkRequestEventArgs$get_webRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._webRequest; + } +Sys.Net.NetworkRequestEventArgs.prototype = { + get_webRequest: Sys$Net$NetworkRequestEventArgs$get_webRequest +} +Sys.Net.NetworkRequestEventArgs.registerClass('Sys.Net.NetworkRequestEventArgs', Sys.CancelEventArgs); + +Sys.Net.WebRequest = function Sys$Net$WebRequest() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + this._url = ""; + this._headers = { }; + this._body = null; + this._userContext = null; + this._httpVerb = null; + this._executor = null; + this._invokeCalled = false; + this._timeout = 0; +} + function Sys$Net$WebRequest$add_completed(handler) { + /// + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().addHandler("completed", handler); + } + function Sys$Net$WebRequest$remove_completed(handler) { + var e = Function._validateParams(arguments, [{name: "handler", type: Function}]); + if (e) throw e; + this._get_eventHandlerList().removeHandler("completed", handler); + } + function Sys$Net$WebRequest$completed(eventArgs) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "eventArgs", type: Sys.EventArgs} + ]); + if (e) throw e; + var handler = Sys.Net.WebRequestManager._get_eventHandlerList().getHandler("completedRequest"); + if (handler) { + handler(this._executor, eventArgs); + } + handler = this._get_eventHandlerList().getHandler("completed"); + if (handler) { + handler(this._executor, eventArgs); + } + } + function Sys$Net$WebRequest$_get_eventHandlerList() { + if (!this._events) { + this._events = new Sys.EventHandlerList(); + } + return this._events; + } + function Sys$Net$WebRequest$get_url() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._url; + } + function Sys$Net$WebRequest$set_url(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + this._url = value; + } + function Sys$Net$WebRequest$get_headers() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._headers; + } + function Sys$Net$WebRequest$get_httpVerb() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._httpVerb === null) { + if (this._body === null) { + return "GET"; + } + return "POST"; + } + return this._httpVerb; + } + function Sys$Net$WebRequest$set_httpVerb(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + if (value.length === 0) { + throw Error.argument('value', Sys.Res.invalidHttpVerb); + } + this._httpVerb = value; + } + function Sys$Net$WebRequest$get_body() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._body; + } + function Sys$Net$WebRequest$set_body(value) { + var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); + if (e) throw e; + this._body = value; + } + function Sys$Net$WebRequest$get_userContext() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._userContext; + } + function Sys$Net$WebRequest$set_userContext(value) { + var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); + if (e) throw e; + this._userContext = value; + } + function Sys$Net$WebRequest$get_executor() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._executor; + } + function Sys$Net$WebRequest$set_executor(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Sys.Net.WebRequestExecutor}]); + if (e) throw e; + if (this._executor !== null && this._executor.get_started()) { + throw Error.invalidOperation(Sys.Res.setExecutorAfterActive); + } + this._executor = value; + this._executor._set_webRequest(this); + } + function Sys$Net$WebRequest$get_timeout() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._timeout === 0) { + return Sys.Net.WebRequestManager.get_defaultTimeout(); + } + return this._timeout; + } + function Sys$Net$WebRequest$set_timeout(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Number}]); + if (e) throw e; + if (value < 0) { + throw Error.argumentOutOfRange("value", value, Sys.Res.invalidTimeout); + } + this._timeout = value; + } + function Sys$Net$WebRequest$getResolvedUrl() { + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return Sys.Net.WebRequest._resolveUrl(this._url); + } + function Sys$Net$WebRequest$invoke() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._invokeCalled) { + throw Error.invalidOperation(Sys.Res.invokeCalledTwice); + } + Sys.Net.WebRequestManager.executeRequest(this); + this._invokeCalled = true; + } +Sys.Net.WebRequest.prototype = { + add_completed: Sys$Net$WebRequest$add_completed, + remove_completed: Sys$Net$WebRequest$remove_completed, + completed: Sys$Net$WebRequest$completed, + _get_eventHandlerList: Sys$Net$WebRequest$_get_eventHandlerList, + get_url: Sys$Net$WebRequest$get_url, + set_url: Sys$Net$WebRequest$set_url, + get_headers: Sys$Net$WebRequest$get_headers, + get_httpVerb: Sys$Net$WebRequest$get_httpVerb, + set_httpVerb: Sys$Net$WebRequest$set_httpVerb, + get_body: Sys$Net$WebRequest$get_body, + set_body: Sys$Net$WebRequest$set_body, + get_userContext: Sys$Net$WebRequest$get_userContext, + set_userContext: Sys$Net$WebRequest$set_userContext, + get_executor: Sys$Net$WebRequest$get_executor, + set_executor: Sys$Net$WebRequest$set_executor, + get_timeout: Sys$Net$WebRequest$get_timeout, + set_timeout: Sys$Net$WebRequest$set_timeout, + getResolvedUrl: Sys$Net$WebRequest$getResolvedUrl, + invoke: Sys$Net$WebRequest$invoke +} +Sys.Net.WebRequest._resolveUrl = function Sys$Net$WebRequest$_resolveUrl(url, baseUrl) { + if (url && url.indexOf('://') !== -1) { + return url; + } + if (!baseUrl || baseUrl.length === 0) { + var baseElement = document.getElementsByTagName('base')[0]; + if (baseElement && baseElement.href && baseElement.href.length > 0) { + baseUrl = baseElement.href; + } + else { + baseUrl = document.URL; + } + } + var qsStart = baseUrl.indexOf('?'); + if (qsStart !== -1) { + baseUrl = baseUrl.substr(0, qsStart); + } + baseUrl = baseUrl.substr(0, baseUrl.lastIndexOf('/') + 1); + if (!url || url.length === 0) { + return baseUrl; + } + if (url.charAt(0) === '/') { + var slashslash = baseUrl.indexOf('://'); + if (slashslash === -1) { + throw Error.argument("baseUrl", Sys.Res.badBaseUrl1); + } + var nextSlash = baseUrl.indexOf('/', slashslash + 3); + if (nextSlash === -1) { + throw Error.argument("baseUrl", Sys.Res.badBaseUrl2); + } + return baseUrl.substr(0, nextSlash) + url; + } + else { + var lastSlash = baseUrl.lastIndexOf('/'); + if (lastSlash === -1) { + throw Error.argument("baseUrl", Sys.Res.badBaseUrl3); + } + return baseUrl.substr(0, lastSlash+1) + url; + } +} +Sys.Net.WebRequest._createQueryString = function Sys$Net$WebRequest$_createQueryString(queryString, encodeMethod) { + if (!encodeMethod) + encodeMethod = encodeURIComponent; + var sb = new Sys.StringBuilder(); + var i = 0; + for (var arg in queryString) { + var obj = queryString[arg]; + if (typeof(obj) === "function") continue; + var val = Sys.Serialization.JavaScriptSerializer.serialize(obj); + if (i !== 0) { + sb.append('&'); + } + sb.append(arg); + sb.append('='); + sb.append(encodeMethod(val)); + i++; + } + return sb.toString(); +} +Sys.Net.WebRequest._createUrl = function Sys$Net$WebRequest$_createUrl(url, queryString) { + if (!queryString) { + return url; + } + var qs = Sys.Net.WebRequest._createQueryString(queryString); + if (qs.length > 0) { + var sep = '?'; + if (url && url.indexOf('?') !== -1) + sep = '&'; + return url + sep + qs; + } else { + return url; + } +} +Sys.Net.WebRequest.registerClass('Sys.Net.WebRequest'); + +Sys.Net.WebServiceProxy = function Sys$Net$WebServiceProxy() { +} + function Sys$Net$WebServiceProxy$get_timeout() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._timeout; + } + function Sys$Net$WebServiceProxy$set_timeout(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Number}]); + if (e) throw e; + if (value < 0) { throw Error.argumentOutOfRange('value', value, Sys.Res.invalidTimeout); } + this._timeout = value; + } + function Sys$Net$WebServiceProxy$get_defaultUserContext() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._userContext; + } + function Sys$Net$WebServiceProxy$set_defaultUserContext(value) { + var e = Function._validateParams(arguments, [{name: "value", mayBeNull: true}]); + if (e) throw e; + this._userContext = value; + } + function Sys$Net$WebServiceProxy$get_defaultSucceededCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._succeeded; + } + function Sys$Net$WebServiceProxy$set_defaultSucceededCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._succeeded = value; + } + function Sys$Net$WebServiceProxy$get_defaultFailedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._failed; + } + function Sys$Net$WebServiceProxy$set_defaultFailedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._failed = value; + } + function Sys$Net$WebServiceProxy$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path; + } + function Sys$Net$WebServiceProxy$set_path(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + this._path = value; + } + function Sys$Net$WebServiceProxy$_invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "servicePath", type: String}, + {name: "methodName", type: String}, + {name: "useGet", type: Boolean}, + {name: "params"}, + {name: "onSuccess", type: Function, mayBeNull: true, optional: true}, + {name: "onFailure", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (onSuccess === null || typeof onSuccess === 'undefined') onSuccess = this.get_defaultSucceededCallback(); + if (onFailure === null || typeof onFailure === 'undefined') onFailure = this.get_defaultFailedCallback(); + if (userContext === null || typeof userContext === 'undefined') userContext = this.get_defaultUserContext(); + + return Sys.Net.WebServiceProxy.invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext, this.get_timeout()); + } +Sys.Net.WebServiceProxy.prototype = { + get_timeout: Sys$Net$WebServiceProxy$get_timeout, + set_timeout: Sys$Net$WebServiceProxy$set_timeout, + get_defaultUserContext: Sys$Net$WebServiceProxy$get_defaultUserContext, + set_defaultUserContext: Sys$Net$WebServiceProxy$set_defaultUserContext, + get_defaultSucceededCallback: Sys$Net$WebServiceProxy$get_defaultSucceededCallback, + set_defaultSucceededCallback: Sys$Net$WebServiceProxy$set_defaultSucceededCallback, + get_defaultFailedCallback: Sys$Net$WebServiceProxy$get_defaultFailedCallback, + set_defaultFailedCallback: Sys$Net$WebServiceProxy$set_defaultFailedCallback, + get_path: Sys$Net$WebServiceProxy$get_path, + set_path: Sys$Net$WebServiceProxy$set_path, + _invoke: Sys$Net$WebServiceProxy$_invoke +} +Sys.Net.WebServiceProxy.registerClass('Sys.Net.WebServiceProxy'); +Sys.Net.WebServiceProxy.invoke = function Sys$Net$WebServiceProxy$invoke(servicePath, methodName, useGet, params, onSuccess, onFailure, userContext, timeout) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "servicePath", type: String}, + {name: "methodName", type: String}, + {name: "useGet", type: Boolean, optional: true}, + {name: "params", mayBeNull: true, optional: true}, + {name: "onSuccess", type: Function, mayBeNull: true, optional: true}, + {name: "onFailure", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true}, + {name: "timeout", type: Number, optional: true} + ]); + if (e) throw e; + var request = new Sys.Net.WebRequest(); + request.get_headers()['Content-Type'] = 'application/json; charset=utf-8'; + if (!params) params = {}; + var urlParams = params; + if (!useGet || !urlParams) urlParams = {}; + request.set_url(Sys.Net.WebRequest._createUrl(servicePath+"/"+encodeURIComponent(methodName), urlParams)); + var body = null; + if (!useGet) { + body = Sys.Serialization.JavaScriptSerializer.serialize(params); + if (body === "{}") body = ""; + } + request.set_body(body); + request.add_completed(onComplete); + if (timeout && timeout > 0) request.set_timeout(timeout); + request.invoke(); + function onComplete(response, eventArgs) { + if (response.get_responseAvailable()) { + var statusCode = response.get_statusCode(); + var result = null; + + try { + var contentType = response.getResponseHeader("Content-Type"); + if (contentType.startsWith("application/json")) { + result = response.get_object(); + } + else if (contentType.startsWith("text/xml")) { + result = response.get_xml(); + } + else { + result = response.get_responseData(); + } + } catch (ex) { + } + var error = response.getResponseHeader("jsonerror"); + var errorObj = (error === "true"); + if (errorObj) { + if (result) { + result = new Sys.Net.WebServiceError(false, result.Message, result.StackTrace, result.ExceptionType); + } + } + else if (contentType.startsWith("application/json")) { + if (!result || typeof(result.d) === "undefined") { + throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceInvalidJsonWrapper, methodName)); + } + result = result.d; + } + if (((statusCode < 200) || (statusCode >= 300)) || errorObj) { + if (onFailure) { + if (!result || !errorObj) { + result = new Sys.Net.WebServiceError(false , String.format(Sys.Res.webServiceFailedNoMsg, methodName), "", ""); + } + result._statusCode = statusCode; + onFailure(result, userContext, methodName); + } + else { + var error; + if (result && errorObj) { + error = result.get_exceptionType() + "-- " + result.get_message(); + } + else { + error = response.get_responseData(); + } + throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); + } + } + else if (onSuccess) { + onSuccess(result, userContext, methodName); + } + } + else { + var msg; + if (response.get_timedOut()) { + msg = String.format(Sys.Res.webServiceTimedOut, methodName); + } + else { + msg = String.format(Sys.Res.webServiceFailedNoMsg, methodName) + } + if (onFailure) { + onFailure(new Sys.Net.WebServiceError(response.get_timedOut(), msg, "", ""), userContext, methodName); + } + else { + throw Sys.Net.WebServiceProxy._createFailedError(methodName, msg); + } + } + } + return request; +} +Sys.Net.WebServiceProxy._createFailedError = function Sys$Net$WebServiceProxy$_createFailedError(methodName, errorMessage) { + var displayMessage = "Sys.Net.WebServiceFailedException: " + errorMessage; + var e = Error.create(displayMessage, { 'name': 'Sys.Net.WebServiceFailedException', 'methodName': methodName }); + e.popStackFrame(); + return e; +} +Sys.Net.WebServiceProxy._defaultFailedCallback = function Sys$Net$WebServiceProxy$_defaultFailedCallback(err, methodName) { + var error = err.get_exceptionType() + "-- " + err.get_message(); + throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); +} +Sys.Net.WebServiceProxy._generateTypedConstructor = function Sys$Net$WebServiceProxy$_generateTypedConstructor(type) { + return function(properties) { + if (properties) { + for (var name in properties) { + this[name] = properties[name]; + } + } + this.__type = type; + } +} + +Sys.Net.WebServiceError = function Sys$Net$WebServiceError(timedOut, message, stackTrace, exceptionType) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "timedOut", type: Boolean}, + {name: "message", type: String, mayBeNull: true}, + {name: "stackTrace", type: String, mayBeNull: true}, + {name: "exceptionType", type: String, mayBeNull: true} + ]); + if (e) throw e; + this._timedOut = timedOut; + this._message = message; + this._stackTrace = stackTrace; + this._exceptionType = exceptionType; + this._statusCode = -1; +} + function Sys$Net$WebServiceError$get_timedOut() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._timedOut; + } + function Sys$Net$WebServiceError$get_statusCode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._statusCode; + } + function Sys$Net$WebServiceError$get_message() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._message; + } + function Sys$Net$WebServiceError$get_stackTrace() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._stackTrace; + } + function Sys$Net$WebServiceError$get_exceptionType() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._exceptionType; + } +Sys.Net.WebServiceError.prototype = { + get_timedOut: Sys$Net$WebServiceError$get_timedOut, + get_statusCode: Sys$Net$WebServiceError$get_statusCode, + get_message: Sys$Net$WebServiceError$get_message, + get_stackTrace: Sys$Net$WebServiceError$get_stackTrace, + get_exceptionType: Sys$Net$WebServiceError$get_exceptionType +} +Sys.Net.WebServiceError.registerClass('Sys.Net.WebServiceError'); +Type.registerNamespace('Sys.Services'); +Sys.Services._ProfileService = function Sys$Services$_ProfileService() { + Sys.Services._ProfileService.initializeBase(this); + this.properties = {}; +} +Sys.Services._ProfileService.DefaultWebServicePath = ''; + function Sys$Services$_ProfileService$get_defaultLoadCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLoadCompletedCallback; + } + function Sys$Services$_ProfileService$set_defaultLoadCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLoadCompletedCallback = value; + } + function Sys$Services$_ProfileService$get_defaultSaveCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultSaveCompletedCallback; + } + function Sys$Services$_ProfileService$set_defaultSaveCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultSaveCompletedCallback = value; + } + function Sys$Services$_ProfileService$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path || ''; + } + function Sys$Services$_ProfileService$load(propertyNames, loadCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyNames", type: Array, mayBeNull: true, optional: true, elementType: String}, + {name: "loadCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var parameters; + var methodName; + if (!propertyNames) { + methodName = "GetAllPropertiesForCurrentUser"; + parameters = { authenticatedUserOnly: false }; + } + else { + methodName = "GetPropertiesForCurrentUser"; + parameters = { properties: this._clonePropertyNames(propertyNames), authenticatedUserOnly: false }; + } + this._invoke(this._get_path(), + methodName, + false, + parameters, + Function.createDelegate(this, this._onLoadComplete), + Function.createDelegate(this, this._onLoadFailed), + [loadCompletedCallback, failedCallback, userContext]); + } + function Sys$Services$_ProfileService$save(propertyNames, saveCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "propertyNames", type: Array, mayBeNull: true, optional: true, elementType: String}, + {name: "saveCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + var flattenedProperties = this._flattenProperties(propertyNames, this.properties); + this._invoke(this._get_path(), + "SetPropertiesForCurrentUser", + false, + { values: flattenedProperties.value, authenticatedUserOnly: false }, + Function.createDelegate(this, this._onSaveComplete), + Function.createDelegate(this, this._onSaveFailed), + [saveCompletedCallback, failedCallback, userContext, flattenedProperties.count]); + } + function Sys$Services$_ProfileService$_clonePropertyNames(arr) { + var nodups = []; + var seen = {}; + for (var i=0; i < arr.length; i++) { + var prop = arr[i]; + if(!seen[prop]) { Array.add(nodups, prop); seen[prop]=true; }; + } + return nodups; + } + function Sys$Services$_ProfileService$_flattenProperties(propertyNames, properties, groupName) { + var flattenedProperties = {}; + var val; + var key; + var count = 0; + if (propertyNames && propertyNames.length === 0) { + return { value: flattenedProperties, count: 0 }; + } + for (var property in properties) { + val = properties[property]; + key = groupName ? groupName + "." + property : property; + if(Sys.Services.ProfileGroup.isInstanceOfType(val)) { + var obj = this._flattenProperties(propertyNames, val, key); + var groupProperties = obj.value; + count += obj.count; + for(var subKey in groupProperties) { + var subVal = groupProperties[subKey]; + flattenedProperties[subKey] = subVal; + } + } + else { + if(!propertyNames || Array.indexOf(propertyNames, key) !== -1) { + flattenedProperties[key] = val; + count++; + } + } + } + return { value: flattenedProperties, count: count }; + } + function Sys$Services$_ProfileService$_get_path() { + var path = this.get_path(); + if (!path.length) { + path = Sys.Services._ProfileService.DefaultWebServicePath; + } + if (!path || !path.length) { + throw Error.invalidOperation(Sys.Res.servicePathNotSet); + } + return path; + } + function Sys$Services$_ProfileService$_onLoadComplete(result, context, methodName) { + if (typeof(result) !== "object") { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Object")); + } + var unflattened = this._unflattenProperties(result); + for (var name in unflattened) { + this.properties[name] = unflattened[name]; + } + + var callback = context[0] || this.get_defaultLoadCompletedCallback() || this.get_defaultSucceededCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(result.length, userContext, "Sys.Services.ProfileService.load"); + } + } + function Sys$Services$_ProfileService$_onLoadFailed(err, context, methodName) { + var callback = context[1] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.ProfileService.load"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_ProfileService$_onSaveComplete(result, context, methodName) { + var count = context[3]; + if (result !== null) { + if (result instanceof Array) { + count -= result.length; + } + else if (typeof(result) === 'number') { + count = result; + } + else { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Array")); + } + } + + var callback = context[0] || this.get_defaultSaveCompletedCallback() || this.get_defaultSucceededCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(count, userContext, "Sys.Services.ProfileService.save"); + } + } + function Sys$Services$_ProfileService$_onSaveFailed(err, context, methodName) { + var callback = context[1] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.ProfileService.save"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_ProfileService$_unflattenProperties(properties) { + var unflattenedProperties = {}; + var dotIndex; + var val; + var count = 0; + for (var key in properties) { + count++; + val = properties[key]; + dotIndex = key.indexOf('.'); + if (dotIndex !== -1) { + var groupName = key.substr(0, dotIndex); + key = key.substr(dotIndex+1); + var group = unflattenedProperties[groupName]; + if (!group || !Sys.Services.ProfileGroup.isInstanceOfType(group)) { + group = new Sys.Services.ProfileGroup(); + unflattenedProperties[groupName] = group; + } + group[key] = val; + } + else { + unflattenedProperties[key] = val; + } + } + properties.length = count; + return unflattenedProperties; + } +Sys.Services._ProfileService.prototype = { + _defaultLoadCompletedCallback: null, + _defaultSaveCompletedCallback: null, + _path: '', + _timeout: 0, + get_defaultLoadCompletedCallback: Sys$Services$_ProfileService$get_defaultLoadCompletedCallback, + set_defaultLoadCompletedCallback: Sys$Services$_ProfileService$set_defaultLoadCompletedCallback, + get_defaultSaveCompletedCallback: Sys$Services$_ProfileService$get_defaultSaveCompletedCallback, + set_defaultSaveCompletedCallback: Sys$Services$_ProfileService$set_defaultSaveCompletedCallback, + get_path: Sys$Services$_ProfileService$get_path, + load: Sys$Services$_ProfileService$load, + save: Sys$Services$_ProfileService$save, + _clonePropertyNames: Sys$Services$_ProfileService$_clonePropertyNames, + _flattenProperties: Sys$Services$_ProfileService$_flattenProperties, + _get_path: Sys$Services$_ProfileService$_get_path, + _onLoadComplete: Sys$Services$_ProfileService$_onLoadComplete, + _onLoadFailed: Sys$Services$_ProfileService$_onLoadFailed, + _onSaveComplete: Sys$Services$_ProfileService$_onSaveComplete, + _onSaveFailed: Sys$Services$_ProfileService$_onSaveFailed, + _unflattenProperties: Sys$Services$_ProfileService$_unflattenProperties +} +Sys.Services._ProfileService.registerClass('Sys.Services._ProfileService', Sys.Net.WebServiceProxy); +Sys.Services.ProfileService = new Sys.Services._ProfileService(); +Sys.Services.ProfileGroup = function Sys$Services$ProfileGroup(properties) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "properties", mayBeNull: true, optional: true} + ]); + if (e) throw e; + if (properties) { + for (var property in properties) { + this[property] = properties[property]; + } + } +} +Sys.Services.ProfileGroup.registerClass('Sys.Services.ProfileGroup'); +Sys.Services._AuthenticationService = function Sys$Services$_AuthenticationService() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + Sys.Services._AuthenticationService.initializeBase(this); +} +Sys.Services._AuthenticationService.DefaultWebServicePath = ''; + function Sys$Services$_AuthenticationService$get_defaultLoginCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLoginCompletedCallback; + } + function Sys$Services$_AuthenticationService$set_defaultLoginCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLoginCompletedCallback = value; + } + function Sys$Services$_AuthenticationService$get_defaultLogoutCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLogoutCompletedCallback; + } + function Sys$Services$_AuthenticationService$set_defaultLogoutCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLogoutCompletedCallback = value; + } + function Sys$Services$_AuthenticationService$get_isLoggedIn() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._authenticated; + } + function Sys$Services$_AuthenticationService$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path || ''; + } + function Sys$Services$_AuthenticationService$login(username, password, isPersistent, customInfo, redirectUrl, loginCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "username", type: String}, + {name: "password", type: String, mayBeNull: true}, + {name: "isPersistent", type: Boolean, mayBeNull: true, optional: true}, + {name: "customInfo", type: String, mayBeNull: true, optional: true}, + {name: "redirectUrl", type: String, mayBeNull: true, optional: true}, + {name: "loginCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._invoke(this._get_path(), "Login", false, + { userName: username, password: password, createPersistentCookie: isPersistent }, + Function.createDelegate(this, this._onLoginComplete), + Function.createDelegate(this, this._onLoginFailed), + [username, password, isPersistent, customInfo, redirectUrl, loginCompletedCallback, failedCallback, userContext]); + } + function Sys$Services$_AuthenticationService$logout(redirectUrl, logoutCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "redirectUrl", type: String, mayBeNull: true, optional: true}, + {name: "logoutCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + this._invoke(this._get_path(), "Logout", false, {}, + Function.createDelegate(this, this._onLogoutComplete), + Function.createDelegate(this, this._onLogoutFailed), + [redirectUrl, logoutCompletedCallback, failedCallback, userContext]); + } + function Sys$Services$_AuthenticationService$_get_path() { + var path = this.get_path(); + if(!path.length) { + path = Sys.Services._AuthenticationService.DefaultWebServicePath; + } + if(!path || !path.length) { + throw Error.invalidOperation(Sys.Res.servicePathNotSet); + } + return path; + } + function Sys$Services$_AuthenticationService$_onLoginComplete(result, context, methodName) { + if(typeof(result) !== "boolean") { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Boolean")); + } + + var redirectUrl = context[4]; + var userContext = context[7] || this.get_defaultUserContext(); + var callback = context[5] || this.get_defaultLoginCompletedCallback() || this.get_defaultSucceededCallback(); + + if(result) { + this._authenticated = true; + if (callback) { + callback(true, userContext, "Sys.Services.AuthenticationService.login"); + } + + if (typeof(redirectUrl) !== "undefined" && redirectUrl !== null) { + window.location.href = redirectUrl; + } + } + else if (callback) { + callback(false, userContext, "Sys.Services.AuthenticationService.login"); + } + } + function Sys$Services$_AuthenticationService$_onLoginFailed(err, context, methodName) { + var callback = context[6] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[7] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.AuthenticationService.login"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_AuthenticationService$_onLogoutComplete(result, context, methodName) { + if(result !== null) { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "null")); + } + + var redirectUrl = context[0]; + var userContext = context[3] || this.get_defaultUserContext(); + var callback = context[1] || this.get_defaultLogoutCompletedCallback() || this.get_defaultSucceededCallback(); + this._authenticated = false; + + if (callback) { + callback(null, userContext, "Sys.Services.AuthenticationService.logout"); + } + + if(!redirectUrl) { + window.location.reload(); + } + else { + window.location.href = redirectUrl; + } + } + function Sys$Services$_AuthenticationService$_onLogoutFailed(err, context, methodName) { + var callback = context[2] || this.get_defaultFailedCallback(); + if (callback) { + callback(err, context[3], "Sys.Services.AuthenticationService.logout"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } + function Sys$Services$_AuthenticationService$_setAuthenticated(authenticated) { + this._authenticated = authenticated; + } +Sys.Services._AuthenticationService.prototype = { + _defaultLoginCompletedCallback: null, + _defaultLogoutCompletedCallback: null, + _path: '', + _timeout: 0, + _authenticated: false, + get_defaultLoginCompletedCallback: Sys$Services$_AuthenticationService$get_defaultLoginCompletedCallback, + set_defaultLoginCompletedCallback: Sys$Services$_AuthenticationService$set_defaultLoginCompletedCallback, + get_defaultLogoutCompletedCallback: Sys$Services$_AuthenticationService$get_defaultLogoutCompletedCallback, + set_defaultLogoutCompletedCallback: Sys$Services$_AuthenticationService$set_defaultLogoutCompletedCallback, + get_isLoggedIn: Sys$Services$_AuthenticationService$get_isLoggedIn, + get_path: Sys$Services$_AuthenticationService$get_path, + login: Sys$Services$_AuthenticationService$login, + logout: Sys$Services$_AuthenticationService$logout, + _get_path: Sys$Services$_AuthenticationService$_get_path, + _onLoginComplete: Sys$Services$_AuthenticationService$_onLoginComplete, + _onLoginFailed: Sys$Services$_AuthenticationService$_onLoginFailed, + _onLogoutComplete: Sys$Services$_AuthenticationService$_onLogoutComplete, + _onLogoutFailed: Sys$Services$_AuthenticationService$_onLogoutFailed, + _setAuthenticated: Sys$Services$_AuthenticationService$_setAuthenticated +} +Sys.Services._AuthenticationService.registerClass('Sys.Services._AuthenticationService', Sys.Net.WebServiceProxy); +Sys.Services.AuthenticationService = new Sys.Services._AuthenticationService(); +Sys.Services._RoleService = function Sys$Services$_RoleService() { + Sys.Services._RoleService.initializeBase(this); + this._roles = []; +} +Sys.Services._RoleService.DefaultWebServicePath = ''; + function Sys$Services$_RoleService$get_defaultLoadCompletedCallback() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._defaultLoadCompletedCallback; + } + function Sys$Services$_RoleService$set_defaultLoadCompletedCallback(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Function, mayBeNull: true}]); + if (e) throw e; + this._defaultLoadCompletedCallback = value; + } + function Sys$Services$_RoleService$get_path() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._path || ''; + } + function Sys$Services$_RoleService$get_roles() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return Array.clone(this._roles); + } + function Sys$Services$_RoleService$isUserInRole(role) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "role", type: String} + ]); + if (e) throw e; + var v = this._get_rolesIndex()[role.trim().toLowerCase()]; + return !!v; + } + function Sys$Services$_RoleService$load(loadCompletedCallback, failedCallback, userContext) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "loadCompletedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "failedCallback", type: Function, mayBeNull: true, optional: true}, + {name: "userContext", mayBeNull: true, optional: true} + ]); + if (e) throw e; + Sys.Net.WebServiceProxy.invoke( + this._get_path(), + "GetRolesForCurrentUser", + false, + {} , + Function.createDelegate(this, this._onLoadComplete), + Function.createDelegate(this, this._onLoadFailed), + [loadCompletedCallback, failedCallback, userContext], + this.get_timeout()); + } + function Sys$Services$_RoleService$_get_path() { + var path = this.get_path(); + if(!path || !path.length) { + path = Sys.Services._RoleService.DefaultWebServicePath; + } + if(!path || !path.length) { + throw Error.invalidOperation(Sys.Res.servicePathNotSet); + } + return path; + } + function Sys$Services$_RoleService$_get_rolesIndex() { + if (!this._rolesIndex) { + var index = {}; + for(var i=0; i < this._roles.length; i++) { + index[this._roles[i].toLowerCase()] = true; + } + this._rolesIndex = index; + } + return this._rolesIndex; + } + function Sys$Services$_RoleService$_onLoadComplete(result, context, methodName) { + if(result && !(result instanceof Array)) { + throw Error.invalidOperation(String.format(Sys.Res.webServiceInvalidReturnType, methodName, "Array")); + } + this._roles = result; + this._rolesIndex = null; + var callback = context[0] || this.get_defaultLoadCompletedCallback() || this.get_defaultSucceededCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + var clonedResult = Array.clone(result); + callback(clonedResult, userContext, "Sys.Services.RoleService.load"); + } + } + function Sys$Services$_RoleService$_onLoadFailed(err, context, methodName) { + var callback = context[1] || this.get_defaultFailedCallback(); + if (callback) { + var userContext = context[2] || this.get_defaultUserContext(); + callback(err, userContext, "Sys.Services.RoleService.load"); + } + else { + Sys.Net.WebServiceProxy._defaultFailedCallback(err, methodName); + } + } +Sys.Services._RoleService.prototype = { + _defaultLoadCompletedCallback: null, + _rolesIndex: null, + _timeout: 0, + _path: '', + get_defaultLoadCompletedCallback: Sys$Services$_RoleService$get_defaultLoadCompletedCallback, + set_defaultLoadCompletedCallback: Sys$Services$_RoleService$set_defaultLoadCompletedCallback, + get_path: Sys$Services$_RoleService$get_path, + get_roles: Sys$Services$_RoleService$get_roles, + isUserInRole: Sys$Services$_RoleService$isUserInRole, + load: Sys$Services$_RoleService$load, + _get_path: Sys$Services$_RoleService$_get_path, + _get_rolesIndex: Sys$Services$_RoleService$_get_rolesIndex, + _onLoadComplete: Sys$Services$_RoleService$_onLoadComplete, + _onLoadFailed: Sys$Services$_RoleService$_onLoadFailed +} +Sys.Services._RoleService.registerClass('Sys.Services._RoleService', Sys.Net.WebServiceProxy); +Sys.Services.RoleService = new Sys.Services._RoleService(); +Type.registerNamespace('Sys.Serialization'); +Sys.Serialization.JavaScriptSerializer = function Sys$Serialization$JavaScriptSerializer() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); +} +Sys.Serialization.JavaScriptSerializer.registerClass('Sys.Serialization.JavaScriptSerializer'); +Sys.Serialization.JavaScriptSerializer._serverTypeFieldName = '__type'; +Sys.Serialization.JavaScriptSerializer._stringRegEx = new RegExp('["\\b\\f\\n\\r\\t\\\\\\x00-\\x1F]', 'i'); +Sys.Serialization.JavaScriptSerializer._dateRegEx = new RegExp('(^|[^\\\\])\\"\\\\/Date\\((-?[0-9]+)(?:[a-zA-Z]|(?:\\+|-)[0-9]{4})?\\)\\\\/\\"', 'g'); +Sys.Serialization.JavaScriptSerializer._jsonRegEx = new RegExp('[^,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t]', 'g'); +Sys.Serialization.JavaScriptSerializer._jsonStringRegEx = new RegExp('"(\\\\.|[^"\\\\])*"', 'g'); +Sys.Serialization.JavaScriptSerializer._serializeBooleanWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeBooleanWithBuilder(object, stringBuilder) { + stringBuilder.append(object.toString()); +} +Sys.Serialization.JavaScriptSerializer._serializeNumberWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeNumberWithBuilder(object, stringBuilder) { + if (isFinite(object)) { + stringBuilder.append(String(object)); + } + else { + throw Error.invalidOperation(Sys.Res.cannotSerializeNonFiniteNumbers); + } +} +Sys.Serialization.JavaScriptSerializer._serializeStringWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeStringWithBuilder(object, stringBuilder) { + stringBuilder.append('"'); + if (Sys.Serialization.JavaScriptSerializer._stringRegEx.test(object)) { + var length = object.length; + for (i = 0; i < length; ++i) { + var curChar = object.charAt(i); + if (curChar >= ' ') { + if (curChar === '\\' || curChar === '"') { + stringBuilder.append('\\'); + } + stringBuilder.append(curChar); + } + else { + switch (curChar) { + case '\b': + stringBuilder.append('\\b'); + break; + case '\f': + stringBuilder.append('\\f'); + break; + case '\n': + stringBuilder.append('\\n'); + break; + case '\r': + stringBuilder.append('\\r'); + break; + case '\t': + stringBuilder.append('\\t'); + break; + default: + stringBuilder.append('\\u00'); + if (curChar.charCodeAt() < 16) stringBuilder.append('0'); + stringBuilder.append(curChar.charCodeAt().toString(16)); + } + } + } + } else { + stringBuilder.append(object); + } + stringBuilder.append('"'); +} +Sys.Serialization.JavaScriptSerializer._serializeWithBuilder = function Sys$Serialization$JavaScriptSerializer$_serializeWithBuilder(object, stringBuilder, sort, prevObjects) { + var i; + switch (typeof object) { + case 'object': + if (object) { + if (prevObjects){ + for( var j = 0; j < prevObjects.length; j++) { + if (prevObjects[j] === object) { + throw Error.invalidOperation(Sys.Res.cannotSerializeObjectWithCycle); + } + } + } + else { + prevObjects = new Array(); + } + try { + Array.add(prevObjects, object); + + if (Number.isInstanceOfType(object)){ + Sys.Serialization.JavaScriptSerializer._serializeNumberWithBuilder(object, stringBuilder); + } + else if (Boolean.isInstanceOfType(object)){ + Sys.Serialization.JavaScriptSerializer._serializeBooleanWithBuilder(object, stringBuilder); + } + else if (String.isInstanceOfType(object)){ + Sys.Serialization.JavaScriptSerializer._serializeStringWithBuilder(object, stringBuilder); + } + + else if (Array.isInstanceOfType(object)) { + stringBuilder.append('['); + + for (i = 0; i < object.length; ++i) { + if (i > 0) { + stringBuilder.append(','); + } + Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(object[i], stringBuilder,false,prevObjects); + } + stringBuilder.append(']'); + } + else { + if (Date.isInstanceOfType(object)) { + stringBuilder.append('"\\/Date('); + stringBuilder.append(object.getTime()); + stringBuilder.append(')\\/"'); + break; + } + var properties = []; + var propertyCount = 0; + for (var name in object) { + if (name.startsWith('$')) { + continue; + } + if (name === Sys.Serialization.JavaScriptSerializer._serverTypeFieldName && propertyCount !== 0){ + properties[propertyCount++] = properties[0]; + properties[0] = name; + } + else{ + properties[propertyCount++] = name; + } + } + if (sort) properties.sort(); + stringBuilder.append('{'); + var needComma = false; + + for (i=0; i + /// + /// + var e = Function._validateParams(arguments, [ + {name: "object", mayBeNull: true} + ]); + if (e) throw e; + var stringBuilder = new Sys.StringBuilder(); + Sys.Serialization.JavaScriptSerializer._serializeWithBuilder(object, stringBuilder, false); + return stringBuilder.toString(); +} +Sys.Serialization.JavaScriptSerializer.deserialize = function Sys$Serialization$JavaScriptSerializer$deserialize(data, secure) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "data", type: String}, + {name: "secure", type: Boolean, optional: true} + ]); + if (e) throw e; + + if (data.length === 0) throw Error.argument('data', Sys.Res.cannotDeserializeEmptyString); + try { + var exp = data.replace(Sys.Serialization.JavaScriptSerializer._dateRegEx, "$1new Date($2)"); + + if (secure && Sys.Serialization.JavaScriptSerializer._jsonRegEx.test( + exp.replace(Sys.Serialization.JavaScriptSerializer._jsonStringRegEx, ''))) throw null; + return eval('(' + exp + ')'); + } + catch (e) { + throw Error.argument('data', Sys.Res.cannotDeserializeInvalidJson); + } +} + +Sys.CultureInfo = function Sys$CultureInfo(name, numberFormat, dateTimeFormat) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "name", type: String}, + {name: "numberFormat", type: Object}, + {name: "dateTimeFormat", type: Object} + ]); + if (e) throw e; + this.name = name; + this.numberFormat = numberFormat; + this.dateTimeFormat = dateTimeFormat; +} + function Sys$CultureInfo$_getDateTimeFormats() { + if (! this._dateTimeFormats) { + var dtf = this.dateTimeFormat; + this._dateTimeFormats = + [ dtf.MonthDayPattern, + dtf.YearMonthPattern, + dtf.ShortDatePattern, + dtf.ShortTimePattern, + dtf.LongDatePattern, + dtf.LongTimePattern, + dtf.FullDateTimePattern, + dtf.RFC1123Pattern, + dtf.SortableDateTimePattern, + dtf.UniversalSortableDateTimePattern ]; + } + return this._dateTimeFormats; + } + function Sys$CultureInfo$_getMonthIndex(value) { + if (!this._upperMonths) { + this._upperMonths = this._toUpperArray(this.dateTimeFormat.MonthNames); + } + return Array.indexOf(this._upperMonths, this._toUpper(value)); + } + function Sys$CultureInfo$_getAbbrMonthIndex(value) { + if (!this._upperAbbrMonths) { + this._upperAbbrMonths = this._toUpperArray(this.dateTimeFormat.AbbreviatedMonthNames); + } + return Array.indexOf(this._upperAbbrMonths, this._toUpper(value)); + } + function Sys$CultureInfo$_getDayIndex(value) { + if (!this._upperDays) { + this._upperDays = this._toUpperArray(this.dateTimeFormat.DayNames); + } + return Array.indexOf(this._upperDays, this._toUpper(value)); + } + function Sys$CultureInfo$_getAbbrDayIndex(value) { + if (!this._upperAbbrDays) { + this._upperAbbrDays = this._toUpperArray(this.dateTimeFormat.AbbreviatedDayNames); + } + return Array.indexOf(this._upperAbbrDays, this._toUpper(value)); + } + function Sys$CultureInfo$_toUpperArray(arr) { + var result = []; + for (var i = 0, il = arr.length; i < il; i++) { + result[i] = this._toUpper(arr[i]); + } + return result; + } + function Sys$CultureInfo$_toUpper(value) { + return value.split("\u00A0").join(' ').toUpperCase(); + } +Sys.CultureInfo.prototype = { + _getDateTimeFormats: Sys$CultureInfo$_getDateTimeFormats, + _getMonthIndex: Sys$CultureInfo$_getMonthIndex, + _getAbbrMonthIndex: Sys$CultureInfo$_getAbbrMonthIndex, + _getDayIndex: Sys$CultureInfo$_getDayIndex, + _getAbbrDayIndex: Sys$CultureInfo$_getAbbrDayIndex, + _toUpperArray: Sys$CultureInfo$_toUpperArray, + _toUpper: Sys$CultureInfo$_toUpper +} +Sys.CultureInfo._parse = function Sys$CultureInfo$_parse(value) { + var cultureInfo = Sys.Serialization.JavaScriptSerializer.deserialize(value); + return new Sys.CultureInfo(cultureInfo.name, cultureInfo.numberFormat, cultureInfo.dateTimeFormat); +} +Sys.CultureInfo.registerClass('Sys.CultureInfo'); +Sys.CultureInfo.InvariantCulture = Sys.CultureInfo._parse('{"name":"","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"\u00A4","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, dd MMMM yyyy HH:mm:ss","LongDatePattern":"dddd, dd MMMM yyyy","LongTimePattern":"HH:mm:ss","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"MM/dd/yyyy","ShortTimePattern":"HH:mm","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"yyyy MMMM","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]}}'); +if (typeof(__cultureInfo) === 'undefined') { + var __cultureInfo = '{"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":false,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinity","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"Infinity","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"\u2030","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"@-62135568000000@","MaxSupportedDateTime":"@253402300799999@","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":false},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM dd, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM dd, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM dd","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\':\'mm\':\'ss \'GMT\'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy\'-\'MM\'-\'dd\'T\'HH\':\'mm\':\'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\'-\'MM\'-\'dd HH\':\'mm\':\'ss\'Z\'","YearMonthPattern":"MMMM, yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":false,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]}}'; +} +Sys.CultureInfo.CurrentCulture = Sys.CultureInfo._parse(__cultureInfo); +delete __cultureInfo; + +Sys.UI.Behavior = function Sys$UI$Behavior(element) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + Sys.UI.Behavior.initializeBase(this); + this._element = element; + var behaviors = element._behaviors; + if (!behaviors) { + element._behaviors = [this]; + } + else { + behaviors[behaviors.length] = this; + } +} + function Sys$UI$Behavior$get_element() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._element; + } + function Sys$UI$Behavior$get_id() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + var baseId = Sys.UI.Behavior.callBaseMethod(this, 'get_id'); + if (baseId) return baseId; + if (!this._element || !this._element.id) return ''; + return this._element.id + '$' + this.get_name(); + } + function Sys$UI$Behavior$get_name() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._name) return this._name; + var name = Object.getTypeName(this); + var i = name.lastIndexOf('.'); + if (i != -1) name = name.substr(i + 1); + if (!this.get_isInitialized()) this._name = name; + return name; + } + function Sys$UI$Behavior$set_name(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + if ((value === '') || (value.charAt(0) === ' ') || (value.charAt(value.length - 1) === ' ')) + throw Error.argument('value', Sys.Res.invalidId); + if (typeof(this._element[value]) !== 'undefined') + throw Error.invalidOperation(String.format(Sys.Res.behaviorDuplicateName, value)); + if (this.get_isInitialized()) throw Error.invalidOperation(Sys.Res.cantSetNameAfterInit); + this._name = value; + } + function Sys$UI$Behavior$initialize() { + Sys.UI.Behavior.callBaseMethod(this, 'initialize'); + var name = this.get_name(); + if (name) this._element[name] = this; + } + function Sys$UI$Behavior$dispose() { + Sys.UI.Behavior.callBaseMethod(this, 'dispose'); + if (this._element) { + var name = this.get_name(); + if (name) { + this._element[name] = null; + } + Array.remove(this._element._behaviors, this); + delete this._element; + } + } +Sys.UI.Behavior.prototype = { + _name: null, + get_element: Sys$UI$Behavior$get_element, + get_id: Sys$UI$Behavior$get_id, + get_name: Sys$UI$Behavior$get_name, + set_name: Sys$UI$Behavior$set_name, + initialize: Sys$UI$Behavior$initialize, + dispose: Sys$UI$Behavior$dispose +} +Sys.UI.Behavior.registerClass('Sys.UI.Behavior', Sys.Component); +Sys.UI.Behavior.getBehaviorByName = function Sys$UI$Behavior$getBehaviorByName(element, name) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "name", type: String} + ]); + if (e) throw e; + var b = element[name]; + return (b && Sys.UI.Behavior.isInstanceOfType(b)) ? b : null; +} +Sys.UI.Behavior.getBehaviors = function Sys$UI$Behavior$getBehaviors(element) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if (!element._behaviors) return []; + return Array.clone(element._behaviors); +} +Sys.UI.Behavior.getBehaviorsByType = function Sys$UI$Behavior$getBehaviorsByType(element, type) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true}, + {name: "type", type: Type} + ]); + if (e) throw e; + var behaviors = element._behaviors; + var results = []; + if (behaviors) { + for (var i = 0, l = behaviors.length; i < l; i++) { + if (type.isInstanceOfType(behaviors[i])) { + results[results.length] = behaviors[i]; + } + } + } + return results; +} + +Sys.UI.VisibilityMode = function Sys$UI$VisibilityMode() { + /// + /// + /// + if (arguments.length !== 0) throw Error.parameterCount(); + throw Error.notImplemented(); +} +Sys.UI.VisibilityMode.prototype = { + hide: 0, + collapse: 1 +} +Sys.UI.VisibilityMode.registerEnum("Sys.UI.VisibilityMode"); + +Sys.UI.Control = function Sys$UI$Control(element) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "element", domElement: true} + ]); + if (e) throw e; + if (typeof(element.control) != 'undefined') throw Error.invalidOperation(Sys.Res.controlAlreadyDefined); + Sys.UI.Control.initializeBase(this); + this._element = element; + element.control = this; +} + function Sys$UI$Control$get_element() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + return this._element; + } + function Sys$UI$Control$get_id() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._element) return ''; + return this._element.id; + } + function Sys$UI$Control$set_id(value) { + var e = Function._validateParams(arguments, [{name: "value", type: String}]); + if (e) throw e; + throw Error.invalidOperation(Sys.Res.cantSetId); + } + function Sys$UI$Control$get_parent() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (this._parent) return this._parent; + if (!this._element) return null; + + var parentElement = this._element.parentNode; + while (parentElement) { + if (parentElement.control) { + return parentElement.control; + } + parentElement = parentElement.parentNode; + } + return null; + } + function Sys$UI$Control$set_parent(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Sys.UI.Control}]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + var parents = [this]; + var current = value; + while (current) { + if (Array.contains(parents, current)) throw Error.invalidOperation(Sys.Res.circularParentChain); + parents[parents.length] = current; + current = current.get_parent(); + } + this._parent = value; + } + function Sys$UI$Control$get_visibilityMode() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + return Sys.UI.DomElement.getVisibilityMode(this._element); + } + function Sys$UI$Control$set_visibilityMode(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Sys.UI.VisibilityMode}]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.setVisibilityMode(this._element, value); + } + function Sys$UI$Control$get_visible() { + /// + if (arguments.length !== 0) throw Error.parameterCount(); + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + return Sys.UI.DomElement.getVisible(this._element); + } + function Sys$UI$Control$set_visible(value) { + var e = Function._validateParams(arguments, [{name: "value", type: Boolean}]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.setVisible(this._element, value) + } + function Sys$UI$Control$addCssClass(className) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "className", type: String} + ]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.addCssClass(this._element, className); + } + function Sys$UI$Control$dispose() { + Sys.UI.Control.callBaseMethod(this, 'dispose'); + if (this._element) { + this._element.control = undefined; + delete this._element; + } + if (this._parent) delete this._parent; + } + function Sys$UI$Control$onBubbleEvent(source, args) { + /// + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "source"}, + {name: "args", type: Sys.EventArgs} + ]); + if (e) throw e; + return false; + } + function Sys$UI$Control$raiseBubbleEvent(source, args) { + /// + /// + /// + var e = Function._validateParams(arguments, [ + {name: "source"}, + {name: "args", type: Sys.EventArgs} + ]); + if (e) throw e; + var currentTarget = this.get_parent(); + while (currentTarget) { + if (currentTarget.onBubbleEvent(source, args)) { + return; + } + currentTarget = currentTarget.get_parent(); + } + } + function Sys$UI$Control$removeCssClass(className) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "className", type: String} + ]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.removeCssClass(this._element, className); + } + function Sys$UI$Control$toggleCssClass(className) { + /// + /// + var e = Function._validateParams(arguments, [ + {name: "className", type: String} + ]); + if (e) throw e; + if (!this._element) throw Error.invalidOperation(Sys.Res.cantBeCalledAfterDispose); + Sys.UI.DomElement.toggleCssClass(this._element, className); + } +Sys.UI.Control.prototype = { + _parent: null, + _visibilityMode: Sys.UI.VisibilityMode.hide, + get_element: Sys$UI$Control$get_element, + get_id: Sys$UI$Control$get_id, + set_id: Sys$UI$Control$set_id, + get_parent: Sys$UI$Control$get_parent, + set_parent: Sys$UI$Control$set_parent, + get_visibilityMode: Sys$UI$Control$get_visibilityMode, + set_visibilityMode: Sys$UI$Control$set_visibilityMode, + get_visible: Sys$UI$Control$get_visible, + set_visible: Sys$UI$Control$set_visible, + addCssClass: Sys$UI$Control$addCssClass, + dispose: Sys$UI$Control$dispose, + onBubbleEvent: Sys$UI$Control$onBubbleEvent, + raiseBubbleEvent: Sys$UI$Control$raiseBubbleEvent, + removeCssClass: Sys$UI$Control$removeCssClass, + toggleCssClass: Sys$UI$Control$toggleCssClass +} +Sys.UI.Control.registerClass('Sys.UI.Control', Sys.Component); +Type.registerNamespace('Sys'); +Sys.Res={ +'argumentTypeName':'Value is not the name of an existing type.', +'methodRegisteredTwice':'Method {0} has already been registered.', +'cantSetIdAfterInit':'The id property can\'t be set on this object after initialization.', +'cantBeCalledAfterDispose':'Can\'t be called after dispose.', +'componentCantSetIdAfterAddedToApp':'The id property of a component can\'t be set after it\'s been added to the Application object.', +'behaviorDuplicateName':'A behavior with name \'{0}\' already exists or it is the name of an existing property on the target element.', +'notATypeName':'Value is not a valid type name.', +'typeShouldBeTypeOrString':'Value is not a valid type or a valid type name.', +'boolTrueOrFalse':'Value must be \'true\' or \'false\'.', +'stringFormatInvalid':'The format string is invalid.', +'referenceNotFound':'Component \'{0}\' was not found.', +'enumReservedName':'\'{0}\' is a reserved name that can\'t be used as an enum value name.', +'eventHandlerNotFound':'Handler not found.', +'circularParentChain':'The chain of control parents can\'t have circular references.', +'undefinedEvent':'\'{0}\' is not an event.', +'notAMethod':'{0} is not a method.', +'propertyUndefined':'\'{0}\' is not a property or an existing field.', +'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.', +'scriptLoadFailedDebug':'The script \'{0}\' failed to load. Check for:\r\n Inaccessible path.\r\n Script errors. (IE) Enable \'Display a notification about every script error\' under advanced settings.\r\n Missing call to Sys.Application.notifyScriptLoaded().', +'propertyNotWritable':'\'{0}\' is not a writable property.', +'enumInvalidValueName':'\'{0}\' is not a valid name for an enum value.', +'controlAlreadyDefined':'A control is already associated with the element.', +'addHandlerCantBeUsedForError':'Can\'t add a handler for the error event using this method. Please set the window.onerror property instead.', +'namespaceContainsObject':'Object {0} already exists and is not a namespace.', +'cantAddNonFunctionhandler':'Can\'t add a handler that is not a function.', +'scriptLoaderAlreadyLoading':'ScriptLoader.loadScripts cannot be called while the ScriptLoader is already loading scripts.', +'invalidNameSpace':'Value is not a valid namespace identifier.', +'notAnInterface':'Value is not a valid interface.', +'eventHandlerNotFunction':'Handler must be a function.', +'propertyNotAnArray':'\'{0}\' is not an Array property.', +'typeRegisteredTwice':'Type {0} has already been registered. The type may be defined multiple times or the script file that defines it may have already been loaded. A possible cause is a change of settings during a partial update.', +'cantSetNameAfterInit':'The name property can\'t be set on this object after initialization.', +'appDuplicateComponent':'Two components with the same id \'{0}\' can\'t be added to the application.', +'appComponentMustBeInitialized':'Components must be initialized before they are added to the Application object.', +'baseNotAClass':'Value is not a class.', +'methodNotFound':'No method found with name \'{0}\'.', +'arrayParseBadFormat':'Value must be a valid string representation for an array. It must start with a \'[\' and end with a \']\'.', +'cantSetId':'The id property can\'t be set on this object.', +'stringFormatBraceMismatch':'The format string contains an unmatched opening or closing brace.', +'enumValueNotInteger':'An enumeration definition can only contain integer values.', +'propertyNullOrUndefined':'Cannot set the properties of \'{0}\' because it returned a null value.', +'argumentDomNode':'Value must be a DOM element or a text node.', +'componentCantSetIdTwice':'The id property of a component can\'t be set more than once.', +'createComponentOnDom':'Value must be null for Components that are not Controls or Behaviors.', +'createNotComponent':'{0} does not derive from Sys.Component.', +'createNoDom':'Value must not be null for Controls and Behaviors.', +'cantAddWithoutId':'Can\'t add a component that doesn\'t have an id.', +'badTypeName':'Value is not the name of the type being registered or the name is a reserved word.', +'argumentInteger':'Value must be an integer.', +'scriptLoadMultipleCallbacks':'The script \'{0}\' contains multiple calls to Sys.Application.notifyScriptLoaded(). Only one is allowed.', +'invokeCalledTwice':'Cannot call invoke more than once.', +'webServiceFailed':'The server method \'{0}\' failed with the following error: {1}', +'webServiceInvalidJsonWrapper':'The server method \'{0}\' returned invalid data. The \'d\' property is missing from the JSON wrapper.', +'argumentType':'Object cannot be converted to the required type.', +'argumentNull':'Value cannot be null.', +'controlCantSetId':'The id property can\'t be set on a control.', +'formatBadFormatSpecifier':'Format specifier was invalid.', +'webServiceFailedNoMsg':'The server method \'{0}\' failed.', +'argumentDomElement':'Value must be a DOM element.', +'invalidExecutorType':'Could not create a valid Sys.Net.WebRequestExecutor from: {0}.', +'cannotCallBeforeResponse':'Cannot call {0} when responseAvailable is false.', +'actualValue':'Actual value was {0}.', +'enumInvalidValue':'\'{0}\' is not a valid value for enum {1}.', +'scriptLoadFailed':'The script \'{0}\' could not be loaded.', +'parameterCount':'Parameter count mismatch.', +'cannotDeserializeEmptyString':'Cannot deserialize empty string.', +'formatInvalidString':'Input string was not in a correct format.', +'invalidTimeout':'Value must be greater than or equal to zero.', +'cannotAbortBeforeStart':'Cannot abort when executor has not started.', +'argument':'Value does not fall within the expected range.', +'cannotDeserializeInvalidJson':'Cannot deserialize. The data does not correspond to valid JSON.', +'invalidHttpVerb':'httpVerb cannot be set to an empty or null string.', +'nullWebRequest':'Cannot call executeRequest with a null webRequest.', +'eventHandlerInvalid':'Handler was not added through the Sys.UI.DomEvent.addHandler method.', +'cannotSerializeNonFiniteNumbers':'Cannot serialize non finite numbers.', +'argumentUndefined':'Value cannot be undefined.', +'webServiceInvalidReturnType':'The server method \'{0}\' returned an invalid type. Expected type: {1}', +'servicePathNotSet':'The path to the web service has not been set.', +'argumentTypeWithTypes':'Object of type \'{0}\' cannot be converted to type \'{1}\'.', +'cannotCallOnceStarted':'Cannot call {0} once started.', +'badBaseUrl1':'Base URL does not contain ://.', +'badBaseUrl2':'Base URL does not contain another /.', +'badBaseUrl3':'Cannot find last / in base URL.', +'setExecutorAfterActive':'Cannot set executor after it has become active.', +'paramName':'Parameter name: {0}', +'cannotCallOutsideHandler':'Cannot call {0} outside of a completed event handler.', +'cannotSerializeObjectWithCycle':'Cannot serialize object with cyclic reference within child properties.', +'format':'One of the identified items was in an invalid format.', +'assertFailedCaller':'Assertion Failed: {0}\r\nat {1}', +'argumentOutOfRange':'Specified argument was out of the range of valid values.', +'webServiceTimedOut':'The server method \'{0}\' timed out.', +'notImplemented':'The method or operation is not implemented.', +'assertFailed':'Assertion Failed: {0}', +'invalidOperation':'Operation is not valid due to the current state of the object.', +'breakIntoDebugger':'{0}\r\n\r\nBreak into debugger?' +}; +if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded(); diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/TestHelpers/BuildEngine.cs b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/TestHelpers/BuildEngine.cs new file mode 100644 index 0000000..d88e48d --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/TestHelpers/BuildEngine.cs @@ -0,0 +1,55 @@ +using System.Text; +using Microsoft.Build.Framework; +using NUnit.Framework; + +namespace Yahoo.Yui.Compressor.MsBuild.Tests.TestHelpers +{ + public static class BuildEngine + { + public static bool ContainsError(IBuildEngine engine, string error) + { + return CheckForError(engine, error, true); + } + + public static bool DoesNotContainError(IBuildEngine engine, string error) + { + return CheckForError(engine, error, false); + } + + private static bool CheckForError(IBuildEngine engine, string error, bool exists) + { + var buildEngine = engine as BuildEngineStub; + if (buildEngine == null) + { + Assert.Fail("Not a BuildEngineStub, cannot test with this"); + } + if (buildEngine.Errors != null && buildEngine.Errors.Count > 0) + { + foreach (var anError in buildEngine.Errors) + { + if (anError.StartsWith(error)) + { + return exists; + } + } + } + + if (!exists) + { + return true; + } + + var sb = new StringBuilder(); + sb.AppendLine(error + " not found. Actual errors: "); + foreach (var anError in buildEngine.Errors) + { + sb.AppendLine(anError); + } + Assert.Fail(sb.ToString()); + + // ReSharper disable HeuristicUnreachableCode + return !exists; + // ReSharper restore HeuristicUnreachableCode + } + } +} diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/TestHelpers/BuildEngineStub.cs b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/TestHelpers/BuildEngineStub.cs new file mode 100644 index 0000000..a344709 --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/TestHelpers/BuildEngineStub.cs @@ -0,0 +1,63 @@ +using Microsoft.Build.Framework; +using System.Collections; +using System.Collections.Generic; + +namespace Yahoo.Yui.Compressor.MsBuild.Tests.TestHelpers +{ + public class BuildEngineStub : IBuildEngine + { + public BuildEngineStub() + { + Errors = new List(); + } + + public List Errors { get; private set; } + + #region IBuildEngine Members + + public void LogErrorEvent(BuildErrorEventArgs e) + { + Errors.Add(e.Message); + } + + public void LogWarningEvent(BuildWarningEventArgs e) + { + } + + public void LogMessageEvent(BuildMessageEventArgs e) + { + } + + public void LogCustomEvent(CustomBuildEventArgs e) + { + } + + public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, + IDictionary targetOutputs) + { + return true; + } + + public bool ContinueOnError + { + get { return true; } + } + + public int LineNumberOfTaskNode + { + get { return 1; } + } + + public int ColumnNumberOfTaskNode + { + get { return 1; } + } + + public string ProjectFileOfTaskNode + { + get { return string.Empty; } + } + + #endregion + } +} \ No newline at end of file diff --git a/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Yahoo.Yui.Compressor.MsBuild.Tests.csproj b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Yahoo.Yui.Compressor.MsBuild.Tests.csproj new file mode 100644 index 0000000..49043b2 --- /dev/null +++ b/tests/Yahoo.Yui.Compressor.MsBuild.Tests/Yahoo.Yui.Compressor.MsBuild.Tests.csproj @@ -0,0 +1,44 @@ + + + + netcoreapp2.1 + + false + + + + + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + +