function checkAmount(f) {
	if(parseInt(f.minpayment.value) <= f.amount.value && f.amount.value <= parseInt(f.approx_price.value)) {
		$('#payment_notice_p').remove();
		return true;
	} else {
		$('#payment_notice_p').remove();
		$('#payment_notice').append('<div class="ajax_notice ajax_notice_fail" id="payment_notice_p"><strong>Please input correctly data to amount payment.</strong></div>');
		return false;
	}
}

function validate_email(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

	if(reg.test(email) == false) {
		return 1;
	} else {
		return 0;
	}

}

function isInt(x) {
	var y=parseInt(x);
	if (isNaN(y)) return false;
		return x==y && x.toString()==y.toString();
}
 
function unixtimetodate(date_) {
	var theDate = new Date(date_ * 1000);
		dateString = theDate.toDateString();
	return dateString;
};

function build_inquiry()
{
	var f = $('#step1')[0];
	var o = {
		"group" : {
			"adults" : parseInt(f.adults.value),
			"ch3" : parseInt(f.ch3.value),
			"ch8" : parseInt(f.ch8.value),
			"ch12" : parseInt(f.ch12.value),
			"ch16" : parseInt(f.ch16.value)
		},
		"month" : parseInt(f.month.value),
		"year" : parseInt(f.year.value)
	};
	var s = JSON.stringify(o);
	//alert(s);
	return s;
};


