// JavaScript Document

/*
  LOADER
*/
function initLoader(){
	document.body.className = 'loading';
}

function clearLoader(){
	if(HTTPRequest) return;

	document.body.className = '';
}
/*
  // LOADER
*/


/*
	HANDLE HTTP REQUEST
*/
var HTTPRequest;
function handleHTTPRequest(post, method){
	initLoader();
	
	if(HTTPRequest) return;
	
	HTTPRequest = new XMLHttpRequest();
	
	if(!HTTPRequest) return;
	
	HTTPRequest.onreadystatechange = function(){
		
		if(HTTPRequest.readyState == 4){
			if(HTTPRequest.status == 200){
				try{
					debug.contentWindow.document.write(HTTPRequest.responseText);
					debug.contentWindow.document.close();
				}catch(e){}
				
				try{
					eval(HTTPRequest.responseText);
				}catch(e){}
				
				clearLoader();
			}else{
				alert('An error has occured. The webmaster has been notified. The calculator will be reloaded.');
				window.location = '/';
			}
		}
		
		
	}

	HTTPRequest.open('POST', 'controllers/selector.cfc?method='+method, true);
	HTTPRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	HTTPRequest.send(post);
}
/*
	// HANDLE HTTP REQUEST
*/


/*
	APPTOOLBAR
*/

function handleLogout(){
	rubberProfileCalculator.userIsLoggedIn = false;
	window.location = 'controllers/sessionValidator.cfc?method=logout';
}

function loadDesign(){
	var designGUID = this.getAttribute('designGUID');
	
	HTTPRequest = null;

	handleHTTPRequest('designGUID='+designGUID, 'load');
	
	return;
}

function deleteDesign(){
	var designName = document.getElementById('designName');
	var post = '';
	
	if(designName.value == ''){
		return;
	}
	
	if(!confirm(text.deleteDesignA + ' "' + designName.value + '" ' + text.deleteDesignB)){
		return;
	}
	
	post = 'designGUID='+designName.getAttribute('designGUID');

	HTTPRequest = null;
	
	handleHTTPRequest(post, 'delete');
}

var loginForm = false;
openLoginForm = function(){
	if(!loginForm){
		loginForm = document.createElement('div');
		var titleBar = document.createElement('div');
		var main = document.createElement('div');
		var a = document.createElement('a');

		loginForm.id = 'loginForm';
		
		titleBar.className = 'titleBar';
		main.className = 'main';
		
		a.innerHTML = 'X';
		main.innerHTML = '<iframe src="/controllers/sessionValidator.cfc?method=handleSession" frameborder="0" scrolling="yes">Your browser doesn\'t support iframes, please download a different browser...</iframe>';
		
		a.onclick = closeLoginForm;
		
		titleBar.appendChild( a );
		loginForm.appendChild( titleBar );
		loginForm.appendChild( main );
		
		document.getElementsByTagName('body')[0].appendChild(loginForm);
	}
	
	loginForm.style.display = 'block';
	positionLoginForm();
	disableInputs();
}


closeLoginForm = function(){
	if( loginForm ) loginForm.style.display = 'none';
	enableInputs();	
}

positionLoginForm = function(){
	var loginButton = document.getElementById('loginButton');
	var screenWidth = document.body.clientWidth;
	var loginWidth = loginForm.offsetWidth;
	
	loginForm.style.left = (screenWidth - loginWidth) / 2 + 'px';
	loginForm.style.top = 290 + 'px';
}

doLogin = function(){
	closeLoginForm();
	rubberProfileCalculator.userIsLoggedIn = true;
	toggleButtons();
	handleHTTPRequest('', 'fillSavedDesignsSelectAfterLogin');

	updateSiteToolbar();

	if( oRingCalculator.userPreferredLanguage != oRingCalculator.preferredLanguage ){
		alert( text.preferredLanguageChanged );
	}
}

/*
	HANDEL INPUTS
*/
	function disableInputs(){
		var inputs = document.getElementById('application').getElementsByTagName('input');
		
		// INPUTS READONLY
		for(var i = 0; i < inputs.length; i++){
			if(inputs[i].parentNode.id != '')
				inputs[i].readOnly = true;
		}
	}
	
	function enableInputs(){
		var inputs = document.getElementById('application').getElementsByTagName('input');
		
		// INPUTS REMOVE READONLY
		for(var i = 0; i < inputs.length; i++){
			if(inputs[i].parentNode.id != '')
				inputs[i].readOnly = false;
		}
	}
/*
	// HANDLE INPUTS
*/


// HANDLE OFFER REQUEST, CHECK IF THE NEEDED DATA IS PRESENT
var designName;
var address;
var postalCode;
var locality;

