/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
* 
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* 
*/
var Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
}
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)}, 
	max : function(v,elm,opt) {return v <= parseFloat(opt)},
	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = elm.parentNode;
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							new Insertion.After(elm, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				advice.style.display = 'block';
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['required', 'This is a required field.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Please enter a valid number in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-date', 'Please enter a valid date.', function(v) {
				var test = new Date(v);
				return Validation.get('IsEmpty').test(v) || !isNaN(test);
			}],
	['validate-email', 'Please enter a valid email address. For example fred@domain.com .', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
				if(!regex.test(v)) return false;
				var d = new Date(v.replace(regex, '$2/$1/$3'));
				return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) && 
							(parseInt(RegExp.$1, 10) == d.getDate()) && 
							(parseInt(RegExp.$3, 10) == d.getFullYear() );
			}],
	['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
				// [$]1[##][,###]+[.##]
				// [$]1###+[.##]
				// [$]0.##
				// [$].##
				return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
			}],
	['validate-selection', 'Please make a selection', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', 'Please select one of the above options.', function (v,elm) {
				var p = elm.parentNode;
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}]
]);

/* Add some custom validations */

Validation.addAllThese([
  ['validate-mandatory-number', 'Please enter a valid number.', {
        include: ['validate-digits', 'required']
      }],

  ['validate-all-selection', 'Please make a selection', function(v,elm){
        var p = elm.parentNode;
        var options = p.getElementsByTagName('SELECT');
        return $A(options).all(function(elm) {
          return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
        });
      }],

  ['validate-all-required', 'These are required fields.', function(v, elm) {
        var p      = elm.parentNode;
        var inputs = p.getElementsByTagName('INPUT');
        return $A(inputs).all(function(elm) {
          return !Validation.get('IsEmpty').test($F(elm));
        });
      }],

  ['validate-two-part-height', 'Please enter a valid height.', function (v,elm) {
        /* This expects mm dd yyyy as the order of select tags */
        var p     = elm.parentNode;
        var parts = p.getElementsByTagName('SELECT');
        return !Validation.get('IsEmpty').test($F(parts[0])) && !/^\s$/.test($F(parts[0])) && !Validation.get('IsEmpty').test($F(parts[1])) && !/^\s$/.test($F(parts[1]));
      }],

  ['validate-gender-radios', 'Please select gender.', function (elm) {
        var p     = elm.parentNode.parentNode; // go two levels up b/c radios are within labels
        var parts = p.getElementsByTagName('INPUT');
        var selection = '';
        for (var i=0;i<parts.length;i++) {
           if (parts[i].checked) selection = parts[i].value;
        }
        return !Validation.get('IsEmpty').test(selection) && /^(m|f|male|female)$/i.test(selection);
      }],

    ['validate-one-part-height', 'Please enter a valid height.', {
          include: ['required', 'validate-number']
        }],

  ['validate-child-weight', 'Please enter a valid weight.', {
        min: 1,
        max: 1000,
        include: ['required', 'validate-number']
      }],

  ['validate-adult-weight', 'Please enter a valid weight.', {
        min: 50,
        max: 1000,
        include: ['required', 'validate-number']
      }],

  ['validate-age-licensed', 'Please enter a valid age.', {
        min: 15,
        max: 100,
        include: ['required', 'validate-number']
      }],

  ['validate-three-part-dob', 'Please enter a valid date of birth.', function (v,elm) {
        /* This expects mm dd yyyy as the order of tags */
        var p     = elm.parentNode;
        var parts = p.getElementsByTagName('SELECT');
        if (parts.length == 0) {
          parts = p.getElementsByTagName('INPUT');
        }

        /* Check to see that this is a valid date format */
        var valid_format = /(^0?[1-9]$)|(^1[012]$)/.test($F(parts[0])) && /(^0?[1-9]$)|(^[12][0-9]$)|(^3[01]$)/.test($F(parts[1])) && /^[0-9]{4}$/.test($F(parts[2]));
        if (valid_format == false) return valid_format;

        var month = $F(parts[0]) * 1 - 1;
        var day   = $F(parts[1]) * 1;
        var year  = $F(parts[2]) * 1;

        var is_leap_year   = ((year % 100 == 0) && (year % 400 == 0)) || ((year % 100 != 0) && (year % 4 == 0));
        var feb_days       = (is_leap_year) ? 29 : 28;
        var days_in_months = [31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        /* Check to make sure that the days doesn't exceed the day in that month */
        if (day > days_in_months[month]) return false;

        /* Now that we know the date is at least a valid format, check to see that the birthdate is within a sensible range */
        var oldest_age_ever = 122;
        var dob                       = new Date(year, month, day);
        var dob_of_oldest_person_ever = new Date(year + oldest_age_ever, month, day);

        var today = new Date();

        /* not_too_young */
        var not_too_young = (today - dob) >= 0;

        /* not_too_old */
        var not_too_old = (dob_of_oldest_person_ever - today) >= 0;

        return (not_too_old && not_too_young);
      }],

  ['validate-coverage-start-date', 'Please enter a valid future date.', function (v,elm) {
        /* This expects mm dd yyyy as the order of tags */
        var p     = elm.parentNode;
        var parts = p.getElementsByTagName('SELECT');
        if (parts.length == 0) {
          parts = p.getElementsByTagName('INPUT');
        }

        /* Check to see that this is a valid date format */
        var valid_format = /(^0?[1-9]$)|(^1[012]$)/.test($F(parts[0])) && /(^0?[1-9]$)|(^[12][0-9]$)|(^3[01]$)/.test($F(parts[1])) && /^[0-9]{4}$/.test($F(parts[2]));
        if (valid_format == false) return valid_format;

        var month = $F(parts[0]) * 1 - 1;
        var day   = $F(parts[1]) * 1;
        var year  = $F(parts[2]) * 1;

        var is_leap_year   = ((year % 100 == 0) && (year % 400 == 0)) || ((year % 100 != 0) && (year % 4 == 0));
        var feb_days       = (is_leap_year) ? 29 : 28;
        var days_in_months = [31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        /* Check to make sure that the days doesn't exceed the day in that month */
        if (day > days_in_months[month]) return false;

        /* Now that we know the date is at least a valid format, check to see that the birthdate is within a sensible range */
        var coverage_date = new Date(year, month, day);

        var today = new Date();

        /* not before yesterday */
        var not_before_yesterday = (today - coverage_date) <= 0;

        /* not after 3 months */
        var three_months_from_now   = new Date();
        three_months_from_now.setDate(today.getDate() + 90);
        var not_after_three_months  = (coverage_date < three_months_from_now);

        return not_before_yesterday && not_after_three_months;
      }],

  ['validate-policy-expires-on', 'Please enter a valid future date.', function (v,elm) {
        /* This expects mm dd yyyy as the order of tags */
        var p     = elm.parentNode;
        var parts = p.getElementsByTagName('SELECT');
        if (parts.length == 0) {
          parts = p.getElementsByTagName('INPUT');
        }

        /* Check to see that this is a valid date format */
        var valid_format = /(^0?[1-9]$)|(^1[012]$)/.test($F(parts[0])) && /(^0?[1-9]$)|(^[12][0-9]$)|(^3[01]$)/.test($F(parts[1])) && /^[0-9]{4}$/.test($F(parts[2]));
        if (valid_format == false) return valid_format;

        var month = $F(parts[0]) * 1 - 1;
        var day   = $F(parts[1]) * 1;
        var year  = $F(parts[2]) * 1;

        var is_leap_year   = ((year % 100 == 0) && (year % 400 == 0)) || ((year % 100 != 0) && (year % 4 == 0));
        var feb_days       = (is_leap_year) ? 29 : 28;
        var days_in_months = [31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        /* Check to make sure that the days doesn't exceed the day in that month */
        if (day > days_in_months[month]) return false;

        /* Now that we know the date is at least a valid format, check to see that the date is within a sensible range */
        var policy_date = new Date(year, month, day);

        var today = new Date();
        today     = new Date(today.getFullYear(), today.getMonth(), today.getDate());

        /* not before yesterday */
        var not_before_yesterday = (today - policy_date) <= 0;
        return not_before_yesterday;
      }],

  ['validate-claim-amount', 'Please enter a valid amount', function (v,elm) {
        if(/\D/.test(v)) {
          return false
        } else {
          if(/^[0]+?$/.test(v)){
            elm.value = 0;
          }
          //trim leading zeros
          $(elm).value = (v).replace(/^0+/, "");
          return true
        }
      }],

  ['validate-state', 'Please enter a valid state abbreviation.', {
        pattern: /^[a-zA-Z]{2}$/,
        include: ['required']
      }],

  ['validate-zip', 'Please enter a valid zip code.', {
        pattern: /^\d{5}$/,
        include: ['required']
      }],

  ['validate-full-name', 'Please enter a first and last name.', {
        pattern: /\w+\s+\w+/,
        include: ['required']
      }],

  ['validate-name', 'Please use letters only (a-z) in this field.', {
        pattern: /^[a-zA-Z\s-']+$/,
        include: ['required']
      }],

  ['validate-mandatory-email', 'Please enter a valid email.', {
        include: ['validate-email', 'required']
      }],

  // Phone patterns checked (000)000-0000, (000) 000-0000, 000-000-0000, 000.000.0000, 000 000 0000, 0000000000
  ['validate-phone', 'Please enter a valid phone number.', {
        pattern: /^\(?[2-9]\d{2}[\)\.-]?\s?[2-9]\d{2}[\s\.-]?\d{4}$/
      }],

  ['validate-mandatory-phone', 'Please enter a valid phone number.', {
        include: ['validate-phone', 'required']
      }],

  ['validate-checked', 'Please check the checkbox.', {
        pattern: /^[1yY]$/,
        include: ['required']
      }]
]);


var BrowserDetect={init:function(){this.browser=this.searchString(this.dataBrowser)||"An unknown browser";this.version=this.searchVersion(navigator.userAgent)||this.searchVersion(navigator.appVersion)||"an unknown version";this.OS=this.searchString(this.dataOS)||"an unknown OS";},searchString:function(data){for(var i=0;i<data.length;i++){var dataString=data[i].string;var dataProp=data[i].prop;this.versionSearchString=data[i].versionSearch||data[i].identity;if(dataString){if(dataString.indexOf(data[i].subString)!=-1)
return data[i].identity;}
else if(dataProp)
return data[i].identity;}},searchVersion:function(dataString){var index=dataString.indexOf(this.versionSearchString);if(index==-1)return;return parseFloat(dataString.substring(index+this.versionSearchString.length+1));},dataBrowser:[{string:navigator.userAgent,subString:"OmniWeb",versionSearch:"OmniWeb/",identity:"OmniWeb"},{string:navigator.vendor,subString:"Apple",identity:"Safari"},{prop:window.opera,identity:"Opera"},{string:navigator.vendor,subString:"iCab",identity:"iCab"},{string:navigator.vendor,subString:"KDE",identity:"Konqueror"},{string:navigator.userAgent,subString:"Firefox",identity:"Firefox"},{string:navigator.vendor,subString:"Camino",identity:"Camino"},{string:navigator.userAgent,subString:"Netscape",identity:"Netscape"},{string:navigator.userAgent,subString:"MSIE",identity:"Explorer",versionSearch:"MSIE"},{string:navigator.userAgent,subString:"Gecko",identity:"Mozilla",versionSearch:"rv"},{string:navigator.userAgent,subString:"Mozilla",identity:"Netscape",versionSearch:"Mozilla"}],dataOS:[{string:navigator.platform,subString:"Win",identity:"Windows"},{string:navigator.platform,subString:"Mac",identity:"Mac"},{string:navigator.platform,subString:"Linux",identity:"Linux"}]};BrowserDetect.init();

/*
*
* Copyright (c) 2007 Andrew Tetlaw
* 
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* * 
*
*
* FastInit
* http://tetlaw.id.au/view/javascript/fastinit
* Andrew Tetlaw
* Version 1.4.1 (2007-03-15)
* Based on:
* http://dean.edwards.name/weblog/2006/03/faster
* http://dean.edwards.name/weblog/2006/06/again/
* Help from:
* http://www.cherny.com/webdev/26/domloaded-object-literal-updated
* 
*/
var FastInit = {
	onload : function() {
		if (FastInit.done) { return; }
		FastInit.done = true;
		for(var x = 0, al = FastInit.f.length; x < al; x++) {
			FastInit.f[x]();
		}
	},
	addOnLoad : function() {
		var a = arguments;
		for(var x = 0, al = a.length; x < al; x++) {
			if(typeof a[x] === 'function') {
				if (FastInit.done ) {
					a[x]();
				} else {
					FastInit.f.push(a[x]);
				}
			}
		}
	},
	listen : function() {
		if (/WebKit|khtml/i.test(navigator.userAgent)) {
			FastInit.timer = setInterval(function() {
				if (/loaded|complete/.test(document.readyState)) {
					clearInterval(FastInit.timer);
					delete FastInit.timer;
					FastInit.onload();
				}}, 10);
		} else if (document.addEventListener) {
			document.addEventListener('DOMContentLoaded', FastInit.onload, false);
		} else if(!FastInit.iew32) {
			if(window.addEventListener) {
				window.addEventListener('load', FastInit.onload, false);
			} else if (window.attachEvent) {
				return window.attachEvent('onload', FastInit.onload);
			}
		}
	},
	f:[],done:false,timer:null,iew32:false
};
/*@cc_on @*/
/*@if (@_win32)
FastInit.iew32 = true;
document.write('<script id="__ie_onload" defer src="' + ((location.protocol == 'https:') ? '//0' : 'javascript:void(0)') + '"><\/script>');
document.getElementById('__ie_onload').onreadystatechange = function(){if (this.readyState == 'complete') { FastInit.onload(); }};
/*@end @*/
FastInit.listen();


var Popup = Class.create({
  initialize : function(uri, options) {
    this.options = {
      toolbar:    'no',
      status:     'no',
      menubar:    'no',
      location:   'no',
      scrollbars: 'yes',
      resizable:  'yes',
      height:     '320',
      width:      '480'
    }
    Object.extend(this.options, options || {});
    
    var window_options = $H(this.options).collect(function(o) { return o[0] + '=' + o[1] }).join(',');
    var win    = window.open(uri, "TellObj", window_options);
    win.opener = top;
    win.focus();
  }
});

// Automatically handle any links with class popup.
FastInit.addOnLoad(function() {
  $$("a.popup").each(function(el) {
    $(el).observe('click', function(e) {
      var ele = Event.element(e);
      new Popup(ele.href, { height: 600, width: 800 });
      if (e) Event.stop(e);
    });
  });
});


// From http://wiki.script.aculo.us/scriptaculous/show/Cookie
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if(!daysToExpire) daysToExpire = 365;
    var d = new Date();
    d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
    expire = 'expires=' + d.toGMTString();
    var path = "path=/"
    var cookieValue = escape(name) + '=' + escape(value || '') + '; ' + path + '; ' + expire + ';';
    return document.cookie = cookieValue;
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]+)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  eraseAll: function() {
    // Get cookie string and separate into individual cookie phrases:
    var cookieString = "" + document.cookie;
    var cookieArray = cookieString.split("; ");

    // Try to delete each cookie:
    for(var i = 0; i < cookieArray.length; ++ i)
    {
      var singleCookie = cookieArray[i].split("=");
      if(singleCookie.length != 2)
        continue;
      var name = unescape(singleCookie[0]);
      Cookie.erase(name);
    }
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  },
  exists: function(cookieName) {
    var cookieValue = Cookie.get(cookieName);
    if(!cookieValue) return false;
    return cookieValue.toString() != "";
  }
};


/*
Copyright (c) 2005 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/*
    The global object JSON contains two methods.

    JSON.stringify(value) takes a JavaScript value and produces a JSON text.
    The value must not be cyclical.

    JSON.parse(text) takes a JSON text and produces a JavaScript value. It will
    return false if there is an error.
*/
var JSON = function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            'boolean': function (x) {
                return String(x);
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            },
            object: function (x) {
                if (x) {
                    var a = [], b, f, i, l, v;
                    if (x instanceof Array) {
                        a[0] = '[';
                        l = x.length;
                        for (i = 0; i < l; i += 1) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a[a.length] = v;
                                    b = true;
                                }
                            }
                        }
                        a[a.length] = ']';
                    } else if (x instanceof Object) {
                        a[0] = '{';
                        for (i in x) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a.push(s.string(i), ':', v);
                                    b = true;
                                }
                            }
                        }
                        a[a.length] = '}';
                    } else {
                        return;
                    }
                    return a.join('');
                }
                return 'null';
            }
        };
    return {
        copyright: '(c)2005 JSON.org',
        license: 'http://www.JSON.org/license.html',
/*
    Stringify a JavaScript value, producing a JSON text.
*/
        stringify: function (v) {
            var f = s[typeof v];
            if (f) {
                v = f(v);
                if (typeof v == 'string') {
                    return v;
                }
            }
            return null;
        },
/*
    Parse a JSON text, producing a JavaScript value.
    It returns false if there is a syntax error.
*/
        parse: function (text) {
            try {
                return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                        text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
                    eval('(' + text + ')');
            } catch (e) {
                return false;
            }
        }
    };
}();

var Flash = new Object();

Flash.data = {};

Flash.transferFromCookies = function() {
  var data = JSON.parse(unescape(Cookie.get("flash")));
  if(!data) data = {};
  Flash.data = data;
  Cookie.erase("flash");
};

Flash.writeDataTo = function(name, element) {
  element = $(element);
  var content = "";
  if(Flash.data[name]) {
    content = Flash.data[name].toString().gsub(/\+/, ' ');
  }
  element.innerHTML = unescape(content);
};
