//########################################
//## script copyright fusio.net         ##
//## developped for railtours<.>ie  ##
//## by remi [at] fusio<.>net           ##
//########################################
function openWindow(pageurl,winName,features)
{
	window.open(pageurl,winName,features);
}


// expand hidden fields 
function ShowLayer(ThisLayer) 
{ 
	document.getElementById(ThisLayer).style.display = 'block';
}
function HideLayer(ThisLayer) 
{ 
	document.getElementById(ThisLayer).style.display = 'none';
}

function ShowNextCat(spanID) 
{
	if (document.all) 
	{ // is IE
		eval("document.all."+spanID+".style.visibility='visible';");
	} else 
	{ // is NS? 
		eval("document.layers['"+spanID+"'].visibility='show';");
	}
}

function ShowTable(checkbox) 
{
	
	if (!checkbox.checked)
	{

		if (document.booking.ReturnFees.value !="")
		{
			ok = window.confirm("By closing this table, you will reset all the data entered for your return journey.");
			if(ok)
			{
			closetable = true;
			ResetReturnJourneyFields();
			CalculTtlFees()
			}
			else
			{
			document.booking.showreturn.checked = true;
			closetable = false
			}
		}
		else
		{
			closetable = true
		}
		if (closetable)
		{
			HideLayer('divt3')
		}
	}
	else
	{
		//Preselect the return dates
		PreselectdDate();
		ShowLayer('divt3')
	}
}


function OpenFcalendar(ThisForm)
{

	//get startday from drop boxes
	var fstartday = document.booking.fday.value;
	var fstartmonth = document.booking.fmonth.value;
	var fstartyear = document.booking.fyear.value;
	//alert(fstartday + " " + fstartmonth + " " + fstartyear)
	var dddate = fstartday + " " + fstartmonth + " " + fstartyear

	window.open("calendar.asp?fd=StartDate&dddate="+dddate, "calendar", "width=230,height=180")
}

function OpenDcalendar(ThisForm)
{

	//get startday from drop boxes
	var dstartday = document.booking.dday.value;
	var dstartmonth = document.booking.dmonth.value;
	var dstartyear = document.booking.dyear.value;
	//alert(fstartday + " " + fstartmonth + " " + fstartyear)
	var dddate = dstartday + " " + dstartmonth + " " + dstartyear

	window.open("calendar.asp?fd=dStartDate&dddate="+dddate, "calendar", "width=230,height=180")
}


function updatefdate()
{
	document.booking.StartDate.value =  document.booking.fday.value + " " + document.booking.fmonth.value + " " + document.booking.fyear.value;
	PreselectdDate();
	UpdateDepartFees();
}


function PreselectdDate()
	{
	//update only if the user has not started to fill up the return data
	//but update when the departure date has been moved forward
	var ThisDate = new Date(document.booking.StartDate.value);
	if (document.booking.dStartDate.value !="")
	{
		var ThisReturnDate = new Date(document.booking.dStartDate.value);
		var StartDateMovdeForward = CalcDiffDays(DateAdd(ThisDate,document.booking.days.value, 0, 0),ThisReturnDate)
		//alert(StartDateMovdeForward)
	}
	else
	{
		StartDateMovdeForward = 1
	}
	
	if (document.booking.ddays.value < 1 || StartDateMovdeForward < 0)
	{
		
		if (document.booking.days.value > 0){ThisDate = DateAdd(ThisDate,document.booking.days.value, 0, 0)}

		document.booking.dStartDate.value =  DateToStrg(ThisDate);
		document.booking.dday.selectedIndex = (ThisDate.getDate()-1);
		document.booking.dmonth.selectedIndex = ThisDate.getMonth();
		
		var Myyear =  ThisDate.getYear();

		for (i=0; i<= document.booking.dyear.length-1; i++)
		{
		if (document.booking.dyear[i].value == eval(Myyear) )
			{
			document.booking.dyear.selectedIndex = i
			break
			}
		}
		//update the return fees
		UpdateReturnFees()
	}
}

function updateddate()
{
	document.booking.dStartDate.value =  document.booking.dday.value + " " + document.booking.dmonth.value + " " + document.booking.dyear.value
	UpdateReturnFees()
}

// calcul fees
function UpdateDepartFees()
{
	CheckResetValue()

	if (document.booking.days.value > 0) //at least 1 night selected 
	{
		
		var TempFees = 0;
		//loop though the selected days
		for (i=1; i<=document.booking.days.value ; i++)
		{
				var winsumvalue = WinSum(GetMonthValue('d',i));
				TempFees += parseFloat(RoomFees[winsumvalue]);
		}
			
		
		//write the total fees
		if (TempFees > 0)
		{

			document.booking.DepartureFees.value = TempFees;
			ShowLayer('fieldTotal')
		}

		//Preselect the return dates
		PreselectdDate();

	} //end chk at least 1 night selected
	else
	{
		//nothing selected
		document.booking.DepartureFees.value = "";
	}

	//update total which appears near CC
	CalculTtlFees()
}


