var currFormNum;
var formCount;
var cal;
var isArrived;
var dirtyFlag;
var toolTipFlag = 0;

var msg_tooltip_dateRequired = 'For transfers that are to be delivered within one working day please contact our office directly.';
var msg_tooltip_timeRequired = 'What time do you want to be collected. Please note that all date and time information you provide should be in Local Time, or, if you are not sure please contact our operators for assistance.';
var msg_tooltip_collectionFrom = 'Please let us know where to collect you from, include the name, address and as much detail as you can.';
var msg_tooltip_transferTo = 'Please let us know where to transfer you to, include the name, address and as much detail as you can.';
var msg_tooltip_nameOnBoard = 'What name do you want us to put on the board so you can recognise our driver.';
var msg_tooltip_mobile = 'Please provide your mobile number that our driver or travel team can call if required. Please note this phone number should work in Russia and you should include country and city codes.';
var msg_tooltip_arrivingTrain = 'Please give us as much detail as you can about your inbound journey, the train number and the city you are arriving from.'; 
var msg_tooltip_arrivingFlight = 'Please give us as much detail as you can about your inbound journey, the operating company, the flight number and the city you are arriving from.'; 
var msg_tooltip_departingTrain = 'Please give us as much detail as you can about your outbound journey, the train number and the city you are departing to.'; 
var msg_tooltip_departingFlight = 'Please give us as much detail as you can about your outbound journey, the operating company, the flight number and the city you are departing to.'; 
var msg_tooltip_arriving 
var msg_tooltip_departing

var msg_error_invalidTime = 'The time of collection for Transfer Request %num% is not valid, please correct this and try again.';
var msg_error_invalidArrTime = 'The %transport% arrival time for transfer %num% is not valid, please correct this and try again.';
var msg_error_invalidDepTime = 'The %transport% departure time for transfer %num% is not valid, please correct this and try again.';
var msg_error_invalidCollectionFrom = 'You have not told us where our driver is to collect you from for Transfer Request %num%. Please correct this and try again.'; 
var msg_error_invalidTransferTo = 'You have not told us where our driver is to transfer you to for Transfer Request %num%. Please correct this and try again.'; 
var msg_error_invalidArrInfo = 'You may not have given us enough information to meet you at the %station% for Transfer Request %num%. Click CANCEL to enter more details or OK to continue without.';
var msg_error_invalidDepInfo = 'You may not have given us enough information to transfer you at the %station% for Transfer Request %num%. Click CANCEL to enter more details or OK to continue without.';
var msg_error_blankNameOnBoard = 'You have not entered a name for the collection board for Transfer Request %num%. Click CANCEL to enter a name for the board, or OK to continue using the name from your contact details.'; 
var msg_error_blankContactName = 'Please enter a name in the contact details, this does not need to be a person travelling but will be the person responsible for travel arrangements.';
var msg_error_blankContactEmail = 'Please enter an email address in the contact details, this does not need to be of a person travelling but of the person responsible for travel arrangements.';  
var msg_error_blankContactPhone = 'Please enter a phone number in the contact details, this does not need to be of a person travelling but of the person responsible for travel arrangements. You may click OK to continue without entering a phone number or click CANCEL to enter a phone number.';
var msg_error_invalidContactName = 'The email address is in contact details in not valid, please correct this and try again.';
var msg_error_blankCaptcha = 'Verification code has not been set, please correct this and try again.'

var lastErrorMsg;

var msg_error_AjaxServer = "Server connection error, please check your internet connection and reload the page by pressing F5.";

function markBlock(div){
	if(div.parentNode.className == 'string visibleArrived depArrBlock')
		div.parentNode.className = 'string visibleArrived depArrBlockMarked'
	else
		div.parentNode.className = 'string visibleArrived depArrBlock'
}

