// nachhilfe.de Javascript
// @author Andreas frey, frey@kono.de

document.observe("dom:loaded", function() {
	
    var duration = 0.3;
	var transition = function(pos) {
     	return Math.sqrt(pos);
    };

	
	
	
	if(window.location.host.substr(window.location.host.length - 3) == '.ch') {
		var search_pid = 2917;
		var country =  'ch';
	} else {
		var search_pid = 9;
		var country =  'de';
	}
	
	// Autocompletion Suchbox:
		var first_value = "PLZ oder Ort";
		if ($('standortsuche')) {
// console.info(document.URL);
			new Ajax.Autocompleter('city', 'autocomplete_search',
					'index.php?id='+ search_pid + "&tx_konosdk_pi1[country]=" + country, {
						encoding :'UTF-8',
						minChars :4,
						updateElement : function(value) {
							// // console.info(value);
						if (value) {
							if (value.hasClassName('city')) {
								$('pid').setValue('');
							}
						}
					},
					// callback : function(field, querystring) {
						// if($('flashcontent')) {
						// $('flashcontent').setStyle({visibility: 'hidden'});
						// }
						// return querystring;
						// },
						// afterUpdateElement : function(field, item) {
						// if($('flashcontent')) {
						// $('flashcontent').setStyle({visibility: 'visible'});
						// }
						// return querystring;
						// },
						indicator :"indicator"
					});
			$('city').setValue(first_value);
			$('city').observe("click", clear_field);
			$('city').observe("keyup", clear_field);
		} // end if standortsuche
		
		
		
		// Standort-Portaits Routenplaner ein und ausblenden:
		
		
		if($('drive_container')) {
		
		
			
				
        	$('nhf_undriver').observe("click", function(event) {
        			event.stop();
        			Effect.toggle('drive_container', 'blind', {duration:duration, transition:transition});
        			Effect.Appear('kontaktformular', {duration:duration, transition:transition});
        			Effect.Appear('nhf_driver', {duration:duration, transition:transition});
        	})
        	
        	$('nhf_driver').observe("click", function(event) {
        		  		
        			
        			
        			event.stop();
        			Effect.toggle('kontaktformular', 'blind', {duration:duration, transition:transition});
        			Effect.Appear('drive_container', {duration:duration, transition:transition});
        			if ($('station_map').src == ""){
        			$('station_map').src = $('yellow_marker').getAttribute("name");
        			}
        			$('nhf_driver').hide();
   			
        	})
        	
        	if ($('route_marker') !=null) {
        		if ($('station_map').src == ""){
        			$('station_map').src = $('yellow_marker').getAttribute("name");
        		}
        		$('kontaktformular').hide();
        		$('drive_container').style.display= "block";
        		$('nhf_driver').hide();
        	
        		
        		
        	}
              
        }

		
		
		
		
		
		

		if ($('konosdk_search')) {
			$('konosdk_search').observe('submit', function(event) {
				var current_value = $F('city');
				if (!current_value || current_value == first_value) {
					$('city').setValue(first_value);
					$('city').observe("click", clear_field);
					( function() {
						$('city').observe("keyup", clear_field)
					}).delay(1);
					new Effect.Highlight('city', {
						duration :5
					});
					event.stop();
				}
			});
		}

		/*
		 * if($('suchefull')) { new
		 * Ajax.Autocompleter('suchefull','autocomplete_searchfull',
		 * 'index.php?id=1250', { encoding: 'UTF-8', minChars:4,
		 * updateElement:function(value) { if (value) {
		 * $('indicatorfull').show(); $('suchefull').value =
		 * value.down().firstChild.nodeValue; $('suchefull').form.submit(); } },
		 * indicator:"indicatorfull" }); }
		 */

		$$("div.link_box").each( function(box) {
			var a = box.down("a");
			if (a) {
				box.setStyle( {
					cursor :'pointer'
				});
				box.observe("click", function(event) {
					window.location = a.href;
				});
			}
		});

		$$("div.p_box", "div.neue_texte").each( function(box) {
			var a = box.down("a");
			if (a) {
				box.setStyle( {
					cursor :'pointer'
				});
				box.observe("click", function(event) {
					window.location = a.href;
				});

			}
			box.select("img").each( function(img) {
				img.alt = img.alt.replace(/\|/g, ' ');
				img.title = img.title.replace(/\|/g, ' ');
			});
		});

		// IE 6 first-child
		if (Prototype.Browser.IE) {
			$$('#menue ul ul').each( function(li) {
				li.down().setStyle( {
					borderTopWidth :"1px",
					borderTopStyle :"solid",
					paddingTop :"5px"
				});
			});
		}

		
		
		check_nach_oben_links();
		
		Event.observe(window, "resize", check_nach_oben_links);
		
		
		// Get Document Dimensions
		/*
		 * if ( Prototype.Browser.IE ) { $$('body').each(function(doc) { if
		 * (doc.getHeight() < document.viewport.getHeight()) { BottomOffset =
		 * (document.viewport.getHeight() - doc.getHeight() - 140) + "px";
		 * $('bottom').setStyle({marginTop:BottomOffset}); } }); } else {
		 * $$('html').each(function(doc) { if (doc.getHeight() <
		 * document.viewport.getHeight()) { BottomOffset =
		 * (document.viewport.getHeight() - doc.getHeight()) + "px";
		 * $('bottom').setStyle({marginTop:BottomOffset}); } }); }
		 */

		
		// alle Linkziele mit ref='load' vorausladen. Dies verfälscht allerdings
		// den eTracker
		/*
		 * $$('a[rel="load"]').each(function(e) { p_sHref =
		 * e.getAttribute('href'); if (/^#/.match(p_sHref) || p_sHref == '' ||
		 * !p_sHref) return; l_oIframe = new Element('iframe', { src :p_sHref
		 * }).hide(); document.body.appendChild(l_oIframe); } ); //
		 */
		
		if($('lerncheck')) {
			// label-for simulieren in Tabellenzellen
			$('lerncheck').observe("click", function(event) {
				if(event.target.tagName.toLowerCase() == 'td') {
					var td = $(event.target);
					if(td) {
						td.down("input").checked = true;
					}
				}
			});
		}
		
}); // end document.observe

