﻿/*
typeof\(([:a|.|:b|\(]*)getAttribute
*/

try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {};


var gE=function(x){ 
        if(x==''){ return null;}
		return document.getElementById(x);
	  };

var YU = YAHOO.util;
var YUE = YU.Event;
var YUD = YU.Dom;
var YDDM = YU.DDM;
var g$ = function(el) {
            if (!el) { return null; } // nothing to work with
            //object is an event - convert into element
            if(el.target || el.srcElement){
                //el = el.target || el.srcElement;
                el = YUE.getTarget(el);
            }
            if (typeof el != 'string' && !(el instanceof Array) ) { // assuming HTMLElement or HTMLCollection, so pass back as is
                return el;
            }
            if (typeof el == 'string') { // ID
				var elem = document.getElementById(el);
                return ((elem && elem.id!=el)?null:elem);
            }else { // array of ID's and/or elements
                var collection = [];
                for (var i = 0, len = el.length; i < len; ++i) {
                    collection[collection.length] = g$(el[i]);
                }
                return collection;
            }
            return null; // safety, should never happen
        };
//what = true means that must get only what's in the dom tag & NOT attribute
var	TagName = function(elem,what){
        what = what || false;
		// check if the dom elem has a tagName attribute, then return that
		// if elem instanceof Focus.Controls.Ctrl then so it will return the tagName attribute
		if(typeof(elem) == 'string'){
			elem = g$(elem);
		} 
		try{
			//var tagName = elem.getAttribute("tagname") || elem.tagName;
			var tagName = ((what || !elem.getAttribute("tagname"))? elem.tagName : elem.getAttribute("tagname"));

			return tagName.toLowerCase();
		}catch(e){
			return "";
		}
};

Function.prototype.createDelegate = function(obj, args){
  var method = this;
  return function() {
	if(args){
		if(args instanceof Array){
			for(var i=0;i<arguments.length;i++){
				args.push(arguments[i]);
			}
		}
	}else{
		args = arguments;
	}
    return method.apply(obj || window, args);
  };
};



Array.prototype.copy = function(){
 return [].concat([],this);
};

Array.prototype.merge = function(arr){
    arr = arr || [];
    for(var i =0,len=arr.length;i<len;i++){
        this.push(arr[i]);
    }
    return this;
};