function bindFunctions(i){
	calView(i);

	msg_tooltip_arriving[i] = msg_tooltip_arrivingTrain;
	msg_tooltip_departing[i] = msg_tooltip_departingTrain;
	
	document.getElementById('select_country_'+i).form_num = i;
	document.getElementById('select_country_'+i).onchange = function() {refreshCities(this, this.form_num)};
	document.getElementById('select_city_'+i).form_num = i;
	document.getElementById('select_city_'+i).onchange = function() {var num = i; refreshTransfers(this, this.form_num)};
	var tmp = document.getElementById('select_loc2_'+i) 
	tmp.form_num = i;
	tmp.onchange = function() {var num = i; refreshVehicles(this, this.form_num); changeDeparting(this, this.form_num)}
	changeDeparting(tmp, i)
	
	tmp = document.getElementById('select_loc1_'+i)
	tmp.form_num = i;
	tmp.onchange = function() {refreshLocation2(this, this.form_num); changeArriving(this, this.form_num)}
	changeArriving(tmp, i)
	
	document.getElementById('select_vehicles_'+i).form_num = i;
	document.getElementById('select_vehicles_'+i).onchange = function() {refreshVehicleInfo(this, this.form_num); return false;};
	document.getElementById('deleteFormLink_'+i).onclick = function() {removeForm(this); return false;};
	
	refreshVehicleInfo(document.getElementById('select_vehicles_'+i), i)
	
	document.getElementById('imgTooltip_timeRequired_'+i).onclick = function() {showTooltip(event, this, msg_tooltip_timeRequired); return false;};
	document.getElementById('imgTooltip_collectionFrom_'+i).onclick = function() {showTooltip(event, this, msg_tooltip_collectionFrom); return false;};
	document.getElementById('imgTooltip_transferTo_'+i).onclick = function() {showTooltip(event, this, msg_tooltip_transferTo); return false;};
	document.getElementById('imgTooltip_nameOnBoard_'+i).onclick = function() {showTooltip(event, this, msg_tooltip_nameOnBoard); return false;};
	document.getElementById('imgTooltip_mobile_'+i).onclick = function() {showTooltip(event, this, msg_tooltip_mobile); return false;};
	
	document.getElementById('label1_'+i).onmouseover = function() {markBlock(this)};
	document.getElementById('label1_'+i).onmouseout = function() {markBlock(this)};
	document.getElementById('label2_'+i).onmouseover = function() {markBlock(this)};
	document.getElementById('label2_'+i).onmouseout = function() {markBlock(this)};
	
	document.getElementById('imgTooltip_arrivingFrom_'+i).form_num = i;
	document.getElementById('imgTooltip_arrivingFrom_'+i).onclick = function() {showTooltip(event, this, msg_tooltip_arriving[this.form_num]); return false;};
	document.getElementById('imgTooltip_departingFrom_'+i).form_num = i;
	document.getElementById('imgTooltip_departingFrom_'+i).onclick = function() {showTooltip(event, this, msg_tooltip_departing[this.form_num]); return false;};
	document.getElementById('imgTooltip_dateRequired_'+i).onclick = function() {showTooltip(event, this, msg_tooltip_dateRequired); return false;};
	
}

function refreshVehicleInfo(div, formNum){
	var tmp = document.getElementById('vehicle_info_'+formNum);
	var attr = div.options[div.selectedIndex].getAttribute('vehicle_note')
	tmp.innerHTML = attr
}

function refreshNumeration(){
	for(var i=0, j=0; i<currFormNum; ++i){
		var tmp = document.getElementById('transferNum_'+i);
		if(!tmp)continue;
		
		tmp.innerHTML = 'Transfer request '+(++j);
	}
}

function hideLastDelete (){
	if(formCount != 1)
		return false;
	for(var i=0; i<currFormNum; ++i){
		var tmp = document.getElementById('deleteButton_'+i);
		if(!tmp)continue;
		tmp.style.display = 'none';
	}
}

function showLastDelete (){
	for(var i=0; i<currFormNum; ++i){
		var tmp = document.getElementById('deleteButton_'+i);
		if(!tmp)continue;
		tmp.style.display = 'block';
	}
}

function changeCaptcha(){
	div = document.getElementById("urina");
	
	img = new Image();
	img.src = 'libs/captcha/captcha.php?a=image&op='+Math.random();
	div.src = img.src;
}

function getPriceInSelectedCurrency(price_gbp, price_rur, price_eur, price_usd){
	var curr = document.getElementById('currency');
	
	switch(curr.value)
	{
		case 'GBP':return '\u00A3'+price_gbp;
		case 'RUR':return price_rur+' rur';
		case 'EUR':return '\u20AC'+price_eur;
		case 'USD':return '$'+price_usd;
	}
}

function changeCurrency(div){
	for(var i=0; i<currFormNum; ++i){
		var tmp = document.getElementById('select_vehicles_'+i);
		if(!tmp)continue;
		
		for(var ind in tmp.options){
			if(isNaN(parseInt(ind)))continue;
			name = tmp.options[ind].getAttribute('vehicle_name')
			pax =  tmp.options[ind].getAttribute('pax')
			price_gbp = tmp.options[ind].getAttribute('price_gbp')
			price_rur = tmp.options[ind].getAttribute('price_rur')
			price_eur = tmp.options[ind].getAttribute('price_eur')
			price_usd = tmp.options[ind].getAttribute('price_usd')
			price = getPriceInSelectedCurrency(price_gbp, price_rur, price_eur, price_usd)
			tmp.options[ind].text =  name + " for maximum " + pax + " passengers - " + price
		}
	}
}

function dateToStr_digit(dt){
	var str = dt[2];
	
	str+= ".";
	str+= dt[1];
	str+= ".";
	str+= dt[0];
	
	return str;
}

function dateToStr_alpha(dt){
	var str = dt[2];
	str+=" ";
	switch(parseInt(dt[1])){
		case 1:str+="January";break;
		case 2:str+="February";break;
		case 3:str+="March";break;
		case 4:str+="April";break;
		case 5:str+="May";break;
		case 6:str+="June";break;
		case 7:str+="July";break;
		case 8:str+="August";break;
		case 9:str+="September";break;
		case 10:str+="October";break;
		case 11:str+="November";break;
		case 12:str+="December";break;
	}
	str+=" ";
	str += dt[0];
	
	return str;
}

