// Core Taobase Javascript functionality
var tao = {
    form: {
		errorClass: 'formError',
		errorMessages: [],
        // Validates a form element to a given rule which can either be a 
        // function or a string corresponding to a library function
        validateElement: function(formEle, validationFn, errorMessage, className) {
			formEle = $(formEle);
			if (!formEle) return false;
            if (tao.form.isElementValid(formEle, validationFn)) {
                tao.form.removeError(formEle);
                tao.form.removeErrorMessage(errorMessage);
                return true;
            } else {
            	tao.form.errorClass = className || tao.form.errorClass;
                tao.form.displayError(formEle, errorMessage, className);
                tao.form.storeErrorMessage(errorMessage);
                return false;
            }
        },
        // Check whether one of a set of radio buttons is selected
        validateRadioButtons: function(name, message) {
        	var buttons = $$('input[name='+name+']');
        	if (!buttons || buttons.length == 0) return false;
        	return tao.form.validateElement(buttons.last().up(), function() {
        		return !!$$('input[name='+name+']').find(function(ele){return ele.checked;});
        	}, message);
        },
        isElementValid: function(formEle, validationFn) {
            if (null === $(formEle)) return false;
            if ((typeof validationFn == "object" || typeof validationFn == "function") && typeof validationFn.match == "function") {
            	return tao.form.validate.regex($F(formEle), validationFn);
            } else if (typeof validationFn == 'function') {
                return validationFn(formEle);
            } else if (typeof tao.form.validate[validationFn] == 'function') {
                validationFn = tao.form.validate[validationFn];
                return validationFn(formEle);
            }
            return false;
        },
        // Displays an error message beneath a specified element.
        displayError: function(ele, message, className) {
            if (tao.form.isErrorElementCreated(ele)) {
                ele.next().update(message);
            } else {
                ele.insert({after: new Element('div', {'class': tao.form.errorClass}).update(message)});
            }
        },
        flushErrorMessages: function() {
        	tao.form.errorMessages = [];
        },
        storeErrorMessage: function(message) {
        	if (message && tao.form.errorMessages.indexOf(message) == -1) {
        		tao.form.errorMessages.push(message);
        	}
        },
        removeErrorMessage: function(message) {
        	var index = tao.form.errorMessages.indexOf(message);
        	if (index != -1) {
        		delete tao.form.errorMessages[index];
        		tao.form.errorMessages = tao.form.errorMessages.compact();
            }
        },
        removeError: function(ele) {
            if (tao.form.isErrorElementCreated(ele)) {
                ele.next().remove();
            }
        },
        removeAllErrors: function(ele) {
            $(ele).select('.'+tao.form.errorClass).invoke('remove');
        },
        isErrorElementCreated: function(ele) {
            return !!(ele.next() && ele.next().className == tao.form.errorClass);
        },
        // Library of validation functions
        validate: {
            regex: function(testString, regEx) {
                return testString.search(regEx) != -1;
            },
            required: function(test) {
                return !$F(test).strip().empty();
            },
            nonzero: function(test) {
                return parseInt($F(test), 10) > 0;
            },
            emailAddress: function(test) {
                return tao.form.validate.regex($F(test), /^\w+([.\-+]\w+)*@[A-Za-z0-9]+([.-]\w+)*\.[A-Za-z]+$/);
            },
            drivingLicense: function(test) {
            	return tao.form.validate.regex($F(test), /^[A-Z]{5}\d{6}[A-Z]{2}[A-Z0-9]{3}$/);
            },
            password: function(test) {
                return tao.form.validate.regex($F(test), /^.{6,}$/);
            },
            postcode: function(test) {
                return tao.form.validate.regex($F(test), /^[a-zA-Z][a-zA-Z0-9]{1,3}\s*\d[a-zA-Z]{2}$/);
            },
            phoneNumber: function(test) {
                return tao.form.validate.regex($F(test), /^[\d() ]{10,}$/);
            },
            vehicleRegistration: function(test) {
            	return tao.form.validate.regex($F(test), /^([A-Z]{1,2}\d{2}\s*[A-Z]{3}|[A-Z]\d+\s*[A-Z]{3})$/);
            },
            date: function(test) {
                return tao.form.validate.regex($F(test), /^(0[1-9]|1[012])\/\d{2}$/);
            },
            englishdate: function(test) {
            	return tao.form.validate.regex($F(test), /^\d{2}\/\d{2}\/\d{4}$/);
            },
            ddmmyy: function(ele) {
            	return tao.form.validate.regex($F(test), /^[0-3]?[0-9]\/\d{2}\/\d{2}$/);
            },
            price: function(test) {
                return tao.form.validate.regex($F(test), /^\d+\.\d{2}$/);
            },
            checked: function(ele) {
            	return ele.checked == true;
            },
            mobileNumber: function(test) {
                return tao.form.validate.regex($F(test), /^[\d() -+]{10,11}/);
            },
            securityNumber: function(test) {
                return tao.form.validate.regex($F(test), /^\d{3,4}$/);
            },
            issueNumber: function(test) {
                return tao.form.validate.regex($F(test), /^\d+$/);
            },
            cardNumber: function(test) {
                var length = $F(test).length;
                if (0 == length) return false;
                var total = 0;
                var valid = true;
                var digits = 0 - length;
                var i = -1;
                while (i >= digits) {
                    if ((i % 2) == 0) {
                        var digit = 2 * ($F(test).substring(length+i, length+i+1));
                        digit = digit.toString();
                        total += parseInt(digit.substring(0, 1));
                        if (digit.length > 1) {
                            total += parseInt(digit.substring(1,2));
                        }
                    } else {
                        total += parseInt($F(test).substring(length+i, length+i+1));
                    }
                    i--;
                }
                if ((total % 10) != 0){
                    valid = false;
                }
                return valid;
            }
        },
        tips: {
			init: function() {
				tao.form.tips.defaultText = new Hash();
				$$('.formTip').each(tao.form.tips.storeDefaultText)
				              .invoke('observe', 'click', tao.form.tips.clearDefaultText)
				              .invoke('observe', 'blur', tao.form.tips.restoreDefaultText);
			},
			storeDefaultText: function(ele) {
				tao.form.tips.defaultText.set(ele.identify(), $F(ele));
			},
			clearDefaultText: function(event) {
				var input = event.findElement('input');
				if ($F(input) == tao.form.tips.defaultText.get(input.identify())) {
					input.clear();
				}
			},
			restoreDefaultText: function(event) {
				var input = event.findElement('input');
				if ($F(input).strip().empty()) {
					input.setValue(tao.form.tips.defaultText.get(input.identify()));
				}
			}
        }
    },
    date: {
    	getFormattedDatetime: function(datetime) {
			var year = datetime.getFullYear();
			var month = tao.date.convertToTwoDigits(datetime.getMonth()+1);
			var day = tao.date.convertToTwoDigits(datetime.getDate());
			var hour = tao.date.convertToTwoDigits(datetime.getHours());
			var minutes = tao.date.convertToTwoDigits(datetime.getMinutes());
			var seconds = tao.date.convertToTwoDigits(datetime.getSeconds());
			return day+'-'+month+'-'+year+' '+hour+':'+minutes;
		},
		convertToTwoDigits: function(number) {
			return (number < 10) ? "0"+number : number;
		},
		getNextDatetimeByHour: function(hour, offsetDate) {
			var offsetDate = offsetDate || new Date();
			var datetime = new Date();
			datetime.setTime(offsetDate.getTime());
			if (offsetDate.getHours() >= hour) {
				datetime.setTime(offsetDate.getTime() + 24*60*60*1000);
			}
			datetime.setHours(hour);
			datetime.setMinutes(0);
			datetime.setSeconds(0);
			return datetime;
		},
		getDatetimeFromString: function(string) {
			var matches = string.match(/^(\d+)-(\d+)-(\d+) (\d+):(\d+)$/);
			if (!matches || matches.length != 6) return null;
			var datetime = new Date();
			datetime.setFullYear(matches[3]);
			datetime.setMonth(matches[2]-1);
			datetime.setDate(matches[1]);
			datetime.setHours(matches[4]);
			datetime.setMinutes(matches[5]);
			datetime.setSeconds(0);
			return datetime;
		}
    },
    // Cookie manipulation
    cookie: {
        set: function(key, value, days) {
            if (days) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                var expires = "; expires="+date.toGMTString();
            } else var expires = "";
            document.cookie = key+"="+value+expires+"; path=/";
        },
        get: function(key)
        {
            var keyEquals = key+"=";
            var value = null;
            document.cookie.split(';').each(function(s){
                s = s.replace(/^\s*/, '');
                if (s.startsWith(keyEquals)) {
                    value = s.substring(keyEquals.length, s.length);
                    throw $break;
                }
            });
            return value;
        },
        clear: function(key) {
            tao.cookie.set(key, '', -1);
        }
    },
    // Positioning of elements
    position: {
    	getViewportOffset: function(ele) {
    	    var positionInWindow = ele.cumulativeOffset();
    	    var viewportPosition = document.viewport.getScrollOffsets();
    		return [positionInWindow[0] - viewportPosition[0], positionInWindow[1] - viewportPosition[1]];
    	},
        centreInViewport: function(ele) {
	        var positionLeft = document.viewport.getWidth()/2 - ele.getDimensions().width/2;
	        var positionTop = document.viewport.getScrollOffsets().last() + document.viewport.getHeight()/2 - ele.getDimensions().height/2;
	        ele.setStyle({
	            top: String(positionTop)+'px',
	            left: String(positionLeft)+'px'
	        });
	    },
	    centreHorizontally: function(ele) {
	        var positionLeft = document.viewport.getWidth()/2 - ele.getDimensions().width/2;
	        ele.setStyle({ left: String(positionLeft)+'px' });
	    },
        nextToClick: function(ele, clickX, clickY) {
            // Determine top position
            var eleHeight = ele.getDimensions().height;
            var distanceToViewPortBottom = document.viewport.getScrollOffsets().last() + document.viewport.getHeight() - clickY;
            var distanceToViewPortTop = clickY - document.viewport.getScrollOffsets().last();
            var positionTop;
            if (distanceToViewPortBottom > eleHeight) {
                positionTop = clickY;    
            } else if (distanceToViewPortTop > eleHeight) {
                positionTop = clickY - eleHeight; 
            } else {
                positionTop = clickY - eleHeight/2;
            }
            // Determine left position
            var eleWidth = ele.getDimensions().width;
            var distanceToViewPortRight = document.viewport.getScrollOffsets().first() + document.viewport.getWidth() - clickX;
            var distanceToViewPortLeft = clickX - document.viewport.getScrollOffsets().first();
            var positionLeft;
            if (distanceToViewPortRight > eleWidth) {
                positionLeft = clickX;    
            } else if (distanceToViewPortLeft > eleWidth) {
                positionLeft = clickX - eleWidth; 
            } else {
                positionLeft = clickX - eleWidth/2;
            }
            
            // Set position
            ele.setStyle({
                top: String(positionTop)+'px',
                left: String(positionLeft)+'px'
            });
        }
    },
    // Debugging
    debug: {
        log: function() {
            if (typeof console == 'object') {
                if (arguments.length == 1) {
                    console.log(arguments[0]);
                } else {
                    console.log(arguments);
                }
            }
        },
        timer: function() {
            tao.debug.log('['+tao.debug.getExecutionTime().toFixed(3)+' seconds]');
            tao.debug.log(arguments);
        },
        getExecutionTime: function() {
            date = new Date();
            if (!tao.debug.startTime) {
                tao.debug.startTime = date.getTime();
                return 0;
            } else {
                var totalMilliseconds = date.getTime() - tao.debug.startTime;
                var totalSeconds = totalMilliseconds/1000;
                return totalSeconds;
            }
        }
    },
    analytics: {
        track: function(path) {
            try {
                pageTracker._trackPageview(path);
            } catch (error) {
                tao.debug.log(error.message);
            }
        },
        event: function(category, action, label, value) {
        	try {
                pageTracker._trackEvent(category, action, label, value);
            } catch (error) {
                tao.debug.log(error.message);
            } 
        }
    },
    timer: {
    	delayId: null,
    	delay: function(pointer, delaySeconds) {
    		if(typeof(tao.timer.delayId) != 'undefined') {
    			clearTimeout(tao.timer.delayId);
    		}
    		tao.timer.delayId = pointer.delay(delaySeconds);
    	}
    }
};
(function($){
$.jGrowl=function(m,o){
if($("#jGrowl").size()==0){
$("<div id=\"jGrowl\"></div>").addClass($.jGrowl.defaults.position).appendTo("body");
}
$("#jGrowl").jGrowl(m,o);
};
$.fn.jGrowl=function(m,o){
if($.isFunction(this.each)){
var _6=arguments;
return this.each(function(){
var _7=this;
if($(this).data("jGrowl.instance")==undefined){
$(this).data("jGrowl.instance",$.extend(new $.fn.jGrowl(),{notifications:[],element:null,interval:null}));
$(this).data("jGrowl.instance").startup(this);
}
if($.isFunction($(this).data("jGrowl.instance")[m])){
$(this).data("jGrowl.instance")[m].apply($(this).data("jGrowl.instance"),$.makeArray(_6).slice(1));
}else{
$(this).data("jGrowl.instance").create(m,o);
}
});
}
};
$.extend($.fn.jGrowl.prototype,{defaults:{pool:0,header:"",group:"",sticky:false,position:"top-right",glue:"after",theme:"default",corners:"10px",check:250,life:3000,speed:"normal",easing:"swing",closer:true,closeTemplate:"&times;",closerTemplate:"<div>[ close all ]</div>",log:function(e,m,o){
},beforeOpen:function(e,m,o){
},open:function(e,m,o){
},beforeClose:function(e,m,o){
},close:function(e,m,o){
},animateOpen:{opacity:"show"},animateClose:{opacity:"hide"}},notifications:[],element:null,interval:null,create:function(_17,o){
var o=$.extend({},this.defaults,o);
this.notifications.push({message:_17,options:o});
o.log.apply(this.element,[this.element,_17,o]);
},render:function(_19){
var _1a=this;
var _1b=_19.message;
var o=_19.options;
var _19=$("<div class=\"jGrowl-notification ui-state-highlight ui-corner-all"+((o.group!=undefined&&o.group!="")?" "+o.group:"")+"\">"+"<div class=\"close\">"+o.closeTemplate+"</div>"+"<div class=\"header\">"+o.header+"</div>"+"<div class=\"message\">"+_1b+"</div></div>").data("jGrowl",o).addClass(o.theme).children("div.close").bind("click.jGrowl",function(){
$(this).parent().trigger("jGrowl.close");
}).parent();
$(_19).bind("mouseover.jGrowl",function(){
$("div.jGrowl-notification",_1a.element).data("jGrowl.pause",true);
}).bind("mouseout.jGrowl",function(){
$("div.jGrowl-notification",_1a.element).data("jGrowl.pause",false);
}).bind("jGrowl.beforeOpen",function(){
if(o.beforeOpen.apply(_19,[_19,_1b,o,_1a.element])!=false){
$(this).trigger("jGrowl.open");
}
}).bind("jGrowl.open",function(){
if(o.open.apply(_19,[_19,_1b,o,_1a.element])!=false){
if(o.glue=="after"){
$("div.jGrowl-notification:last",_1a.element).after(_19);
}else{
$("div.jGrowl-notification:first",_1a.element).before(_19);
}
$(this).animate(o.animateOpen,o.speed,o.easing,function(){
if($.browser.msie&&(parseInt($(this).css("opacity"),10)===1||parseInt($(this).css("opacity"),10)===0)){
this.style.removeAttribute("filter");
}
$(this).data("jGrowl").created=new Date();
});
}
}).bind("jGrowl.beforeClose",function(){
if(o.beforeClose.apply(_19,[_19,_1b,o,_1a.element])!=false){
$(this).trigger("jGrowl.close");
}
}).bind("jGrowl.close",function(){
$(this).data("jGrowl.pause",true);
$(this).animate(o.animateClose,o.speed,o.easing,function(){
$(this).remove();
var _1d=o.close.apply(_19,[_19,_1b,o,_1a.element]);
if($.isFunction(_1d)){
_1d.apply(_19,[_19,_1b,o,_1a.element]);
}
});
}).trigger("jGrowl.beforeOpen");
if($.fn.corner!=undefined){
$(_19).corner(o.corners);
}
if($("div.jGrowl-notification:parent",_1a.element).size()>1&&$("div.jGrowl-closer",_1a.element).size()==0&&this.defaults.closer!=false){
$(this.defaults.closerTemplate).addClass("jGrowl-closer ui-state-highlight ui-corner-all").addClass(this.defaults.theme).appendTo(_1a.element).animate(this.defaults.animateOpen,this.defaults.speed,this.defaults.easing).bind("click.jGrowl",function(){
$(this).siblings().children("div.close").trigger("click.jGrowl");
if($.isFunction(_1a.defaults.closer)){
_1a.defaults.closer.apply($(this).parent()[0],[$(this).parent()[0]]);
}
});
}
},update:function(){
$(this.element).find("div.jGrowl-notification:parent").each(function(){
if($(this).data("jGrowl")!=undefined&&$(this).data("jGrowl").created!=undefined&&($(this).data("jGrowl").created.getTime()+$(this).data("jGrowl").life)<(new Date()).getTime()&&$(this).data("jGrowl").sticky!=true&&($(this).data("jGrowl.pause")==undefined||$(this).data("jGrowl.pause")!=true)){
$(this).trigger("jGrowl.beforeClose");
}
});
if(this.notifications.length>0&&(this.defaults.pool==0||$(this.element).find("div.jGrowl-notification:parent").size()<this.defaults.pool)){
this.render(this.notifications.shift());
}
if($(this.element).find("div.jGrowl-notification:parent").size()<2){
$(this.element).find("div.jGrowl-closer").animate(this.defaults.animateClose,this.defaults.speed,this.defaults.easing,function(){
$(this).remove();
});
}
},startup:function(e){
this.element=$(e).addClass("jGrowl").append("<div class=\"jGrowl-notification\"></div>");
this.interval=setInterval(function(){
$(e).data("jGrowl.instance").update();
},this.defaults.check);
if($.browser.msie&&parseInt($.browser.version)<7&&!window["XMLHttpRequest"]){
$(this.element).addClass("ie6");
}
},shutdown:function(){
$(this.element).removeClass("jGrowl").find("div.jGrowl-notification").remove();
clearInterval(this.interval);
},close:function(){
$(this.element).find("div.jGrowl-notification").each(function(){
$(this).trigger("jGrowl.beforeClose");
});
}});
$.jGrowl.defaults=$.fn.jGrowl.prototype.defaults;
})(jQuery);


