/**
*	PayPal clientside form validator/submitter.
*	Version 0.1 (Beta)
*
*	Maniaked by:
*		Umkus [ crystality@mail.ru ]
*
*	Exclusively for:
*		GuessWho design band [ www.guesswho.com.ua ]
*/

/**
*	Returns the element with id
*	@param	string id
* 	@return object
*/
function get(id)
{
	return document.getElementById(id);
}

/**
*	Sets error for the field.
*	Makes a field class="error" also  adds a span
*	class="'fieldname'_error_text" with the error text
*	@param	string	fieldName
*	@param	string error
* 	@return boolean
*/
function setError(fieldName, error)
{
	//creating the span element
	var span = document.createElement('span');
	//setting it up
	span.innerHTML = error;
	span.className = 'error';
	span.id = fieldName+'_error_text';

	var br = document.createElement('br');
	br.id = fieldName+'_error_br';

	//injecting
	get(fieldName).parentNode.appendChild(br);
	get(fieldName).parentNode.appendChild(span);

	//setting field error class
	get(fieldName).className = 'error';

	return true;
}

/**
*	Sets title
*	@param	string string
* 	@return boolean
*/
function setTitle(string)
{
	get('pp_title').innerHTML = string;
	return true;
}

/**
*	Sets up PayPal hidden fields values needed to be filled as well as
*	project specific values
* 	@return	boolean
*/
function populatePPFields()
{
	//setting up the return address
	get('return').value = 'http://'+location.host+location.pathname + '?action=success';

	//setting up the address to use in case when the transaction is canceled
	get('cancel').value = 'http://'+location.host+location.pathname + '?action=cancel';

	//Resetting the custom field
	get('custom').value = '';

	var customer = '\nCustomer: ' + get('name').value;

	//Set up item name
	get('item_name').value = get('amount').options[get('amount').selectedIndex].text;

	//Set up custom field
	var suite = '\n' + get('suite').options[get('suite').selectedIndex].value;
	var suiteText = '\nSuite: '+get('suite').options[get('suite').selectedIndex].text;

	//Set up the additional services
	var checks = getCheckboxes();

	//dates
	var dates = getDates();

	//Set up the additional information
	var extra = getAdditionalInfo();

	var city = '\nCity: ' + get('city').value;

	var country = '\nCountry: ' + get('country').value;

	var phone = '\nPhone: ' + get('phone').value;

	get('custom').value = customer + suite + checks + dates + city + country + phone + extra;

	return customer + suiteText + dates + city + country + phone + extra;
}

/**
*	Sets up "Additional services" checkbox ids which.
*	Those will be converted back to string values on the server side. It's a
*	paypal field bandwidth issue.
*	"Custom" paypal field allows only 1 kb of info so we're leaving more space
*	for the "Additional Info" field by converting fulltext checkboxes values to
*	their ids.
* 	@return boolean
*/
function getCheckboxes()
{
	var num = 1;
	var content = '<';

	//Walking each checkbox
	while(get('c'+num) != null && num < 10)
	{
		//Adding it to the stack if it is selected
		if(get('c'+num).checked)
		{
			content = content + num + ',';
		}

		num++;
	}

	//Setting up services if any
	if(content.length > 0)
	{
		content = get('custom').value + content + '>';
	}
	else
	{
		content = '';
	}

	return content;
}

function getDates()
{
	return '\nCheck-in: ' + get('checkin').value + '\nCheck-out: ' + get('checkin').value;
}

/**
*	Clears previous error -- removes field class and span class="error" if any.
*	@param	string	fieldName
* 	@return boolean
*/
function clearError(fieldName)
{
	//clear error class
	get(fieldName).className = null;

	var container = get(fieldName).parentNode;

	//span elemnt to be deleted
	var victim = get(fieldName+'_error_text');

	if(victim != null)
	{
		container.removeChild(victim);
	}

	var victim = get(fieldName+'_error_br');

	if(victim != null)
	{
		container.removeChild(victim);
	}

	return true;
}

/**
*	Launches all needed fields validation and returns true if the form is valid or false otherwise
* 	@return boolean
*/
function validateForm()
{
	//These fields are required
	var fields = ['name','country','phone','mail'/*,'checkin','checkout'*/];

	//errors flag
	var errors = false;

	//Validate required fileds
	for( var key in fields)
	{
		if(typeof(fields[key]) == 'string')
		{
			if(!validateField(fields[key]))
			{
				errors = true;
			}
		}
	}

	//There were errors! Handle them and return false to cancel form submittion
	if(errors)
	{
		setTitle('There were errors in the form. Please correct them and try again');
		window.location.href = '#pp_title';
		return false;
	}
	//We're good - set up title and submit the form
	else
	{
		setTitle('Processing... please wait.');
		window.location.href = '#pp_title';
		//disableSubmit();

		//populatePPFields();

		/*
		console.log('delay...');
		var info = (function(){alert(123)}).delay(2000);
		console.log('end.');
		*/

		/*
		var url = 'http://renaissancesuitesodessa.com/reservations/tell.php';
		var res = false;
		new Ajax(url, {
		method: 'post',
		data: 'content='+info
		}).request();
		*/

		return true;
	}
}

