// 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+']');
        	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 != 'string' && typeof validationFn.test == "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 (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.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)) > 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 tao.date.getFormattedDatetime(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'
            });
        },
        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._trackPage(path);
            } catch (error) {
                tao.debug.log(error.message);
            }
        }
    }
};
/** 
 * @description		prototype.js based hover menu
 * @author        	Peter Slagter; peter [at] procurios [dot] nl; http://twitter.com/pesla or http://techblog.procurios.nl/k/618/news/view/34556/14863/ProtoFish-advanced-hover-menu-based-on-Prototype.html
 * @license			ProtoFish is based on the MIT license (http://protofish.procurios.nl/protofish-license).
 * 					If you want to remove this copyright notice, contact me for a crate of beer, and we'll see whats possible ;)
 * @parameters		id: menu id <string>, timeout: amount of milliseconds delay on mouseout <string>, cssClass: hover class <string>
 * 					remActive: whether or not remove active class when user enters menu <boolean>, ARIA: choose to use ARIA roles and states <boolean>
 * 					useShortKey: whether or not to use a shortkey to focus menu <boolean> 
 * 
*/

var ProtoFish=Class.create({initialize:function(f,c,a,e,d,b){this.id=f;this.timeout=c||"400";this.cssClass=a||"hover";this.remActive=e||false;this.ARIA=d||false;this.useShortKey=b||false;this.queue=[];this.activeTimeout="";this.menuFocus=false;this.menuCount=0;this.isParent=false;this.shiftDown=false;this.mDown=false;this.ctrlDown=false;this.altDown=false;if($(f)&&$(f).down()){if(this.ARIA!=false){$(f).writeAttribute("role","menubar");this.menuContainers=$(f).select("ul");this.menuContainers.each(function(h,g){h.writeAttribute("role","menu")})}this.listItems=$(f).select("li");this.activeItems=$(f).select("li.active");this.listItems[0].down("a").setAttribute("tabindex","0");this.initObservers()}},initObservers:function(){this.listItems.each(function(a){a.observe("mouseover",function(c,b){this.enterMenu(b);b.addClassName(this.cssClass)}.bindAsEventListener(this,a));a.observe("mouseout",function(c,b){this.queue.push([this.leaveMenu.delay(this.timeout/1000,this),b])}.bindAsEventListener(this,a));if(this.ARIA!=false){a.down("a").writeAttribute("role","menuitem");if(a.down("ul")){a.down("a").writeAttribute("aria-haspopup","true")}}}.bind(this));Event.observe(document,"keydown",function(b){var a=b.keyCode;var c=[9,13,27,32,37,38,39,40];if(c.indexOf(a)!=-1){this.keyBoardNav(b,a,c)}if(b.keyCode==16){this.shiftDown=true}else{if(this.useShortKey!=false){if(b.keyCode==77){this.mDown=true}if(b.keyCode==17){this.ctrlDown=true}if(b.keyCode==18){this.altDown=true}if(this.mDown==true&&this.ctrlDown==true&&this.altDown==true){this.listItems[0].down("a").focus()}}}}.bind(this));Event.observe(document,"keyup",function(a){if(a.keyCode==16){this.shiftDown=false}else{if(this.useShortKey!=false){if(a.keyCode==77){this.mDown=false}if(a.keyCode==17){this.ctrlDown=false}if(a.keyCode==18){this.altDown=false}}}}.bind(this));Event.observe(document,"click",function(b){var a=Event.element(b);if(a!=$(this.id)&&!a.descendantOf(this.id)&&this.menuFocus==true){this.listItems.invoke("removeClassName",this.cssClass);this.menuFocus=false}}.bind(this));$$("body")[0].observe("focusin",this.handleMenuFocus.bind(this));if(window.addEventListener){$$("body")[0].addEventListener("focus",this.handleMenuFocus.bind(this),true)}},handleMenuFocus:function(b){var a=Event.element(b);if(a.up("#"+this.id)){this.menuFocus=true;this.menuCount=this.listItems.indexOf(a.up("li"));this.isParent=(a.next())?true:false;if(this.isParent==false){a.up().addClassName(this.cssClass);while(a.up("li")){a.up("li").addClassName(this.cssClass);a=a.up("li")}}else{if(this.isParent==true){a.up().removeClassName("hover")}}}else{this.listItems.invoke("removeClassName",this.cssClass);this.menuFocus=false}},keyBoardNav:function(b,c,g){if(this.menuFocus==true){if(g.indexOf(c)!=0){b.preventDefault()}var d=this.listItems[this.menuCount];switch(true){case c==Event.KEY_DOWN:if(!d.up("li")){var f=d.down("li")}else{var f=(d.next("li"))||d.up("ul").childElements().first();if(f){d.removeClassName(this.cssClass)}}if(f){this.menuCount=this.listItems.indexOf(f);f.addClassName(this.cssClass);f.down("a").focus()}break;case c==Event.KEY_UP:if(!d.up("li")){var j=false}else{var j=d.previous("li")||d.up("ul").childElements().last();d.removeClassName(this.cssClass)}if(j){this.menuCount=this.listItems.indexOf(j);j.addClassName(this.cssClass);j.down("a").focus()}break;case c==Event.KEY_RIGHT:if(!d.up("li")){var i=d.next("li");if(i){d.removeClassName(this.cssClass)}}else{var i=d.down("li")||false}if(i){this.menuCount=this.listItems.indexOf(i);i.addClassName(this.cssClass);i.down("a").focus()}break;case c==Event.KEY_LEFT:if(!d.up("li")){var e=d.previous("li");if(e){d.removeClassName(this.cssClass)}}else{var e=d.up("li")||false;if(e){d.removeClassName(this.cssClass)}}if(e){this.menuCount=this.listItems.indexOf(e);e.addClassName(this.cssClass);e.down("a").focus()}break;case c==Event.KEY_TAB:if(this.shiftDown==false){this.menuCount++;var j=this.listItems[this.menuCount-1];if(!j.down("li")){j.removeClassName(this.cssClass);while(j.up("li")&&!j.next("li")){j.up("li").removeClassName(this.cssClass);j=j.up("li")}}}else{if(this.shiftDown==true){this.menuCount--;var d=this.listItems[this.menuCount];var f=this.listItems[this.menuCount+1];f.removeClassName(this.cssClass);if(d){while(d.up("li")&&d.up("li").hasClassName(this.cssClass)==false){d.up("li").addClassName(this.cssClass);d=d.up("li")}}}}break;case c==Event.KEY_ESC:while(d.up("li")){d.removeClassName(this.cssClass);var h=d.up("li");d=d.up("li")}if(h){h.down("a").focus();this.menuCount=this.listItems.indexOf(d)}break;case c==32:if(this.isParent==true){this.parentBehavior(d)}else{var a=d.down("a").href;window.location.href=a}break;case c==Event.KEY_RETURN:if(this.isParent==true){this.parentBehavior(d)}break}}},parentBehavior:function(b){var a=b.down("li");if(a){this.menuCount=this.listItems.indexOf(a);a.addClassName(this.cssClass);a.down("a").focus()}},enterMenu:function(){while(this.queue.length){clearTimeout(this.queue[0][0]);this.leaveMenu(this)}if(this.remActive==true){if(typeof this.activeTimeout=="number"){clearTimeout(this.activeTimeout);delete this.activeTimeout}this.activeItems.invoke("removeClassName","active")}},leaveMenu:function(b){if(b.queue.length){var a=b.queue.shift()[1];a.removeClassName(b.cssClass)}if(b.remActive==true){b.activeItems.invoke("addClassName","active")}}});
var swc = {};