function checkOrderStatus(f) {
	var proxy_url = 'http://'+document.domain + '/wp-content/themes/amphibia/proxy.php';

	$.ajax({
		url: proxy_url,
		dataType : "json",
		type : "POST",
		data : {type : "order_status", request : build_order_status_request()},
		success: function(data, textStatus){ 
			$('#client_data').show();
			$('#status_notice').remove();
			var o_contacts_label    = ["Company", "First name", "Middle name", "Last name", "Email address", "Address", "City", "State", "Post Code", "Country", "Phone", "Fax"],
				o_contacts_data     = [data.o_contact.company, data.o_contact.fname, data.o_contact.mname, data.o_contact.lname, data.o_contact.email, data.o_contact.address, data.o_contact.city, data.o_contact.state, data.o_contact.pcode, data.o_contact.country, data.o_contact.phone, data.o_contact.fax],
				o_group_label       = ["Adults", "Children under 3", "Children under 8", "Children under 12", "Children under 16", "Month", "Year"];
				o_group_data        = [data.o_inquiry.group.adults, data.o_inquiry.group.ch3, data.o_inquiry.group.ch8, data.o_inquiry.group.ch12, data.o_inquiry.group.ch16, data.o_inquiry.month, data.o_inquiry.year],
				o_tour_label        = ["Date start", "Date end"],
				o_tour_data         = [data.o_tour.dstart, data.o_tour.dend];



			$('#client_data_c').remove();
			$('#client_data').append('<h3 id="client_data_c">Contacts Data</h3>');
			for (i = 0; i < 12; i++) {
				$('#client_data_c' + i).remove();
				if (o_contacts_data[i]) {
					$('#client_data').append('\
						<p id="client_data_c' + i + '" class="form-item form-item-condenced">\
							<span class="form-item-label">\
								<label>' + o_contacts_label[i] + '</label>\
							</span>\
							<label>'+ o_contacts_data[i] + '</label>\
						</p>\
					');
				}
			}

			$('#client_data_t').remove();
			$('#client_data').append('<h3 id="client_data_t">Tour group information</h3>');
			for (i = 0; i < 7; i++) {
				$('#client_data_t' + i).remove();
				if (o_group_data[i]) {
					$('#client_data').append('\
						<p id="client_data_t' + i + '" class="form-item form-item-condenced">\
							<span class="form-item-label">\
								<label>' + o_group_label[i] + '</label>\
							</span>\
							<label>' + o_group_data[i] + '</label>\
						</p>\
					');
				}
			}

			$('#client_data_i').remove();
			$('#client_data').append('<h3 id="client_data_i">Tour information</h3>');
			for (i = 0; i < 2; i++) {
				$('#client_data_i' + i).remove();
				$('#client_data').append('\
					<p id="client_data_i' + i + '" class="form-item form-item-condenced">\
						<span class="form-item-label">\
							<label>' + o_tour_label[i] + '</label>\
						</span>\
						<label>' + o_tour_data[i] + '</label>\
					</p>\
				');
			}
			
			$('#client_data_d').remove();
			$('#client_data').append('\
				<div id="client_data_d">\
					<p class="form-item form-item-condenced">\
						<span class="form-item-label">\
							<label>Tour Name</label>\
						</span>\
						<label><a target="_blank" href = "' + data.o_tour.url + '">' + data.o_tour.kind + '</a></label>\
					</p>\
					<p class="form-item form-item-condenced">\
						<span class="form-item-label">\
							<label>Tour price</label>\
						</span>\
						<label>' + data.o_price / 100 +'$</label>\
					</p>\
				</div>\
			');

			$('#client_data_p').remove();
			$('#client_data_payments').remove();
			$('#client_data').append('<h3 id="client_data_p">Payments</h3>');
			$('#client_data').append('\
				<table id="client_data_payments" class="payments-list">\
					<thead>\
						<th>Method</th>\
						<th class="payments-list-date">Date</th>\
						<th class="payments-list-amount">Payed amount, $</th>\
					</thead>\
					<tbody></tbody>\
				</table>\
			');
			var tbody = $('#client_data_payments tbody')

			var sum_payments = 0;
			for (i = 0; i < (data.o_payments.length); i++) {
				sum_payments += parseInt(data.o_payments[i].amount) / 100;
	
				$('#client_data_p' + i).remove();
				tbody.append('<tr id="client_data_p' + i + '"></tr>');
				var tr = $('#client_data_p' + i);
				
				tr.append('<td>' + data.o_payments[i].meth +  '</td>');
				tr.append('<td class="payments-list-date">' + data.o_payments[i].date +  '</td>');
				tr.append('<td class="payments-list-amount">' + data.o_payments[i].amount / 100 +  '</td>');
			}
			$('#client_paypal_notice').remove();
			var total_price = 0;
			total_price = (data.o_price / 100) - sum_payments;

			if (total_price != 0) {

				var s_url = 'http://'+document.domain+'/online_booking?email=' + f.email.value + '&code=' + data.o_code + '#status';
				var f_url = 'http://'+document.domain+'/online_booking#failed';

				$('#client_paypal_form').show();
				$('#client_paypal').append('<input type="hidden" name="item_number" value="' + data.o_code + '" />\
					<input type="hidden" name="return" value="' + s_url + '">');

				$('#client_paypal').append('<input type="hidden" name="cancel_return" value="' + f_url + '" />\
					<input type="hidden" name="notify_url" value="http://62.149.9.24/amphibiya.cgi" />\
					<input type="hidden" name="custom"  value="' + data.o_id + '" />\
				');
				$('#client_paypal').append('<input type = "hidden" name = "minpayment" value = "' + data.o_minpayment / 100 + '">\
					<input type="hidden" name="approx_price" value="' + total_price + '">\
				');
				
				$('#client_paypal_s').append('<div id="client_paypal_notice"><strong>Please note</strong> that your payment can not be less than the minimal payment <strong>$' + data.o_minpayment / 100 + '</strong> and can not exceed the total price <strong>$' + total_price + ' </strong> of the tour.</div>');
			}
		},
		error: function(data, textStatus) { 
			$('#client_data').hide();
			$('#client_paypal_form').hide();
			$('#status_notice').remove();
			$('#status_data').append('<div id = "status_notice" align = "center"><strong>You entered the wrong e-mail or ordering code, please enter the correct data!</strong></div>');
		}
	});

};

function build_order_status_request() {

	var f = $('#status_data')[0];
	//alert("build_order_status_request");

	var o = {
		"status_email" : "" + f.email.value + "",
		"status_code" : "" + f.code.value + ""
	};
	var s = JSON.stringify(o);
	//alert(s);
	return s;
};

function updateOwnQuestionBox(value) { 

	var chooseQuestionValue = "United States";
	var ownQuestionValue = "United States";
	var ownQuestionName =  "showstate";

	var ownQuestionField = document.forms['order'].elements[ownQuestionName];

	if (value != "United States") { 
		ownQuestionField.style.display = 'none';  
		ownQuestionField.focus();
		$('#state_show').hide();
	} else { 
		ownQuestionField.style.display = 'block'; 

		$('#state_show').show();
		var lastIndex = "1";
		var value = "state";
		var label = "United States";

		document.forms['order'].questions.options[lastIndex] = new Option(label, value);
	}  
}