var swc = {};

swc.event = {
	eventDomUpdated: 'swc:dom:updated',
	
	fireDomUpdatedEvent: function()
	{
		$j(document).trigger(swc.event.eventDomUpdated);
	}
}

// POPUP ENGINE
// Relies on jQuery UI
swc.popup = {
	
	counter: 0,
	
	create: function(content, options)
	{
		if (typeof(options.reusePopup) == 'undefined' || options.reusePopup == true) {
			swc.popup.closeLast();
		}
		if (typeof(options.modal) == 'undefined') {
			options.modal = true;
		}
		if (typeof(options.closeButton) == 'undefined') {
			options.closeButton = true;
		}
		
		swc.popup.counter++;
		closeCall = (typeof(options.close) == 'undefined') ? '' : options.close;
		openCall = (typeof(options.open) == 'undefined') ? '' : options.open;
		
		// On open callback
		options.open = function(event, ui) { 
			eval(openCall);
			if (!options.closeButton) {
				$j(event.target).parents('.ui-dialog').find(".ui-dialog-titlebar-close").hide();
			}
		};
		if (!options.closeButton) {
			options.closeOnEscape = false;
		}
		
		// Onclose callback
		options.close = function(event) { $j(this).remove(); eval(closeCall); };
		if (typeof(options.position) == 'undefined') {
			options.position = ['center', 65];
		}
		$j('body').append('<div id="popup_number_'+swc.popup.counter+'">'+content+'</div>');
		$j('#popup_number_'+swc.popup.counter).dialog(options);
		swc.event.fireDomUpdatedEvent();
	},
	
	closeLast: function()
	{
		ele = $j('.ui-dialog-titlebar-close').last();
		if(ele) { ele.trigger('click'); }
	}
};


