function ajaxRequest(url, params, postProcessor) {
  new Ajax.Request(url, {
    method: 'post',
    parameters: params,
    onSuccess: function(transport) {
      if (postProcessor) {
        postProcessor(transport);
      }
    }
  });
}

function reloadFields(fieldId, params, postProcessor) {
  new Ajax.Request("loadFieldData.do", {
    method: 'post',
    parameters: params,
    onSuccess: function(transport) {
      $H(transport.responseText.evalJSON(true)).sortBy(function(obj) {return obj.value})
        .each(function(obj) {
        var option = new Option(obj.value, obj.key);
        $(fieldId).options.add(option);
      });
      if (postProcessor) {
        postProcessor();
      }
    }
  });
}

function emptySelectBox(fieldId) {
  $A($(fieldId).options).each(function(n) {
    if (n.index > 0) {
      $(fieldId).remove(n.index);
    }
  });
}

function reloadPickUpCities() {
  emptySelectBox("pickUpCityId");
  emptySelectBox("pickUpLocationId");
  reloadFields("pickUpCityId", {action: "cities", country: $F("pickUpCountryId"), marketId: marketId, lang : activeLang});
}

function reloadPickUpLocations() {
  emptySelectBox("pickUpLocationId");
  reloadFields("pickUpLocationId",  {action: "locations", city: $F("pickUpCityId"), marketId: marketId, lang : activeLang});
}

function reloadDropOffCountries() {
  emptySelectBox("dropOffCountryId");
  reloadFields("dropOffCountryId", {action: "dropOffCountries", locationId: $F("pickUpLocationId"), marketId: marketId, lang : activeLang}, function() {
    $("dropOffCountryId").setValue($F("pickUpCountryId"));
    $("dropOffCountryId").onchange();
  });
}

function reloadDropOffCities() {
  emptySelectBox("dropOffCityId");
  emptySelectBox("dropOffLocationId");
  reloadFields("dropOffCityId", {action: "dropOffCities", locationId: $F("pickUpLocationId"), country: $F("dropOffCountryId"), marketId: marketId, lang : activeLang}, function() {
    $("dropOffCityId").setValue($F("pickUpCityId"));
    $("dropOffCityId").onchange();
  });
}

function reloadDropOffLocations() {
  emptySelectBox("dropOffLocationId");
  reloadFields("dropOffLocationId", {action: "dropOffLocations", locationId: $F("pickUpLocationId"), city: $F("dropOffCityId"), marketId: marketId, lang : activeLang}, function() {
    $("dropOffLocationId").setValue($F("pickUpLocationId"));
  });
}

function reloadLocationPickUpTime(locationElement) {
  var date = $F('pickUpYear')+'-'+$F('pickUpMon')+'-'+$F('pickUpDay');

  ajaxRequest("loadFieldData.do", {action: "locationPickUpTime", locationId: $F(locationElement), date: date}, function(transport) {
    populateTimeBlock(transport.responseText, "pickUpHour", "pickUpMin");
  });
}

function reloadLocationDropOffTime(locationElement) {
  var date = $F('dropOffYear')+'-'+$F('dropOffMon')+'-'+$F('dropOffDay');

  ajaxRequest("loadFieldData.do", {action: "locationDropOffTime", locationId: $F(locationElement), date: date}, function(transport) {
    populateTimeBlock(transport.responseText, "dropOffHour", "dropOffMin");
  });
}

function populateTimeBlock(result, hourElement, minuteElement) {
  var timeObj = $(hourElement);
  var minObj = $(minuteElement);

  var closed = false;

  var time = result.evalJSON(true).time;

  if (time && time != '') {

    closed = true;

    for (var i = 0; i < time.length; i++) {
      if (time.charAt(i) == 1) {
        closed = false;
      }
    }

    if (!closed) {
      minObj.show();
    }
  }
  else {
    closed = true;
  }

  if (closed) {
    timeObj.options.length = 0;
    timeObj.options[0] = new Option($("msg_closed").innerHTML, 'closed');
    minObj.hide();
    return;
  }

  timeObj.options.length = 0;
  var index = 0;
  for (i = 0; i < time.length; i++) {
    j = (i < 10) ? "0" + i : i;
    if (time.charAt(i) == '1') {
      timeObj.options[index] = new Option(j, i);
      if (j == '12') timeObj.options[index].selected = true;
      index++;
    }
  }
}