function selectTour(f) {

	$('#step3').show();

	$('#hidden_post').append('<input type = "hidden" name = "id" value = "'+ f.id.value + '">\
	<input type = "hidden" name = "tid" value = "'+ f.tid.value + '">\
	<input type = "hidden" name = "adults" value = "'+ f.adults.value + '">\
	<input type = "hidden" name = "ch3" value = "'+ f.ch3.value + '">\
	<input type = "hidden" name = "ch8" value = "'+ f.ch8.value + '">\
	<input type = "hidden" name = "ch12" value = "'+ f.ch12.value + '">\
	<input type = "hidden" name = "ch16" value = "'+ f.ch16.value + '">\
	<input type = "hidden" name = "month" value = "'+ f.month.value + '">\
	<input type = "hidden" name = "year" value = "'+ f.year.value + '">\
	');

	$('#hidden_post_client').append('<input type = "hidden" name = "id" value = "'+ f.id.value + '">\
	<input type = "hidden" name = "tid" value = "'+ f.tid.value + '">\
	<input type = "hidden" name = "adults" value = "'+ f.adults.value + '">\
	<input type = "hidden" name = "ch3" value = "'+ f.ch3.value + '">\
	<input type = "hidden" name = "ch8" value = "'+ f.ch8.value + '">\
	<input type = "hidden" name = "ch12" value = "'+ f.ch12.value + '">\
	<input type = "hidden" name = "ch16" value = "'+ f.ch16.value + '">\
	<input type = "hidden" name = "month" value = "'+ f.month.value + '">\
	<input type = "hidden" name = "year" value = "'+ f.year.value + '">\
	');

	$('#step2').hide();
};

function gotoPayPal() {

	$('#step3').hide();
	$('#step4').show();
}

function build_order()
{
	//alert("bild order");

	var f = $('#order')[0];

	var o = {
		"inquiry_id": parseInt(f.id.value),
		"contact" : {
				"company" : "" + f.company.value + "",
				"fname" : "" + f.fname.value + "",
				"mname" : "" + f.mname.value + "",
				"lname" : "" + f.lname.value + "",
				"email" : "" + f.email.value + "",
				"password" : "" + f.password.value + "",
				"address" : "" + f.address.value + "",
				"city" : "" + f.city.value + "",
				"state" : "" + f.state.value + "",
				"pcode" : "" + f.pcode.value + "",
				"country" : "" + f.country.value + "",
				"phone" : "" + f.phone.value + "",
				"fax" : "" + f.fax.value + ""
		},
		"tour_id": parseInt(f.tid.value)
	};
	var s = JSON.stringify(o);


	//alert(s);
	return s;

};

function build_order_client()
{
	//alert("bild order client");

	var f = $('#orderClient')[0];

	var o = {
		"inquiry_id": parseInt(f.id.value),
		"contact" : {
				"company" : "" + f.company.value + "",
				"fname" : "" + f.fname.value + "",
				"mname" : "" + f.mname.value + "",
				"lname" : "" + f.lname.value + "",
				"email" : "" + f.email.value + "",
				"password" : "" + f.password.value + "",
				"address" : "" + f.address.value + "",
				"city" : "" + f.city.value + "",
				"state" : "" + f.state.value + "",
				"pcode" : "" + f.pcode.value + "",
				"country" : "" + f.country.value + "",
				"phone" : "" + f.phone.value + "",
				"fax" : "" + f.fax.value + ""
		},
		"tour_id": parseInt(f.tid.value)
	};
	var s = JSON.stringify(o);

	//alert(s);
	return s;

};

function makeOrderClient(f)
{
	//alert("makeOrderClient");

	$('#step3').hide();

	var proxy_url = 'http://'+document.domain + '/wp-content/themes/amphibia/proxy.php';
	//alert(proxy_url);
	//alert(s_url);
	$.ajax({
		url: proxy_url,
		dataType : "json",
		type : "POST",
		data : {type : "create_order", request : build_order_client()},
		success: function(data, textStatus){

			var s_url = 'http://'+document.domain+'/online_booking?email=' + f.email.value + '&code=' + data.order_code + '#status';
			var f_url = 'http://'+document.domain+'/online_booking#failed';


			$('#step4').show(); 
			$('#hidden_post_paypal_s').append('\
				<input type="hidden" name="custom" value="' + data.order_id + '" />\
				<input type="hidden" name="item_number" value="' + data.order_code + '" />\
				<input type="hidden" name="notify_url" value="http://62.149.9.24/amphibiya.cgi" />\
				<input type="hidden" name="cancel_return" value="' + f_url + '" />\
				<input type="hidden" name="return" value="'+s_url+'">');
			$('#hidden_post_paypal_s').append('<h2>Order data</h2>\
			<p class="form-item">\
				<span class="form-item-label">\
					<label>Your order code</label>\
				</span>\
				<strong>' + data.order_code + '</strong></p>\
			<p class="form-item">\
				<span class="form-item-label">\
					<label>Your email</label>\
				</span>\
				<strong>' + f.email.value + '</strong></p>');

			price = data.order_price / 100;
			minpayment = data.order_minpayment / 100;

			$('#hidden_post_paypal_s').append('<input type = "hidden" name = "minpayment" value = "' + minpayment	 + '">\
					<input type = "hidden" name = "approx_price" value = "' + price + '">\
			');

			$('#step4').append('Your payment can not be less than the minimal payment <strong>$' + minpayment + '</strong> and can not exceed the total price <strong>$' + price + '</strong> of the tour.');

		},
		error: function(data, textStatus){
			$('#step3').show();
			$('#r_notice').remove();
			$('#rightside').append('<div id="r_notice"><strong>You entered the wrong e-mail or password, please enter the correct data!</strong></div>');
		}
	});
}