/**
 * Den nach-oben-link ein-oder ausblenden, abh�ngig von der Gr��e des Viewports
 * und der Position des Links
 * 
 * @return
 */
function check_nach_oben_links() {
	
	$$('div.top_link_div').each(function(a) {
		var top;
		if(a.getAttribute("cumulativeOffsetTop")) {
			top = a.getAttribute("cumulativeOffsetTop");
		} else {
			top = a.cumulativeOffset()['top'];
			a.setAttribute("cumulativeOffsetTop", top);
		}
		
		if(top < document.viewport.getHeight()) {
			a.hide();
		} else {
			a.show();
		}
		
	});
}

function city_search_selected(element) {
	var pid = element.getAttribute('pid');
	var city = getObjInnerText(element);
	// // console.info('pid: ', pid, ', city: ', city);
	$('city').setValue(city);
	$('pid').setValue(pid);
	$('konosdk_search').down("input[type='submit']").setValue("Zum Standort");
}

function getObjInnerText(obj) {
	if (obj.innerText) { // IE;
		return obj.innerText;
	} else {
		if (obj.textContent) {
			return obj.textContent;
		} else {
			alert("Error: This application does not support your browser. Try again using IE or Firefox.");
		}
	}
}

function switch_route(what) {
	var station_image = $F('station_image');
	if (what == 'route') {
		$('station_map').src = Prototype.station_map;
		$('switch_to_route').hide();
		$('switch_to_map').show();
	} else {
		Prototype.station_map = $('station_map').src;
		$('station_map').src = station_image;
		$('switch_to_map').hide();
		$('switch_to_route').show();
	}
}

function check_required(event) {
	event.stop();
	if ($('required_hint')) {
		$('required_hint').removeClassName('error');
	}

	var inputs = this
			.select('input.required')
			.map( function(input) {
				input.removeClassName('error');
				 //console.info(input.id);
					input.up().down("label[for='" + input.id + "']")
							.removeClassName('error');
					
									
					
					if (input.getAttribute('type') == 'radio') {
						var id = input.id.substr(0, input.id.length - 2);
						if ($(id)) {
							$(id).removeClassName('error');
						}
						// console.info($A(document.getElementsByName(input.name)).find(function(i)
						// {return i.checked}));
						if (!$A(document.getElementsByName(input.name)).find(
								function(i) {
									return i.checked
								})) {
							return input;
						}

						return;
					}
					var value = $F(input);
					if (!value) {
						return input;
					}

					if (input.hasClassName("email")) {
						emailpat = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9]+)+$/;
						if (!emailpat.test(value)) {
							return input;
						}
					}
                    if (input.hasClassName("date")) {
                        if($F(input) == 'TT.MM.YYYY') {
                            return input;
                        }
                    }
			});                 
         			
                    
           
			
	inputs = inputs.compact();
	//console.info(inputs);
	
		
	if (inputs.length > 0 | check_application_required(this.name)==true) {

		if ($('required_hint')) {
			$('required_hint').addClassName('error');
		}
		inputs.each( function(input) {
			// input.addClassName('error');
			input.up().down("label[for='" + input.id + "']").addClassName(
					'error');
             
			if (input.getAttribute('type') == 'radio') {
				var id = input.id.substr(0, input.id.length - 1);
				if ($(id)) {
					$(id).addClassName('error');
				}
			}
            
		});
			
		// console.info("Fehler");
	} else {
			
		this.submit();
			
	}
}