/**
*	Validates a field and returns true if field is valid, otherwise -- false
*	@param string fieldName
* 	@return boolean
*/
function validateField(fieldName)
{
	//Clearing the field errors if any beforr we start
	clearError(fieldName);

	var patterns = [];
	var errors = [];

	//PCRE patterns of the specific fields
	patterns['phone'] = /(^[0-9 \-\(\)+]*$)/;
	patterns['mail'] = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	//patterns['checkin'] = patterns['checkout'] = /^\d{4}\-\d{1,2}\-\d{1,2}$/;

	patterns['generic'] = /.*/;

	//Errors
	errors['phone'] = 'Phone number is invalid';
	errors['mail'] = 'Mail address is invalid';
	//errors['checkin'] = errors['checkout'] = 'Date is invalid';
	errors['dateChrono'] = 'You can\'t check-out before checking-in';
	errors['required'] = 'This field is required';

	var patern = '';

	//Which pattern do we need for this field?
	if(typeof(patterns[fieldName]) == 'undefined')
	{
		pattern = patterns['generic'];
	}
	else
	{
		pattern = patterns[fieldName];
	}

	var content = get(fieldName).value;

	//No data entered :(
	if(content.length == 0)
	{
		setError(fieldName, errors['required']);
		return false;
	}

	//Didn't qualified against pattern
	if(!pattern.test(content))
	{
		setError(fieldName, errors[fieldName]);
		return false;
	}

	//Standart checks like empty field or invalid values passed. Now
	//validating dates. They need special care and have multiple error types
	//Like invalid date values and wrong chronological order
	if(fieldName == "checkin" || fieldName == "checkout")
	{
		var brother = "";

		if(fieldName == "checkin")
		{
			brother = "checkout"
		}
		else
		{
			brother = "checkin"
		}

		clearError(brother);
		if(!pattern.test(get(brother).value))
		{
			setError(brother, errors[brother]);
			return true;
		}

		//Is it a valid date?
		if(validateDate(fieldName))
		{
			//Pass this one. Other field has been left empty
			if(get(brother).value == '')
			{
				return true;
			}
			else
			{
				date1 = get("checkin").value;

				var y = date1.split("-")[0];
				var m = date1.split("-")[1];
				var d = date1.split("-")[2];

				if(m.length == 1)
				{
					m = '0' + m;
				}

				if(d.length == 1)
				{
					d = '0' + d;
				}

				date1 = y + '' + m + '' + d;


				date2 = get("checkout").value;

				var y = date2.split("-")[0];
				var m = date2.split("-")[1];
				var d = date2.split("-")[2];

				if(m.length == 1)
				{
					m = '0' + m;
				}

				if(d.length == 1)
				{
					d = '0' + d;
				}

				date2 = y + '' + m + '' + d;

				//Check if dates are chronologically valid
				if(parseInt(date1) > parseInt(date2) && fieldName == 'checkout')
				{
					setError(fieldName, errors['dateChrono']);
					return false;
				}
			}
		}
		else
		{
			setError(fieldName, errors[fieldName]);
			return false;
		}
	}

	//Field is valid
	return true;
}


function validateDate(input)
{
	input = get(input);

	//Detailed check for valid date ranges
	var yearfield = input.value.split("-")[0];
	var monthfield = input.value.split("-")[1];
	var dayfield = input.value.split("-")[2];

	var dayobj = new Date(yearfield, monthfield-1, dayfield);

	if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
	{
		return false;
	}
	else
	{
		return true;
	}
}

/**
*	Disables submit button to ensure the form isn't sent twice(or more)
* 	@return		boolean
*/
function disableSubmit()
{
	get('registerFormSubmit').disabled = true;
	return true;
}

/**
*	Enables submit button
* 	@return		boolean
*/
function enableSubmit()
{
	get('registerFormSubmit').disabled = false;
	return true;
}

//This enables submit button because it is disabled from the start in case when
enableSubmit();

//Form submit hook which starts all the fun
get('register').onsubmit = function (){return validateForm();}

//The form has just returned from the paypal site and was successfull
if(location.search == '?action=success')
{
	setTitle("Thank you for your order!");
}

//The form has just returned from the paypal site and the purchase was canceled
if(location.search == '?action=cancel')
{
	setTitle("The transaction was canceled");
}

/**
*	Adds the "Additional info" textarea value to the "custom" paypal hidden field
* 	@return 	boolean
*/
function getAdditionalInfo()
{
	if(get('extra').value.length > 0)
	{
		return '\nExtra info:' + get('extra').value.replace(/"/,'\\"');
	}
	else
	{
		return '';
	}
}

/*Kawai smiley --> ^_^ */