var SwcInit = {
    page: function() {
    	return SwcInit.ajax($$('body')[0]);
    },

    ajax: function(e) {
    	if (!e) return;
    	e.fire("swc:element:init");

        $$('#'+e.identify()+' input').each(function(e){if(!e.hasClassName('swc_SearchBox')) {e.addClassName('swc_Input');} });
        $$('#'+e.identify()+' input[type="button"]').each(function(e){e.addClassName('swc_Button');});
        $$('#'+e.identify()+' input[type="submit"]').each(function(e){e.addClassName('swc_Button');});
        $$('#'+e.identify()+' input[type="radio"]').each(function(e){e.removeClassName('swc_Input');});
        $$('#'+e.identify()+' input[type="button"]').each(function(e){e.removeClassName('swc_Input');});
        $$('#'+e.identify()+' input[type="checkbox"]').each(function(e){e.removeClassName('swc_Input');});
        
        // Disable input / textarea listeners
    	if ( (typeof swcOptions != "undefined")
    	    && (typeof swcOptions.disableInputListeners != "undefined")
    	    && (swcOptions.disableInputListeners == true)
    	) {
    	    return;
    	}
    	
        $$('#'+e.identify()+' textarea').each(function(e){e.addClassName('swc_Textarea');e.observe('focus',SwcUtils.textarea.activate);});
        $$('#'+e.identify()+' input').each(function(e){if (e.hasClassName('swc_Input')) {e.observe('focus',SwcUtils.input.activate);}});
        
    }
};