// Dialog's engine
// Relies on swc.popup + jQuery UI
swc.dialog = {
		
	alert: function (content, options)
	{
		if ('undefined' == typeof(options) || null == options) {
			options = new Array();
		}
		if (typeof(options.title) == 'undefined') {
			options.title = "Information";
		}
		options.reusePopup = false;
		options.buttons = {
			'OK': function() {
				swc.popup.closeLast();
			}
		};
		swc.popup.create(content, options);
	},
	
	confirm: function (content, options, okCallback, okText)
	{
		if ('undefined' == typeof(okText) || null == okText || '' == okText) {
			okText = 'OK';
		}
		
		if ('undefined' == typeof(options) || null == options) {
			options = new Array();
		}
		
		if (typeof(options.title) == 'undefined') {
			options.title = "Please confirm";
		}
		
		options.buttons = {
			'Cancel': function() {
				swc.popup.closeLast();
			}
		};
		
		options.buttons[okText] = function() {
		    swc.popup.closeLast();
			eval(okCallback);
		}
		options.reusePopup = false;
		swc.popup.create(content, options);
	},
	
	loading: function(content, options)
	{
		if ('undefined' == typeof(options) || null == options) {
			options = new Array();
		}
		if (typeof(options.title) == 'undefined') {
			options.title = "Please wait...";
		}
		options.closeButton = false;
		content += '<br /><br /><div class="swc_ProgressBar"></div>';
		swc.popup.create(content, options);
	},
	
	closeLast: function()
	{
		swc.popup.closeLast();
	}
};