var f = document.main;
var lang=33;

var projectPath = '';

if (tomcatProjectName != '') {
	projectPath = ('/' + tomcatProjectName)
}

if (!isMSIE()){
		Document.prototype.loadXML = function (s){
		 // parse the string to a new doc
		var doc2 = (new DOMParser()).parseFromString(s, "text/xml")
		 // remove all initial children
		while (this.hasChildNodes())
			this.removeChild(this.lastChild)
	   // insert and import nodes
		for (var i = 0; i < doc2.childNodes.length; i++) {
			this.appendChild(this.importNode(doc2.childNodes[i], true))
		}
	};
}

function makeRequest(request, type){ // type = 0 - return opts array, type=1 - return xml
	// Create an instance of the XML HTTP Request object
	if (typeof type =="undefined") type=0;

	var to_time = new Date();to_time = to_time.getTime()
	try {		//IE
		oXMLHTTP = new ActiveXObject("Msxml2.XMLHTTP")
	} catch (e) {
		try {
			oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP")
		} catch (E) {
			oXMLHTTP = false
		}
	}
	if (!oXMLHTTP && typeof XMLHttpRequest!='undefined') {		//MOZILLA
		oXMLHTTP = new XMLHttpRequest()
	}
	var sURL = projectPath+"/dynaList.do?type="+type+"&xml="+encodeURI(request)
	oXMLHTTP.open( "POST", sURL, false )
	oXMLHTTP.send(null) // Execute the request
	var xmlResponse=oXMLHTTP.responseText
	var from_time = new Date();from_time = from_time.getTime()
	//window.status+=xmlResponse.substring(2,7)+" "+(from_time - to_time) /1000
		//window.status += xmlResponse
	//alert(xmlResponse)
	return xmlResponse
}

function toDom(input) {
  var xml;

	if (window.ActiveXObject) {
    xml = new ActiveXObject("Microsoft.XMLDOM"); //IE
  }
	else {
		if (document.implementation && document.implementation.createDocument) {
      xml = document.implementation.createDocument("","doc",null);
    }
  }

	xml.async = false;

	if (!isMSIE()) {
		Document.prototype.loadXML = function (s) {
			var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
			while (this.hasChildNodes()) {
        this.removeChild(this.lastChild);
      }
			for (var i = 0; i < doc2.childNodes.length; i++) {
				this.appendChild(this.importNode(doc2.childNodes[i], true));
			}
		};
	}
	xml.loadXML(input);
	rqnode=xml.childNodes[0];

	return rqnode;
}

function getDocElement(request) {
	var xmlResponse = makeRequest(request,1);
	return toDom(xmlResponse);
}

function updatecity(f) {
	var request="<CityRQ lang='"+lang+"'><CountryName>"+f.pickUpCountry.value+"</CountryName></CityRQ>"
	eval( makeRequest(request, 0))
	emptyOptions(f.pickUpCity,1)
	opts.sort();
	for(i=0;i<opts.length;i++){
		if (opts[i] != undefined) {
			f.pickUpCity.options[i+1] = new Option(unescape(opts[i]), opts[i])
		}
	}
	emptyOptions(f.pickUpLocationId,1)
	emptyOptions(f.dropOffCountryId,1)
	emptyOptions(f.dropOffCityId,1)
	emptyOptions(f.dropOffLocationId,1)
}

function updateloc(f) {
	var request="<LocRQ lang='"+lang+"'><CountryName>"+f.pickUpCountry.value+"</CountryName><CityName>"+f.pickUpCity.value+"</CityName></LocRQ>";
	eval( makeRequest(request, 0))
	var i=1;
	emptyOptions(f.pickUpLocationId,1)
	for(key in opts){
		if(opts[key].replace) {
			opts[key] = opts[key].replace( "&#39;", "'");
		} else {
			continue;
		}
		f.pickUpLocationId.options[i++] = new Option(unescape(opts[key]), key)
	}
	emptyOptions(f.dropOffCountryId,1)
	emptyOptions(f.dropOffCityId,1)
	emptyOptions(f.dropOffLocationId,1)
}