/**
 * Core JS library for SWC 
 * version: $Id: swc.js 2782 2010-04-19 14:34:20Z winterbottomd $
 */
var Swc = {
		
	_growler: null,

    DelayId: null,

    // Delays any JS function by intDelay secons with an auto cancel if executed again
    Delay: function(FunctionToCall,Delay) {
		if(typeof(Swc.DelayId) != 'undefined') {
            clearTimeout(Swc.DelayId);
		}
		Swc.DelayId   = FunctionToCall.delay(Delay);
    },

    /**
     * Open / Close popup functions
     */
    OpenPopup: function(Title,Width,Height) {
        startPopup(Title,'divPopupContainer','divPopupTitle', Width, Height);
        SwcInit.ajax($('divPopupContainer'));
    },
    ClosePopup: function() {
        stopPopup('divPopupContainer','divPopup');
    },
    
    _getGrowler: function(){
    	if(!this._growler){
			this._growler = new k.Growler({location :'br'});
		}
    	return this._growler;
    },
    
    /**
     * Provides the basic notification functionality
     */
	Notify: function(Message, Options) {
    	if(Effect){
    		//we can use growler
    		this._getGrowler().growl(Message, Options);
    	}else{
    		if( typeof( window.innerWidth ) == 'number' ) {
    	        $('divSaveMessage').style.position   = 'fixed';
    	    }
    	    $('divSaveMessage').style.top     = 'auto';
    	    $('divSaveMessage').style.left    = 'auto';
    	    $('divSaveMessage').style.bottom  = '12px';
    	    $('divSaveMessage').style.right   = '12px';
    	    $('divSaveMessage').innerHTML     = Message;
    	    $('divSaveMessage').style.display = 'block';
    	    timerScroll = setTimeout(Swc.NotifyStop,2000);
    	}
	    
    },
    
    NotifyStop: function() {
        $('divSaveMessage').style.display = 'none';
    },
    
    Error: function(Message, Options) {
    	if(Effect){
    		if(!Options){
    			Options = {}
    		}
    		if(!Options.header){
    			Options.header = ' '; //weird bug that means errors always had an annoying header even if I set it to ''
    		}
            if(!Options.sticky) {
                Options.sticky = true;
            }
        	this._getGrowler().error(Message, Options);
    	}else{
    		this.Notify(Message);
    	}
    },
    
    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) {
        if (getCookie(name)) {
            document.cookie = name + "=" + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    },
    
    getCookie: function(name) {
        var dc = document.cookie;
        var prefix = name + "=";
        var begin = dc.indexOf("; " + prefix);
        if (begin == -1) {
            begin = dc.indexOf(prefix);
            if (begin != 0) return null;
        } else {
            begin += 2;
        }
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
        return unescape(dc.substring(begin + prefix.length, end));
    },
    
    setCookie: function(name, value, expires, path, domain, secure) {
	    document.cookie= name + "=" + escape(value) +
	        ((expires) ? "; expires=" + expires.toGMTString() : "") +
	        ((path) ? "; path=" + path : "") +
	        ((domain) ? "; domain=" + domain : "") +
	        ((secure) ? "; secure" : "");
	},
	
	
    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');
    	},
    	
    	
    	get_html_translation_table: function (table, quote_style) {
		    
		    var entities = {}, histogram = {}, decimal = 0, symbol = '';
		    var constMappingTable = {}, constMappingQuoteStyle = {};
		    var useTable = {}, useQuoteStyle = {};
		    
		    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
		    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
		    
		    // Translate arguments
		    constMappingTable[0]      = 'HTML_SPECIALCHARS';
		    constMappingTable[1]      = 'HTML_ENTITIES';
		    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
		    constMappingQuoteStyle[2] = 'ENT_COMPAT';
		    constMappingQuoteStyle[3] = 'ENT_QUOTES';
		    
		    // Map numbers to strings for compatibilty with PHP constants
		    if (!isNaN(useTable)) {
		        useTable = constMappingTable[useTable];
		    }
		    if (!isNaN(useQuoteStyle)) {
		        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
		    }
		 
		    if (useTable == 'HTML_SPECIALCHARS') {
		        // ascii decimals for better compatibility
		        entities['38'] = '&amp;';
		        if (useQuoteStyle != 'ENT_NOQUOTES') {
		            entities['34'] = '&quot;';
		        }
		        if (useQuoteStyle == 'ENT_QUOTES') {
		            entities['39'] = '&#039;';
		        }
		        entities['60'] = '&lt;';
		        entities['62'] = '&gt;';
		    } else if (useTable == 'HTML_ENTITIES') {
		        // ascii decimals for better compatibility
		      entities['38']  = '&amp;';
		        if (useQuoteStyle != 'ENT_NOQUOTES') {
		            entities['34'] = '&quot;';
		        }
		        if (useQuoteStyle == 'ENT_QUOTES') {
		            entities['39'] = '&#039;';
		        }
		      entities['60']  = '&lt;';
		      entities['62']  = '&gt;';
		      entities['160'] = '&nbsp;';
		      entities['161'] = '&iexcl;';
		      entities['162'] = '&cent;';
		      entities['163'] = '&pound;';
		      entities['164'] = '&curren;';
		      entities['165'] = '&yen;';
		      entities['166'] = '&brvbar;';
		      entities['167'] = '&sect;';
		      entities['168'] = '&uml;';
		      entities['169'] = '&copy;';
		      entities['170'] = '&ordf;';
		      entities['171'] = '&laquo;';
		      entities['172'] = '&not;';
		      entities['173'] = '&shy;';
		      entities['174'] = '&reg;';
		      entities['175'] = '&macr;';
		      entities['176'] = '&deg;';
		      entities['177'] = '&plusmn;';
		      entities['178'] = '&sup2;';
		      entities['179'] = '&sup3;';
		      entities['180'] = '&acute;';
		      entities['181'] = '&micro;';
		      entities['182'] = '&para;';
		      entities['183'] = '&middot;';
		      entities['184'] = '&cedil;';
		      entities['185'] = '&sup1;';
		      entities['186'] = '&ordm;';
		      entities['187'] = '&raquo;';
		      entities['188'] = '&frac14;';
		      entities['189'] = '&frac12;';
		      entities['190'] = '&frac34;';
		      entities['191'] = '&iquest;';
		      entities['192'] = '&Agrave;';
		      entities['193'] = '&Aacute;';
		      entities['194'] = '&Acirc;';
		      entities['195'] = '&Atilde;';
		      entities['196'] = '&Auml;';
		      entities['197'] = '&Aring;';
		      entities['198'] = '&AElig;';
		      entities['199'] = '&Ccedil;';
		      entities['200'] = '&Egrave;';
		      entities['201'] = '&Eacute;';
		      entities['202'] = '&Ecirc;';
		      entities['203'] = '&Euml;';
		      entities['204'] = '&Igrave;';
		      entities['205'] = '&Iacute;';
		      entities['206'] = '&Icirc;';
		      entities['207'] = '&Iuml;';
		      entities['208'] = '&ETH;';
		      entities['209'] = '&Ntilde;';
		      entities['210'] = '&Ograve;';
		      entities['211'] = '&Oacute;';
		      entities['212'] = '&Ocirc;';
		      entities['213'] = '&Otilde;';
		      entities['214'] = '&Ouml;';
		      entities['215'] = '&times;';
		      entities['216'] = '&Oslash;';
		      entities['217'] = '&Ugrave;';
		      entities['218'] = '&Uacute;';
		      entities['219'] = '&Ucirc;';
		      entities['220'] = '&Uuml;';
		      entities['221'] = '&Yacute;';
		      entities['222'] = '&THORN;';
		      entities['223'] = '&szlig;';
		      entities['224'] = '&agrave;';
		      entities['225'] = '&aacute;';
		      entities['226'] = '&acirc;';
		      entities['227'] = '&atilde;';
		      entities['228'] = '&auml;';
		      entities['229'] = '&aring;';
		      entities['230'] = '&aelig;';
		      entities['231'] = '&ccedil;';
		      entities['232'] = '&egrave;';
		      entities['233'] = '&eacute;';
		      entities['234'] = '&ecirc;';
		      entities['235'] = '&euml;';
		      entities['236'] = '&igrave;';
		      entities['237'] = '&iacute;';
		      entities['238'] = '&icirc;';
		      entities['239'] = '&iuml;';
		      entities['240'] = '&eth;';
		      entities['241'] = '&ntilde;';
		      entities['242'] = '&ograve;';
		      entities['243'] = '&oacute;';
		      entities['244'] = '&ocirc;';
		      entities['245'] = '&otilde;';
		      entities['246'] = '&ouml;';
		      entities['247'] = '&divide;';
		      entities['248'] = '&oslash;';
		      entities['249'] = '&ugrave;';
		      entities['250'] = '&uacute;';
		      entities['251'] = '&ucirc;';
		      entities['252'] = '&uuml;';
		      entities['253'] = '&yacute;';
		      entities['254'] = '&thorn;';
		      entities['255'] = '&yuml;';
		    } else {
		        throw Error("Table: "+useTable+' not supported');
		        return false;
		    }
		    
		    // ascii decimals to real symbols
		    for (decimal in entities) {
		        symbol = String.fromCharCode(decimal);
		        histogram[symbol] = entities[decimal];
		    }
		    
		    return histogram;
		},
    	
    	htmlentities: function (string, quote_style) {
            var histogram = {}, symbol = '', tmp_str = '', entity = '';
            tmp_str = string.toString();
            if (false === (histogram = SwcUtils.string.get_html_translation_table('HTML_ENTITIES', quote_style))) {
                return false;
            }
            
            for (symbol in histogram) {
                entity = histogram[symbol];
                tmp_str = tmp_str.split(symbol).join(entity);
            }
            return tmp_str;
        }
    }

};


