/**
 * @author Christoph Gentsch / Ironshark Entertainment
 */
 var cont_instance;
 
 function Contact() {
 	
	this.std_keys = [8,9,35,36,37,38,39,40,45,46,32,109,190]; //bsp,tab,end,home,left,up,down,right,ins,del,leer,-,.
	this.num_keys = [48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105]; //0-9 std & numpad
	
 	this.init = function() {
 		
 		cont_instance = this;
 		
 		$("#submit").hide();
 		
 		//events definieren
 		$("select").change( function () {
			if($("select :selected")[0].index>0) {
				$(this).removeClass("error");
			}
			else
				$(this).addClass("error");
 		});
 		
 		//restrict input
		$("#email").keydown( function(e) {
				var keys = cont_instance.std_keys.concat(cont_instance.num_keys);
				if($.inArray(e.which,keys)!=-1 || (e.which>64 && e.which<91))
					return this;
				else
					return false;
		});
		
		$("#tel,#zipcode").keydown( function(e) {
				var keys = cont_instance.std_keys.concat(cont_instance.num_keys);
				if($.inArray(e.which,keys)!=-1 || e.which==111)
					return this;
				else
					return false;
		});
		//give error when empty
		$("#name,#firstname,#captcha,#message,#tel,#city").keyup( function() {
			if(trim($(this).attr("value"))!="")
				$(this).removeClass("error"); 
			else
				$(this).addClass("error");
		});
		$("#name,#firstname,#captcha,#message,#tel,#city").blur( function() {
			$(this).attr("value",trim($(this).attr("value")));
			if(trim($(this).attr("value"))!="")
				$(this).removeClass("error"); 
			else
				$(this).addClass("error");
		});
		
		$("#email").keyup( function() {
			var text = $(this).attr("value");
			if(text!="" && text.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/gi)==text ) {
				$(this).removeClass("error");
			}
			else
				$(this).addClass("error");
		});
		$("#email").blur( function() {
			var text = $(this).attr("value");
			if(text!="" && text.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/gi)==text ) {
				$(this).removeClass("error");
			}
			else
				$(this).addClass("error");
		});

		$("#zipcode").keyup( function() {
			var text = $(this).attr("value");
			var param = {};
			param.zipcode = text;
			$.post("./lib/lib_request.php", param, function(e){
				if (e.city!=undefined)
				{
					$('#city').attr('value',e.city);
					$('#city').removeClass("error");
					$('#zipcode').removeClass("error");
				}
				else
				{
					$('#zipcode').addClass("error");
					$('#city').attr('value','');
					$('#city').addClass("error");
				}
			}, "json");
		});
		$("#zipcode").blur( function() {
			var text = $(this).attr("value");
			var param = {};
			param.zipcode = text;
			$.post("./lib/lib_request.php", param, function(e){
				if (e.city!=undefined)
				{
					$('#city').attr('value',e.city);
					$('#city').removeClass("error");
					$('#zipcode').removeClass("error");
				}
				else
				{
					$('#zipcode').addClass("error");
					$('#city').addClass("error");
					$('#city').attr('value','');
				}
			}, "json");
		});
		
		$("#conConfig input, #conConfig select, #conConfig textarea").keyup( function() {
			if($("#conConfig input.error,#conConfig textarea.error,#conConfig select.error").length==0)
				$("#submit").fadeIn();
			else
				$("#submit").hide();
		});
		$("#conConfig input, #conConfig select, #conConfig textarea").blur( function() {
			if($("#conConfig input.error,#conConfig textarea.error,#conConfig select.error").length==0)
				$("#submit").fadeIn();
			else
				$("#submit").hide();
		});
		
		$("#conConfig #captcha").keypress( function(e) {
			if(e.which==13 && $("#conConfig input.error,#conConfig textarea.error,#conConfig select.error").length==0) {
				cont_instance.sendMail();
			}
		});
		
		$("#submit").click( function() {
			cont_instance.sendMail();
		});
		
		//load captcha picture
		this.loadCaptcha();
		
 	};
 	
 	this.sendMail = function() {
 		var fields = this.mapInputs("conConfig");
 		var mail = { mail: this.genMailText(fields), captcha:fields.captcha, zipcode:$('#zipcode').attr("value"), city:$('#city').attr("value") };
		$.post("index.php", mail, cont_instance.messageSent, "json");
 	};
 	
 	this.messageSent = function(data){
 		sessid = data.newsid;
 		if(data.status=="ok") {
 			Boxy.ask("Ihre Anfrage wurde versandt.", ["OK"], conf_instance.showPage(5) , {title: "Erfolg"});
 		}
 		else if(data.status=="error") {
 			if(data.type=="captcha") {
 				Boxy.ask("Der Sicherheitscode war leider falsch, bitte probieren Sie es noch einmal!", ["OK"], cont_instance.loadCaptcha, {title: "Fehler"});
 			}
 			else
 				Boxy.ask("Ihre Anfrage konnte leider nicht verschickt werden. Versuchen Sie es später noch einmal!", ["OK"], conf_instance.showPage(5), {title: "Fehler"});
 		} 			
 	};
 	
 	this.loadCaptcha = function() {
 		$("#cp_img").attr("src", "./lib/cpt_img.php?PHPSESSID="+sessid);
 	};
 	
 	/***
 	 * Create dataobject (map) from all inputs,selects and
 	 * textareas in a given div
 	 * @param {} div - id from container to be parsed for inputs
 	 * @return {} map
 	 */
 	this.mapInputs = function(div) {
 		var map = {};
 		$("#"+div+" input").each( function() {
 			var key = escape($(this).attr("id"));
 			var value =  escape($(this).attr("value"));
 			var temp = {};
 			eval( "temp."+key+"='"+value+"'" );
 			$.extend(map, temp );
 		});
 		$("#"+div+" textarea").each( function() {
 			var key = escape($(this).attr("id"));
 			var value =  escape($(this).attr("value"));
 			var temp = {};
 			eval( "temp."+key+"='"+value+"'" );
 			$.extend(map, temp );
 		});
 		$("#"+div+" value").each( function() {
 			var key = escape($(this).attr("id"));
 			var value =  escape($(this).attr("value"));
 			var temp = {};
 			eval( "temp."+key+"='"+value+"'" );
 			$.extend(map, temp );
 		});
 		$("#"+div+" select").each( function() {
 			var key = escape($(this).attr("id"));
 			var value =  parseInt($(this).attr("value"));
 			value = escape( this.options[value].text);
 			var temp = {};
 			eval( "temp."+key+"='"+value+"'" );
 			$.extend(map, temp );
 		});
 		return map;
 	};
 	
 	this.genMailText = function(mail) {
 		var line = "=============================================\n";
 		var msg = "";
 		
 		msg+= "Kundenanfrage\n\n";
 		msg+= "Kunde\n" + line;
 		msg+= "Firma: " + mail.company + "\n"; 
 		msg+= "Name: " + mail.gender + " " + mail.firstname + " " + mail.name + "\n";
 		msg+= "E-Mail: " + mail.email + "\n";
 		msg+= "Tel: " + mail.tel + "\n";
 		msg+= "Ort: " + mail.zipcode + " " + mail.city+"\n";
 		msg+= "Nachricht: " + mail.message + "\n\n\n";
 		
 		msg+= this.genMailAttachment();
 		return msg;
 	};
 	
 	this.genMailAttachment = function() {
 		var line = "=============================================\n";
 		var msg = "Konfiguration\n"+line;
 		$(conf_instance.config).each( function() {
 			var thisOpt = this.split("_")[2]; var thisStep = this.split("_")[1]; 
 			msg = msg + Configurator.mouseOver[thisStep].name + ": " + Configurator.mouseOver[thisStep].opts[thisOpt].name +"\n";
 		});
 		msg = msg + "\n\nProduktauswahl\n" + line;
 		msg = msg + "Dämmung: " + Configurator.products.dp.products[conf_instance.prodarray.dp[0]].name;
 		msg = msg + "\nEstrich: " + Configurator.products.ep.products[conf_instance.prodarray.ep[0]].name;
 		if(conf_instance.prodarray.zp!=undefined)
 			msg = msg + "\nZusatz: " + Configurator.products.zp.products[conf_instance.prodarray.zp].name;
 		msg = msg + "\n\nMaße:\n"+line;
 		msg = msg + "Fläche: " + calc_instance.dims.area + " m²\n";
 		msg = msg + "Schüttung: " + calc_instance.dims.height + " cm\n";
 		return msg;
 	};
 }

 function trim (zeichenkette) {
  // Erst führende, dann Abschließende Whitespaces entfernen
  // und das Ergebnis dieser Operationen zurückliefern
  return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
}