function handleOfferRequest(){
	
	var material = document.getElementById('material');
	var meters = document.getElementById('meters');
	var surface = document.getElementById('surface');
	var offerName = '';
	var errorMessage = '';
	HTTPRequest = null;
	
	if ((isNaN(material.value)) || (material.value <= 0)) 
		errorMessage += text.materialError + '\n';
	if ((isNaN(meters.value)) || (meters.value <= 0)) 
		errorMessage += text.metersError + '\n';
	if ((isNaN(surface.value)) || (surface.value <= 0)) 
		errorMessage += text.surfaceError;
	
	if (errorMessage.length > 0) {
		alert(errorMessage);
		return false;
	}
	
	//users who are logged in are directly forwarded
	if (rubberProfileCalculator.userIsLoggedIn) {
		handleHTTPRequest('material=' + material.value + '&meters=' + meters.value + '&surface=' + surface.value, 'handleMyDetails');
	} else {
		/*
		 * Save the variables in the form and show the popup
		 */		
		document.getElementById('requestOfferWrapper').style.display = 'block';
	}
}

function handleRequestOfferLoggedOut(){
	var material = document.getElementById('material');
	var meters = document.getElementById('meters');
	var surface = document.getElementById('surface');
	var companyname = document.getElementById('companyname');
	var firstname = document.getElementById('firstname');
	var lastname = document.getElementById('lastname');
	var streetname = document.getElementById('streetname');
	var housenumber = document.getElementById('housenumber');
	var postalcode = document.getElementById('postalcode');
	var locality = document.getElementById('locality');
	var emailaddress = document.getElementById('emailaddress');
	var phonenumber = document.getElementById('phonenumber');
	var male = document.getElementById('male');
	var female = document.getElementById('female');
	var offerName = '';
	var errorMessage = '';
	var gender = '';
	HTTPRequest = null;
	
	if ((isNaN(material.value)) || (material.value <= 0)) 
		errorMessage += text.materialError + '\n';
	if ((isNaN(meters.value)) || (meters.value <= 0)) 
		errorMessage += text.metersError + '\n';
	if ((isNaN(surface.value)) || (surface.value <= 0)) 
		errorMessage += text.surfaceError;
	if ( companyname.value == '' ){
		errorMessage += text.companynameError + '\n';
	}
	if ( firstname.value == '' ){
		errorMessage += text.firstnameError + '\n';
	}
	if ( lastname.value == '' ){
		errorMessage += text.lastNameError + '\n';
	}
	if ( streetname.value == '' ){
		errorMessage += text.streetnameError + '\n';
	}
	if ( housenumber.value == '' ){
		errorMessage += text.housenumberError + '\n';
	}
	if ( postalcode.value == '' ){
		errorMessage += text.postalCodeError + '\n';
	}
	if ( locality.value == '' ){
		errorMessage += text.localityError + '\n';
	}
	if ( emailaddress.value == '' ){
		errorMessage += text.emailaddressError + '\n';
	}
	if ( phonenumber.value == '' ){
		errorMessage += text.phonenumberError + '\n';
	}
	if( !male.checked && !female.checked){
		errorMessage += text.genderError + '\n';
	}
	
	if( male.checked){
		gender = 'male';
	}
	if( female.checked ){
		gender = 'female';
	}
	
	if (errorMessage.length > 0) {
		alert(errorMessage);
		return false;
	}
	
	handleHTTPRequest('material=' + material.value
					 + '&meters=' + meters.value
					 + '&surface=' + surface.value
					 + '&companyname=' + companyname.value
					 + '&firstname=' + firstname.value
					 + '&lastname=' + lastname.value
					 + '&streetname=' + streetname.value
					 + '&housenumber=' + housenumber.value
					 + '&postalcode=' + postalcode.value
					 + '&locality=' + locality.value
					 + '&emailaddress=' + emailaddress.value
					 + '&phonenumber=' + phonenumber.value
					 + '&gender=' + gender
					 , 'requestOffer');
}

// CHECK DESIGNNAME FOR EXISTENS IF NOT GENERATE A NAME
function handleSaveOfferRequest(){
	var designName = document.getElementById('designName').value;
	var currentTime = new Date();
	
	HTTPRequest = null;
	
	if(designName == ''){
		var date = ("" + currentTime.getDate());
		var month = ("" + (currentTime.getMonth()+1));
		var year = ("" + currentTime.getFullYear());
		var hours = ("" + currentTime.getHours());
		var minutes = ("" + currentTime.getMinutes());
		var seconds = ("" + currentTime.getSeconds());
		
		if(date.length == 1) date = '0' + date;
		if(month.length == 1) month = '0' + month;
		if(hours.length == 1) hours = '0' + hours;
		if(minutes.length == 1) minutes = '0' + minutes;
		if(seconds.length == 1) seconds = '0' + seconds;
		
		offerName = date+month+year+hours+minutes+seconds;
		
		if (rubberProfileCalculator.userIsLoggedIn) {
			var designName = prompt(text.saveOfferRequestError, offerName);
		} else {
			designName = offerName;
		}
	}
	
	if(designName){
		document.getElementById('designName').value = designName;
		saveDesign();
	}
}

