
// Show form to enter client informations
function kundenInformationenPrompt() 
{
	// Show custom prompt promptform
	var pf = document.getElementById( 'promptform' );
	pf.style.display = 'block';
}

// Show form to advise customers that the chosen shell isn't buildable cause containing errors
function showServiceForm()
{
    alert('Bitte diese Planungsvariante mit dem Kundenservice durchsprechen, Rufnummer: 05244 9305 431');
}

// Send offer if all form fields are valid
function sendAnfrage(arg)
{
	var f = document.getElementById( 'promptform' );
	if ( 'cancel' == arg ) {
		f.style.display = 'none'; // hide form
		return; // exit immediately
	}
	else {
		var clientInfoArray=getClientData();
		
		dataValid=true;
		// Check if all fields are correct
		var i;
		for (i=0;i<5;i++) // 6 is nbItems in table, but montage already set
		{
			if(clientInfoArray[i]=='') 
			{
				dataValid=false;
			}
		}
		
		var f = document.getElementById( 'promptform' );
		// Check email
		if(echeck(f.mail.value))
		{
			// Check other fields
			if(dataValid) 
			{
				// Close form
				f.style.display = 'none'; // hide form
				
				generatePDFDatei(false, clientInfoArray);
			}
			else alert('Bitte alle Felder ausfüllen!');
		}
		else
		{
			alert('Bitte füllen Sie eine gültige Emailadresse aus!');
		}
	}
}

// Get informations from the form and return an array containing these informations
function getClientData() 
{
	var f = document.getElementById('promptform');
	var firstName = f.name.value;
	var name = f.firstName.value;
	var place=f.place.value;
	var phone=f.phone.value;
	var mail=f.mail.value;
	var montage=f.montage[0].checked;
	
	return new Array(firstName, name, place, phone, mail, montage);
}