var SwcEffects = {
	
    EFFECT_APPEAR: 'Appear',
    EFFECT_FADE: 'Fade',
    EFFECT_PUFF: 'Puff',
    EFFECT_DROP_OUT: 'DropOut',
    EFFECT_SHAKE: 'Shake',
    EFFECT_SWITCH_OFF: 'SwitchOff',
    EFFECT_BLIND_DOWN: 'BlindDown',
    EFFECT_BLIND_UP: 'BlindUp',
    EFFECT_SLIDE_DOWN: 'SlideDown',
    EFFECT_SLIDE_UP: 'SlideUp',
    EFFECT_PULSATE: 'Pulsate',
    EFFECT_SQUISH: 'Squish',
    EFFECT_FOLD: 'Fold',
    EFFECT_GROW: 'Grow',
    EFFECT_SHRINK: 'Shrink',
    EFFECT_HIGHLIGHT: 'Shrink',
    
    effect: function(ElementId, EffectName, Options) {
        switch(EffectName){
            case SwcEffects.EFFECT_FADE:
            case SwcEffects.EFFECT_BLIND_UP:
            case SwcEffects.EFFECT_SLIDE_UP:
            case SwcEffects.EFFECT_SHRINK:
            case SwcEffects.EFFECT_PUFF:
            case SwcEffects.EFFECT_DROP_OUT:
            case SwcEffects.EFFECT_SWITCH_OFF:
            case SwcEffects.EFFECT_FOLD:
                
                if(Effect){
                	Effect[EffectName]($(ElementId), Options);
                }
                else {
                    $(ElementId).hide();
                }
                break;
            case SwcEffects.EFFECT_APPEAR:
            case SwcEffects.EFFECT_SHAKE:
            case SwcEffects.EFFECT_BLIND_DOWN:
            case SwcEffects.EFFECT_SLIDE_DOWN:
            case SwcEffects.EFFECT_SQUISH:
            case SwcEffects.EFFECT_GROW:
                
                if(Effect){
                    Effect[EffectName]($(ElementId), Options);
                }
                else {
                    $(ElementId).show();
                }
                
                break;
                
            case SwcEffects.EFFECT_PULSATE:
            case SwcEffects.EFFECT_HIGHLIGHT:
                
                if(Effect){
                    Effect[EffectName]($(ElementId), Options);
                }
                break;
        }
    }
	
};