// GET ALL DATA THAT IS CALCULATED AND POST IT TO THE CONTROLLER
function saveDesign(){
	var post = '';
	var lengthA;
	var lengthB;
	var lengthC;
	var lengthD;
	var lengthE;
	var lengthF; 
	var painting;
	var x;
	var y;
	
	if(isNaN(shape.getLengthA())){
		lengthA = parseFloat(0);
	}else{
		lengthA = shape.getLengthA();
	}
	
	if(isNaN(shape.getLengthB())){
		lengthB = parseFloat(0);
	}else{
		lengthB = shape.getLengthB();
	}
	
	if(isNaN(shape.getLengthC())){
		lengthC = parseFloat(0);
	}else{
		lengthC = shape.getLengthC();
	}
	
	if(isNaN(shape.getLengthD())){
		lengthD = parseFloat(0);
	}else{
		lengthD = shape.getLengthD();
	}
	
	if(isNaN(shape.getLengthE())){
		lengthE = parseFloat(0);
	}else{
		lengthE = shape.getLengthE();
	}
	
	if(isNaN(shape.getLengthF())){
		lengthF = parseFloat(0);
	}else{
		lengthF = shape.getLengthF();
	}
	
	if(shape.getShape() == 'free'){
		painting = getMovieName('flashapp').getPainting();
		x = getMovieName('flashapp').getX();
		y = getMovieName('flashapp').getY();
	}else{
		painting = '';
		x = parseFloat(0);
		y = parseFloat(0);
	}
	
	post = 'designName='+encodeURIComponent(document.getElementById('designName').value)+'&';
	post += 'material='+document.getElementById('material').value+'&';
	post += 'meters='+document.getElementById('meters').value+'&';
	post += 'shape='+shape.getShape()+'&';
	post += 'surface='+document.getElementById('surface').value+'&';
	post += 'lengthA='+lengthA+'&';
	post += 'lengthB='+lengthB+'&';
	post += 'lengthC='+lengthC+'&';
	post += 'lengthD='+lengthD+'&';
	post += 'lengthE='+lengthE+'&';
	post += 'lengthF='+lengthF+'&';
	post += 'painting='+painting+'&';
	post += 'x='+x+'&';
	post += 'y='+y;
	
	HTTPRequest = null;
	
	/*
	 * For users not logged in we got a different method
	 */
	if (rubberProfileCalculator.userIsLoggedIn) {
		handleHTTPRequest(post, 'save');
	}
	else {
		handleHTTPRequest(post, 'saveNotLoggedIn');
	} 
}

/*
	arguments.a = applicationGUID
*/
function handleMyDetails(a){
	var myDetails = '';
	
	myDetails = document.createElement('div');
	myDetails.id = 'myDetails';
	myDetails.innerHTML = '<iframe src="https://my.eriksgroup.com/myDetails/?a=' + a + '" allowtransparency="true" frameborder="0"></iframe>';//localhost/usermanagement

	document.getElementsByTagName('body')[0].appendChild(myDetails);
}



function resetCalculator(){

	HTTPRequest = null;
	
	clearTimeOut();

	handleHTTPRequest('', 'reset');
}
/*
	// APPTOOLBAR
*/

/*
	HTTP REQUEST
*/
if (!window.XMLHttpRequest) {
	window.XMLHttpRequest = function() {
		var types = [
			'Microsoft.XMLHTTP',
			'MSXML2.XMLHTTP.5.0',
			'MSXML2.XMLHTTP.4.0',
			'MSXML2.XMLHTTP.3.0',
			'MSXML2.XMLHTTP'
		];
		
		for (var i = 0; i < types.length; i++) {
			try{
				return new ActiveXObject(types[i]);
			} catch(e) {}
		}
	
		return false; // XMLHttpRequest not supported
	}
}	
/*
	// HTTP REQUEST
*/

automaticLoginDetection = function(){
	var body = document.getElementsByTagName('body')[0];
	var automaticDetectionLogin = document.createElement('div');
	automaticDetectionLogin.style.display = 'none';
	automaticDetectionLogin.innerHTML = '<iframe src="/controllers/sessionValidator.cfc?method=handleSession" frameborder="0" scrolling="yes">Your browser doesn\'t support iframes, please download a different browser...</iframe>';
	
	
	setTimeout( function(){
		body.appendChild( automaticDetectionLogin );
		setTimeout( function(){ automaticDetectionLogin.parentNode.removeChild( automaticDetectionLogin );}, 5000);
	}, 100);
}

