

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

    ajax: function(e) {
        
        $$('#'+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="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');});
        
        $$('#'+e.identify()+' textarea').each(function(e){e.addClassName('swc_Textarea');e.observe('focus',SwcUtils.textarea.activate);});
        $$('#'+e.identify()+' input').each(function(e){e.observe('focus',SwcUtils.input.activate);});
        
        //console.log('firing swc:element:init');
        e.fire("swc:element:init");
        
        //$$('#'+e.identify()+' .swc_Autosize').each(function(e){if(e.hasAttribute('autohight')) { e.style.height=eval(e.getAttribute('autohight'));} });
        
    }
}

/**
 * Core JS library for SWC 
 * version: $Id: swc.js 2003 2009-03-20 17:05:54Z szczesnym $
 */
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 = {
    	
	open: function(Title, Content) {
        Sidebar = document.createElement('div');
        $$('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);
	},
    
    close: function() {
        $$('body')[0].removeChild($('swc_Sidebar'));
        document.stopObserving('resize', SwcSidebar.updateSize);
    },
    
    observeResize: function() {
        document.observe('resize',SwcSidebar.updateSize);
    },
	
	updateSize: function() {
		NewHeight = (document.viewport.getHeight() - $('swc_SidebarHeader').getHeight() - 105);
		$$('#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 = 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;
    },

    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;
        },
    	
        deactivate: function(e) {
            element = Event.element(e);
            CounterId = element.identify()+'_info';
            if($(CounterId)) {
                $(CounterId).hide();
            }
        },
        
    	maxLengthInit: function(e) {
    		SwcUtils.input.maxLengthPrepare(Event.element(e));
    	},
    	
    	maxLengthPrepare: function(element) {
            
            if(!element.hasAttribute('maxlength')) return false;
            
            MaxLength = element.getAttribute('maxlength');
            if(!(MaxLength > 0)) return false;  
            
            PopulateId  = SwcUtils.createInfoBox(element);
            $(PopulateId).update("Characters left: "+element.getAttribute('maxlength'));
            
            element.observe('keypress',SwcUtils.input.monitorMaxLength);
            SwcUtils.input.monitorMaxLength(element);
        },
        
        monitorMaxLength: function(e) {
            element     = Event.element(e);
            MaxLen      = element.getAttribute('maxlength');
            CharsLeft   = MaxLen - element.value.length;
            PopulateId  = SwcUtils.createInfoBox(element);
            
            $(PopulateId).update("Characters left: "+CharsLeft);
            
            if(element.value.length > MaxLen) {
                NewValue = element.value.truncate(MaxLen,'');
                element.value = NewValue;
                $(PopulateId).update("Maximum length reached!");
            }
        }
        
    },
    
    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;
        }
    }
	
};


/**
 * 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);
    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 613 2008-07-29 15:43:32Z szczesnym $
 */

var FileBrowser = {

  /**
   * Close the file browser
   */
  close: function() {
      return Swc.ClosePopup();
  },
  
  /**
   * 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);
  }
  
}
		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'); }
        
        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 sfHover() {
			
		    if(document.getElementById("ai_nav") && document.getElementById("ai_nav").getElementsByTagName("LI")){
	            var sfEls = document.getElementById("ai_nav").getElementsByTagName("LI");
	            for (var i=0; i<sfEls.length; i++) {
	                sfEls[i].onmouseover=function() {
	                    this.className+=" sfhover";
	                }
	                sfEls[i].onmouseout=function() {
	                    this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
	                }
	            }
			}
        }
        if (window.attachEvent) window.attachEvent("onload", sfHover);
		
        /**
         * CustomMsg: {short:'xxx',weak:'xx',medium:'yyyy',strong:'zzz'}
         */
        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;
            }
        }
        
        var Track = {
            classPrefix: 'tr_',
            register: function() {
                $$('a[href!="javascript:void(0);"]').invoke('observe','mousedown',Track.log);
	        },
	        log: function(e) {
	            var strClass = $w(e.element().className).find(function(strClass){return strClass.startsWith(Track.classPrefix)});
                if(!strClass) {
                    return true;
                }
                var objLog = { pid: Page.pid, lid: strClass.match('_(.*)').last() }
                var strUrl = '/js/common/ct.tao?'+Object.toQueryString(objLog);
                new Ajax.Request(strUrl, {method: 'get'});
                return true;
            }
        }
        if(typeof(Page) != 'undefined' && Page.ltr) document.observe('dom:loaded',Track.register);
        
        
        