 
Request.XML = new Class({
 
Extends: Request,
 
success: function(text, xml){
    xml = { documentElement: this.createXML(xml.documentElement) };
    this.onSuccess(text, xml);
},
 
createXML : function(xml, parent) { 

    if (! parent) parent = new Element(xml.nodeName);
 
    var tmp;
    for(var j = 0; j < xml.attributes.length; j++) {
        tmp = xml.attributes[j];
        parent.setProperty(tmp.nodeName, tmp.nodeValue);
    } 
    if (! xml.childNodes.length) return parent;
 
    var i, j, currChildNode;
    for(i = 0; i < xml.childNodes.length; i++) {
        currChildNode = xml.childNodes[i];
       // console.log(currChildNode.nodeType == 1);
        if (currChildNode.nodeType == 1) { // Element type
            // NodeName
            var el = new Element(currChildNode.nodeName);
 
            // Attributes
            if(currChildNode.attributes.length) {
                for(j = 0; j < currChildNode.attributes.length; j++) {
                    tmp = currChildNode.attributes[j];
                    el.setProperty(tmp.nodeName, tmp.nodeValue);
                }
            }
 
            // set Value
            if( currChildNode.childNodes.length)
                    el.set({'text' : currChildNode.firstChild.nodeValue});
            else  //IE ignores empty-data nodes in childNode-Array
                    el.set({'text' : null});
           
            parent.adopt(el);
 
            if (currChildNode.childNodes.length) this.createXML(currChildNode, el);
        }
    }
 
    return parent;
}
 
});

window.addEvent('domready', function() {
	status = "";
	yli = false;
	dataNodes = null;
	currentP = null;
	currentPrice = 0;
	
	//document.id('setup').setStyle('height','0px').fade('hide');
	//document.id('control').setStyle('height','0px').fade('hide');
	
	
	mySetup = new Fx.Morph('setup').set({
    	'height': 0,
    	'opacity': 0,
    	'display':'none'
	});
	myControl = new Fx.Morph('control').set({
    	'height': 0,
    	'opacity': 0,
    	'display':'none'
	});

	
	
	initData();
	
	
	document.getElements('div.info, div.infoA').addEvent('click',function(e){
				var ajaxFace = new LightFace.Request({
					width: 350,
					url:'info.php?target='+e.target.get('id'),
					height: 170,
					buttons: [
						{ title: 'Sulje', event: function() { this.close(); }, color: 'green' }
					],
					request: { 
						data: { 
							name: 'Info'
						},
						method: 'post'
					},
					title: e.target.get('title')
				}).open();
				e.stopPropagation();
			});
	
	
	
	
	document.id('add1_check').addEvent("change",function(){document.id('sm').getChildren('select').fireEvent('change')})
	
	document.id('submit_offer').addEvent("click", function(){
		if(checkForm()){
			var sm = document.id('sm').getChildren('select').get('value');
			var k = document.id('kerrokset_select').getSelected().get('text');
			var t = document.id('termostaatit_select').getSelected().get('text');			
			var add = document.id('add1_check').get('checked');
			var extra = document.id('extra').get('value');
			var nimi = document.id('nimi').get('value');
			var puhelin = document.id('puhelin').get('value');
			var postiO = document.id('postiO').get('value');
			var postiNr = document.id('postiNr').get('value');
			var email = document.id('email').get('value');
			var y = document.id('yritys').get('value');
			var yEmail = document.id('email_yritys').get('value');
			var yPuhelin = document.id('puhelin_yritys').get('value');
			var myyja = document.id('myyja').get('value');
			var isYli = yli;
		
			var myRequest = new Request({
    			url: 'createPDF.php',
		    	method: 'get',
			    data: 'sm='+sm+
			    		 '&kerrokset='+k+
			    		 '&termostaatit='+t+
			    		 '&add1='+add+
			    		 '&extra='+escape(extra)+
			    		 '&nimi='+escape(nimi)+
			    		 '&puhelin='+puhelin+
			    		 '&osoite='+escape(postiO)+
			    		 '&zip='+postiNr+
			    		 '&email='+email+
			    		 '&yritys='+escape(y)+
			    		 '&yEmail='+yEmail+
			    		 '&yPuhelin='+yPuhelin+
			    		 '&myyja='+escape(myyja)+
			    		 '&price='+currentPrice+
			    		 '&contact='+document.id('contact_me').get('checked')+
			    		 '&pID='+currentP+
			    		 '&yli='+isYli+
			    		 '&pName='+document.id('p_name').get('html'),
			    onRequest: function(){
			        document.id('send_status').set('html', 'Tarjousta l&auml;hetet&auml;&auml;n');
    			},
		    	onSuccess: function(responseText){
        			document.id('send_status').set('html', responseText);
		    	},
    			onFailure: function(){
		        	document.id('send_status').set('html', 'Valitettavasti jokin meni vikaan, ole hyvŠ ja yritŠ uudestaan.');
    			}
			}).send();
		}
	});
	
	
	var pIDs = $('products').getElements('div').get('id');
	//console.log(pIDs);
		
	document.id('products').addEvent("click", function(event){
		if(pIDs.contains(event.target.id)){		
			document.id('products').getElements('div.product').fade(0.5);
			document.id('products').getElement('div#'+event.target.id).fade(1);
			currentP = event.target.id;
			if(document.id('setup').getStyle('visibility') == 'hidden'){
				//document.id('setup').tween('height','0').fade('in');
				//document.id('control').tween('height','0').fade('in');
				mySetup.start(
					{
						height: '800',
						opacity: '1',
						display: 'block'
					}
				);
				myControl.start(
					{
						height: '500',
						opacity: '1',
						display: 'block'
					}
				);
			}	
			var myFx = new Fx.Scroll(window).toElement(document.id('products'));		
			document.id('sm').getChildren('select').fireEvent('change');
			if(dataNodes != null)
				productTitle();
		}						
	});
});