function updateDropCountry(f) {
	_GET = new Array();
	_GET['lang']=33

	var request="<DropCountryRQ lang='"+lang+"'><LocID>"+f.pickUpLocId.value+"</LocID><City>"+f.pickUpCity.value+"</City><Country>"+f.pickUpCountry.value+"</Country></DropCountryRQ>";
	request+="<DropCityRQ lang='"+lang+"'><LocID>"+f.pickUpLocId.value+"</LocID><Country>"+f.pickUpCountry.value+"</Country><City>"+f.pickUpCity.value+"</City><DropCountry>"+f.pickUpCountry.value+"</DropCountry></DropCityRQ>"
	request+="<DropLocRQ lang='"+lang+"'><LocID>"+f.pickUpLocId.value+"</LocID><Country>"+f.pickUpCountry.value+"</Country><City>"+f.pickUpCity.value+"</City><DropCountry>"+f.pickUpCountry.value+"</DropCountry><DropCity>"+f.pickUpCity.value+"</DropCity></DropLocRQ>"

	var resp = getDocElements(request);
	for(i=0;i<resp.length;i++){
		if(resp[i].tagName=='DropCountryRS')
			doCountryNode=resp[i]
		if(resp[i].tagName=='DropCityRS')
			doCityNode=resp[i]
		if(resp[i].tagName=='DropLocRS')
			doLocNode=resp[i]
	}
	setPointer();
	fillDropCountryOptions(f, doCountryNode);
	f.dropOffCountry.value = f.pickUpCountry.value;
	fillDropCityOptions(f, doCityNode);
	f.dropOffCity.value=f.pickUpCity.value;
	fillDropLocOptions(f, doLocNode);
	selectValue(f.dropOffLocationId,f.pickUpLocationId.options[f.pickUpLocationId.selectedIndex].text);
	updateOpenTimes(f);
	updateDropTimes(f);
	resetPointer();
}

function updateDropCity(f) {
	var request="<DropCityRQ lang='"+lang+"'><LocID>"+f.pickUpLocId.value+"</LocID><Country>"+f.pickUpCountry.value+"</Country><City>"+f.pickUpCity.value+"</City><DropCountry>"+f.dropOffCountry.value+"</DropCountry></DropCityRQ>";
	eval( makeRequest(request, 0))

	emptyOptions(f.dropOffCity,1)
	var i=1;
	for(key in opts){
		f.dropOffCity.options[i++] = new Option(unescape(opts[key]),opts[key])
	}
	emptyOptions(f.dropOffLocationId,1)
}

function updateDropLoc(f){
	try{
		var request="<DropLocRQ lang='"+lang+"'><LocID>"+f.pickUpLocId.value+"</LocID><Country>"+f.pickUpCountry.value+"</Country><City>"+f.pickUpCity.value+"</City><DropCountry>"+f.dropOffCountry.options[f.dropOffCountry.selectedIndex].value+"</DropCountry><DropCity>"+f.dropOffCity.value+"</DropCity></DropLocRQ>";

		eval( makeRequest(request, 0))
		emptyOptions(f.dropOffLocationId,1)
		var i=1;
		for(key in opts){
			opts[key] = opts[key].replace( "&#39;", "'")
			f.dropOffLocationId.options[i++] = new Option(unescape(opts[key]), key)
		}
		updateDropTimes(f);
	} catch(e) {
	}
}


function isMSIE() {
    return (navigator.userAgent).indexOf('MSIE')!=-1 && (navigator.userAgent).indexOf('Opera')==-1
}

function emptyOptions(obj,start_index){
	len=obj.length
	for(i=0;i<len;i++)
		obj.options[start_index]=null
}

function init(form){

	if (form.dropOffLocationId.value>0){
		form.pickUpDay.onchange();
		form.dropOffDay.onchange();
	}

}

function fillTimes(element,time){
	emptyOptions(element,0)
	var index=0;
	for(i=0;i<time.length;i++){
		j= (i<10)?"0"+i:i
		if (time.charAt(i)=='1')
			element.options[index++]=new Option(j,i)
	}
	if (element.options[0]==null)
		element.options[0]=new Option('Closed','Closed')

	selectValue(element, "12");
}