// Notifications engine
// Relies on jGrowl and jQuery
$j.jGrowl.defaults.position = 'bottom-right';
swc.notifier = {
		
	notify: function(message, options)
	{
		$j.jGrowl(message, options);
	},
	
	notifyError: function(message, options)
	{
		if (undefined == options) {
			options = new Array();
		}
		options.sticky = true;
		options.theme = 'ui-state-error';
		$j.jGrowl(message, options);
	},
	
	error: function(message, options)
	{
		if (undefined == options) {
			options = new Array();
		}
		if (typeof(options.dialogClass) == 'undefined') {
			options.dialogClass = "ui-error";
		} else {
			options.dialogClass += " ui-error";
		}
		return swc.dialog.alert(message, options);
	}
};

// OTHER - DEPRECATED

var SwcInit = {
    page: function() {
    	return;
    },

    ajax: function(e) {
    	return;
    }
};

/**
 * Core JS library for SWC 
 * version: $Id: swc.js 2934 2010-09-03 12:31:28Z tilleyshortd $
 */
var Swc = {

    DelayId: null,

    // Delays any JS function by intDelay secons with an auto cancel if executed again
    Delay: function(functionToCall, delay) {
		tao.timer.delay(functionToCall, delay)
    },

    /**
     * Open / Close popup functions
     */
    OpenPopup: function(Title,Width,Height) {
        startPopup(Title,'divPopupContainer','divPopupTitle', Width, Height);
        SwcInit.ajax($('divPopupContainer'));
    },
    ClosePopup: function() {
        stopPopup('divPopupContainer','divPopup');
    },
    
    /**
     * Provides the basic notification functionality
     */
	Notify: function(message, options) {
    	return swc.notifier.notify(message, options);
    },
    
    NotifyStop: function() {
        return true;
    },
    
    Error: function(message, options) {
    	return swc.notifier.error(message, options);
    },
    
    loader: function(EleId) {
      $(EleId).update('<div class="swc_Loading"></div>');
    },
    
    progress: function(EleId) {
      $(EleId).update('<div class="swc_ProgressBar"></div>');
    },
    
    deleteCookie: function(name, path, domain) {
        return tao.cookie.clear(name);
    },
    
    getCookie: function(name) {
    	return tao.cookie.get(name);
    },
    
    setCookie: function(name, value, expires, path, domain, secure) {
    	return tao.cookie.set(name, value, 30);
	},
	
	
    loadFile: function (Filename, FileType) {
        
        switch(FileType) {
            case "js":
                var fileref=document.createElement('script')
                fileref.setAttribute("type","text/javascript")
                fileref.setAttribute("src", Filename)
                break;
                
            case "css":
                var fileref=document.createElement("link")
                fileref.setAttribute("rel", "stylesheet")
                fileref.setAttribute("type", "text/css")
                fileref.setAttribute("href", Filename)
            break;
        }
        if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
    },
    
    
    unloadFile: function (Filename, FileType) {
        var targetelement=(FileType=="js")? "script" : (FileType=="css")? "link" : "none" //determine element type to create nodelist from
        var targetattr=(FileType=="js")? "src" : (FileType=="css")? "href" : "none" //determine corresponding attribute to test for
        var allsuspects=document.getElementsByTagName(targetelement)
        for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
            if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(Filename)!=-1)
            allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
        }
    },
    
	
	loadStylesheet: function (Filename) {
		return Swc.loadFile(Filename, 'css');
	},
	
	
	unloadStylesheet: function(Filename) {
		return Swc.unloadFile(Filename, 'css');
	}	
};