function makeOrder(f)
{
	//alert("make order");

		var empty_fields = 0;
		var o_contacts_label = new Array("First name", 
							"Middle name", 
							"Last name", 
							"Email address", 
							"Password", 
							"Address", 
							"City", 
							"State", 
							"Post Code", 
							"Country", 
							"Phone");

		var o_contacts_fields = new Array(f.fname.value, 
							f.mname.value, 
							f.lname.value, 
							f.email.value, 
							f.password.value, 
							f.address.value, 
							f.city.value, 
							f.state.value, 
							f.pcode.value, 
							f.country.value, 
							f.phone.value);

		for (i = 0; i < (o_contacts_fields.length); i++) {

			if (i == 3 && o_contacts_fields[3] != "") {
				var valid = validate_email(o_contacts_fields[3]);
				if (valid == 1) {
					empty_fields++;
					$('#contacts_not01').remove();
					$('#contact_notice').append('<div id = "contacts_not01">Field <span class="req">"Email address"</span> not validate</div>');
				} else {
					$('#contacts_not01').remove();
				}

			}

			if (o_contacts_fields[i] == "") {
				$('#contacts_not' + [i]).remove();
				$('#contact_notice').append('<div id = "contacts_not' + [i] + '">Field <span class="req">"' + o_contacts_label[i] + '"</span> can not be empty</div>');
				empty_fields++;
			} else {
				if(o_contacts_fields[i] != f.phone.value && o_contacts_fields[i] != f.fax.value && o_contacts_fields[i] != f.pcode.value && o_contacts_fields[i] != f.password.value) {
					if(isInt(o_contacts_fields[i])) {
						empty_fields++;
						$('#contacts_not' + [i]).remove();
						$('#contact_notice').append('<div id = "contacts_not' + [i] + '">Field <span class="req">"' + o_contacts_label[i] + '"</span> can not be a number</div>');
					} else {
						$('#contacts_not' + [i]).remove();
					}
				}
			}
		}

		if(empty_fields == 0) {
			var proxy_url = 'http://'+document.domain+'/wp-content/themes/amphibia/proxy.php';
			
			$.post(proxy_url,
				{type : "create_order", request : build_order()},
				function(data) {
				//alert(JSON.stringify(data));
				var s_url = 'http://'+document.domain+'/online_booking?email=' + f.email.value + '&code=' + data.order_code + '#status';
				var f_url = 'http://'+document.domain+'/online_booking#failed';
				//alert(s_url);
	
				$('#hidden_post_paypal_s').append('\
					<input type="hidden" name="custom" value="' + data.order_id + '" />\
					<input type="hidden" name="item_number" value="' + data.order_code + '" />\
					<input type="hidden" name="notify_url" value="http://62.149.9.24/amphibiya.cgi" />\
					<input type="hidden" name="cancel_return" value="' + f_url + '" />\
					<input type="hidden" name="return" value="' + s_url + '">');
				//$('#hidden_post_paypal_s').append('<h2>Attention!</h2> This code (<strong>' + data.order_code + '</strong>), along with your contact email (<strong>' + f.email.value + '</strong>) is key information to access the status of your order and payment forms!');

			$('#hidden_post_paypal_s').append('<h2>Order data</h2>\
			<p class="form-item">\
				<span class="form-item-label">\
					<label>Your order code</label>\
				</span>\
				<strong>' + data.order_code + '</strong></p>\
			<p class="form-item">\
				<span class="form-item-label">\
					<label>Your email</label>\
				</span>\
				<strong>' + f.email.value + '</strong></p>');

			price = data.order_price / 100;
			minpayment = data.order_minpayment / 100;

			$('#hidden_post_paypal_s').append('<input type = "hidden" name = "minpayment" value = "' + minpayment	 + '">\
					<input type = "hidden" name = "approx_price" value = "' + price + '">\
			');

			$('#step4').append('Your payment can not be less than the minimal payment <strong>$' + minpayment + '</strong> and can not exceed the total price <strong>$' + price + '</strong> of the tour.');
				},
				"json"
			);
			$('#step3').hide();
			$('#step4').show();

		}

		//$('#step3').hide();

};