Array.prototype.has = function (value) {
	for (var i=0,len=this.length; i < len; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

Array.prototype.index = function (value) {
	for (var i=0,len=this.length; i < len; i++) {
		if (this[i] === value) {
			return i;
		}
	}
	return -1;
};

/*
String.prototype.in = function(values){
    //return (values.indexOf(this)<0?false:true);
	for (var i=0,len=values.length; i < len; i++) {
		if (values[i] === this) {
			return true;
		}
	}
	return false;
};*/

/*The only difference is the args option allows you to optionally supply arguments to the call as well.
For example: setTimeout(myObject.myMethod.createDelegate(myObject, [arg1, arg2]), 100);*/



var killconsole={};

var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

for (var i = 0; i < names.length; ++i){
    killconsole[names[i]] = function() {}
}


// stop console in IE
if (!("console" in window) || !("firebug" in console))
{
    window.console = killconsole;
}

var Focus = {};

Focus.Strict = (document.compatMode == 'CSS1Compat');

/**
 * @class
 * @constructor
 */
Focus.Browser = new function(){
	var ua = navigator.userAgent.toLowerCase();
	/** @type Boolean */
	this.isOpera = (ua.indexOf('opera') > -1);
   	/** @type Boolean */
	this.isSafari = (ua.indexOf('webkit') > -1);
   	/** @type Boolean */
	this.isIE = (window.ActiveXObject);
   	/** @type Boolean */
	this.isIE7 = (ua.indexOf('msie 7') > -1);
	if(this.isIE7){
		//this.isIE = false;
	}
   	/** @type Boolean */
	this.isGecko = !this.isSafari && (ua.indexOf('gecko') > -1);
}();
/**
    Copies all the properties of config to obj only if they already exist.
*/
Focus.applyOnly = function(o,c){
    if(o && c && typeof c == 'object'){
        for(k in o){
            if(typeof(o[k])!='function' && typeof(c[k])!='undefined'){
                o[k] = c[k];
            }
        }
    }
    return o;
};

Focus.merge = function(a,b){
    return YAHOO.lang.merge(a,b);
}
Focus.Logger = function(params){
	var IsLogger = true;//false;//
	if(document.all){
		IsLogger = false;
	}
	if(IsLogger && typeof(ygLogger)!='undefined'){
		return new ygLogger(params.group); 
	}else{
		console = {dir:function(str){},debug:function(str){},info:function(str){},log:function(str){},warn:function(str){}};
	}
	this.debug = function(str){};
	this.log = function(str){};
	return this;
};


// MOST IMP
Focus.id = function(el){
    return YUD.generateId(el);
};

Focus.tmpId = function(el){
    YUD.generateId(el);
};

Focus.Global = {};
Focus.Misc = {};
Focus.Event = {};
Focus.Windows = {};
Focus.Windows.Bubble = {};
Focus.DnD = {};
Focus.DnD.Type = {};
Focus.Controls = {};
Focus.Simul= {};
Focus.Simul.Control = {};
Focus.Simul.Object = {};
Focus.Simul.Dom = {};
Focus.Simul.UI = {};

Focus.Task = {};
Focus.Task.Function = {};
Focus.Task.Misc = {};

/*All Validations*/
Ext.eachKey = function(obj, fn, scope){
    if(typeof obj != "object"){
		return false;
    }
    for(o in obj){
		//key =o, val =obj[o]
		if(fn.call(scope || window, o, obj[o]) === false){ return false; };
	}
	//return true;
};

Focus.Split = function(str,splitter){
			var splitResult=[];
			if(str.indexOf(splitter)>=0){
				splitResult = str.split(splitter);
			}else{
				splitResult.push(str);
			}
			return splitResult;
		};


Focus.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}
Focus.Field = {
	isVisible : function(elm) {
		if(elm.disabled){
			return false;
		}
		while(elm.tagName != 'BODY') {
			if(YUD.getStyle(elm,"display")=="none"){
				return false;
			}
			elm = elm.parentNode;
		}
		return true;
	},
	getValue : function(elm){
		elm = g$(elm);
		return elm.value.trim();
	}
}



Focus.Validator = function(className, error, test, options){
	this.init(className, error, test, options);
};
Focus.Validator.prototype ={
	init : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = options;//$H(options);
			this._test = test;
		} else {
			this.options = test;//$H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		var result = this._test(v,elm);
		var result1 = true;
		var optjson ={};
		if(elm){
		    try{
			    optjson = eval("new Object(" + (elm.getAttribute("options") || "{}") + ")");
		    }catch(e){
			    optjson = {};
		    }
		}    
		for(key in this.options){
			var val = this.options[key];
			if(val=="@att"){
				val = optjson[key];
			}
			result1 = Focus.Validator.methods[key] ? Focus.Validator.methods[key](v,elm,val) : true;
			if(!result1){
				if(Focus.Validation.methods[key]){
					//reset the value of @att to real
					Focus.Validation.methods[key].error = Focus.Validation.methods[key].error.replace(/@att/g,val);
				}	
				break;
			}
		}
		return result && result1;
	}
};
Focus.Validator.methods = {
	pattern : function(v,elm,opt) {return Focus.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) {
		var result = true;
		for(var i=0,len=opt.length;i<len;i++){
			if(opt[i]==v){
				result = false;
				break;
			}
		}
		return result;
	},
	oneOf : function(v,elm,opt) {
		var result = false;
		for(var i=0,len=opt.length;i<len;i++){
			if(opt[i]==v){
				result = true;
				break;
			}
		}
		return result;
	},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == Focus.Field.getValue(opt)},
	pwdEqualsConfirmPwd : function(v,elm,opt) {return v == Focus.Field.getValue(opt)},
	notEqualToField : function(v,elm,opt) {return v != Focus.Field.getValue(opt)},
	include : function(v,elm,opt) {return Ext.each(opt,function(value) {
		return Focus.Validation.get(value).test(v,elm);
	})}
}
/**
* @class Validations
* @desc validations which can be added to a field on the form and the way the error messages are shown
*/
 Focus.Validation = {
	add : function(obj) {
		//className, error, test, options
		if(obj instanceof Array){
			for(var i=0;i<obj.length;i++){
				Focus.Validation.add(obj[i]);			
			}	
		}else{
			var nv = {};
			nv[obj.className] = new Focus.Validator(obj.className, obj.error, obj.test, obj.options);
			Focus.extend(Focus.Validation.methods,nv);
		}
	},
	get : function(name) {
		return  Focus.Validation.methods[name] ? Focus.Validation.methods[name] : Focus.Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Focus.Validator('_LikeNoIDIEverSaw_','',{}) //,
		//IsEmpty : new Focus.Validator('IsEmpty','',function(v) { return  ((v == null) || (v.length == 0)); })
	}
}