var SwcSidebar = {
		
	defaultOptions: {
		effect: false
	},
    	
	open: function(Title, Content) 
	{
		//var options = typeof sidebarOptions==undefined ? SwcSidebar.defaultOptions : sidebarOptions;
		
        Sidebar = document.createElement('div');
        if(Effect){
        	Sidebar.hide();
        }
        $$('body')[0].appendChild(Sidebar);
        Sidebar.id = 'swc_Sidebar';
        Sidebar.update('<div id="swc_SidebarHeader"><div id="swc_SidebarClose" onclick="SwcSidebar.close();"></div><div id="swc_SidebarTitle"></div></div><div id="swc_SidebarContent"></div>');
        $('swc_SidebarContent').update(Content);
        $('swc_SidebarTitle').update(Title);
        SwcSidebar.updateSize.delay(3);
        SwcSidebar.observeResize.delay(5);
        
        //if(options.effect && Effect) 
        //{
	    //	Effect.BlindDown('swc_Sidebar');
	    //}
        //else {
        	$('swc_Sidebar').show();
        //}
	},
    
	close: function() {
		document.stopObserving('resize', SwcSidebar.updateSize);
		if(Effect){
			Effect.BlindUp($('swc_Sidebar'), {afterFinish: function(){
				$$('body')[0].removeChild($('swc_Sidebar'));
			}});
		}else{
			$$('body')[0].removeChild($('swc_Sidebar'));
		}
	},
    
    observeResize: function() {
        document.observe('resize',SwcSidebar.updateSize);
    },
	
	updateSize: function() {
		NewHeight = (document.viewport.getHeight() - $('swc_SidebarHeader').getHeight() - 105);
		if($$('#swc_SidebarContent iframe')[0]) {
			$$('#swc_SidebarContent iframe')[0].style.height = NewHeight + 'px';
		}
	}

};


var SwcUtils = {

    createInfoBox: function(element) {
        
        InfoId      = element.identify()+'_info';
        PopulateId  = element.identify()+'_content';
        
        if($(InfoId)) {
            $(InfoId).show();
            $(InfoId).clonePosition(element);
            $(InfoId).style.top = parseInt($(InfoId).style.top) + element.getHeight() + 'px';
            return PopulateId;
        }
        
        InfoEle = new Element('span');
        element.up(0).appendChild(InfoEle);
        InfoEle.id = InfoId;
        InfoEle.absolutize();
        InfoEle.addClassName('swc_FieldInfo');
        InfoEle.clonePosition(element);
        InfoEle.style.height = null;
        InfoEle.style.top = parseInt(InfoEle.style.top) + element.getHeight() + 'px';
        InfoEle.update('<div class="swc_Pad" id="'+PopulateId+'"></div>');
        return PopulateId;
    },

    textarea: {
    	
    	adjustSize: function(e) {
            element = Event.element(e);
    		CloneId = element.identify()+'_clone';
            Data = SwcUtils.string.nl2br($F(element));
            Data = SwcUtils.string.htmlentities(Data);
    		$(CloneId).update(Data);
    		NewHeight = $(CloneId).getHeight();
    		if(NewHeight > element.getHeight()) {
    		  element.style.height = NewHeight+'px';
    		}
    	},
    	
        activate: function(e) {
        	
        	element = Event.element(e);
        	CloneId = element.identify()+'_clone';
            
            element.observe('blur',SwcUtils.input.deactivate);
            SwcUtils.input.maxLengthPrepare(element);
            
        	if($(CloneId)) {
        		return true;
        	}
        	TextClone = document.createElement('div');
            $$('body')[0].appendChild(TextClone);
            TextClone.id = CloneId;
            TextClone.style.fontSize = element.style.fontSize;
            TextClone.style.fontFamily = element.style.fontFamily;
            TextClone.style.padding = element.style.padding;
            TextClone.style.width = element.getWidth()+'px';
            TextClone.style.position = 'absolute';
            TextClone.style.left = '-999em';
            element.observe('keypress',SwcUtils.textarea.adjustSize);
            return true;
        }
    },
    
    input: {
        
        activate: function(e) {
            element = Event.element(e);
            element.observe('blur',SwcUtils.input.deactivate);
            SwcUtils.input.maxLengthPrepare(element);
            return true;
        },

        createInfoBox: function(element) {
            
            InfoId      = element.identify()+'_info';
            PopulateId  = element.identify()+'_content';
            
            if($(InfoId)) {
                $(InfoId).show();
                $(InfoId).clonePosition(element);
                $(InfoId).style.width = '35px';
                $(InfoId).style.height = '25px';
                $(InfoId).style.top = parseInt($(InfoId).style.top) + 'px';
                $(InfoId).style.left = (parseInt($(InfoId).style.left) + element.getWidth()) + 'px';
                return PopulateId;
            }
            
            InfoEle = document.createElement('span');
            element.up(0).appendChild(InfoEle);
            InfoEle.id = InfoId;
            InfoEle.absolutize();
            InfoEle.addClassName('swc_FieldInfo');
            InfoEle.clonePosition(element);
            InfoEle.style.height = null;
            InfoEle.style.top = parseInt(InfoEle.style.top) + element.getHeight() + 'px';
            InfoEle.update('<div class="swc_Pad" id="'+PopulateId+'"></div>');
            return PopulateId;
        },
    	
        deactivate: function(e) {
            element = Event.element(e);
            CounterId = element.identify()+'_info';
            if($(CounterId)) {
                $(CounterId).hide();
            }
        },
        
    	maxLengthInit: function(e) {
    		SwcUtils.input.maxLengthPrepare(Event.element(e));
    	},
    	/*
    	 * RICHARD NOBLE 02-07-09
    	 * 
    	 * Modified the key ounting code due to JS errors
    	 * 
    	 * 1. Changed the event from keypress to keyup to correctly get the content length
    	 * 
    	 * 2. added a wrapper to allow the monitorMaxLength top be called via wrapMonitorKeyPress (passed an event)
    	 * or via monitorMaxLength as an element. 
    	 */
    	maxLengthPrepare: function(element) {
            
            if(!element.hasAttribute('maxlength')) return false;
            
            MaxLength = element.getAttribute('maxlength');
            if(!element.hasClassName('swc_Maxlength')) return false;  
            
            PopulateId  = SwcUtils.input.createInfoBox(element);
            $(PopulateId).update(element.getAttribute('maxlength'));
            
            element.observe('keyup',SwcUtils.input.wrapMonitorKeyPress);
            SwcUtils.input.monitorMaxLength(element);
        },
        
        wrapMonitorKeyPress: function (e){
        	element     = Event.element(e);
        	SwcUtils.input.monitorMaxLength(element);
        },
        
        monitorMaxLength: function(element) {
            
            MaxLen      = element.getAttribute('maxlength');
            CharsLeft   = MaxLen - $F(element).length;
            PopulateId  = SwcUtils.input.createInfoBox(element);
            
            $(PopulateId).update(CharsLeft);
            
            if(element.value.length > MaxLen) {
                NewValue = element.value.truncate(MaxLen,'');
                element.value = NewValue;
                $(PopulateId).update("-");
            }
        }
        
    },
    
    string: {
    	
    	makeFriendlyUrl: function(string) {
    		newString = string.gsub(/([ ])/, '-').gsub(/([^a-zA-Z0-9_-])/, '').toLowerCase();
    		return newString;
    	},
    	
    	nl2br: function(str) {
    	   breakTag = '<br />';
    	   return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
    	}
    }

};