function fillDropCountryOptions(f, rootNode){
	emptyOptions(f.dropOffCountry,1)
	for(i=0;i<rootNode.childNodes.length;i++){
		x = rootNode.childNodes.item(i).childNodes.item(0).nodeValue
		f.dropOffCountry.options[i+1]=new Option(x, x)
	}
}

function fillDropCityOptions(f, rootNode){
	emptyOptions(f.dropOffCity,1)
	for(i=0;i<rootNode.childNodes.length;i++){
		x=rootNode.childNodes.item(i).childNodes.item(0).nodeValue
		f.dropOffCity.options[i+1]=new Option(x,x)
	}
}

function fillDropLocOptions(f, rootNode){
	emptyOptions(f.dropOffLocationId,1)
	for(i=0;i<rootNode.childNodes.length;i++)
		f.dropOffLocationId.options[i+1]=new Option(rootNode.childNodes.item(i).childNodes.item(0).nodeValue,rootNode.childNodes.item(i).attributes.getNamedItem('id').nodeValue)
	selectValue(f.dropOffLocationId,f.pickUpLocationId.options[f.pickUpLocationId.selectedIndex].text)
}

function getDocElements(request){
	var xmlResponse = makeRequest(request,1)
	xmlResponse = xmlResponse.replace(/&lt;/g, "<")
	xmlResponse = xmlResponse.replace(/&gt;/g, ">")
	xmlResponse = xmlResponse.replace(/&#39;/g, "'")
	if (window.ActiveXObject) {
		var xml = new ActiveXObject("Microsoft.XMLDOM")//IE
	} else {
		if (document.implementation && document.implementation.createDocument) { //MOZILLA
			var xml= document.implementation.createDocument("","doc",null)
			//var xml = Sarissa.getDomDocument("", "doc");
		}
	}
	xml.async = false
	if (!isMSIE()){
		if (typeof DOMParser == "undefined") {
   			DOMParser = function() {}
   			DOMParser.prototype.parseFromString = function (str, contentType) {
      			if (typeof ActiveXObject != "undefined") {
         			var d = new ActiveXObject("MSXML.DomDocument");
         			d.loadXML(str);
         			return d;
      			} else if (typeof XMLHttpRequest != "undefined") {
         			var req = new XMLHttpRequest;
         			req.open("GET", "data:" + (contentType || "application/xml") +
                         ";charset=utf-8," + encodeURIComponent(str), false);
         			if (req.overrideMimeType) {
            			req.overrideMimeType(contentType);
         			}
         			req.send(null);
         			return req.responseXML;
      			}
  	 		}
		}
		if (typeof Document == 'undefined') {
			Document = function() {}
		}
		Document.prototype.loadXML = function(s) {
			var doc2 = (new DOMParser()).parseFromString(s, "text/xml")// parse the string to a new doc
			while (this.hasChildNodes()) { //remove all initial children
				this.removeChild(this.lastChild)
			}
			for (var i = 0; i < doc2.childNodes.length; i++){ // nsert and import nodes
				this.appendChild(this.importNode(doc2.childNodes[i], true))
			}
		}
	}
	if ((navigator.userAgent).indexOf('Safari') == -1) {
		xml.loadXML(xmlResponse)
	} else {
		var doc2 = (new DOMParser()).parseFromString(xmlResponse, "text/xml")// parse the string to a new doc
		while (xml.hasChildNodes()) {//remove all initial children
			xml.removeChild(xml.lastChild)
		}
		for (var i = 0; i < doc2.childNodes.length; i++){ // insert and import nodes
			xml.appendChild(xml.importNode(doc2.childNodes[i], true))
		}
	}
	if (xml.childNodes[0].tagName == 'RS') {
		return xml.childNodes[0].childNodes
	} else if (xml.childNodes[1].tagName == 'RS') {
		return xml.childNodes[1].childNodes
	}else {
		return xml.childNodes
	}
}

function updateOpenTimes(f){
	var request="<OpenTimeRQ lang='"+lang+"'><Country>"+f.pickUpCountry.value+"</Country><City>"+f.pickUpCity.value+"</City><LocID>"+f.pickUpLocId.options[f.pickUpLocId.selectedIndex].value+"</LocID><Date>"+f.pickUpYear.value+"-"+f.pickUpMon.value+"-"+f.pickUpDay.value+"</Date></OpenTimeRQ>";
	eval( makeRequest(request, 0))
	fillTimes(f.pickUpHour,opts[1])
}

function setPointer() {
	if (document.all) {
		for (var i=0;i < document.all.length; i++) {
			document.all(i).style.cursor = 'wait';
			if (i == 3) {
				break;
			}
		}
	}
}

function resetPointer() {
	if (document.all) {
		for (var i=0;i < document.all.length; i++) {
			document.all(i).style.cursor = 'default';
		}
	}
}

function selectValue(element,loc){
	for (i=0;i<element.options.length;i++ )
		if (element.options[i].text==loc){
			element.options[i].selected=true
			return true
		}
	return false
}

function updateDropTimes(f){
	var request="<DropTimeRQ lang='"+lang+"'><Country>"+f.pickUpCountry.value+"</Country><City>"+f.pickUpCity.value+"</City><LocID>"+f.dropOffLocId.options[f.dropOffLocId.selectedIndex].value+"</LocID><Date>"+f.dropOffYear.value+"-"+f.dropOffMon.value+"-"+f.dropOffDay.value+"</Date></DropTimeRQ>";
	eval( makeRequest(request, 0))
	fillTimes(f.dropOffHour,opts[1])
}

function getAddDrv(loc){
	try{
		if (typeof loc=='undefined')
			return
		var request = "<AddDrvRQ locId='"+loc+"' /> "
		var xml = makeRequest(request,1)
//		var adddrv = transformXslStr(xml,adddrvxsl)
//		document.getElementById("adddrv").innerHTML = adddrv
	}
	catch(e){}
}

function getAddDrv(loc){
	try{
		var request = "<AddDrvRQ locId='"+loc+"' /> "
		eval( makeRequest(request,0))

		if (opts[1]!='Y') document.getElementById("addDrvDiv").style.display='none';
	}
	catch(e){}
}

function initForm(){
	f = document.bookingBean.pickUpLocId;
	for (i=0;i<f.options.length ;i++ ){
		if (f.options[i].text=="<bean:write name='bookingBean' property='pickUpLocName'/>"){
			f.options[i].selected=true
		}
	}
	f = document.bookingBean.dropOffLocationId;
	for (i=0;i<f.options.length ;i++ ){
		if (f.options[i].text=="<bean:write name='bookingBean' property='dropOffLocName'/>"){
			f.options[i].selected=true
		}
	}
}

/**
 * Returns XMLHttpRequest object in case of Firefox, Opera, Safari and ActiveXObject in case of IE, object
 * is needed to perform ajax-requests.
 *
 * @author Viktor
 */
function getXMLHttpRequest() {
	try {
    	// Firefox, Opera 8.0+, Safari
    	return new XMLHttpRequest();
    } catch (e) {
    	// Internet Explorer
    	try {
      		return new ActiveXObject("Msxml2.XMLHTTP");
      	} catch (e) {
      		try {
        		return new ActiveXObject("Microsoft.XMLHTTP");
        	} catch (e) {
        		alert("Your browser does not support AJAX!");
        		return false;
        	}
      	}
    }
}

/**
 * Sends ajax-request to finish car-searching proccess.
 *
 * @author Viktor
 */
function finishSearching() {
	var xmlHttp = getXMLHttpRequest();
	type = typeof(xmlHttp)
	if (type == 'object') {
		var sURL = projectPath+"/finishSearching.do"
		xmlHttp.open("POST", sURL, true)
		xmlHttp.send(null) // Execute the request

		xmlHttp.onreadystatechange=function() {
  			if(xmlHttp.readyState==4) {
  				elem = document.getElementById('searching')
				vehs = 'vehicle'
				if (count > 1)
					vehs += 's'
				elem.innerHTML = '<div><b>Found ' + count + ' ' + vehs + '</b></div>'
				currentGroup = 0

				if ((navigator.userAgent).indexOf("Firefox") > -1)
						window.setTimeout("window.stop()", 1500)
  			}
  		}
	}
}

/**
 * Sends ajax-request to retrieve vehicles list.
 *
 * Method principle: all vehicles have hierarhy by their subgroups values, accroding to ACRISS it can
 * be 7 subgroups, method is retrieving vehicles grouped by their subgroup step by step begining
 * from first subgroup ending with last. When last subgroup is reached finishSearching()
 * method is executed. Also method can accept limited number of subgroups, this functionality
 * is called 'filtering',  'any' - parameter is responsible for this.
 *
 * @param group -
 *				actualy spesified vehicle subgroup.
 * @param any -
 *				boolean parameter that specify filtering.
 *
 * @author Viktor
 */
function getVehicles(subgroup, any) {
	var xmlHttp = getXMLHttpRequest();
	type = typeof(xmlHttp)
	if (type == 'object') {
    	var sURL = projectPath+"/vehiclesList.do?subgroup="+subgroup
		xmlHttp.open("POST", sURL, true)
		xmlHttp.send(null) // Execute the request

		xmlHttp.onreadystatechange=function() {
  			if(xmlHttp.readyState==4) {
    			var xmlResponse=xmlHttp.responseText
    			executeScripts(xmlResponse)
    			if (currentCount > 0) {
    				var resp = ''
    				var init = '<?xml version="1.0" encoding="UTF-8"?>'
    				if (xmlResponse.indexOf(init) > -1) {
    					resp += xmlResponse.substring(0, xmlResponse.indexOf(init))
    					resp += xmlResponse.substring(xmlResponse.indexOf(init) + init.length, xmlResponse.length)
    					var xxx = xmlResponse.substring(xmlResponse.indexOf(init) + init.length, xmlResponse.length)
    				}
    				searchElem = document.getElementById('results')
    				searchElem.innerHTML += resp
    			}

    			if (any == 'true' && currentGroup < groups.length) {
    				nextGroup()
    				window.setTimeout("getVehicles('"+groups[currentGroup]+"', 'true')", 500)
    			} else {
    				window.setTimeout("finishSearching()", 500)
    			}
    		}
  		}
  	}
}

/**
 * Switch 'currentGroup' iterator to next subgroup index.
 *
 * @author Viktor
 */
function nextGroup() {
	currentGroup += 1
	if (groups[currentGroup] == '')
		nextGroup()
}

/**
 * Executes scripts comming in html with ajax-requests.
 *
 * NB! Method has big discourage: it accepts scripts parts defined within simple <script></script> tags.
 * Non <script type="text/javascript"> or <script language="javascript"> are proccessed. Keeping this in
 * mind all ajax-comming jsp pages are made to use javascripts within <script></script> tags.
 *
 * @param response -
 *					ajax response content.
 *
 * @author Viktor
 */
function executeScripts(response) {
	if (response.indexOf('<script>') == -1) {
		return;
	} else {
		var script = response.substring(response.indexOf('<script>')+8, response.indexOf('</script>'))
		try {
			eval(script)
			response = response.substring(response.indexOf('</script>') + 9)
			executeScripts(response)
		} catch (e) {
		}
	}
}

/**
 * Opens window for printing 'Terms & conditions'.
 *
 * @author Viktor
 */
function printTerms(carSupplierId, priceListId) {
	window.open(projectPath+"/terms.do?carSupplierId="+carSupplierId+"&priceListId="+priceListId+"&print=true")
}

/**
 * Sends ajax-request to e-mail 'terms & conditions'.
 *
 * @param carSupplierId -
 *							car supplier location id.
 * @param email -
 *				email addres the 'terms & conditions' will be send to.
 *
 * @author Viktor
 */
function mailTerms(carSupplierId, email) {
	var sURL = projectPath+"/sendEmail.do?carSupplierId="+carSupplierId+"&email="+email
	sendEmail(sURL);
}

function mailTerms2(carSupplierId, email) {
	var sURL = projectPath+"/sendEmail.do?carSupplierId="+carSupplierId+"&email="+email
	sendEmail2(sURL);
}

function mailTerms3(carSupplierId, priceListId, email) {
	var sURL = projectPath+"/sendHtmlTerms.do?carSupplierId="+carSupplierId+"&priceListId="+priceListId+"&email="+email
	sendEmail2(sURL);
}

/**
 * Sends ajax-request to e-mail booking/amend form.
 *
 * @param resNum -
 *					booking (reservation) number.
 * @param email -
 *				email addres the form will be send to.
 * @act -
 *		specifies which form will be sent booking or amend.
 *
 * @author Viktor
 */
function mailVoucher(resNum, email, act) {
	var sURL = projectPath+"/sendEmail.do?email="+email+"&resNum="+resNum+"&act="+act
	sendEmail(sURL);
}

function mailVoucher2(resNum, email, act)
{
	var sURL = projectPath+"/sendHtmlVoucher.do?email="+email+"&resNum="+resNum+"&act="+act
	sendEmail2(sURL);
}

/**
 * Asynchronously email sending.
 */
function sendEmail(sURL) {
	var xmlHttp = getXMLHttpRequest();
	type = typeof(xmlHttp)
	if (type == 'object') {
		xmlHttp.open("POST", sURL, true)
		xmlHttp.send(null) // Execute the request

		xmlHttp.onreadystatechange=function() {
  			if(xmlHttp.readyState==4) {
    			var xmlResponse=xmlHttp.responseText
				if (xmlResponse.indexOf('Email is invalid') == -1) {
					document.getElementById('mailedTo').style.display = 'none';
					document.getElementById('emailInvalid').style.display = 'none';
					document.getElementById('mailResult').innerHTML = xmlResponse;
					document.getElementById('mailResult').style.display = 'block';
					show_popup('insert_mail')
					setTimeout("hide_popup('insert_mail')", 3000)
					setTimeout("setEmailInitialFields()", 3100)
				} else {
					document.getElementById('emailInvalid').style.display = 'block';
				}
    		}
  		}
  	}
}

function sendEmail2(sURL)
{
  var xmlHttp = getXMLHttpRequest();
	type = typeof(xmlHttp)

	xmlHttp.onreadystatechange=function()
	{
 			if(xmlHttp.readyState==4)
 			{
   			var xmlResponse=xmlHttp.responseText
   			elem = document.getElementById('mailResult')
   			elem.innerHTML = xmlResponse;
   		}
 	}

	if (type == 'object')
	{
		xmlHttp.open("POST", sURL, false)
		xmlHttp.send(null) // Execute the request
  	}
}

/**
 * Sends ajax-request to retrive 'terms & conditions'.
 *
 * @param carSupplierId -
 *					car supplier location id.
 *
 * @author Viktor
 */
function getTerms(carSupplierId) {
	var xmlHttp = getXMLHttpRequest();
	type = typeof(xmlHttp)
	if (type == 'object') {
    	var sURL = projectPath+"/terms.do?carSupplierId="+carSupplierId
		xmlHttp.open("POST", sURL, true)
		xmlHttp.send(null) // Execute the request

		xmlHttp.onreadystatechange=function() {
  			if(xmlHttp.readyState==4) {
    			var xmlResponse=xmlHttp.responseText
    			elem = document.getElementById('terms_n_conditions')
    			elem.innerHTML = xmlResponse
    		}
  		}
  	}
}

function getVoucher(resNum, email)
{
	var xmlHttp = getXMLHttpRequest();
	type = typeof(xmlHttp)

	xmlHttp.onreadystatechange=function()
	{
 			if(xmlHttp.readyState==4)
 			{
   			var xmlResponse=xmlHttp.responseText;
   			elem = document.getElementById('voucher');
   			elem.innerHTML = xmlResponse;
   		}
 	}

	if (type == 'object') {
    var sURL = projectPath+"/voucher.do?email="+email+"&resnum="+resNum;
		xmlHttp.open("POST", sURL, false);
		xmlHttp.send(null); // Execute the request
  }
}

/**
 * Opens new window with voucher printing task.
 */
function printPage(resNum, email) {
	window.open("displayBookingForm.do?resNum="+resNum+"&email="+email)
}

/**
 * Opens new window with amend form printing task.
 */
function printVoucher(resNum, email) {
	window.open("voucher.do?resnum="+resNum+"&email="+email + "&print=true")
}