Focus.FieldSetValidation = function(fields,options){
	this.init(fields,options);
};

Focus.FieldSetValidation.prototype = {
	init : function(fields,options) {
		this.fields = fields;	
		this.options = options || {};
	},
	validate : function(){
		var result = true;
		for(var i=0,len=this.fields.length;i<len;i++){
			var fv = new Focus.FieldValidation(this.fields[i],this.options);
			var test = fv.validate();
			if(!test){
				result = false;
			}
		}
		return result;
	},
	reset : function(){
		for(var i=0,len=this.fields.length;i<len;i++){
			var fv = new Focus.FieldValidation(this.fields[i],this.options);
			fv.reset();
		}
	}
};	

Focus.FieldValidation = function(field,options){
	this.init(field,options);
};

Focus.FieldValidation.prototype = {
	init : function(field,options) {
		this.options = {};
		Ext.apply(this.options,options || {} ,{
			useTitle : false,
			onElementValidate : function(result, elm) {}
			}
		);
		this.field = g$(field);
		this.prop = false; 
	},
	getValidations : function(){
		var validate = this.field.getAttribute("validation") || "";
		if(validate==""){
			validate = "_NoValidation_";
		}
		validate = Focus.Split(validate," ");
		return validate;
	}, 
	validate : function(){
		var validate = this.getValidations();
		var test;
		for(var i=0,len=validate.length;i<len;i++){
			test = this.test(validate[i],this.options.useTitle);
			if(!test){
				return test; //if one validation fails then return no further checking
			}
		}
		this.options.onElementValidate(test, this.field);
		return test;
	},
	test : function(name,useTitle){
		if(name=="_NoValidation_"){
			return true;
		}
		var elm = this.field;
		var v = Focus.Validation.get(name);
		//var prop = '__advice'+name.camelize();
		try {
		if(Focus.Field.isVisible(elm) && !v.test(Focus.Field.getValue(elm), elm)) {
			if(!this.prop) {
				var advice = this.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 + '-' + this.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);
				    }
				    
				    Ext.get(elm).insertHtml("afterEnd",advice);
				    
				    
					advice = this.getAdvice(name, elm);
				}
				//if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				//} else {
				//	new Effect.Appear(advice, {duration : 1 });
				//}
			}
			this.prop = true;
			YUD.removeClass(elm,'validation-passed');
			YUD.addClass(elm,'validation-failed');
			return false;
		} else {
			var advice = this.getAdvice(name, elm);
			if(advice != null) {
				advice.style.display="none";
			}	
			this.prop = false;
			YUD.removeClass(elm,'validation-failed');
			YUD.addClass(elm,'validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	reset : function() {
		var elm = this.field;
		var validate = this.getValidations();
		for(var i=0,len=validate.length;i<len;i++){
			//if(this.prop) {
			var advice = this.getAdvice(validate[i], elm);
			if(advice){
				advice.style.display="none";
				this.prop = false;
			}
			YUD.removeClass(elm,'validation-failed');
			YUD.removeClass(elm,'validation-passed');
		}
	},	
	getAdvice : function(name, elm) {
		return g$('advice-' + name + '-' + this.getElmID(elm)) || g$('advice-' + this.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	}
};



Focus.Validation.add({className:'IsEmpty',error:'',test:function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			},options:{}});