/**
 * Core SWC TinyMCE configurations
 * Version: $Id: tiny.js 2897 2010-06-28 15:41:59Z szczesnym $
 */
var Tiny = {
  tinyConfigs: {
      'default': {
        mode: "specific_textareas",
        plugins: "spellchecker,media",
        theme: "advanced",
        theme_advanced_toolbar_location: "top",
        theme_advanced_buttons1: "bold,italic,underline,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist",
        theme_advanced_buttons2: "forecolor,image,code,anchor,html,link,unlink,spellchecker,media",
        theme_advanced_buttons3: "",
        convert_urls: false,
        theme_advanced_statusbar_location: "bottom",
        theme_advanced_path: false,
        theme_advanced_resize_horizontal: false,
        theme_advanced_resizing: true,
        cleanup_on_startup: true,
        apply_source_formatting: true,
        extended_valid_elements: "object[width|height],param[name|value],embed[src|type|wmode|width|height]",
        width: "100%",
        spellchecker_rpc_url: "js/common/tiny_mce/plugins/spellchecker/rpc.php"},
        
    'simple': {
        mode: "specific_textareas",
        theme: "simple",
        width: "100%" }
  },
  
  /**
   * Registers alternative tinyMCE configuration
   */
  addConfig: function(ConfigurationName, ConfigurationObject) {
      Tiny.tinyConfigs[ConfigurationName] = ConfigurationObject;
  },
  
  // Disables tinyMCE on ElementId
  disable: function(ElementId) {
      tinyMCE.execCommand('mceRemoveControl', false, ElementId);
  },
  
  /**
   * Enables editor on any ElementId, with a given ConfigurationName
   */
  enable: function(ElementId, ConfigurationName) {
    if(typeof(ConfigurationName) == 'undefined') {
        ConfigurationName = 'default';
    }
    if(typeof(Tiny.tinyConfigs[ConfigurationName]) == 'undefined') {
        ConfigurationName = 'default';
    }
    tinyMCE.settings = Tiny.tinyConfigs[ConfigurationName];
    tinyMCE.execCommand('mceAddControl', true, ElementId);
  },
  
  save: function()
  {
    tinyMCE.triggerSave();
  }
};/**
 * File browser interface for SWC 
 * version: $Id: filebrowser.js 2532 2009-10-30 15:09:24Z szczesnym $
 */

var FileBrowser = {

  /**
   * Close the file browser
   */
  close: function() {
      return swc.popup.closeLast();
  },
  
  /**
   * SelectionFunction:
   *  - JS function that will be called on the file, ie. doSomething({FileId});
   *  - {FileId} bracket that will be replaced with an ID of the file
   * Filter: empty, 'Images','PdfDocuments','OfficeDocuments','ZipFiles'
   */
  open: function(SelectionFunction, Filter) {
      return xajax_openFileManager(Filter, SelectionFunction);
  }
  
}