swc.dimmer = {

	pointer: null,
	
	create: function()
	{
		if($(swc.dimmer.pointer))
		{
			if(!$(swc.dimmer.pointer).visible()) $(swc.dimmer.pointer).show();
			return true;
		}

		var dimmer = document.createElement('div');
		dimmer.addClassName('swc_Dimmer');
		dimmer.setStyle({zIndex:390, display:'none'});
		$$('body').first().appendChild(dimmer);
		$(dimmer).show();
		swc.dimmer.pointer = dimmer;
		return dimmer;
	},
	
	close: function()
	{
		if($(swc.dimmer.pointer))
		{
			$(swc.dimmer.pointer).hide();
		}
		return true;
	}
};

swc.popup = {
	
	initialIndex: 400,
	maxIndex: 400,
	counter: 0,
	appearance: {duration:0.2, from:0, to:0.5},
	disappearance: {duration:0.2, from:0.5, to:0},
	
	model: function()
	{
		this.title = null,
		this.content = null,
		this.id = null,
		
		this.toString = function()
		{
			return '<div class="swc_PopupHeader"><div class="swc_PopupClose">x</div><div class="swc_PopupTitle">'+this.title+'</div></div><div class="swc_PopupContent">'+this.content+'</div>';
		}
	},
	
	closeLast: function()
	{
		if(swc.popup.counter == 0) return true;
		var popupId='swc_Popup'+swc.popup.maxIndex;
		swc.popup.close($(popupId));
	},
	
	close: function(popup)
	{
		$(popup).remove();
		swc.popup.maxIndex--;
		swc.popup.counter--;
		
		if(swc.popup.maxIndex==swc.popup.initialIndex) 
		{
			swc.dimmer.close();
		}
		if(Prototype.Browser.IE)
		{
			swc.popup.dropdownRestate(popup);
		}
	},
	
	create: function(content, options)
	{
		var options = typeof options!=undefined ? options : {};
		options.width = typeof options.width!=undefined ? options.width : 'auto';
		options.closeLast = typeof options.closeLast!=undefined ? options.closeLast : true;
		options.dimmer = typeof options.dimmer!=undefined ? options.dimmer : true;
		options.closeButton = typeof options.closeButton!=undefined ? options.closeButton : true;
		
		if(!options.closeLast) swc.popup.closeLast();
		if(options.dimmer === true) swc.dimmer.create();
		
		// Increase overall z-index
		swc.popup.maxIndex++;
		swc.popup.counter++;
		
		// Create popup
		var popupId = 'swc_Popup'+swc.popup.maxIndex;
		var popup=document.createElement('div');
		popup.addClassName('swc_Popup');
		popup.setStyle({zIndex:swc.popup.maxIndex, display:'none',width:options.width});
		popup.setAttribute('id',popupId);
		if(typeof options.className!=undefined)
		{
			popup.addClassName(options.className);
		}
		
		// Add it to the page
		$$('body').first().appendChild(popup);
		
		var popupObject = new swc.popup.model();
		popupObject.title = typeof options.title==undefined ? '' : options.title;
		popupObject.content = typeof content==undefined ? '' : content;
		popupObject.id = options.popupId;
		$(popup).update(popupObject);
		
		// Adjust size
		tao.position.centreInViewport($(popup));
		
		$(popup).appear({duration:0.2});
		
		if(options.closeButton === true) 
		{
			$(popup).down('.swc_PopupClose').observe('click', function(e){
				if(typeof options.onClose!=undefined)
				{
					options.onClose();
					tao.debug.log("Executing onClose function: ",options.onClose);
				}
				swc.popup.handleClose(e);
			});
		}
		else 
		{
			$(popup).down('.swc_PopupClose').hide();
		}
		
		if(Prototype.Browser.IE)
		{
			swc.popup.dropdownRemove(popup);
		}
		
		if(typeof options.onReady!=undefined)
		{
			options.onReady();
			tao.debug.log("Executing onReady function: ",options.onReady);
		}
		
		return $(popup);
	},
	
	handleClose: function(e)
	{
		var popupId = Event.element(e).up('.swc_Popup').identify();
		swc.popup.close($(popupId));
	},
	
	dropdownRemove: function(popup)
	{
        $$('body select').each(function(e) {
        	if(!e.descendantOf(popup)) {
        		e.style.visibility='hidden';
        	}
        });
	},
	
	dropdownRestate: function(popup)
	{
        $$('body select').each(function(e) {
        	if(!e.descendantOf(popup)) {
        		e.style.visibility='visible';
        	}
        });
	}
};