function UpdateReturnFees()
{
CheckResetValue()

	if (document.booking.ddays.value > 0) //at least 1 night selected 
	{
		
		var TempFees = 0;
		//loop though the selected days
		for (i=1; i<=document.booking.ddays.value ; i++)
		{
				var winsumvalue = WinSum(GetMonthValue('r',i));
				TempFees += parseFloat(RoomFees[winsumvalue]);
		}
			
		
		//write the total fees
		if (TempFees > 0)
		{

			document.booking.ReturnFees.value = TempFees;
			ShowLayer('dfieldTotal')
		}

		//Preselect the return dates
		PreselectdDate();

	} //end chk at least 1 night selected
	else
	{
		//nothing selected
		document.booking.ReturnFees.value = "";
	}

	//update total which appears near CC
	CalculTtlFees()

}


//GetRoomValue
function GetMonthValue(ThisCal,AddDay)
{
	if (ThisCal == 'd')
	{
		var adate = DateAdd(new Date(document.booking.StartDate.value), AddDay, 0, 0);

	}
	else
	{
		var adate = DateAdd(new Date(document.booking.dStartDate.value), AddDay, 0, 0);
	}

	month = adate.getMonth() 
	return month;
}


//check and reset values when needed
function CheckResetValue()
{
	
	if (document.booking.days.selectedIndex == 0)
	{
		document.getElementById('fieldTotal').style.display = 'none';
	}
	if (document.booking.dday.selectedIndex == 0 )
	{
		document.getElementById('dfieldTotal').style.display = 'none';
	}
	CalculTtlFees();
}

//reset return journey values only
function ResetReturnJourneyFields()
{
	document.booking.droomtype1Fee.value =""
	document.booking.droomtype1.selectedIndex = 0
	document.getElementById('dfield1').style.display = 'none';
	document.booking.droomtype2Fee.value =""
	document.booking.droomtype2.selectedIndex = 0
	document.getElementById('dfield2').style.display = 'none';
	document.booking.droomtype3Fee.value =""
	document.booking.droomtype3.selectedIndex = 0
	document.getElementById('dfield3').style.display = 'none';
	document.getElementById('dfieldTotal').style.display = 'none';
	document.booking.ReturnFees.value =""
	CalculTtlFees();
}

//calculate total fees
function CalculTtlFees()
{
	var TotalFee = 0;
	if (document.booking.DepartureFees.value >= 1)
	{
	TotalFee = TotalFee + parseFloat(document.booking.DepartureFees.value);
	}
	if (document.booking.ReturnFees.value >= 1)
	{
	TotalFee = TotalFee + parseFloat(document.booking.ReturnFees.value);
	}
	//set total
	document.booking.TotalFees.value  = TotalFee;
}