Focus.Validation.add([
	{className:'required',error: 'This is a required field.',test: function(v) {
				return !Focus.Validation.get('IsEmpty').test(v);
			},options:{}},
	{className:'maxLength',error: 'Maximum Length Required @att.',test: {maxLength:'@att'},options:{}},
	{className:'minLength',error: 'Minimum Length Required @att.',test: {minLength:'@att'},options:{}},
	{className:'min',error: 'Minimum Value is @att.',test: {min:'@att'},options:{}},
	{className:'max',error: 'Maximum Value is @att.',test: {max:'@att'},options:{}},
	{className:'notOneOf',error: 'Should not be in list [@att].',test: {notOneOf:'@att'},options:{}},
	{className:'oneOf',error: 'Should be in list [@att].',test: {oneOf:'@att'},options:{}},
	{className:'is',error: 'Value is not equal to @att.',test: {is:'@att'},options:{}},
	{className:'isNot',error: 'Value should not be equal to @att.',test: {isNot:'@att'},options:{}},
	{className:'equalToField',error: 'Value is not equal to @att.',test: {equalToField:'@att'},options:{}},
	{className:'pwdEqualsConfirmPwd',error: 'Password and Confirm Password are not matched.',test: {pwdEqualsConfirmPwd:'@att'},options:{}},
	{className:'notEqualToField',error: 'Value should not be equal to @att.',test: {notEqualToField:'@att'},options:{}},
	{className:'validate-number',error: 'Please enter a valid number in this field.',test: function(v) {
				return Focus.Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			},options:{}},
	{className : 'validate-digits',error: 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.',test: function(v) {
				return Focus.Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			},options:{}},
	{className:'validate-date',error: 'Please enter a valid date.',test: function(v) {
				var test = new Date(v);
				return Focus.Validation.get('IsEmpty').test(v) || !isNaN(test);
			},options:{}},
	{className:'validate-email',error: 'Please enter a valid email address. For example fred@domain.com .', test: function (v) {
				return Focus.Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v);
			},options:{}},
	{className:'validate-url',error: 'Please enter a valid URL.',test: function (v) {
				return Focus.Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v);
			},options:{}},
	{className:'validate-url-no-http',error: 'Please enter a valid URL.',test: function (v) {
				return Focus.Validation.get('IsEmpty').test(v) || /^(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v);
			},options:{}},
	{className:'validate-selection', error:'Please make a selection',test: function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Focus.Validation.get('IsEmpty').test(v);
			},options:{}},
	{className:'validate-date-att',error: 'Please enter a valid date.',test: function(v,elm) {
				var IsEmpty = Focus.Validation.get('IsEmpty').test(v);
				var format = elm.getAttribute("format") || "m-d-Y";
				Focus.Validation.methods["validate-date-att"].error = "Please enter a valid date. Date format is [" + format + "]";
				var test = Date.parseDate(v,format) || false;
				return IsEmpty || test;
			},options:{}},
	{className:'validate-name',error: 'Please enter a valid name. Only A-Z, a-z, 0-9, _, - characters are allowed.',test: function (v) {
				return Focus.Validation.get('IsEmpty').test(v) || /^[A-Z|a-z|0-9|_|\-|\s]+$/i.test(v);
			},options:{}},
	{className:'validate-name-with-and',error: 'Please enter a valid name. Only A-Z, a-z, 0-9, _, -,& characters are allowed.',test: function (v) {
				return Focus.Validation.get('IsEmpty').test(v) || /^[A-Z|a-z|0-9|_|\-|\s|\&]+$/i.test(v);
			},options:{}},
	{className:'first-char-only-eng-char',error: 'Name should start from an english character A-Z,a-z',test: function (v) {
				return Focus.Validation.get('IsEmpty').test(v) || /^[A-Z|a-z]/i.test(v);
			},options:{}},
	{className:'validate-emails-with-comma',error: 'Please enter a valid email addresses with comma delimited. For example fred@domain.com,tom@domain.com .', test: function (v) {
	            var flag = Focus.Validation.get('IsEmpty').test(v);
	            if(!flag){
	                var arr = Focus.Split(v,',');
                    flag = true;
                    var emailrg = /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/;
                    for(var i=0,len = arr.length;i<len;i++){
                        var email = String(arr[i]).trim();
                        if(email.length>0){ //check if some value found
                            if(!emailrg.test(email)){
                                flag = false;
                                break;
                            }    
                        }
                    }
	            }
				return flag;
			},options:{}}
	]);


