
var ErmJS = {
	Utility: {
		Validators: new new Class({
			Validate: function(target){
				var validators = target.getElements("span.validator");
				var valid = true;
				for (var x = 0; x < validators.length; x++) {
					ValidatorValidate(validators[x]);
					if (validators[x].getStyle("visibility") == "visible") {
						valid = false;
					}
				}
				return valid;
			},
			Toggle: function(target, onoff){
				var validators = target.getElements("span.validator");
				for (var x = 0; x < validators.length; x++) {
					ValidatorEnable(validators[x], onoff);
				}
			}
		}),
		ViewStateHandler: new Class({}),
		SetModalizer: function(mod){
			mod.setModalOptions({
				modalStyle: {
					background: "#000000"
				}
			});
		},
		InputTextHolder: new Class({
		    initialize: function(target,text) {
		        this.target = target;
		        this.placeholderText = text;
		        this.target.addEvent("focus",this.enterEvent.bind(this));
		        this.target.addEvent("blur",this.leaveEvent.bind(this));
		        window.addEvent("domready", this.leaveEvent.bind(this));
		    },
		    leaveEvent: function() {
		        if (this.target.get("value") == "") {
		            this.target.setStyle("color","#5E5E5E");
		            this.target.set("value",this.placeholderText);
		        }
		    },
		    enterEvent: function() {
		        if (this.target.get("value") == this.placeholderText) {
		            this.target.setStyle("color","#000000");
		            this.target.set("value","");
		        }
		    }  
		}),
		AjaxProRequest: new Class({
			Extends: Request,
			initialize: function(arguments){
				this.arguments = arguments;
				this.nSpace = arguments.nSpace;
				this.failureFunc = arguments.onFailure;
				if ($defined(arguments.retryAttempts)) {
				    this.retryAttempts = arguments.retryAttempts;
				} else {
				    this.retryAttempts = 0;
				}
				var url = "/ajaxpro/" + this.nSpace;
				if (this.nSpace.indexOf("Erm.Web.Common") > -1) url += ",Erm.Web.Common.ashx";
				else url += ",Erm.Web.ashx";
				this.parent({
					method: "post",
					url: url,
					onSuccess: function(){
					    //console.log(this.data);
					   // try {
						    // MooTools appends "value:{}" to returned strings. This is a pain, so we remove it.
						    returnobj = ErmJS.Utility.SafeJsonParse(this.response.text).value;
						    if (typeof(returnobj) == "string") {
						        returnobj = ErmJS.Utility.SafeJsonParse(returnobj);
						    }
						    this.arguments.onSuccess.run([{
							    json: returnobj
						    }, this.arguments.onSuccessParams, this]);
						//} catch(err) {
						//    alert(err);
						//    this.failureFunc.run();
						//}
					}.bind(this)					,
					onFailure: function() {
					    if (this.retryAttempts > 0) {
					        this.retryAttempts = this.retryAttempts - 1;
					        this.send(this.data);
					    } else {
					        this.failureFunc.run();
					    }
					}.bind(this),
					data: JSON.encode(arguments.arguments),
					link: arguments.link,
					headers: {
						"Content-Type": "text/plain; charset=utf-8",
						"X-AjaxPro-Method": arguments.methodName,
						"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
					},
					urlEncoded: false
				});
			},
			send: function(data) {
			    this.data = data;
			    this.parent(data);
			}
		}),
		// This is a compressed version of json_sans_eval. 
		// Copyright (C) 2008 Google Inc.
		//
		// Licensed under the Apache License, Version 2.0 (the "License");
		// you may not use this file except in compliance with the License.
		// You may obtain a copy of the License at
		//
		//      http://www.apache.org/licenses/LICENSE-2.0
		//
		// Unless required by applicable law or agreed to in writing, software
		// distributed under the License is distributed on an "AS IS" BASIS,
		// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		// See the License for the specific language governing permissions and
		// limitations under the License.
		SafeJsonParse: (function(){var number='(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)';var oneChar='(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]'+'|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';var string='(?:\"'+oneChar+'*\")';var jsonToken=new RegExp('(?:false|true|null|[\\{\\}\\[\\]]'+'|'+number+'|'+string+')','g');var escapeSequence=new RegExp('\\\\(?:([^u])|u(.{4}))','g');var escapes={'"':'"','/':'/','\\':'\\','b':'\b','f':'\f','n':'\n','r':'\r','t':'\t'};function unescapeOne(_,ch,hex){return ch?escapes[ch]:String.fromCharCode(parseInt(hex,16))}var EMPTY_STRING=new String('');var SLASH='\\';var firstTokenCtors={'{':Object,'[':Array};var hop=Object.hasOwnProperty;return function(json,opt_reviver){var toks=json.match(jsonToken);var result;var tok=toks[0];if('{'===tok){result={}}else if('['===tok){result=[]}else{throw new Error(tok);}var key;var stack=[result];for(var i=1,n=toks.length;i<n;++i){tok=toks[i];var cont;switch(tok.charCodeAt(0)){default:cont=stack[0];cont[key||cont.length]=+(tok);key=void 0;break;case 0x22:tok=tok.substring(1,tok.length-1);if(tok.indexOf(SLASH)!==-1){tok=tok.replace(escapeSequence,unescapeOne)}cont=stack[0];if(!key){if(cont instanceof Array){key=cont.length}else{key=tok||EMPTY_STRING;break}}cont[key]=tok;key=void 0;break;case 0x5b:cont=stack[0];stack.unshift(cont[key||cont.length]=[]);key=void 0;break;case 0x5d:stack.shift();break;case 0x66:cont=stack[0];cont[key||cont.length]=false;key=void 0;break;case 0x6e:cont=stack[0];cont[key||cont.length]=null;key=void 0;break;case 0x74:cont=stack[0];cont[key||cont.length]=true;key=void 0;break;case 0x7b:cont=stack[0];stack.unshift(cont[key||cont.length]={});key=void 0;break;case 0x7d:stack.shift();break}}if(stack.length){throw new Error();}if(opt_reviver){var walk=function(holder,key){var value=holder[key];if(value&&typeof value==='object'){var toDelete=null;for(var k in value){if(hop.call(value,k)&&value!==holder){var v=walk(value,k);if(v!==void 0){value[k]=v}else{if(!toDelete){toDelete=[]}toDelete.push(k)}}}if(toDelete){for(var i=toDelete.length;--i>=0;){delete value[toDelete[i]]}}}return opt_reviver.call(holder,key,value)};result=walk({'':result},'')}return result}})(),

	    SessionTimeout: new Class({
	        initialize: function(timeout) {
	            //this.timeoutTime = new Date().increment("ms",timeout);
	            
	            this.timeoutFunction = this.timeoutAction.delay(timeout - 180000,this);
	            window.addEvent("unload",this.clearTimer.bind(this));
	        },
	        clearTimer: function() {
	            $clear(this.timeoutFunction);
	        },
	        timeoutAction: function() {
	            var split = captable[1386].split("#time#");
	            this.timeoutLeft = 180000;
	            var text = split[0] + "</p><div id='timeoutbox' class='timeouttime'>3:00</div><p><span id='timeouttext'>" + split[1] + "</span>";
	            this.confirmBox = ErmJS.Controls.confirm({
	                title: captable[1385],
	                text: text,
	                width: 500,
	                okText: captable[1387],
	                cancelText: captable[1388],
	                cancelFunction: function() {
	                    window.location = "/content/common/sessionclear.aspx";
	                },
	                okFunction: this.keepLoggedIn.bind(this),
	                overrideOkDefault: true,
	                overrideCancelDefault: true
	            });
	            this.tickerInstance = this.timeoutTicker.periodical(1000,this);
	        },
	        timeoutTicker: function() {
	            this.timeoutLeft = this.timeoutLeft - 1000;
	            var minutes = 0;
	            var seconds = this.timeoutLeft / 1000;
	            if (this.timeoutLeft >= 120000) {
	                minutes = 2;
	                seconds = seconds - 120;
	            } else if (this.timeoutLeft >= 60000) {
	                minutes = 1;
	                seconds = seconds - 60;
	            }
	            if (seconds < 10) seconds = "0" + seconds;
	            $('timeoutbox').set("html",minutes + ":" + seconds);
	            if (this.timeoutLeft == 0) {
	                $clear(this.tickerInstance);
	                this.timedOutFunction();
	            }
	        },
	        timedOutFunction: function() {
	            $(this.confirmBox).getElement(".graybutton").dispose();
	            var targetDiv = $(this.confirmBox).getElement(".orangebutton").getParent();
	            $(this.confirmBox).getElement(".orangebutton").dispose();
	            targetDiv.adopt($(new ErmJS.Controls.ColorButton(captable[1390],"orange",function(e) {e.stop; window.location = "/content/common/sessionclear.aspx";})));
	            $('timeouttext').set("html",captable[1389]);
	            $('timeouttext').setStyles({
	                "font-weight": "bold",
	                "color": "#990000"
	            });
	        },
	        keepLoggedIn: function(e) {
	            e.stop();
	            this.waiterLayer = new Waiter($(this.confirmBox).getElement(".body"), {
	                layer: {
	                    styles: {"margin-left": "-10px"}
	                }
	            });
	            this.waiterLayer.start();
	            new ErmJS.Utility.AjaxProRequest({
                    nSpace: "Erm.Web.Common.Handlers.AjaxAssistant",
                    methodName: "KeepSessionAlive",
                    onSuccess: this.loggedInRefresh.bind(this)
                }).send();
	        },
	        loggedInRefresh: function(data) {
	            if (data.json == true) {
	                $clear(this.tickerInstance);
	                this.waiterLayer.stop();
	                this.confirmBox.destroy();
	            } else {
	                window.location = "/content/common/sessionclear.aspx";
	            }
	        }
	    }),
	    AutoHideUlHandler: new Class({ 
	        initialize: function() {
	            if ($(document.body).hasClass("ie")) {
	                this.doAutoHideSetup();
	             //   window.addEvent("load",);
	            }
	        },
	        doAutoHideSetup: function() {
	            var targets = $$(".autohideul");
	            for (var x = 0; x<targets.length;x++) {
	                var indTarget = targets[x].getElement("ul");
	                if (indTarget != null) {
	                    /* because of weird z-index issues, we have to take the <ul> out of the DOM and put it back in at the end */
	                    /* set it to block so we can measure it, but keep it invisible*/
	                    indTarget.setStyles({
	                        "display":"block",
	                        "visibility":"hidden"
	                    });
	                    var position = indTarget.getPosition(window);
    	                var size = indTarget.getSize();
	                    /* set it back */
	                    indTarget.setStyles({
	                        "display":"none",
	                        "visibility":"visible"
	                    });
    	                indTarget.addClass("detatchedautohideul");
	                    $(document.body).grab(indTarget);
    	                indTarget.setStyles({
    	                    top: position.y,
    	                    left: targets[x].getPosition(window).x - size.x + 10
    	                });
    	                
	                    $$([targets[x],indTarget]).addEvents({
	                        "mouseenter": function() {
	                            this.setStyle("display","block");
	                        }.bind(indTarget),
	                        "mouseleave": function(e) {
	                            this.setStyle("display","none");
	                        }.bindWithEvent(indTarget)
	                    });
	                }
	            }
	        }
	    }),
	    ForgotPassword: new Class({
	        initialize: function(args) {
	            this.args = args;
	            this.args.link.addEvent("click", this.showForgotBox.bind(this));
	            
	            this.confirmBox = null;
	        },
	        showForgotBox: function(e) {
	            e.stop();
	            
                this.confirmBox = ErmJS.Controls.confirm({
                    title: captable[333],
                    contentHolder: this.args.contentDiv.clone(),
                    width: 500,
                    okText: captable[335],
                    cancelText: captable[341],
                    okFunction: this.sendPasswordFunction.bind(this),
                    overrideOkDefault: true

                });
	           
	        },
	        sendPasswordFunction: function(e) {
	            e.stop();
	            var targetTextbox = $(this.confirmBox).getElement("input");
	            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
                if (emailPattern.test(targetTextbox.value) == false) {
                    targetTextbox.addClass("error");
                    $(this.confirmBox).getElement("p").setStyles({
	                    "font-weight": "bold",
	                    "color": "#990000"
	                });
                    $(this.confirmBox).getElement("p").set("html",captable[437]);
                    targetTextbox.focus();
                } else {
	                this.waiterLayer = new Waiter($(this.confirmBox).getElement(".body"), {
	                    layer: {
	                        styles: {"margin-left": "-10px"}
	                    }
	                });
	                this.waiterLayer.start();
	                 new ErmJS.Utility.AjaxProRequest({
                        nSpace: "Erm.Web.Common.Handlers.AjaxAssistant",
                        methodName: "SendPassword",
                        arguments: {
                            email: targetTextbox.value
                        },
                        onSuccess: this.returnAjax.bind(this)
                    }).send();
                }
	        },
	        returnAjax: function(json) {
	            var targetTextbox = $(this.confirmBox).getElement("input");
	            if (json.json > 0) {
	                $(this.confirmBox).getElement("p").setStyles({
	                    "font-weight": "bold",
	                    "color": "#990000"
	                });
	            } else {
	                $(this.confirmBox).getElement("p").setStyles({
	                    "font-weight": "normal",
	                    "color": "#000000"
	                });
	            }
	            if (json.json == 1) {
	                $(this.confirmBox).getElement("p").set("html",captable[437]);
	                targetTextbox.addClass("error");
	                targetTextbox.focus();
	            } else if (json.json == 3) {
	                 $(this.confirmBox).getElement("p").set("html",captable[1395]);
	            } else {
	                 $(this.confirmBox).getElement("p").set("html",captable[443]);
	                 $(this.confirmBox).getElements(".graybutton, .orangebutton").dispose();
	                 $(this.confirmBox).getElement("ol").dispose();
	                 var closeButton = new ErmJS.Controls.ColorButton(captable[1233],"orange",function() {this.hide(); this.destroy();}.bind(this.confirmBox));
	                 $(this.confirmBox).getElement(".body").getFirst().getLast("div").adopt(closeButton);
	            }

	            this.waiterLayer.stop();
	        }
	    })
	}
}