function gup( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}


$(document).ready(function(){
	
	$('#status_data').append('<p class="form-item">\
				<span class="form-item-label">\
					<label for="email">E-mail</label>\
				</span>\
				<input type = "text" name = "email" value = "' + gup('email') + '">\
				<small class="form-item-note">Tour email address</small>\
			</p>\
			<p class="form-item">\
				<span class="form-item-label">\
					<label for="code">Code</label>\
				</span>\
					<input type = "text" name = "code" value = "' + gup('code') + '">\
				<small class="form-item-note">Code of tour order</small>\
			</p>\
			<p class="form-item form-item-action">\
				<input type="submit" name="submit" value="Check order status" class="input-button input-button-submit" />\
			</p>\
	');

	$('#step2').hide()
	$('#client_paypal_form').hide();
	$('#step3').hide();
	$('#step4').hide();

	/*$('#domain').append('<p>Document domain: <strong>' + document.domain + '</strong></p>');
	$('#domain').show();*/

	$('#step1 :submit').click(function(e){

		e.preventDefault();
		var proxy_url = 'http://'+document.domain + '/wp-content/themes/amphibia/proxy.php';

		$.post(proxy_url,
			{type : "inquiry", request : build_inquiry()},
			function(data) {
			//alert(JSON.stringify(data));
			
				if (data.tours.length == 0) {
					$("#tour_not").remove();
					$('#tour_notice').append('<strong class="ajax_notice ajax_notice_fail" id="tour_not">Tours not found! Please select other month of tour.</strong>');

					$('#step1').show();
				}
				if (data.tours.length != 0) {
					$("#tour_not").remove();
					for (i = 0; i < (data.tours.length); i++) {
						var item = data.tours[i],
							approx_price = item.approx_price / 100,
							minpayment = item.minpayment / 100;
			
						var f = $('#step1')[0];
						
						$('#step2').append('\
							<form name="tours' + item.tour.tid + '" onSubmit="selectTour(this); return false">\
								<input type="hidden" name="id" value="'+ data.id + '">\
								<input type="hidden" name="tid" value="'+ item.tour.tid + '">\
								<input type="hidden" name="adults" value="'+ f.adults.value + '">\
								<input type="hidden" name="ch3" value="'+ f.ch3.value + '">\
								<input type="hidden" name="ch8" value="'+ f.ch8.value + '">\
								<input type="hidden" name="ch12" value="'+ f.ch12.value + '">\
								<input type="hidden" name="ch16" value="'+ f.ch16.value + '">\
								<input type="hidden" name="month" value="'+ f.month.value + '">\
								<input type="hidden" name="year" value="'+ f.year.value + '">\
								<input type="hidden" name="minpayment" value="' + minpayment + '">\
								<input type="hidden" name="approx_price" value="' + approx_price + '">\
								<table class="order_list">\
									<tr>\
										<th><a target="_blank" href="'+ item.tour.url + '" title="">'+ item.tour.kind + '</a></th>\
									</tr>\
									<tr>\
										<td class="name">Tour starts</td>\
										<td class="data">' + item.tour.dstart + '</td>\
									</tr>\
									<tr>\
										<td class="name">Tour ends</td>\
										<td class="data">' + item.tour.dend + '</td>\
									</tr>\
									<tr>\
										<td class="name">Free seats</td>\
										<td class="data">' + item.loaded + '</td>\
									</tr>\
									<tr>\
										<td class="name">Minimal payment</td>\
										<td class="data">$' + minpayment + '</td>\
									</tr>\
									<tr>\
										<td class="name">Approximate price</td>\
										<td class="data">$' + approx_price + '</td>\
									</tr>\
									<tr>\
										<td colspan="2" class="submit">\
											<input type="submit" class="input-button input-button-submit" value="Order this tour" />\
										</td>\
									</tr>\
								</table>\
							</form>\
						');
					}

					$('#step1').hide();
					$('#step2').show();
				}
			},
			"json"
		);
	});
});