// Collect informations from JS arrays and send it to PHP script to gererate a PDF file
// openPDF: boolean value, if true, the PDF will be directly opened, if false, it will be send by email
// kundenInformationen: array containing the following informations: first name, name, place, phone, mail, montage
function generatePDFDatei(openPDF, kundenInformationen)
{
	// Extrat regal structure material
	var materialSelect=document.getElementById('selectAusfuehrungRegal');
	strStructureMaterial=materialSelect.value;
	
	// Browse JS arrays to extract content
	var exportVerticalsArray=new Array(); // Will be used for the save operation
	var exportHorizontalsArray=new Array(); // Will be used for the save operation
	var exportJointsArray=new Array(); 
	var exportAddonsArray=new Array(); // Will be used for the save operation
	var exportFeetArray=new Array();
			
	// Verticals
	for(var i=0;i<verticals.length;i++)
	{
		for(var j=0;j<verticals[i].length;j++)
		{
			if(verticals[i][j]!=null && verticals[i][j].isRegal)
			{
				exportVerticalsArray.push(i+','+j);
				//alert('verticals:'+i+', '+j+' is regal');
			}
		}
	}
			
	// Horizontals
	for(var i=0;i<horizontals.length;i++)
	{
		for(var j=0;j<horizontals[i].length;j++)
		{
			if(horizontals[i][j]!=null && horizontals[i][j].isRegal)
			{
				exportHorizontalsArray.push(i+','+j);
				//alert('horizontals:'+i+', '+j+' is regal');
			}
		}
	}
			
	// Joints
	for(var i=0;i<joints.length;i++)
	{
		for(var j=0;j<joints[i].length;j++)
		{
			if(joints[i][j]!=null && (joints[i][j].toTop || joints[i][j].toBottom || joints[i][j].toLeft || joints[i][j].toRight))
			{
				exportJointsArray.push(i+','+j+','+joints[i][j].icon.className);
			}
		}
	}
	
	// Feet
	for(var i=0;i<feet.length;i++)
	{
		if(feet[i]!=null && feet[i].isRegal)
		{
			exportFeetArray.push(i);
		}
	}
	
	// Addons
	for(var i=0; i<addons.length;i++)
	{
		exportAddonsArray.push(addons[i].col+','+addons[i].row+','+addons[i].addonType+','+addons[i].ausfuehrung);
	}
	
	// Tables data
	strRegalWidth=document.getElementById('feldRegalMaszWidth').innerHTML;
	strRegalHeight=document.getElementById('feldRegalMaszHeight').innerHTML;
	strRegalDepth=document.getElementById('feldRegalMaszDepth').innerHTML;
	
	// Articles list
	var items=getElementsByClass('TableStuecklisteTdBezeichnung', null, 'td');
	var articlesArray=new Array();
	for(var i=0;i<items.length;i++)
	{
		if(items[i].parentNode.className=="")
		{
			articlesArray.push(WhiteSpaceTrim(items[i].parentNode.childNodes[0].innerHTML)+','+WhiteSpaceTrim(items[i].parentNode.childNodes[1].innerHTML)+','+WhiteSpaceTrim(items[i].parentNode.childNodes[2].innerHTML)+','+WhiteSpaceTrim(items[i].parentNode.childNodes[3].innerHTML)+','+WhiteSpaceTrim(items[i].parentNode.childNodes[4].innerHTML));
		}
	}
	var gesamtPreis=document.getElementById('feldPreis');
	gesamtPreisString=WhiteSpaceTrim(gesamtPreis.innerHTML);

	// Send data to server using Ajax
	exportVerticalsString=exportVerticalsArray.join(";");
	exportHorizontalsString=exportHorizontalsArray.join(";");
	exportAddonsString=exportAddonsArray.join(";");
	exportJointsString=exportJointsArray.join(";");
	exportFeetString=exportFeetArray.join(";");
	articlesListString=articlesArray.join(','); // Achtung, hier nur Komma
	
	// Create a global string containing all informations
	var globalString="&material="+strStructureMaterial+"&verticals="+exportVerticalsString+"&horizontals="+exportHorizontalsString+"&addons="+exportAddonsString+"&joints="+exportJointsString+"&feet="+exportFeetString+"&width="+strRegalWidth+"&height="+strRegalHeight+"&depth="+strRegalDepth+"&articles="+articlesListString+"&globalPrice="+gesamtPreisString;
	
	if(kundenInformationen!=null)
	{
		// Add these informationens to globalString
		exportClientInfosString=kundenInformationen.join(";");
		globalString+="&clientInfos="+exportClientInfosString;
	}
	
	if(openPDF)
	{
		// Create PDF and open it 
		//alert(globalString);
		answer=ajaxAccessOpen("php/createPDF.php", globalString+"&open=1");
		//answer=AjaxjQueryOpen("php/createPDF.php", globalString);
	}
	else
	{
		// Create PDF and sent it to company
		ajaxAccessSendMail("php/createPDF.php", globalString);
		
	}
}

// Send data to PHP script and then open PDF if the file has been correctly generated
// If an error occured during the generation, the message is displayed on screen
function ajaxAccessOpen(url, regalParameters)
{
  var xhr_object;
	if(window.XMLHttpRequest) // FIREFOX, IE7, IE8, Safari and so on, use native object
          xhr_object = new XMLHttpRequest();
     else if(window.ActiveXObject) // IE
          xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
     else
          return(false);
     
	var params = "regal="+regalParameters;
	xhr_object.open("POST", url, true);
	
	//Send the proper header information along with the request
	xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr_object.setRequestHeader("Content-length", params.length);
	xhr_object.setRequestHeader("Connection", "close");
	
		xhr_object.onreadystatechange = function() {//Call a function when the state changes.
			if(xhr_object.readyState == 4 && xhr_object.status == 200) {
				// Check answer
				if(testValidPDFFile(xhr_object.responseText))
				{
					// Open PDF file
					window.open("php/"+xhr_object.responseText);
				}
				else
				{
					// Error message
					alert('Die PDF Datei wurde nicht generiert: Fehler:'+xhr_object.responseText);
				}
			}
		}
	xhr_object.send(params);
}

