var oldtext = '';
var isOver = false;
var imgElem = false;

var rules = {
	'input#searchfield' : function(element){
		element.onfocus = function() {	
			if (this.value=='Suchwort eingeben')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Suchwort eingeben';				
		}		
	},
	'input#tx_tipafriend_name' : function(element){		

		element.onfocus = function() {		
			if (this.value=='Ihr Name: *')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Ihr Name: *';				
		}		
	},
	'input#tx_tipafriend_email' : function(element){
		element.onfocus = function() {	
			if (this.value=='Ihre E-Mail: *')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Ihre E-Mail: *';				
		}		
	},
	'input#tx_tipafriend_recipient' : function(element){
		element.onfocus = function() {	
			if (this.value=='E-Mail des Empfängers: *')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='E-Mail des Empfängers: *';				
		}		
	},
	'input#tx_tipafriend_pi1_captcha_response' : function(element){
		element.onfocus = function() {	
			if (this.value=='Bildwort *')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Bildwort *';				
		}		
	},	
	
	'textarea#tx_tipafriend_message' : function(element){
		element.onfocus = function() {	
			if (this.value=='Ihre Mitteilung an den Empfänger')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Ihre Mitteilung an den Empfänger';				
		}	
		element.onchange = function() {
			tmp=this.scrollHeight;
			if (tmp>225) 
				this.value = oldtext;	
		}
		element.onkeyup = function() {
			tmp=this.scrollHeight;
			if (tmp>225) 
				this.value = oldtext; 
			oldtext=this.value;

		}		
	},	
	'input#tx-sremailsubscribe-pi1-first_name' : function(element){
		element.onfocus = function() {	
			if (this.value=='Vorname')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Vorname';				
		}		
	},	
	'input#tx-sremailsubscribe-pi1-last_name' : function(element){
		element.onfocus = function() {	
			if (this.value=='Nachname')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Nachname';				
		}		
	},	
	'input#tx-sremailsubscribe-pi1-email' : function(element){
		element.onfocus = function() {	
			if (this.value=='E-Mail *')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='E-Mail *';				
		}		
	},	
	'input#tx-sremailsubscribe-pi1-module_sys_dmail_html' : function(element){
		element.onclick = function() {	
			if (this.checked)
				document.getElementById('tx-sremailsubscribe-pi1-module_sys_dmail_plain').checked=false;	
			else
				document.getElementById('tx-sremailsubscribe-pi1-module_sys_dmail_plain').checked=true;
		}		
	},	
	'input#tx-sremailsubscribe-pi1-module_sys_dmail_plain' : function(element){
		element.onclick = function() {	
			if (this.checked)
				document.getElementById('tx-sremailsubscribe-pi1-module_sys_dmail_html').checked=false;	
			else
				document.getElementById('tx-sremailsubscribe-pi1-module_sys_dmail_html').checked=true;
		}			
	},
	'.csc-textpic-image img': function(element){
		element.onmouseover = function() {	
			window.clearTimeout(isOver);
			objPar = this.parentNode;
			if (objPar.tagName!='DT')
				objPar = objPar.parentNode;
				
			if (objPar.nextSibling) {
				objPar.nextSibling.style.display = 'block';
				objPar.nextSibling.style.height = parseInt(this.offsetHeight)-10+'px';		
				imgElem = objPar;
			}
		}	
		element.onmouseout = function() {	
			//var obj = this;
			objPar = this.parentNode;
			if (objPar.tagName!='DT')
				objPar = objPar.parentNode;
			if (objPar.nextSibling) 
				isOver = window.setTimeout(function() {objPar.nextSibling.style.display = 'none';},100);
			
		}		
	},
	'.csc-textpic-caption': function(element){
		element.onmouseover = function() {	
			window.clearTimeout(isOver);
		}
		element.onmouseout = function() {	
			var obj = this;
			isOver = window.setTimeout(function() {imgElem.nextSibling.style.display = 'none';},100);		
		}			
	
	},
	'input#user' : function(element){
		element.onfocus = function() {	
			if (this.value=='Ihr Benutzername')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Ihr Benutzername';				
		}		
	},
	'input#pass' : function(element){
		element.onfocus = function() {	
			if (this.value=='Ihr Passwort')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Ihr Passwort';				
		}		
	},
	'input#ccctinp' : function(element){
		element.onfocus = function() {	
			if (this.value=='Titel der Veranstaltung, Veranstalter')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Titel der Veranstaltung, Veranstalter';				
		}		
	},
	'input#cclinp' : function(element){
		element.onfocus = function() {	
			if (this.value=='link zu Ihrer Website (www.netzwerkpartner.de)')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='link zu Ihrer Website (www.netzwerkpartner.de)';				
		}		
	},
	'input#ccsinp' : function(element){
		element.onfocus = function() {	
			if (this.value=='Datum (Format: JJJJ-MM-TT)' || !this.isChanged)
				this.value='';				
		}
		element.onchange = function() {	
			this.isChanged = true;				
		}		
		element.onblur = function() {	
			if (this.value=='')
				this.value='Datum (Format: JJJJ-MM-TT)';				
		}		
	},
	'input#ccsinp' : function(element){
		element.onfocus = function() {	
			if (this.value=='Datum (Format: JJJJ-MM-TT)' || !this.isChanged)
				this.value='';				
		}
		element.onchange = function() {	
			this.isChanged = true;				
		}		
		element.onblur = function() {	
			if (this.value=='')
				this.value='Datum (Format: JJJJ-MM-TT)';				
		}		
	},	
	'input#query' : function(element){
		element.onfocus = function() {	
			if (this.value=='Suchwort eingeben')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Suchwort eingeben';				
		}		
	},
	'input#cal_searchfield' : function(element){
		element.onfocus = function() {	
			if (this.value=='Suchwort eingeben')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Suchwort eingeben';				
		}		
	},	
	'a#printlink' : function(element){
		element.onclick = function() {
			document.getElementById('cal_printfield').value=document.getElementById('query').value;
			document.getElementById('printform').submit();
			return false;			
		}
	
	},
	'textarea#cal_event_description'  : function(element){
		if (element.value=='')
			element.value='Kurzbeschreibung (max. 100 Zeichen)';
		element.onfocus = function() {	
			if (this.value=='Kurzbeschreibung (max. 100 Zeichen)')
				this.value='';				
		}
		element.onblur = function() {	
			if (this.value=='')
				this.value='Kurzbeschreibung (max. 100 Zeichen)';				
		}			
		element.onkeyup = function() {
			if (this.value.length>100) {
				this.value=this.value.substr(0,100);
			}
			else if (this.value=='')
				this.value='Kurzbeschreibung (max. 100 Zeichen)';			
		}
	},
	'div#map_canvas'  : function(element){
		//initialize_maps();
	},
	'div#pg_gallery'  : function(element){
		element.innerHTML = '<span id="pg_pager_prev"> &nbsp;&nbsp;</span><span id="pg_counter">1 / '+$('pg_gallery').getNext().getElements('img').length+'</span> <span id="pg_pager_next"> &nbsp; &nbsp;</span>';
		$('pg_pager_next').onclick = function() {
			pagerNext(this);
		}
		$('pg_pager_prev').onclick = function() {
			pagerPrev(this);
		}		
	},

	'div.projektgalerie_single_image div.pg_image'  : function(element){
		element.onclick = function() {	
			imgNext(this);
		}
	},	
	'div#pg_quotes_list'  : function(element){
		cnt = 0;
		if (!element.getElements('div.pg_quotes_quote')[0].innerHTML.match(/[a-zA-Z]/))
			element.setStyle('display','none');
		element.getElements('div.pg_quotes_quote').each (function(item) {
			if (item.innerHTML.match(/[a-zA-Z]/))
				cnt++;
		});
		if (cnt<2)
			element.getElements('div.pg_quotes_item').setStyle('cursor','default');
		else {
		
			var pg_quotes  = new Element('div', {id: 'pg_quotes'});
			var pgq_pager_prev  = new Element('span', {id: 'pg_pagerq_prev', html: ' &nbsp;&nbsp;', events: {
						click: function(){
							pagerPrevQ(this);
						}
					}
				}
			);
			var pgq_counter = new Element('span', {id: 'pg_counterq', html: '1 / '+cnt});
			var pgq_pager_next  = new Element('span', {id: 'pg_pagerq_next', html: ' &nbsp;&nbsp;', events: {
						click: function(){
							pagerNextQ(this);
						}
					}
				}
			);
			
			pgq_pager_prev.inject(pg_quotes);
			pgq_counter.inject(pg_quotes);
			pgq_pager_next.inject(pg_quotes);
			pg_quotes.inject(element);
					
		}		
			
	},		
	'div.pg_quotes_item'  : function(element){
		element.onclick = function() {	
			quotesNext(this);
		}
	},
	'div.caliconlisthome_entry'  : function(element){
		element.onmouseover = function() {	
			this.getElements('a').each(function(elem) {
				elem.setStyle('color','#B4B4B4');
			});	
		},
		element.onmouseout = function() {	
			this.getElements('a').each(function(elem) {
				elem.setStyle('color','#2F2F31');
			});	
		}		
	} ,
	'table.pg_list td.area'  : function(element){
		element.innerHTML = element.innerHTML.replace(/ m2/g,' m<sup>2</sup>');	
		element.innerHTML = element.innerHTML.replace(/\/m2/g,'/m<sup>2</sup>');		
	},
	'select#map_state'  : function(element){
		element.onchange = function() {
			if ($("area_"+this.value)) 
				var lan = $("area_"+this.value).getProperty("alt");	
			else
				var lan = 'Deutschland.gif';
				
			$("karte_bundeslaender").setProperty("src",'fileadmin/templates/templateimages/Karte_'+lan);
				
		};		
	},	
	'map#map_bundeslaender area'  : function(element){
		tmp = new Image();
		tmp.src = 'fileadmin/templates/templateimages/Karte_'+element.get('alt');
		element.onmouseover = function() {	
			var lan = this.getProperty("alt");	
			$("karte_bundeslaender").setProperty("src",'fileadmin/templates/templateimages/Karte_'+lan);
		}
		element.onmouseout = function() {	
			var lan = this.getProperty("alt");	
			$("karte_bundeslaender").setProperty("src",'fileadmin/templates/templateimages/Karte_Deutschland.gif');
		}
		element.onclick = function() {	
			val = this.get('id').split('_')[1];
			obj = this;
			$$("#map_state option").each(function(elem) {
				if (elem.get('value')==val) {
					elem.set('selected','selected');
					obj.getParent('form').submit();
				}	
			});
			$$("input#map_state").each(function(elem) {
				elem.set('value',val);
				obj.getParent('form').submit();
			});
			
			
			//this.getParent('form').submit();
			return false;
		}					
	} 
}	