/**
 * k.Growler 1.0.0
 *
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Written by Kevin Armstrong <kevin@kevinandre.com>
 * Last updated: 2008.10.14
 *
 * Growler is a PrototypeJS based class that displays unobtrusive notices on a page. 
 * It functions much like the Growl (http://growl.info) available on the Mac OS X. 
 *
 * Changes in 1.0.1:
 * - 
 *
 * @todo
 */
window.k = window.k || {};
;(function(){

var noticeOptions = {
    header:             '&nbsp;'
    ,speedin:           0.3
    ,speedout:          0.5
    ,outDirection:      { x: 40 }
    ,life:              5
    ,sticky:            false
    ,className:         ""
};
var growlerOptions = {
    location:           "br"
    ,width:             "250px"
};
var IE = (Prototype.Browser.IE) ? parseFloat(navigator.appVersion.split("MSIE ")[1]) || 0 : 0;
function removeNotice(n, o){
    o = o || noticeOptions;
    new Effect.Parallel([
        new Effect.Move(n, Object.extend({ sync: true, mode: 'relative' }, o.outDirection)),
        new Effect.Opacity(n, { sync: true, to: 0 }) 
    ], {
        duration: o.speedout
        ,afterFinish: function(){
            try {
                var ne = n.down("div.notice-exit");
                if(ne != undefined){
                    ne.stopObserving("click", removeNotice);
                }
                if(o.created && Object.isFunction(o.created)){
                    n.stopObserving("notice:created", o.created);
                }
                if(o.destroyed && Object.isFunction(o.destroyed)){
                    n.fire("notice:destroyed");
                    n.stopObserving("notice:destroyed", o.destroyed);
                }
            } catch(e){}
            try {
                n.remove();
            } catch(e){}
        }
    });
}
function createNotice(growler, msg, options){
    var opt = Object.clone(noticeOptions);
    options = options || {};
    Object.extend(opt, options);
    var notice;
    if (opt.className != ""){
        notice = new Element("div", {"class": opt.className}).setStyle({display: "block", opacity: 0});
    } else {
        notice = new Element("div", {"class": "Growler-notice"}).setStyle({display: "block", opacity: 0});
    }
    if(opt.created && Object.isFunction(opt.created)){
        notice.observe("notice:created", opt.created);
    }
    if(opt.destroyed && Object.isFunction(opt.destroyed)){
        notice.observe("notice:destroyed", opt.destroyed);
    }
    if (opt.sticky){
        var noticeExit = new Element("div", {"class": "Growler-notice-exit"}).update("&times;");
        noticeExit.observe("click", function(){ removeNotice(notice, opt); });
        notice.insert(noticeExit);
    }
    notice.insert(new Element("div", {"class": "Growler-notice-head"}).update(opt.header));
    notice.insert(new Element("div", {"class": "Growler-notice-body"}).update(msg));
    growler.insert(notice);
    if (typeof Effect != "undefined") new Effect.Opacity(notice, { to: 0.85, duration: opt.speedin });
    if (!opt.sticky){
        removeNotice.delay(opt.life, notice, opt);
    }
    notice.fire("notice:created");
    return notice;
}
function specialNotice(g, m, o, t, b, c){
    o.header = o.header || t;
    var n = createNotice(g, m, o);
    n.setStyle({ backgroundColor: b, color: c });
    return n;
}
k.Growler = Class.create({
    initialize: function(options){
        var opt = Object.clone(growlerOptions);
        options = options || {};
        Object.extend(opt, options);
        this.growler = new Element("div", { "class": "Growler", "id": "Growler" });
        this.growler.setStyle({ position: ((IE==6)?"absolute":"fixed"), padding: "10px", "width": opt.width, "z-index": "50000" });
        if(IE==6){
            var offset = { w: parseInt(this.growler.style.width)+parseInt(this.growler.style.padding)*3, h: parseInt(this.growler.style.height)+parseInt(this.growler.style.padding)*3 };
            switch(opt.location){
                case "br":
                    this.growler.style.setExpression("left", "( 0 - Growler.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");
                    this.growler.style.setExpression("top", "( 0 - Growler.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
                    break;
                case "tl":
                    this.growler.style.setExpression("left", "( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");
                    this.growler.style.setExpression("top", "( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
                    break;
                case "bl":
                    this.growler.style.setExpression("left", "( 0 + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");
                    this.growler.style.setExpression("top", "( 0 - Growler.offsetHeight + ( document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
                    break;
                default:
                    this.growler.setStyle({right: "auto", bottom: "auto"});
                    this.growler.style.setExpression("left", "( 0 - Growler.offsetWidth + ( document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth ) + ( ignoreMe2 = document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ) ) + 'px'");
                    this.growler.style.setExpression("top", "( 0 + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ) ) + 'px'");
                    break;
            }
        } else {
            switch(opt.location){
                case "br":
                    this.growler.setStyle({bottom: 0, right: 0});
                    break;
                case "tl":
                    this.growler.setStyle({top: 0, left: 0});
                    break;
                case "bl":
                    this.growler.setStyle({top: 0, right: 0});
                    break;
                case "tc":
                    this.growler.setStyle({top: 0, left: "25%", width: "50%"});
                    break;
                case "bc":
                    this.growler.setStyle({bottom: 0, left: "25%", width: "50%"});
                    break;
                default:
                    this.growler.setStyle({top: 0, right: 0});
                    break;
            }
        }
        this.growler.wrap( document.body );     
    }
    ,growl: function(msg, options) {
        return createNotice(this.growler, msg, options);
    }
    ,warn: function(msg, options){
        return specialNotice(this.growler, msg, options, "Warning!", "#F6BD6F", "#000");
    }
    ,error: function(msg, options){
        return specialNotice(this.growler, msg, options, "Critical!", "#F66F82", "#000");
    }
    ,info: function(msg, options){
        return specialNotice(this.growler, msg, options, "Information!", "#BBF66F", "#000");
    }
    ,ungrowl: function(n, o){
        removeNotice(n, o);
    }
});

})();/**
 * Core SWC TinyMCE configurations
 * Version: $Id: tiny.js 743 2008-12-09 13:47:22Z mossj $
 */
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);
  }
  
};/**
 * 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();}
	        }
		}
		
		
		document.observe('dom:loaded', function(){
	        new ProtoFish('ai_nav', '200', 'hover', false, true, true);
	    });
		
		
		
        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;
            }
        }
        
        
        