// Most of the code below is deprecated!

		var currentMenuId   = null;
		document.onclick    = check;
		
		function check(e){
		    if(currentMenuId) {
		        var target  = (e && e.target) || (event && event.srcElement);
		        var obj     = $('AdminMenu_' + currentMenuId);
		        var objIcon = $('AdminMenuIcon_' + currentMenuId);
		        var objBlSet= $('aibs_' + currentMenuId);
		        var objBtSet= $('aibts_' + currentMenuId);
		        if (obj) {
		            if (target!=obj && target!=objIcon && target!=objBlSet && target!=objBtSet) {
		                closeAdminNav(currentMenuId);
		            }
		        }
		    }
		}
		
		
        var PopupsCounter = 0;
        var PageReloadRequired = 0;
		var EditorOnClose = 0;
		
		// POPUPS
        function openPopup(Title, Width, Height) { startPopup(Title,'divPopupContainer','divPopupTitle', Width, Height); }
        function hidePopup() { stopPopup('divPopupContainer','divPopup'); }
		
        function openPopup2(Title, Width, Height) { startPopup(Title,'divPopup2Container','divPopup2Title', Width, Height); }
        function hidePopup2() { stopPopup('divPopup2Container','divPopup2'); }
        
        // deprecated
        function startPopup(Title, PopupContainerDiv, PopupTitleDiv, Width, Height) {
            var Dimmer = 'divDimmer';
            if( typeof( window.innerWidth ) == 'number' ) { // Non-IE
                $(Dimmer).style.position = 'fixed';
                intHeight = document.body.parentNode.scrollHeight;
                intWidth  = document.body.parentNode.scrollWidth;
            } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { // IE 6+ in 'standards compliant mode'
                intHeight = Math.max(document.body.parentNode.scrollHeight, document.documentElement.clientHeight);
                intWidth  = Math.max(document.body.parentNode.scrollWidth, document.documentElement.clientWidth);
            } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { // IE 4 compatible (quirk mode)
                intHeight = document.body.parentNode.scrollHeight-20;
                intWidth  = document.body.parentNode.scrollWidth-20;
            }
            $(Dimmer).style.height = intHeight+'px';
            $(Dimmer).style.width  = intWidth+'px';
            intPopWidth = Math.floor(intWidth * 0.9);
            intPopHeight = '90%';
            strTop = '5%';
            strLeft = '5%';
            if(typeof(Width) == 'number') {
              intPopWidth = Width;
              strLeft = ((intWidth - intPopWidth) / 2)+'px';
            }
            $(PopupContainerDiv).style.width  = intPopWidth+'px';
            $(PopupContainerDiv).style.top = strTop;
            $(PopupContainerDiv).style.left = strLeft;
            
            var arrSelects = $$('body select');
            if(arrSelects) {
              for (x=0;x<arrSelects.length;x++) {
                if(!arrSelects[x].descendantOf(PopupContainerDiv)) {
                    arrSelects[x].style.visibility='hidden';
                }
              }
            }
            $(PopupTitleDiv).innerHTML = Title;
            $(Dimmer).style.display = 'block';
            $(PopupContainerDiv).style.display = 'block';
            loadingStop();
            window.scrollTo(0,0);
            new Draggable(PopupContainerDiv, {handle:PopupTitleDiv});
            loadTooltips(PopupContainerDiv);
            
        }
        
        function stopPopup(PopupContainerDiv,PopupDiv) {
            if(EditorOnClose && currentEditorId) {
                switchOffEditor(currentEditorId);
            }
            Dimmer = 'divDimmer';
			$(Dimmer).style.display = 'none';
			$(Dimmer).style.height = '1px';
			$(PopupContainerDiv).style.display = 'none';
			$(PopupDiv).innerHTML = '';
			if(PageReloadRequired) {
			    printSaveMessage('Reloading Page... Please wait...');
			    document.location=document.location;
			}
            var arrSelects = $$('body select');
            if(arrSelects) {
              for (x=0; x<arrSelects.length; x++) {
                if(!arrSelects[x].descendantOf(PopupContainerDiv)) {
                    arrSelects[x].style.visibility='visible';
                }
              }
            }
        }
		
		function printSaveMessage(Message) {
            Swc.Notify(Message);
		}
				
		function loading() {
		    //$('divLoading').style.display = 'block';
		}
		function loadingStop() {
		    //$('divLoading').style.display = 'none';
		}
		function loadPageVersion() {
		    $('ai_divPageVersion').innerHTML = 'Loading page...';
		}
		
		
		function checkUploadForm() {
		    // You can do some checks here
		    $('ai_FileUploadSubmit').disabled = 'true';
		    $('ai_FileUploadSubmit').value   = 'Uploading...';
		    return xajax.upload('uploadFile','ai_FileManager_UploadForm');
		
		}
		
		
		function openAdminNav(BlockId) {
		    if(currentMenuId) {
		        closeAdminNav(currentMenuId);
		    }
		    currentMenuId   = BlockId;
		    desiredTop      = $('AdminMenuIcon_'+BlockId).offsetTop  + 23;
		    desiredLeft     = $('AdminMenuIcon_'+BlockId).offsetLeft - 229;
		    arrBlocks       = $$('.ai_cb');
            for(x=0;x<arrBlocks.length;x++){
                arrBlocks[x].style.zIndex = '0';
            }
            $('aicb_'+BlockId).style.zIndex           = '1';
		    $('AdminMenu_'+BlockId).style.top         = desiredTop+'px';
		    $('AdminMenu_'+BlockId).style.left        = desiredLeft+'px';
		    $('AdminMenu_'+BlockId).style.display     = 'block';
		}
		
		function closeAdminNav(BlockId) {
		    $('AdminMenu_'+BlockId).style.display     = 'none';
		    currentMenuId   = null;
		}
		
		
		// FUNCTION TO DELAY / CANCELL ONKEYUP
		var ActionTimer = null;
		
		function delayedOnKeyUpAction(FunctionToCall,Delay) {
		    if(ActionTimer) {
		        clearTimeout(ActionTimer);
		    }
		    ActionTimer     = setTimeout(FunctionToCall,Delay);
		}
		
		var MoveBlockId = null;
		var MoveDirection = null;
		var MoveDivId = null;
		
		var ShadowDiv = null;
		var ddRevert = true;
		var myDrags = [];
		
		function startDragging(BlockId) {
		    MoveBlockId = BlockId;
		    //console.log('Dragged BlockId:' + BlockId);
		}
		
		var OverBlockMarked = null;
		
		function calculateDrop(DropBlock,DraggedBlock) {
		
		    Container = DropBlock.parentNode;
		
		    if(ShadowDiv) {
		        ShadowDiv = null;
		    }
		    if($('_Shadow')) {
		        Container = $('_Shadow').parentNode;
		        Container.removeChild($('_Shadow'));
		    }
		
		    ShadowDiv = document.createElement("div");
		    ShadowDiv.setAttribute('id', '_Shadow');
		    ShadowDiv.setAttribute('style','float:left;position:relative;margin:-2px;border:2px dashed #aaa;');
		    ShadowDiv.style.width = DraggedBlock.style.width;//.clientWidth + 'px';
		    ShadowDiv.style.height = DraggedBlock.clientHeight + 'px';
		    MoveDivId = DropBlock.id;
		
		    booBefore = calculateDropBefore(DropBlock,DraggedBlock);
		    if(booBefore) {
		        MoveDirection = 'Before';
		        Container.insertBefore(ShadowDiv, DropBlock);
		        ddRevert = false;
		    }
		    else {
		        MoveDirection = 'After';
		        Container.insertBefore(ShadowDiv, DropBlock.nextSibling);
		        ddRevert = false;
		    }
		}
		
		function calculateDropBefore(DropBlock,DraggedBlock) {
		
		    Dragged_x = getX(DraggedBlock);
		    Drop_x = getX(DropBlock);
		    Dragged_mx = Dragged_x + 0.5 * DraggedBlock.clientWidth;
		    Drop_mx = Drop_x + 0.5 * DropBlock.clientWidth;
		    if(Dragged_mx > Drop_mx) {
		        return false;
		    }
		    return true;
		}
		
		
		function endDragging(BlockId) {
		
		    if($('_Shadow')) {
		        //console.log('End of drag: MoveBlockId = ', MoveBlockId, '; MoveDirection = ', MoveDirection, '; MoveDivId = ', MoveDivId);
		        TargetContainer = $('_Shadow').parentNode;
		        switch(MoveDirection) {
		            case 'Before':
		                TargetContainer.insertBefore($('aicb_'+MoveBlockId), $(MoveDivId));//insertbefore);
		                xajax_moveBlock(MoveBlockId,MoveDivId,'Before');
		                break;
		            case 'After':
		                TargetContainer.insertBefore($('aicb_'+MoveBlockId), $(MoveDivId).nextSibling);//insertbefore);
		                xajax_moveBlock(MoveBlockId,MoveDivId,'After');
		                break;
		        }
		        $('aicb_'+MoveBlockId).style.top = null;
		        $('aicb_'+MoveBlockId).style.left = null;
		
		        TargetContainer.removeChild($('_Shadow'));
		        MoveBlockId = null;
		        MoveDirection = null;
		        MoveDivId = null;
		        ddRevert = true;
		        return true;
		    }
		    else {
		        return true;
		    }
		}
		
		function getY(oElement) {
		    var iReturnValue = 0;
		    while( oElement != null ) {
		        iReturnValue += oElement.offsetTop;
		        oElement = oElement.offsetParent;
		    }
		    return iReturnValue;
		}
		
		function getX(oElement) {
		    var iReturnValue = 0;
		    while (oElement != null) {
		        iReturnValue += oElement.offsetLeft;
		        oElement = oElement.offsetParent;
		    }
		    return iReturnValue;
		}

		var currentEditorId         = null;
		var currentContentBlockId   = null;
		
        if(typeof(tinyMCE) !== 'undefined') {
	        tinyMCE.init({
		        mode: "specific_textareas",
		        editor_selector : "mceEditor",
		        plugins: "spellchecker,media",
		        theme: "advanced",
		        theme_advanced_toolbar_location: "top",
		        theme_advanced_buttons1: "bold,italic,underline,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist",
		        theme_advanced_buttons2: "forecolor,image,code,anchor,html,link,unlink,spellchecker,media",
		        theme_advanced_buttons3: "",
		        convert_urls: false,
		        theme_advanced_statusbar_location: "bottom",
		        theme_advanced_path: false,
		        theme_advanced_resize_horizontal: false,
		        theme_advanced_resizing: true,
		        cleanup_on_startup: true,
		        apply_source_formatting: true,
		        extended_valid_elements: "object[width|height],param[name|value],embed[src|type|wmode|width|height]",
		        width: "100%" });
        }
		
		function switchOnEditor(ElementId, ContentBlockId, PopupEditor) {
		    if(currentEditorId) {
		        switchOffEditor(currentEditorId); 
		        xajax_getHtmlContent(currentContentBlockId,1);
		    }
		    if(PopupEditor) { EditorOnClose = 1; }
		    currentEditorId         = ElementId;
		    currentContentBlockId   = ContentBlockId;
		    
		    $(ElementId).style.height = "300px";
		    //Tiny.enable(ElementId);
		    tinyMCE.execCommand('mceAddControl', false, ElementId);
		}
		
		function switchOffEditor(ElementId) {
		    tinyMCE.execCommand('mceRemoveControl', false, ElementId);
		    //Tiny.disable(ElementId);
		    currentEditorId         = null;
		    EditorOnClose           = 0;
		}
		
		var arrTooltips=[];
        var arrTipIds=[];

        function loadTooltips(ContainerDiv) {
            if(typeof(Tip) == 'undefined') return;
		    if(ContainerDiv) {
		        var arrTips = $$('body #'+ContainerDiv+' [tip]');
		    } else {
		        var arrTips = $$('body [tip]');
		    }
		    arrTipIdsTmp=[];
		    if(arrTips) {
		        for (x=0; x<arrTips.length; x++) {
		          tid = arrTips[x].readAttribute('tip');
		          if(arrTipIds.indexOf(tid) == -1) {
		            arrTipIdsTmp.push(tid);
		            arrTipIds.push(tid);
		          }
		        }
		    }
		    if(arrTipIdsTmp) xajax_loadTooltips(arrTipIdsTmp);
		}
		
		function setTooltip(Tid, Tooltip, booSticky) {
		    var arrTipTags = $$('body [tip='+Tid+']');
		    for (x=0; x<arrTipTags.length; x++) {
		      if(booSticky) {
		        arrTipTags[x].onmouseover=function(){return Tip(Tooltip,STICKY,1,CLOSEBTN,true,CLICKCLOSE,true,TITLE,'Tooltip for: '+Tid);}
	          }
	          else {
	            arrTipTags[x].onmouseover=function(){return Tip(Tooltip);}
	          }
	          arrTipTags[x].onmouseout=function(){UnTip();}
	        }
		}
		
		function checkPasswordStrength(pwd,did,CustomMsg) {
        
            if(typeof(CustomMsg)=='undefined') {
              CustomMsg = new Object({short: 'Password is too short',
    	                   weak: '<span style="color:red">Password is weak</span>',
                           medium: '<span style="color:orange">Password is ok</span>',
    	                   strong: '<span style="color:green">Password is strong</span>'
    	                   });
            }
            var strength = $(did);
            var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
            var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
            var enoughRegex = new RegExp("(?=.{6,}).*", "g");
            if (pwd.length==0) {
              strength.innerHTML = '';
            } else if (false == enoughRegex.test(pwd)) {
              strength.innerHTML = CustomMsg.short;
            } else if (strongRegex.test(pwd)) {
              strength.innerHTML = CustomMsg.strong;
            } else if (mediumRegex.test(pwd)) {
              strength.innerHTML = CustomMsg.medium;
            } else {
              strength.innerHTML = CustomMsg.weak;
            }
        }
        
        
        