Behaviour.register(rules);	



var grayscale = (function(){
    
    var config = {
            colorProps: ['color','backgroundColor','borderBottomColor','borderTopColor','borderLeftColor','borderRightColor','backgroundImage'],
            externalImageHandler : {
                /* Grayscaling externally hosted images does not work
                   - Use these functions to handle those images as you so desire */
                /* Out of convenience these functions are also used for browsers
                   like Chrome that do not support CanvasContext.getImageData */
                init : function(el, src) {
                    if (el.nodeName.toLowerCase() === 'img') {
                        // Is IMG element...
                    } else {
                        // Is background-image element:
                        // Default - remove background images
                        data(el).backgroundImageSRC = src;
                        el.style.backgroundImage = '';
                    }
                },
                reset : function(el) {
                    if (el.nodeName.toLowerCase() === 'img') {
                        // Is IMG element...
                    } else {
                        // Is background-image element:
                        el.style.backgroundImage = 'url(' + (data(el).backgroundImageSRC || '') + ')';
                    }
                }
            }
        },
        log = function(){
            try { window.console.log.apply(console, arguments); }
            catch(e) {};
        },
        isExternal = function(url) {
            // Checks whether URL is external: 'CanvasContext.getImageData'
            // only works if the image is on the current domain.
            return (new RegExp('https?://(?!' + window.location.hostname + ')')).test(url);
        },
        data = (function(){
            
            var cache = [0],
            expando = 'data' + (+new Date());
            
            return function(elem) {
                var cacheIndex = elem[expando],
                    nextCacheIndex = cache.length;
                if(!cacheIndex) {
                    cacheIndex = elem[expando] = nextCacheIndex;
                    cache[cacheIndex] = {};
                }
                return cache[cacheIndex];
            };
            
        })(),
        desatIMG = function(img, prepare, realEl) {
            
            // realEl is only set when img is temp (for BG images)
            
            var canvas = document.createElement('canvas'),
                context = canvas.getContext('2d'),
                height = img.naturalHeight || img.offsetHeight || img.height,
                width = img.naturalWidth || img.offsetWidth || img.width,
                imgData;
                
            canvas.height = height;
            canvas.width = width;
            context.drawImage(img, 0, 0);
            try {
                imgData = context.getImageData(0, 0, width, height);
            } catch(e) {}
            
            if (prepare) {
                desatIMG.preparing = true;
                // Slowly recurse through pixels for prep,
                // :: only occurs on grayscale.prepare()
                var y = 0;
                (function(){
                    
                    if (!desatIMG.preparing) { return; }
                    
                    if (y === height) {
                        // Finished!
                        context.putImageData(imgData, 0, 0, 0, 0, width, height);
                        realEl ? (data(realEl).BGdataURL = canvas.toDataURL())
                               : (data(img).dataURL = canvas.toDataURL())
                    }
                    
                    for (var x = 0; x < width; x++) {
                        var i = (y * width + x) * 4;
                        // Apply Monoschrome level across all channels:
                        imgData.data[i] = imgData.data[i+1] = imgData.data[i+2] =
                        RGBtoGRAYSCALE(imgData.data[i], imgData.data[i+1], imgData.data[i+2]);
                    }
                    
                    y++;
                    setTimeout(arguments.callee, 0);
                    
                })();
                return;
            } else {
                // If desatIMG was called without 'prepare' flag
                // then cancel recursion and proceed with force! (below)
                desatIMG.preparing = false;
            }
            
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var i = (y * width + x) * 4;
                    // Apply Monoschrome level across all channels:
                    imgData.data[i] = imgData.data[i+1] = imgData.data[i+2] =
                    RGBtoGRAYSCALE(imgData.data[i], imgData.data[i+1], imgData.data[i+2]);
                }
            }
            
            context.putImageData(imgData, 0, 0, 0, 0, width, height);
            return canvas;
        
        },
        getStyle = function(el, prop) {
            var style = document.defaultView && document.defaultView.getComputedStyle ? 
                        document.defaultView.getComputedStyle(el, null)[prop]
                        : el.currentStyle[prop];
            // If format is #FFFFFF: (convert to RGB)
            if (style && /^#[A-F0-9]/i.test(style)) {
                    var hex = style.match(/[A-F0-9]{2}/ig);
                    style = 'rgb(' + parseInt(hex[0], 16) + ','
                                   + parseInt(hex[1], 16) + ','
                                   + parseInt(hex[2], 16) + ')';
            }
            return style;
        },
        RGBtoGRAYSCALE = function(r,g,b) {
            // Returns single monochrome figure:
            return parseInt( (0.2125 * r) + (0.7154 * g) + (0.0721 * b), 10 );
        },
        getAllNodes = function(context) {
            var all = Array.prototype.slice.call(context.getElementsByTagName('*'));
            all.unshift(context);
            return all;
        };
        
    var init = function(context) {
        
        // Handle if a DOM collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodeName) {
            // Is a DOM collection:
            var allContexts = Array.prototype.slice.call(context),
                cIndex = -1, cLen = allContexts.length;
            while (++cIndex<cLen) { init.call(this, allContexts[cIndex]); }
            return;
        }
        
        context = context || document.documentElement;
        
        if (!document.createElement('canvas').getContext) {
            context.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)';
            context.style.zoom = 1;
            return;
        }
        
        var all = getAllNodes(context),
            i = -1, len = all.length;
            
        while (++i<len) {
            var cur = all[i];
            
            if (cur.nodeName.toLowerCase() === 'img') {
                var src = cur.getAttribute('src');
                if(!src) { continue; }
                if (isExternal(src)) {
                    config.externalImageHandler.init(cur, src);
                } else {
                    data(cur).realSRC = src;
                    try {
                        // Within try statement just encase there's no support....
                        cur.src = data(cur).dataURL || desatIMG(cur).toDataURL();
                    } catch(e) { config.externalImageHandler.init(cur, src); }
                }
                
            } else {
                for (var pIndex = 0, pLen = config.colorProps.length; pIndex < pLen; pIndex++) {
                    var prop = config.colorProps[pIndex],
                    style = getStyle(cur, prop);
                    if (!style) {continue;}
                    if (cur.style[prop]) {
                        data(cur)[prop] = style;
                    }
                    // RGB color:
                    if (style.substring(0,4) === 'rgb(') {
                        var monoRGB = RGBtoGRAYSCALE.apply(null, style.match(/\d+/g));
                        cur.style[prop] = style = 'rgb(' + monoRGB + ',' + monoRGB + ',' + monoRGB + ')';
                        continue;
                    }
                    // Background Image:
                    if (style.indexOf('url(') > -1) {
                        var urlPatt = /\(['"]?(.+?)['"]?\)/,
                            url = style.match(urlPatt)[1];
                        if (isExternal(url)) {
                            config.externalImageHandler.init(cur, url);
                            data(cur).externalBG = true;
                            continue;
                        }
                        // data(cur).BGdataURL refers to caches URL (from preparation)
                        try {
                            var imgSRC = data(cur).BGdataURL || (function(){
                                    var temp = document.createElement('img');
                                    temp.src = url;
                                    return desatIMG(temp).toDataURL();
                                })();
                            
                            cur.style[prop] = style.replace(urlPatt, function(_, url){
                                return '(' + imgSRC + ')';
                            });
                        } catch(e) { config.externalImageHandler.init(cur, url); }
                    }
                }
            }
        }
        
    };
    
    init.reset = function(context) {
        // Handle if a DOM collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodeName) {
            // Is a DOM collection:
            var allContexts = Array.prototype.slice.call(context),
                cIndex = -1, cLen = allContexts.length;
            while (++cIndex<cLen) { init.reset.call(this, allContexts[cIndex]); }
            return;
        }
        context = context || document.documentElement;
        if (!document.createElement('canvas').getContext) {
            context.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=0)';
            return;
        }
        var all = getAllNodes(context),
            i = -1, len = all.length;
        while (++i<len) {
            var cur = all[i];
            if (cur.nodeName.toLowerCase() === 'img') {
                var src = cur.getAttribute('src');
                if (isExternal(src)) {
                    config.externalImageHandler.reset(cur, src);
                }
                cur.src = data(cur).realSRC || src;
            } else {
                for (var pIndex = 0, pLen = config.colorProps.length; pIndex < pLen; pIndex++) {
                    if (data(cur).externalBG) {
                        config.externalImageHandler.reset(cur);
                    }
                    var prop = config.colorProps[pIndex];
                    cur.style[prop] = data(cur)[prop] || '';
                }
            }
        }
    };
    
    init.prepare = function(context) {
        
        // Handle if a DOM collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodeName) {
            // Is a DOM collection:
            var allContexts = Array.prototype.slice.call(context),
                cIndex = -1, cLen = allContexts.length;
            while (++cIndex<cLen) { init.prepare.call(null, allContexts[cIndex]); }
            return;
        }
        
        // Slowly recurses through all elements
        // so as not to lock up on the user.
        
        context = context || document.documentElement;
        
        if (!document.createElement('canvas').getContext) { return; }
        
        var all = getAllNodes(context),
            i = -1, len = all.length;
        
        while (++i<len) {
            var cur = all[i];
            if (data(cur).skip) { return; }
            if (cur.nodeName.toLowerCase() === 'img') {
                if (cur.getAttribute('src') && !isExternal(cur.src)) {
                    desatIMG(cur, true);
                }
                
            } else {
                var style = getStyle(cur, 'backgroundImage');
                if (style.indexOf('url(') > -1) {
                    var urlPatt = /\(['"]?(.+?)['"]?\)/,
                        url = style.match(urlPatt)[1];
                    if (!isExternal(url)) {
                        var temp = document.createElement('img');
                        temp.src = url;
                        desatIMG(temp, true, cur);
                    }
                }
            }
        }
    };
    
    return init;

})();
	

	
	
	