function productTitle(){
	//console.log(dataNodes.getElement('product[id='+currentP+']').getElement('name').get('text'));
	document.id('p_name').set('text',dataNodes.getElement('product[id='+currentP+']').getElement('name').get('text'));
}

function initData(){
	var myNodes;

	var myRequest = new Request.XML({
	    url: 'xml/prices.xml',
    	method: 'get',
	    onRequest: function(){
        	//myElement.set('text', 'loading...');
    	},
	    onSuccess: function(responseText, responseXML){	    
			//console.log(responseXML.documentElement);
		    dataNodes = responseXML.documentElement;
			createSelects();

	    },
    	onFailure: function(){
	    	status = "Tuotetietoja ei pystytty lataamaan";
        	//myElement.set('text', 'Sorry, your request failed :(');
    	}
	}).send();
}

function createSelects(){

	var kerrokset = new Element('select',{
		'id' : 'kerrokset_select',
		events:{
			change: function(){
				document.id('sm').getChildren('select').fireEvent('change');
			}
		}
	});
	var termostaatit = new Element('select',{
		'id' : 'termostaatit_select',
		events:{
			change: function(){
				document.id('sm').getChildren('select').fireEvent('change');
			}
		}
	});
	
	var termoInfo = new Element('div', {
		'id':'info9',
		'class':'infoA',
		'html':'info',
		'title':'Termostaatit'
	});
		
	var sm = new Element('select',{
		'id' : 'sm_select',
		events: {
			change: function(){
				if(this.getSelected().get('class') == "yli"){
					yli = true;
					document.id('yli_msg').set('html','Lattian pinta-ala > 300 m<sup>2</sup>: Ole hyv&auml; ja ota yhteytt&auml; Somasyriin saadaksesi tarjous suuremmalle projektille.');
					document.id('yli_msg').set('style','border-bottom:1px solid black; color:#ff0000;padding-bottom:15px;');
				}else{
					yli = false;
					document.id('yli_msg').set('html','');
					document.id('yli_msg').set('style','border-bottom:none');
				};
				var v = this.value;
				var vNew = this.value;
				var add1 = 0;
				if(document.id('add1_check').checked == true)
					add1 = Number.from(document.id('add1_check').value);
					
				while(vNew%5 != 0){
					vNew--;
					//console.log(vNew);
				}
				//console.log( dataNodes.getElement('vesiPatteriverkosto').getElement('amount').get('text'));
				var vesi = (document.id('add1_check').checked == true ? Number.from(dataNodes.getElement('vesiPatteriverkosto').getElement('amount').get('text')) : 0);
				//console.log("Vesi "+vesi);				
				var priceTag = dataNodes.getElement('product[id='+currentP+']').getElements('sm[val='+vNew+']').get('text');
				var price = ( (v*priceTag) + (Number.from(kerrokset.value)) + (Number.from(termostaatit.value)) + vesi).round(3);
				var xZero = "";
				if(price.toString().charAt(price.toString().length-2) == "."){
					xZero = "0";
				}
				document.id('price').set('html',price+xZero+" &euro;");
				document.id('price').highlight();
				currentPrice = price;
				//console.log("Current price "+currentPrice);
				//console.log("Overall: "+price+" sm: "+(v*priceTag).round(3)+" - termos: "+termostaatit.value+" - ker: "+kerrokset.value+" - add: "+vesi);
			}
		}
	});

	if(dataNodes != null){
		dataNodes.getElement('kerrokset').getElements('amount').each(function(amount) {
			kerrokset.grab(new Element('option',{
				'text' : amount.get('val'),
				'value' : amount.get('text')
			}));
		});
	}
	
	dataNodes.getElement('termostaatit').getElements('amount').each(function(amount) {
		termostaatit.grab(new Element('option',{
			'text' : amount.get('val'),
			'value' : amount.get('text')
		}));			
	});
	for(var i = 40; i < 301; i++){
		sm.grab(new Element('option',{
			'text' : i,
			'value' : i
		}));
	}
	sm.grab(new Element('option',{
		'text' : 'yli 300',
		'value' : '300',
		'class' : 'yli'
	}));

	termoInfo.addEvent('click',function(e){
				var ajaxFace = new LightFace.Request({
					width: 350,
					url:'info.php?target='+e.target.get('id'),
					height: 170,
					buttons: [
						{ title: 'Sulje', event: function() { this.close(); }, color: 'green' }
					],
					request: { 
						data: { 
							name: 'Info'
						},
						method: 'post'
					},
					title: e.target.get('title')
				}).open();
				e.stopPropagation();
			});


	document.id('kerrokset').grab(kerrokset);
	document.id('termostaatit').grab(termostaatit).grab(termoInfo);
	document.id('sm').grab(sm);
}