function mySelectHandler(type,args,obj) {
	var selDate = dateToStr_digit(args[0][0]);
	var elem = document.getElementById("dateRequired_"+obj.num);
	elem.value = selDate;
	
	var selDate = dateToStr_alpha(args[0][0]);
	var elem = document.getElementById("dateRequiredInput_"+obj.num);
	elem.value = selDate;
	
	var div = document.getElementById("calContainer_"+obj.num);
	div.style.display = 'none';
	
	//if(window.event) window.event.cancelBubble = true; 
	//if (e) e.stopPropagation();
}

function calView(formNum){
	var elem
	if(elem = document.getElementById('calContainer_'+formNum)){
	
		var today = new Date();
		var tom =  new Date();
		today = Date.parse(today)
		tomorrow = today + 1000*60*60*24; 
		tom.setTime(tomorrow) 

		tom.day = tom.getDate();
		tom.month = tom.getMonth() + 1;
		tom.year = tom.getFullYear();	
	
		cal[formNum] = new YAHOO.widget.Calendar("calContainer_"+formNum, { title:"Choose a date:", close:true, iframe: false } );
		cal[formNum].cfg.setProperty('START_WEEKDAY', '1');
		cal[formNum].cfg.queueProperty("selected", tom.month + "/" + tom.day + "/" + tom.year, false);
		cal[formNum].cfg.queueProperty("mindate", tom.month + "/" + tom.day + "/" + tom.year, false);

	
		cal[formNum].cfg.fireQueue();
		var arg = new Object();
		arg.cal = cal[formNum];
		arg.num = formNum;
		cal[formNum].selectEvent.subscribe(mySelectHandler, arg, true); 
		
		
		cal[formNum].render(); 
		YAHOO.util.Event.addListener("dateRequiredInput_"+formNum, "click", cal[formNum].show, cal[formNum], true);
	}
}

function refreshVehicles(div,formNum){
	var select = document.createElement('select');
	select.id = 'select_vehicles_'+formNum;
	select.name = 'select_vehicles_'+formNum;
	select.className = 'select_vehicles';
	
	var tmp = vehicles[formNum];
	
	//for( var ind=0;ind<tmp.length;ind++){
	for( var ind in tmp ){
		//if(ind=='length')break;
		if(tmp[ind].route_id != div.value)continue;
		id = tmp[ind].cr_id
		name = tmp[ind].name
		vehicle_note = tmp[ind].vehicle_note
		pax = tmp[ind].pax
		price_gbp = tmp[ind].price_gbp
		price_rur = tmp[ind].price_rur
		price_eur = tmp[ind].price_eur
		price_usd = tmp[ind].price_usd
		price = getPriceInSelectedCurrency(price_gbp, price_rur, price_eur, price_usd)
		var s = name + " for maximum " + pax + " passengers - " + price;
		var option = new Option(s, id, false, null);
		
		option.setAttribute('vehicle_name',name)
		option.setAttribute('vehicle_note',vehicle_note)
		option.setAttribute('pax',pax)
		option.setAttribute('price_gbp',price_gbp)
		option.setAttribute('price_rur',price_rur)
		option.setAttribute('price_eur',price_eur)
		option.setAttribute('price_usd',price_usd)
		
		select.options[select.options.length] = option;
    }  	
    
	var span = document.getElementById('select_vehicles_'+formNum).parentNode;
	span.innerHTML = '';
	span.appendChild(select);

	document.getElementById('select_vehicles_'+formNum).formNum = formNum
	document.getElementById('select_vehicles_'+formNum).onchange = function() {refreshVehicleInfo(this, this.formNum); return false;};
    refreshVehicleInfo(document.getElementById('select_vehicles_'+formNum), formNum)	
	
   	tmp = document.getElementById('arrGroup_'+formNum);
    /*if(tmp && div.options[div.selectedIndex].getAttribute('isArrived') == 1){
    	tmp.className = 'string visibleArrived';
    }else{
    	tmp.className = 'string hiddenArrived';
    }*/
    tmp.parentNode.parentNode.style.zoom='1'
}

function findLastForm(){
	for(i=currFormNum-1;i>=0;i--)
		if(document.getElementById('transferForm_'+i))
			return i;
}