function validate_form(form_name)
{
	
	if (document.booking.TourCode.selectedIndex == 0)
	{
		alert("We're sorry, but you can not book an hotel with us before indicating the tour you've booked with us.")
		form_name.TourCode.focus();
		return false;
	}
	
	if (form_name.FirstName.value == "")
	{
		alert("What's your First Name !");
		form_name.FirstName.select();
		return false;
	}


	if (form_name.Address.value == "")
	{
		alert("What's your Address !");
		form_name.Address.focus();
		return false;
	}

	if (form_name.email.value != "")
	{
		
		var emailStr=form_name.email.value;
		var emailPat=/^(.+)@(.+)$/
		var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
		var validChars="\[^\\s" + specialChars + "\]"
		var quotedUser="(\"[^\"]*\")"
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
		var atom=validChars + '+'
		var word="(" + atom + "|" + quotedUser + ")"
		var word2 = "(" + validChars + "*|" + quotedUser + ")";
		var userPat=new RegExp("^" + word + "(\\." + word2 + ")*$")

		//var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
		var matchArray=emailStr.match(emailPat)
		if (matchArray==null) {
			alert("Invalid email address! (error1)")
			form_name.email.select();
			return false;
		}
		var user=matchArray[1]
		var domain=matchArray[2]
		if (user.match(userPat)==null) {
			alert("Invalid email address! (error2)")
			form_name.email.select();
			return false;
		}
		var IPArray=domain.match(ipDomainPat)
		if (IPArray!=null) {
			  for (var i=1;i<=4;i++) {
				if (IPArray[i]>255) {
					alert("Invalid email address! (error3)")
				form_name.email.select();
				return false;
				}
			}
			return true;
		}
		var domainArray=domain.match(domainPat)
		if (domainArray==null) {
			alert("Invalid email address! (error4)")
			form_name.email.select();
			return false;
		}
		var atomPat=new RegExp(atom,"g")
		var domArr=domain.match(atomPat)
		var len=domArr.length
		if (domArr[domArr.length-1].length<2 ||
			domArr[domArr.length-1].length>3) {
		   alert("Invalid email address! (error5)")
		   form_name.email.select();
		   return false;
		}
		if (len<2) {
		   alert("Invalid email address! Address Too Short!")
		   form_name.email.select();
		   return false;
		}
	}

	//validate Credit Card && Payments
	if (document.booking.CCardHolderName.value == "")
		{
		alert('What is the name printed on your Credit Card?');
		document.booking.CCardHolderName.select();
		return false;
		}

	if (document.booking.CCNumber.value == "") 
	{
		alert("Please enter a Card Number. \n Our form is secure!");
		form_name.CCNumber.focus();
		return false;
	}


	if (!isValidCreditCardNumber(document.booking.CCardType.value,document.booking.CCNumber.value))
	{
		return false;
	}

	if (isValidExpDate(document.booking.CCExpMM.value ,"20" + document.booking.CCExpYY.value) == false)
	{
		return false;
	}

	if (document.booking.CCSecurityCode.value == "")
	{
		alert("The security code is the last 3 digits of the number printed on the back of your Credit Card");
		document.booking.CCSecurityCode.focus();
		return false;
	}
	else
	{
		if (!allDigits(document.booking.CCSecurityCode.value ))
		{
			alert('Please enter only numbers (no dashes or spaces)');
			document.booking.CCSecurityCode.select();
			return false;
		}
	}

	// T & C
	if (form_name.TC.checked==false)
	{
		alert("You must agree to the terms and conditions of the site to continue!");
		document.booking.TC.select();
		return false;
	}

	//a booking made?
	if (form_name.TotalFees.value == "")
	{
		alert("You must at least book one night");
		return false;
	}
	return true;
}

// isValidCreditCardNumber()
function isValidCreditCardNumber(ccType,ccNum)
{
	var result = true;
	if (!allDigits(ccNum))
 	{
 		alert('Please enter only numbers (no dashes or spaces)');
		document.booking.CCNumber.select();
		result = false;
	}


	if (result)
 	{
	if (!LuhnCheck(ccNum) || !validateCCNum(ccType,ccNum))
		{
			alert('Please enter a valid card number');
			document.booking.CCNumber.focus();
			result = false;
		}
	}
	return result;
}

// validateCCNum()
function validateCCNum(cardType,cardNum)
{
	var result = false;
	cardType = cardType.toUpperCase();

	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
	case "VISA":
		result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
	break;
	case "AMEX":
		var validNums = "47";
		result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
	break;
	case "MASTERCARD":
		result = (cardLen == 16) && (firstdig == "5");
	break;
	case "DISCOVER":
		result = (cardLen == 16) && (first4digs == "6011");
	break;
	case "DINERS":
		var validNums = "068";
		result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
	break;
	}
	return result;
}

function LuhnCheck(str)
{
	var result = true;

	var sum = 0;
	var mul = 1;
	var strLen = str.length;

	for (i = 0; i < strLen; i++)
	{
		var digit = str.substring(strLen-i-1,strLen-i);
		var tproduct = parseInt(digit ,10)*mul;
		if (tproduct >= 10)
			sum += (tproduct % 10) + 1;
		else
			sum += tproduct;
			if (mul == 1)
				mul++;
			 else
			 mul--;
	}
	if ((sum % 10) != 0)
		result = false;
		return result;
}



// start  isValidExpDate()
function isValidExpDate(tmpMon,tmpyear)
{
	var result = true;
	var now = new Date();
	var nowMonth = now.getMonth() + 1;
	var nowYear = now.getFullYear();

	expired = (nowYear > tmpyear) || ((nowYear == tmpyear ) && (nowMonth > tmpMon));
	if (expired)
		{
		alert('Your Credit Card date has expired.');
		result = false;
		return result;
		document.booking.CCExpYY.focus();

		}

return result;
}
//
// end  isValidExpDate()

function allDigits(str)
		{
		return inValidCharSet(str,"0123456789");
		}

function inValidCharSet(str,charset)
	{
	var result = true;
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
		result = false;
		break;
		}
	return result;
	}



function SameName()
{
	//alert (document.booking.CCardHolderName.value.length)
	if ((document.booking.LastName.value != "") && (document.booking.CCardHolderName.value.length<1))
	{
		areyouthesame = confirm("Is the Credit Card Holder the same as the person making the booking?");
		if (areyouthesame == true)
		{
		document.booking.CCardHolderName.value  = document.booking.FirstName.value + " " + document.booking.LastName.value
		}
	}
}