function checkForm(){
	var error = false;
	document.getElements(".error").toggleClass('error');
	var sElement = document.id('send_status');
	var name = document.id('nimi').get('value').toString();
	var email = document.id('email').get('value').toString();
	var company = document.id('yritys').get('value').toString();
	var cEmail = document.id('email_yritys').get('value').toString();
	
	//console.log(name+" "+email+" -----"+ typeof(name)+" - "+typeof(email)+" "+name.length);	
	
	
	if( (name == "" && email != "") || (name != "" && email == "")){								
		if(name.length != 0){
			document.id('email').set('class','error');
			sElement.set('html','Ole hyv&auml; ja t&auml;yt&auml; puuttuvat kent&auml;t (Email)');
		}else{									
			document.id('nimi').set('class','error');
			sElement.set('html','Ole hyv&auml; ja t&auml;yt&auml; puuttuvat kent&auml;t (Nimi)');
		}		
		return false;
	}else if(name != "" && email != ""){
			if(!checkemail(email)){
				document.id('email').set('class','error');
				sElement.set('html','Ole hyv&auml; ja tarkista email-osoitteesi.');		
			return false;
			}
	}
	
	if( (company == "" && cEmail != "") || (company != "" && cEmail == "")){								
		if(company.length != 0){
			document.id('email_yritys').set('class','error');
			sElement.set('html','Ole hyv&auml; ja t&auml;yt&auml; puuttuvat kent&auml;t (Yritys Email)');
		}else{									
			document.id('yritys').set('class','error');
			sElement.set('html','Ole hyv&auml; ja t&auml;yt&auml; puuttuvat kent&auml;t (Yritys)');
		}		
		return false;
	}else if(company != "" && cEmail != ""){
			if(!checkemail(cEmail)){
				document.id('email_yritys').set('class','error');
				sElement.set('html','Ole hyv&auml; ja tarkista email-osoitteesi.');		
			return false;
			}
	}	
	
	if(name == "" && email == "" && company == "" && cEmail == ""){
		sElement.set('html','T&auml;yt&auml; yhteystietolomake.');		
		return false;
	}
	
	

	return true;
}

function checkemail(m){
	var str=m
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i

	if (filter.test(str))
		testresults=true
	else
		testresults=false
	
	return (testresults)
}