function setSelectElement(div, value){
	for(i=0;;i++){
		if(!div.options[i])break;
		
		if(div.options[i].value == value){
			div.options[i].selected = true;
			break;
		}
	}
}
function addNewForm(){
	var transfersContainer = document.getElementById('transfersContainer'); 

	var div = document.createElement('div');
	div.id = 'transferForm_'+currFormNum;
	div.className = 'yui-skin-sam  transferForm';
	var s = formTemplate1+formTemplate2
	s = s.replace(/%minList%/g, minList)
	s = s.replace(/%hourList%/g, hourList)
	s = s.replace(/%formNumber%/g, currFormNum)
	div.innerHTML = s;
	transfersContainer.appendChild(div);
	
	var lastNum = findLastForm();
	//country
	var cl = document.getElementById('select_country_'+lastNum).cloneNode(true);
	cl.id = 'select_country_'+currFormNum;
	cl.name = 'select_country_'+currFormNum;
	var old = document.getElementById('select_country_'+currFormNum).parentNode;
	old.innerHTML='';
	old.appendChild(cl);

	//city
	cl = document.getElementById('select_city_'+lastNum).cloneNode(true);
	cl.id = 'select_city_'+currFormNum;
	cl.name = 'select_city_'+currFormNum;
	old = document.getElementById('select_city_'+currFormNum).parentNode;
	old.innerHTML='';
	old.appendChild(cl);

	//transfers
	cl = document.getElementById('select_loc1_'+lastNum).cloneNode(true);
	cl.id = 'select_loc1_'+currFormNum;
	cl.name = 'select_loc1_'+currFormNum;
	old = document.getElementById('select_loc1_'+currFormNum).parentNode;
	old.innerHTML='';
	old.appendChild(cl);

	cl = document.getElementById('select_loc2_'+lastNum).cloneNode(true);
	cl.id = 'select_loc2_'+currFormNum;
	cl.name = 'select_loc2_'+currFormNum;
	old = document.getElementById('select_loc2_'+currFormNum).parentNode;
	old.innerHTML='';
	old.appendChild(cl);
	
	var num=currFormNum;
	var elem = document.getElementById('select_country_'+currFormNum)
	setSelectElement(elem, document.getElementById('select_country_'+lastNum).value)
	
	elem = document.getElementById('select_city_'+currFormNum)
	setSelectElement(elem, document.getElementById('select_city_'+lastNum).value)

	elem = document.getElementById('select_loc1_'+currFormNum)
	setSelectElement(elem, document.getElementById('select_loc1_'+lastNum).value)

	document.getElementById('nameForBoard_'+currFormNum).value = document.getElementById('nameForBoard_'+lastNum).value
	document.getElementById('mobile_'+currFormNum).value = document.getElementById('mobile_'+lastNum).value
	
	vehicles[currFormNum] = vehicles[lastNum]
    div = document.getElementById('select_loc2_'+currFormNum)
    refreshVehicles(div,currFormNum)  

    bindFunctions(currFormNum)
	
	currFormNum++
	formCount++
	showLastDelete()
	refreshNumeration()
	document.getElementById('transfersBody').style.zoom='1'
}

function removeForm(div){
	if(formCount <= 1)return;
	var p = div.parentNode.parentNode;
	var pp = p.parentNode;
	pp.removeChild(p)
	formCount--
	refreshNumeration()
	hideLastDelete()
	document.getElementById('transfersBody').style.zoom='1'
}

function fillVehicles(xml,formNum){
	vehicles[formNum] = new Array()

	var tmp = xml.getElementsByTagName('vehicle');
	for( var ind=0;ind<tmp.length;ind++){
//alert(xml)
//	for( var ind in tmp ){
//		if(isNaN(parseInt(ind)))continue;
		
		tmp1 = new Object();
		tmp1.cr_id = tmp[ind].getAttribute("cr_id")
		tmp1.route_id = tmp[ind].getAttribute("route_id")
		tmp1.name = tmp[ind].getAttribute("name")
		tmp1.vehicle_note = ''
		for( var jnd=0;jnd<tmp[ind].childNodes.length;jnd++){
			tmp1.vehicle_note += tmp[ind].childNodes[jnd].nodeValue
		}
		tmp1.pax = tmp[ind].getAttribute("pax")
		tmp1.price_gbp = tmp[ind].getAttribute("price_gbp")
		tmp1.price_rur = tmp[ind].getAttribute("price_rur")
		tmp1.price_eur = tmp[ind].getAttribute("price_eur")
		tmp1.price_usd = tmp[ind].getAttribute("price_usd")
		vehicles[formNum][ind] = tmp1;
    }
    /*tmp = xml.getElementsByTagName('defaultIsArrived');
    if(tmp[0].value == 1){
    	isArrived[formNum] = 1;
    }*/

    //var div = document.getElementById('select_loc2_'+formNum);
    //refreshVehicles(div,formNum)  	
}