//Function check_application_required(formName)
//Gordon Schmidt 9.12.09
//ueberprueft die Sonderfelder des Job-Application-Forms


function check_application_required(formName){
	
	var error=false;
	//alert(formName);
	if (formName=="application_form"){
	
	
	//Salutation
	if	($F("tx_konosdk_pi15_salutation")==""){
		$("salutation").addClassName('error');
		error=true;
	}else{
		$("salutation").removeClassName('error');
    	error=false;
	}	
		
	
	// Faecher
	if ($F("tx_konosdk_pi15_fach_franzoesisch")!="Französisch" && $F("tx_konosdk_pi15_fach_englisch")!="Englisch" && $F("tx_konosdk_pi15_fach_mathematik")!="Mathematik" && $F("tx_konosdk_pi15_fach_latein")!="Latein" && $F("tx_konosdk_pi15_fach_deutsch")!="Deutsch" && $F("tx_konosdk_pi15_sonstige_faecher")==""   ){
		$("unterrichtsfaecher").addClassName('error');
		error=true;
     }else{
    	 $("unterrichtsfaecher").removeClassName('error');
    	 error=false;
     }
	
	// Standorte
	if ($F("tx_konosdk_pi15_station_uid1")=="" && $F("tx_konosdk_pi15_station_uid2")=="" && $F("tx_konosdk_pi15_station_uid3")==""){
		$("arbeitsorte").addClassName('error');
		error=true;
     }else{
    	 $("arbeitsorte").removeClassName('error');
    	 error=false;
     }
	
	// Erreichte Qualifikationen
	if ($F("tx_konosdk_pi15_qualification")==""){
		$("qualifikation").addClassName('error');
		error=true;
     }else{
    	 $("qualifikation").removeClassName('error');
    	 error=false;
     }
	
	
	// Jahrgangsstufen
	if ($F("tx_konosdk_pi15_jahrgangsstufe_primarstufe")!= "Klassen 1-4" && $F("tx_konosdk_pi15_jahrgangsstufe_sekundarstufe1")!="Klassen 5-10" && $F("tx_konosdk_pi15_jahrgangsstufe_sekundarstufe2")!="Klassen 11-13" && $F("tx_konosdk_pi15_jahrgangsstufe_berufsschule")!="Berufsschule" ){
		$("jahrgangsstufen").addClassName('error');
		error=true;
     }else{
    	 $("jahrgangsstufen").removeClassName('error');
    	 error=false;
     }
	
	}
	return error;

}


function show_date(date_uid) {
	var div = $('date_' + date_uid);
	if (div) {
		$('date_open_' + date_uid, 'date_close_' + date_uid).invoke("toggle");
		var text = div.next("tr.date_text");
		if (text.visible()) {
			new Effect.Fade(text);
		} else {
			new Effect.Appear(text);
		}
	}
}

function clear_field(event) {
	if (this.getAttribute("type") != 'submit'
			&& this.getAttribute("type") != 'button') {
		this.setValue('');
	}
	this.stopObserving('click', clear_field);
	this.stopObserving('keyup', clear_field);
}

var toSleep = true;
function stopTimer() {
	toSleep = false;
}
function clickTracker(LinkName) {
	var secureID = "VjV1l3";
	var redirectUrl = "http://www.etracker.de/skin/de.def/img/1px.gif";
	etrackerSink = new Image(1, 1);
	toSleep = true;
	etrackerSink.src = "http://www.etracker.de/lnkcnt.php?et=" + secureID
			+ "&url=" + redirectUrl + "&lnkname=" + LinkName;
	etrackerSink.onload = stopTimer;
	if (toSleep == true) {
		maxDelay(500);
	}
	return true;
}
function maxDelay(gap) {
	var then, now;
	then = new Date().getTime();
	now = then;
	while (toSleep == true && (now - then) < gap) {
		now = new Date().getTime();
	}
}