// Send data to PHP script and then send the path of the PDF file to another script which will
// will send a mail with the file as attachment
// If an error occured during the PDF generation, an error mail will be sent
function ajaxAccessSendMail(url, regalParameters)
{
	var xhr_object;
	if(window.XMLHttpRequest) // FIREFOX
          xhr_object = new XMLHttpRequest();
     else if(window.ActiveXObject) // IE
          xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
     else
          return(false);
     
	var params = "regal="+regalParameters;
	xhr_object.open("POST", url, true);
	
	//Send the proper header information along with the request
	xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr_object.setRequestHeader("Content-length", params.length);
	xhr_object.setRequestHeader("Connection", "close");
	
		xhr_object.onreadystatechange = function() {//Call a function when the state changes.
			if(xhr_object.readyState == 4 && xhr_object.status == 200) {
		
				// Mail PDF file
				AjaxSendMail("php/sendMail.php", xhr_object.responseText);
			}
		}
	xhr_object.send(params);
}

// Send the PDF file path to a PHP script in order to send a mail with this file as attachment
function AjaxSendMail(url, regalParameters)
{
  var xhr_object;
	if(window.XMLHttpRequest) // FIREFOX
          xhr_object = new XMLHttpRequest();
     else if(window.ActiveXObject) // IE
          xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
     else
          return(false);
     
    // Get client informations
    var clientData=getClientData();
     
	var params = "file="+regalParameters+"&senderFirstName="+clientData[0]+"&senderName="+clientData[1]+"&senderEmail="+clientData[4];
	xhr_object.open("POST", url, true);
	
	//Send the proper header information along with the request
	xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xhr_object.setRequestHeader("Content-length", params.length);
	xhr_object.setRequestHeader("Connection", "close");
	
		xhr_object.onreadystatechange = function() {//Call a function when the state changes.
			if(xhr_object.readyState == 4 && xhr_object.status == 200) {
				
				// Show confirmation message
				alert(xhr_object.responseText);
			}
		}
	// Mail PDF file
	xhr_object.send(params);
}

function AjaxjQueryOpen(url, regalParameters){
  $.ajax({
    type: "POST",
    url: url,
    data: "regal="+regalParameters,
    success: function(msg){
      //alert( "Data Saved: " + msg );
      if(testValidPDFFile(msg)){
				// Open PDF file
				window.open("php/"+msg);
			}
			else{
				// Error message
				alert('Die PDF Datei wurde nicht generiert: Fehler:'+msg);
			}
    }
  });
  
}

/* --------------
   Tool classes
   -------------- */
		
function getElementsByClass(searchClass,node,tag) 
{
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}
		
function WhiteSpaceTrim (str)
{
	if(isString(str))
	{
	return str.replace('&nbsp;',' ');
	}
	else return str;
}

function isString(a) {
  		return typeof a == 'string';
}

function testValidPDFFile(str) {
	if (str.substring(str.length-4).toLowerCase() == ".pdf" && str.indexOf('<')==-1){
	return true;}
	else{
	return false;}
}

// Code to check the email address
function echeck(str) 
{
	var at="@"
	var dot="."
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
	   return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    return false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    return false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
	    return false;
	 }

	return true;					
}

// Check for each double horizontal item if it has a vertical item in the middle direct under
// For instance, for two horizontal items located at coordinates (1;1) and (2;1), a vertical 
// item of coordinates (1;1) must be defined
// Does not browse horizontals item from the floor
function isDesignValid(){
	for(var i=0;i<horizontals.length;i++)
	{
		for(var j=1;j<horizontals[i].length;j++) // Start at 1, cause the ground doesn't need to be checked
		{
			if(horizontals[i][j]!=null && horizontals[i][j].isRegal && hasHorizontalItemToRight(i, j) && !hasMiddleVerticalItem(i, j))
			{
				return false;
			}
		}
	}
	return true;
}

function hasHorizontalItemToRight(i, j) {
  return (horizontals[i+1][j] != null && horizontals[i+1][j].isRegal);
}

function hasMiddleVerticalItem(i, j) {
  return (verticals[i][j] != null && verticals[i][j].isRegal);
}