function fillTransfers(xml,formNum){
	var select = document.createElement('select');
	select.id = 'select_loc1_'+formNum;
	select.name = 'select_loc1_'+formNum;
	select.className = 'select_country';
	select.onchange = function() {refreshLocation2(this,formNum); changeArriving(this, formNum)};

/*	var tmp = xml.getElementsByTagName('transfer');
	for( var ind=0;ind<tmp.length;ind++){
		
		id = tmp[ind].getAttribute("id")
		
		isArrived = tmp[ind].getAttribute("isArrived")
		location1 = tmp[ind].getAttribute("location1")
		location2 = tmp[ind].getAttribute("location2")
		note = tmp[ind].getAttribute("note")
		var s = location1 + ' to ' + location2 + ' :: ' + note;
		var tmp1 = new Option(s, id, false, null);
		tmp1.setAttribute('isArrived',isArrived)
		select.options[select.options.length] = tmp1
    }  	
*/  
	doubleListJSON = new Array()
	var tmp = xml.getElementsByTagName('location1');
	var id, name, locType, autoHide, tmp1
	for( var ind=0;ind<tmp.length;ind++){
		
		id = tmp[ind].getAttribute("id")
		name = tmp[ind].getAttribute("name")
		locType = tmp[ind].getAttribute("locType")
		autoHide = tmp[ind].getAttribute("autoHide")

		tmp1 = new Option(name, id, false, null);
		tmp1.setAttribute('locType',locType)
		tmp1.setAttribute('autoHide',autoHide)
		select.options[select.options.length] = tmp1
		
		doubleListJSON[id] = new Object()
		doubleListJSON[id].name = name
		doubleListJSON[id].locType = locType
		doubleListJSON[id].autoHide = autoHide
		doubleListJSON[id].location2 = new Array()
		
		for(jnd=0;jnd<tmp[ind].childNodes.length;jnd++){
			if(tmp[ind].childNodes[jnd].nodeName != 'location2')
				continue
			loc2 = new Object()
			loc2.id = tmp[ind].childNodes[jnd].getAttribute('id')
			loc2.route_id = tmp[ind].childNodes[jnd].getAttribute('routeId')
			loc2.name = tmp[ind].childNodes[jnd].getAttribute('name')
			loc2.locType = tmp[ind].childNodes[jnd].getAttribute('locType')
			loc2.autoHide = tmp[ind].childNodes[jnd].getAttribute('autoHide')
			doubleListJSON[id].location2[loc2.id] = loc2
		}
    }
    	
	var span = document.getElementById('select_loc1_'+formNum).parentNode;
	span.innerHTML = '';
	span.appendChild(select);

	fillVehicles(xml, formNum);
	
	tmp = document.getElementById('select_loc1_'+formNum)
	changeArriving(tmp,formNum)
	refreshLocation2(tmp,formNum)
	
}

function fillCitiesTransfers(xml,formNum){
	var select = document.createElement('select');
	select.id = 'select_city_'+formNum;
	select.name = 'select_city_'+formNum;
	select.className = 'select_city';

	var tmp = xml.getElementsByTagName('city');
	for( var ind=0;ind<tmp.length;ind++){
	//for( var ind in tmp ){
		//if(isNaN(parseInt(ind)))continue;
		
		name = tmp[ind].getAttribute("name");
		id = tmp[ind].getAttribute("id")
		select.options[select.options.length] = new Option(name, id, false, null);
    }
      	
	var span = document.getElementById('select_city_'+formNum).parentNode;
	span.innerHTML = '';
	span.appendChild(select);
	
	tmp = xml.getElementsByTagName('defaultCity')[0].getAttribute('id');
	var sc = document.getElementById('select_city_'+formNum)
	setSelectElement(sc, tmp)
	sc.onchange = function() {refreshTransfers(this,formNum)};
	fillTransfers(xml,formNum);
}


// AJAX********
function alertClient(http_request, getType,formNum) {
	var sD;
	if (http_request.readyState == 4) {
		if (http_request.status == 200){
			xml = http_request.responseXML.getElementsByTagName('units')[0];
			if(getType == 0)fillCitiesTransfers(http_request.responseXML,formNum);
			if(getType == 1)fillTransfers(http_request.responseXML,formNum)		
		}
		//else alert(msg_error_AjaxServer);
	}
}

function makeRequest(url, getType,formNum) {
	var http_request = false;

	if (window.XMLHttpRequest) { 
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	http_request.onreadystatechange = function(){
		alertClient(http_request, getType,formNum);
	};
	http_request.open('GET', url, true);
	http_request.send(null);
}

function refreshCities(div,formNum){
	makeRequest('refresh.php?action=1&country=' + div.value+'&rand='+(new Date()).getTime(), 0,formNum);
}

function refreshTransfers(div,formNum){
	makeRequest('refresh.php?action=2&city=' + div.value+'&rand='+(new Date()).getTime(), 1,formNum);
}

var addToFavourites = function(){
  if (window.external&&(typeof window.external.AddFavorite=='unknown')) window.external.AddFavorite(location.href,document.title);
  else if (window.sidebar&&window.sidebar.addPanel) window.sidebar.addPanel(document.title, location.href, "");
  else alert('Please press CTRL-D to bookmark the page!');
  return false;
};

var lockSite = function(){
  if(location.protocol.toLowerCase() == 'https:') alert("The site is already secure as using 128 bit SSL technology to protect your personal information.");
  else {
    location.href = location.href.replace('http', 'https');
    alert("Your web browser has now been set to browse our website using 128 bit SSL technology.\n\nThis will protect any personal information you choose to send to us or that we send to you visa our website.\n\nPlease note that the site is secure while the padlock icon is showing in the address bar of your web browser.");
  }
};

var createLIwA = function(liId, linkText, handler) {
  var li = document.createElement('li');
  li.id = liId;
  var lnk = li.appendChild(document.createElement('a'));
  lnk.href='#';
  lnk.appendChild(document.createTextNode(linkText));
  lnk.onclick = handler;
  
  return li;
};

var prepareLinks = function(){
  var mainMenu = document.getElementById('mainMenu');
  if (mainMenu) { //we create these links only if menu is there
//    mainMenu.insertBefore(createLIwA('mmiBookmark', 'Bookmark this site', addToFavourites), mainMenu.firstChild);
    mainMenu.insertBefore(createLIwA('mmiSecure', 'Secure site', lockSite), document.getElementById('mmiTracking'));
  }      
};

function checkEmail(email){
	var reg=/[0-9a-z_.]+@[0-9a-z_^.]+.[a-z]{2,3}/i
	return reg.test(email)
}

function printError(msg, formNum, transport){
	if(transport == 1)msg = msg.replace(/%transport%/g, 'flight')
	if(transport == 2)msg = msg.replace(/%transport%/g, 'train')
	alert (msg.replace(/%num%/g, formNum));
}

function checkForm(){
	lastErrorMsg = new Array();
	dirtyFlag = 0;
	var lastFormNum = document.getElementById('lastFormNum');
	lastFormNum.value = currFormNum - 1;
	var div, ans;
	var x = new Boolean(true);
	ok=x.valueOf(); 
	
	var elem, elem1, msg
	
	for(i=0, j=0;i<currFormNum;++i){
		if(!document.getElementById('transferForm_'+i))
			continue
		sel1 = document.getElementById('select_loc1_'+i)
		sel2 = document.getElementById('select_loc2_'+i)
		locType1 = sel1.options[sel1.selectedIndex].getAttribute('locType')
		locType2 = sel2.options[sel2.selectedIndex].getAttribute('locType')
		autoHide1 = sel1.options[sel1.selectedIndex].getAttribute('autoHide')
		autoHide2 = sel2.options[sel2.selectedIndex].getAttribute('autoHide')
		
		elem = document.getElementById('dateRequiredInput_'+i)
		if(!elem)continue;
		j++;
		
		if(elem.value==''){
			printError (msg_error_invalidTime, j);
			elem.focus();
			return false;		
		}
		
		
		if(locType1 == 0 && locType2 == 0){
			elem = document.getElementById('hourRequired_'+i)
			elem1 = document.getElementById('minuteRequired_'+i)
			if((elem.value=='100') || (elem1.value=='100')){
				printError (msg_error_invalidTime, j);
				elem.focus();
				return false;		
			}		
		}

		if(autoHide1 == 0){
			elem = document.getElementById('collectionFrom_'+i)
			if(elem.value==''){
				printError (msg_error_invalidCollectionFrom, j);
				elem.focus();
				return false;		
			}
		}
		
		if(locType1 != 0){		
			elem = document.getElementById('arrHourRequired_'+i)
			elem1 = document.getElementById('arrMinuteRequired_'+i)
			if((elem.value=='100') || (elem1.value=='100')){
				printError (msg_error_invalidArrTime, j, locType1);
				elem.focus();
				return false;	
			}			
			elem = document.getElementById('arrNumber_'+i)
			elem1 = document.getElementById('arrFrom_'+i)
			if(elem.value=='' || elem1.value==''){
				
				msg = msg_error_invalidArrInfo.replace(/%station%/g, (locType1==1?'airport':'station'))
				ans = confirm( msg.replace(/%num%/g, j) )
				if(ans != ok)
					return false;
			}
		}

		if(autoHide2 == 0){
			elem = document.getElementById('transferTo_'+i)
			if(elem.value==''){
				printError (msg_error_invalidTransferTo, j);
				elem.focus();
				return false;		
			}
		}		
		
		if(locType2 != 0){		
			elem = document.getElementById('depHourRequired_'+i)
			elem1 = document.getElementById('depMinuteRequired_'+i)
			if((elem.value=='100') || (elem1.value=='100')){
				printError (msg_error_invalidDepTime, j, locType2);
				elem.focus();
				return false;	
			}			
			elem = document.getElementById('depNumber_'+i)
			elem1 = document.getElementById('depFrom_'+i)
			if(elem.value=='' || elem1.value==''){
				msg = msg_error_invalidDepInfo.replace(/%station%/g, (locType2==1?'airport':'station'))
				ans = confirm( msg.replace(/%num%/g, j) )
				if(ans != ok)
					return false;
			}		
		}
		
		/*div = document.getElementById('select_transfers_'+i)
		if(div.options[div.selectedIndex].getAttribute('isArrived') == 1){
			var counter = 0;
			elem = document.getElementById('arrCompany_'+i)
			if(elem.value=='')
				counter++; 
			elem = document.getElementById('arrNumber_'+i)
			if(elem.value=='')
				counter++; 
			elem = document.getElementById('arrFrom_'+i)
			if(elem.value=='')
				counter++;
				 
			if(counter>=2){
				ans = confirm( msg_error_invalidArrInfo.replace(/%num%/g, j) )
				if(ans != ok)
					return false;
			}		
		}*/
		
		elem = document.getElementById('nameForBoard_'+i)
		if(elem.value==''){
			ans = confirm( msg_error_blankNameOnBoard.replace(/%num%/g, j) )
			if(ans != ok)
				return false;
		}
	}

	elem = document.getElementById('contactName')
	elem1 = document.getElementById('contactSurname')
	if((elem.value=='') && (elem1.value=='')){
		alert (msg_error_blankContactName);
		elem.focus();
		return false;
	}
	
	elem = document.getElementById('contactEmail')
	if(elem.value==''){
		alert (msg_error_blankContactEmail);
		elem.focus();
		return false;
	}
	else if(!checkEmail(elem.value)){
		alert (msg_error_invalidContactName);
		elem.focus();
		return false;
	}
	
	elem = document.getElementById('contactPhone')
	if(elem.value==''){
		ans = confirm( msg_error_blankContactPhone )
		if(ans != ok)
			return false;
	}	
	
	elem = document.getElementById('captcha')
	if(elem.value==''){
		alert (msg_error_blankCaptcha);
		elem.focus();
		return false;		
	}		
	
	return true;
}

window.onbeforeunload = function(e) {
	if(dirtyFlag == 1){
		var tmp = '';
	   	
	   	for(var i=0; i<lastErrorMsg.length;i++)
	   	{
	   		//tmp += lastErrorMsg[i]+'\n\r\n\r'
	   		//e.returnValue = tmp;
	   		e = e || window.event;
	   		e.returnValue = lastErrorMsg[i];
	   	}
   	}
}

function refreshLocation2(div, formNum){
	var parent = document.getElementById('select_loc2_'+formNum).parentNode
	
	var select = document.createElement('select')
	select.id = 'select_loc2_'+formNum
	select.name = 'select_loc2_'+formNum
	select.className = 'select_country'
	select.num = formNum
	select.onchange = function(){refreshVehicles(this,this.num); changeDeparting(this, this.num)}

	var tmp = doubleListJSON[div.value].location2
	var option
	for( var ind in tmp ){
		if(isNaN(parseInt(ind)))continue;
		
		name = tmp[ind].name
		id = tmp[ind].route_id
		option = new Option(name, id, false, null)
		option.setAttribute('locType', tmp[ind].locType)
		option.setAttribute('autoHide', tmp[ind].autoHide)
		select.options[select.options.length] = option
    }
    parent.innerHTML = ''
    parent.appendChild(select)
    
	select = document.getElementById('select_loc2_'+formNum);
	refreshVehicles(select,formNum)   
	
	changeDeparting(select, formNum)
	
}

function changeArriving(div, formNum){
	loc1 = div
	locType1 = loc1.options[loc1.selectedIndex].getAttribute('locType')
	autoHide1 = loc1.options[loc1.selectedIndex].getAttribute('autoHide')

	loc2 = document.getElementById('select_loc2_'+formNum)
	locType2 = loc2.options[loc2.selectedIndex].getAttribute('locType')
	autoHide2 = loc2.options[loc2.selectedIndex].getAttribute('autoHide')
	
	if(locType1 == 1){
		msg_tooltip_arriving[formNum] = msg_tooltip_arrivingFlight
		document.getElementById('commonTime1_'+formNum).style.display = 'none'
		document.getElementById('commonTime2_'+formNum).style.display = 'none'
		document.getElementById('arrGroup_'+formNum).className = 'string visibleArrived depArrBlock'
		document.getElementById('spanArrCompany_'+formNum).style.display = 'inline'
		document.getElementById('labelArrNumber_'+formNum).innerHTML = 'Flight number:'
		document.getElementById('labelArrTime_'+formNum).innerHTML = 'Flight arrives:'
	}else if(locType1 == 2){
		msg_tooltip_arriving[formNum] = msg_tooltip_arrivingTrain
		document.getElementById('commonTime1_'+formNum).style.display = 'none'
		document.getElementById('commonTime2_'+formNum).style.display = 'none'
		document.getElementById('arrGroup_'+formNum).className = 'string visibleArrived depArrBlock'
		document.getElementById('spanArrCompany_'+formNum).style.display = 'none'
		document.getElementById('labelArrNumber_'+formNum).innerHTML = 'Train, carriage number:'
		document.getElementById('labelArrTime_'+formNum).innerHTML = 'Train arrives:'
	}else{
		if(locType2 == 0){
			document.getElementById('commonTime1_'+formNum).style.display = 'inline'
			document.getElementById('commonTime2_'+formNum).style.display = 'inline'
		}
		document.getElementById('arrGroup_'+formNum).className = 'string hiddenArrived depArrBlock'
	}
	
	if(autoHide1 == 1)
		document.getElementById('spanCollectionFrom_'+formNum).style.display = 'none'
	else
		document.getElementById('spanCollectionFrom_'+formNum).style.display = 'block'
	
	document.getElementById('transfersBody').style.zoom='1'
}

function changeDeparting(div, formNum){
	loc1 = document.getElementById('select_loc1_'+formNum)
	locType1 = loc1.options[loc1.selectedIndex].getAttribute('locType')
	autoHide1 = loc1.options[loc1.selectedIndex].getAttribute('autoHide')

	loc2 = div
	locType2 = loc2.options[loc2.selectedIndex].getAttribute('locType')
	autoHide2 = loc2.options[loc2.selectedIndex].getAttribute('autoHide')
	
	if(locType2 == 1){
		msg_tooltip_departing[formNum] = msg_tooltip_departingFlight
		document.getElementById('commonTime1_'+formNum).style.display = 'none'
		document.getElementById('commonTime2_'+formNum).style.display = 'none'
		document.getElementById('depGroup_'+formNum).className = 'string visibleArrived depArrBlock'
		document.getElementById('spanDepCompany_'+formNum).style.display = 'inline'
		document.getElementById('labelDepNumber_'+formNum).innerHTML = 'Flight number:'
		document.getElementById('labelDepTime_'+formNum).innerHTML = 'Flight departs:'
	}else if(locType2 == 2){
		msg_tooltip_departing[formNum] = msg_tooltip_departingTrain
		document.getElementById('commonTime1_'+formNum).style.display = 'none'
		document.getElementById('commonTime2_'+formNum).style.display = 'none'
		document.getElementById('depGroup_'+formNum).className = 'string visibleArrived depArrBlock'
		document.getElementById('spanDepCompany_'+formNum).style.display = 'none'
		document.getElementById('labelDepNumber_'+formNum).innerHTML = 'Train, carriage number:'
		document.getElementById('labelDepTime_'+formNum).innerHTML = 'Train departs:'
	}else{
		if(locType1 == 0){
			document.getElementById('commonTime1_'+formNum).style.display = 'inline'
			document.getElementById('commonTime2_'+formNum).style.display = 'inline'
		}
		document.getElementById('depGroup_'+formNum).className = 'string hiddenArrived depArrBlock'
	}

	if(autoHide2 == 1)
		document.getElementById('spanTransferTo_'+formNum).style.display = 'none'
	else
		document.getElementById('spanTransferTo_'+formNum).style.display = 'block'
	document.getElementById('transfersBody').style.zoom='1'
}

window.onload = function(){
	//vehicles = new Array();
	cal = new Array()
	msg_tooltip_arriving = new Array()
	msg_tooltip_departing = new Array()
	
	dirtyFlag = 0;
	formCount = 0;
	//vehicles[0] = firstVehicles;
	if((typeof(trCount) == 'undefined') || !trCount)
		currFormNum = 1; 
	else
		currFormNum = parseInt(trCount);
		
	if(typeof(event) == 'undefined')
		event = window.event;
		
	for(var i=0;i<currFormNum;++i){
		formCount++
		bindFunctions(i)
	}
	setSelectElement(document.getElementById('select_country_0'),defaultCountry)
	setSelectElement(document.getElementById('select_city_0'),defaultCity)
	
	document.getElementById('refreshCaptcha').onclick = function() {changeCaptcha(); return false;};
	document.getElementById('addFormLink').onclick = function() {addNewForm(this); return false;};
	document.getElementById('mainForm').onsubmit = function() {return checkForm()};
	document.getElementById('currency').onchange = function() {changeCurrency(this)};
	
	hideLastDelete ()
	refreshNumeration()	
	
	document.getElementById('transfersBody').style.zoom='1'
	
	changeCurrency(document.getElementById('currency'))
	
	//prepare links in the main navigation
 	prepareLinks();
 	
 	document.getElementById('transfersBody').onclick = function(e){
 		if(toolTipFlag == 0)return
 		if(toolTipFlag == 1 && /a/[-1]=='a'){
 			toolTipFlag++
 			return
 		}
		var event = e||window.event;
		var toolTip = document.getElementById('myToolTip');
		var shim = document.getElementById('myShim');

		if (toolTip) toolTip.style.display = 'none';
		if (shim) shim.style.display = 'none';
		toolTipFlag = 0;
		
		
		for(var i=0;i<currFormNum;++i){
			var tmp = document.getElementById('calContainer_'+i)
			if(tmp)tmp.style.display = 'none' 
		}
   }; 
   document.getElementById('transfersBody').style.zoom='1'
}
